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,1476 @@
1
+ import copy
2
+ import math
3
+ from collections.abc import Mapping
4
+ from typing import Any
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+
9
+ from gridforge.core.constraints import (
10
+ ConstraintType,
11
+ ConstraintViolation,
12
+ _relative_excess,
13
+ )
14
+ from gridforge.core.cost_model import CostModel
15
+ from gridforge.core.power_flow import PowerFlowEngine
16
+ from gridforge.core.strategy import EnhancementStrategy
17
+ from gridforge.utils.logging import logger
18
+
19
+ # Share of a limit that a flexibility step aims inside it by (1e-4 % of loading for a
20
+ # 100 % limit, about 1e-6 p.u. of voltage), far above the error left by the Newton step
21
+ # that ends each power flow of the engine (about 1e-10 p.u. and 1e-7 %, #18). It was not
22
+ # above the solver's own error, up to 5.2e-6 p.u. and 3.5e-3 % at a tolerance of 1e-8
23
+ _SIZING_MARGIN = 1.0e-6
24
+
25
+
26
+ def _checked_share(name: str, value: float) -> float:
27
+ """A share in percent, which must be between 0 and 100 (a NaN is refused)."""
28
+ if not 0.0 <= value <= 100.0:
29
+ raise ValueError(f"{name} must be between 0 and 100, not {value}")
30
+ return value
31
+
32
+
33
+ class FlexibilityStrategy(EnhancementStrategy):
34
+ """
35
+ Strategy for Active Power Flexibility Management.
36
+
37
+ Manages active power flexibility to securely resolve operational constraints
38
+ using a deterministic, sensitivity-driven heuristic algorithm.
39
+
40
+ Attributes:
41
+ max_iterations (int): Maximum number of iterations for the flexibility management loop.
42
+ n_activation (int): Number of nodes to activate flexibility on per iteration.
43
+ tabu_list (Set[Tuple[str, Any]]): The assets set aside for the rest of the
44
+ call, as their steps went round in a cycle (see `apply_to_group`), by type
45
+ and index in the table of the engine.
46
+ unrelievable (Dict[Tuple[Any, Any], float]): The violations of the last
47
+ call that no asset could relieve when last examined, by constraint type
48
+ and element, with their levels: the lowest excess over their limits at
49
+ which the call gave up on them, beyond which no step of the call takes
50
+ them (see `apply_to_group`).
51
+ history (List[Dict[str, Any]]): The actions of the last call, each with the
52
+ iteration it was taken at, the violations of the network it was taken on
53
+ ("violations"), those the call acted on, by constraint type and element,
54
+ with the excess it acted on ("excesses", see `apply_to_group`), its
55
+ target among them, as such a key and excess ("target"), the sum of the
56
+ `_relative_excess` of the violations it acted on ("relative_excess"), and
57
+ what every violation of the network exceeded its limit by, by key
58
+ ("measured"), these four in the state the action was taken from. It is
59
+ reset at the start of each `apply_to_group` call, so that after a run it
60
+ holds the last call only.
61
+ logs (List[str]): A list of log messages generated during the application of the strategy.
62
+ It is reset at the start of each `apply_to_group` call, so that after a run
63
+ it holds the messages of the last call only.
64
+ initial_power (Optional[Mapping[Tuple[str, Any], float]]): The power of the
65
+ flexible assets that their limits count from, by type and index in the
66
+ table of the engine: an asset can be taken down to `1 - max_flex_pct / 100`
67
+ of it, whatever the calls before took off. `GridEnhancementAlgorithm` lends
68
+ the powers as its run started, for the time of the run. None otherwise (the
69
+ default): the limits then count from the powers at each call of
70
+ `apply_to_group`, so that a strategy used on its own on another network,
71
+ or on loads changed since its last call, takes their limits from them. An
72
+ asset that it does not list counts from its power at the call.
73
+
74
+ The limits hold within a call, or a run, not across them. A strategy
75
+ called again on its own on a network that its first call shed can shed
76
+ up to `max_flex_pct` of what that call left: a 112 kW load at 30 % ends
77
+ 45 % under its first power after two calls. A caller that calls the
78
+ strategy several times on one network must give it the powers to count
79
+ from here, as `{("load", 0): 0.112}`, and set it back to None for
80
+ another network. Likewise, a run counts from the powers of the engine
81
+ as it starts: a second run on an engine that the first left shed sheds
82
+ again from there (45 % in all for that load). A copy or a pickle of the
83
+ strategy made during a run keeps the powers of that run, and counts from
84
+ them if it is then used on its own.
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ max_iterations: int = 500,
90
+ n_activation: int = 1,
91
+ min_achievable_relief_pct: float = 5.0,
92
+ min_asset_relief_pct: float = 0.01,
93
+ min_round_relief_pct: float = 5.0,
94
+ ):
95
+ """
96
+ Initialize the FlexibilityStrategy.
97
+
98
+ Args:
99
+ max_iterations (int, optional): Maximum number of iterations for the flexibility management loop. Defaults to 500.
100
+ n_activation (int, optional): Number of nodes to activate flexibility on per iteration. Defaults to 1.
101
+ min_achievable_relief_pct (float, optional): Share of the target violation, in
102
+ percent, that the assets able to reduce it must be able to relieve together,
103
+ by the linear estimate of the sensitivities. Under it, no asset is activated
104
+ for that violation. The threshold applies to the assets together, not to
105
+ each of them: many small assets that are enough together are used.
106
+ Between 0 and 100, checked when it is set. Defaults to 5.0.
107
+ min_asset_relief_pct (float, optional): Share of the target violation, in
108
+ percent, that one asset must be able to relieve to be considered: an asset
109
+ under it has a negligible effect and is left out, and does not count
110
+ towards `min_achievable_relief_pct`. Between 0 and 100, checked when it
111
+ is set. Defaults to 0.01.
112
+ min_round_relief_pct (float, optional): Share, in percent, of the reach of
113
+ a round of a see-saw (the largest excess of each violation over the
114
+ round) that the next round must relieve of at least one violation to
115
+ be progress. A round ends when a violation that the call had
116
+ resolved, and that came back, is resolved again. Two violations whose
117
+ steps bring each other back, each round a little smaller, are taken
118
+ for a cycle once two rounds in a row relieve no more than this; the
119
+ asset set aside is that of the latest step of the two rounds for a
120
+ violation outside the group, the one that brings the group's violation
121
+ back (see `apply_to_group`). Steps that bring no violation back end no
122
+ round, however little each relieves. Between 0 and 100, checked when
123
+ it is set. Defaults to 5: it stops the see-saw of the feeder of #55
124
+ (about 4.4 % a round) and stays a factor of two below the slowest
125
+ see-saw met that resolved its violations (11.5 % a round, which a
126
+ threshold above about 11 % cuts); see "Active Power Flexibility
127
+ Management" in the methodology for what it rests on and what it can
128
+ cost. 0 judges no round and takes any relief for progress, as the
129
+ cycle rule of #55: the strategy before #65 to the bit.
130
+ """
131
+ super().__init__()
132
+ self.max_iterations = max_iterations
133
+ self.n_activation = n_activation
134
+ self.tabu_list: set[tuple[str, Any]] = set()
135
+ self.unrelievable: dict[tuple[Any, Any], float] = {}
136
+ # Of the current call: the number of steps kept when each violation set aside
137
+ # was last examined, and the assets that a step for a violation took a
138
+ # violation set aside beyond its level with
139
+ self._examined_after: dict[tuple[Any, Any], int] = {}
140
+ self._spoilers: dict[tuple[Any, Any], set[tuple[str, Any]]] = {}
141
+ # The lowest excess at which each violation was given up on in the call
142
+ self._levels: dict[tuple[Any, Any], float] = {}
143
+ # Of the current call, rounds being identified by the count of the states
144
+ # before the state they ended at: the reach of each round with the count of
145
+ # the states before its first state; the rounds judged since the last asset
146
+ # set aside, with that count and whether they were slow; the count of the
147
+ # states at the last asset set aside; and the violations of the group the
148
+ # call was given
149
+ self._reaches: dict[int, tuple[int, dict[tuple[Any, Any], float]]] = {}
150
+ self._judged: dict[int, tuple[int, bool]] = {}
151
+ self._aside_at = 0
152
+ self._group: set[tuple[Any, Any]] = set()
153
+ self.history: list[dict[str, Any]] = []
154
+ # The powers the limits of the current call count from
155
+ self._limits_from: Mapping[tuple[str, Any], float] = {}
156
+ self._name = "Flexibility Management"
157
+ self.min_achievable_relief_pct = min_achievable_relief_pct
158
+ self.min_asset_relief_pct = min_asset_relief_pct
159
+ self.min_round_relief_pct = min_round_relief_pct
160
+
161
+ @property
162
+ def min_round_relief_pct(self) -> float:
163
+ """
164
+ Share, in percent, of the reach of a round of a see-saw that the next round
165
+ must relieve of one of its violations to be progress: two rounds in a row
166
+ that do not are a cycle (see `apply_to_group`). Between 0 and 100, checked
167
+ when it is set; 5 by default, 0 for the exact cycle rule alone.
168
+ """
169
+ return self._min_round_relief_pct
170
+
171
+ @min_round_relief_pct.setter
172
+ def min_round_relief_pct(self, value: float) -> None:
173
+ self._min_round_relief_pct = _checked_share("min_round_relief_pct", value)
174
+
175
+ @property
176
+ def min_achievable_relief_pct(self) -> float:
177
+ """
178
+ Share, in percent, of the target violation that the candidate assets must be
179
+ able to relieve together for flexibility to be used. Between 0 and 100, checked
180
+ when it is set; 5 by default.
181
+ """
182
+ return self._min_achievable_relief_pct
183
+
184
+ @min_achievable_relief_pct.setter
185
+ def min_achievable_relief_pct(self, value: float) -> None:
186
+ self._min_achievable_relief_pct = _checked_share(
187
+ "min_achievable_relief_pct", value
188
+ )
189
+
190
+ @property
191
+ def min_asset_relief_pct(self) -> float:
192
+ """
193
+ Share, in percent, of the target violation under which the relief that one
194
+ asset can give is negligible and the asset is left out. Between 0 and 100,
195
+ checked when it is set; 0.01 by default.
196
+ """
197
+ return self._min_asset_relief_pct
198
+
199
+ @min_asset_relief_pct.setter
200
+ def min_asset_relief_pct(self, value: float) -> None:
201
+ self._min_asset_relief_pct = _checked_share("min_asset_relief_pct", value)
202
+
203
+ def calculate_cost(self, action: dict[str, Any], cost_model: CostModel) -> float:
204
+ """
205
+ Calculate the cost of the flexibility action.
206
+
207
+ Args:
208
+ action (Dict[str, Any]): The action dictionary.
209
+ cost_model (CostModel): The cost model.
210
+
211
+ Returns:
212
+ float: The cost of the action.
213
+ """
214
+ total_cost = 0.0
215
+ for bus_action in action.get("buses", []):
216
+ old_power = bus_action.get("old_power", 0.0)
217
+ new_power = bus_action.get("new_power", 0.0)
218
+ amount = max(0.0, old_power - new_power)
219
+ if bus_action.get("action_type") == "load_shedding":
220
+ total_cost += cost_model.calculate_load_shedding_cost(amount)
221
+ elif bus_action.get("action_type") == "gen_curtailment":
222
+ total_cost += cost_model.calculate_generation_curtailment_cost(amount)
223
+ return total_cost
224
+
225
+ def required_unit_costs(self, pf_engine: PowerFlowEngine) -> set[tuple[str, ...]]:
226
+ """
227
+ List the prices of the flexibility available on this network.
228
+
229
+ A study that only has flexible loads has no use for a curtailment price, and the
230
+ other way round.
231
+
232
+ Args:
233
+ pf_engine (PowerFlowEngine): The power flow engine.
234
+
235
+ Returns:
236
+ Set[Tuple[str, ...]]: The keys of the prices in `CostModel.unit_costs`.
237
+ """
238
+ prices = {"load": "load_shedding", "sgen": "generation_curtailment"}
239
+ return {
240
+ (price,)
241
+ for element_type, price in prices.items()
242
+ if self._has_flexibility(pf_engine, element_type)
243
+ }
244
+
245
+ @staticmethod
246
+ def _has_flexibility(pf_engine: PowerFlowEngine, element_type: str) -> bool:
247
+ assets = pf_engine.get_flexibility_data(element_type)
248
+ return not assets.empty and bool((assets["max_flex_pct"] > 0).any())
249
+
250
+ @property
251
+ def cost_level(self) -> int:
252
+ """
253
+ Get the cost level of the strategy.
254
+
255
+ Returns:
256
+ int: The cost level (2 for flexibility).
257
+ """
258
+ return 2
259
+
260
+ @property
261
+ def stage(self) -> str:
262
+ """
263
+ Get the stage of the strategy.
264
+
265
+ Returns:
266
+ str: The stage ("operation").
267
+ """
268
+ return "operation"
269
+
270
+ def applicable_constraints(self) -> set[ConstraintType]:
271
+ """
272
+ Get the set of applicable constraint types.
273
+
274
+ Returns:
275
+ Set[ConstraintType]: The set of applicable constraint types.
276
+ """
277
+ return {
278
+ ConstraintType.UNDER_VOLTAGE,
279
+ ConstraintType.OVER_VOLTAGE,
280
+ ConstraintType.LINE_LOADING,
281
+ ConstraintType.TRANSFORMER_LOADING,
282
+ }
283
+
284
+ @property
285
+ def name(self) -> str:
286
+ """
287
+ Get the name of the strategy.
288
+
289
+ Returns:
290
+ str: The name of the strategy.
291
+ """
292
+ return self._name
293
+
294
+ def apply_to_group(
295
+ self, violations: list[ConstraintViolation], pf_engine: PowerFlowEngine
296
+ ) -> dict[str, Any] | None:
297
+ """
298
+ Apply the flexibility strategy to a group of violations.
299
+
300
+ This method iteratively selects the most severe violation, identifies the most effective
301
+ flexible asset to mitigate it using sensitivity analysis, and applies a corrective action.
302
+
303
+ The call acts on the violations of the group it is given, and on what its own
304
+ steps add to the others: a violation that was not there as the call started,
305
+ whole, and of one that was, what it exceeds its limit by beyond what it did
306
+ then, as a violation of that excess, which a step aims to take off just inside
307
+ (the starting excess less `_SIZING_MARGIN` of the limit). The rest of a
308
+ violation that was there, outside the group, is left to the strategies of its
309
+ type, which the run applies at its turn, in the priority order of the registry
310
+ and with its own choice between them: the call does not resolve it, nor take
311
+ its relief for progress. The comparison has no tolerance, as the cycle rule
312
+ below. Before #63 the call acted on every violation of the network after its
313
+ first step: given an overloaded line, it went on to shed loads for an
314
+ under-voltage elsewhere once the line was resolved.
315
+
316
+ The steps are aimed at the target, but a step can relieve less than the
317
+ sensitivities estimate, or bring back a violation that another step relieved.
318
+ The call has gone round in a cycle when it comes back to a state no better than
319
+ one it has been in, every violation of that state still there and none less than
320
+ it was, and every violation it has resolved since then is one it had met at or
321
+ before that state: the steps since that state have brought none of its
322
+ violations down, and those they resolved are coming round too. Of the latest
323
+ such state, the first asset acted on from it (the one ranked first) is set aside
324
+ for the rest of the call (`tabu_list`); if all those are set aside already, the
325
+ first one that is not of the latest such state before it. Each cycle thus sets
326
+ aside a new asset, as long as one is left. A step that relieves a violation,
327
+ however little, is progress, not a cycle: the comparison has no tolerance, so
328
+ that a violation that a step reduces by less than a rounding (the former rule
329
+ compared violations to 4 decimals) is not mistaken for one that it leaves as it
330
+ was.
331
+
332
+ The violations of these states are those the call acts on, with the excess it
333
+ acts on. A violation that the call meets for the first time on the way and
334
+ resolves gives it one more round: relieving the target can bring up a
335
+ violation, or worsen one outside the group the call was given, and relieving
336
+ that one bring the target back larger, where the next round can resolve both.
337
+ When one of them comes back again, no smaller than the time before, the
338
+ violation resolved in between has been met before, and it is a cycle.
339
+
340
+ Two violations that bring each other back, each a little smaller than the
341
+ time before, are progress by this rule alone: the call would go on
342
+ alternating between them until one comes back no smaller, which can take
343
+ until an asset it uses has no margin left. `min_round_relief_pct` stops such
344
+ a see-saw. A round ends at a state at which a violation that was met at or
345
+ before an earlier state, and was not in it, has come back and been resolved
346
+ again, every violation of that earlier state still there: the latest such
347
+ earlier state is the first state of the round (the windows of the cycle rule
348
+ that have resolved something since their state). The reach of a round is the
349
+ largest excess of each violation over its states, from its first to the last
350
+ before the state it ends at, so that it holds every violation the see-saw
351
+ passes through, the group's included, at its peak. A round is judged against
352
+ the round that ended at its first state: it is slow if none of the
353
+ violations of that round's reach is relieved by more than
354
+ `min_round_relief_pct` of what it reached there (reach now >= reach then x
355
+ (1 - min_round_relief_pct / 100) for each of them); a violation the round no
356
+ longer reaches is relieved. A round is judged only against a round that
357
+ ended exactly at its first state: the first round of a see-saw has nothing to
358
+ be judged against, nor has a round whose first state is not the end of a
359
+ round, so that a window that grows from the same first state, one state
360
+ longer at each step, is never judged. A slow round that follows a slow round,
361
+ the latest judged before it, is taken for a cycle and sets an asset aside: of
362
+ the steps of the two rounds, latest first, those for a violation outside the
363
+ group of the call come first, as they are what brings back the violation of
364
+ the group
365
+ that the other steps relieve, then the others; the first asset of them not
366
+ set aside yet, if another asset could act on the violation its step was
367
+ relieving (`_relievable_without`: the test of the candidates of a target, on
368
+ the sensitivities of the state now, without a power flow). If none could,
369
+ nothing is set aside and the see-saw goes on as without a threshold: setting
370
+ the asset aside would leave the violation, or the run to pay a reinforcement
371
+ that going on avoids. After an asset is set aside, by this rule or the cycle
372
+ rule, the rounds whose round before started before it are not judged, and
373
+ those judged before it no longer count: two new slow rounds, with the assets
374
+ left, are needed for the next asset. One slow
375
+ round is not enough: a see-saw that makes steady progress can have one, when
376
+ an asset it uses runs out and another takes its place. Judging a round again
377
+ after a step undone gives the same result. The steps of the rounds are kept,
378
+ as those of a cycle, and the call goes on with the assets left, so that what
379
+ it returns is built as before. Steps that bring no violation back end no
380
+ round, so that a call that relieves its target a little at each step, an
381
+ asset after another, is never cut, whatever the threshold. The default is
382
+ 5 %; at 0 no round is judged, and the call is the same to the bit as before
383
+ #65. Before the rework of #65 a round was judged on the violations of its
384
+ first state only, so that a see-saw resolving the group's violation was
385
+ taken for slow by the rounds of the other one, and the asset set aside was
386
+ the first acted on from that state, which could be the reliever of the
387
+ group's violation. In a small random feeder, shedding a load for a line and
388
+ curtailing a generator for the over-voltage that it brings up, each round
389
+ relieving about 4.4 % of the reach, goes on for 74 steps for 421.05 EUR at
390
+ 0; from 4.5 % the generator is set aside after two slow rounds and another
391
+ resolves both in 10 steps for 187.01 EUR (see "Active Power Flexibility
392
+ Management" in the methodology, which also says what the rule does not
393
+ guarantee).
394
+
395
+ A violation that no asset can relieve, by the filters of `_evaluate_assets`
396
+ and `min_achievable_relief_pct`, does not stop the call: it is set aside
397
+ (`unrelievable`), and the step is taken on the most severe violation that an
398
+ asset can relieve. Its level is what it exceeds its limit by when it is set
399
+ aside, or, if the call has given up on it before, the lowest of these: it is
400
+ kept for the rest of the call, also while the violation is taken up again,
401
+ when the steps for other targets can take it up to its level but not beyond.
402
+ A step after which a violation given up on exceeds its level, as the power
403
+ flow after the step measures it, is undone: its assets get back their powers
404
+ (reactive power included), and it leaves no trace in `history` or in the
405
+ action returned. A step on one asset leaves that asset out of the candidates
406
+ of that target for the rest of the call. A step on several assets is taken
407
+ again one asset at a time, in the order they were ranked, each by what it
408
+ took in the step and each measured by a power flow: an asset whose step,
409
+ after those kept before it, takes a violation given up on beyond its level
410
+ is undone and left out for that target, and the others are kept. The harm is
411
+ measured, not predicted: the sensitivities need not show it. The call thus
412
+ never leaves a violation it gave up on above the lowest level at which it
413
+ gave up on it. Only steps undone cost power flows: 2 for a step on one asset,
414
+ 2 + k for a step on k assets, and one more for each of them undone again.
415
+ Each asset undone leaves out one more pair of a target and an asset, of
416
+ which there are finitely many, and each asset kept is a step kept, so that
417
+ undoing does not keep the call from ending.
418
+
419
+ After a step undone, the network has the powers of the state before it, and
420
+ the call goes on from the violations it measured then. Solved again, the
421
+ network gives them to the precision of the power flow, not bit for bit (up
422
+ to 5.0e-12 % of loading on 700 random feeders); and a load or generator
423
+ whose `scaling` is not 1 gets its powers back to a rounding (1.6e-16
424
+ relative), as `apply_flexibility_action` divides them by the scaling, which
425
+ the revert of operation actions by the algorithm shares.
426
+
427
+ Of the filters, the margins and the assets left out only shrink during a
428
+ call, but the share of a violation that the assets must relieve together
429
+ follows the violation, and a sensitivity follows the state of the network:
430
+ a step kept for another violation can bring one set aside within reach.
431
+ Those set aside are therefore examined again, most severe first, once no
432
+ other violation can be relieved, if a step has been kept since they were
433
+ last examined (a step undone leaves the network as it was). A violation is
434
+ thus examined again at most once per step kept or undoing of the steps that
435
+ brought a violation about (below), and all of them at most (number set
436
+ aside) x (steps kept + such undoings) times. A violation set aside stays among
437
+ those the cycle rule compares: its relief by the steps for others is
438
+ progress of the call. Before, the call stopped at the first target that no
439
+ asset could relieve, whatever the other violations it could have relieved.
440
+
441
+ A violation that a call brings about and cannot relieve is left at its
442
+ level, for the strategies of its type, which the run applies in the same
443
+ pass: at their turn if its type comes after that of the group in the
444
+ priority order, at their turn given again otherwise (see
445
+ `GridEnhancementAlgorithm`; until #66, in the next pass). If an asset that
446
+ relieves it has been left out of its candidates, because its step for it
447
+ took a violation given up on beyond its level or by an earlier undoing
448
+ (below), the call can undo the steps that brought it about instead
449
+ (`_undo_what_brought_about`); the same holds for a violation that its steps
450
+ worsened, of the group or not: the steps since the latest state in which the
451
+ call acted on the least of it, all at once. It does so only if the network
452
+ is more severe in total now than in that state, by the sum of the
453
+ `_relative_excess` of all its violations, the measure the algorithm rates
454
+ states by, a voltage against the width of its band and a loading against its
455
+ limit: what the steps brought about or added outweighs what they relieved,
456
+ outside the group as in it (a violation outside the group is weighed, never
457
+ worked on beyond what the steps added to it). A step
458
+ that resolves a 30 % overload of the group and brings up a 2 % one is kept,
459
+ and the 2 % set aside; so is a step that resolves an under-voltage of 0.05
460
+ pu (0.5 of a band of 0.1 pu) and brings up a 6 % overload. It does not undo
461
+ them either if a violation given up on exceeded its limit by more than its
462
+ level in that state, which undoing brings back, as a level lowered since can
463
+ be: the call tells it from what it measured then, without a power flow, and
464
+ never breaks the rule above. Of the first of the steps undone, an asset on
465
+ its own is left out of the candidates of its target; the assets of a step on
466
+ several are taken again one at a time, in the order they were ranked, and
467
+ one after which the call acts on more of the violation than in that state
468
+ (beyond `_SIZING_MARGIN` of its limit, for one that was there: every asset
469
+ moves every loading a little), or after which a violation given up on is
470
+ beyond its level, is undone and left out, the last one if none is. The call
471
+ goes on from there. It costs a power flow for the undoing, one for each
472
+ asset of a step on several taken again, one for each of them undone again,
473
+ and one more if none of them does harm. The comparison is of totals,
474
+ measured in the state the steps were taken from: the call can end with more
475
+ violations than if it had set the violation aside, or with one of them
476
+ larger, when the total is smaller. The targets of the steps are still
477
+ ranked by `_severity`, against the limit. Until #66 the call left both:
478
+ given up on at 10 %, a line was taken up again at 8.9 %, and the step that
479
+ took it to 8.45 % brought about an overload of 21.5 %, which only an asset
480
+ that worsens the line relieved; the call now undoes that step (30 % in all
481
+ against 8.9 %) and leaves the line at 8.9 %.
482
+
483
+ The call ends when the violations it acts on are resolved, when none of
484
+ those left can be relieved, when the steps no longer change a power, or after
485
+ `max_iterations`: each iteration of the loop, an undoing included, counts
486
+ towards it. Without undoings of the steps that brought a violation about, it
487
+ ends before `max_iterations` whenever the margins run out first: every step
488
+ that goes on takes power off an asset and puts none back, and takes at least
489
+ the smaller of 1e-4 MW (the margin under which an asset is not a candidate)
490
+ and what the target needs to be brought just inside its limit
491
+ (`_SIZING_MARGIN` of it), which is never zero. An undoing gives power back:
492
+ it takes back at least one step kept, and leaves out, for the target of the
493
+ first step it takes back, at least one asset of that step, if it was not
494
+ left out already (a later step for the same target, undone by the level
495
+ rule, can have left it out before). No bound tighter than `max_iterations`
496
+ is shown for the undoings: a step on the same target and asset taken before
497
+ the one left out, still in `history`, can be the first step of a later
498
+ undoing. A call that
499
+ resolves part of its group returns its steps, like one that resolves it all:
500
+ `total_violations_addressed` counts the violations of the group resolved,
501
+ and the algorithm gives what is left of the group to the next strategy of
502
+ the chain.
503
+
504
+ Args:
505
+ violations (List[ConstraintViolation]): The list of violations to address.
506
+ pf_engine (PowerFlowEngine): The power flow engine.
507
+
508
+ Returns:
509
+ Optional[Dict[str, Any]]: A dictionary describing the actions taken, or None if no action was applied.
510
+ Its `total_violations_addressed` is the number of violations of the group
511
+ that the call resolved.
512
+ """
513
+ self.logs = []
514
+ self.history = []
515
+ self.tabu_list.clear()
516
+ self.unrelievable = {}
517
+ self._examined_after = {}
518
+ self._spoilers = {}
519
+ self._levels = {}
520
+ self._reaches = {}
521
+ self._judged = {}
522
+ self._aside_at = 0
523
+
524
+ # The limits are those of the run, if the strategy is given its powers, and
525
+ # those of the powers now otherwise
526
+ if self.initial_power is not None:
527
+ self._limits_from = self.initial_power
528
+ else:
529
+ self._capture_initial_state(pf_engine)
530
+
531
+ violation_count = len(violations)
532
+ group = {self._key(v) for v in violations}
533
+ self._group = group
534
+ # What the violations outside the group exceed their limits by as the call
535
+ # starts: the call answers only for what its steps add to them
536
+ concerns = violations
537
+ # The violations of the network, kept current from here on
538
+ violations = pf_engine.check_violations()
539
+ found = {
540
+ key: excess
541
+ for key, excess in self._excesses(violations).items()
542
+ if key not in group
543
+ }
544
+ self._found = found
545
+ # The steps kept so far, those undone left out
546
+ kept = 0
547
+
548
+ # Log Grid State
549
+ grid_state_str = self._format_grid_state(violations)
550
+ iteration = 0
551
+ while iteration < self.max_iterations:
552
+ iteration += 1
553
+
554
+ # Cycle Detection
555
+ excesses = self._excesses(concerns)
556
+ # Of the state, every violation of the network: in all, as the algorithm
557
+ # rates states, and what each exceeds its limit by (see
558
+ # `_undo_what_brought_about`)
559
+ relative_excess = sum(_relative_excess(v) for v in violations)
560
+ measured = self._excesses(violations)
561
+ self._set_aside_after_a_cycle(excesses, iteration, pf_engine)
562
+
563
+ # Target Selection, Sensitivity Extraction and Action Evaluation: the most
564
+ # severe violation that an asset can relieve
565
+ target, action_candidates = self._next_target(
566
+ pf_engine, concerns, iteration, kept, grid_state_str
567
+ )
568
+
569
+ if target is None:
570
+ self._log_iteration(
571
+ iteration,
572
+ grid_state_str,
573
+ "None",
574
+ "No effective flexibility resources for the violations left.",
575
+ "None",
576
+ )
577
+ break
578
+
579
+ if not action_candidates:
580
+ # The steps that brought the target about were undone (see
581
+ # `_undo_what_brought_about`): the call goes on from the state before
582
+ # them, with the assets of their first step that did it left out
583
+ kept += 1
584
+ violations = pf_engine.check_violations()
585
+ concerns = self._concerns(violations, group, found)
586
+ grid_state_str = self._format_grid_state(violations)
587
+ if not concerns:
588
+ self._log_iteration(
589
+ iteration,
590
+ grid_state_str,
591
+ "None",
592
+ "The violations of the group, and what the steps added to "
593
+ "others, are resolved.",
594
+ "None",
595
+ )
596
+ break
597
+ continue
598
+
599
+ # Step 4: Action Sizing & Execution
600
+ # Balance the flexibility activation between the nodes. The step aims
601
+ # just inside the limit: sized for the limit itself, it ends on it to
602
+ # within the noise of the power flow, and on the wrong side as often as
603
+ # not, where the violation is still reported.
604
+ target_violation = abs(target.violation_value) + _SIZING_MARGIN * abs(
605
+ target.violated_value or 0.0
606
+ )
607
+
608
+ # Calculate total sensitivity of selected candidates to distribute MW equally
609
+ total_sens = sum(c["sens_abs"] for c in action_candidates)
610
+
611
+ # P_per_node * Sum(Sens) = Target => P_per_node = Target / Sum(Sens)
612
+ needed_p_per_node = (
613
+ target_violation / total_sens if total_sens > 1e-9 else 0
614
+ )
615
+
616
+ executed_actions_str = []
617
+ justifications_str = []
618
+ power_changed = False
619
+
620
+ for candidate in action_candidates:
621
+ candidate["effective_margin"] = min(
622
+ candidate["margin"], needed_p_per_node
623
+ )
624
+
625
+ action_details = self._execute_action(pf_engine, candidate)
626
+ power_changed = power_changed or action_details["delta"] != 0.0
627
+
628
+ # Log details for this action
629
+ sens_unit = (
630
+ "p.u./MW" if "VOLTAGE" in target.constraint_type.name else "%/MW"
631
+ )
632
+ justification = (
633
+ f"Extracted {candidate['sens_type']}. "
634
+ f"Node {candidate['element_name']} exhibited sensitivity "
635
+ f"{candidate['sens']:.4f} {sens_unit} and margin {candidate['margin']:.4f} MW."
636
+ )
637
+ justifications_str.append(justification)
638
+
639
+ action_str = (
640
+ f"{candidate['type']} on {candidate['element_name']}: "
641
+ f"{action_details['old_p']:.4f} MW -> {action_details['new_p']:.4f} MW "
642
+ f"(Delta: {action_details['delta']:.4f} MW)"
643
+ )
644
+ executed_actions_str.append(action_str)
645
+
646
+ self.history.append(
647
+ {
648
+ "iteration": iteration,
649
+ "violations": violations,
650
+ "excesses": excesses,
651
+ "relative_excess": relative_excess,
652
+ "measured": measured,
653
+ "target": (self._key(target), abs(target.violation_value)),
654
+ "action": candidate | action_details,
655
+ }
656
+ )
657
+
658
+ unit = "p.u." if "VOLTAGE" in target.constraint_type.name else "%"
659
+ self._log_iteration(
660
+ iteration,
661
+ grid_state_str,
662
+ f"{target.element_type} '{target.element_id}' ({target.constraint_type.value}) - Violation: {target.violation_value:.4f} {unit}",
663
+ "\n".join(justifications_str),
664
+ "\n".join(executed_actions_str),
665
+ )
666
+
667
+ # State Evaluation
668
+ pf_engine.run_power_flow(warm_start=True)
669
+ after = pf_engine.check_violations()
670
+ beyond = self._beyond_their_level(after)
671
+ if beyond:
672
+ # The step took a violation given up on beyond its level: undone. The
673
+ # state is the one before the step, whose violations are kept as they
674
+ # were measured. Of a step on several assets, each is tried again on
675
+ # its own, so that only one whose own step takes a violation given up
676
+ # on beyond its level is left out for this target
677
+ after = self._undo_or_split(pf_engine, iteration, target)
678
+ self._log_iteration(
679
+ iteration,
680
+ grid_state_str,
681
+ "None",
682
+ "Step undone: it took "
683
+ + ", ".join(f"'{key[1]}' ({key[0].value})" for key in beyond)
684
+ + " beyond the excess at which it was given up on."
685
+ + (" Part of it kept." if after is not None else ""),
686
+ "None",
687
+ )
688
+ if after is None:
689
+ continue
690
+ kept += 1
691
+ violations = after
692
+ concerns = self._concerns(violations, group, found)
693
+ # Log Grid State
694
+ grid_state_str = self._format_grid_state(violations)
695
+
696
+ if not concerns:
697
+ resolved = (
698
+ "Constraints Resolved."
699
+ if not violations
700
+ else "The violations of the group, and what the steps added to "
701
+ "others, are resolved."
702
+ )
703
+ self._log_iteration(iteration, grid_state_str, "None", resolved, "None")
704
+ break
705
+
706
+ if not power_changed:
707
+ # The steps are too small to change a power: repeating them would
708
+ # only use up the iterations
709
+ self._log_iteration(
710
+ iteration,
711
+ grid_state_str,
712
+ "None",
713
+ "The flexibility steps no longer change the powers.",
714
+ "None",
715
+ )
716
+ break
717
+
718
+ if iteration >= self.max_iterations and concerns:
719
+ self._log_iteration(
720
+ iteration,
721
+ "Unresolved Violations",
722
+ "None",
723
+ "Max iterations reached",
724
+ "None",
725
+ "Manual Engineering Intervention Required",
726
+ )
727
+
728
+ if self.history:
729
+ modified_buses = [
730
+ {
731
+ "bus_id": entry["action"]["bus_id"],
732
+ "element_name": entry["action"]["element_name"],
733
+ "element_type": entry["action"]["element_type"],
734
+ "element_index": entry["action"]["element_index"],
735
+ "action_type": entry["action"]["type"],
736
+ # Not rounded: reverting the action restores these powers
737
+ "old_power": entry["action"]["old_p"],
738
+ "old_reactive_power": entry["action"].get("old_q"),
739
+ "new_power": entry["action"]["new_p"],
740
+ }
741
+ for entry in self.history
742
+ ]
743
+ return {
744
+ "type": "flexibility_management",
745
+ "buses": modified_buses,
746
+ # The violations of the group that the call resolved
747
+ "total_violations_addressed": violation_count
748
+ - len(group & {self._key(v) for v in violations}),
749
+ }
750
+ else:
751
+ return None
752
+
753
+ @staticmethod
754
+ def _key(violation: ConstraintViolation) -> tuple[Any, Any]:
755
+ """A violation, whatever its value: its constraint type and element."""
756
+ return violation.constraint_type, violation.element_id
757
+
758
+ def _concerns(
759
+ self,
760
+ violations: list[ConstraintViolation],
761
+ group: set[tuple[Any, Any]],
762
+ found: dict[tuple[Any, Any], float],
763
+ ) -> list[ConstraintViolation]:
764
+ """
765
+ The violations the call acts on, among those of the network now: those of its
766
+ `group`, whole, and, of the others, what the steps of the call have added to
767
+ what they exceeded their limits by as it started (`found`, nothing for one
768
+ that was not there), as a violation of that excess (see `apply_to_group`).
769
+ """
770
+ concerns = []
771
+ for violation in violations:
772
+ key = self._key(violation)
773
+ if key in group:
774
+ concerns.append(violation)
775
+ continue
776
+ added = abs(violation.violation_value) - found.get(key, 0.0)
777
+ if added <= 0.0:
778
+ continue
779
+ if key in found:
780
+ # Only what the steps added: the rest is left to its turn
781
+ violation = copy.copy(violation)
782
+ violation.violation_value = math.copysign(
783
+ added, violation.violation_value
784
+ )
785
+ concerns.append(violation)
786
+ return concerns
787
+
788
+ def _capture_initial_state(self, pf_engine: PowerFlowEngine) -> None:
789
+ """Count the limits of the call from the powers of the assets now."""
790
+ self._limits_from = limits = {}
791
+ for asset_type in ("load", "sgen"):
792
+ assets = pf_engine.get_flexibility_data(asset_type)
793
+ if not assets.empty:
794
+ # By index: several assets can have the same name
795
+ for index, power in zip(
796
+ assets.index.tolist(), assets["p_mw"].tolist(), strict=True
797
+ ):
798
+ limits[(asset_type, index)] = power
799
+
800
+ @staticmethod
801
+ def _excesses(
802
+ violations: list[ConstraintViolation],
803
+ ) -> dict[tuple[Any, Any], float]:
804
+ """What each violation exceeds its limit by, by constraint type and element."""
805
+ return {
806
+ (v.constraint_type, v.element_id): abs(v.violation_value)
807
+ for v in violations
808
+ }
809
+
810
+ @staticmethod
811
+ def _no_better(
812
+ now: dict[tuple[Any, Any], float], then: dict[tuple[Any, Any], float]
813
+ ) -> bool:
814
+ """
815
+ Whether the state `now` is no better than the state `then`: every violation of
816
+ `then` is still there, and none is less than it was. Violations of `now` that
817
+ `then` did not have do not make it better.
818
+ """
819
+ return all(key in now and now[key] >= excess for key, excess in then.items())
820
+
821
+ def _set_aside_after_a_cycle(
822
+ self,
823
+ now: dict[tuple[Any, Any], float],
824
+ now_iteration: int,
825
+ pf_engine: PowerFlowEngine,
826
+ ) -> None:
827
+ """
828
+ Set an asset aside if the call has gone round in a cycle and come back, with
829
+ the violations `now` (`_excesses`) at iteration `now_iteration`, to a state no
830
+ better than one it has been in, having resolved since then only violations
831
+ met at or before that state: the asset acted on first from the latest such
832
+ state that is not set aside yet. Otherwise, with `min_round_relief_pct`,
833
+ judge the round that ends now, if one does (`_judge_round`). See
834
+ `apply_to_group`.
835
+ """
836
+ # The states of the call, latest first, each with the assets acted on from it
837
+ # in the order they were ranked, and the violation they were acted on for
838
+ states: dict[
839
+ int,
840
+ tuple[dict[tuple[Any, Any], float], list[tuple[str, Any]], tuple[Any, Any]],
841
+ ]
842
+ states = {}
843
+ for entry in reversed(self.history):
844
+ _, assets, _ = states.setdefault(
845
+ entry["iteration"], (entry["excesses"], [], entry["target"][0])
846
+ )
847
+ action = entry["action"]
848
+ assets.insert(0, (action["element_type"], action["element_index"]))
849
+ latest_first = list(states.items())
850
+
851
+ # The violations met at or before each state, in the same order
852
+ met: list[set[tuple[Any, Any]]] = []
853
+ met_so_far: set[tuple[Any, Any]] = set()
854
+ for _, (then, _, _) in reversed(latest_first):
855
+ met_so_far = met_so_far | then.keys()
856
+ met.append(met_so_far)
857
+ met.reverse()
858
+
859
+ # The violations of the states after the one looked at
860
+ since: set[tuple[Any, Any]] = set()
861
+ # The latest state that a round ending now started from
862
+ round_start = None
863
+ for position, ((iteration, (then, assets, _)), met_by_then) in enumerate(
864
+ zip(latest_first, met, strict=True)
865
+ ):
866
+ resolved_since = since - now.keys()
867
+ since |= then.keys()
868
+ if not resolved_since <= met_by_then:
869
+ continue
870
+ if self._no_better(now, then):
871
+ for asset_key in assets:
872
+ if asset_key not in self.tabu_list:
873
+ self.tabu_list.add(asset_key)
874
+ self._aside_at = len(latest_first)
875
+ self._judged = {}
876
+ logger.warning(
877
+ "Cycle detected: the violations are no better than at "
878
+ f"iteration {iteration}. {asset_key} set aside."
879
+ )
880
+ return
881
+ elif round_start is None and resolved_since and then.keys() <= now.keys():
882
+ round_start = position
883
+ if self.min_round_relief_pct > 0.0 and round_start is not None:
884
+ self._judge_round(latest_first, round_start, pf_engine)
885
+
886
+ def _judge_round(
887
+ self,
888
+ latest_first: list[
889
+ tuple[
890
+ int,
891
+ tuple[
892
+ dict[tuple[Any, Any], float],
893
+ list[tuple[str, Any]],
894
+ tuple[Any, Any],
895
+ ],
896
+ ]
897
+ ],
898
+ start: int,
899
+ pf_engine: PowerFlowEngine,
900
+ ) -> None:
901
+ """
902
+ Judge the round that ends now and started from the state `latest_first[start]`
903
+ (see `apply_to_group`): its reach is the largest excess of each violation over
904
+ its states, from its first to the last before now. It is slow if no violation
905
+ of the reach of the round before it, the one that ended at its first state, is
906
+ relieved by more than `min_round_relief_pct` of what it reached there; a
907
+ violation that the round does not reach is relieved. A slow round that
908
+ follows a slow round, the latest judged before it, sets aside an asset of the
909
+ steps of the two rounds: of a step for a violation outside the group of the
910
+ call, the latest such, or of the latest step if all are for the group. Rounds
911
+ whose round before started before the last asset set aside are not judged, so
912
+ that two new slow rounds are needed for the next. The asset is set aside only
913
+ if another could act on the violation its step was relieving
914
+ (`_relievable_without`); otherwise nothing is, and the see-saw goes on as
915
+ without a threshold until a slow round finds one.
916
+ """
917
+ # States are counted from the first of the call: undoing a step leaves the
918
+ # count of the states before it as it was, and judging the same round again
919
+ # after a step undone gives the same result
920
+ count = len(latest_first)
921
+ reach: dict[tuple[Any, Any], float] = {}
922
+ for _, (excesses, _, _) in latest_first[: start + 1]:
923
+ for key, excess in excesses.items():
924
+ reach[key] = max(reach.get(key, 0.0), excess)
925
+ first = count - 1 - start
926
+ self._reaches[count] = (first, reach)
927
+ if first not in self._reaches or self._reaches[first][0] < self._aside_at:
928
+ # The first round of the see-saw, with nothing to compare it with, or one
929
+ # whose round before started before the last asset was set aside: the
930
+ # rounds with the assets left are judged on rounds with those assets only
931
+ return
932
+ before = self._reaches[first][1]
933
+ kept = 1.0 - self.min_round_relief_pct / 100.0
934
+ slow = all(
935
+ key in reach and reach[key] >= excess * kept
936
+ for key, excess in before.items()
937
+ )
938
+ self._judged[count] = (first, slow)
939
+ earlier = [end for end in self._judged if end < count]
940
+ if not slow or not earlier or not self._judged[max(earlier)][1]:
941
+ return
942
+ # Two slow rounds in a row, this one and the one judged before it. The steps
943
+ # of the two, latest first: those for a violation outside the group first,
944
+ # as they bring back what the steps for the group relieve
945
+ span = latest_first[: count - min(first, self._judged[max(earlier)][0])]
946
+ outside = [state for state in span if state[1][2] not in self._group]
947
+ for iteration, (_, assets, _) in outside + span:
948
+ for asset_key in assets:
949
+ if asset_key not in self.tabu_list:
950
+ if not self._relievable_without(pf_engine, iteration, asset_key):
951
+ # No other asset for the violation it relieves: setting it
952
+ # aside would leave that violation, or the run to pay a
953
+ # reinforcement that going on avoids
954
+ return
955
+ self.tabu_list.add(asset_key)
956
+ self._aside_at = count
957
+ self._judged = {}
958
+ logger.warning(
959
+ "Slow rounds: two rounds in a row relieved no violation by "
960
+ f"more than {self.min_round_relief_pct:g} % of its reach; "
961
+ f"{asset_key}, acted on at iteration {iteration}, set aside."
962
+ )
963
+ return
964
+
965
+ def _forget_rounds(self) -> None:
966
+ """
967
+ Forget the rounds of the call, after steps other than the latest were undone
968
+ (`_undo_what_brought_about`): the states they were counted from are gone, or
969
+ come back as they were before those steps. As after an asset set aside, the
970
+ rounds whose round before started before now are not judged, so that two new
971
+ slow rounds are needed.
972
+ """
973
+ self._reaches = {}
974
+ self._judged = {}
975
+ self._aside_at = len({entry["iteration"] for entry in self.history})
976
+
977
+ def _relievable_without(
978
+ self, pf_engine: PowerFlowEngine, iteration: int, asset_key: tuple[str, Any]
979
+ ) -> bool:
980
+ """
981
+ Whether an asset other than `asset_key`, and than those set aside or left out
982
+ for it, could act now on the violation that the step of `iteration` acted on,
983
+ as the call acted on it (for a violation outside the group that was there as
984
+ the call started, the excess its steps added), by the test that picks the
985
+ candidates of a target (`_evaluate_actions`) on the sensitivities of the state
986
+ now. No power flow is run.
987
+ """
988
+ entry = next(e for e in reversed(self.history) if e["iteration"] == iteration)
989
+ key, excess = entry["target"]
990
+ violation = copy.copy(
991
+ next(v for v in entry["violations"] if self._key(v) == key)
992
+ )
993
+ violation.violation_value = math.copysign(excess, violation.violation_value)
994
+ self.tabu_list.add(asset_key)
995
+ try:
996
+ sensitivities = self._extract_sensitivities(pf_engine, violation)
997
+ return bool(self._evaluate_actions(pf_engine, violation, sensitivities))
998
+ finally:
999
+ self.tabu_list.discard(asset_key)
1000
+
1001
+ def _next_target(
1002
+ self,
1003
+ pf_engine: PowerFlowEngine,
1004
+ concerns: list[ConstraintViolation],
1005
+ iteration: int,
1006
+ kept: int,
1007
+ grid_state_str: str,
1008
+ ) -> tuple[ConstraintViolation | None, list[dict[str, Any]]]:
1009
+ """
1010
+ The violation to take the next step on, with the candidates to take it with:
1011
+ of the violations the call acts on (`concerns`), the most severe that an asset
1012
+ can relieve. One that none can is set aside (`unrelievable`), and the next is
1013
+ examined. Those set aside are examined again, most severe first, once no other
1014
+ is left, if a step has been kept since they were last examined (`kept` counts
1015
+ the steps kept): a step can bring an excess down to where the assets left can
1016
+ relieve enough of it, or change a sensitivity, where a step undone leaves the
1017
+ network as it was. None, and no candidate, if no violation the call acts on
1018
+ can be relieved. A violation and no candidate if the steps that brought that
1019
+ violation about, or worsened it, were undone instead of setting it aside
1020
+ (see `_undo_what_brought_about`): the network has changed.
1021
+ """
1022
+ ranked = sorted(concerns, key=self._severity, reverse=True)
1023
+ fresh = [v for v in ranked if self._key(v) not in self.unrelievable]
1024
+ again = [
1025
+ v
1026
+ for v in ranked
1027
+ if self._key(v) in self.unrelievable
1028
+ and self._examined_after[self._key(v)] < kept
1029
+ ]
1030
+ for target in fresh + again:
1031
+ key = self._key(target)
1032
+ sensitivities = self._extract_sensitivities(pf_engine, target)
1033
+ candidates = self._evaluate_actions(pf_engine, target, sensitivities)
1034
+ if candidates:
1035
+ self.unrelievable.pop(key, None)
1036
+ self._examined_after.pop(key, None)
1037
+ return target, candidates
1038
+ if self._undo_what_brought_about(pf_engine, target) is not None:
1039
+ self._forget_rounds()
1040
+ self._log_iteration(
1041
+ iteration,
1042
+ grid_state_str,
1043
+ f"{target.element_type} '{target.element_id}' ({target.constraint_type.value})",
1044
+ "Steps undone: they brought it about or worsened it, the assets "
1045
+ "that relieve it are left out, and the network is more severe in "
1046
+ "total than before them.",
1047
+ "None",
1048
+ )
1049
+ return target, []
1050
+ # What it exceeds its limit by, of the whole violation for one the call
1051
+ # acts on only in part: the lowest of the call is its level, which no
1052
+ # step takes it beyond for the rest of the call, also when it is taken up
1053
+ # again
1054
+ excess = abs(target.violation_value) + self._found.get(key, 0.0)
1055
+ self._levels[key] = min(self._levels.get(key, excess), excess)
1056
+ self.unrelievable[key] = self._levels[key]
1057
+ self._examined_after[key] = kept
1058
+ unit = "p.u." if "VOLTAGE" in target.constraint_type.name else "%"
1059
+ self._log_iteration(
1060
+ iteration,
1061
+ grid_state_str,
1062
+ f"{target.element_type} '{target.element_id}' ({target.constraint_type.value}) - Violation: {target.violation_value:.4f} {unit}",
1063
+ "No effective flexibility resources available: set aside.",
1064
+ "None",
1065
+ )
1066
+ return None, []
1067
+
1068
+ def _beyond_their_level(
1069
+ self, violations: list[ConstraintViolation]
1070
+ ) -> list[tuple[Any, Any]]:
1071
+ """The violations the call has given up on, now or before, that exceed their
1072
+ limits by more than their levels (see `apply_to_group`)."""
1073
+ now = self._excesses(violations)
1074
+ return [key for key, level in self._levels.items() if now.get(key, 0.0) > level]
1075
+
1076
+ def _undo(self, pf_engine: PowerFlowEngine, entries: list[dict[str, Any]]) -> None:
1077
+ """
1078
+ Undo the steps of `entries`, entries of `history`: give their assets back
1079
+ their powers, the reactive power of a load included, drop them from `history`,
1080
+ and solve the power flow again.
1081
+ """
1082
+ for entry in reversed(entries):
1083
+ action = entry["action"]
1084
+ reactive = (
1085
+ {} if action.get("old_q") is None else {"new_q_mvar": action["old_q"]}
1086
+ )
1087
+ pf_engine.apply_flexibility_action(
1088
+ action["element_type"],
1089
+ int(action["element_index"]),
1090
+ action["old_p"],
1091
+ **reactive,
1092
+ )
1093
+ undone = {id(entry) for entry in entries}
1094
+ self.history = [e for e in self.history if id(e) not in undone]
1095
+ pf_engine.run_power_flow(warm_start=True)
1096
+
1097
+ def _undo_or_split(
1098
+ self,
1099
+ pf_engine: PowerFlowEngine,
1100
+ iteration: int,
1101
+ target: ConstraintViolation,
1102
+ ) -> list[ConstraintViolation] | None:
1103
+ """
1104
+ Undo the step of `iteration`, which took a violation given up on beyond its
1105
+ level. A step on one asset leaves that asset out of the candidates of
1106
+ `target` for the rest of the call. A step on several assets is taken again
1107
+ one asset at a time, in the order they were ranked, each by what it took in
1108
+ the step and measured by a power flow: an asset whose step, after those kept
1109
+ before it, takes a violation given up on beyond its level is undone and left
1110
+ out for `target`; the others are kept.
1111
+
1112
+ Returns:
1113
+ The violations measured after the last asset kept, None if none is.
1114
+ """
1115
+ entries = [e for e in self.history if e["iteration"] == iteration]
1116
+ self._undo(pf_engine, entries)
1117
+ left_out = self._spoilers.setdefault(self._key(target), set())
1118
+ if len(entries) == 1:
1119
+ action = entries[0]["action"]
1120
+ left_out.add((action["element_type"], action["element_index"]))
1121
+ return None
1122
+ after = None
1123
+ for entry in entries:
1124
+ action = entry["action"]
1125
+ # Undone exactly: the asset is back at the power the step started from,
1126
+ # and the same step takes it to the same power
1127
+ self._execute_action(pf_engine, action)
1128
+ self.history.append(entry)
1129
+ pf_engine.run_power_flow(warm_start=True)
1130
+ measured = pf_engine.check_violations()
1131
+ if self._beyond_their_level(measured):
1132
+ self._undo(pf_engine, [entry])
1133
+ left_out.add((action["element_type"], action["element_index"]))
1134
+ else:
1135
+ after = measured
1136
+ return after
1137
+
1138
+ def _redo(self, pf_engine: PowerFlowEngine, entries: list[dict[str, Any]]) -> None:
1139
+ """
1140
+ Take again the steps of `entries`, undone by `_undo` from the state they were
1141
+ taken from, in their order, put them back in `history`, and solve the power
1142
+ flow again. Each asset gets the power its step gave it.
1143
+ """
1144
+ for entry in entries:
1145
+ self._execute_action(pf_engine, entry["action"])
1146
+ self.history.append(entry)
1147
+ pf_engine.run_power_flow(warm_start=True)
1148
+
1149
+ def _undo_what_brought_about(
1150
+ self,
1151
+ pf_engine: PowerFlowEngine,
1152
+ target: ConstraintViolation,
1153
+ ) -> list[ConstraintViolation] | None:
1154
+ """
1155
+ Undo the steps that brought `target` about, or worsened it, a violation the
1156
+ call acts on that no asset left can relieve, if an asset that relieves it has
1157
+ been left out of its candidates (`_spoilers`: by the level rule, after its
1158
+ step for it, or by an earlier undoing), and if the steps did more harm than
1159
+ good (see `apply_to_group`).
1160
+
1161
+ The steps are those since the latest of the states in which the call acted
1162
+ on the least of `target` (nothing, for one it brought about), if it acts on
1163
+ more of it now. They are undone together, if:
1164
+
1165
+ - the network is more severe in total now than in that state, by the sum of
1166
+ the `_relative_excess` of all its violations, as the algorithm rates
1167
+ states: what the steps brought about, or added to, outweighs what they
1168
+ relieved, outside the group as in it;
1169
+ - no violation given up on exceeded its limit by more than its level in that
1170
+ state, as the call measured it then: undoing the steps brings that state
1171
+ back, to the precision of the power flow, and a level may have been
1172
+ lowered since. Telling it costs no power flow.
1173
+
1174
+ Of the first step, an asset on its own is left out of the candidates of its
1175
+ target for the rest of the call; the assets of a step on several are taken
1176
+ again one at a time, in the order they were ranked, each measured by a power
1177
+ flow, and an asset after which the call acts on more of `target` than in
1178
+ that state (beyond `_SIZING_MARGIN` of its limit, if it was there), or a
1179
+ violation given up on is beyond its level, is undone and left out, the
1180
+ others kept; if none is, the last one is.
1181
+
1182
+ Returns:
1183
+ The violations measured after, None if nothing was undone.
1184
+ """
1185
+ key = self._key(target)
1186
+ if not self._spoilers.get(key):
1187
+ return None
1188
+ # The state the call acted on the least of it in, the latest of them: the
1189
+ # steps since then brought it about, or added to it
1190
+ states = {}
1191
+ for entry in self.history:
1192
+ states.setdefault(entry["iteration"], entry)
1193
+ if not states:
1194
+ return None
1195
+ start = min(states, key=lambda it: (states[it]["excesses"].get(key, 0.0), -it))
1196
+ least = states[start]["excesses"].get(key, 0.0)
1197
+ if abs(target.violation_value) <= least:
1198
+ return None
1199
+ undone = [e for e in self.history if e["iteration"] >= start]
1200
+ now = sum(_relative_excess(v) for v in pf_engine.check_violations())
1201
+ if now <= undone[0]["relative_excess"]:
1202
+ return None
1203
+ then = undone[0]["measured"]
1204
+ if any(then.get(k, 0.0) > level for k, level in self._levels.items()):
1205
+ return None
1206
+ self._undo(pf_engine, undone)
1207
+
1208
+ first = [e for e in undone if e["iteration"] == undone[0]["iteration"]]
1209
+ left_out = self._spoilers.setdefault(first[0]["target"][0], set())
1210
+ if len(first) == 1:
1211
+ left_out.add(self._asset(first[0]))
1212
+ return pf_engine.check_violations()
1213
+ # Of a violation that was there in that state, the excesses compared are
1214
+ # both above the limit, and every asset moves them a little: a change under
1215
+ # the margin by which a step aims inside a limit is not counted. One that
1216
+ # was not there is compared with the limit itself, as the violations are
1217
+ tolerance = _SIZING_MARGIN * abs(target.violated_value or 0.0) if least else 0.0
1218
+ harmful = []
1219
+ for entry in first:
1220
+ self._redo(pf_engine, [entry])
1221
+ measured = pf_engine.check_violations()
1222
+ # What the call acts on of it, against the least it acted on
1223
+ acted_on = self._excesses(measured).get(key, 0.0) - self._found.get(
1224
+ key, 0.0
1225
+ )
1226
+ if self._beyond_their_level(measured) or acted_on > least + tolerance:
1227
+ self._undo(pf_engine, [entry])
1228
+ harmful.append(entry)
1229
+ if not harmful:
1230
+ # Taken again one at a time, the assets do not bring it back, where the
1231
+ # step did: the power flow does not give a state back bit for bit, and an
1232
+ # engine can depend on the path. The last one is left out, so that the
1233
+ # step, its target with its assets, cannot be taken again
1234
+ harmful.append(first[-1])
1235
+ self._undo(pf_engine, harmful)
1236
+ left_out.update(self._asset(entry) for entry in harmful)
1237
+ return pf_engine.check_violations()
1238
+
1239
+ @staticmethod
1240
+ def _asset(entry: dict[str, Any]) -> tuple[str, Any]:
1241
+ """The asset of an entry of `history`, by type and index."""
1242
+ return entry["action"]["element_type"], entry["action"]["element_index"]
1243
+
1244
+ @staticmethod
1245
+ def _severity(violation: ConstraintViolation) -> float:
1246
+ """How severe a violation is, for the choice of the target: relative to its limit."""
1247
+ if violation.violated_value == 0:
1248
+ return 0
1249
+ return abs(violation.violation_value) / abs(violation.violated_value)
1250
+
1251
+ @staticmethod
1252
+ def _extract_sensitivities(
1253
+ pf_engine: PowerFlowEngine, target: ConstraintViolation
1254
+ ) -> dict[str, float]:
1255
+ sensitivities = {}
1256
+
1257
+ if target.constraint_type in [
1258
+ ConstraintType.OVER_VOLTAGE,
1259
+ ConstraintType.UNDER_VOLTAGE,
1260
+ ]:
1261
+ # Voltage Sensitivities, of the target bus only
1262
+ df = pf_engine.calculate_voltage_power_sensitivities(
1263
+ buses=[target.element_id]
1264
+ )
1265
+ if not df.empty and target.element_id in df.index:
1266
+ # Row is target bus, Columns are injection buses
1267
+ sensitivities = df.loc[target.element_id].to_dict()
1268
+
1269
+ elif target.constraint_type in [
1270
+ ConstraintType.LINE_LOADING,
1271
+ ConstraintType.TRANSFORMER_LOADING,
1272
+ ]:
1273
+ # Thermal Sensitivities
1274
+ df = pf_engine.calculate_branch_loading_sensitivities(
1275
+ target.element_type, target.element_id
1276
+ )
1277
+ if not df.empty:
1278
+ # d(loading %)/d(injection in MW): positive where injecting more at
1279
+ # the bus raises the loading, whatever the direction of the flow
1280
+ sensitivities = df["sensitivity"].to_dict()
1281
+
1282
+ return sensitivities
1283
+
1284
+ def _evaluate_actions(
1285
+ self,
1286
+ pf_engine: PowerFlowEngine,
1287
+ target: ConstraintViolation,
1288
+ sensitivities: dict[str, float],
1289
+ ) -> list[dict[str, Any]]:
1290
+ # Every action reduces the power of an asset (shedding or curtailment), which
1291
+ # raises the injection at its bus for a load and lowers it for a generator.
1292
+ # Against an under-voltage only shedding load is considered, against an
1293
+ # over-voltage only curtailing generation, and against a loading violation
1294
+ # both. Only the assets whose action moves the violated quantity the right way
1295
+ # are kept, ranked by what a MW of their action relieves.
1296
+ if target.constraint_type in (
1297
+ ConstraintType.LINE_LOADING,
1298
+ ConstraintType.TRANSFORMER_LOADING,
1299
+ ):
1300
+ asset_types = ["load", "sgen"]
1301
+ elif target.constraint_type == ConstraintType.UNDER_VOLTAGE:
1302
+ asset_types = ["load"]
1303
+ elif target.constraint_type == ConstraintType.OVER_VOLTAGE:
1304
+ asset_types = ["sgen"]
1305
+ else:
1306
+ return []
1307
+
1308
+ # The violated quantity must go up for an under-voltage, down otherwise
1309
+ wanted_change = (
1310
+ 1.0 if target.constraint_type == ConstraintType.UNDER_VOLTAGE else -1.0
1311
+ )
1312
+ delta_target = abs(target.violation_value)
1313
+ min_relief = self.min_achievable_relief_pct / 100.0 * delta_target
1314
+ negligible_relief = self.min_asset_relief_pct / 100.0 * delta_target
1315
+ sens_type = (
1316
+ "active power voltage sensitivity"
1317
+ if "VOLTAGE" in target.constraint_type.name
1318
+ else "active power injection shift factors"
1319
+ )
1320
+
1321
+ # The assets left out: those set aside after a cycle, and those a step for
1322
+ # this target took a violation set aside beyond its level with
1323
+ excluded = self.tabu_list | self._spoilers.get(
1324
+ (target.constraint_type, target.element_id), set()
1325
+ )
1326
+
1327
+ # Loads first, then generators, each in the order of the network's table:
1328
+ # the order breaks ties between equal sensitivities
1329
+ candidates = []
1330
+ for asset_type in asset_types:
1331
+ assets = pf_engine.get_flexibility_data(asset_type)
1332
+ if assets.empty:
1333
+ continue
1334
+ # What a MW of the action changes in the injection at the bus of the asset
1335
+ injection_change = 1.0 if asset_type == "load" else -1.0
1336
+ candidates += self._evaluate_assets(
1337
+ asset_type,
1338
+ assets,
1339
+ sensitivities,
1340
+ wanted_change * injection_change,
1341
+ delta_target,
1342
+ negligible_relief,
1343
+ sens_type,
1344
+ excluded,
1345
+ )
1346
+
1347
+ # Flexibility is worth using if the candidates relieve enough of the violation
1348
+ # together, however small each of them is
1349
+ if sum(c["achievable_relief"] for c in candidates) < min_relief:
1350
+ return []
1351
+
1352
+ # Select optimal nodes
1353
+ candidates.sort(key=lambda x: x["sens_abs"], reverse=True)
1354
+ return candidates[: self.n_activation]
1355
+
1356
+ def _evaluate_assets(
1357
+ self,
1358
+ asset_type: str,
1359
+ assets: pd.DataFrame,
1360
+ sensitivities: dict[str, float],
1361
+ relief_sign: float,
1362
+ delta_target: float,
1363
+ negligible_relief: float,
1364
+ sens_type: str,
1365
+ excluded: frozenset | set = frozenset(),
1366
+ ) -> list[dict[str, Any]]:
1367
+ """
1368
+ The candidate actions on the assets of one type, in the order of the table,
1369
+ those of `excluded` (by type and index) left out.
1370
+
1371
+ `sensitivities` are those of the violated quantity to the injection at each
1372
+ bus, and `relief_sign` the sign they must have for the action on these assets
1373
+ to reduce the violation. An asset of the opposite sign would worsen it, and is
1374
+ left out.
1375
+
1376
+ The tests run on whole columns, and are written as their negation
1377
+ (``~(x < limit)``) so that a NaN passes them as it would a scalar test.
1378
+ """
1379
+ names = assets["name"].tolist()
1380
+ buses = assets["bus_name"].tolist()
1381
+ p = assets["p_mw"].to_numpy(dtype=float)
1382
+
1383
+ # The sensitivity of the target to the injection at the asset's bus
1384
+ sens = np.array([sensitivities.get(bus, 0.0) for bus in buses], dtype=float)
1385
+ # What a MW of the action relieves of the violation: negative if it worsens it
1386
+ sens_abs = relief_sign * sens
1387
+
1388
+ initial_p = np.array(
1389
+ [
1390
+ self._limits_from.get((asset_type, index), power)
1391
+ for index, power in zip(assets.index.tolist(), p.tolist(), strict=True)
1392
+ ],
1393
+ dtype=float,
1394
+ )
1395
+ # Not under zero: no more than the power of the asset can be taken off the
1396
+ # network, whatever its flexibility (a max_flex_pct over 100)
1397
+ min_p = np.maximum(
1398
+ initial_p * (1.0 - assets["max_flex_pct"].to_numpy(dtype=float) / 100.0),
1399
+ 0.0,
1400
+ )
1401
+ margin = p - min_p
1402
+
1403
+ # Cap the useful margin at what is needed, then leave out the assets whose
1404
+ # effect on the violation is negligible
1405
+ with np.errstate(divide="ignore", invalid="ignore"):
1406
+ delta_p_needed = delta_target / sens_abs
1407
+ effective_margin = np.where(delta_p_needed < margin, delta_p_needed, margin)
1408
+ achievable_relief = effective_margin * sens_abs
1409
+
1410
+ keep = (
1411
+ ~(sens_abs < 1e-6)
1412
+ & ~(margin < 1e-4)
1413
+ & ~(achievable_relief < negligible_relief)
1414
+ )
1415
+ if excluded:
1416
+ keep &= np.array(
1417
+ [
1418
+ (asset_type, index) not in excluded
1419
+ for index in assets.index.tolist()
1420
+ ],
1421
+ dtype=bool,
1422
+ )
1423
+
1424
+ # Needed to undo a shed: the power factor is lost at zero power. Of loads only:
1425
+ # curtailing a generator does not touch its reactive power, so undoing the
1426
+ # curtailment must not set it either, whatever the engine gives for generators
1427
+ q = (
1428
+ assets["q_mvar"].tolist()
1429
+ if asset_type == "load" and "q_mvar" in assets.columns
1430
+ else None
1431
+ )
1432
+ action_type = "gen_curtailment" if asset_type == "sgen" else "load_shedding"
1433
+ index = assets.index.tolist()
1434
+ candidates = []
1435
+ for i in np.flatnonzero(keep).tolist():
1436
+ candidates.append(
1437
+ {
1438
+ "element_name": names[i],
1439
+ "element_type": asset_type,
1440
+ "element_index": index[i],
1441
+ "bus_id": buses[i],
1442
+ "type": action_type,
1443
+ "sens": float(sens[i]),
1444
+ "margin": float(margin[i]),
1445
+ "achievable_relief": float(achievable_relief[i]),
1446
+ "sens_abs": float(sens_abs[i]), # Relief per MW, for the ranking
1447
+ "current_p": float(p[i]),
1448
+ "current_q": None if q is None else q[i],
1449
+ "min_p": float(min_p[i]),
1450
+ "effective_margin": float(effective_margin[i]),
1451
+ "sens_type": sens_type,
1452
+ }
1453
+ )
1454
+ return candidates
1455
+
1456
+ @staticmethod
1457
+ def _execute_action(
1458
+ pf_engine: PowerFlowEngine, candidate: dict[str, Any]
1459
+ ) -> dict[str, float | None]:
1460
+ # Apply. The engine does not go under zero, and neither must the record of the
1461
+ # action, which is what is charged
1462
+ new_p = max(candidate["current_p"] - candidate["effective_margin"], 0.0)
1463
+ pf_engine.apply_flexibility_action(
1464
+ candidate["element_type"], int(candidate["element_index"]), new_p
1465
+ )
1466
+
1467
+ return {
1468
+ "old_p": candidate["current_p"],
1469
+ "old_q": candidate.get("current_q"),
1470
+ "new_p": new_p,
1471
+ "delta": candidate["current_p"] - new_p,
1472
+ }
1473
+
1474
+ def _log(self, msg):
1475
+ logger.info(msg)
1476
+ self.logs.append(msg)