pymgrid.Microgrid#

class pymgrid.Microgrid(modules, add_unbalanced_module=True, loss_load_cost=10.0, overgeneration_cost=2.0, reward_shaping_func=None, trajectory_func=None)[source]#

Microgrid class, used to define and simulate an environment with a variety of modules.

Parameters#

modulesList[Union[Tuple[str, BaseMicrogridModule], BaseMicrogridModule]]

List of modules that define the microgrid. The list can contain either/both microgrid modules – subclasses of BaseMicrogridModule – and tuples of length two, which must contain a string defining the name of the module followed by the module.

Microgrid groups modules into lists based on their names. If no name is given (e.g. an element in modules is a subclass of BaseMicrogridModule and not a tuple, then the name is defined to be module.__class__.name[0]. Modules are then exposed (within lists) by name as attributes to the microgrid. See below for an example.

The constructor copies modules passed to it.

add_unbalanced_modulebool, default True.

Whether to add an unbalanced energy module to your microgrid. Such a module computes and attributes costs to any excess supply or demand. Set to True unless modules contains an UnbalancedEnergyModule.

loss_load_costfloat, default 10.0

Cost per unit of unmet demand. Ignored if add_unbalanced_module=False.

overgeneration_costfloat, default 2.0

Cost per unit of excess generation. Ignored if add_unbalanced_module=False.

reward_shaping_funccallable or None, default None

Function that allows for custom definition of the microgrid’s reward/cost. If None, the cost of each step is simply the total cost of all modules. For example, you may define a function that defines the cost as only being the loss load, or only the pv curtailment.

trajectory_funccallable or None, default None

Callable that sets an initial and final step for an episode. trajectory_func must take two inputs: initial_step and final_step, and return two integers: the initial and final step for that particular episode, respectively. This function will be called every time reset() is called.

If None, initial_step and final_step are used to define every episode.

Examples#

>>> from pymgrid import Microgrid
>>> from pymgrid.modules import LoadModule, RenewableModule, GridModule, BatteryModule
>>> timesteps = 10
>>> load = LoadModule(10*np.random.rand(timesteps), loss_load_cost=10.)
>>> pv = RenewableModule(10*np.random.rand(timesteps))
>>> grid = GridModule(max_import=100, max_export=10, time_series=np.random.rand(timesteps, 3))
>>> battery_0 = BatteryModule(min_capacity=0,                                   max_capacity=100,                                   max_charge=1,                                  max_discharge=10,                                   efficiency=0.9,                                   init_soc=0.5)
>>> battery_1 = BatteryModule(min_capacity=1,                                   max_capacity=20,                                   max_charge=5,                                   max_discharge=10,                                   efficiency=0.9,                                   init_soc=0.5)
>>> microgrid = Microgrid(modules=[load, ('pv', pv), grid, battery_0, battery_1])
>>> # The modules are now available as attributes. The exception to this is `load`, which is an exposed method.
>>> print(microgrid.pv)
[RenewableModule(time_series=<class 'numpy.ndarray'>, raise_errors=False, forecaster=NoForecaster, forecast_horizon=0, forecaster_increase_uncertainty=False, provided_energy_name=renewable_used)]
>>> print(microgrid.grid)
[GridModule(max_import=100, max_export=10)]
>>> print(microgrid.grid.item()) # Return the module instead of a list containing the module, if list has one item.
GridModule(max_import=100, max_export=10)
>>> for j, battery in enumerate(microgrid.battery):
>>>     print(f"Battery {j}: {battery}")
Battery 0: BatteryModule(min_capacity=0, max_capacity=100, max_charge=1, max_discharge=10, efficiency=0.9, battery_cost_cycle=0.0, battery_transition_model=None, init_charge=None, init_soc=0.5, raise_errors=False)
Battery 1: BatteryModule(min_capacity=1, max_capacity=20, max_charge=5, max_discharge=10, efficiency=0.9, battery_cost_cycle=0.0, battery_transition_model=None, init_charge=None, init_soc=0.5, raise_errors=False)

Methods

compute_net_load([normalized])

Compute the net load at the current step.

deserialize(mapping)

dump([stream])

Save a microgrid to a YAML buffer.

from_nonmodular(nonmodular)

Convert to Microgrid from old-style NonModularMicrogrid.

from_normalized(data_dict[, act, obs])

De-normalize an action or observation.

from_scenario([microgrid_number])

Load one of the pymgrid25 benchmark microgrids.

get_cost_info()

get_empty_action([sample_flex_modules])

Get an action for the microgrid with no values set.

get_forecast_horizon()

Get the forecast horizon of timeseries modules contained in the microgrid.

get_log([as_frame, drop_singleton_key, ...])

Collect a log of controls and responses of the microgrid.

load(stream)

Load a microgrid from a yaml buffer.

reset()

Reset the microgrid and flush the log.

run(control[, normalized])

sample_action([strict_bound, ...])

Get a random action within the microgrid's action space.

set_forecaster(forecaster[, ...])

Set the forecaster for timeseries modules in the microgrid.

set_module_attrs([attr_dict])

Set the value of an attribute in all modules containing that attribute.

state_dict([normalized, as_run_output, _initial])

State of the microgrid as a dict.

state_series([normalized])

State of the microgrid as a pandas Series.

step(control[, normalized])

Run the microgrid for a single step.

to_nonmodular()

Convert Microgrid to old-style NonModularMicrogrid.

to_normalized(data_dict[, act, obs])

Normalize an action or observation.

verbose_eq(other[, indent])

Attributes

controllable

Container of all controllable modules in the microgrid.

current_step

Current step of underlying modules.

final_step

Final step of underlying timeseries data.

fixed

Container of all fixed modules in the microgrid.

flex

Container of all flex modules in the microgrid.

initial_step

Initial step at which to start underlying timeseries data.

log

Microgrid's log as a DataFrame.

module_list

List of all modules in the microgrid.

modules

View of the module container.

n_modules

Number of modules in the microgrid.

yaml_tag

Tag used for yaml serialization.