Core Modules#
- class gridforge.core.constraints.ConstraintType(*values)[source]#
Bases:
EnumEnum defining types of constraint violations in power systems.
- LINE_LOADING = 'line_loading'#
- OVER_VOLTAGE = 'over_voltage'#
- TRANSFORMER_LOADING = 'transformer_loading'#
- UNDER_VOLTAGE = 'under_voltage'#
- class gridforge.core.constraints.ConstraintViolation(element_id, element_type, violated_value, absolute_value, constraint_type, violation_value, level=None)[source]#
Bases:
objectRepresents a single constraint violation in the power grid.
- element_id#
Unique identifier for the element (e.g., bus, line, transformer).
- Type:
Union[int, str]
- element_type#
Type of the element (‘Bus’, ‘Line’, ‘Transformer’).
- Type:
str
- violated_value#
The threshold value that is violated by the constraint (e.g., voltage limit, loading limit).
- Type:
float
- absolute_value#
The actual value measured at the element (e.g., voltage in p.u., current in A).
- Type:
float
- constraint_type#
The type of constraint violated (e.g., OVER_VOLTAGE).
- Type:
- violation_value#
The magnitude of the violation (difference from the threshold).
- Type:
float
- level#
The level of the network the element is in, one of LEVELS: “mv”, or “lv” for a bus of 1 kV or less, a line between such buses, and a transformer whose LV side is such a bus (an MV/LV unit, whose loading is a matter of the LV network it feeds). None if the engine does not tell. A priority order that names levels gives the violations of each level their own turn (see EnhancementStrategyRegistry).
- Type:
Optional[str]
- gridforge.core.constraints.LEVELS = ('mv', 'lv')#
the MV network, or an LV network (buses of 1 kV or less).
- Type:
The levels of network a violation can be at (ConstraintViolation.level)
- class gridforge.core.constraints.NetworkConstraints(mv_max_voltage=1.05, mv_min_voltage=0.95, lv_max_voltage=1.1, lv_min_voltage=0.9, max_line_loading=80.0, max_transformer_loading=80.0)[source]#
Bases:
objectDefines network constraints and provides methods to check for violations.
This class encapsulates the logic for identifying voltage and thermal violations based on configurable limits for different voltage levels and equipment types.
- mv_max_voltage#
Maximum allowable per unit voltage for medium voltage.
- Type:
float
- mv_min_voltage#
Minimum allowable per unit voltage for medium voltage.
- Type:
float
- lv_max_voltage#
Maximum allowable per unit voltage for low voltage.
- Type:
float
- lv_min_voltage#
Minimum allowable per unit voltage for low voltage.
- Type:
float
- max_line_loading#
Maximum allowable line loading in percentage.
- Type:
float
- max_transformer_loading#
Maximum allowable transformer loading in percentage.
- Type:
float
- violations#
List of identified violations.
- Type:
List[ConstraintViolation]
- logger#
Logger instance.
- Type:
logging.Logger
- analyze_violations() dict[str, Any][source]#
Analyze a list of violations and return statistics.
- Returns:
DataFrame containing summary statistics of violations grouped by constraint type.
- Return type:
pandas.DataFrame
- check_line_loading_violations(branch_data) list[ConstraintViolation][source]#
Check for loading constraint violations in network branches.
- Parameters:
branch_data (pandas.DataFrame) – DataFrame containing branch loading data. Expected format: DataFrame with columns ‘line_id’, ‘loading_percent’, and ‘current’.
- Returns:
List of ConstraintViolation objects for loading violations.
- Return type:
List[ConstraintViolation]
- check_transformer_loading_violations(transformer_data) list[ConstraintViolation][source]#
Check for loading constraint violations in transformers.
- Parameters:
transformer_data (pandas.DataFrame) – DataFrame containing transformer loading data. Expected format: DataFrame with columns ‘transformer_id’, ‘loading_percent’, and ‘power’.
- Returns:
List of ConstraintViolation objects for loading violations.
- Return type:
List[ConstraintViolation]
- check_violations(bus_data, line_data, transformer_data) list[ConstraintViolation][source]#
Check for violations of voltage, line loading, and transformer loading constraints.
- Parameters:
bus_data (pandas.DataFrame) – DataFrame with columns ‘bus_id’, ‘vm_pu’, and ‘voltage_level’.
line_data (pandas.DataFrame) – DataFrame with columns ‘line_id’ and ‘loading_percent’.
transformer_data (pandas.DataFrame) – DataFrame with columns ‘transformer_id’ and ‘loading_percent’.
- Returns:
A list of ConstraintViolation objects capturing all types of violations found.
- Return type:
List[ConstraintViolation]
- check_voltage_violations(bus_data) list[ConstraintViolation][source]#
Check for voltage constraint violations in the network.
- Parameters:
bus_data (pandas.DataFrame) – DataFrame containing bus voltage data. Expected format: DataFrame with columns ‘bus_id’, ‘vm_pu’, and ‘voltage_level’ where ‘voltage_level’ indicates if it’s ‘mv’ or ‘lv’.
- Returns:
List of ConstraintViolation objects for voltage violations.
- Return type:
List[ConstraintViolation]
- Raises:
ValueError – If required columns are missing in bus_data.
Cost modeling for network changes.
- class gridforge.core.cost_model.CostModel(unit_costs: dict[str, float | dict[str, float] | dict[str, dict[str, float]]])[source]#
Bases:
objectModel for calculating costs of network changes.
This class provides methods to calculate the financial impact of various grid enhancement strategies, such as line upgrades, transformer upgrades, and operational actions like tap changes.
Every price an action needs must be in unit_costs, otherwise pricing the action raises MissingUnitCostError. A price is a real number, 0 or more: pricing an action with anything else raises InvalidUnitCostError. See __init__ for the schema.
- unit_costs#
A dictionary containing unit costs for different actions and equipment types.
- Type:
- logger#
Logger instance.
- Type:
logging.Logger
- calculate_generation_curtailment_cost(amount_curtailed: float) float[source]#
Calculate the cost of generation curtailment.
- Parameters:
amount_curtailed (float) – Amount of generation curtailed in MW.
- Returns:
Total cost in euros.
- Return type:
float
- Raises:
MissingUnitCostError – If generation_curtailment has no price.
- calculate_line_upgrade_cost(line_id: str, new_type: str, length: float) float[source]#
Calculate the cost of upgrading a line.
- Parameters:
line_id (str) – ID of the line being upgraded.
new_type (str) – Type of the new line conductor/cable.
length (float) – Length of the line in kilometers.
- Returns:
Total cost in euros.
- Return type:
float
- Raises:
MissingUnitCostError – If new_type has no line_upgrade price.
- calculate_load_shedding_cost(amount_shed: float) float[source]#
Calculate the cost of load shedding.
- Parameters:
amount_shed (float) – Amount of load shed in MW.
- Returns:
Total cost in euros.
- Return type:
float
- Raises:
MissingUnitCostError – If load_shedding has no price.
- calculate_new_line_cost(line_type: str, length: float) float[source]#
Calculate the cost of adding a new line.
- Parameters:
line_type (str) – Type of the new line.
length (float) – Length of the line in kilometers.
- Returns:
Total cost in euros.
- Return type:
float
- Raises:
MissingUnitCostError – If line_type has neither a new_line nor a line_upgrade price.
- calculate_new_substation_cost(transformer_id: str, transformer_type: str, mv_line_type: str, mv_length_km: float) float[source]#
Calculate the cost of a new MV/LV substation: its works, its unit and its MV cable. Splitting the MV line it is teed into and opening LV lines cost nothing.
Works: new_substation[“works”][transformer_type], € per substation, by the type of its unit, so that the class of substation follows the unit.
Unit: the transformer_upgrade price of transformer_type.
MV cable: new_substation[“mv_cable”][mv_line_type], €/km, its own price, which the line upgrades do not read: it does not fall back on the new_line or line_upgrade price of the type.
- Parameters:
transformer_id (str) – Name of the new unit.
transformer_type (str) – Type of the new unit.
mv_line_type (str) – Type of its MV cable.
mv_length_km (float) – Length of its MV cable (km).
- Returns:
Total cost in euros.
- Return type:
float
- Raises:
MissingUnitCostError – If one of the three prices is missing.
- calculate_new_substation_works_cost(transformer_id: str, transformer_type: str) float[source]#
Calculate the cost of the works of a new substation whose unit is of transformer_type: new_substation[“works”][transformer_type].
A unit that a run created with its substation is charged these works with each unit of its final type (see TransformerUpgradeStrategy.calculate_cost), so that a substation created at one type and upgraded to another costs in all what one created at the other type costs.
- Parameters:
transformer_id (str) – Name of the unit.
transformer_type (str) – Its type.
- Returns:
Cost of the works in euros.
- Return type:
float
- Raises:
MissingUnitCostError – If the type has no works price.
- calculate_no_load_tap_cost(transformer_id: str, interventions: int = 1) float[source]#
Calculate the cost of interventions on the no-load tap of a unit in place (NoLoadTapStrategy, #80, step 6e): unit_costs[“no_load_tap”] per intervention, a site visit, whatever the number of positions moved.
- Parameters:
transformer_id (str) – Name of the transformer.
interventions (int) – Number of interventions, negative for one taken back.
- Returns:
Total cost in euros.
- Return type:
float
- Raises:
MissingUnitCostError – If no_load_tap has no price.
- calculate_tap_change_cost(transformer_id: str, tap_change: int) float[source]#
Calculate the cost of changing transformer tap position.
- Parameters:
transformer_id (str) – ID of the transformer.
tap_change (int) – Number of tap positions changed (absolute value is used).
- Returns:
Total cost in euros.
- Return type:
float
- Raises:
MissingUnitCostError – If tap_change has no price.
- calculate_transformer_upgrade_cost(transformer_id: str, new_type: str) float[source]#
Calculate the cost of upgrading a transformer.
- Parameters:
transformer_id (str) – ID of the transformer being upgraded.
new_type (str) – Type of the new transformer.
- Returns:
Total cost in euros.
- Return type:
float
- Raises:
MissingUnitCostError – If new_type has no transformer_upgrade price.
- check_prices(required: Iterable[tuple[str, ...]]) None[source]#
Check that unit_costs holds the given prices.
- Parameters:
required (Iterable[Tuple[str, ...]]) – Keys of unit_costs, like (“tap_change”,) or (“line_upgrade”, “NAYY 4x120 SE”).
- Raises:
InvalidUnitCostError – If some of them are not prices (not a number, not finite, or negative), listing all of them and the missing ones.
MissingUnitCostError – If prices are missing, listing all of them.
- find_price(*key: str) float | None[source]#
Get the price at key of unit_costs, None if there is nothing there: the way to read a price that may be absent, where the calculate_* methods raise MissingUnitCostError for one that must be there. A new_line price is not replaced by the line_upgrade price of its type here.
- Parameters:
*key (str) – The path to the price in unit_costs, like (“tap_change”,) or (“line_upgrade”, “NAYY 4x120 SE”).
- Returns:
- The price, None if unit_costs has nothing at key (or a
table of prices, which is a misplaced price).
- Return type:
Optional[float]
- Raises:
InvalidUnitCostError – If what is there is not a price.
- missing_prices(keys: Iterable[tuple[str, ...]]) list[str][source]#
List those of the given prices that unit_costs does not hold, as check_prices names them.
A new_line price falls back on the line_upgrade price of the type, as calculate_new_line_cost does.
- Parameters:
keys (Iterable[Tuple[str, ...]]) – Keys of unit_costs.
- Returns:
The missing prices, empty if there is none.
- Return type:
List[str]
- Raises:
InvalidUnitCostError – If some of those that are there are not prices, as check_prices would, listing all of them.
- exception gridforge.core.cost_model.InvalidUnitCostError[source]#
Bases:
ValueErrorA price of unit_costs is not a price: not a number, not finite, or negative.
A price is a real number (int, float, Decimal, numpy scalar…), 0 or more. A string is not converted, even if it reads as a number: a price must not depend on how a text is parsed.
- exception gridforge.core.cost_model.MissingUnitCostError[source]#
Bases:
LookupErrorA price is missing from unit_costs.
Pricing the action at 0 instead would understate the reported total cost. An action that really is free must say so with an explicit price of 0.0.
- gridforge.core.cost_model.UnitCosts#
a price, a table of prices by type, or, for new_substation, tables of prices by type under further keys (see CostModel).
- Type:
The prices of CostModel
alias of
dict[str,float|dict[str,float] |dict[str,dict[str,float]]]
Grid Enhancement Algorithm for constraint management in electricity distribution networks.
- class gridforge.core.grid_enhancement.EnhancementStrategyRegistry(violation_priority_order: list[Any] | None = None)[source]#
Bases:
objectRegistry for managing enhancement strategies by violation type.
- get_all_strategies() set[EnhancementStrategy][source]#
Get the registered strategies, each one once whatever the violations it addresses.
- Returns:
The registered strategies.
- Return type:
Set[EnhancementStrategy]
- get_strategies_for_type(violation_type: str) list[EnhancementStrategy][source]#
Get strategies applicable to the given violation type.
- Parameters:
violation_type (str) – Type of violation: an entry of the priority order, a ConstraintType or a TypeAtLevel.
- Returns:
List of applicable strategies, ordered by increasing cost level.
- Return type:
List[EnhancementStrategy]
- register_strategy(strategy: EnhancementStrategy)[source]#
Register a strategy for its applicable violation types.
The types the priority order leaves out are not addressed, so a strategy is only registered for the others, with a warning for each type dropped. A strategy for none of them is not registered.
Where the priority order gives a type turns at levels, the strategy is registered for the turns of the levels it applies to (EnhancementStrategy.applicable_levels, both by default). Where the order gives a type one turn at every level, it is registered for it whatever its levels.
- Parameters:
strategy (EnhancementStrategy) – The strategy to register.
- class gridforge.core.grid_enhancement.GridEnhancementAlgorithm(power_flow_engine: PowerFlowEngine, cost_model: CostModel | None = None, max_iterations: int = 13, strategy_registry: EnhancementStrategyRegistry | None = None, strategy_choice: str = 'lookahead')[source]#
Bases:
objectBase algorithm to enhance electricity distribution networks to prevent operational constraints.
The algorithm runs in a hierarchical manner:
Execute power flow and identify all constraint violations.
Group violations by type.
For each type of violation, apply appropriate strategies in order of increasing cost level, or, with a cost model, those leading to the best end of the run (see strategy_choice). A type whose turn has passed is given it again in the pass, once, if a later turn brings about violations of it (see _turns).
Rerun power flow after each strategy application to check if violations are resolved.
- pf_engine#
Engine to perform power flow calculations.
- Type:
- max_iterations#
Maximum number of passes through the violation types.
- Type:
int
- strategy_registry#
Registry of enhancement strategies.
- logger#
Logger instance.
- Type:
logging.Logger
- applied_actions#
List of actions applied during the enhancement process.
- Type:
List[Dict[str, Any]]
- total_cost#
Total cost of all applied actions.
- Type:
float
- history#
History of the enhancement process.
- Type:
List[Dict[str, Any]]
- divergence_events#
Power flow divergences met during the last run. Each event gives the violation_type and strategy_name being applied (both None for the initial power flow) and the solver message.
- Type:
List[Dict[str, Any]]
- divergence_events: list[dict[str, Any]]#
- run() tuple[bool, dict[str, Any]][source]#
Run the grid enhancement algorithm using Sequential Greedy approach with best partial solution tracking.
Applies strategies one at a time in user-defined order, but returns the best partial solution if a complete solution cannot be found. Every state left by a strategy is a candidate, including those between two strategies of the same violation type.
If a strategy makes the power flow diverge, it is undone (including everything it did before diverging) and the next strategy is tried, so a diverging strategy never leaves the network in an unsolved state. The divergence is reported in the results. Because undoing restores a saved copy of the network, the engine’s network may be a different object after run() than before.
- Returns:
- A tuple containing:
Success flag (bool): True if all constraints were completely resolved.
Results dictionary (Dict[str, Any]): Details on violations, actions taken, and costs. diverged tells whether a power flow diverged along the way, and divergence_events lists those divergences. A run can both diverge and succeed, when another strategy resolved the violations. A run that ends unsuccessfully with diverged False found no strategy able to do more, or reached max_iterations. iterations is the number of passes made. An unsuccessful run returns its best partial solution: the state with the fewest violations, then the cheapest, then the one with the least severe violations.
- Return type:
Tuple[bool, Dict[str, Any]]
- Raises:
MissingUnitCostError – If unit_costs lacks a price, either one the strategies are known to need, which stops the run before it starts, or one that an action turns out to need along the way.
Exception – Whatever a strategy raises, other than a power flow divergence. The run stops there, with no results. Like a missing price met along the way, it leaves the engine, applied_actions and total_cost in the last solved state of the run: the one the failing strategy started from, or, if it failed while the strategies of a violation type were being compared (strategy_choice=”lookahead”), the one that comparison started from.
PowerFlowNotConverged – If the initial power flow diverges, as there is then no partial solution to return.
ValueError – If the engine refuses the network before the initial power flow, for names (PandaPowerEngine.check_names) or ZIP shares (PandaPowerEngine.check_zip_shares): it is not a divergence, and diverged and divergence_events do not report it, as run() ends there with no results.
The strategies hold the cost model of the run as their cost_model while it runs, to choose between their own options with, and, in a run with a cost model, the state of the lines and of the transformers as it started as their line_origins and transformer_origins, to price them as the run charges them. They hold the powers of the loads and generators as the run started as their initial_power, from which the limits of flexibility count, the type and conductors of each line and the type and units of each transformer as the run started as their lines_at_start and transformers_at_start, with a cost model or without (see NewSubstationStrategy), and a mapping, shared by all of them, of the lines found at a cap on conductors in parallel as their lines_at_cap_of_the_run (see LineUpgradeStrategy), and another of the transformers no option was left for as their units_at_top_of_the_run (see TransformerUpgradeStrategy). They also hold the parallel_units of the strategies that have one (TransformerUpgradeStrategy, #83) as their parallel_units_of_the_run, None if none has, so that a strategy that refunds transformer upgrades (NewSubstationStrategy) refunds what they charged. They get their own back when it ends.
- Raises:
ValueError – If the strategies that have a parallel_units disagree, or a strategy’s own transformer_parallel_units differs from theirs: the run would charge a unit in parallel by one rule and refund it by another.
- gridforge.core.grid_enhancement.TOP_DOWN_ORDER = ((ConstraintType.TRANSFORMER_LOADING, 'mv'), (ConstraintType.LINE_LOADING, 'mv'), (ConstraintType.OVER_VOLTAGE, 'mv'), (ConstraintType.UNDER_VOLTAGE, 'mv'), (ConstraintType.TRANSFORMER_LOADING, 'lv'), (ConstraintType.LINE_LOADING, 'lv'), (ConstraintType.OVER_VOLTAGE, 'lv'), (ConstraintType.UNDER_VOLTAGE, 'lv'))#
The top-down order of the reinforcement (#80, decided by the maintainer on 2026-11-25): the MV network first, then the LV networks. In each, the loading of the transformers (an HV/MV unit in the MV network; an MV/LV unit in the LV network it feeds, whose voltages and loadings its upgrade moves), then that of the lines, then the over- and under-voltages. A violation an LV turn brings about in the MV network, such as a new substation moving the MV voltage, gets the MV turn again in the pass, or in the next (see GridEnhancementAlgorithm._turns).
- class gridforge.core.grid_enhancement.TypeAtLevel(constraint_type: ConstraintType, level: str)[source]#
Bases:
NamedTupleA violation type at one level of network, “mv” or “lv” (ConstraintViolation.level): an entry of a priority order that gives the violations of each level of a type a turn of their own (see EnhancementStrategyRegistry). A registry takes it as a pair,
(ConstraintType.OVER_VOLTAGE, "lv").- constraint_type: ConstraintType#
Alias for field number 0
- level: str#
Alias for field number 1
Planning profiles (#80, step 6f): named ways of searching for the works that resolve a network’s violations, each made for a persona and translated into the settings of a run.
A profile fixes how the run searches: - the priority order of the violation types (order, a name of ORDERS); - how the strategies of a turn are chosen (strategy_choice); - whether the run is priced (priced); - which strategies it registers, with their search options.
It does not fix the data of a study: line and transformer types, prices, the cap on conductors in parallel, the flexibility of loads and generators. gridforge’s strategies are heuristics: no profile, nor any setting, claims the plan of lowest cost, and none ranks above another. The profiles explore the space of solutions in different ways, at different CPU costs; the measured figures of the documentation say what each gives on the case study.
A study can use a profile without the case study: PROFILES[“hosting_capacity”] gives the priority order (priority_order, or new_registry()), the options of GridEnhancementAlgorithm (algorithm_options) and those of each strategy (line_upgrade_options, new_substation_options), for strategies the study builds itself. get_profile(name, **overrides) replaces any setting.
- gridforge.core.profiles.LOADING_FIRST_ORDER = ((ConstraintType.TRANSFORMER_LOADING, 'lv'), (ConstraintType.LINE_LOADING, 'lv'), (ConstraintType.TRANSFORMER_LOADING, 'mv'), (ConstraintType.LINE_LOADING, 'mv'), (ConstraintType.OVER_VOLTAGE, 'mv'), (ConstraintType.UNDER_VOLTAGE, 'mv'), (ConstraintType.OVER_VOLTAGE, 'lv'), (ConstraintType.UNDER_VOLTAGE, 'lv'))#
The loading first, from the bottom up (the LV networks, then the MV network), then the voltages from the top down (the MV network, then the LV networks); the “loadup” order of the measurements of #80. A named setting, not a profile. Measured with every lever (as extended), against the top-down order, on the 150 feeders of version 2 (total cost, researcher’s runs at cbdbccf, 2026-11-27): −1.2 % at 0 % of flexibility and −0.5 % at 30 % with loads × 2.5, the data it was chosen on; −0.1 % and −0.0 % with loads × 2.0, which it was not chosen on.
- gridforge.core.profiles.ORDERS: dict[str, tuple[TypeAtLevel, ...] | None] = {'default': None, 'loading_first': ((ConstraintType.TRANSFORMER_LOADING, 'lv'), (ConstraintType.LINE_LOADING, 'lv'), (ConstraintType.TRANSFORMER_LOADING, 'mv'), (ConstraintType.LINE_LOADING, 'mv'), (ConstraintType.OVER_VOLTAGE, 'mv'), (ConstraintType.UNDER_VOLTAGE, 'mv'), (ConstraintType.OVER_VOLTAGE, 'lv'), (ConstraintType.UNDER_VOLTAGE, 'lv')), 'top_down': ((ConstraintType.TRANSFORMER_LOADING, 'mv'), (ConstraintType.LINE_LOADING, 'mv'), (ConstraintType.OVER_VOLTAGE, 'mv'), (ConstraintType.UNDER_VOLTAGE, 'mv'), (ConstraintType.TRANSFORMER_LOADING, 'lv'), (ConstraintType.LINE_LOADING, 'lv'), (ConstraintType.OVER_VOLTAGE, 'lv'), (ConstraintType.UNDER_VOLTAGE, 'lv'))}#
The named priority orders a profile can take, by name.
- gridforge.core.profiles.PROFILES: dict[str, PlanningProfile] = {'extended': PlanningProfile(name='extended', persona='A planner who wants to see what a wider set of measures and a top-down order find, at more CPU.', search="The top-down order (the MV network first, then each LV network), every lever: the line upgrades restricted to the zone of the violations, one per zone, and new MV/LV substations, which take back the line and unit upgrades of an LV network before adding one unit to it per call (at most the study's number of new units); lookahead, priced. More CPU than `standard`.", order='top_down', strategy_choice='lookahead', priced=True, no_load_tap=True, restrict_to_violation_zone=True, one_upgrade_per_zone=True, new_substation=True, take_back_line_upgrades=True, take_back_transformer_upgrades=True, units_per_call=1, max_new_substations=None), 'hosting_capacity': PlanningProfile(name='hosting_capacity', persona='A connection or hosting-capacity analyst who needs the works a scenario requires, not their cost: runs without prices, as pv-flex runs, and the set-up proposed for pv-flex.', search='As `extended`, without prices: the first strategy that resolves a turn is kept. Its plan is a set of works that resolves the violations, not a cost estimate: the line choices are not guided by price.', order='top_down', strategy_choice='first', priced=False, no_load_tap=True, restrict_to_violation_zone=True, one_upgrade_per_zone=True, new_substation=True, take_back_line_upgrades=True, take_back_transformer_upgrades=True, units_per_call=1, max_new_substations=None), 'screening': PlanningProfile(name='screening', persona='An analyst running many feeders or scenarios, for an envelope or a ranking rather than a programme.', search="As `standard`, but the first strategy that resolves a turn is kept, without the lookahead: it rates fewer chains of strategies, so its plans can differ from `standard`'s where the choices interact (flexibility against works), and it takes less CPU.", order='default', strategy_choice='first', priced=True, no_load_tap=True, restrict_to_violation_zone=False, one_upgrade_per_zone=False, new_substation=False, take_back_line_upgrades=False, take_back_transformer_upgrades=True, units_per_call=None, max_new_substations=None), 'standard': PlanningProfile(name='standard', persona='The planner of an investment programme: routine works (line upgrades, transformer upgrades, the no-load tap of the unit in place), priced.', search="The default order of the violation types; in each turn, the lookahead rates the chains of strategies it tries by their cost, and keeps the one of lower cost among them. The case study's default.", order='default', strategy_choice='lookahead', priced=True, no_load_tap=True, restrict_to_violation_zone=False, one_upgrade_per_zone=False, new_substation=False, take_back_line_upgrades=False, take_back_transformer_upgrades=True, units_per_call=None, max_new_substations=None)}#
The planning profiles, by name (#80, step 6f).
- class gridforge.core.profiles.PlanningProfile(name: str, persona: str, search: str, order: str | tuple = 'default', strategy_choice: str = 'lookahead', priced: bool = True, no_load_tap: bool = True, restrict_to_violation_zone: bool = False, one_upgrade_per_zone: bool = False, new_substation: bool = False, take_back_line_upgrades: bool = False, take_back_transformer_upgrades: bool = True, units_per_call: int | None = None, max_new_substations: int | None = None)[source]#
Bases:
objectA way of searching for the works of a network: the persona it is made for, how it searches, and the settings that translate them.
- name#
The name of the profile.
- Type:
str
- persona#
Who it is for, and the question it answers.
- Type:
str
- search#
How it searches, and what that trades off.
- Type:
str
- order#
The priority order of the violation types: a name of ORDERS, or the entries of an order (see EnhancementStrategyRegistry), each a ConstraintType (a turn for every level) or a pair of a ConstraintType and a level, “lv” or “mv”; not empty, no entry twice, and no type both alone and at a level.
- Type:
str | tuple
- strategy_choice#
How the strategies of a turn are chosen (GridEnhancementAlgorithm): “lookahead” rates the chains of strategies by their cost, “first” keeps the first that resolves the turn.
- Type:
str
- priced#
Whether the run has a cost model. Without one, the strategies choose without prices, and only “first” is meaningful.
- Type:
bool
- no_load_tap#
Whether NoLoadTapStrategy is registered.
- Type:
bool
- restrict_to_violation_zone#
LineUpgradeStrategy’s option: the lines of the zone of the violated buses only.
- Type:
bool
- one_upgrade_per_zone#
LineUpgradeStrategy’s option: one upgrade per zone and call.
- Type:
bool
- new_substation#
Whether NewSubstationStrategy is registered.
- Type:
bool
- take_back_line_upgrades#
NewSubstationStrategy’s option: take back the line upgrades of the run in an LV network before adding a unit to it.
- Type:
bool
- take_back_transformer_upgrades#
NewSubstationStrategy’s option, with take_back_line_upgrades: take back the upgrades of the unit in place too.
- Type:
bool
- units_per_call#
NewSubstationStrategy’s option: the most units added per call (None: as many as the strategy finds).
- Type:
int | None
- max_new_substations#
NewSubstationStrategy’s option: the most new units of an LV network over a run (None: the study’s).
- Type:
int | None
- algorithm_options(cost_model: Any = None) dict[str, Any][source]#
The options of GridEnhancementAlgorithm of the profile: strategy_choice, and cost_model, the one given for a priced profile, None for one without prices.
- Raises:
ValueError – If the profile is priced and no cost model is given.
- line_upgrade_options() dict[str, Any][source]#
The options of LineUpgradeStrategy that the profile sets.
- new_registry() EnhancementStrategyRegistry[source]#
An empty registry with the priority order of the profile.
- new_substation_options() dict[str, Any][source]#
The options of NewSubstationStrategy that the profile sets; without max_new_substations when it leaves it to the study.
- property priority_order: tuple | None#
the default).
- Type:
The priority order, for EnhancementStrategyRegistry (None
- settings() dict[str, Any][source]#
The settings of the profile, without its texts, as a run records them.
- with_overrides(**overrides: Any) PlanningProfile[source]#
The profile with overrides replacing its settings, by name; the name says that it was overridden.
- Raises:
ValueError – If an override is not a setting of a profile.
- gridforge.core.profiles.get_profile(profile: str | PlanningProfile = 'standard', **overrides: Any) PlanningProfile[source]#
A profile, by name or as given, with overrides replacing its settings (PlanningProfile.with_overrides).
- Raises:
ValueError – If no profile has the name, or an override is not a setting.
Core interfaces for power flow engines.
- class gridforge.core.power_flow.PowerFlowEngine(config: dict[str, Any] | None = None)[source]#
Bases:
ABCAbstract base class for power flow engines.
This class defines the standard interface that any power flow engine (e.g., PandaPower, OpenDSS) must implement to be compatible with the GridForge framework. It handles network creation, modification, simulation, and results retrieval.
- network#
The underlying network model object (engine-specific).
- Type:
Any
- pf_settings#
Configuration settings for power flow calculations.
- Type:
Dict[str, Any]
- network_partition#
Cached network partition data.
- Type:
Optional[Dict[int, Any]]
- latest_results#
Results from the most recent power flow run.
- Type:
Optional[Dict[str, Any]]
- config#
General configuration dictionary.
- Type:
Dict[str, Any]
- logger#
Logger instance.
- Type:
logging.Logger
- flexibility_settings#
Settings for flexible assets (loads/sgens).
- Type:
Dict[str, Dict[str, float]]
- constraints#
Object managing network operational limits.
- Type:
- add_bus(like_bus: int, coordinates: tuple[float, float] | None = None, name: str | None = None) int[source]#
Create a bus of the voltage level and limits of like_bus, not connected to anything.
- Parameters:
like_bus (int) – Index of the bus whose nominal voltage, zone and limits the new bus takes.
coordinates (tuple[float, float] | None) – Its (longitude, latitude), if any.
name (str | None) – Its name, followed by
_2,_3… when another bus has it. A name made from that of like_bus if None.
- Returns:
Index of the new bus.
- Return type:
int
- add_line(from_bus: int, to_bus: int, line_type: str, length_km: float, geometry: list[tuple[float, float]] | None = None, name: str | None = None) str[source]#
Create a line of a type between two buses of the same nominal voltage.
- Parameters:
from_bus (int) – Index of its from_bus.
to_bus (int) – Index of its to_bus.
line_type (str) – Its type.
length_km (float) – Its length, more than 0.
geometry (list[tuple[float, float]] | None) – Its route, (longitude, latitude) points from from_bus to to_bus, if any.
name (str | None) – Its name, followed by
_2,_3… when another line has it. A name made from those of its buses if None.
- Returns:
Name of the new line.
- Return type:
str
- abstractmethod add_parallel_line(line_id: str) int[source]#
Add a parallel line.
- Parameters:
line_id (str) – Name of the line to add a conductor to.
- Returns:
Number of parallel conductors of the line after the addition.
- Return type:
int
- abstractmethod add_parallel_transformer(trafo_id: str) int[source]#
Add a parallel transformer.
- Parameters:
trafo_id (str) – Name of the transformer to add a unit to.
- Returns:
Number of parallel units of the transformer after the addition.
- Return type:
int
- add_transformer(hv_bus: int, lv_bus: int, transformer_type: str, tap_pos: float, like: str | None = None, name: str | None = None) str[source]#
Create a transformer of a type between two buses, at a tap position.
- Parameters:
hv_bus (int) – Index of its HV bus.
lv_bus (int) – Index of its LV bus.
transformer_type (str) – Its type.
tap_pos (float) – Its tap position, within the tap range it has.
like (str | None) – Name of a transformer whose vector group and tap changer it takes, those of its type if None.
name (str | None) – Its name, followed by
_2,_3… when another transformer has it. A name made from those of its buses if None.
- Returns:
Name of the new transformer.
- Return type:
str
- abstractmethod analyze_thermal_violation(element_type: str, element_id: str) dict[str, Any][source]#
Analyze a thermal violation to determine downstream topology and flow conditions.
- Parameters:
element_type (str) – “Line” or “Transformer”.
element_id (str) – Name of the element.
- Returns:
Dictionary containing: - “downstream_buses”: List[str] of bus names downstream of the element - “flow_mw”: Active power flow through the element (at upstream end) - “rated_mva”: Rated capacity of the element - “is_flow_towards_downstream”: Boolean indicating if power flows towards downstream
- Return type:
Dict[str, Any]
- abstractmethod analyze_violations() Any[source]#
Analyze and summarize network constraint violations.
- Returns:
Summary of violations (format depends on implementation).
- Return type:
Any
- abstractmethod apply_flexibility_action(element_type: str, element_index: int, new_p_mw: float, new_q_mvar: float | None = None) None[source]#
Apply a flexibility action (change active power) to an element.
The method does not check the service state of the element, nor whether its bus is energised: it writes to the element it is given, even when that element is out of service or at a de-energised bus. A caller acting outside FlexibilityStrategy, which never selects such an element, must filter them out itself.
- Parameters:
element_type (str) – ‘load’ or ‘sgen’.
element_index (int) – Index of the element.
new_p_mw (float) – New active power value in MW.
new_q_mvar (Optional[float], optional) – New reactive power of a load, in MVAr. Defaults to None, which keeps the power factor of the load. Passing it is needed to restore a load that was shed down to zero, as its power factor is lost with its active power.
- abstractmethod apply_tap_change(trafo_id: str, tap_pos_shift: int) bool[source]#
Change the tap position of a transformer by a number of steps.
The shift is applied whole or not at all: an engine refuses a shift that would take the position outside the tap range of the unit, and changes nothing then.
- Parameters:
trafo_id (str) – Name of the transformer.
tap_pos_shift (int) – Number of steps added to the current tap position, negative to lower it (TapChangeStrategy passes shifts of several steps).
- Returns:
- True if the position moved by tap_pos_shift, False if nothing
changed, the new position being outside the range.
- Return type:
bool
- abstractmethod calculate_branch_loading_sensitivities(element_type: str, element_name: str) DataFrame[source]#
Calculate sensitivity of a branch’s loading (current) to active power injections.
- Parameters:
element_type (str) – “Line” or “Transformer”.
element_name (str) – Name of the element.
- Returns:
DataFrame with index=bus_names and one column, “sensitivity”, with values = d(Loading_pct)/d(P_mw): the change of the loading of the branch, in %, per MW of active power injected at the bus, at constant reactive injection. Empty if the sensitivities are not available. Positive value means injecting more at the bus increases the loading. Negative value means injecting more at the bus decreases the loading. The sign does not depend on the direction of the flow in the branch.
- Return type:
pd.DataFrame
- calculate_voltage_line_change_effects(changes: dict[str, tuple[float, float, int]], buses: list[str] | None = None) DataFrame[source]#
Predicted bus voltage-magnitude change (p.u.) for a finite change of each line: line name -> (new r_ohm_per_km, new x_ohm_per_km, new parallel count). Returns a DataFrame (index = bus names, or buses when given; columns = line names).
- calculate_voltage_line_change_effects_of_steps(steps: list[tuple[str, float, float, int]], buses: list[str] | None = None) DataFrame[source]#
Predicted bus voltage-magnitude change (p.u.) for each of steps, each a finite change of one line, taken alone: (line name, new r_ohm_per_km, new x_ohm_per_km, new parallel count). Unlike calculate_voltage_line_change_effects, a line can have several steps, so that every step of every line is predicted in one call.
By default, the steps are given to calculate_voltage_line_change_effects in as many calls as a line has steps, the k-th step of every line in the k-th call. An engine whose prediction of one step does not depend on the other steps of the call can predict them all at once.
- Returns:
- index = bus names, or buses when given; columns = the
positions in steps of the steps whose line conducts, in order.
- Return type:
pd.DataFrame
- abstractmethod calculate_voltage_line_resistance_sensitivities(line_names: list[str] | None = None) dict[str, ndarray][source]#
Calculate the sensitivities of bus voltages to line impedance changes.
- Parameters:
line_names (Optional[List[str]], optional) – Restrict the computation to these lines.
- Returns:
Dictionary mapping line IDs to arrays of sensitivity values. Each array contains the sensitivity of that line’s impedance to voltage changes at each bus in the network.
- Return type:
Dict[str, np.ndarray]
- abstractmethod calculate_voltage_power_sensitivities(buses: list[str] | None = None) DataFrame[source]#
Calculate the sensitivities of bus voltage magnitudes to active power injections.
Used for linearized sensitivity analysis: dV ~ (dV/dP) * dP
- Parameters:
buses (Optional[List[str]]) – Names of the buses whose voltage sensitivities are needed, which can be much cheaper than all of them. Defaults to None, for all buses.
- Returns:
DataFrame where index and columns are bus names. Values represent d|V|_i / dP_j (change in voltage at bus i per unit change in P at bus j).
- Return type:
pd.DataFrame
- abstractmethod check_violations() list[ConstraintViolation][source]#
Check if the network violates specified constraints.
- Returns:
List of constraint violations.
- Return type:
List[ConstraintViolation]
- abstractmethod create_bus(name: str, nominal_voltage_v: float, **kwargs: Any) int[source]#
Create a new bus in the network.
- Parameters:
name (str) – Name of the bus.
nominal_voltage_v (float) – Nominal voltage of the bus in V.
**kwargs – Additional parameters for the bus.
- Returns:
Index of the created bus.
- Return type:
int
- abstractmethod create_empty_network(name: str | None = None, f_hz: float | None = 50.0) None[source]#
Create an empty network with a given name and frequency.
- Parameters:
name (Optional[str], optional) – Name of the network. Defaults to None.
f_hz (Optional[float], optional) – System frequency in Hz. Defaults to 50.0.
- abstractmethod create_ext_grid(bus_name: str, name: str, voltage_reference_pu: float, angle_reference_degree: float = 0, **kwargs: Any) int[source]#
Create a new external grid connection in the network.
- Parameters:
bus_name (str) – Name of the bus where the external grid is connected.
name (str) – Name of the external grid.
voltage_reference_pu (float) – Voltage magnitude in per unit.
angle_reference_degree (float, optional) – Voltage angle in degrees. Defaults to 0.
**kwargs – Additional parameters for the external grid.
- Returns:
Index of the created external grid.
- Return type:
int
- abstractmethod create_generator(bus_name: str, name: str, active_power_w: float, reactive_power_var: float, **kwargs: Any) int[source]#
Create a new static generator in the network.
- Parameters:
bus_name (str) – Name of the bus where the generator is connected.
name (str) – Name of the generator.
active_power_w (float) – Active power of the generator in W.
reactive_power_var (float) – Reactive power of the generator in VAr.
**kwargs – Additional parameters for the generator.
- Returns:
Index of the created generator.
- Return type:
int
- abstractmethod create_line(name: str, from_bus: str, to_bus: str, length_km: float, line_type: str, **kwargs: Any) int[source]#
Create a new line in the network.
- Parameters:
name (str) – Name of the line.
from_bus (str) – Name of the starting bus.
to_bus (str) – Name of the ending bus.
length_km (float) – Length of the line in kilometers.
line_type (str) – Type of the line (refers to standard types in the network model).
**kwargs – Additional parameters for the line.
- Returns:
Index of the created line.
- Return type:
int
- abstractmethod create_load(bus_name: int, name: str, active_power_w: float, reactive_power_var: float, **kwargs: Any) int[source]#
Create a new load in the network.
- Parameters:
bus_name (str) – Name of the bus where the load is connected.
name (str) – Name of the load.
active_power_w (float) – Active power of the load in W.
reactive_power_var (float) – Reactive power of the load in VAr.
**kwargs – Additional parameters for the load.
- Returns:
Index of the created load.
- Return type:
int
- abstractmethod create_topology_graph() Any[source]#
Create a NetworkX graph representing the network topology.
- Returns:
NetworkX graph object.
- Return type:
Any
- abstractmethod create_transformer(name: str, hv_bus: str, lv_bus: str, transformer_type: str, **kwargs: Any) int[source]#
Create a new transformer in the network.
- Parameters:
name (str) – Name of the transformer.
hv_bus (str) – Name of the high voltage bus.
lv_bus (str) – Name of the low voltage bus.
transformer_type (str) – Type of the transformer (refers to standard types in the network model).
**kwargs – Additional parameters for the transformer.
- Returns:
Index of the created transformer.
- Return type:
int
- get_bus_coordinates(bus_ids: Iterable[int]) dict[int, tuple[float, float] | None][source]#
Coordinates (longitude, latitude) of buses, None for a bus that has none (no geodata, or NaN coordinates).
- Parameters:
bus_ids (Iterable[int]) – Indices of the buses.
- Returns:
The coordinates of each bus.
- Return type:
dict[int, tuple[float, float] | None]
- get_buses_info() DataFrame[source]#
Every bus, indexed by its index (the nodes of create_topology_graph, the buses of the operations above): its name, nominal voltage vn_kv, in_service, and, from the latest power flow, its voltage vm_pu and the active and reactive power injected into the network there by the elements at the bus, p_mw and q_mvar (positive for a generation, negative for a load), NaN where there is no converged power flow, or no result for the bus; and the active power drawn and produced by the elements in service at the bus, consumption_mw and production_mw (0 or more each).
- get_closed_bus_switches() list[tuple[str, str]][source]#
Pairs of bus names joined by a closed bus-bus switch (galvanic links that are not lines). Engines without bus-bus switches return an empty list.
- get_component_id_for_bus(bus_id: int | str) int | None[source]#
Retrieve the component ID for a given bus ID.
This method looks up which network partition component contains the specified bus.
- Parameters:
bus_id (Union[int, str]) – The ID of the bus to find the component for.
- Returns:
The ID of the component containing the bus, or None if the bus is not found or if the network has not been partitioned.
- Return type:
Optional[int]
- get_config() dict[str, Any][source]#
Get the current configuration dictionary.
- Returns:
Current configuration dictionary.
- Return type:
Dict[str, Any]
- get_customer_buses() set[str][source]#
Names of the buses with a customer: an element in service that draws or produces power (a load, a static or other generator, a storage unit), whatever its power at the moment. Engines that cannot tell raise NotImplementedError.
- abstractmethod get_flexibility_data(element_type: str) DataFrame[source]#
Get flexibility data for loads or static generators.
Only the elements that carry power are returned: those in service, and at a bus that is energised (in service, and not in an island without a source). The elements left out have no power to shed or curtail, and are not part of the load or the generation of the network. FlexibilityStrategy relies on this: what the data lists is what it may act on, charges, and counts in the totals and the shares of a run, so an engine must not return the others. The index of the rows is the engine’s own for the element, whatever is left out.
- Parameters:
element_type (str) – ‘load’ or ‘sgen’.
- Returns:
DataFrame with columns [‘name’, ‘bus’, ‘p_mw’, ‘max_flex_pct’].
- Return type:
pd.DataFrame
- get_line_base_impedance(line_id: int | str) float[source]#
Per-unit base impedance (ohm) of a line. Engines without per-unit data return 1.0.
- get_line_endpoints(line_ids: list[str] | None = None) DataFrame[source]#
Names of the end buses (columns from_bus, to_bus) of the lines that conduct (in service, not opened by a switch, between buses that are in service and supplied), indexed by line name.
- get_line_geometry(line_id: str) list[tuple[float, float]] | None[source]#
Route of a line, as (longitude, latitude) points running from its from_bus to its to_bus, None for a line without one.
- Parameters:
line_id (str) – Name of the line.
- get_line_ids() list[str][source]#
Names of the lines that conduct: in service, not opened by a switch, and between buses that are in service and supplied.
- abstractmethod get_line_imax(line_type) float[source]#
Abstract method for retrieving the maximum current limit of a specified line type.
- Parameters:
line_type (str) – The type of the line.
- Returns:
The maximum current limit (IMAX) for the specified line type.
- Return type:
float
- abstractmethod get_line_length(line_id: int | str) float[source]#
Get the length of a line by its ID.
- Parameters:
line_id (Union[int, str]) – The ID of the line.
- Returns:
The length of the line in kilometers.
- Return type:
float
- get_line_parallel(line_id: int | str) int[source]#
Number of parallel conductors of a line. Engines without this notion return 1.
- abstractmethod get_line_r_ohm_per_km(line_type: str) float[source]#
Abstract method for retrieving the resistance per unit length of a specified line type.
- Parameters:
line_type (str) – The type of the line.
- Returns:
The resistance per unit length (Ohm/km).
- Return type:
float
- get_line_rating(line_id: int | str) float | None[source]#
Rating (A) of one conductor of a line, the one the loading the engine reports is relative to. Engines that do not give it return None: the thermal upgrade then takes the rating of the type of the line.
- abstractmethod get_line_type(line_id: str) str[source]#
Abstract method for retrieving the type of a specified line.
- Parameters:
line_id (str) – The ID of the line.
- Returns:
The type of the line.
- Return type:
str
- get_line_x_ohm_per_km(line_type: str) float[source]#
Reactance per unit length (Ohm/km) of a line type.
- get_lines_info(line_ids: list[str] | None = None) DataFrame[source]#
Type (std_type), length (length_km) and parallel count (parallel) of lines, indexed by name. An engine that has it also gives current_a, the current (A) the whole line carries in the latest power flow, which the strategies that bury lines use to keep them within the rating of the cable; without it they do not check that. And df, the derating factor of the line, which a type change keeps and the loading of the line is relative to; without it, a factor of 1 is assumed.
- abstractmethod get_losses() dict[str, float][source]#
Calculate network losses.
- Returns:
Dictionary with active and reactive power losses.
- Return type:
Dict[str, float]
- abstractmethod get_network_metrics() dict[str, Any][source]#
Get various network metrics.
- Returns:
Dictionary with network metrics.
- Return type:
Dict[str, Any]
- get_open_links() list[tuple[str, str]][source]#
Pairs of bus names that an open switch alone keeps apart: the ends of a line in service opened by a line switch (a normally open point of a loop), and the buses of an open bus-bus switch. Engines without switches return an empty list.
- get_source_buses() set[str][source]#
Names of the buses that feed a galvanic zone: external grid buses and transformer LV buses.
- get_supplying_transformer_for_bus(bus_id: int | str) str | None[source]#
Retrieve the name of the transformer supplying a given bus.
This method finds the component containing the bus and returns the transformer associated with that component.
- Parameters:
bus_id (Union[int, str]) – The ID of the bus to find the supplying transformer for.
- Returns:
The name of the transformer supplying the bus, or None if no transformer is found or if the bus is not present in the network.
- Return type:
Optional[str]
- get_transformer_for_component(component_id: int) str | None[source]#
Retrieve the name of the transformer for a specific network component.
Since each galvanically connected component can have only one transformer, this method returns that transformer’s name, which is how the engine identifies it (apply_tap_change, get_transformer_tap_positions…).
- Parameters:
component_id (int) – The ID of the component to find the transformer for.
- Returns:
The name of the transformer for the component, or None if no transformer exists or if the component ID is invalid.
- Return type:
Optional[str]
- abstractmethod get_transformer_max_power(transformer_type: str) float[source]#
Abstract method for retrieving the maximum power rating of a specified transformer type.
- Parameters:
transformer_type (str) – The type of the transformer.
- Returns:
The maximum power rating for the specified transformer type.
- Return type:
float
- get_transformer_parameters(transformer_id: str) dict[str, Any][source]#
Parameters of a two-winding transformer, as its table holds them.
- Parameters:
transformer_id (str) – Name of the transformer.
- Returns:
- hv_bus and lv_bus (indices), std_type (None without one),
sn_mva, vn_hv_kv, vn_lv_kv, vk_percent, vkr_percent (of one unit), parallel, in_service, its tap changer tap_side (“hv”, “lv” or None), tap_pos, tap_neutral, tap_min, tap_max, tap_step_percent (NaN without one), tap_step_degree (0 without one), tap_changer_type (None without one), and the loading_percent of the latest power flow (NaN without a converged one); an engine that has them also gives, from the same power flow, p_hv_mw and q_hv_mvar, the active and reactive power the transformer draws from its HV bus (negative when it feeds it), which NewFeederStrategy takes as the injections of the MV/LV units of an MV network.
- Return type:
dict
- get_transformer_tap_position(transformer_id: str) float | None[source]#
The tap position of a transformer, None if it has none or the engine does not tell it (the default).
TapChangeStrategy records the positions before and after its tap changes, and GridEnhancementAlgorithm reverts a tap change to the position it started from, which a transformer upgrade made since may have moved; without them it reverts the change by its number of steps.
- Parameters:
transformer_id (str) – Name of the transformer.
- abstractmethod get_transformer_tap_positions(transformer_id: int | str) ndarray[source]#
Get all available tap positions for a given transformer in per unit voltage values.
- Parameters:
transformer_id (Union[int, str]) – The ID of the transformer.
- Returns:
Array of all available tap positions as per unit voltage values, typically sorted from lowest to highest.
- Return type:
np.ndarray
- abstractmethod get_transformer_type(transformer_id: str) str[source]#
Abstract method for retrieving the type of a specified transformer.
- Parameters:
transformer_id (str) – The ID of the transformer.
- Returns:
The type of the transformer.
- Return type:
str
- get_transformer_type_parameters(transformer_type: str) dict[str, Any][source]#
Rating and impedance of a transformer type: sn_mva, vn_hv_kv, vn_lv_kv, vk_percent, vkr_percent.
- Parameters:
transformer_type (str) – The type.
- get_transformers_info() DataFrame[source]#
Type (std_type) and number of units in parallel (parallel) of the transformers, indexed by name. An engine that does not give it raises NotImplementedError: a run with a cost model then charges each transformer upgrade from the state of the transformer before the action, instead of its state at the start of the run.
- abstractmethod get_voltage_magnitude_range(component_id: int) dict[str, float][source]#
Get the minimum and maximum voltage magnitudes in a specific network component.
- Parameters:
component_id (int) – The ID of the component to analyze.
- Returns:
Dictionary containing ‘min’ and ‘max’ voltage magnitude values in per unit.
- Return type:
Dict[str, float]
- group_violations_by_component(violations: list[ConstraintViolation]) dict[int, list[ConstraintViolation]][source]#
Group violations by connected components from the network partition.
This method uses the network partition information from the power flow engine to group voltage violations by their respective galvanically connected components. Each component typically has one main transformer, making this grouping ideal for applying tap changes effectively.
- Parameters:
violations (List[ConstraintViolation]) – List of constraint violations to group.
- Returns:
Dictionary mapping component IDs to lists of violations in that component.
- Return type:
Dict[int, List[ConstraintViolation]]
- abstractmethod load_network(source: str | dict) None[source]#
Load a network from file or dictionary.
- Parameters:
source (Union[str, Dict]) – Path to network file (.json, .p) or network dictionary.
- open_line(line_id: str, bus: int) None[source]#
Open a line by an open switch at one of its ends, as a normally-open point: the line stays in place, carrying no current.
- Parameters:
line_id (str) – Name of the line.
bus (int) – Index of the end bus of the line the switch is at.
- abstractmethod partition_network() dict[int, Any][source]#
Partition the network into galvanically connected components.
This method identifies separate electrical areas in the network that are not connected to each other by power lines or other conducting elements, but can be connected by transformers.
- Returns:
Dictionary mapping component IDs to lists of elements (buses, lines, etc.) in each connected component.
- Return type:
Dict[int, Any]
- plot_network_violations(violations: list[ConstraintViolation] | None = None, show_ids: bool = False, enhancement_results: dict[str, Any] | None = None, save_path: str | Path | None = None, filename: str | None = None, rc_params: dict[str, Any] | None = None) None[source]#
Plot the network topology with violation and action overlays.
This method intentionally stays generic and delegates all rendering logic to gridforge.utils.plot.plot_network_violations.
- Parameters:
violations (Optional[List[ConstraintViolation]], optional) – Optional explicit list of violations. If None, use self.constraints.violations.
show_ids (bool, optional) – Show IDs for buses, lines, and transformers. Defaults to False.
enhancement_results (Optional[Dict[str, Any]], optional) – Results produced by GridEnhancementAlgorithm.run() used to highlight modified elements.
save_path (Optional[Union[str, Path]], optional) – Path to save the plot.
filename (Optional[str], optional) – Filename for the saved plot.
rc_params (Optional[Dict[str, Any]], optional) – Optional style overrides passed to plotting utilities.
- restore_line(line_id: int | str, saved: Any) None[source]#
Give a line back what it was when save_line saved it.
- Parameters:
line_id (int | str) – The line.
saved (Any) – What save_line returned for that line.
- restore_solution(saved: Any) None[source]#
Put back the solution that save_solution saved, as the solution of the latest power flow: a network given back the state it was solved in then is solved again by it, exactly. The same saved solution can be put back several times.
- Parameters:
saved (Any) – What save_solution returned.
- restore_transformer(transformer_id: int | str, saved: Any) None[source]#
Give a transformer back what it was when save_transformer saved it.
- Parameters:
transformer_id (int | str) – The transformer.
saved (Any) – What save_transformer returned for that transformer.
- abstractmethod run_power_flow(warm_start: bool = False) dict[str, Any][source]#
Run power flow calculation on the current network.
- Parameters:
warm_start (bool, optional) – If True, use previous solution as initial guess. Defaults to False. An engine may refuse a requested warm start and solve from a flat start instead, when there is no previous solution to start from, or in the other cases its implementation documents (the pandapower engine refuses one when an angle that a transformer or an external grid applies has changed since the previous solution, or when the warm start fails before any controller has acted). The result of a refused warm start is that of a cold run.
- Returns:
Dictionary with power flow results and statistics.
- Return type:
Dict[str, Any]
- Raises:
PowerFlowNotConverged – If the solver does not converge. Implementations must raise rather than return a result flagged as not converged, and must leave latest_results[“converged”] False so that the results of an earlier run are never mistaken for the current state. Of the engines shipped with gridforge, only PandaPowerEngine does so for now: the OpenDSS and Roseau engines return converged=False in their results, and the GridLab-D engine always reports convergence.
- save_line(line_id: int | str) Any[source]#
Save what a line is (its type, conductors and every parameter the engine holds for it), for restore_line to give it back exactly.
The line strategies save a line before a step that must leave it within its loading limit, to undo the step if the power flow that follows shows it over that limit (see “Steps Checked After the Power Flow” in the methodology). Engines that cannot raise NotImplementedError, the default: the line strategies then take those steps unchecked, and never take a conductor back.
- Parameters:
line_id (int | str) – The line.
- Returns:
What restore_line takes, for this engine only.
- Return type:
Any
- abstractmethod save_network(target: str) None[source]#
Save the current network to a file.
- Parameters:
target (str) – Path where to save the network (.json, .p).
- save_solution() Any[source]#
Save the solution of the latest power flow (its results, and what the engine keeps of it: the starting point of a warm start, the Jacobian), for restore_solution to put it back exactly.
A strategy saves it before steps it checks with the power flow that follows them, so that undoing them leaves the results as they were, bit for bit, with no power flow (see “Steps Checked After the Power Flow” in the methodology). Engines that cannot raise NotImplementedError, the default: the strategies then take those steps unchecked.
- Returns:
What restore_solution takes, for this engine only.
- Return type:
Any
- save_transformer(transformer_id: int | str) Any[source]#
Save what a transformer is (its type, units and every parameter the engine holds for it), for restore_transformer to give it back exactly.
The transformer upgrade saves a transformer before a type change sized to carry it, to undo the change if the power flow that follows shows it over its loading limit. Engines that cannot raise NotImplementedError, the default: the strategy then takes those type changes unchecked.
- Parameters:
transformer_id (int | str) – The transformer.
- Returns:
What restore_transformer takes, for this engine only.
- Return type:
Any
- set_config(new_config: dict[str, Any]) None[source]#
Set a new configuration dictionary and update dependent attributes.
- Parameters:
new_config (Dict[str, Any]) – New configuration dictionary.
- set_line_parallel(line_id: int | str, parallel: int) int[source]#
Set the number of parallel conductors of a line, fewer than it has or more.
A thermal upgrade with prices uses it to replace the conductors it has laid on a line by fewer conductors of a larger type (see “Thermal Sizing” in the methodology). Engines that cannot set it raise NotImplementedError, the default: the line strategies then never take a conductor back, and choose as they did before this operation existed.
- Parameters:
line_id (int | str) – The line.
parallel (int) – Its number of conductors, 1 or more.
- Returns:
The number of conductors of the line.
- Return type:
int
- set_transformer_parallel(transformer_id: str, parallel: int) int[source]#
Set the number of parallel units of a transformer, fewer than it has or more.
NewSubstationStrategy uses it to take back the units the run has added to the unit in place of an LV network before it places a new one (#80, step 6c). Engines that cannot set it raise NotImplementedError, the default: a unit given units in parallel is then not taken back at all, neither its units nor its type (one whose type alone has changed is).
- Parameters:
transformer_id (str) – Name of the transformer.
parallel (int) – Its number of units, 1 or more.
- Returns:
The number of units of the transformer.
- Return type:
int
- split_line(line_id: str, fraction: float) int[source]#
Put a new bus inside a line, at fraction of its length from its from_bus: the line then runs from its from_bus to the new bus, and a new line, of the same type, conductors and parameters, from the new bus to its to_bus. Their lengths and routes are those of the line split at fraction. Nothing is changed electrically but the shunt capacitance being lumped at three buses rather than two.
- Parameters:
line_id (str) – Name of the line.
fraction (float) – Where the new bus is, strictly between 0 and 1.
- Returns:
Index of the new bus.
- Return type:
int
- unresolved_power_mva() float | None[source]#
The largest power mismatch, in MVA, that the last run of the engine left at a bus: the power that its solution does not resolve.
GridEnhancementAlgorithm takes two costs that differ by less than the price of flexibility on the largest such power of its run for equal. None (the default) if the engine does not tell: the costs are then compared exactly.
- update_config(updates: dict[str, Any]) None[source]#
Partially update the configuration dictionary and dependent attributes.
- Parameters:
updates (Dict[str, Any]) – Key-value pairs to update in the configuration.
- exception gridforge.core.power_flow.PowerFlowNotConverged[source]#
Bases:
RuntimeErrorRaised by PowerFlowEngine.run_power_flow when the solver does not converge.
Engines translate their own non-convergence error into this exception, so that callers such as GridEnhancementAlgorithm can handle a diverging power flow without depending on a specific engine library.
- gridforge.core.power_flow.type_in_place(element_type: Any) str | None[source]#
The type of a line or a transformer as the network gives it, None for one that has no type: a std_type of None, NaN or ‘’ (pandapower writes NaN or ‘’ for an element created from its parameters, depending on the elements already in the table). The price of a conductor or a unit added to such an element is that under the key None of CostModel.unit_costs.
A name absent from the standard types is kept: an element added in parallel is charged at its price.
Enhancement strategies for grid constraint management.
- class gridforge.core.strategy.EnhancementStrategy[source]#
Bases:
ABCAbstract base class for all grid enhancement strategies.
This class defines the interface that all specific enhancement strategies (e.g., tap changing, line upgrades) must implement. It ensures a consistent way to apply strategies, calculate costs, and integrate with the main enhancement algorithm.
- logs#
Log messages generated while applying the strategy. Reset by subclasses at the start of each apply_to_group call.
- Type:
List[str]
- cost_model#
The prices a strategy may choose between its own options with, such as a larger type or a unit in parallel. GridEnhancementAlgorithm sets it to its own cost model for the time of each run, None in a run without one, and gives the strategy back its own value when the run ends, however it ends. None otherwise: a strategy used on its own chooses without prices unless it is given one.
- Type:
Optional[CostModel]
- line_origins#
The type and number of conductors of each line as the run started, from which the run charges a line upgrade (see LineUpgradeStrategy.calculate_cost). The algorithm lends a copy, complete from the start of the run for the lines in place, to which it adds the lines the actions applied create, charged from nothing, (None, 0), or from the line they were split from, and from which it drops those of an action it undoes (see GridEnhancementAlgorithm._follow_created_elements). The copy can be copied and pickled with the strategy; a copy keeps the states it had. GridEnhancementAlgorithm sets it for the time of each run with a cost model, as it does cost_model, for a strategy to price its options as the run will charge them. None otherwise: a line is then priced from its state before the action.
- Type:
Optional[Mapping[str, Tuple[Any, int]]]
- transformer_origins#
The type and number of units of each transformer as the run started, by name, from which the run charges a transformer upgrade (see TransformerUpgradeStrategy.calculate_cost). Lent as line_origins is, for the time of each run with a cost model, with the units of new substations charged from nothing, (None, 0). None otherwise: a transformer is then priced from its state before the action.
- Type:
Optional[Mapping[str, Tuple[Any, int]]]
- initial_power#
The active power (MW) of each load and static generator as the run started, by type (“load”, “sgen”) and index in the table of the engine, as get_flexibility_data gives it, from which the limits of flexibility count (see FlexibilityStrategy). GridEnhancementAlgorithm lends a copy for the time of each run, as it does cost_model, so that the limits hold across every call of the run, whatever the calls before it took off, and are those of the network the run is on. None otherwise: a strategy used on its own counts from the powers at each call, so that a caller calling it several times on one network must set the powers here for its limits to hold across the calls (see FlexibilityStrategy).
- Type:
Optional[Mapping[Tuple[str, Any], float]]
- lines_at_start#
The type (None for a line without one) and number of conductors of each line as the run started, by name. GridEnhancementAlgorithm lends a copy for the time of each run, with a cost model or without, as it does initial_power: what a strategy that takes the line upgrades of the run back takes them back to (see NewSubstationStrategy). Unlike line_origins, it does not follow the lines the run creates. None otherwise.
- Type:
Optional[Mapping[str, Tuple[Any, int]]]
- tap_positions_at_start#
The tap position of each transformer as the run started, by name, lent as lines_at_start is: what NoLoadTapStrategy charges a unit from (#80, step 6e). None otherwise.
- Type:
Optional[Mapping[str, Optional[float]]]
- may_leave_residuals#
Whether a violation that the call under way leaves can still be taken up by a later turn of the run: True when a cheaper strategy of the same chain has acted in this turn, so that the violations given are what it left, and the run has a pass after this one. GridEnhancementAlgorithm sets it for the time of each call of a chain (#80, step 6d; see NewSubstationStrategy.min_excess_pu). None otherwise.
- Type:
Optional[bool]
- transformers_at_start#
The type and number of units of each transformer as the run started, by name, lent as lines_at_start is (step 6c of #80).
- Type:
Optional[Mapping[str, Tuple[Any, int]]]
- abstractmethod applicable_constraints() set[str][source]#
Get the set of constraint types this strategy can address.
- Returns:
A set of ConstraintType values (as strings or enums) that this strategy can resolve.
- Return type:
Set[str]
- applicable_levels() set[str] | None[source]#
The levels of network (“mv”, “lv”) whose violations this strategy addresses, None for both (the default).
It matters only in a priority order that names levels (see EnhancementStrategyRegistry): the strategy is registered for the types of applicable_constraints at these levels alone. In an order that gives a type one turn whatever the level, as the default order does, the strategy gets every violation of the type, as before levels were told.
- Returns:
The levels, or None for both.
- Return type:
Optional[Set[str]]
- abstractmethod apply_to_group(violations: list[ConstraintViolation], pf_engine: PowerFlowEngine) dict[str, Any] | None[source]#
Apply the strategy to address a group of violations of the same type.
- Parameters:
violations (List[ConstraintViolation]) – The constraint violations to address.
pf_engine (PowerFlowEngine) – The power flow engine to use for network analysis and modification.
- Returns:
A dictionary describing the action taken if successful, or None if no action could be applied.
- Return type:
Optional[Dict[str, Any]]
- abstractmethod calculate_cost(action: dict[str, Any], cost_model: CostModel) float[source]#
Calculate the cost of the applied action.
- Parameters:
action (Dict[str, Any]) – The action dictionary returned by apply_to_group.
cost_model (CostModel) – The cost model to use for calculation.
- Returns:
The calculated cost of the action.
- Return type:
float
- abstract property cost_level: int#
Get the relative cost level of this strategy.
Lower values indicate less expensive strategies that should be tried first.
- Returns:
The cost level.
- Return type:
int
- abstract property name: str#
Get the name of the strategy.
- Returns:
The name of the strategy.
- Return type:
str
- possible_unit_costs(pf_engine: PowerFlowEngine) set[tuple[str, ...]][source]#
List the prices this strategy may need on this network, depending on what the run turns out to do, like that of a conductor added in parallel to a line of a type outside the configured ones.
A run starts without them, with a warning: it stops with MissingUnitCostError if an action needs one, the network being left as it was before that action.
- Parameters:
pf_engine (PowerFlowEngine) – The power flow engine.
- Returns:
- Keys of CostModel.unit_costs, as for
required_unit_costs.
- Return type:
Set[Tuple[str, …]]
- required_unit_costs(pf_engine: PowerFlowEngine) set[tuple[str, ...]][source]#
List the prices this strategy needs on this network, to check them before a run.
These are the prices the strategy needs whatever the run does: a run does not start without them. The prices it may need, depending on what the run turns out to do, are listed by possible_unit_costs.
- Parameters:
pf_engine (PowerFlowEngine) – The power flow engine.
- Returns:
- Keys of CostModel.unit_costs, like (“tap_change”,) or
(“line_upgrade”, “NAYY 4x120 SE”).
- Return type:
Set[Tuple[str, …]]
- abstract property stage: str#
Get the stage of the strategy (e.g., ‘operation’, ‘planning’).
- Returns:
The stage of the strategy.
- Return type:
str
- gridforge.core.strategy.note_origins(upgrades: Iterable[Any] | None, origins: Mapping[str, tuple[Any, int]] | None, element_id: str, origin_count: str) None[source]#
Give each upgrade of an action the state of its element at the start of the run, from origins (name -> type, number of elements in parallel), as origin_type and origin_count, unless it has one: the state the upgrade is charged from, (None, 0) for an element the run has created from nothing (see LineUpgradeStrategy.calculate_cost and TransformerUpgradeStrategy.calculate_cost). element_id is the key of the name of the element in an upgrade.