distgridforge 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. distgridforge-0.3.0.dist-info/METADATA +266 -0
  2. distgridforge-0.3.0.dist-info/RECORD +38 -0
  3. distgridforge-0.3.0.dist-info/WHEEL +5 -0
  4. distgridforge-0.3.0.dist-info/licenses/LICENCE.txt +21 -0
  5. distgridforge-0.3.0.dist-info/top_level.txt +1 -0
  6. gridforge/__init__.py +32 -0
  7. gridforge/case_study/config.py +158 -0
  8. gridforge/case_study/dickert_lv_network_script.py +109 -0
  9. gridforge/case_study/mv_lv_feeder.py +314 -0
  10. gridforge/case_study/simbench_network_test_case.py +168 -0
  11. gridforge/core/__init__.py +0 -0
  12. gridforge/core/constraints.py +421 -0
  13. gridforge/core/cost_model.py +363 -0
  14. gridforge/core/grid_enhancement.py +1932 -0
  15. gridforge/core/power_flow.py +1146 -0
  16. gridforge/core/strategy.py +297 -0
  17. gridforge/engines/__init__.py +0 -0
  18. gridforge/engines/gridlabd_engine.py +527 -0
  19. gridforge/engines/opendss_engine.py +885 -0
  20. gridforge/engines/pandapower_engine.py +3766 -0
  21. gridforge/engines/roseau_engine.py +1234 -0
  22. gridforge/examples/__init__.py +0 -0
  23. gridforge/examples/quick_start.py +85 -0
  24. gridforge/main.py +0 -0
  25. gridforge/strategies/__init__.py +0 -0
  26. gridforge/strategies/flexibility.py +1476 -0
  27. gridforge/strategies/line_upgrade.py +1846 -0
  28. gridforge/strategies/path_to_source.py +596 -0
  29. gridforge/strategies/sizing.py +210 -0
  30. gridforge/strategies/step_check.py +183 -0
  31. gridforge/strategies/tap_change.py +267 -0
  32. gridforge/strategies/transformer_upgrade.py +622 -0
  33. gridforge/utils/__init__.py +0 -0
  34. gridforge/utils/config.py +55 -0
  35. gridforge/utils/interactive_plot.py +700 -0
  36. gridforge/utils/logging.py +86 -0
  37. gridforge/utils/plot.py +1078 -0
  38. gridforge/utils/reporting.py +0 -0
@@ -0,0 +1,1932 @@
1
+ """
2
+ Grid Enhancement Algorithm for constraint management in electricity distribution networks.
3
+ """
4
+
5
+ import copy
6
+ import logging
7
+ import math
8
+ from collections.abc import Iterable, Iterator
9
+ from contextlib import contextmanager
10
+ from dataclasses import dataclass, field
11
+ from typing import TYPE_CHECKING, Any, Optional
12
+
13
+ from gridforge import ConstraintType, ConstraintViolation
14
+ from gridforge.core.constraints import _relative_excess
15
+ from gridforge.core.cost_model import (
16
+ CostModel,
17
+ InvalidUnitCostError,
18
+ MissingUnitCostError,
19
+ )
20
+ from gridforge.core.power_flow import (
21
+ PowerFlowEngine,
22
+ PowerFlowNotConverged,
23
+ type_in_place,
24
+ )
25
+ from gridforge.core.strategy import note_origins
26
+ from gridforge.utils.logging import _format_grid_state
27
+
28
+ if TYPE_CHECKING:
29
+ from gridforge.core.strategy import EnhancementStrategy
30
+
31
+
32
+ @dataclass
33
+ class _StateSnapshot:
34
+ """
35
+ A state of the enhancement process that can be restored later.
36
+
37
+ Holds the network along with everything that must stay consistent with it: the
38
+ engine's latest power flow status and the actions applied (with their cost) to
39
+ reach it. A snapshot is meant to be restored at most once, as the network it holds
40
+ becomes the engine's live network.
41
+ """
42
+
43
+ network: Any
44
+ latest_results: dict[str, Any] | None
45
+ applied_actions: list[dict[str, Any]]
46
+ total_cost: float
47
+
48
+
49
+ @dataclass
50
+ class _BestState:
51
+ """
52
+ The best state met along a path of the enhancement process, as `_score` rates it.
53
+
54
+ `keep` tells whether the state is saved along with its score, to be restored as
55
+ the partial solution; a path that is only rated, like a lookahead rollout, does
56
+ not pay for the copies. A state without violations is never saved, as a run that
57
+ reaches one ends there and does not fall back on a partial solution.
58
+ """
59
+
60
+ score: tuple[int, float, float] | None = None
61
+ snapshot: _StateSnapshot | None = None
62
+ keep: bool = False
63
+ # The cost of the state that the best one tied with, when it was kept: a state that
64
+ # wins on its severity, at a cost within the tie, does not move it, so that ties
65
+ # cannot add up (see `GridEnhancementAlgorithm._is_better`)
66
+ anchor: float | None = None
67
+
68
+
69
+ @dataclass
70
+ class _Pass:
71
+ """
72
+ Where a pass of the run, or of a rollout, stands: the turns it has given, for
73
+ `GridEnhancementAlgorithm._turns` to give the next ones (#66).
74
+ """
75
+
76
+ # The violations of the network now, kept current by the one taking the turns
77
+ violations: list[ConstraintViolation]
78
+ # Index in the priority order of the type of the last turn given in that order
79
+ position: int = -1
80
+ # Of each type whose turn has ended, its violations as it ended, by type and element
81
+ ended_with: dict[Any, set[tuple[Any, Any]]] = field(default_factory=dict)
82
+ # The types given a turn again
83
+ again: set[Any] = field(default_factory=set)
84
+
85
+ def end_turn(self, violation_type: Any) -> None:
86
+ """Note the end of a turn of `violation_type`, on the violations now."""
87
+ self.ended_with[violation_type] = {
88
+ (v.constraint_type, v.element_id)
89
+ for v in self.violations
90
+ if v.constraint_type == violation_type
91
+ }
92
+
93
+ def copy(self) -> "_Pass":
94
+ return _Pass(
95
+ list(self.violations),
96
+ self.position,
97
+ {key: set(keys) for key, keys in self.ended_with.items()},
98
+ set(self.again),
99
+ )
100
+
101
+
102
+ STRATEGY_CHOICES = ("first", "lookahead")
103
+
104
+
105
+ def _ranks_before(
106
+ key: tuple[int, float], best: tuple[int, float], tie: float = 0.0
107
+ ) -> bool:
108
+ """
109
+ Tell whether a state rated `key` (number of violations, total cost) beats the best
110
+ so far: fewer violations, then a cost lower by more than `tie` (see
111
+ `GridEnhancementAlgorithm._cost_tie_of_the_state`).
112
+ """
113
+ if key[0] != best[0]:
114
+ return key[0] < best[0]
115
+ return best[1] - key[1] > tie
116
+
117
+
118
+ # A price that a choice the run only tries needs, and that is missing or not a price:
119
+ # that choice is not open to the run, which goes on with the others
120
+ _PRICE_ERRORS = (MissingUnitCostError, InvalidUnitCostError)
121
+
122
+
123
+ @dataclass(frozen=True)
124
+ class _ChargedFromOrigin:
125
+ """
126
+ A kind of element that a run with a cost model charges from its state at the start
127
+ of the run (see `GridEnhancementAlgorithm._origins_of_the_run`).
128
+
129
+ Attributes:
130
+ upgrades: Key of the upgrades of the elements in an action.
131
+ action_type: The type of the actions whose upgrades they are, None for any.
132
+ engine_info: Method of the engine that lists their `std_type` and `parallel`,
133
+ by name.
134
+ attribute: Attribute of the strategies the states are lent as.
135
+ element_id: Key of the name of the element in an upgrade.
136
+ origin_count: Key of the number of elements in parallel at run start, noted in
137
+ an upgrade with `origin_type`.
138
+ """
139
+
140
+ upgrades: str
141
+ action_type: str | None
142
+ engine_info: str
143
+ attribute: str
144
+ element_id: str
145
+ origin_count: str
146
+
147
+
148
+ _CHARGED_FROM_ORIGIN = (
149
+ _ChargedFromOrigin(
150
+ "lines", None, "get_lines_info", "line_origins", "line_id", "origin_conductors"
151
+ ),
152
+ # Not a tap change, whose action also lists transformers
153
+ _ChargedFromOrigin(
154
+ "transformers",
155
+ "transformer_upgrade",
156
+ "get_transformers_info",
157
+ "transformer_origins",
158
+ "transformer_id",
159
+ "origin_units",
160
+ ),
161
+ )
162
+
163
+
164
+ @contextmanager
165
+ def _lent_to(
166
+ strategies: Iterable["EnhancementStrategy"], **values: Any
167
+ ) -> Iterator[None]:
168
+ """
169
+ Give the strategies `values` as attributes for the time of a run, and give them
170
+ back their own when it ends, however it ends: a strategy used on its own after the
171
+ run chooses as it did before it.
172
+ """
173
+ own = [
174
+ (strategy, {name: getattr(strategy, name, None) for name in values})
175
+ for strategy in strategies
176
+ ]
177
+ try:
178
+ for strategy, _ in own:
179
+ for name, value in values.items():
180
+ setattr(strategy, name, value)
181
+ yield
182
+ finally:
183
+ for strategy, attributes in own:
184
+ for name, value in attributes.items():
185
+ setattr(strategy, name, value)
186
+
187
+
188
+ class GridEnhancementAlgorithm:
189
+ """
190
+ Base algorithm to enhance electricity distribution networks to prevent operational constraints.
191
+
192
+ The algorithm runs in a hierarchical manner:
193
+
194
+ 1. Execute power flow and identify all constraint violations.
195
+ 2. Group violations by type.
196
+ 3. For each type of violation, apply appropriate strategies in order of increasing cost
197
+ level, or, with a cost model, those leading to the best end of the run (see
198
+ `strategy_choice`). A type whose turn has passed is given it again in the pass,
199
+ once, if a later turn brings about violations of it (see `_turns`).
200
+ 4. Rerun power flow after each strategy application to check if violations are resolved.
201
+
202
+ Attributes:
203
+ pf_engine (PowerFlowEngine): Engine to perform power flow calculations.
204
+ cost_model (Optional[CostModel]): Model to calculate costs of network changes.
205
+ max_iterations (int): Maximum number of passes through the violation types.
206
+ strategy_registry (EnhancementStrategyRegistry): Registry of enhancement strategies.
207
+ logger (logging.Logger): Logger instance.
208
+ applied_actions (List[Dict[str, Any]]): List of actions applied during the enhancement process.
209
+ total_cost (float): Total cost of all applied actions.
210
+ history (List[Dict[str, Any]]): History of the enhancement process.
211
+ divergence_events (List[Dict[str, Any]]): Power flow divergences met during the last
212
+ run. Each event gives the `violation_type` and `strategy_name` being applied
213
+ (both None for the initial power flow) and the solver `message`.
214
+ """
215
+
216
+ def __init__(
217
+ self,
218
+ power_flow_engine: PowerFlowEngine,
219
+ cost_model: CostModel | None = None,
220
+ max_iterations: int = 13,
221
+ strategy_registry: Optional["EnhancementStrategyRegistry"] = None,
222
+ strategy_choice: str = "lookahead",
223
+ ):
224
+ """
225
+ Initialize the grid enhancement algorithm.
226
+
227
+ Args:
228
+ power_flow_engine (PowerFlowEngine): Engine to perform power flow calculations.
229
+ cost_model (Optional[CostModel], optional): Model to calculate costs of network changes. Defaults to None.
230
+ max_iterations (int, optional): Maximum number of passes. A pass addresses each
231
+ violation type of the priority order once, and a type once more if a
232
+ later turn of the pass brings about violations of it that were not there
233
+ as its turn ended (#66): the turns given again are not passes. Defaults
234
+ to 13, the number of passes of the former default of 50 per-type steps
235
+ with the 4 default types.
236
+ strategy_registry (Optional[EnhancementStrategyRegistry], optional): Registry of enhancement strategies by violation type. Defaults to None.
237
+ strategy_choice (str, optional): How the strategies of a violation type are
238
+ chosen, with a cost model (without one, always "first"):
239
+
240
+ - "first": in the order of their cost levels, each applied to what the
241
+ previous ones left, until the violations of the type are resolved.
242
+ - "lookahead" (default): the chain of strategies "first" makes is also
243
+ tried from the second strategy, from the third..., and each chain is
244
+ rated by the end of the run it leads to, finished with "first": the
245
+ fewest violations left, then the cheapest. A rating stops after a
246
+ pass that removed no violation and lowered no cost. The chain of
247
+ "first" is one of those rated, so the run ends with no more
248
+ violations, and no higher a cost for as many, than with "first":
249
+ where a rating was stopped and another chain kept, the run is also
250
+ made with "first", and the better of the two is returned.
251
+ """
252
+ if strategy_choice not in STRATEGY_CHOICES:
253
+ raise ValueError(
254
+ f"strategy_choice must be one of {', '.join(STRATEGY_CHOICES)}, "
255
+ f"not {strategy_choice!r}"
256
+ )
257
+ self.strategy_choice = strategy_choice
258
+ self.pf_engine = power_flow_engine
259
+ self.cost_model = cost_model
260
+ self.max_iterations = max_iterations
261
+ self.logger = logging.getLogger(__name__)
262
+
263
+ # Set default strategy registry if not provided
264
+ self.strategy_registry = strategy_registry or EnhancementStrategyRegistry()
265
+
266
+ self.applied_actions = []
267
+ self.total_cost = 0.0
268
+ self.history = []
269
+ self.divergence_events: list[dict[str, Any]] = []
270
+ # Number of divergence events already attached to a history entry
271
+ self._divergences_in_history = 0
272
+ # Violated types left out of the priority order, already warned about
273
+ self._unaddressed_types: set[ConstraintType] = set()
274
+ # Best partial solution of the run
275
+ self._best = _BestState(keep=True)
276
+ # Costs that differ by no more than this are equal: the largest
277
+ # `_cost_tie_of_the_state` of the states of the run so far
278
+ self._cost_tie = 0.0
279
+ # The state of each line and transformer at the start of the run, by the key
280
+ # of their upgrades in an action, from which a run with a cost model charges
281
+ # them (see `_origins_of_the_run`)
282
+ self._origins: dict[str, dict[str, tuple[Any, int]]] = {}
283
+ # The pass under way, for a lookahead rollout to finish it as the run would
284
+ self._pass_state: _Pass | None = None
285
+ # Turns given again in the passes of the run returned (see `_turns`): not
286
+ # those of rollouts, nor of a run with "first" that checks lookahead and is
287
+ # not kept, nor of the lookahead run it replaces
288
+ self._turns_given_again = 0
289
+
290
+ def run(self) -> tuple[bool, dict[str, Any]]:
291
+ """
292
+ Run the grid enhancement algorithm using Sequential Greedy approach with best partial solution tracking.
293
+
294
+ Applies strategies one at a time in user-defined order, but returns the best partial solution
295
+ if a complete solution cannot be found. Every state left by a strategy is a
296
+ candidate, including those between two strategies of the same violation type.
297
+
298
+ If a strategy makes the power flow diverge, it is undone (including everything it
299
+ did before diverging) and the next strategy is tried, so a diverging strategy
300
+ never leaves the network in an unsolved state. The divergence is reported in the
301
+ results. Because undoing restores a saved copy of the network, the engine's
302
+ `network` may be a different object after `run()` than before.
303
+
304
+ Returns:
305
+ Tuple[bool, Dict[str, Any]]: A tuple containing:
306
+ - Success flag (bool): True if all constraints were completely resolved.
307
+ - Results dictionary (Dict[str, Any]): Details on violations, actions taken, and costs.
308
+ `diverged` tells whether a power flow diverged along the way, and
309
+ `divergence_events` lists those divergences. A run can both diverge and
310
+ succeed, when another strategy resolved the violations. A run that ends
311
+ unsuccessfully with `diverged` False found no strategy able to do more,
312
+ or reached `max_iterations`. `iterations` is the number of passes made.
313
+ An unsuccessful run returns its best partial solution: the state with
314
+ the fewest violations, then the cheapest, then the one with the least
315
+ severe violations.
316
+
317
+ Raises:
318
+ MissingUnitCostError: If `unit_costs` lacks a price, either one the strategies
319
+ are known to need, which stops the run before it starts, or one that an
320
+ action turns out to need along the way.
321
+ Exception: Whatever a strategy raises, other than a power flow divergence.
322
+ The run stops there, with no results. Like a missing price met along
323
+ the way, it leaves the engine, `applied_actions` and `total_cost` in
324
+ the last solved state of the run: the one the failing strategy
325
+ started from, or, if it failed while the strategies of a violation
326
+ type were being compared (`strategy_choice="lookahead"`), the one
327
+ that comparison started from.
328
+ PowerFlowNotConverged: If the initial power flow diverges, as there is then no
329
+ partial solution to return.
330
+
331
+ The strategies hold the cost model of the run as their `cost_model` while it
332
+ runs, to choose between their own options with, and, in a run with a cost
333
+ model, the state of the lines and of the transformers as it started as their
334
+ `line_origins` and `transformer_origins`, to price them as the run charges
335
+ them. They hold the powers of the loads and
336
+ generators as the run started as their `initial_power`, from which the
337
+ limits of flexibility count. They get their own back when it ends.
338
+ """
339
+ strategies = self.strategy_registry.get_all_strategies()
340
+ with _lent_to(
341
+ strategies,
342
+ cost_model=self.cost_model,
343
+ line_origins=None,
344
+ transformer_origins=None,
345
+ initial_power=None,
346
+ ):
347
+ return self._run(strategies)
348
+
349
+ def _run(
350
+ self, strategies: set["EnhancementStrategy"]
351
+ ) -> tuple[bool, dict[str, Any]]:
352
+ """`run`, with the strategies holding the cost model of the run."""
353
+ if self.cost_model:
354
+ self.cost_model.check_prices(
355
+ key
356
+ for strategy in strategies
357
+ for key in strategy.required_unit_costs(self.pf_engine)
358
+ )
359
+ unpriced = self.cost_model.missing_prices(
360
+ key
361
+ for strategy in strategies
362
+ for key in strategy.possible_unit_costs(self.pf_engine)
363
+ )
364
+ if unpriced:
365
+ untyped = any(price.endswith("[None]") for price in unpriced)
366
+ self.logger.warning(
367
+ "No unit cost for some types in place on the network: "
368
+ f"{', '.join(unpriced)}. The run stops with a missing price if a "
369
+ "strategy adds a conductor or a unit of one of them in parallel."
370
+ + (
371
+ " The type None is that of the elements that have no type, "
372
+ "like a line or a transformer created from its parameters."
373
+ if untyped
374
+ else ""
375
+ )
376
+ )
377
+
378
+ iteration = 0
379
+ self.applied_actions = []
380
+ self.total_cost = 0.0
381
+ self.history = []
382
+ self.divergence_events = []
383
+ self._divergences_in_history = 0
384
+ self._unaddressed_types = set()
385
+ self._pass = 0
386
+ self._cost_tie = 0.0
387
+
388
+ self.logger.info(
389
+ "Starting grid enhancement algorithm (Sequential Greedy with Best Partial Solution)"
390
+ )
391
+ success = False
392
+
393
+ # Initial power flow. If it diverges there is no state with valid results to fall
394
+ # back on, so the run cannot produce a partial solution.
395
+ try:
396
+ self.pf_engine.run_power_flow()
397
+ except PowerFlowNotConverged as exc:
398
+ self._record_divergence(None, None, exc)
399
+ self.logger.error(
400
+ f"Initial power flow did not converge, nothing can be enhanced: {exc}"
401
+ )
402
+ raise PowerFlowNotConverged(
403
+ f"The initial power flow did not converge, so there is no partial solution "
404
+ f"to return: {exc}"
405
+ ) from exc
406
+
407
+ # Capture initial load and generation statistics
408
+ self.initial_total_load_mw = 0.0
409
+ self.initial_flexible_load_mw = 0.0
410
+ self.initial_total_gen_mw = 0.0
411
+ try:
412
+ loads_df = self.pf_engine.get_flexibility_data("load")
413
+ if not loads_df.empty:
414
+ self.initial_total_load_mw = loads_df["p_mw"].sum()
415
+ if "max_flex_pct" in loads_df.columns:
416
+ self.initial_flexible_load_mw = (
417
+ loads_df["p_mw"] * loads_df["max_flex_pct"] / 100.0
418
+ ).sum()
419
+
420
+ sgens_df = self.pf_engine.get_flexibility_data("sgen")
421
+ if not sgens_df.empty:
422
+ self.initial_total_gen_mw = sgens_df["p_mw"].sum()
423
+ except Exception:
424
+ self.logger.warning("Could not capture initial load/generation statistics.")
425
+
426
+ initial_violations = self.pf_engine.check_violations()
427
+ self._cost_tie = self._cost_tie_of_the_state()
428
+
429
+ # The powers the limits of flexibility count from, for every call of the run
430
+ # and whatever chain of strategies is tried and undone along the way. Lent as
431
+ # a copy shared by the strategies, as `line_origins`
432
+ initial_power = self._initial_power_of_the_run()
433
+ for strategy in strategies:
434
+ strategy.initial_power = initial_power
435
+
436
+ self._origins = (
437
+ self._origins_of_the_run() if self.cost_model is not None else {}
438
+ )
439
+ if self.cost_model is not None:
440
+ # The state the run charges each line and transformer upgrade from,
441
+ # whatever chain of strategies is tried and undone along the way:
442
+ # complete from here on and never added to, lent as a copy, so that a
443
+ # strategy and the algorithm can be copied or pickled during the run and a
444
+ # strategy cannot alter the algorithm's own
445
+ for kind in _CHARGED_FROM_ORIGIN:
446
+ origins = dict(self._origins[kind.upgrades])
447
+ for strategy in strategies:
448
+ setattr(strategy, kind.attribute, origins)
449
+ lookahead = self.cost_model is not None and self.strategy_choice == "lookahead"
450
+ # The state to start again from, should the run have to be checked against
451
+ # the choice of "first" (below)
452
+ initial = self._take_snapshot() if lookahead and initial_violations else None
453
+ self._rollout_cut_short = False
454
+ self._left_first_choice = False
455
+
456
+ success, iteration = self._run_passes(initial_violations)
457
+
458
+ if initial is not None and self._rollout_cut_short and self._left_first_choice:
459
+ success, iteration = self._keep_the_better_of_first(
460
+ initial, initial_violations, success, iteration
461
+ )
462
+
463
+ if self.divergence_events:
464
+ self.logger.warning(
465
+ f"Power flow diverged {len(self.divergence_events)} time(s) during the run; "
466
+ f"the strategies concerned were undone."
467
+ )
468
+
469
+ # Prepare results
470
+ remaining_violations = self.pf_engine.check_violations()
471
+
472
+ summary_stats = self._calculate_summary_stats(remaining_violations)
473
+ self._log_summary(summary_stats)
474
+
475
+ results = {
476
+ "success": success,
477
+ "iterations": iteration,
478
+ "actions_applied": self.applied_actions,
479
+ "total_cost": self.total_cost,
480
+ "remaining_violations": remaining_violations,
481
+ "best_partial_solution": {
482
+ "violation_count": len(remaining_violations),
483
+ },
484
+ "diverged": bool(self.divergence_events),
485
+ "divergence_events": self.divergence_events,
486
+ "summary": summary_stats,
487
+ "history": self.history,
488
+ }
489
+
490
+ return success, results
491
+
492
+ def _run_passes(
493
+ self, initial_violations: list[ConstraintViolation]
494
+ ) -> tuple[bool, int]:
495
+ """
496
+ Run the passes of the algorithm from the current state, the initial one, and
497
+ leave the engine in the state the run returns: the solution, or the best
498
+ partial one.
499
+
500
+ Returns:
501
+ Whether all violations are resolved, and the number of passes made.
502
+ """
503
+ iteration = 0
504
+ success = False
505
+ self.applied_actions = []
506
+ self.total_cost = 0.0
507
+ self.history = []
508
+ self.divergence_events = []
509
+ self._divergences_in_history = 0
510
+ self._pass = 0
511
+ self._pass_state = None
512
+ self._turns_given_again = 0
513
+
514
+ self._record_history(0, "Initial State", initial_violations)
515
+
516
+ # Initialize best solution with initial state. The state each strategy leaves
517
+ # is then rated against it, in `_apply_strategy_chain`.
518
+ score = self._score(initial_violations)
519
+ self._best = _BestState(
520
+ score, self._take_snapshot(), keep=True, anchor=score[1]
521
+ )
522
+
523
+ # The network's power-flow results are already current at this point (from the
524
+ # initial run above). Each loop iteration below keeps them current too, so
525
+ # there's no need to re-run power flow when entering a new iteration.
526
+ violations = initial_violations
527
+
528
+ stuck = False
529
+ while True:
530
+ # Step 1: If no violations, we're done, whatever the passes left
531
+ if not violations:
532
+ self.logger.info(
533
+ f"No violations detected. Algorithm completed successfully after {iteration} passes"
534
+ )
535
+ success = True
536
+ self._record_history(iteration, "Success", [])
537
+ break
538
+ if iteration >= self.max_iterations:
539
+ break
540
+
541
+ # One pass addresses each violation type of the priority order once, and
542
+ # again a type of which a later turn brings violations about
543
+ iteration += 1
544
+ self._pass = iteration
545
+ self.logger.info(f"Pass {iteration}/{self.max_iterations}")
546
+
547
+ # Step 2: Group violations by type
548
+ violation_groups = self._group_violations(violations)
549
+ self.logger.info(f"Grid State : {_format_grid_state(violations)}")
550
+
551
+ # Step 3: Try to resolve each type of violation with appropriate strategies,
552
+ # in the priority order, and again those of a type whose turn has passed
553
+ # if a later turn brings some about (see `_turns`)
554
+ action_applied = False
555
+ self._pass_state = turns = _Pass(violations)
556
+ for violation_type, again in self._turns(turns):
557
+ group = violation_groups.get(violation_type, [])
558
+ if len(group) > 0:
559
+ if again:
560
+ self._turns_given_again += 1
561
+ self.logger.info(
562
+ f"Turn of {violation_type} again in pass {iteration}: a "
563
+ f"later turn brought about some of its violations"
564
+ )
565
+ # We track if ANY strategy was applied in this iteration
566
+ type_action_applied = self._apply_strategies_for_violation_type(
567
+ violation_type, group
568
+ )
569
+ if type_action_applied:
570
+ action_applied = True
571
+
572
+ # If a strategy was applied, refresh the violation list to reflect
573
+ # its effect. `_apply_strategies_for_violation_type` already re-ran
574
+ # power flow right after the last successful action, so the
575
+ # network's results are already current — no need to solve again.
576
+ if type_action_applied:
577
+ violations = self.pf_engine.check_violations()
578
+ turns.violations = violations
579
+
580
+ # Record history after action
581
+ self._record_history(
582
+ iteration,
583
+ f"Applied strategy for {violation_type}"
584
+ + (" again" if again else ""),
585
+ violations,
586
+ )
587
+
588
+ if not violations:
589
+ self.logger.info(
590
+ f"All violations resolved after addressing {violation_type} violations"
591
+ )
592
+ success = True
593
+ break
594
+
595
+ # If we still have violations, regroup them for the next violation type
596
+ violation_groups = self._group_violations(violations)
597
+ turns.end_turn(violation_type)
598
+
599
+ # If no strategy could be applied for any violation type, we're stuck
600
+ if not action_applied:
601
+ self.logger.warning(
602
+ "No suitable strategy found for any violation type. Using best partial solution found."
603
+ )
604
+ self._record_history(
605
+ iteration,
606
+ self._with_divergences("No strategy found"),
607
+ violations,
608
+ )
609
+ stuck = True
610
+ break
611
+ # If we've resolved all violations, we're done
612
+ if success:
613
+ break
614
+
615
+ # Check if we reached the maximum iterations
616
+ if iteration >= self.max_iterations and not success and not stuck:
617
+ self.logger.warning(
618
+ f"Maximum iterations ({self.max_iterations}) reached without resolving all violations. "
619
+ f"Using best partial solution found."
620
+ )
621
+ # A divergence after the last entry of this pass would otherwise be in no entry
622
+ if len(self.divergence_events) > self._divergences_in_history:
623
+ self._record_history(
624
+ iteration,
625
+ self._with_divergences("Maximum iterations reached"),
626
+ violations,
627
+ )
628
+
629
+ # If we didn't find a full solution, use the best partial solution
630
+ if not success:
631
+ self.logger.info(
632
+ f"Using best partial solution with {self._best.score[0]} remaining violations "
633
+ )
634
+ self._restore_snapshot(self._best.snapshot)
635
+
636
+ self._pass_state = None
637
+ return success, iteration
638
+
639
+ def _keep_the_better_of_first(
640
+ self,
641
+ initial: _StateSnapshot,
642
+ initial_violations: list[ConstraintViolation],
643
+ success: bool,
644
+ iteration: int,
645
+ ) -> tuple[bool, int]:
646
+ """
647
+ Run again with `strategy_choice="first"` and keep the better of the two runs.
648
+
649
+ Lookahead rates a choice by a run that is given up after a pass without
650
+ improvement. Where it then left the choice of "first", "first" may have done
651
+ better over the passes the rating did not follow: only running it tells. The
652
+ run with the fewest violations, then the cheapest, is kept, lookahead's if
653
+ they are equal.
654
+
655
+ Returns:
656
+ Whether all violations are resolved, and the number of passes made, for
657
+ the run kept.
658
+ """
659
+ lookahead_state = _StateSnapshot(
660
+ network=self.pf_engine.network,
661
+ latest_results=self.pf_engine.latest_results,
662
+ applied_actions=self.applied_actions,
663
+ total_cost=self.total_cost,
664
+ )
665
+ lookahead_run = (
666
+ success,
667
+ iteration,
668
+ self.history,
669
+ self.divergence_events,
670
+ self._divergences_in_history,
671
+ self._turns_given_again,
672
+ )
673
+ lookahead_key = (len(self.pf_engine.check_violations()), self.total_cost)
674
+
675
+ self.logger.info(
676
+ "The choice between strategies was rated by runs cut short: checking it "
677
+ 'against a run with strategy_choice="first"'
678
+ )
679
+ self._restore_snapshot(initial)
680
+ choice, self.strategy_choice = self.strategy_choice, "first"
681
+ try:
682
+ first_success, first_iteration = self._run_passes(initial_violations)
683
+ except Exception as exc:
684
+ # The run of "first" goes further than the ratings did, and can meet what
685
+ # they did not, like a missing price: it is only a check, and the run of
686
+ # lookahead, which has ended, is kept
687
+ self.logger.warning(
688
+ f'The run with strategy_choice="first" that checks the choice failed '
689
+ f"({type(exc).__name__}: {exc}): the run of lookahead is kept"
690
+ )
691
+ first_key = None
692
+ except BaseException:
693
+ # Interrupted: the run of lookahead stands as the state left
694
+ self._restore_snapshot(lookahead_state)
695
+ (_, _, self.history, self.divergence_events, _, _) = lookahead_run
696
+ self._divergences_in_history = lookahead_run[4]
697
+ self._turns_given_again = lookahead_run[5]
698
+ raise
699
+ else:
700
+ first_key = (len(self.pf_engine.check_violations()), self.total_cost)
701
+ finally:
702
+ self.strategy_choice = choice
703
+
704
+ if first_key is not None and _ranks_before(
705
+ first_key, lookahead_key, self._cost_tie
706
+ ):
707
+ self.logger.info(
708
+ f'Keeping the run with strategy_choice="first": {first_key[0]} '
709
+ f"violation(s) costing {first_key[1]:.2f}, against {lookahead_key[0]} "
710
+ f"costing {lookahead_key[1]:.2f}"
711
+ )
712
+ return first_success, first_iteration
713
+ self._restore_snapshot(lookahead_state)
714
+ (
715
+ success,
716
+ iteration,
717
+ self.history,
718
+ self.divergence_events,
719
+ self._divergences_in_history,
720
+ self._turns_given_again,
721
+ ) = lookahead_run
722
+ return success, iteration
723
+
724
+ def _score(self, violations: list[ConstraintViolation]) -> tuple[int, float, float]:
725
+ """
726
+ Rate the current state, the lower the better: number of violations, cost, then
727
+ severity, the sum of the relative excesses of the violations (see
728
+ `_relative_excess`).
729
+ """
730
+ severity = sum(_relative_excess(v) for v in violations)
731
+ return len(violations), self.total_cost, severity
732
+
733
+ @staticmethod
734
+ def _is_better(
735
+ score: tuple[int, float, float],
736
+ best: tuple[int, float, float],
737
+ tie: float = 0.0,
738
+ anchor: float | None = None,
739
+ ) -> bool:
740
+ """
741
+ Tell whether a state rated `score` beats the best one so far.
742
+
743
+ Fewer violations win. With as many, the cheaper state wins, so that spending
744
+ that resolves no violation is not kept. Severity only decides between states of
745
+ the same cost, like those of a run without a cost model.
746
+
747
+ Costs that differ by no more than `tie` are the same (see
748
+ `_cost_tie_of_the_state`). A state cheaper than the best one by more than the
749
+ tie wins. Otherwise its cost is compared with `anchor`, the cost of the state
750
+ that the best one tied with when it was kept (its own cost if None): a series
751
+ of states each a little dearer than the one before, and less severe, replaces
752
+ the best one only as long as it stays within the tie of the first.
753
+ """
754
+ count, cost, severity = score
755
+ best_count, best_cost, best_severity = best
756
+ if count != best_count:
757
+ return count < best_count
758
+ if cost < best_cost - tie:
759
+ return True
760
+ reference = best_cost if anchor is None else anchor
761
+ if abs(cost - reference) > tie:
762
+ return cost < reference
763
+ return severity < best_severity - 1e-9
764
+
765
+ def _cost_tie_of_the_state(self) -> float:
766
+ """
767
+ The difference of cost under which two states are equally cheap, for the
768
+ current state: the price of the power that its power flow does not resolve,
769
+ the largest mismatch it can leave at a bus (`PowerFlowEngine.unresolved_power_mva`),
770
+ at the dearer of the prices of flexibility, once for every flexibility step of
771
+ the state. Each step is sized on a power flow that leaves that much power
772
+ unresolved, and its cost is uncertain by as much: two states with the same
773
+ powers, reached by different steps, can differ in cost by up to the sum (8.7e-8
774
+ €, 1.5e-13 relative, between two chains of a run of the MV/LV case study).
775
+ After the Newton step of `PandaPowerEngine` the power is the rounding floor of
776
+ the power balance, the same for a state reached warm or cold, and the tie of the
777
+ runs of 90 feeders of the case study at 30 % of flexibility 1.3e-6 to 8.9e-3 €.
778
+ Where an engine takes no such step, the power is the solver's tolerance: 0.01 €
779
+ a step at 1e-8, 100 MVA and 10,000 €/MW. The tie is in the unit of the prices,
780
+ whatever it is. A run takes the largest over its states, as each comparison
781
+ involves states rated before it.
782
+
783
+ 0 without a cost model, without a price of flexibility, or when the engine does
784
+ not tell its mismatch: the costs are then compared as they are, which their
785
+ sums allow (see `_cost_of_the_actions`).
786
+ """
787
+ if self.cost_model is None:
788
+ return 0.0
789
+ try:
790
+ mismatch = self.pf_engine.unresolved_power_mva()
791
+ except (AttributeError, NotImplementedError):
792
+ return 0.0
793
+ if not mismatch or not math.isfinite(mismatch):
794
+ return 0.0
795
+ prices = []
796
+ for key in ("load_shedding", "generation_curtailment"):
797
+ try:
798
+ price = self.cost_model.find_price(key)
799
+ except InvalidUnitCostError:
800
+ continue
801
+ if price is not None:
802
+ prices.append(price)
803
+ steps = sum(len(action.get("buses") or ()) for action in self.applied_actions)
804
+ return max(prices, default=0.0) * mismatch * max(1, steps)
805
+
806
+ def _cost_of_the_actions(self) -> float:
807
+ """
808
+ The total cost of the actions applied, summed exactly (`math.fsum`): the same
809
+ actions cost the same, whatever the order they were applied and undone in.
810
+ """
811
+ return math.fsum(action.get("cost", 0.0) for action in self.applied_actions)
812
+
813
+ def _rate_state(
814
+ self, violations: list[ConstraintViolation], trackers: tuple[_BestState, ...]
815
+ ) -> None:
816
+ """
817
+ Rate the current state, whose violations are given, for each of the trackers:
818
+ it becomes the best state of those it beats.
819
+ """
820
+ if not trackers:
821
+ return
822
+ self._cost_tie = max(self._cost_tie, self._cost_tie_of_the_state())
823
+ score = self._score(violations)
824
+ for tracker in trackers:
825
+ if tracker.score is not None and not self._is_better(
826
+ score, tracker.score, self._cost_tie, tracker.anchor
827
+ ):
828
+ continue
829
+ if tracker is self._best:
830
+ self._log_better_partial_solution(score)
831
+ if (
832
+ tracker.score is None
833
+ or tracker.anchor is None
834
+ or score[0] != tracker.score[0]
835
+ or score[1] < tracker.score[1] - self._cost_tie
836
+ or abs(score[1] - tracker.anchor) > self._cost_tie
837
+ ):
838
+ # Kept for its cost or its violations, not for its severity in a tie
839
+ tracker.anchor = score[1]
840
+ tracker.score = score
841
+ if tracker.keep and violations:
842
+ tracker.snapshot = self._take_snapshot()
843
+
844
+ def _log_better_partial_solution(self, score: tuple[int, float, float]) -> None:
845
+ best = self._best.score
846
+ self.logger.info(
847
+ f"Found better partial solution: {score[0]} violations costing "
848
+ f"{score[1]:.2f} (was {best[0]} costing {best[1]:.2f})"
849
+ )
850
+
851
+ def _record_history(
852
+ self, iteration: int, description: str, violations: list[ConstraintViolation]
853
+ ):
854
+ """Record the current state of the algorithm."""
855
+ self.history.append(
856
+ {
857
+ "iteration": iteration,
858
+ "description": description,
859
+ "violations": copy.deepcopy(violations),
860
+ "actions": copy.deepcopy(self.applied_actions),
861
+ "total_cost": self.total_cost,
862
+ # Strategies undone because of a divergence since the previous entry
863
+ "divergence_events": copy.deepcopy(
864
+ self.divergence_events[self._divergences_in_history :]
865
+ ),
866
+ }
867
+ )
868
+ self._divergences_in_history = len(self.divergence_events)
869
+
870
+ def _with_divergences(self, description: str) -> str:
871
+ """Add to a history description the strategies undone since the previous entry."""
872
+ diverged = self.divergence_events[self._divergences_in_history :]
873
+ if not diverged:
874
+ return description
875
+ names = sorted({str(e["strategy_name"]) for e in diverged})
876
+ return f"{description} (power flow diverged after {', '.join(names)})"
877
+
878
+ def _record_divergence(
879
+ self,
880
+ violation_type: str | None,
881
+ strategy_name: str | None,
882
+ exc: Exception,
883
+ ) -> None:
884
+ """Record a power flow divergence in the results of the run."""
885
+ self.divergence_events.append(
886
+ {
887
+ "violation_type": violation_type,
888
+ "strategy_name": strategy_name,
889
+ "message": str(exc),
890
+ }
891
+ )
892
+
893
+ def _drop_divergences_already_reported(
894
+ self, since: int, reported: set[tuple[Any, Any]]
895
+ ) -> set[tuple[Any, Any]]:
896
+ """
897
+ Drop, from the divergence events recorded from index `since` on, those of a
898
+ violation type and strategy in `reported`.
899
+
900
+ Returns:
901
+ The violation type and strategy of the events left.
902
+ """
903
+ events = [
904
+ event
905
+ for event in self.divergence_events[since:]
906
+ if (event["violation_type"], event["strategy_name"]) not in reported
907
+ ]
908
+ self.divergence_events[since:] = events
909
+ return {(event["violation_type"], event["strategy_name"]) for event in events}
910
+
911
+ def _take_snapshot(self) -> _StateSnapshot:
912
+ """Save the current state of the enhancement process, to restore it later."""
913
+ return _StateSnapshot(
914
+ network=copy.deepcopy(self.pf_engine.network),
915
+ latest_results=copy.copy(self.pf_engine.latest_results),
916
+ applied_actions=copy.deepcopy(self.applied_actions),
917
+ total_cost=self.total_cost,
918
+ )
919
+
920
+ def _restore_snapshot(self, snapshot: _StateSnapshot) -> None:
921
+ """Bring the enhancement process back to a state saved by `_take_snapshot`."""
922
+ self.pf_engine.network = snapshot.network
923
+ # The cached partition may describe lines or transformers added since
924
+ self.pf_engine.network_partition = None
925
+ self.pf_engine.latest_results = snapshot.latest_results
926
+ self.applied_actions = snapshot.applied_actions
927
+ self.total_cost = snapshot.total_cost
928
+
929
+ def _calculate_summary_stats(self, remaining_violations) -> dict[str, Any]:
930
+ """Calculate summary statistics of the applied actions."""
931
+ stats = {
932
+ "transformers_upgraded": 0,
933
+ "transformers_added": 0,
934
+ "total_transformer_power_added_upgrade": 0.0,
935
+ "total_transformer_power_added_parallel": 0.0,
936
+ "tap_position_changes": 0,
937
+ "total_load_shed": 0.0,
938
+ "load_shed_share_total": 0.0,
939
+ "load_shed_share_flexible": 0.0,
940
+ "total_generation_curtailed": 0.0,
941
+ "generation_curtailed_share": 0.0,
942
+ "lines_upgraded": 0,
943
+ "lines_added": 0,
944
+ "total_line_length_upgraded": 0.0,
945
+ "total_line_length_added": 0.0,
946
+ "total_cost": self.total_cost,
947
+ "power_flow_divergences": len(self.divergence_events),
948
+ }
949
+
950
+ stats["transformer_violations"] = len(
951
+ [
952
+ c
953
+ for c in remaining_violations
954
+ if c.constraint_type == ConstraintType.TRANSFORMER_LOADING
955
+ ]
956
+ )
957
+ stats["line_violations"] = len(
958
+ [
959
+ c
960
+ for c in remaining_violations
961
+ if c.constraint_type == ConstraintType.LINE_LOADING
962
+ ]
963
+ )
964
+ stats["under_voltage_violations"] = len(
965
+ [
966
+ c
967
+ for c in remaining_violations
968
+ if c.constraint_type == ConstraintType.UNDER_VOLTAGE
969
+ ]
970
+ )
971
+ stats["over_voltage_violations"] = len(
972
+ [
973
+ c
974
+ for c in remaining_violations
975
+ if c.constraint_type == ConstraintType.OVER_VOLTAGE
976
+ ]
977
+ )
978
+
979
+ # A line or a transformer whose type changes in several steps is one upgrade
980
+ upgraded_lines: dict[str, float] = {}
981
+ upgraded_transformers: set[str] = set()
982
+
983
+ for action in self.applied_actions:
984
+ action_type = action.get("type")
985
+
986
+ if action_type == "line_upgrade":
987
+ lines = action.get("lines", [])
988
+ for line in lines:
989
+ if line.get("parallel_count", 0) > 0:
990
+ # Each conductor added is a new line
991
+ stats["lines_added"] += 1
992
+ stats["total_line_length_added"] += line.get("length", 0.0)
993
+ else:
994
+ upgraded_lines[line.get("line_id")] = line.get("length", 0.0)
995
+ # A type change that takes back conductors added earlier in
996
+ # its action: they are not laid
997
+ removed = int(line.get("conductors_removed") or 0)
998
+ stats["lines_added"] -= removed
999
+ stats["total_line_length_added"] -= removed * line.get(
1000
+ "length", 0.0
1001
+ )
1002
+
1003
+ elif action_type == "transformer_upgrade":
1004
+ trafos = action.get("transformers", [])
1005
+ for trafo in trafos:
1006
+ parallel_count = trafo.get("parallel_count", 0)
1007
+ if parallel_count > 0:
1008
+ stats["transformers_added"] += 1
1009
+ else:
1010
+ upgraded_transformers.add(trafo.get("transformer_id"))
1011
+
1012
+ power = self._transformer_power_added(trafo)
1013
+ if power is not None:
1014
+ if parallel_count > 0:
1015
+ stats["total_transformer_power_added_parallel"] += power
1016
+ else:
1017
+ stats["total_transformer_power_added_upgrade"] += power
1018
+
1019
+ elif action_type == "tap_change":
1020
+ trafos = action.get("transformers", [])
1021
+ stats["tap_position_changes"] += len(trafos)
1022
+
1023
+ elif action_type == "flexibility_management":
1024
+ for bus_mod in action.get("buses", []):
1025
+ delta = bus_mod.get("old_power", 0) - bus_mod.get("new_power", 0)
1026
+ if bus_mod.get("action_type") == "load_shedding":
1027
+ stats["total_load_shed"] += delta
1028
+ elif bus_mod.get("action_type") == "gen_curtailment":
1029
+ stats["total_generation_curtailed"] += delta
1030
+
1031
+ stats["lines_upgraded"] = len(upgraded_lines)
1032
+ stats["total_line_length_upgraded"] = sum(upgraded_lines.values())
1033
+ stats["transformers_upgraded"] = len(upgraded_transformers)
1034
+
1035
+ # Calculate shares
1036
+ if stats["total_load_shed"] > 0:
1037
+ if (
1038
+ hasattr(self, "initial_total_load_mw")
1039
+ and self.initial_total_load_mw > 0
1040
+ ):
1041
+ stats["load_shed_share_total"] = (
1042
+ stats["total_load_shed"] / self.initial_total_load_mw
1043
+ ) * 100
1044
+ if (
1045
+ hasattr(self, "initial_flexible_load_mw")
1046
+ and self.initial_flexible_load_mw > 0
1047
+ ):
1048
+ stats["load_shed_share_flexible"] = (
1049
+ stats["total_load_shed"] / self.initial_flexible_load_mw
1050
+ ) * 100
1051
+
1052
+ if stats["total_generation_curtailed"] > 0:
1053
+ if hasattr(self, "initial_total_gen_mw") and self.initial_total_gen_mw > 0:
1054
+ stats["generation_curtailed_share"] = (
1055
+ stats["total_generation_curtailed"] / self.initial_total_gen_mw
1056
+ ) * 100
1057
+
1058
+ return stats
1059
+
1060
+ def _transformer_power_added(self, trafo: dict[str, Any]) -> float | None:
1061
+ """
1062
+ The power (MVA) that one upgrade of a transformer adds to its rating, None if
1063
+ it cannot be told.
1064
+
1065
+ A unit added in parallel adds the rating of a unit in place, which the upgrade
1066
+ records as `old_rating` (VA, as the transformer table holds it: a unit without
1067
+ a catalogued type has no other). A type change replaces every unit
1068
+ (`units`), and adds the difference between the rating of the new type and
1069
+ `old_rating`. The sum over the upgrades of a transformer is then the rating it
1070
+ has at the end of the run less the one it had at the start, whatever the
1071
+ number of steps: each step adds what separates its state from the previous
1072
+ one.
1073
+
1074
+ An upgrade that has no `old_rating`, written by an older version or by
1075
+ another package's strategy, is read from the catalogue as before: from its
1076
+ `old_type` and `new_type`, which it must both have.
1077
+ """
1078
+ old_rating = trafo.get("old_rating")
1079
+ old_type = trafo.get("old_type")
1080
+ new_type = trafo.get("new_type")
1081
+ try:
1082
+ if old_rating is None:
1083
+ if not (old_type and new_type):
1084
+ return None
1085
+ old_rating = self.pf_engine.get_transformer_max_power(old_type)
1086
+ new_rating = self.pf_engine.get_transformer_max_power(new_type)
1087
+ if trafo.get("parallel_count", 0) > 0:
1088
+ # Convert VA to MVA
1089
+ return new_rating / 1e6
1090
+ elif trafo.get("parallel_count", 0) > 0:
1091
+ # A unit added in parallel is of the kind in place
1092
+ return float(old_rating) / 1e6
1093
+ else:
1094
+ new_rating = self.pf_engine.get_transformer_max_power(new_type)
1095
+ # Every unit of the transformer is replaced
1096
+ units = max(1, int(trafo.get("units") or 1))
1097
+ return units * (new_rating - float(old_rating)) / 1e6
1098
+ except Exception:
1099
+ return None
1100
+
1101
+ def _log_summary(self, stats: dict[str, Any]):
1102
+ """Log a high-level summary of the modifications applied."""
1103
+ summary = ["Grid Enhancement Summary:"]
1104
+
1105
+ if stats["lines_upgraded"] > 0:
1106
+ summary.append(f"- Lines Upgraded: {stats['lines_upgraded']}")
1107
+ summary.append(
1108
+ f" - Total Length: {stats['total_line_length_upgraded']:.2f} km"
1109
+ )
1110
+
1111
+ if stats["lines_added"] > 0:
1112
+ summary.append(f"- Lines Added (Parallel): {stats['lines_added']}")
1113
+ summary.append(
1114
+ f" - Total Length: {stats['total_line_length_added']:.2f} km"
1115
+ )
1116
+
1117
+ if stats["transformers_upgraded"] > 0:
1118
+ summary.append(f"- Transformers Upgraded: {stats['transformers_upgraded']}")
1119
+ summary.append(
1120
+ f" - Total Power Added: {stats['total_transformer_power_added_upgrade']:.2f} MVA"
1121
+ )
1122
+
1123
+ if stats["transformers_added"] > 0:
1124
+ summary.append(
1125
+ f"- Transformers Added (Parallel): {stats['transformers_added']}"
1126
+ )
1127
+ summary.append(
1128
+ f" - Total Power Added: {stats['total_transformer_power_added_parallel']:.2f} MVA"
1129
+ )
1130
+
1131
+ if stats["tap_position_changes"] > 0:
1132
+ summary.append(
1133
+ f"- Transformer Tap Changes: {stats['tap_position_changes']}"
1134
+ )
1135
+
1136
+ if stats["total_load_shed"] > 0:
1137
+ summary.append(f"- Load Shed: {stats['total_load_shed']:.6f} MW")
1138
+ if stats["load_shed_share_total"] > 0:
1139
+ summary.append(
1140
+ f" - vs Total Load: {self.initial_total_load_mw:.6f} MW ({stats['load_shed_share_total']:.2f}%)"
1141
+ )
1142
+ if stats["load_shed_share_flexible"] > 0:
1143
+ summary.append(
1144
+ f" - vs Total Flexible Load: {self.initial_flexible_load_mw:.6f} MW ({stats['load_shed_share_flexible']:.2f}%)"
1145
+ )
1146
+
1147
+ if stats["total_generation_curtailed"] > 0:
1148
+ summary.append(
1149
+ f"- Generation Curtailed: {stats['total_generation_curtailed']:.2f} MW"
1150
+ )
1151
+ if stats["generation_curtailed_share"] > 0:
1152
+ summary.append(
1153
+ f" - vs Total Generation: {self.initial_total_gen_mw:.6f} MW ({stats['generation_curtailed_share']:.2f}%)"
1154
+ )
1155
+
1156
+ summary.append(f"- Total Cost: {stats['total_cost']:.2f}")
1157
+
1158
+ for line in summary:
1159
+ self.logger.info(line)
1160
+
1161
+ def _group_violations(
1162
+ self, violations: list[ConstraintViolation]
1163
+ ) -> dict[ConstraintType, list[ConstraintViolation]]:
1164
+ """
1165
+ Group violations by their type.
1166
+
1167
+ Args:
1168
+ violations: List of violations
1169
+
1170
+ Returns:
1171
+ Dictionary mapping violation types to lists of violations
1172
+ """
1173
+ violation_groups: dict[ConstraintType, list[ConstraintViolation]] = {
1174
+ c_type: [] for c_type in self.strategy_registry.violation_priority_order
1175
+ }
1176
+ for violation in violations:
1177
+ violation_type = violation.constraint_type
1178
+ if violation_type not in violation_groups:
1179
+ # Left out of the priority order, so deliberately not addressed: the
1180
+ # violations remain, and the run cannot succeed while they do.
1181
+ if violation_type not in self._unaddressed_types:
1182
+ self._unaddressed_types.add(violation_type)
1183
+ self.logger.warning(
1184
+ f"{violation_type.value} violations are not addressed, as the "
1185
+ f"priority order leaves this type out"
1186
+ )
1187
+ continue
1188
+ violation_groups[violation_type].append(violation)
1189
+ return violation_groups
1190
+
1191
+ def _turns(self, turns: _Pass) -> Iterator[tuple[ConstraintType, bool]]:
1192
+ """
1193
+ The turns of the rest of a pass, each a violation type, and whether it is the
1194
+ type's turn again.
1195
+
1196
+ A pass gives each type of the priority order its turn, in that order. A type
1197
+ whose turn has passed, and of which a violation is there that was not as its
1198
+ turn ended, brought about by a later turn, is given its turn once more, before
1199
+ the next type of the order: in the pass of the order alone, it would wait for
1200
+ the next pass, and a run with `max_iterations=1` would end with it (#66). Of
1201
+ several such types, the first in the order is given its turn first. A type is
1202
+ given its turn again at most once in a pass, so that a pass gives at most twice
1203
+ as many turns as there are types, whatever the turns bring about.
1204
+
1205
+ The one taking the turns keeps `turns.violations` current and calls
1206
+ `turns.end_turn` at the end of each turn, whether it applied anything or not.
1207
+ """
1208
+ order = self.strategy_registry.violation_priority_order
1209
+ while True:
1210
+ again = self._turn_due_again(turns)
1211
+ if again is not None:
1212
+ turns.again.add(again)
1213
+ yield again, True
1214
+ elif turns.position + 1 < len(order):
1215
+ turns.position += 1
1216
+ yield order[turns.position], False
1217
+ else:
1218
+ return
1219
+
1220
+ def _turn_due_again(self, turns: _Pass) -> ConstraintType | None:
1221
+ """
1222
+ The first type, in the priority order, whose turn has passed in the pass of
1223
+ `turns`, has not been given again, and of which a violation is there that was
1224
+ not as its turn ended; None if there is none.
1225
+ """
1226
+ order = self.strategy_registry.violation_priority_order
1227
+ for violation_type in order[: turns.position + 1]:
1228
+ if violation_type in turns.again:
1229
+ continue
1230
+ ended_with = turns.ended_with.get(violation_type, set())
1231
+ if any(
1232
+ violation.constraint_type == violation_type
1233
+ and (violation.constraint_type, violation.element_id) not in ended_with
1234
+ for violation in turns.violations
1235
+ ):
1236
+ return violation_type
1237
+ return None
1238
+
1239
+ def _apply_strategies_for_violation_type(
1240
+ self, violation_type: str, violations: list[ConstraintViolation]
1241
+ ) -> bool:
1242
+ """
1243
+ Try to apply suitable strategies for the given violation type.
1244
+
1245
+ A strategy that makes the power flow diverge, or that returns no action, is undone
1246
+ and counts as not applied. On return, the network is always in a state where power
1247
+ flow has converged.
1248
+
1249
+ Args:
1250
+ violation_type: Type of violation to address
1251
+ violations: List of violations of this type
1252
+
1253
+ Returns:
1254
+ Boolean indicating if a strategy was applied successfully
1255
+ """
1256
+ self.logger.info(
1257
+ f"Trying to resolve {len(violations)} {violation_type} violations"
1258
+ )
1259
+
1260
+ # Get strategies applicable to this violation type, ordered by increasing cost
1261
+ strategies = self.strategy_registry.get_strategies_for_type(violation_type)
1262
+
1263
+ if not strategies:
1264
+ self.logger.warning(
1265
+ f"No strategies registered for violation type: {violation_type}"
1266
+ )
1267
+ return False
1268
+
1269
+ if (
1270
+ self.cost_model is None
1271
+ or self.strategy_choice == "first"
1272
+ or len(strategies) == 1
1273
+ ):
1274
+ applied = self._apply_strategy_chain(
1275
+ violation_type, violations, strategies, (self._best,)
1276
+ )
1277
+ else:
1278
+ applied = self._apply_best_strategy_chain(
1279
+ violation_type, violations, strategies
1280
+ )
1281
+
1282
+ if not applied:
1283
+ self.logger.warning(
1284
+ f"All strategies found for {violation_type} have been tried. {len(violations)} violation(s) remaining."
1285
+ )
1286
+ return bool(applied)
1287
+
1288
+ def _apply_best_strategy_chain(
1289
+ self,
1290
+ violation_type: str,
1291
+ violations: list[ConstraintViolation],
1292
+ strategies: list["EnhancementStrategy"],
1293
+ ) -> list[str]:
1294
+ """
1295
+ Apply the strategy chain that leads to the best end of the run.
1296
+
1297
+ The chains are those `_apply_strategy_chain` makes when starting from each of
1298
+ the strategies in turn: the first strategy and those after it, the second and
1299
+ those after it, and so on. Each is tried from the same state, and rated by the
1300
+ state `_finish_run_greedily` reaches from it: the fewest violations, then the
1301
+ cheapest, then the chain that starts earlier in the order of the strategies.
1302
+ The states the chain itself goes through are rated too, as they can be what
1303
+ the run returns. A chain that is cheaper on its own but makes the rest of the run dearer is thus
1304
+ not kept, nor a dearer strategy only because its cost level comes first. The
1305
+ chains not kept are undone, but their power flow divergences are still
1306
+ reported, once each: a strategy that diverges in a chain usually diverges
1307
+ again in the chains that start after it, which is the same divergence from
1308
+ the same state of the run.
1309
+
1310
+ Returns:
1311
+ The strategies applied by the chain kept, by name, empty if no chain
1312
+ applied any.
1313
+ """
1314
+ start = self._take_snapshot()
1315
+ try:
1316
+ return self._choose_strategy_chain(
1317
+ violation_type, violations, strategies, start
1318
+ )
1319
+ except BaseException:
1320
+ # A strategy failed with something else than a divergence, in a chain or
1321
+ # in the run that rates one: none of them is part of the run
1322
+ self._restore_snapshot(start)
1323
+ raise
1324
+
1325
+ def _choose_strategy_chain(
1326
+ self,
1327
+ violation_type: str,
1328
+ violations: list[ConstraintViolation],
1329
+ strategies: list["EnhancementStrategy"],
1330
+ start: _StateSnapshot,
1331
+ ) -> list[str]:
1332
+ """
1333
+ Do the work of `_apply_best_strategy_chain`, from the state saved in `start`.
1334
+ """
1335
+ # For each chain: the state it ends in, the strategies it applied, the best
1336
+ # state of its path, and the one that would become the partial solution of
1337
+ # the run, if any beats the current one
1338
+ chains: list[tuple[_StateSnapshot, list[str], _BestState, _BestState]] = []
1339
+ # Divergences the chains made so far, by violation type and strategy
1340
+ diverged: set[tuple[Any, Any]] = set()
1341
+ # The price error of the chain in the order of the cost levels, if it had one
1342
+ first_chain_error: Exception | None = None
1343
+ first = 0
1344
+ while first < len(strategies):
1345
+ if chains or first:
1346
+ self._restore_snapshot(copy.deepcopy(start))
1347
+ rating = _BestState()
1348
+ partial = _BestState(self._best.score, keep=True, anchor=self._best.anchor)
1349
+ events = len(self.divergence_events)
1350
+ try:
1351
+ applied = self._apply_strategy_chain(
1352
+ violation_type, violations, strategies[first:], (rating, partial)
1353
+ )
1354
+ except _PRICE_ERRORS as exc:
1355
+ # A chain that needs a price the cost model lacks is not open to the
1356
+ # run: the next one is tried
1357
+ del self.divergence_events[events:]
1358
+ self.logger.warning(
1359
+ f"Chain from {strategies[first].name} for {violation_type} "
1360
+ f"violations left out: {exc}"
1361
+ )
1362
+ if first == 0:
1363
+ first_chain_error = exc
1364
+ first += 1
1365
+ continue
1366
+ diverged |= self._drop_divergences_already_reported(events, diverged)
1367
+ if not applied:
1368
+ break
1369
+ chains.append(
1370
+ (self._take_snapshot(), [s.name for s in applied], rating, partial)
1371
+ )
1372
+ # A chain whose first strategy applied nothing is the next chain: start the
1373
+ # next chain after the first strategy that did apply something
1374
+ # (by identity: a strategy registered twice is two entries of the list)
1375
+ first += (
1376
+ next(i for i, s in enumerate(strategies[first:]) if s is applied[0]) + 1
1377
+ )
1378
+
1379
+ if not chains:
1380
+ self._restore_snapshot(start)
1381
+ if first_chain_error is not None:
1382
+ # No chain is open: the order of the cost levels fails as it would
1383
+ # without lookahead
1384
+ raise first_chain_error
1385
+ return []
1386
+
1387
+ kept = chains[0]
1388
+ if first_chain_error is not None:
1389
+ # The chain of the cost levels is not open: what is kept departs from it
1390
+ self._left_first_choice = True
1391
+ if len(chains) > 1:
1392
+ best: tuple[int, float] | None = None
1393
+ for chain in chains:
1394
+ self._restore_snapshot(copy.deepcopy(chain[0]))
1395
+ try:
1396
+ key = self._finish_run_greedily(violation_type, chain[2])
1397
+ except _PRICE_ERRORS as exc:
1398
+ # The rest of the run from this chain needs a price the cost
1399
+ # model lacks: rated last
1400
+ self.logger.warning(
1401
+ f"Chain {' + '.join(chain[1])} for {violation_type} violations "
1402
+ f"rated last, the run from it needs a price: {exc}"
1403
+ )
1404
+ key = (float("inf"), float("inf"))
1405
+ self.logger.info(
1406
+ f"Chain {' + '.join(chain[1])} for {violation_type} violations "
1407
+ f"leads to {key[0]} violation(s) costing {key[1]:.2f} in total"
1408
+ )
1409
+ if best is None or _ranks_before(key, best, self._cost_tie):
1410
+ best, kept = key, chain
1411
+ self.logger.info(
1412
+ f"Keeping {' + '.join(kept[1])} for {violation_type} violations"
1413
+ )
1414
+ if kept is not chains[0]:
1415
+ self._left_first_choice = True
1416
+ self._restore_snapshot(kept[0])
1417
+ # The states the chain kept went through are now states of the run
1418
+ partial = kept[3]
1419
+ if partial.snapshot is not None:
1420
+ self._log_better_partial_solution(partial.score)
1421
+ self._best.score, self._best.snapshot = partial.score, partial.snapshot
1422
+ self._best.anchor = partial.anchor
1423
+ return kept[1]
1424
+
1425
+ def _finish_run_greedily(
1426
+ self, violation_type: str, rating: _BestState
1427
+ ) -> tuple[int, float]:
1428
+ """
1429
+ Finish the run from the current state, as with `strategy_choice="first"`, to
1430
+ rate the state: the rest of the current pass after the turn of
1431
+ `violation_type`, with the turns it gives again (see `_turns`), then the
1432
+ passes left, as long as they improve the best state of the path.
1433
+
1434
+ The rollout stops after a full pass that has not improved that best state,
1435
+ with fewer violations or a lower cost. Going on to the last pass each time
1436
+ would make a run that does not resolve replay all the passes left at each of
1437
+ its passes. The price is that a path which needs several passes to remove a
1438
+ violation is rated by the state it had before them, not by where a run with
1439
+ `strategy_choice="first"` would take it: `_rollout_cut_short` records it, for
1440
+ `run()` to check the choices made against a run with "first".
1441
+
1442
+ The best state reached is rated as `run()` would return it: the number of
1443
+ violations, then the total cost. `rating` holds the best state of the path
1444
+ that led here, and follows the rest of it. Its power flow divergences are not
1445
+ reported. The caller restores the state it wants afterwards.
1446
+
1447
+ Returns:
1448
+ The number of violations left and the total cost of the best state of the
1449
+ path.
1450
+ """
1451
+ order = self.strategy_registry.violation_priority_order
1452
+ divergences = len(self.divergence_events)
1453
+ try:
1454
+ violations = self.pf_engine.check_violations()
1455
+ self._rate_state(violations, (rating,))
1456
+ # The rest of the pass under way, with the turns it gives again (see
1457
+ # `_turns`), as the run would give them after this chain
1458
+ if self._pass_state is not None:
1459
+ turns = self._pass_state.copy()
1460
+ else:
1461
+ position = order.index(violation_type)
1462
+ turns = _Pass([], position, again=set(order[: position + 1]))
1463
+ turns.violations = violations
1464
+ turns.end_turn(violation_type)
1465
+ passes = self._pass
1466
+ full_pass = False
1467
+ while violations:
1468
+ applied = False
1469
+ best_before = rating.score
1470
+ for vt, _ in self._turns(turns):
1471
+ group = [v for v in violations if v.constraint_type == vt]
1472
+ if group:
1473
+ strategies = self.strategy_registry.get_strategies_for_type(vt)
1474
+ if self._apply_strategy_chain(vt, group, strategies, (rating,)):
1475
+ applied = True
1476
+ violations = self.pf_engine.check_violations()
1477
+ turns.violations = violations
1478
+ if not violations:
1479
+ break
1480
+ turns.end_turn(vt)
1481
+ # A pass that applied nothing has not improved the best state either.
1482
+ # A lower severity alone is not an improvement here: passes that
1483
+ # shave an excess at no cost would otherwise go on to the last one.
1484
+ improved = applied and rating.score[:2] != best_before[:2]
1485
+ if full_pass and applied and not improved and violations:
1486
+ if passes < self.max_iterations:
1487
+ # Given up where a run would have gone on
1488
+ self._rollout_cut_short = True
1489
+ break
1490
+ if (full_pass and not improved) or passes >= self.max_iterations:
1491
+ break
1492
+ turns, full_pass = _Pass(violations), True
1493
+ passes += 1
1494
+ finally:
1495
+ # Also when a strategy fails: the divergences of a rollout are not the run's
1496
+ del self.divergence_events[divergences:]
1497
+ return rating.score[0], rating.score[1]
1498
+
1499
+ def _apply_strategy_chain(
1500
+ self,
1501
+ violation_type: str,
1502
+ violations: list[ConstraintViolation],
1503
+ strategies: list["EnhancementStrategy"],
1504
+ trackers: tuple[_BestState, ...] = (),
1505
+ ) -> list["EnhancementStrategy"]:
1506
+ """
1507
+ Apply the strategies in turn, each to the violations the previous ones left,
1508
+ until the violations of the type are resolved. The state each strategy leaves
1509
+ is rated for the `trackers`.
1510
+
1511
+ A strategy that makes the power flow diverge, or that returns no action, is
1512
+ undone and counts as not applied. On return, the network is in a state where
1513
+ power flow has converged.
1514
+ If a strategy raises anything else, it is undone as well, with the planning
1515
+ change that had its operation actions chosen again if it is one of those, and
1516
+ the exception is raised again.
1517
+
1518
+ Returns:
1519
+ The strategies applied, in order.
1520
+ """
1521
+ applied: list[EnhancementStrategy] = []
1522
+
1523
+ # Try each strategy in order until one works
1524
+ for strategy in strategies:
1525
+ self.logger.info(f"Trying strategy: {strategy.name}")
1526
+
1527
+ # The power flow can diverge in the strategy's own re-runs or in the one right
1528
+ # after it. Keep the state the strategy starts from, to be able to undo it.
1529
+ snapshot = self._take_snapshot()
1530
+ try:
1531
+ # Apply the strategy to all violations of this type at once
1532
+ action = strategy.apply_to_group(violations, self.pf_engine)
1533
+
1534
+ # If the strategy could not be applied, move on to the next one. It
1535
+ # may have changed the network before giving up, a power set or a power
1536
+ # flow re-run, so go back to the state it started from.
1537
+ if not action:
1538
+ self._restore_snapshot(snapshot)
1539
+ continue
1540
+
1541
+ self._record_action(strategy, action, violation_type)
1542
+
1543
+ # A planning strategy changes the network the operation actions were
1544
+ # chosen for: revert them, to choose them again below
1545
+ reverted = (
1546
+ strategy.stage == "planning" and self._revert_operation_actions()
1547
+ )
1548
+
1549
+ # Run power flow to see the effect of this strategy (and of any
1550
+ # operation-strategy reverts just performed above, if applicable).
1551
+ self.pf_engine.run_power_flow(warm_start=True)
1552
+
1553
+ # Choosing the operation actions again is part of applying the
1554
+ # planning strategy: a failure there undoes it as well
1555
+ if reverted:
1556
+ self._rerun_operation_strategies()
1557
+ except PowerFlowNotConverged as exc:
1558
+ # Undo everything the strategy did, even what it did before diverging,
1559
+ # so that the network is back to its last solved state. The next
1560
+ # strategy then starts from that state.
1561
+ self.logger.warning(
1562
+ f"Power flow diverged while applying {strategy.name} for "
1563
+ f"{violation_type} violations ({exc}). Undoing it."
1564
+ )
1565
+ self._restore_snapshot(snapshot)
1566
+ self._record_divergence(violation_type, strategy.name, exc)
1567
+ continue
1568
+ except BaseException:
1569
+ # Anything else is not handled here, a missing price or an error of
1570
+ # the strategy for instance. Do not leave the caller a network the
1571
+ # strategy has changed in part, with results and actions of another
1572
+ # state: go back to the state the strategy started from.
1573
+ self._restore_snapshot(snapshot)
1574
+ raise
1575
+
1576
+ applied.append(strategy)
1577
+
1578
+ # Check if this strategy resolved all violations of this type
1579
+ current_violations = self.pf_engine.check_violations()
1580
+ self._rate_state(current_violations, trackers)
1581
+ remaining_violations_of_type = [
1582
+ v for v in current_violations if v.constraint_type == violation_type
1583
+ ]
1584
+
1585
+ if not remaining_violations_of_type:
1586
+ self.logger.info(
1587
+ f"All {violation_type} violations resolved after applying {strategy.name}"
1588
+ )
1589
+ return applied
1590
+ else:
1591
+ self.logger.info(
1592
+ f"{len(remaining_violations_of_type)} {violation_type} violations remain after applying {strategy.name}"
1593
+ )
1594
+ # Update the violations to work with for the next strategy
1595
+ violations = remaining_violations_of_type
1596
+
1597
+ return applied
1598
+
1599
+ def _record_action(
1600
+ self, strategy: "EnhancementStrategy", action: dict[str, Any], violation_type
1601
+ ) -> None:
1602
+ """Add an action a strategy has applied to the results, with its cost."""
1603
+ if self.cost_model:
1604
+ self._note_origins(action)
1605
+ action["cost"] = strategy.calculate_cost(action, self.cost_model)
1606
+
1607
+ # Inject metadata about the strategy
1608
+ action["strategy_name"] = strategy.name
1609
+ action["stage"] = strategy.stage
1610
+
1611
+ self.applied_actions.append(action)
1612
+ self.total_cost = self._cost_of_the_actions()
1613
+ self.logger.info(f"Applied {strategy.name} for {violation_type} violations")
1614
+
1615
+ def _origins_of_the_run(self) -> dict[str, dict[str, tuple[Any, int]]]:
1616
+ """
1617
+ Type and number of elements in parallel of each line and transformer as the
1618
+ run starts, by the key of their upgrades in an action, for an element that a
1619
+ later action upgrades again to be charged for what the run lays, not for what
1620
+ each action does. Empty for a kind of element the engine cannot list.
1621
+ """
1622
+ origins = {}
1623
+ for kind in _CHARGED_FROM_ORIGIN:
1624
+ # Only an engine that does not implement the listing is tolerated: an error
1625
+ # inside one that does (a result table without a column...) is the engine's
1626
+ listing = getattr(self.pf_engine, kind.engine_info, None)
1627
+ try:
1628
+ info = listing() if listing is not None else None
1629
+ except NotImplementedError:
1630
+ info = None
1631
+ if info is None:
1632
+ origins[kind.upgrades] = {}
1633
+ continue
1634
+ # None for an element that has no type, as the strategies read it
1635
+ origins[kind.upgrades] = {
1636
+ name: (type_in_place(element_type), max(1, int(parallel)))
1637
+ for name, element_type, parallel in zip(
1638
+ info.index, info["std_type"], info["parallel"], strict=True
1639
+ )
1640
+ }
1641
+ return origins
1642
+
1643
+ def _initial_power_of_the_run(self) -> dict[tuple[str, Any], float] | None:
1644
+ """
1645
+ Active power of each load and static generator as the run starts, by type and
1646
+ index in the table of the engine. None if the engine cannot list them: the
1647
+ strategies then count from the powers at each of their calls.
1648
+ """
1649
+ initial_power: dict[tuple[str, Any], float] = {}
1650
+ for element_type in ("load", "sgen"):
1651
+ try:
1652
+ assets = self.pf_engine.get_flexibility_data(element_type)
1653
+ except (NotImplementedError, AttributeError):
1654
+ return None
1655
+ if assets is None or assets.empty or "p_mw" not in assets:
1656
+ continue
1657
+ for index, power in zip(
1658
+ assets.index.tolist(), assets["p_mw"].tolist(), strict=True
1659
+ ):
1660
+ initial_power[(element_type, index)] = power
1661
+ return initial_power
1662
+
1663
+ def _note_origins(self, action: dict[str, Any]) -> None:
1664
+ """
1665
+ Give the line and transformer upgrades of an action the state of their
1666
+ element at run start.
1667
+ """
1668
+ for kind in _CHARGED_FROM_ORIGIN:
1669
+ if kind.action_type is not None and action.get("type") != kind.action_type:
1670
+ continue
1671
+ note_origins(
1672
+ action.get(kind.upgrades),
1673
+ self._origins.get(kind.upgrades),
1674
+ kind.element_id,
1675
+ kind.origin_count,
1676
+ )
1677
+
1678
+ def _rerun_operation_strategies(self) -> None:
1679
+ """
1680
+ Choose the operation actions again, after a planning change reverted them.
1681
+
1682
+ Their violations are addressed again in the priority order, by the operation
1683
+ strategies only, on the network with the planning change. This happens within
1684
+ the pass, so that the planning change does not undo, until the next pass, what
1685
+ the operation actions had resolved. An operation strategy that makes the power
1686
+ flow diverge, or that returns no action, is undone, as in a pass. On return,
1687
+ the power flow results are those of the network, since each strategy that
1688
+ changed it solved power flow again or was undone. If a strategy raises anything
1689
+ else, the caller undoes the planning change, and with it all that was done here.
1690
+ """
1691
+ self.logger.info("Choosing the operation actions again after a planning change")
1692
+ violations = self.pf_engine.check_violations()
1693
+ for violation_type in self.strategy_registry.violation_priority_order:
1694
+ group = [v for v in violations if v.constraint_type == violation_type]
1695
+ for strategy in self.strategy_registry.get_strategies_for_type(
1696
+ violation_type
1697
+ ):
1698
+ if not group:
1699
+ break
1700
+ if strategy.stage != "operation":
1701
+ continue
1702
+ # The state the strategy starts from, to undo it if the power flow
1703
+ # diverges or if it returns no action after changing the network.
1704
+ snapshot = self._take_snapshot()
1705
+ try:
1706
+ action = strategy.apply_to_group(group, self.pf_engine)
1707
+ if not action:
1708
+ # It may have changed the network before giving up
1709
+ self._restore_snapshot(snapshot)
1710
+ continue
1711
+ self._record_action(strategy, action, violation_type)
1712
+ self.pf_engine.run_power_flow(warm_start=True)
1713
+ except PowerFlowNotConverged as exc:
1714
+ self.logger.warning(
1715
+ f"Power flow diverged while applying {strategy.name} again for "
1716
+ f"{violation_type} violations ({exc}). Undoing it."
1717
+ )
1718
+ self._restore_snapshot(snapshot)
1719
+ self._record_divergence(violation_type, strategy.name, exc)
1720
+ continue
1721
+ violations = self.pf_engine.check_violations()
1722
+ group = [v for v in violations if v.constraint_type == violation_type]
1723
+
1724
+ def _revert_operation_actions(self) -> bool:
1725
+ """
1726
+ Revert the operation actions applied so far, as a planning change makes them
1727
+ out of date. `_rerun_operation_strategies` chooses them again.
1728
+
1729
+ Returns:
1730
+ Whether there was an operation action to revert.
1731
+ """
1732
+ self.logger.info("Reverting operation actions due to planning changes")
1733
+
1734
+ indices_to_remove = []
1735
+ # The tap changes reverted, by transformer, in the order they were made
1736
+ tap_changes: dict[str, list[dict[str, Any]]] = {}
1737
+
1738
+ # Iterate backwards to safely identify actions to revert
1739
+ for i in range(len(self.applied_actions) - 1, -1, -1):
1740
+ action = self.applied_actions[i]
1741
+
1742
+ # Check if this is an operation strategy action
1743
+ if action.get("stage") == "operation":
1744
+ self.logger.info(
1745
+ f"Reverting operation action: {action.get('type')} from {action.get('strategy_name')}"
1746
+ )
1747
+
1748
+ if action.get("type") == "flexibility_management":
1749
+ # Reverse order: an asset modified twice in one action must end at
1750
+ # the power it had before the first modification.
1751
+ for bus_mod in reversed(action.get("buses", [])):
1752
+ element_type = bus_mod.get("element_type")
1753
+ element_index = bus_mod.get("element_index")
1754
+ old_power = bus_mod.get("old_power")
1755
+ # A load shed down to zero has lost its power factor: its
1756
+ # reactive power is needed to restore it
1757
+ old_reactive_power = bus_mod.get("old_reactive_power")
1758
+
1759
+ if (
1760
+ element_type
1761
+ and element_index is not None
1762
+ and old_power is not None
1763
+ ):
1764
+ reactive = (
1765
+ {}
1766
+ if old_reactive_power is None
1767
+ else {"new_q_mvar": old_reactive_power}
1768
+ )
1769
+ self.pf_engine.apply_flexibility_action(
1770
+ element_type, int(element_index), old_power, **reactive
1771
+ )
1772
+
1773
+ indices_to_remove.append(i)
1774
+
1775
+ for i in sorted(indices_to_remove):
1776
+ action = self.applied_actions[i]
1777
+ if action.get("type") == "tap_change":
1778
+ for entry in action.get("transformers", []):
1779
+ if entry.get("transformer_id") and entry.get("change") is not None:
1780
+ tap_changes.setdefault(entry["transformer_id"], []).append(
1781
+ entry
1782
+ )
1783
+ for transformer_id, entries in tap_changes.items():
1784
+ self._revert_tap_changes(transformer_id, entries)
1785
+
1786
+ # Remove from applied_actions
1787
+ # Sort indices in descending order to pop correctly
1788
+ indices_to_remove.sort(reverse=True)
1789
+ for i in indices_to_remove:
1790
+ self.applied_actions.pop(i)
1791
+ self.total_cost = self._cost_of_the_actions()
1792
+
1793
+ if indices_to_remove:
1794
+ self.logger.info(
1795
+ f"Reverted {len(indices_to_remove)} operation actions. "
1796
+ "Power flow will be re-run by the caller."
1797
+ )
1798
+ return bool(indices_to_remove)
1799
+
1800
+ def _revert_tap_changes(
1801
+ self, transformer_id: str, entries: list[dict[str, Any]]
1802
+ ) -> None:
1803
+ """
1804
+ Put a transformer back at the tap position it had before the tap changes that
1805
+ `entries` record, in the order they were made, all reverted at once.
1806
+
1807
+ The position is the one recorded before the first of them (`old_position`),
1808
+ reached from the position the unit has now: a transformer upgrade since the
1809
+ changes may have moved it into the range of its new type, and reverting the
1810
+ changes by their number of steps would then not lead back to it. Without that
1811
+ position, or with an engine that does not tell them, the changes are reverted
1812
+ by their steps, all together. A position outside the range the unit has now is
1813
+ not reached: the unit is taken as far towards it as the range allows, with a
1814
+ warning. A position in between, which only one of the changes started from, is
1815
+ not aimed at: once outside the range, it would be warned about for nothing. The
1816
+ actions the operation stage then takes are counted from there.
1817
+ """
1818
+ old = entries[0].get("old_position")
1819
+ current = (
1820
+ self.pf_engine.get_transformer_tap_position(transformer_id)
1821
+ if old is not None
1822
+ else None
1823
+ )
1824
+ shift = (
1825
+ int(round(old - current))
1826
+ if current is not None
1827
+ else -sum(int(entry["change"]) for entry in entries)
1828
+ )
1829
+ if shift == 0 or self.pf_engine.apply_tap_change(transformer_id, shift):
1830
+ return
1831
+ step = 1 if shift > 0 else -1
1832
+ moved = 0
1833
+ while moved != shift and self.pf_engine.apply_tap_change(transformer_id, step):
1834
+ moved += step
1835
+ self.logger.warning(
1836
+ f"Tap changes of transformer {transformer_id} reverted by {moved} of "
1837
+ f"{shift} steps: the position before them is outside the tap range the "
1838
+ "unit has now"
1839
+ )
1840
+
1841
+
1842
+ class EnhancementStrategyRegistry:
1843
+ """Registry for managing enhancement strategies by violation type."""
1844
+
1845
+ def __init__(self, violation_priority_order: list["ConstraintType"] | None = None):
1846
+ """
1847
+ Initialize an empty registry.
1848
+
1849
+ Args:
1850
+ violation_priority_order (Optional[List[ConstraintType]], optional):
1851
+ Order in which violation types should be addressed. Types left out are
1852
+ not addressed: their violations remain, so a run with any of them
1853
+ cannot succeed. Defaults to [TRANSFORMER_LOADING, LINE_LOADING,
1854
+ OVER_VOLTAGE, UNDER_VOLTAGE].
1855
+ """
1856
+
1857
+ if violation_priority_order is None:
1858
+ self.violation_priority_order = [
1859
+ ConstraintType.TRANSFORMER_LOADING,
1860
+ ConstraintType.LINE_LOADING,
1861
+ ConstraintType.OVER_VOLTAGE,
1862
+ ConstraintType.UNDER_VOLTAGE,
1863
+ ]
1864
+ else:
1865
+ self.violation_priority_order = violation_priority_order
1866
+
1867
+ self.strategies_by_type = {
1868
+ c_type: [] for c_type in self.violation_priority_order
1869
+ }
1870
+
1871
+ def register_strategy(self, strategy: "EnhancementStrategy"):
1872
+ """
1873
+ Register a strategy for its applicable violation types.
1874
+
1875
+ The types the priority order leaves out are not addressed, so a strategy is only
1876
+ registered for the others, with a warning for each type dropped. A strategy
1877
+ for none of them is not registered.
1878
+
1879
+ Args:
1880
+ strategy (EnhancementStrategy): The strategy to register.
1881
+ """
1882
+ logger = logging.getLogger(__name__)
1883
+ violation_types = []
1884
+ # Sorted, for the warnings to come in the same order from one run to the next
1885
+ for violation_type in sorted(
1886
+ strategy.applicable_constraints(),
1887
+ key=lambda c_type: str(getattr(c_type, "value", c_type)),
1888
+ ):
1889
+ if violation_type in self.strategies_by_type:
1890
+ violation_types.append(violation_type)
1891
+ else:
1892
+ logger.warning(
1893
+ f"Strategy {strategy.name} is not registered for "
1894
+ f"{getattr(violation_type, 'value', violation_type)} violations: "
1895
+ f"the priority order leaves this type out"
1896
+ )
1897
+ if not violation_types:
1898
+ logger.warning(
1899
+ f"Strategy {strategy.name} is not registered at all: it addresses no "
1900
+ f"violation type of the priority order"
1901
+ )
1902
+ for violation_type in violation_types:
1903
+ self.strategies_by_type[violation_type].append(strategy)
1904
+
1905
+ def get_strategies_for_type(
1906
+ self, violation_type: str
1907
+ ) -> list["EnhancementStrategy"]:
1908
+ """
1909
+ Get strategies applicable to the given violation type.
1910
+
1911
+ Args:
1912
+ violation_type (str): Type of violation.
1913
+
1914
+ Returns:
1915
+ List[EnhancementStrategy]: List of applicable strategies, ordered by increasing cost level.
1916
+ """
1917
+ strategies = self.strategies_by_type.get(violation_type, [])
1918
+ # Sort strategies by cost level
1919
+ return sorted(strategies, key=lambda s: s.cost_level)
1920
+
1921
+ def get_all_strategies(self) -> set["EnhancementStrategy"]:
1922
+ """
1923
+ Get the registered strategies, each one once whatever the violations it addresses.
1924
+
1925
+ Returns:
1926
+ Set[EnhancementStrategy]: The registered strategies.
1927
+ """
1928
+ return {
1929
+ strategy
1930
+ for strategies in self.strategies_by_type.values()
1931
+ for strategy in strategies
1932
+ }