Metadata-Version: 2.4
Name: midas-powergrid
Version: 2.1.6
Summary: A simulator for pandapower grids.
Author-email: Stephan Balduin <stephan.balduin@offis.de>, Eric MSP Veith <eric.veith@offis.de>
License-Expression: LGPL-3.0-only
Project-URL: Documentation, https://midas-mosaik.gitlab.io/midas
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: midas-mosaik>=2.1.0
Requires-Dist: mosaik_api
Requires-Dist: numpy
Requires-Dist: matplotlib
Requires-Dist: pandapower
Requires-Dist: lightsim2grid
Requires-Dist: numba
Requires-Dist: simbench
Requires-Dist: natsort
Requires-Dist: joblib
Requires-Dist: opentelemetry-api
Dynamic: license-file

# Midas Powergrid Simulator

This package contains a Midas module providing a pandapower simulator and a number of custom powergrids.

Although this package is intended to be used with midas, but you can use in any mosaik simulation scenario.

Version: 2.1

## Installation

This package will usually installed automatically together with `midas-mosaik` if you opt-in any of the extras, e.g., `base` or `bh`. 
It is available on pypi, so you can install it manually with

```bash
pip install midas-powergrid
```

## Usage

The complete documentation is available at https://midas-mosaik.gitlab.io/midas.

### Inside of midas

To use the powergrid inside of midas, just add `powergrid` to your modules

```yaml
my_scenario:
  modules:
    - powergrid
    - ...
```

and configure it with (`gridfile` is required, everything else is optional and can be left out if the default values, shown below, are used):


```yaml
  powergrid_params:
    write_csv: false
    csv_dir: _outputs/pandapower_inputs
    my_grid_scope:
      gridfile: midasmv
      grid_params: {}
      step_size: 900
      plotting: False
      plot_path: _plots # Output path defined in runtime config
      save_grid_json: False
      # Set write_csv: true here to enable logging for this scope.
```

CSV input logging is disabled by default. Set `write_csv: true` under
`powergrid_params` to enable it globally, or inside an individual scope.
Both `write_csv` and `csv_dir` support per-scope overrides.
`write_csv` defaults to `False`; `csv_dir` defaults to
`_outputs/pandapower_inputs`. Relative paths are resolved from the process
working directory. When enabled, each grid writes a separate UUID-named CSV
file with normalized input values. Standalone mosaik users pass both options
to `world.start`, e.g. `world.start("Powergrid", step_size=900,
write_csv=True, csv_dir="_outputs/pandapower_inputs")`; these `init` options
apply to grids subsequently created by that simulator.

At each nonnegative power-flow timestep, the CSV includes current `p_mw`,
`q_mvar`, `scaling`, and `in_service` values for load and sgen elements, in
addition to dynamically supplied input rows. A dynamically logged
element/parameter is not repeated by completion for that timestep; unchanged
values appear at later timestamps, including timesteps with no incoming inputs.
This is a timestep snapshot of these input fields, not a complete replay log of
network state or constraint changes.

For per-target accounting, the simulator exposes `p_mw_input` and
`q_mvar_input` (the raw table snapshots after external updates and before
constraints/power flow), `p_mw_fallback` and `q_mvar_fallback`, matching
`*_input_applied` flags, and `input_time`. The fallback is zero when an input
was accepted; otherwise it is the held table value. Use each target's source
columns and sum only those matching targets. For each field, select that
per-target source sum when its `*_input_applied` flag is true; otherwise select
the corresponding `*_fallback`. Do not calculate `0 * NaN`, infer missing
source values from a residual, or sum whole-store data/grid totals to reconcile
target inputs. Raw `p_mw_input`
and `q_mvar_input` are unscaled table values; Pandapower applies element
`scaling` separately. Previously, `constant_*` load/sgen/storage values
contributed to grid totals but were not separately exposed as target input
accounting.
These channels are diagnostics, not RL sensors.

Enable the MIDAS store (`store` in `modules`, with `no_db: false`) to persist
these diagnostics; the powergrid module wires them to the store automatically.
For example, nested in the scenario configuration:

```yaml
my_scenario:
  modules:
    - powergrid
    - store
  no_db: false
  store_params:
    filename: input-accounting.csv
```

This uses the existing MidasCSVStore CSV output; it does not convert existing
HDF5 exports to CSV. Separately, the simulator's direct `write_csv` option can
write its input log without enabling the store. Source rows in asynchronous or
sparse simulations may retain prior values and do not universally identify the
sources accepted in a particular timestep. The diagnostic channels expose the
simulator's accepted-input flags and fallback; they do not filter controllers
or provide exact replay of constraint iterations.

All simulators that want to connect to this grid, will have to use `my_grid_scope` as their `grid_name` value. 
Activating the plotting will results in a considerably longer execution time. 
Activate it only if you really need this feature and it does not work for all of the grids.

The gridfile can be either a path to a .json or .xlsx file, a simbench grid code, one of `cigre_hv`, `cigre_mv`, `cigre_lv`, `midasmv`, `midaslv`, or `bhv`, or an import path to a function or class that either returns a valid pandapower grid or is a pandapower grid itself. 
The `grid_params` can be used to pass keywork arguments to custom grids.

### Any mosaik scenario

If you don't use midas, you can add the `powergrid` manually to your mosaik scenario file. 
First, the entry in the `sim_config`:

```python
sim_config = {
    "Powergrid": {"python": "midas_powergrid.simulator:PandapowerSimulator"}
    # ...
}
```

Next, you need to start the simulator (assuming a `step_size` of 900):

```python
powergrid_sim = world.start("Powergrid", step_size=900)
```

Finally, the model needs to be started:

```python
powergrid = powergrid_sim.Grid(gridfile="midasmv", grid_params={})
```

To connect the output of the grids' buses to another model, you have to get the list of bus models from the powergrids' children like

```python
bus_models = [e for e in powergrid.children if "bus" in e.eid]
```

and then connect those models either individually or in a loop, e.g.,

```python
for bus in bus_models:
    world.connect(bus, other_entity, "vm_pu", "va_degree", "p_mw", "q_mvar")
```

The inputs are generally handled in the same way. 
Have a look at `powergrid.children` to get the required entity eids.

## Runtime power-flow failure

A runtime `LoadflowNotConverged` is an absorbing simulator failure. Both
output-cache layers are invalidated and subsequent inputs cannot resume
physical stepping. Exported result fields use finite zero-valued terminal
sentinels rather than last-good voltages. These are failure sentinels, not a
solved physical blackout.

Each `Grid` exposes `powerflow_failed` and `powerflow_failure_time` (simulation
ticks; `-1` before failure), alongside `health`. Any failed grid stops physical
stepping for all grids in the same simulator. The next-time return remains
valid because mosaik requires it for time-based simulators; the scenario or
ARL bridge must consume the explicit failure signal and stop the world.
Do not infer convergence or termination from `health` alone.

The companion `palaestrai-mosaik` bridge automatically monitors these channels
and ends the episode with `done=True`, `terminated=True`, `truncated=False`.
Constructor/setup errors and unrelated exceptions still propagate as errors.

## License
This software is released under the GNU Lesser General Public License (LGPL). See the license file for more information about the details.
