Metadata-Version: 2.4
Name: distgridforge
Version: 0.3.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 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. The case studies in
`gridforge/case_study` run the algorithm on real MV/LV feeders, the Dickert LV networks
and SimBench. The Dickert LV case study needs `igraph`, which the development environment
installed by `uv sync` provides.

## 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/                      # Example feeders (most of the feeder data is not versioned, see #10)
└── 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.
