Metadata-Version: 2.4
Name: distgridforge
Version: 0.4.0
Summary: A package for analyzing constraints in power grids
Author-email: Yassine Abdelouadoud <yassine.abdelouadoud@minesparis.psl.eu>, Yoann Chiche <yoann.chiche@minesparis.psl.eu>
License: MIT
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENCE.txt
Requires-Dist: pandas<3,>=2.2
Requires-Dist: numpy>=1.26
Requires-Dist: scipy>=1.13
Requires-Dist: matplotlib>=3.8
Requires-Dist: networkx>=3.2
Requires-Dist: pandapower<3.3,>=3.1.2
Requires-Dist: numba>=0.60
Requires-Dist: pyyaml>=6.0
Requires-Dist: folium>=0.16
Requires-Dist: shapely>=2.0
Provides-Extra: roseau
Requires-Dist: roseau-load-flow>=0.12; extra == "roseau"
Provides-Extra: opendss
Requires-Dist: opendssdirect.py>=0.9; extra == "opendss"
Dynamic: license-file

# GridForge

![Python Version](https://img.shields.io/badge/python-3.12+-blue.svg)
![License](https://img.shields.io/badge/license-MIT-green.svg)

## Description

GridForge is a Python library that finds how to resolve the constraint violations of a
distribution network (over- and under-voltages, overloaded lines and transformers) at the
lowest cost. A greedy algorithm applies operational and planning strategies, from tap
changes to equipment upgrades, checks their effect with a power flow, and reports what it
did, why, and at what cost.

## Features

- **Power flow and constraint checks** with [pandapower](https://www.pandapower.org/):
  voltage limits, line and transformer loading.
- **Grid enhancement algorithm**: a greedy loop over the violation types, which chooses,
  for each type, the strategies that lead to the cheapest end of the run, and keeps the
  best partial solution when it cannot resolve everything.
- **Strategies**: transformer tap changes, flexibility (load shedding and generation
  curtailment, guided by power flow sensitivities), line upgrades along conductor ladders
  (including a path-to-source variant), and transformer upgrades or parallel units.
- **Cost model**: prices of every action, checked before a run so that none is assumed.
- **Explainability**: each action is logged with the grid state, the target violation and
  its quantitative justification.
- **Visualisation**: network plots of the violations, and an interactive HTML page of the
  steps of a run.

pandapower is the only working engine. The Roseau, OpenDSS and GridLAB-D adapters in
`gridforge/engines` are incomplete and cannot run the algorithm yet; their future is
discussed in issue #7.

## Installation

GridForge is managed with [uv](https://docs.astral.sh/uv/) and installed from source:

```bash
git clone https://git.persee.minesparis.psl.eu/energy-alternatives/gridforge.git
cd gridforge
uv sync
```

`uv sync` creates `.venv` from `uv.lock`, including the development tools. Run commands
through it with `uv run`:

```bash
uv run pytest gridforge/tests
uv run pre-commit install
```

Optional dependencies are installed on request:

```bash
uv sync --extra roseau --extra opendss  # Roseau and OpenDSS libraries
uv sync --group docs                    # Sphinx documentation
uv sync --group notebooks               # Jupyter, for the case-study notebooks
```

The MV/LV case study needs feeder data that is fetched separately: see [Data](#data).

The PyPI distribution is `distgridforge`, and its import name is `gridforge`:

```bash
pip install distgridforge
```

Do not run `pip install gridforge`: the PyPI project named `gridforge` is an unrelated
table-formatting library that provides the same import name, so the two cannot be installed
in one environment, and that command installs the wrong package.

## Quick Start

The example below builds a small LV feeder with an overloaded cable and an under-voltage,
and lets GridForge resolve them. It is `gridforge/examples/quick_start.py`, which the
tests run, so you can also run it with `uv run python -m gridforge.examples.quick_start`.

```python
import pandapower as pp

from gridforge import CostModel, PandaPowerEngine
from gridforge.core.grid_enhancement import (
    EnhancementStrategyRegistry,
    GridEnhancementAlgorithm,
)
from gridforge.strategies.line_upgrade import LineUpgradeStrategy
from gridforge.strategies.tap_change import TapChangeStrategy
from gridforge.strategies.transformer_upgrade import TransformerUpgradeStrategy

# A small LV feeder: a 250 kVA substation and a 250 m cable feeding 120 kW
net = pp.create_empty_network()
mv_bus = pp.create_bus(net, vn_kv=20.0, name="MV bus")
lv_bus = pp.create_bus(net, vn_kv=0.4, name="LV busbar")
end_bus = pp.create_bus(net, vn_kv=0.4, name="Feeder end")
pp.create_ext_grid(net, bus=mv_bus, vm_pu=1.0, name="Grid")
pp.create_transformer(
    net, hv_bus=mv_bus, lv_bus=lv_bus, std_type="0.25 MVA 20/0.4 kV", name="Substation"
)
pp.create_line(
    net,
    from_bus=lv_bus,
    to_bus=end_bus,
    length_km=0.25,
    std_type="NAYY 4x50 SE",
    name="Cable",
)
pp.create_load(net, bus=end_bus, p_mw=0.12, q_mvar=0.04, name="Load")

engine = PandaPowerEngine()
engine.network = net

# The cable is overloaded and the feeder end is under-voltage
engine.run_power_flow()
for violation in engine.check_violations():
    print(f"Before: {violation.constraint_type.value} at {violation.element_id}")

# The strategies try the cheapest fixes first: tap changes, then line and
# transformer upgrades: a larger type, or one more conductor or unit of the type
# in place, whichever is cheaper at the prices below.
registry = EnhancementStrategyRegistry()
registry.register_strategy(TapChangeStrategy())
registry.register_strategy(
    LineUpgradeStrategy(
        line_types={
            "lv": {
                "overhead": [],
                "underground": ["NAYY 4x50 SE", "NAYY 4x120 SE", "NAYY 4x150 SE"],
            }
        }
    )
)
registry.register_strategy(
    TransformerUpgradeStrategy(["0.25 MVA 20/0.4 kV", "0.4 MVA 20/0.4 kV"])
)

# Every type of these ladders needs a price: a missing one raises
# MissingUnitCostError before the run (see "Unit Costs" in the usage docs).
cost_model = CostModel(
    {
        "line_upgrade": {  # €/km
            "NAYY 4x50 SE": 50.0e3,
            "NAYY 4x120 SE": 70.0e3,
            "NAYY 4x150 SE": 80.0e3,
        },
        "transformer_upgrade": {  # € per unit
            "0.25 MVA 20/0.4 kV": 5000.0,
            "0.4 MVA 20/0.4 kV": 8000.0,
        },
        "tap_change": 10.0,  # € per tap step
    }
)

algorithm = GridEnhancementAlgorithm(
    power_flow_engine=engine,
    strategy_registry=registry,
    cost_model=cost_model,
)
success, results = algorithm.run()

print(f"Resolved: {success}, total cost: {results['total_cost']:.0f} €")
for action in results["actions_applied"]:
    print(f"- {action['type']}")
print(f"Remaining violations: {len(results['remaining_violations'])}")
```

It prints the violations before the run, then:

```
Resolved: True, total cost: 12500 €
- line_upgrade
Remaining violations: 0
```

GridForge identifies buses, lines and transformers by their name, so each must have one
of its own, as in the example: `run_power_flow` refuses a network where one has none or
shares it. For a network that leaves elements unnamed, as several of pandapower's example
networks do, call `engine.fill_missing_names()` after assigning it; `engine.check_names()`
tells at once whether a network will be accepted.

The [usage documentation](https://pages.persee.minesparis.psl.eu/energy-alternatives/gridforge/usage.html)
describes the results, the unit costs and the visualisation.

## Data

The MV/LV case study runs on 150 MV/LV feeders that are not in the repository. Fetch them
once, from a clone:

```bash
uv run python -m gridforge.data fetch
```

or, where gridforge is installed with pip, `python -m gridforge.data fetch`. In Python,
`gridforge.data.fetch_feeders()` does the same. It downloads one archive of 10 MB (94 MB
once extracted) from the permanent link of the dataset on data.gouv.fr, checks it against
the SHA-256 pinned in gridforge, extracts only its 150 `networks/*.json` files, checks
each against the `SHA256SUMS` of the archive, and moves each into place once checked, so
that an error leaves no partial file. When the 150 files are there and unchanged, it
downloads nothing. When any is missing, it downloads the whole archive again, and writes
only the missing files; the others are left as they are. A file of version 1 of the
feeders, which gridforge 0.3.0 used, is replaced by that of version 2 as a missing file
is written, without `--replace`: a fetch upgrades a directory of version 1. A file that
differs from the published ones of both versions is an error, before any download,
unless `--replace` is given, which replaces it. A fetch that was killed can leave a
directory `.gridforge-fetch-*` in the directory of the feeders: the next fetch removes
those older than a day. Options: `--dest DIR` to write elsewhere,
`--url file:///path/to/archive.tar.xz` to install from a copy of the archive, for a
machine without access to data.gouv.fr.
`python -m gridforge.data where` prints where gridforge looks and how many of the
feeders it finds there, with the fetch command when some are missing.

gridforge looks for the feeders, and `gridforge.data_path["pandapower"]` points, to the
first of:

1. the directory named by the environment variable `GRIDFORGE_FEEDER_DIR`;
2. `gridforge/data/pandapower` of a source checkout, if it holds feeder files besides
   the two of the repository (for instance after
   `fetch --dest gridforge/data/pandapower`). The package is in a source checkout, or
   an editable install of one, when `pyproject.toml` is next to its directory; an
   installed package never is, and the files put in its `data/pandapower` for
   gridforge 0.3.0 are no longer used (`where` says so);
3. the user's data directory, `$XDG_DATA_HOME/gridforge/pandapower`, by default
   `~/.local/share/gridforge/pandapower` (`%LOCALAPPDATA%\gridforge\pandapower` on
   Windows), where `fetch` writes, whether it exists yet or not.

`data_path` is resolved once, when gridforge is imported, while
`gridforge.data.feeder_dir()` reads `GRIDFORGE_FEEDER_DIR` at each call: set the
variable before importing gridforge. A relative value is resolved against the working
directory at the time it is read. The case studies and the benchmarks that find no
feeder there say so and give the fetch command. They also check the feeders they find
against the pinned checksums (`gridforge.data.check_feeders()`): the case study loads a
file of version 1, or a changed one, with a warning, and `benchmarks/profile_study.py`
refuses it unless `--allow-other-data` is given. After upgrading from gridforge 0.3.0,
run `python -m gridforge.data fetch` to replace the files of version 1.

**Provenance and licence.** The feeders are those of the dataset
[Départs HTA représentatifs pour l'analyse des réseaux de distribution Français](https://www.data.gouv.fr/datasets/departs-hta-representatifs-pour-lanalyse-des-reseaux-de-distribution-francais),
published on data.gouv.fr by the author of gridforge under the
[Licence Ouverte / Open Licence 2.0](https://www.etalab.gouv.fr/licence-ouverte-open-licence/),
which allows their reuse and redistribution, with attribution (the source and the date
of its last update). As the dataset describes them, they were built from open data (the
network routes published by Agence ORE, local energy consumption data, and the building
footprints of the IGN BD TOPO), and chosen by clustering to be representative of the
distribution networks across France. The dataset holds them in the format of Roseau Load
Flow (`departs-hta-representatifs-roseau-v012.zip`), with a report on their selection,
and in pandapower format, in two versions: version 1, exactly as gridforge 0.3.0 uses
them (`departs-hta-representatifs-pandapower-gridforge-0.3.0.tar.xz`), and version 2
(`departs-hta-representatifs-pandapower-gridforge-v2.tar.xz`, which `fetch` downloads).
The pandapower files have the names of the Roseau ones and the same numbers of buses,
lines, transformers and loads, except `84_MVFeeder4049`, repaired to be read by
pandapower 3.2 and described with the line types of the other feeders (#45, #54), which
has 486 loads against 594. In all: 90,020 buses, 84,220 lines, 5,500 transformers of
20/0.4 kV and 147,896 loads, balanced, with loads of constant power; the case study
multiplies the loads by 2.5 as it reads them. The `LISEZMOI.md` of each archive
describes its files and lists their known limits.

**Version 2.** It is version 1 with two cells changed in each file, on the slack bus,
two redundant load columns removed from `84_MVFeeder4049`, which pandapower 3.5 refused,
and nothing else (#14), made from it, byte for byte, by `scripts/repair_feeders.py`:
the closed switch at the head of each feeder has `z_ohm = 0` instead of 0.1 Ω, so that
pandapower fuses the bus of the external grid with the first MV bus, as the ideal switch
of the Roseau source; and the slack bus has the coordinates of that first MV bus
instead of `[nan, nan]`, which pandapower 3.5 cannot read. The 1,626 loads of type
`delta` are the Roseau loads connected without neutral, and keep that label: it changes
nothing in a balanced power flow, but an engine that cannot take delta loads has to map
them itself. See "Data" in the installation documentation.

**What is in git.** `gridforge/data/` holds the code of the fetch, the pinned checksums
of the 150 files of version 2 (`pandapower-feeders.sha256`) and of version 1
(`pandapower-feeders-v1.sha256`), and two of the feeders,
`pandapower/52_MVFeeder1118.json` and `pandapower/84_MVFeeder4049.json`, identical to
those of the archive of version 2, which the tests read from the checkout (and under
the licence of the dataset, not the MIT licence of the code). The wheel holds no feeder.

## Case Studies

The scripts and notebooks of `gridforge/case_study` run the algorithm on example networks,
with the types and prices of `gridforge/case_study/config.py`:

- **MV/LV feeders** (`mv_lv_feeder.py`): the 150 fetched feeders, with loads at 2.5 times
  their value, without flexibility and with 30 % of every load flexible.
  `uv run python gridforge/case_study/mv_lv_feeder.py` runs the 300 cases, in one
  process by default, so as never to take all the cores of a shared machine, and
  writes the HTML page of each run in `results/`. Its options are `--workers` (the
  number of processes, 1 by default), `--data-dir` (the feeder files, by default
  where `python -m gridforge.data fetch` writes them), `--feeders` (names of feeder
  files of `--data-dir`, not paths; all of them by default) and `--out` (the directory
  of the pages, `results`). It warns, before the runs, of published feeders that are
  not those of the version of the data gridforge pins; a feeder of one's own, of
  another name, is not checked:

  ```bash
  OMP_NUM_THREADS=1 uv run python gridforge/case_study/mv_lv_feeder.py --workers 4 \
      --feeders 52_MVFeeder1118 11_MVFeeder0725
  ```

  `benchmarks/profile_study.py` runs the same cases, with the same `--data-dir` and
  `--feeders`, and `--workers` (4 by default, not 1), and records the time and the
  version of the data in a JSON file:

  ```bash
  OMP_NUM_THREADS=1 uv run python benchmarks/profile_study.py study --workers 4 \
      --feeders 52_MVFeeder1118 11_MVFeeder0725 --out study.json
  ```

  Without `--feeders`, both run all of them (see `docs/source/performance.rst`).
- **Dickert LV networks**: `uv run python -m gridforge.case_study.dickert_lv_network_script`,
  and the notebook `dickert_lv_network.ipynb`, on networks that pandapower builds. They
  need `igraph`, which the development environment installed by `uv sync` provides.
- **SimBench**: `uv run python gridforge/case_study/simbench_network_test_case.py`, from
  any directory, on a SimBench LV network (provided by the `simbench` package of the
  development environment), without and with 25 % of flexibility. It writes
  `gridforge/case_study/test_case_results.csv`, next to the script, which the notebook
  `test_case_visualisation.ipynb` plots; `--out` writes the CSV file elsewhere (the
  notebook then needs that path in its `RESULTS`).

The notebooks run in the environment of the notebooks group:
`uv run --group notebooks jupyter notebook gridforge/case_study`.

## Project Structure

```
gridforge/
├── core/
│   ├── constraints.py         # Constraint types, limits and violations
│   ├── cost_model.py          # Unit costs and pricing of actions
│   ├── grid_enhancement.py    # The enhancement algorithm and the strategy registry
│   ├── power_flow.py          # The engine interface
│   └── strategy.py            # The strategy interface
├── engines/
│   ├── pandapower_engine.py
│   ├── roseau_engine.py       # Incomplete, see #7
│   ├── opendss_engine.py      # Incomplete, see #7
│   └── gridlabd_engine.py     # Incomplete, see #7
├── strategies/
│   ├── tap_change.py
│   ├── flexibility.py
│   ├── line_upgrade.py
│   ├── path_to_source.py
│   └── transformer_upgrade.py
├── utils/
│   ├── interactive_plot.py    # HTML page of the steps of a run
│   ├── plot.py                # Network plots of the violations
│   ├── logging.py
│   └── config.py
├── case_study/                # Scripts and notebooks on example networks
├── examples/                  # The quick start
├── data/                      # Fetch of the feeders, and the two that the tests use (see Data)
└── tests/
benchmarks/                    # Profiling of the case study
docs/                          # Sphinx documentation
```

## Documentation

The documentation is published on GitLab Pages:
<https://pages.persee.minesparis.psl.eu/energy-alternatives/gridforge/>. To build it
locally, see the [installation guide](docs/source/installation.rst).

## Contributing

Changes go through merge requests on
[GitLab](https://git.persee.minesparis.psl.eu/energy-alternatives/gridforge):

1. Open or pick an issue that describes the change.
2. Create a branch from `main`, named after the issue (`git checkout -b 42-short-description`).
3. Run `uv run pre-commit install` once, so that ruff checks and formats each commit, and
   run the tests with `uv run pytest gridforge/tests`.
4. Push the branch and open a merge request that closes the issue (`Closes #42`).
5. The CI pipeline (lint, tests, documentation build) must pass before merging.

## License

This project is licensed under the MIT License. See [LICENCE.txt](LICENCE.txt) for details.
