Strategies#
- class gridforge.strategies.flexibility.FlexibilityStrategy(max_iterations: int = 500, n_activation: int = 1, min_achievable_relief_pct: float = 5.0, min_asset_relief_pct: float = 0.01, min_round_relief_pct: float = 5.0)[source]#
Bases:
EnhancementStrategyStrategy for Active Power Flexibility Management.
Manages active power flexibility to securely resolve operational constraints using a deterministic, sensitivity-driven heuristic algorithm.
- max_iterations#
Maximum number of iterations for the flexibility management loop.
- Type:
int
- n_activation#
Number of nodes to activate flexibility on per iteration.
- Type:
int
- tabu_list#
The assets set aside for the rest of the call, as their steps went round in a cycle (see apply_to_group), by type and index in the table of the engine.
- Type:
Set[Tuple[str, Any]]
- unrelievable#
The violations of the last call that no asset could relieve when last examined, by constraint type and element, with their levels: the lowest excess over their limits at which the call gave up on them, beyond which no step of the call takes them (see apply_to_group).
- Type:
Dict[Tuple[Any, Any], float]
- history#
The actions of the last call, each with the iteration it was taken at, the violations of the network it was taken on (“violations”), those the call acted on, by constraint type and element, with the excess it acted on (“excesses”, see apply_to_group), its target among them, as such a key and excess (“target”), the sum of the _relative_excess of the violations it acted on (“relative_excess”), and what every violation of the network exceeded its limit by, by key (“measured”), these four in the state the action was taken from. It is reset at the start of each apply_to_group call, so that after a run it holds the last call only.
- Type:
List[Dict[str, Any]]
- logs#
A list of log messages generated during the application of the strategy. It is reset at the start of each apply_to_group call, so that after a run it holds the messages of the last call only.
- Type:
List[str]
- initial_power#
The power of the flexible assets that their limits count from, by type and index in the table of the engine: an asset can be taken down to 1 - max_flex_pct / 100 of it, whatever the calls before took off. GridEnhancementAlgorithm lends the powers as its run started, for the time of the run. None otherwise (the default): the limits then count from the powers at each call of apply_to_group, so that a strategy used on its own on another network, or on loads changed since its last call, takes their limits from them. An asset that it does not list counts from its power at the call.
The limits hold within a call, or a run, not across them. A strategy called again on its own on a network that its first call shed can shed up to max_flex_pct of what that call left: a 112 kW load at 30 % ends 45 % under its first power after two calls. A caller that calls the strategy several times on one network must give it the powers to count from here, as {(“load”, 0): 0.112}, and set it back to None for another network. Likewise, a run counts from the powers of the engine as it starts: a second run on an engine that the first left shed sheds again from there (45 % in all for that load). A copy or a pickle of the strategy made during a run keeps the powers of that run, and counts from them if it is then used on its own.
- Type:
Optional[Mapping[Tuple[str, Any], float]]
- applicable_constraints() set[ConstraintType][source]#
Get the set of applicable constraint types.
- Returns:
The set of applicable constraint types.
- Return type:
Set[ConstraintType]
- apply_to_group(violations: list[ConstraintViolation], pf_engine: PowerFlowEngine) dict[str, Any] | None[source]#
Apply the flexibility strategy to a group of violations.
This method iteratively selects the most severe violation, identifies the most effective flexible asset to mitigate it using sensitivity analysis, and applies a corrective action.
The call acts on the violations of the group it is given, and on what its own steps add to the others: a violation that was not there as the call started, whole, and of one that was, what it exceeds its limit by beyond what it did then, as a violation of that excess, which a step aims to take off just inside (the starting excess less _SIZING_MARGIN of the limit). The rest of a violation that was there, outside the group, is left to the strategies of its type, which the run applies at its turn, in the priority order of the registry and with its own choice between them: the call does not resolve it, nor take its relief for progress. The comparison has no tolerance, as the cycle rule below. Before #63 the call acted on every violation of the network after its first step: given an overloaded line, it went on to shed loads for an under-voltage elsewhere once the line was resolved.
The steps are aimed at the target, but a step can relieve less than the sensitivities estimate, or bring back a violation that another step relieved. The call has gone round in a cycle when it comes back to a state no better than one it has been in, every violation of that state still there and none less than it was, and every violation it has resolved since then is one it had met at or before that state: the steps since that state have brought none of its violations down, and those they resolved are coming round too. Of the latest such state, the first asset acted on from it (the one ranked first) is set aside for the rest of the call (tabu_list); if all those are set aside already, the first one that is not of the latest such state before it. Each cycle thus sets aside a new asset, as long as one is left. A step that relieves a violation, however little, is progress, not a cycle: the comparison has no tolerance, so that a violation that a step reduces by less than a rounding (the former rule compared violations to 4 decimals) is not mistaken for one that it leaves as it was.
The violations of these states are those the call acts on, with the excess it acts on. A violation that the call meets for the first time on the way and resolves gives it one more round: relieving the target can bring up a violation, or worsen one outside the group the call was given, and relieving that one bring the target back larger, where the next round can resolve both. When one of them comes back again, no smaller than the time before, the violation resolved in between has been met before, and it is a cycle.
Two violations that bring each other back, each a little smaller than the time before, are progress by this rule alone: the call would go on alternating between them until one comes back no smaller, which can take until an asset it uses has no margin left. min_round_relief_pct stops such a see-saw. A round ends at a state at which a violation that was met at or before an earlier state, and was not in it, has come back and been resolved again, every violation of that earlier state still there: the latest such earlier state is the first state of the round (the windows of the cycle rule that have resolved something since their state). The reach of a round is the largest excess of each violation over its states, from its first to the last before the state it ends at, so that it holds every violation the see-saw passes through, the group’s included, at its peak. A round is judged against the round that ended at its first state: it is slow if none of the violations of that round’s reach is relieved by more than min_round_relief_pct of what it reached there (reach now >= reach then x (1 - min_round_relief_pct / 100) for each of them); a violation the round no longer reaches is relieved. A round is judged only against a round that ended exactly at its first state: the first round of a see-saw has nothing to be judged against, nor has a round whose first state is not the end of a round, so that a window that grows from the same first state, one state longer at each step, is never judged. A slow round that follows a slow round, the latest judged before it, is taken for a cycle and sets an asset aside: of the steps of the two rounds, latest first, those for a violation outside the group of the call come first, as they are what brings back the violation of the group that the other steps relieve, then the others; the first asset of them not set aside yet, if another asset could act on the violation its step was relieving (_relievable_without: the test of the candidates of a target, on the sensitivities of the state now, without a power flow). If none could, nothing is set aside and the see-saw goes on as without a threshold: setting the asset aside would leave the violation, or the run to pay a reinforcement that going on avoids. After an asset is set aside, by this rule or the cycle rule, the rounds whose round before started before it are not judged, and those judged before it no longer count: two new slow rounds, with the assets left, are needed for the next asset. One slow round is not enough: a see-saw that makes steady progress can have one, when an asset it uses runs out and another takes its place. Judging a round again after a step undone gives the same result. The steps of the rounds are kept, as those of a cycle, and the call goes on with the assets left, so that what it returns is built as before. Steps that bring no violation back end no round, so that a call that relieves its target a little at each step, an asset after another, is never cut, whatever the threshold. The default is 5 %; at 0 no round is judged, and the call is the same to the bit as before #65. Before the rework of #65 a round was judged on the violations of its first state only, so that a see-saw resolving the group’s violation was taken for slow by the rounds of the other one, and the asset set aside was the first acted on from that state, which could be the reliever of the group’s violation. In a small random feeder, shedding a load for a line and curtailing a generator for the over-voltage that it brings up, each round relieving about 4.4 % of the reach, goes on for 74 steps for 421.05 EUR at 0; from 4.5 % the generator is set aside after two slow rounds and another resolves both in 10 steps for 187.01 EUR (see “Active Power Flexibility Management” in the methodology, which also says what the rule does not guarantee).
A violation that no asset can relieve, by the filters of _evaluate_assets and min_achievable_relief_pct, does not stop the call: it is set aside (unrelievable), and the step is taken on the most severe violation that an asset can relieve. Its level is what it exceeds its limit by when it is set aside, or, if the call has given up on it before, the lowest of these: it is kept for the rest of the call, also while the violation is taken up again, when the steps for other targets can take it up to its level but not beyond. A step after which a violation given up on exceeds its level, as the power flow after the step measures it, is undone: its assets get back their powers (reactive power included), and it leaves no trace in history or in the action returned. A step on one asset leaves that asset out of the candidates of that target for the rest of the call. A step on several assets is taken again one asset at a time, in the order they were ranked, each by what it took in the step and each measured by a power flow: an asset whose step, after those kept before it, takes a violation given up on beyond its level is undone and left out for that target, and the others are kept. The harm is measured, not predicted: the sensitivities need not show it. The call thus never leaves a violation it gave up on above the lowest level at which it gave up on it. Only steps undone cost power flows: 2 for a step on one asset, 2 + k for a step on k assets, and one more for each of them undone again. Each asset undone leaves out one more pair of a target and an asset, of which there are finitely many, and each asset kept is a step kept, so that undoing does not keep the call from ending.
After a step undone, the network has the powers of the state before it, and the call goes on from the violations it measured then. Solved again, the network gives them to the precision of the power flow, not bit for bit (up to 5.0e-12 % of loading on 700 random feeders); and a load or generator whose scaling is not 1 gets its powers back to a rounding (1.6e-16 relative), as apply_flexibility_action divides them by the scaling, which the revert of operation actions by the algorithm shares.
Of the filters, the margins and the assets left out only shrink during a call, but the share of a violation that the assets must relieve together follows the violation, and a sensitivity follows the state of the network: a step kept for another violation can bring one set aside within reach. Those set aside are therefore examined again, most severe first, once no other violation can be relieved, if a step has been kept since they were last examined (a step undone leaves the network as it was). A violation is thus examined again at most once per step kept or undoing of the steps that brought a violation about (below), and all of them at most (number set aside) x (steps kept + such undoings) times. A violation set aside stays among those the cycle rule compares: its relief by the steps for others is progress of the call. Before, the call stopped at the first target that no asset could relieve, whatever the other violations it could have relieved.
A violation that a call brings about and cannot relieve is left at its level, for the strategies of its type, which the run applies in the same pass: at their turn if its type comes after that of the group in the priority order, at their turn given again otherwise (see GridEnhancementAlgorithm; until #66, in the next pass). If an asset that relieves it has been left out of its candidates, because its step for it took a violation given up on beyond its level or by an earlier undoing (below), the call can undo the steps that brought it about instead (_undo_what_brought_about); the same holds for a violation that its steps worsened, of the group or not: the steps since the latest state in which the call acted on the least of it, all at once. It does so only if the network is more severe in total now than in that state, by the sum of the _relative_excess of all its violations, the measure the algorithm rates states by, a voltage against the width of its band and a loading against its limit: what the steps brought about or added outweighs what they relieved, outside the group as in it (a violation outside the group is weighed, never worked on beyond what the steps added to it). A step that resolves a 30 % overload of the group and brings up a 2 % one is kept, and the 2 % set aside; so is a step that resolves an under-voltage of 0.05 pu (0.5 of a band of 0.1 pu) and brings up a 6 % overload. It does not undo them either if a violation given up on exceeded its limit by more than its level in that state, which undoing brings back, as a level lowered since can be: the call tells it from what it measured then, without a power flow, and never breaks the rule above. Of the first of the steps undone, an asset on its own is left out of the candidates of its target; the assets of a step on several are taken again one at a time, in the order they were ranked, and one after which the call acts on more of the violation than in that state (beyond _SIZING_MARGIN of its limit, for one that was there: every asset moves every loading a little), or after which a violation given up on is beyond its level, is undone and left out, the last one if none is. The call goes on from there. It costs a power flow for the undoing, one for each asset of a step on several taken again, one for each of them undone again, and one more if none of them does harm. The comparison is of totals, measured in the state the steps were taken from: the call can end with more violations than if it had set the violation aside, or with one of them larger, when the total is smaller. The targets of the steps are still ranked by _severity, against the limit. Until #66 the call left both: given up on at 10 %, a line was taken up again at 8.9 %, and the step that took it to 8.45 % brought about an overload of 21.5 %, which only an asset that worsens the line relieved; the call now undoes that step (30 % in all against 8.9 %) and leaves the line at 8.9 %.
The call ends when the violations it acts on are resolved, when none of those left can be relieved, when the steps no longer change a power, or after max_iterations: each iteration of the loop, an undoing included, counts towards it. Without undoings of the steps that brought a violation about, it ends before max_iterations whenever the margins run out first: every step that goes on takes power off an asset and puts none back, and takes at least the smaller of 1e-4 MW (the margin under which an asset is not a candidate) and what the target needs to be brought just inside its limit (_SIZING_MARGIN of it), which is never zero. An undoing gives power back: it takes back at least one step kept, and leaves out, for the target of the first step it takes back, at least one asset of that step, if it was not left out already (a later step for the same target, undone by the level rule, can have left it out before). No bound tighter than max_iterations is shown for the undoings: a step on the same target and asset taken before the one left out, still in history, can be the first step of a later undoing. A call that resolves part of its group returns its steps, like one that resolves it all: total_violations_addressed counts the violations of the group resolved, and the algorithm gives what is left of the group to the next strategy of the chain.
- Parameters:
violations (List[ConstraintViolation]) – The list of violations to address.
pf_engine (PowerFlowEngine) – The power flow engine.
- Returns:
A dictionary describing the actions taken, or None if no action was applied. Its total_violations_addressed is the number of violations of the group that the call resolved.
- Return type:
Optional[Dict[str, Any]]
- calculate_cost(action: dict[str, Any], cost_model: CostModel) float[source]#
Calculate the cost of the flexibility action.
- Parameters:
action (Dict[str, Any]) – The action dictionary.
cost_model (CostModel) – The cost model.
- Returns:
The cost of the action.
- Return type:
float
- property cost_level: int#
Get the cost level of the strategy.
- Returns:
The cost level (2 for flexibility).
- Return type:
int
- property min_achievable_relief_pct: float#
Share, in percent, of the target violation that the candidate assets must be able to relieve together for flexibility to be used. Between 0 and 100, checked when it is set; 5 by default.
- property min_asset_relief_pct: float#
Share, in percent, of the target violation under which the relief that one asset can give is negligible and the asset is left out. Between 0 and 100, checked when it is set; 0.01 by default.
- property min_round_relief_pct: float#
Share, in percent, of the reach of a round of a see-saw that the next round must relieve of one of its violations to be progress: two rounds in a row that do not are a cycle (see apply_to_group). Between 0 and 100, checked when it is set; 5 by default, 0 for the exact cycle rule alone.
- property name: str#
Get the name of the strategy.
- Returns:
The name of the strategy.
- Return type:
str
- required_unit_costs(pf_engine: PowerFlowEngine) set[tuple[str, ...]][source]#
List the prices of the flexibility available on this network.
A study that only has flexible loads has no use for a curtailment price, and the other way round.
- Parameters:
pf_engine (PowerFlowEngine) – The power flow engine.
- Returns:
The keys of the prices in CostModel.unit_costs.
- Return type:
Set[Tuple[str, …]]
- property stage: str#
Get the stage of the strategy.
- Returns:
The stage (“operation”).
- Return type:
str
- class gridforge.strategies.line_upgrade.LineUpgradeStrategy(line_types: dict[str, dict[str, list[str]]], max_iterations: int = 100, min_voltage_sensitivity: float = 0.0001, restrict_to_violation_zone: bool = False, one_upgrade_per_zone: bool = False, max_parallel_conductors: int | None | Mapping[str, int | None] = 3, uncapped_lines: Collection[str] | Callable[[PowerFlowEngine], Collection[str]] | None = None, extend_section_changes: str | None = None)[source]#
Bases:
EnhancementStrategyStrategy to upgrade lines to address line loading and voltage violations.
This strategy identifies overloaded lines or lines contributing to voltage violations and upgrades them to a type with higher capacity or lower impedance.
- line_types_dict#
Dictionary of available line types.
- Type:
Dict[str, Dict[str, List[str]]]
- line_types#
Combined list of all available line types.
- Type:
List[str]
- max_iterations#
Maximum number of iterations for the upgrade loop.
- Type:
int
- min_voltage_sensitivity#
Minimum voltage change (p.u.) that the next upgrade step of a line must be predicted to bring to a violated bus for the step to be considered. See __init__.
- Type:
float
- max_parallel_conductors#
Most conductors in parallel the strategy leaves a line with, None for no cap. See __init__.
- Type:
Optional[int]
- lines_at_cap_of_the_run#
The lines the strategy has found at the cap during a run, in any of the actions the run tried, with the reason (“loading” or “voltage”) and the violated elements they were found at the cap for: the line itself for its loading, the violated buses one more conductor would have helped enough for a voltage violation. GridEnhancementAlgorithm lends a new mapping for the time of each run, shared by its strategies, from which lines_at_the_cap reports them. None otherwise.
- Type:
Optional[Dict[str, Tuple[str, FrozenSet[str]]]]
- logs#
List of log messages generated during execution.
- Type:
List[str]
- applicable_constraints() set[ConstraintType][source]#
Get the set of applicable constraint types.
- Returns:
The set of applicable constraint types.
- Return type:
Set[ConstraintType]
- apply_to_group(violations: list[ConstraintViolation], pf_engine: PowerFlowEngine) dict[str, Any] | None[source]#
Apply line upgrades to address a group of violations.
This method delegates to specialized methods for handling different types of violations: - Line loading violations are handled by _handle_line_loading_violations - Voltage violations are handled by _handle_voltage_violations
The lines that the action found at the cap on conductors in parallel (max_parallel_conductors) are logged, and listed in the action as lines_at_cap (name -> “loading” or “voltage”) when it has upgrades.
- Parameters:
violations (List[ConstraintViolation]) – List of violations to address.
pf_engine (PowerFlowEngine) – The power flow engine.
- Returns:
A dictionary of upgrade actions if any were performed, otherwise None.
- Return type:
Optional[Dict[str, Any]]
- calculate_cost(action: dict[str, Any], cost_model: CostModel) float[source]#
Calculate the cost of the line upgrade actions.
A line is charged once, for what is laid, however many steps took it there: a line taken from one type to the next and then to a third is charged for the third only, not for the type in between, which is never laid, and a line given a conductor that a type change then takes back (conductors_removed) is charged for the conductors of the new type only. What a line costs, from the state it had at first to the state it is left in, is:
if the type has changed, the line_upgrade price of the final type for every conductor the line had at first, as they are all replaced;
the new_line price of the final type for every conductor added.
The state at first is that of the line when the run started, which GridEnhancementAlgorithm records in the upgrades (origin_type, origin_conductors). The action is then charged the difference between what the line costs after it and what it cost before it, so that a line upgraded by several actions of a run (for its loading, then for its voltage) is charged in all for what the run lays. Without that record, the state at first is the one before the action.
The state of a line before the action is read from its first step, and the state after it from its last: a type change gives the conductors it leaves (conductors) and those it takes back (conductors_removed), so that a line whose first step takes back conductors laid by an earlier action of the run had them all before the action, and one whose last step is a type change is left with the conductors that step gives, fewer than before the action if a step of it took some back. An entry that does not give its conductors is read as leaving the line at least the conductors it had before the action.
- Parameters:
action (Dict[str, Any]) – The action dictionary.
cost_model (CostModel) – The cost model.
- Returns:
The total cost of the upgrades.
- Return type:
float
- cap_of(line_id: str, pf_engine: PowerFlowEngine) int | None[source]#
The most conductors in parallel the strategy leaves the line line_id with: the cap of its level (level_of), None for no cap, or for a line of uncapped_lines. With one cap for every line and no line exempt (an int, or None), that cap, with no engine read. A line whose level cannot be told takes the lowest cap of the levels.
- property cost_level: int#
Get the cost level of the strategy.
- Returns:
The cost level (3 for line upgrades).
- Return type:
int
- level_of(line_id: str, pf_engine: PowerFlowEngine) str | None[source]#
The level of network of the line line_id, “lv” or “mv”, as ConstraintViolation.level takes it: “lv” for a line between buses of 1 kV or less. A line that does not conduct (out of service, opened) takes the level its type is configured at; None if neither tells.
- lines_at_the_cap(violations: list[ConstraintViolation], pf_engine: PowerFlowEngine) dict[str, str][source]#
The lines that the cap on conductors in parallel (max_parallel_conductors) stops the strategy on, for violations on the latest power flow of the engine, by name: “loading” for an overloaded line that has no option within the cap (_thermal_options), “voltage” for a line at the cap whose one more conductor would be worth its works for the voltage violations (_lines_at_cap_for_voltage). Empty without a cap. GridEnhancementAlgorithm counts them in the summary of a run, on the violations it leaves.
In a run, also the lines that an action of the run found at the cap (lines_at_cap_of_the_run), even if the run then undid it, as when it keeps a cheaper state with as many violations: a line found at the cap for its loading that is still overloaded, and one found at the cap for voltage violations of which one is left at a bus that its one more conductor would then have helped enough.
- Parameters:
violations (List[ConstraintViolation]) – The violations, of the latest power flow of pf_engine.
pf_engine (PowerFlowEngine) – The engine.
- Returns:
The reason of each line at the cap, the loading first.
- Return type:
Dict[str, str]
- property name: str#
Get the name of the strategy.
- Returns:
The name of the strategy (“Line Upgrade”).
- Return type:
str
- possible_unit_costs(pf_engine: PowerFlowEngine) set[tuple[str, ...]][source]#
List the price of a new conductor of every line type in place on the network.
A line can be given a parallel conductor of the type it has, whether or not that type is one of the configured ones, and the conductor is charged at the new_line price of that type, or at its line_upgrade price. That of a line that has no type (a std_type of None, NaN or ‘’, like a line created from its parameters) is the price under the key None. Whether a run adds one is not known before it: the run starts without these prices, and stops if it needs a missing one. Only the lines that conduct are listed.
- Parameters:
pf_engine (PowerFlowEngine) – The power flow engine.
- Returns:
The keys of the prices in CostModel.unit_costs.
- Return type:
Set[Tuple[str, …]]
- required_unit_costs(pf_engine: PowerFlowEngine) set[tuple[str, ...]][source]#
List the upgrade price of every configured line type.
- Parameters:
pf_engine (PowerFlowEngine) – The power flow engine.
- Returns:
The keys of the prices in CostModel.unit_costs.
- Return type:
Set[Tuple[str, …]]
- property stage: str#
Get the stage of the strategy.
- Returns:
The stage (“planning”).
- Return type:
str
- gridforge.strategies.line_upgrade.dedicated_lines(pf_engine: PowerFlowEngine) set[str][source]#
The MV lines of the network that lie on a direct feeder: one that leaves a source of the network and serves one customer alone (#80, step 6g), the only lines on which Enedis lays cables in parallel (Enedis-NMO-RES_011E §3.2.3), as LineUpgradeStrategy(uncapped_lines=dedicated_lines) exempts them from the cap on conductors in parallel.
The sources are the buses above 1 kV that feed the network (get_source_buses: an external grid, the LV side of an HV/MV transformer), each with the buses that closed bus-bus switches join it to, its busbar (in GridFlex networks, the external grid’s bus is joined so to the busbar of the HV/MV substation). Without them, the network falls into parts, each hanging from the sources. A part is a direct feeder if it hangs from one busbar alone, has no transformer, and has exactly one bus with a customer (get_customer_buses: an element in service that draws or produces power, whatever its power at the moment, so that the rule depends on the structure of the network alone). Its lines, and those that join it to its source bus, are dedicated: all the segments of a feeder in series, and the cables of a feeder laid twice. A spur off a shared feeder, a line of a feeder that serves several customers or an MV/LV unit, or one between two sources is not, nor one that runs up to a normally open point (get_open_links: a loop run open, whose parts are taken with the open point closed; an engine without the read reports none). Lines that conduct, transformers in service and closed bus-bus switches join the buses.
- Returns:
The names of the dedicated lines; empty if the engine lacks one of the reads it needs.
- Return type:
set[str]
- gridforge.strategies.line_upgrade.section_groups(endpoints: Mapping[str, tuple[str, str]], kinds: Mapping[str, tuple[str, str, str]], stations: Collection[str], customers: Collection[str], reading: str, degree: Mapping[str, int] | None = None) dict[str, tuple[str, ...]][source]#
The sections of a network that a section change is extended over, under reading (“joint” or “branch”, see EXTEND_SECTION_CHANGES): the lines of one type, level and category joined through buses that are not boundaries of their kind.
A bus is a boundary of every kind if it is a substation (stations), of the kinds read “joint” or “branch” if it is an end or a branch (a bus with other than two lines: those of degree, or else of endpoints), and of the kinds read “joint” if it carries a customer (customers).
- Parameters:
endpoints – The end buses of each line that conducts, by name.
kinds – The type, level and category of each line, by name; a line left out is a section of its own.
stations – The buses of substations: of transformers, external grids and closed bus-bus switches.
customers – The buses with a customer.
reading – “joint” or “branch”.
degree – The number of lines at each bus, in service whether or not they conduct (a line opened by a switch makes its bus a branch, as the cable is in place); that of endpoints for a bus left out, or if None.
- Returns:
- The lines of the section of each line of
endpoints, itself included, in the order of endpoints.
- Return type:
Dict[str, Tuple[str, …]]
New MV/LV substations against LV over-voltages and under-voltages (#80).
An LV network whose busbar has no headroom left, because its MV side is high and its tap is up (or low and down), cannot be brought within its limits by its cables: a new MV/LV unit near the generation (or the load) and a split of the network can. The strategy places the units with the placement core (gridforge.strategies.substation_placement) and builds them with the engine’s operations (split_line, add_bus, add_line, add_transformer, open_line).
- class gridforge.strategies.new_substation.CheckedSet(beyond: int, worst: float, beyond_other: int = 0, old_unit_loading: float = nan, new_unit_loadings: tuple[float, ...] = (), lines_over: tuple[str, ...] = ())[source]#
Bases:
EvaluationA power flow of the network with a set of new units, rated as Evaluation, with the loadings the strategy records.
- old_unit_loading#
Loading (%) of the unit in place.
- Type:
float
- new_unit_loadings#
Loading (%) of each new unit, in the order of the set.
- Type:
tuple[float, …]
- lines_over#
LV lines of the network over their loading limit.
- Type:
tuple[str, …]
- gridforge.strategies.new_substation.ENEDIS_NO_LOAD_TAPS = (0.0, 2.5, 5.0)#
Rise of the LV voltage (%) of the no-load taps of Enedis’s current MV/LV units above 400 V (Enedis-NMO-RAC_007E §5.2.1.3).
- gridforge.strategies.new_substation.FIXED_TAP_TOLERANCE = 0.0125#
A unit whose tap changer the power flow does not apply has the ratio of its rated voltages: it gives a rise of new_unit_taps if that ratio is within this much of it, half of Enedis’s step of 2.5 %.
- gridforge.strategies.new_substation.MIN_EXCESS_PU = 0.001#
Least excess (pu) of the worst bus of an LV network beyond the limit for a new unit to be placed in it (NewSubstationStrategy.min_excess_pu, #80, step 6d): 0.4 V on a 400 V network, within the uncertainty of any planning study, and the step the case study’s line ladder judges worth its works (line_upgrade_min_voltage_sensitivity).
- gridforge.strategies.new_substation.MIN_MV_CABLE_KM = 0.01#
a unit next to the MV line.
- Type:
Shortest MV cable from the tee to a new unit
- gridforge.strategies.new_substation.NEW_UNIT_SUFFIX = '_new_substation'#
A new unit is named after the unit whose LV network it was placed in, or after the unit that one descends from, followed by this suffix (and
_2,_3… as the engine makes names unique):<unit>_new_substation. The strategy counts the units it has added to an LV network from these names, so that the count follows the network through the undo of the algorithm, which puts back a copy of the network.
- class gridforge.strategies.new_substation.NewSubstationStrategy(transformer_types: Sequence[str], mv_line_type: str, max_mv_distance_km: float = 0.5, mv_detour_factor: float = 1.0, default_mv_distance_km: float | None = None, new_unit_taps: Sequence[float] = (0.0, 2.5, 5.0), n_checked: int = 3, max_new_substations: int = 3, min_buses: int = 3, take_back_line_upgrades: bool = False, units_per_call: int | None = None, take_back_transformer_upgrades: bool = True, min_excess_pu: float = 0.001, transformer_parallel_units: str | None = None)[source]#
Bases:
EnhancementStrategyResolve LV over-voltages or under-voltages by new MV/LV substations, each teed into a nearby MV line and feeding a part of the LV network split off by opening lines.
For each LV network with violations of the group (group_violations_by_component) that one MV/LV unit feeds, radially, the strategy places new units one at a time (place_units): the candidate buses are ranked by LinDistFlow, with the new unit at each of Enedis’s no-load taps, and a power flow of the network with the units built decides between the first n_checked buses; a pass then moves each new unit to its best bus given the others. Each LV bus is fed by the nearest unit along the cables, and the lines between buses fed by different units are opened by an open switch (split_by_nearest_source).
Of the sets of units placed (one, two… up to max_new_substations less the units the strategy has already added to that network), the one applied is the first that leaves the fewest buses beyond the limit (a bus beyond the other limit counting first): a unit is added only if it resolves a bus. A set is applied only if it leaves fewer buses beyond the limit than there were, and no more beyond the other limit; the violations it leaves, and the loading violations it brings about, go to the other strategies.
A network is fed by the transformers in service whose LV bus it holds. An LV network is left out if its MV side is beyond the MV limits of the engine: a new unit there is at or near the LV limit at no load, and the problem is the MV network’s (it is reported as MV-limited). It is left out as well if it has fewer than min_buses buses, if the strategy has already added max_new_substations units to it, if it is not radial, or if no bus can be connected to the MV network.
New unit. It takes the vector group and the tap changer of the unit in place (add_transformer(…, like=…)). A tap is chosen by the rise of the LV voltage at no load it gives, one of new_unit_taps: the position of that tap changer whose ratio, with the rated voltages of the type built (_reach), is nearest to 1 + rise / 100, if less than half a step away. On the units of the feeder files (tap on the LV side, +2.5 % per position, rated 20/0.4 kV) Enedis’s 0, +2.5 and +5 % are positions 0, 1 and 2; a unit rated 410 V on a 400 V network is 2.5 % up at its neutral, and they are positions -1, 0 and 1. The action records the position, the rise chosen (tap_target_percent) and the rise of the unit as built (tap_percent). A tap changer the power flow does not apply (no side, a step of NaN or 0, no changer type) leaves a new unit at its neutral position, with the ratio of its rated voltages. A network whose unit has a tap changer of another type than a ratio one, or one that shifts the phase, is left out.
Its type is sized by size_unit, among the types that give the rise of its tap, on what the loads, storage units, static generators and generators of the part it feeds draw and produce (get_buses_info; a load of negative power produces), in Enedis’s winter and summer situations; the largest when none passes, its overload then left to TransformerUpgradeStrategy (undersized in the action). The ranking cannot know the part of a bus before it splits the network, and ranks every bus with one type: the one sized for the whole LV network (the most a new unit can take). Each power flow is run with the units sized for their parts, so that the units checked, and the set applied, are those the ranking’s choice gives once sized.
MV side. LinDistFlow takes the MV side of every new unit at the voltage of the MV bus of the unit in place, as the placement core takes one MV voltage per tap; the power flow then has the voltage at the tee. The unit is teed into the MV line of the MV network of the unit in place nearest to its LV bus, at the nearest point of its route, or of the straight line between its ends for a line without a route (whose tee then has no coordinates and the cable no route). The cable runs from the tee to a new MV bus at the LV bus, mv_detour_factor times the straight distance long, at least MIN_MV_CABLE_KM; a bus whose cable would be longer than max_mv_distance_km is not a candidate. A tee at an end of a line connects to its end bus. Without geodata (an LV bus without coordinates, or an MV network without routes or coordinates), a bus is not a candidate unless default_mv_distance_km is set: its cable then runs that distance (times the detour factor) from the MV bus of the unit in place. That length is not bounded by max_mv_distance_km: it is a setting the caller chose, not a distance found.
Counting. New units are named after the unit in place (NEW_UNIT_SUFFIX), and a network split off by a new unit is counted with the network it was split from.
Undo. Each power flow of the placement is run on the network with the units built, which is then put back from a copy taken before; the set applied is built again. The algorithm undoes the action by its own copy of the network.
The strategy needs the engine operations of a new substation and get_buses_info, get_transformer_parameters and get_transformer_type_parameters: on an engine without them, it takes no action.
- transformer_types#
The types a new unit may be.
- Type:
List[str]
- mv_line_type#
The type of the MV cable of a new unit.
- Type:
str
- max_mv_distance_km#
Longest MV cable of a new unit.
- Type:
float
- mv_detour_factor#
Length of an MV cable per km of straight distance.
- Type:
float
- default_mv_distance_km#
Length of the MV cable of a new unit without geodata, None to place none there; not bounded by max_mv_distance_km.
- Type:
Optional[float]
- new_unit_taps#
Rises of the LV voltage (%) the tap of a new unit may take.
- Type:
Tuple[float, …]
- n_checked#
Buses of the ranking a power flow decides between.
- Type:
int
- max_new_substations#
Most new units the strategy adds to an LV network over a run.
- Type:
int
- min_buses#
Fewest buses of an LV network to place a unit in.
- Type:
int
- take_back_line_upgrades#
Whether, before it places a unit in an LV network, the strategy takes back the line upgrades the run has made in it, for its loading as for its voltage: each line of the network gets the type and conductors it had at the start of the run (lines_at_start, which the algorithm lends), and the unit is placed on the network as it was then. The action lists them under lines_taken_back, and a run with prices is charged for them from the state at the start of the run, as the line upgrades are (calculate_cost): what the earlier actions were charged for those lines is refunded. If no unit is placed in the network, its lines keep their upgrades. Under the top-down order of #80, the line upgrades of the next pass then reinforce what the unit leaves, and the strategy is called again if they are not enough. False by default: the conductors laid before stay, as before step 6b.
- Type:
bool
- take_back_transformer_upgrades#
With take_back_line_upgrades, whether the take-back also gives the MV/LV unit feeding the network, if it was in place at the start of the run, its type and number of units of then (transformers_at_start), listed under transformers_taken_back and refunded as the transformer upgrades charge it (#80, step 6c, decided by the maintainer on 2026-11-25). It keeps the tap position it has: a no-load tap set during the run is a measure of its own, priced as such. A unit created by the run is not taken back. True by default; without take_back_line_upgrades it does nothing.
- Type:
bool
- min_excess_pu#
Excess (pu) of the worst bus of an LV network beyond the limit under which the network is a residual of the cheaper measures (MIN_EXCESS_PU by default, 0 for none): it gets no new unit in a call where they can still take it up (may_leave_residuals: a cheaper strategy of the chain has acted in this turn, and the run has a pass after this one), with a log line, and is left to the turns that follow (#80, step 6d). In any other call, as in the last pass or when the cheaper measures had nothing to offer, it gets a unit as any network: the threshold delays a unit, it never refuses one. The excess is that of the network as the strategy finds it, what the cheaper measures left, before any take-back.
- Type:
float
- units_per_call#
Most new units a call adds to one LV network, None for as many as max_new_substations allows (the default). 1 under the top-down order: one unit, then the line upgrades of the next pass.
- Type:
Optional[int]
- transformer_parallel_units#
The parallel_units by which the unit in place taken back is refunded what the transformer upgrades charged for it (#83): with “with_works”, the works of a new substation for each unit it had beyond those of the start of the run. None (the default): that of the TransformerUpgradeStrategy of the run, which the algorithm lends (parallel_units_of_the_run), and “allowed” for the strategy used on its own. A value given that differs from the run’s makes the run refuse to start (see GridEnhancementAlgorithm.run).
- Type:
Optional[str]
- applicable_constraints() set[ConstraintType][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][source]#
The LV networks alone: a new unit splits an LV network. In a priority order without levels, the strategy is given the violations of both, and leaves out those of the MV network, which no MV/LV unit feeds.
- apply_to_group(violations: list[ConstraintViolation], pf_engine: PowerFlowEngine) dict[str, Any] | None[source]#
Add new substations to the LV networks of a group of over-voltages or under-voltages (see the class).
- Returns:
The action, with one entry per new unit under substations, one per LV network given units under networks, and the units of the LV networks left out as MV-limited under mv_limited, and, with take_back_line_upgrades, one entry per line whose upgrades it took back under lines_taken_back (see _take_back); None if no unit was added. The network is then as it was, but for its partition, which is computed again.
- calculate_cost(action: dict[str, Any], cost_model: CostModel) float[source]#
Price of the new substations of an action: for each, its works (new_substation[“works”] of the type of its unit), its unit (transformer_upgrade of its type) and its MV cable (new_substation[“mv_cable”] of its type, per km), as CostModel.calculate_new_substation_cost prices them. Opening lines and splitting the MV line cost nothing.
The action lists the units and cables it created under created, from which a run with a cost model charges a later upgrade of them from nothing (see GridEnhancementAlgorithm._follow_created_elements). A unit is then charged, for each unit, the works of a new substation of its type and its unit price (see TransformerUpgradeStrategy._charge), less what it cost as created: a unit taken from 250 kVA (a compact substation) to 400 kVA is charged the difference of the works and of the units, so that the substation costs in all what a new 400 kVA one costs, whatever the path, and a unit added in parallel its works and unit again. A cable is charged at the line prices of its types, what it costs at the end less what it cost as created: the part of its own price above the line price of its type (the trench) stays as charged here.
The lines whose upgrades the action took back (lines_taken_back) are charged as LineUpgradeStrategy charges a line, from its state at the start of the run: back in that state, a line costs nothing, and the action is charged less what the earlier actions of the run were charged for it, a refund. A line upgraded again later is then charged from the start of the run again. An action with lines_taken_back records the two parts of its cost, the substations (substation_cost) and the take-back (take_back_cost, 0 or less); its cost is their sum.
- Raises:
MissingUnitCostError – If a price is missing.
- 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
- lv_networks_mv_limited(violations: list[ConstraintViolation], pf_engine: PowerFlowEngine) dict[str, float][source]#
The LV networks with an over-voltage or under-voltage of violations that the strategy would leave out as MV-limited (see the class): those fed by one MV/LV unit whose MV side is beyond the MV limits of the engine, by the name of their unit, with the voltage (pu) of its MV side. For the summary of a run, from the violations it leaves: violations no new substation can resolve, whatever the strategy did before.
- Returns:
The MV voltage of each, by unit; empty if no violation is an over-voltage or under-voltage, or if the engine lacks an operation the strategy needs.
- Return type:
dict[str, float]
- 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 price of a conductor added in parallel to a new MV cable, which the line upgrades charge at the new_line price of mv_line_type (or its line_upgrade price) if a run lays one. A unit added in parallel to a new unit is of a type of transformer_types, whose prices are required.
The works of a type that TransformerUpgradeStrategy may take a new unit to are not listed: this strategy does not know the types of the other. Without them, that type is left out of the options for a new unit, with a log line, and an action that takes a new unit there anyway raises MissingUnitCostError when it is priced.
- Parameters:
pf_engine (PowerFlowEngine) – The power flow engine.
- Returns:
The keys of the prices in CostModel.unit_costs.
- Return type:
Set[Tuple[str, …]]
- refund_parallel_units() str[source]#
The parallel_units the unit in place taken back is refunded by: the strategy’s own transformer_parallel_units if given, otherwise that of the transformer upgrades of the run (parallel_units_of_the_run, lent by the algorithm), otherwise “allowed”.
- required_unit_costs(pf_engine: PowerFlowEngine) set[tuple[str, ...]][source]#
List the prices of a new substation with a unit of each type of transformer_types: its works and its unit, and the price per km of its MV cable of mv_line_type.
- Parameters:
pf_engine (PowerFlowEngine) – The power flow engine.
- Returns:
The keys of the prices in CostModel.unit_costs.
- Return type:
Set[Tuple[str, …]]
- property stage: str#
Get the stage of the strategy (e.g., ‘operation’, ‘planning’).
- Returns:
The stage of the strategy.
- Return type:
str
- gridforge.strategies.new_substation.describe_new_substation(substation: dict[str, Any]) str[source]#
One new substation of a new_substation action (an entry of its substations), as the strategies describe their actions in their log: “New substation ‘name’: type at bus ‘b’, tap +2.5 % (position 1), teed into MV line ‘l’ by 0.120 km of U_AL_150_mv, LV lines opened: ‘a’, ‘b’”.
- gridforge.strategies.new_substation.positions_for_rises(tap: dict[str, Any], rated: dict[str, Any], vn_hv_kv: float, vn_lv_kv: float, rises: Sequence[float]) dict[float, tuple[Any, float]][source]#
For each rise of the LV voltage at no load of rises (%) that a unit of the rated voltages rated with the tap changer tap gives, on buses of nominal voltages vn_hv_kv and vn_lv_kv: its position, the nearest if less than half a step away, and its ratio there, LV voltage at no load per unit of the MV voltage, both in pu of their buses (the tap and the rated voltages together).
A unit whose tap changer the power flow does not apply is at its neutral position (None without a range) and has the ratio of its rated voltages, which gives the rises within FIXED_TAP_TOLERANCE of it.
- gridforge.strategies.new_substation.tap_changer_kind(tap: dict[str, Any]) str[source]#
“ratio” for a ratio tap changer the power flow applies, “fixed” for a unit whose tap changer it does not apply (no side, a step of NaN or 0, no changer type: pandapower ignores it), otherwise why it cannot be used: a tap changer of another type, or one that shifts the phase, which tap_ratio does not describe.
The no-load tap of an MV/LV unit in place, against LV over-voltages and under-voltages (#80, step 6b): Enedis’s units have taps set off load, by a crew, at 0, +2.5 or +5 % of the LV voltage (Enedis-NMO-RAC_007E §5.2.1.3), a planning decision that later works do not take back.
- class gridforge.strategies.no_load_tap.NoLoadTapStrategy(taps: Sequence[float] = (0.0, 2.5, 5.0))[source]#
Bases:
EnhancementStrategyMove the no-load tap of the MV/LV unit feeding an LV network with over-voltages (down) or under-voltages (up), one position at a time, among the positions that give a rise of the LV voltage at no load of taps, while that leaves fewer buses of the network beyond the limit of the direction and none more beyond the other. A step that does not is undone, and the unit stays where it was before it. A unit at a position outside them (set by a study at the start, say) goes in one step to the nearest of them in the direction of the move, past the positions between.
A position gives a rise if its full no-load ratio (the tap with the rated voltages of the unit against those of its buses, as NewSubstationStrategy takes the taps of a new unit) is within half a step of 1 + rise / 100. On the units of the feeder files (tap on the LV side, +2.5 % per position, 20/0.4 kV), Enedis’s 0, +2.5 and +5 % are positions 0, 1 and 2; the units are at 1.
It is a planning strategy: the tap of an Enedis unit is set off load, once, by a crew, and stays through the works that follow. TapChangeStrategy, an operation strategy, is reverted after each planning change and chosen again, over the whole range of the unit, to centre the voltages of the network on 1 pu whatever its limits. The two should not be registered for the same units: the revert of an operation tap change aims at the position before it, and would undo a no-load tap set since.
A network is left out if it is fed by more than one unit, or by a unit that is not an MV/LV one, or whose tap changer the power flow does not apply or is not a ratio one (see tap_changer_kind).
- taps#
The rises of the LV voltage (%) the no-load tap of a unit may give: Enedis’s current units by default (0, +2.5, +5 %); its older units have -2.5, 0, +2.5 %. Which of the two the units in place of a network are is not known: a study that knows sets it.
- Type:
Tuple[float, …]
- applicable_constraints() set[ConstraintType][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][source]#
The LV networks alone: the tap of an MV/LV unit moves its LV network.
- apply_to_group(violations: list[ConstraintViolation], pf_engine: PowerFlowEngine) dict[str, Any] | None[source]#
Move the no-load tap of the unit of each LV network with violations of the group (see the class).
- Returns:
A tap_change action, with one entry per unit moved under transformers, or None if no unit moved.
- calculate_cost(action: dict[str, Any], cost_model: CostModel) float[source]#
The no_load_tap price (a site visit) for each intervention of the action, whatever the number of positions moved (#80, step 6e): each entry records its interventions (see interventions), 1 for a unit moved away from its position at the start of the run, 0 for one moved again that was away from it already (the move adjusts the first, in the same plan), -1 for one moved back to it (the first is taken back), 0 for a unit the run created. An entry without the key, written before step 6e, counts as one intervention.
- Raises:
MissingUnitCostError – If the price is missing.
- 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
- property name: str#
Get the name of the strategy.
- Returns:
The name of the strategy.
- Return type:
str
- required_unit_costs(pf_engine: PowerFlowEngine) set[tuple[str, ...]][source]#
The price of an intervention on a no-load tap.
- property stage: str#
Get the stage of the strategy (e.g., ‘operation’, ‘planning’).
- Returns:
The stage of the strategy.
- Return type:
str
- gridforge.strategies.no_load_tap.changed_in_the_run(unit: str, pf_engine: PowerFlowEngine, transformers_at_start: Any) bool[source]#
Whether the run has works on the unit unit: its type or its number of units in parallel now are not those at the start of the run (transformers_at_start, the type and units of each, as the algorithm lends them). Its tap is then moved by the crew already on site for the works, and is not charged (#80, step 6e, decided on 2026-11-27): a replaced unit’s tap is set when the new one is commissioned, and Enedis’s price for a transformer power increase has no line for the tap; the retap of a unit kept in place when one is added in parallel, about 50 € of labour, is left out as a simplification. False without the states at the start, or for a unit not among them.
- gridforge.strategies.no_load_tap.interventions(start: Any, old: Any, new: Any, known: bool = True) int[source]#
The interventions a move of a no-load tap from position old to new adds to a run, for a unit whose position at the start of the run is start (#80, step 6e): the run pays one per unit whose tap ends away from its start, so a move away from the start is one, a move between two positions away from it adjusts the first (none), and a move back to the start takes the first back (-1). Without the start (start None: the strategy used on its own, or an engine that does not tell the position), each move is one. A unit the run created, or has works on (known False: not among the positions at the start of the run, or of another type or number of units than at the start, see changed_in_the_run), costs none: its tap is set by the crew of the works. A unit with works after its tap moved has that intervention taken back by the run (GridEnhancementAlgorithm, no_load_tap_adjustments).
Where to put new MV/LV substations in a radial LV network, and how large to make them (#80).
Pure functions on plain data, with no engine: the strategy builds the data from its engine and passes a power flow in as check, so that everything here is tested without one.
The LV network is a tree (networkx.Graph) whose edges carry their resistance and reactance in ohms, r_ohm and x_ohm, conductors in parallel included, and their length under the attribute named by length (length_km by default). Its “sources” are the buses fed by an MV/LV unit, the busbar of the unit in place first. Each LV bus is fed by the nearest source along the cables (by length; a tie goes to the source listed first) and the lines whose ends are fed by different sources are opened. On a tree each source then feeds a connected part, and choosing the bus of a new unit is the only choice: the lines to open follow from it.
A candidate bus is rated by LinDistFlow (voltages without losses, the unit’s transformer included), the way an operator splits a feeder: by the number of buses beyond the limit of the direction (above the upper limit for “over”, below the lower one for “under”), then by the worst voltage in that direction. A candidate that puts a bus beyond the other limit ranks after every candidate that does not, so that a tap chosen against one direction does not cross the other at the same point. Units are added one at a time, the power flow check deciding between the first few buses of the ranking, then each new unit is moved to its best bus given the others while that improves the check.
The units are sized on Enedis’s two situations (Enedis-NMO-RAC_007E §5.3): the winter peak of consumption against the active power limit of the unit, and the summer peak of production less 20 % of the peak of consumption against its rating.
- gridforge.strategies.substation_placement.ACTIVE_POWER_PER_KVA = 0.84#
kW per kVA for a rating outside ENEDIS_ACTIVE_POWER_LIMIT_KW, about Enedis’s ratio.
- gridforge.strategies.substation_placement.EARTH_RADIUS_M = 6371008.8#
Mean radius of the Earth, for the local projection.
- gridforge.strategies.substation_placement.ENEDIS_ACTIVE_POWER_LIMIT_KW = {100: 85, 160: 135, 250: 210, 400: 335, 630: 525, 1000: 835}#
Largest active power (kW) Enedis lets through an MV/LV unit of each rating (kVA) in the winter situation, the consumption peak at the base minimum temperature (Enedis-NMO-RAC_007E §5.3).
- class gridforge.strategies.substation_placement.Evaluation(beyond: int, worst: float, beyond_other: int = 0)[source]#
Bases:
objectVoltages rated in one direction.
- beyond#
Number of buses beyond the limit of the direction.
- Type:
int
- worst#
Worst voltage in that direction (pu): the highest for “over”, the lowest for “under”.
- Type:
float
- beyond_other#
Number of buses beyond the other limit.
- Type:
int
A check may return a subclass carrying more (loadings, for instance).
- beyond: int#
- beyond_other: int = 0#
- worst: float#
- gridforge.strategies.substation_placement.Injection#
Active and reactive power injected at a bus (MW, Mvar), negative for a load.
alias of
tuple[float,float]
- class gridforge.strategies.substation_placement.NewUnit(bus: Any, tap: Any)[source]#
Bases:
objectA new unit: the LV bus it feeds and its tap, a key of the caller’s new_unit.
- bus: Any#
- tap: Any#
- class gridforge.strategies.substation_placement.PlacementStep(units: tuple[NewUnit, ...], estimate: Evaluation, checked: Evaluation | None)[source]#
Bases:
objectThe new units after one addition (and the moves that follow it).
- units#
The new units, in the order they were placed.
- Type:
- estimate#
The LinDistFlow rating of the network with them.
- checked#
What check returned for them, None if it failed.
- Type:
- checked: Evaluation | None#
- estimate: Evaluation#
- class gridforge.strategies.substation_placement.RankedCandidate(unit: NewUnit, estimate: Evaluation)[source]#
Bases:
objectA new unit and the LinDistFlow rating of the network with it.
- estimate: Evaluation#
- gridforge.strategies.substation_placement.SUMMER_CONSUMPTION_SHARE = 0.2#
Share of the peak of consumption that runs during the summer production peak.
- class gridforge.strategies.substation_placement.UnitParameters(v_mv_pu: float, ratio: float, r_pu: float, x_pu: float)[source]#
Bases:
objectAn MV/LV unit as LinDistFlow sees it.
- v_mv_pu#
Voltage of the MV side (pu).
- Type:
float
- ratio#
Voltage of the LV side at no load per unit of the MV side (pu/pu), from the tap (tap_ratio).
- Type:
float
- r_pu#
Resistance of the unit in pu of a 1 MVA base at the LV voltage, so that r_pu * p_mw is a voltage in pu.
- Type:
float
- x_pu#
Reactance, likewise.
- Type:
float
- classmethod from_rating(v_mv_pu: float, ratio: float, sn_mva: float, vk_percent: float, vkr_percent: float, parallel: int = 1) UnitParameters[source]#
The unit from the rating and short-circuit voltages of its transformer.
- r_pu: float#
- ratio: float#
- v_mv_pu: float#
- x_pu: float#
- gridforge.strategies.substation_placement.active_power_limit_mw(sn_mva: float) float[source]#
Largest active power through a unit of sn_mva in Enedis’s winter situation: Enedis’s table for 100 to 1000 kVA, ACTIVE_POWER_PER_KVA otherwise.
- gridforge.strategies.substation_placement.cable_distances(tree: Graph, length: str = 'length_km') dict[Hashable, dict[Hashable, float]][source]#
Distance along the cables between every two buses, distances[a][b] from a to b, to share between calls on the same tree.
- gridforge.strategies.substation_placement.lindistflow(tree: Graph, sources: Sequence[Hashable], injections: Mapping[Hashable, tuple[float, float]], unit_parameters: Mapping[Hashable, UnitParameters], *, vn_kv: float, length: str = 'length_km', distances: Mapping[Hashable, Mapping[Hashable, float]] | None = None) dict[Hashable, float][source]#
The voltage of each bus (pu) by LinDistFlow, the network split between sources as split_by_nearest_source splits it.
Each part is fed by its unit at v_mv_pu * ratio, less nothing at no load; the voltage then moves by R P + X Q across the unit and each line of the path, with P and Q the power injected downstream (negative for a load) and the voltages taken at 1 pu: no losses. In the benchmarks, the worst voltage by LinDistFlow less that by the power flow, with the new unit at its best bus, is positive in 259 of their 260 networks: a median of +0.002 pu under generation (over-voltages) and +0.004 pu under load (under-voltages), +0.003 and +0.008 pu on the networks of 40 buses or more. LinDistFlow thus puts the worst bus a little beyond the upper limit and a little short of the lower one. The error grows with the current, to a few hundredths of a pu at the highest currents.
- Parameters:
tree – The LV network, a tree, edges with r_ohm and x_ohm.
sources – The buses fed by a unit, the unit in place first.
injections – (P in MW, Q in Mvar) injected at each bus, negative for a load; a bus left out injects nothing.
unit_parameters – The unit of each source.
vn_kv – Nominal voltage of the LV network.
length – The edge attribute that splits the network.
distances – cable_distances(tree, length), if already computed.
- gridforge.strategies.substation_placement.nearest_point_on_lines(point: Sequence[float], geometries: Mapping[Any, Sequence[Sequence[float]]]) tuple[Any, float, float] | None[source]#
The point of the lines nearest to point, all in the same metric frame (projected).
- Parameters:
point – (x, y).
geometries – Each line’s polyline, a sequence of (x, y), from one end of the line to the other. A line with no point, or with a point that is not finite (a route with a gap), is skipped: its nearest point is not known.
- Returns:
The line, the fraction of its length from its first point to the nearest point (0 for a line of no length), and the distance to it; None without any line left. A tie goes to the line listed first, then to the segment nearest its first point.
- Raises:
ValueError – if point is not finite, or a point has other than 2 coordinates.
- gridforge.strategies.substation_placement.place_units(tree: Graph, sources: Sequence[Hashable], injections: Mapping[Hashable, tuple[float, float]], unit_parameters: Mapping[Hashable, UnitParameters], new_unit: Mapping[Any, UnitParameters], check: Callable[[tuple[NewUnit, ...]], Evaluation | None], *, limits: tuple[float, float], direction: str, vn_kv: float, max_units: int, n_checked: int = 3, max_rounds: int = 3, candidates: Iterable[Hashable] | None = None, length: str = 'length_km', distances: Mapping[Hashable, Mapping[Hashable, float]] | None = None) list[PlacementStep][source]#
New units added one at a time, until no bus is beyond the limit or max_units are placed.
Each addition ranks the free candidate buses by LinDistFlow given the units already placed (rank_candidates) and keeps, of the first n_checked buses of the ranking (each at its best tap), the one check rates best. Then, while that improves the check (at most max_rounds rounds, 0 for none), each new unit in turn is moved to the bus that an addition would choose given the others. The units of sources stay where they are.
- Parameters:
tree
sources
injections
unit_parameters
new_unit
limits
direction
vn_kv
:param : :param candidates: as for rank_candidates. :param length: as for rank_candidates. :param distances: as for rank_candidates. :param check: Rates the network with the new units it is given, sorted by bus (so bus
labels must be orderable), the network being split by split_by_nearest_source between sources and their buses, in that order; None if it fails (a power flow that does not converge). It is called once per set of units.
- Parameters:
max_units – Most new units to place.
n_checked – Buses of the ranking that check decides between.
max_rounds – Most rounds of moves after each addition.
- Returns:
the units after it and its moves, their LinDistFlow rating (split as the check splits) and their check. The caller chooses among them; a step whose check fails ends the placement. The ranking of an addition splits with the unit added last, which decides the buses at the same distance from two new units.
- Return type:
One step per addition
- gridforge.strategies.substation_placement.projected(coordinates: Iterable[Sequence[float]], origin: Sequence[float] | None = None) ndarray[source]#
Points (longitude, latitude, in degrees) in metres east and north of origin, by a local equirectangular projection: exact enough over the few kilometres of an LV network and the MV lines around it.
- Parameters:
coordinates – The points, as (longitude, latitude) pairs.
origin – The (longitude, latitude) mapped to (0, 0); the mean of the points by default. Pass the same origin to project points that are compared.
- Returns:
x east, y north, in metres.
- Return type:
An array of shape (n, 2)
- Raises:
ValueError – if a point, or the origin, has other than 2 coordinates.
- gridforge.strategies.substation_placement.rank_candidates(tree: Graph, sources: Sequence[Hashable], injections: Mapping[Hashable, tuple[float, float]], unit_parameters: Mapping[Hashable, UnitParameters], new_unit: Mapping[Any, UnitParameters], *, limits: tuple[float, float], direction: str, vn_kv: float, candidates: Iterable[Hashable] | None = None, length: str = 'length_km', distances: Mapping[Hashable, Mapping[Hashable, float]] | None = None) list[RankedCandidate][source]#
Every new unit, at each candidate bus and each tap, rated by LinDistFlow with the units of sources, best first (ranking_key); a tie keeps the order of candidates, then that of new_unit.
- Parameters:
tree – as for lindistflow.
sources – as for lindistflow.
injections – as for lindistflow.
unit_parameters – as for lindistflow.
vn_kv – as for lindistflow.
length – as for lindistflow.
new_unit – The new unit at each tap it may take, by a key of the caller’s (the tap position, for instance), recorded in NewUnit.tap.
limits – (lower, upper) voltage limits of the LV network (pu).
direction – “over” or “under”, the violations to resolve.
candidates – The buses a new unit may feed; by default every bus that is not a source. A source among them is left out.
distances – cable_distances(tree, length), if already computed.
- gridforge.strategies.substation_placement.ranking_key(evaluation: Evaluation | None, direction: str) tuple[source]#
Sort key of a rating, best first: no bus beyond the other limit, then the fewest buses beyond the limit of the direction, then the least worst voltage; None (a check that failed) last.
- gridforge.strategies.substation_placement.rate_voltages(voltages: Iterable[float], limits: tuple[float, float], direction: str) Evaluation[source]#
Voltages (pu) rated in direction against limits, (lower, upper): a voltage equal to a limit is within it.
- gridforge.strategies.substation_placement.size_unit(peak_consumption_mw: float, peak_production_mw: float, transformer_types: Mapping[str, float]) str | None[source]#
The smallest transformer type that passes Enedis’s two situations for the part it feeds (Enedis-NMO-RAC_007E §5.3):
winter: the peak of consumption, production off, within the active power limit of the unit (active_power_limit_mw, about 0.84 kW per kVA);
summer: the peak of production less SUMMER_CONSUMPTION_SHARE of the peak of consumption, within the rating.
- Parameters:
peak_consumption_mw – Peak of the consumption of the part (MW, 0 or more).
peak_production_mw – Peak of its production (MW, 0 or more).
transformer_types – The rating (MVA) of each type that may be chosen.
- Returns:
The type, the first listed among those of the smallest rating; None if no type passes, which the caller settles (with the largest type, its overload then left to the thermal strategies, for instance).
- gridforge.strategies.substation_placement.split_by_nearest_source(tree: Graph, sources: Sequence[Hashable], length: str = 'length_km', *, distances: Mapping[Hashable, Mapping[Hashable, float]] | None = None) tuple[dict[Hashable, Hashable], list[tuple[Hashable, Hashable]]][source]#
The source that feeds each bus and the edges to open.
Each bus is fed by the nearest source along the cables, by the edge attribute length, among the sources it reaches without passing another one; a tie goes to the source listed first, and a source feeds its own bus. On a tree, the buses fed by a source then form a connected part that holds it, and exactly len(sources) - 1 edges are opened. (The nearest source alone gives the same parts but where sources are at no distance from each other, through lines of no length: there, a source could be fed by another one and feed nothing.)
- Parameters:
tree – The LV network, a tree.
sources – The buses fed by a unit, distinct, the unit in place first.
length – The edge attribute to measure the distance with.
distances – cable_distances(tree, length), if already computed.
- Returns:
The source of each bus, and the edges whose ends are fed by different sources, each as (end nearer the first source, other end), in breadth-first order from the first source.
- gridforge.strategies.substation_placement.tap_ratio(tap_pos: float, tap_step_percent: float, tap_side: str, tap_neutral: float = 0.0) float[source]#
Voltage of the LV side at no load per unit of the MV side, for a ratio tap changer on side tap_side (“hv” or “lv”), as pandapower models it, the rated voltages of the unit being those of its buses.
- class gridforge.strategies.tap_change.TapChangeStrategy[source]#
Bases:
EnhancementStrategyStrategy to change transformer tap positions to address voltage violations.
This strategy identifies voltage violations in galvanically connected components and adjusts the tap position of the supplying transformer to shift the voltage profile towards the target value (typically 1.0 p.u.).
- logs#
List of log messages generated during execution.
- Type:
List[str]
- applicable_constraints() set[ConstraintType][source]#
Get the set of applicable constraint types.
- Returns:
The set of applicable constraint types.
- Return type:
Set[ConstraintType]
- apply_to_group(violations: list[ConstraintViolation], pf_engine: PowerFlowEngine) dict[str, Any] | None[source]#
Find the optimal tap setting for transformers to address voltage violations.
This method analyzes voltage violations in each network component and calculates the optimal tap position that will bring the voltages closest to the nominal value (typically 1.0 p.u.), while staying within acceptable limits.
- Parameters:
violations (List[ConstraintViolation]) – List of voltage-related constraint violations.
pf_engine (PowerFlowEngine) – Power flow engine instance to use for network analysis.
- Returns:
Dictionary with details of the tap change actions performed, or None if no actions could be applied.
- Return type:
Optional[Dict[str, Any]]
- calculate_cost(action: dict[str, Any], cost_model: CostModel) float[source]#
Calculate the cost of the tap change actions.
- Parameters:
action (Dict[str, Any]) – The action dictionary.
cost_model (CostModel) – The cost model.
- Returns:
The total cost of the tap changes.
- Return type:
float
- property cost_level: int#
Get the cost level of the strategy.
- Returns:
The cost level (1 for tap changes, as they are low-cost).
- Return type:
int
- property name: str#
Get the name of the strategy.
- Returns:
The name of the strategy (“Transformer Tap Change”).
- Return type:
str
- required_unit_costs(pf_engine: PowerFlowEngine) set[tuple[str, ...]][source]#
List the price of a tap step.
- Parameters:
pf_engine (PowerFlowEngine) – The power flow engine.
- Returns:
The key of the price in CostModel.unit_costs.
- Return type:
Set[Tuple[str, …]]
- property stage: str#
Get the stage of the strategy.
- Returns:
The stage (“operation”).
- Return type:
str
- gridforge.strategies.transformer_upgrade.PARALLEL_UNITS = ('allowed', 'with_works', 'none')#
whether a unit may be added beside the units in place, and what it is charged.
- Type:
The values of TransformerUpgradeStrategy(parallel_units=…) (#83, D10)
- class gridforge.strategies.transformer_upgrade.TransformerUpgradeStrategy(transformer_types: list[str], parallel_units: str = 'allowed')[source]#
Bases:
EnhancementStrategyStrategy to upgrade transformers to address transformer loading violations.
This strategy identifies overloaded transformers and replaces their units with a type of higher rating, or adds units of the type in place in parallel. The units are sized on the loading the engine reports, and the choice between a larger type and units in parallel is made on the prices of the run, if it has some (see _choose_upgrade).
Whether a unit may be added beside the units in place, and what it is charged, is parallel_units (#83): Enedis’s substation has one LV protection device per transformer (Enedis-NMO-RES_011E §4.2.1), and its LV ladder replaces the unit, then creates a substation (Enedis-NMO-RAC_007E §3.5.1), with no unit in parallel.
- transformer_types#
List of available transformer types.
- Type:
List[str]
- parallel_units#
One of PARALLEL_UNITS (see __init__).
- Type:
str
- logs#
List of log messages generated during execution.
- Type:
List[str]
- applicable_constraints() set[ConstraintType][source]#
Get the set of applicable constraint types.
- Returns:
The set of applicable constraint types.
- Return type:
Set[ConstraintType]
- apply_to_group(violations: list[ConstraintViolation], pf_engine: PowerFlowEngine) dict[str, Any] | None[source]#
Apply transformer upgrades to address a group of transformer loading violations.
The strategy identifies overloaded transformers and upgrades them based on loading levels. A transformer whose loading the last unit added in parallel did not lower gets no more units (see _stalled). With parallel_units “none”, a transformer that no configured type carries with the units it has gets nothing, keeps its violation and is listed in the action under units_at_the_top_of_the_ladder.
A type change sized to carry the transformer with the units in place is checked by the power flow that follows the iteration: a larger unit has a lower impedance, which under export lowers the voltage on the LV side and raises the current. If the transformer is over its limit, the type change is undone (the engine gives the transformer back what it was, save_transformer, restore_transformer, and puts back the solution the iteration was decided on, save_solution, restore_solution), and the transformer takes, in the same iteration, the step chosen on the same power flow with that type offered with one more unit for the rest of the action (see StepCheck), at the cost of one more power flow. On an engine that cannot do all four operations, the type changes are not checked: a transformer still overloaded takes its next step at the next iteration.
- Parameters:
violations (List[ConstraintViolation]) – List of transformer loading violations.
pf_engine (PowerFlowEngine) – Power flow engine instance.
- Returns:
Dictionary with details of the transformer upgrade actions performed, or None if no actions could be applied.
- Return type:
Optional[Dict[str, Any]]
- calculate_cost(action: dict[str, Any], cost_model: CostModel) float[source]#
Calculate the cost of the transformer upgrade actions.
A transformer is charged once, for the units laid, however many steps took it there: a unit taken from one type to the next and then to a third is charged for a unit of the third only, not for the type in between, which is never laid, and a unit added in parallel and then replaced, with the others, by a unit of another type is charged at that type only. What a transformer costs, from the state it had at first to the state it is left in, is the transformer_upgrade price of its final type for every unit it has then, if the type has changed, as they are all replaced, and for every unit added otherwise. A transformer that has no type is priced under the key None. With parallel_units “with_works”, each unit beyond those the transformer had at the start of the run is also charged the works of a new substation of its final type (see _charge).
The state at first is that of the transformer when the run started, which GridEnhancementAlgorithm records in the upgrades (origin_type, origin_units). The action is then charged the difference between what the transformer costs after it and what it cost before it, so that a transformer upgraded by several actions of a run is charged in all for what the run lays (see sizing.charge). Without that record, the state at first is the one before the action.
- Parameters:
action (Dict[str, Any]) – The action dictionary.
cost_model (CostModel) – The cost model.
- Returns:
The total cost of the upgrades.
- Return type:
float
- property cost_level: int#
Get the cost level of the strategy.
- Returns:
The cost level (4 for transformer upgrades).
- Return type:
int
- property name: str#
Get the name of the strategy.
- Returns:
The name of the strategy (“Transformer Upgrade”).
- Return type:
str
- parallel_units = 'allowed'#
- possible_unit_costs(pf_engine: PowerFlowEngine) set[tuple[str, ...]][source]#
List the upgrade price of every transformer type in place on the network.
A transformer can be given a unit in parallel of the type it has, whether or not that type is one of the configured ones: when no configured type is larger, or when its rating is enough for the power it carries. The unit is charged at the price of that type, and that of a transformer that has no type (a std_type of None, NaN or ‘’, like a unit created from its parameters) at the price under the key None. Whether a run adds one is not known before it: the run starts without these prices, and stops if it needs a missing one. With parallel_units “with_works”, the works of a new substation of each type in place are listed too, those of a unit without a type under the key None as its unit price is; with “none”, no unit is added in parallel and nothing is listed.
- Parameters:
pf_engine (PowerFlowEngine) – The power flow engine.
- Returns:
The keys of the prices in CostModel.unit_costs.
- Return type:
Set[Tuple[str, …]]
- required_unit_costs(pf_engine: PowerFlowEngine) set[tuple[str, ...]][source]#
List the upgrade price of every configured transformer type, and with parallel_units “with_works” the works of a new substation of each (new_substation[“works”]), which a type change that adds units is charged.
- Parameters:
pf_engine (PowerFlowEngine) – The power flow engine.
- Returns:
The keys of the prices in CostModel.unit_costs.
- Return type:
Set[Tuple[str, …]]
- property stage: str#
Get the stage of the strategy.
- Returns:
The stage (“planning”).
- Return type:
str
- units_at_the_top_of_the_ladder(remaining_violations: list[ConstraintViolation], pf_engine: PowerFlowEngine) list[str][source]#
The transformers over their loading limit that no option of the strategy carries, among remaining_violations, by name: with parallel_units “none”, those that no configured type carries with the units they have, which keep their violation (#83). Judged on the loading the violations report, as the strategy sizes them, and also, in a run, those an action of the run had no option left for (units_at_top_of_the_run, which the algorithm lends), as one whose type change the power flow refused (see StepCheck) with no larger type left. Empty with “allowed” and “with_works”, where a unit in parallel is always an option.
- Parameters:
remaining_violations (List[ConstraintViolation]) – The violations left.
pf_engine (PowerFlowEngine) – The power flow engine, in the state that left them.
- Returns:
The names of the transformers, sorted.
- Return type:
List[str]