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,1846 @@
1
+ import math
2
+ from collections.abc import Container, Mapping
3
+ from typing import Any
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+
8
+ from gridforge import CostModel, PowerFlowEngine
9
+ from gridforge.core.constraints import ConstraintType, ConstraintViolation
10
+ from gridforge.core.cost_model import MissingUnitCostError
11
+ from gridforge.core.power_flow import type_in_place
12
+ from gridforge.core.strategy import EnhancementStrategy, note_origins
13
+ from gridforge.strategies.sizing import (
14
+ SizingOption,
15
+ charge,
16
+ choose_option,
17
+ keep_type_option,
18
+ type_change_option,
19
+ units_to_carry,
20
+ unlogged,
21
+ )
22
+ from gridforge.strategies.step_check import StepCheck
23
+ from gridforge.utils.logging import logger as _logger
24
+
25
+
26
+ class LineUpgradeStrategy(EnhancementStrategy):
27
+ """
28
+ Strategy to upgrade lines to address line loading and voltage violations.
29
+
30
+ This strategy identifies overloaded lines or lines contributing to voltage violations
31
+ and upgrades them to a type with higher capacity or lower impedance.
32
+
33
+ Attributes:
34
+ line_types_dict (Dict[str, Dict[str, List[str]]]): Dictionary of available line types.
35
+ line_types (List[str]): Combined list of all available line types.
36
+ max_iterations (int): Maximum number of iterations for the upgrade loop.
37
+ min_voltage_sensitivity (float): Minimum voltage change (p.u.) that the next upgrade
38
+ step of a line must be predicted to bring to a violated bus for the step to be
39
+ considered. See `__init__`.
40
+ logs (List[str]): List of log messages generated during execution.
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ line_types: dict[str, dict[str, list[str]]],
46
+ max_iterations: int = 100,
47
+ min_voltage_sensitivity: float = 0.0001,
48
+ restrict_to_violation_zone: bool = False,
49
+ one_upgrade_per_zone: bool = False,
50
+ ):
51
+ """
52
+ Initialize the LineUpgradeStrategy.
53
+
54
+ Args:
55
+ line_types (Dict[str, Dict[str, List[str]]]): Dictionary of available line types.
56
+ First level keys are voltage levels (e.g., 'mv', 'lv').
57
+ Second level keys are 'overhead' and 'underground'.
58
+ Values are lists of line type strings.
59
+ max_iterations (int, optional): Maximum number of iterations. Defaults to 100.
60
+ min_voltage_sensitivity (float, optional): Threshold below which an upgrade step
61
+ is not worth its works, for voltage violations. It is a voltage change, in
62
+ p.u. of the nominal voltage (0.001 is 0.4 V on a 400 V network): the next
63
+ step of a line (next conductor type, or one more parallel conductor) is
64
+ only considered if it is predicted to move at least one violated bus by
65
+ this much towards its limit, or by what that bus exceeds its limit by if
66
+ that is less, without moving the violated buses the wrong way on average.
67
+ When no line has such a step the strategy stops, and leaves the remaining
68
+ violations to the other strategies: line upgrades cannot fix them at a
69
+ sensible cost, as when the voltage of the source itself is out of its
70
+ limits. A step is judged on the buses it helps, however many others are
71
+ violated. With 0.0, every step predicted to improve the violated buses is
72
+ considered, down to the last parallel conductor that `max_iterations`
73
+ allows. Despite its name, kept for compatibility, it is not a
74
+ sensitivity dV/dr. Thermal upgrades do not use it. Defaults to 0.0001.
75
+ restrict_to_violation_zone (bool, optional): For voltage violations, only consider
76
+ lines of the galvanic zones (no transformer crossed) of the violated buses, so an
77
+ LV over-voltage is fixed with LV lines rather than with the MV trunk. Defaults to False.
78
+ one_upgrade_per_zone (bool, optional): For voltage violations, upgrade the best line
79
+ of every violated galvanic zone at each iteration instead of a single line in the
80
+ whole network (zones are nearly independent, so this saves many power flows on
81
+ large feeders). Defaults to False.
82
+ """
83
+ super().__init__()
84
+ self.line_types_dict = line_types
85
+ self.max_iterations = max_iterations
86
+ self.min_voltage_sensitivity = min_voltage_sensitivity
87
+ self.restrict_to_violation_zone = restrict_to_violation_zone
88
+ self.one_upgrade_per_zone = one_upgrade_per_zone
89
+ # The type and conductors of each line before the action under way, shared by
90
+ # its thermal and voltage steps (see `_states_before_the_action`)
91
+ self._before_action: dict[str, tuple[str | None, int]] | None = None
92
+
93
+ # Flatten line types for easy access
94
+ self.line_types = []
95
+ for voltage_level in line_types:
96
+ for category in line_types[voltage_level]:
97
+ self.line_types.extend(line_types[voltage_level][category])
98
+
99
+ @property
100
+ def name(self) -> str:
101
+ """
102
+ Get the name of the strategy.
103
+
104
+ Returns:
105
+ str: The name of the strategy ("Line Upgrade").
106
+ """
107
+ return "Line Upgrade"
108
+
109
+ @property
110
+ def stage(self) -> str:
111
+ """
112
+ Get the stage of the strategy.
113
+
114
+ Returns:
115
+ str: The stage ("planning").
116
+ """
117
+ return "planning"
118
+
119
+ @property
120
+ def cost_level(self) -> int:
121
+ """
122
+ Get the cost level of the strategy.
123
+
124
+ Returns:
125
+ int: The cost level (3 for line upgrades).
126
+ """
127
+ # Line upgrades are moderately expensive
128
+ return 3
129
+
130
+ def applicable_constraints(self) -> set[ConstraintType]:
131
+ """
132
+ Get the set of applicable constraint types.
133
+
134
+ Returns:
135
+ Set[ConstraintType]: The set of applicable constraint types.
136
+ """
137
+ return {
138
+ ConstraintType.LINE_LOADING,
139
+ ConstraintType.OVER_VOLTAGE,
140
+ ConstraintType.UNDER_VOLTAGE,
141
+ }
142
+
143
+ def apply_to_group(
144
+ self, violations: list[ConstraintViolation], pf_engine: PowerFlowEngine
145
+ ) -> dict[str, Any] | None:
146
+ """
147
+ Apply line upgrades to address a group of violations.
148
+
149
+ This method delegates to specialized methods for handling different types of violations:
150
+ - Line loading violations are handled by `_handle_line_loading_violations`
151
+ - Voltage violations are handled by `_handle_voltage_violations`
152
+
153
+ Args:
154
+ violations (List[ConstraintViolation]): List of violations to address.
155
+ pf_engine (PowerFlowEngine): The power flow engine.
156
+
157
+ Returns:
158
+ Optional[Dict[str, Any]]: A dictionary of upgrade actions if any were performed, otherwise None.
159
+ """
160
+ self.logs = []
161
+ # Check if we have any violations
162
+ if not violations:
163
+ return None
164
+
165
+ # Track upgrade actions
166
+ line_upgrades = []
167
+
168
+ # Check if we have voltage violations
169
+ voltage_violations = [
170
+ v
171
+ for v in violations
172
+ if v.constraint_type
173
+ in (ConstraintType.OVER_VOLTAGE, ConstraintType.UNDER_VOLTAGE)
174
+ ]
175
+
176
+ # Check if we have line loading violations
177
+ line_loading_violations = [
178
+ v for v in violations if v.constraint_type == ConstraintType.LINE_LOADING
179
+ ]
180
+
181
+ # The thermal and the voltage steps of the action share the state of each line
182
+ # before it, from which `calculate_cost` charges the action
183
+ self._before_action = {}
184
+ try:
185
+ # Handle line loading violations
186
+ if line_loading_violations:
187
+ line_upgrades.extend(
188
+ self._handle_line_loading_violations(
189
+ line_loading_violations, pf_engine
190
+ )
191
+ )
192
+ if line_upgrades and voltage_violations:
193
+ # The voltage violations given were measured before the thermal
194
+ # steps, which move the voltages: the latest power flow, which
195
+ # ended the thermal steps, has the ones to handle
196
+ voltage_violations = [
197
+ v
198
+ for v in pf_engine.check_violations()
199
+ if v.constraint_type
200
+ in (ConstraintType.OVER_VOLTAGE, ConstraintType.UNDER_VOLTAGE)
201
+ ]
202
+
203
+ # Handle voltage violations
204
+ if voltage_violations:
205
+ line_upgrades.extend(
206
+ self._handle_voltage_violations(voltage_violations, pf_engine)
207
+ )
208
+ finally:
209
+ self._before_action = None
210
+
211
+ # The state each line is charged from, if the strategy holds it, so that the
212
+ # action is charged as its options were priced
213
+ note_origins(
214
+ line_upgrades,
215
+ getattr(self, "line_origins", None),
216
+ "line_id",
217
+ "origin_conductors",
218
+ )
219
+ if line_upgrades:
220
+ return {
221
+ "type": "line_upgrade",
222
+ "lines": line_upgrades,
223
+ "violation_type": [v.constraint_type.value for v in violations],
224
+ "total_violations_addressed": len(violations),
225
+ }
226
+
227
+ return None
228
+
229
+ def _handle_line_loading_violations(
230
+ self, violations: list[ConstraintViolation], pf_engine: PowerFlowEngine
231
+ ) -> list[dict[str, Any]]:
232
+ """
233
+ Handle line loading violations by upgrading overloaded lines.
234
+
235
+ At each iteration, every line that is overloaded then gets one step towards the
236
+ state `_choose_thermal_upgrade` chooses for it, from its state before the
237
+ action: a conductor type of higher rating, or one more parallel conductor. A
238
+ line is thus not reinforced further once it is within its limit, and a line
239
+ that becomes overloaded along the way is treated.
240
+
241
+ With prices, a type change can also take back conductors that the action has
242
+ added to the line: the type change then leaves the line with the conductors
243
+ of the option, as few as those it had before the action, which the engine
244
+ sets with `set_line_parallel`.
245
+
246
+ A type change sized to carry the line with the conductors it leaves, a
247
+ take-back or not, is checked by the power flow that follows the iteration
248
+ (see `StepCheck`): under generation, or in a mesh, the step moves the current
249
+ it was sized on. If the line is overloaded, the type change is undone: the
250
+ engine gives the line back what it was before it (`save_line`,
251
+ `restore_line`) and puts back the solution the iteration was decided on
252
+ (`save_solution`, `restore_solution`), the type is offered to the line with
253
+ at least one more conductor for the rest of the action, a line whose take-back
254
+ is undone takes no other, and the line takes in its place the step chosen on
255
+ the same power flow with those offers. The iteration then ends as it would
256
+ have had the type not been offered with so few conductors, in state, entries,
257
+ charge and results, with one more power flow. Unless the engine can do the
258
+ four operations, no step is checked and no conductor is taken back.
259
+
260
+ Args:
261
+ violations (List[ConstraintViolation]): List of line loading constraint violations.
262
+ pf_engine (PowerFlowEngine): Power flow engine instance.
263
+
264
+ Returns:
265
+ List[Dict[str, Any]]: List of line upgrade actions performed.
266
+ """
267
+ line_upgrades: list[dict[str, Any]] = []
268
+ action_count = 0
269
+
270
+ # A conductor may be loaded up to the limit (%) of its rating
271
+ max_loading = getattr(
272
+ getattr(pf_engine, "constraints", None), "max_line_loading", 100.0
273
+ )
274
+ line_violations = violations
275
+ iteration = 0
276
+ # Type and conductors of each line before this action, from which its options
277
+ # are chosen at every step, and priced for what the action lays, as
278
+ # `calculate_cost` charges it
279
+ before = self._states_before_the_action()
280
+ # The type changes sized to carry their line, checked by the power flow that
281
+ # follows them (see `StepCheck`)
282
+ check = StepCheck(pf_engine, "line")
283
+ # Whether a type change may take back conductors the action has added: None
284
+ # until the engine has shown, at the first take-back, that it can set the
285
+ # conductors of a line, as well as check the step
286
+ take_back: bool | None = None
287
+ # The lines whose take-back has been undone, which take no other one
288
+ undone: set[str] = set()
289
+
290
+ def step(
291
+ chosen_on: tuple[Any, ...], overload_factor: float
292
+ ) -> tuple[dict[str, Any], str]:
293
+ """
294
+ Take a line one step towards the option chosen for it on `chosen_on`. A
295
+ type change sized to carry the line with the conductors it leaves is saved
296
+ first, to be checked; a take-back is only made if it can be.
297
+ """
298
+ nonlocal take_back
299
+ line_id, current_type, parallel = chosen_on[:3]
300
+ while True:
301
+ option = self._choose_thermal_upgrade(
302
+ *chosen_on,
303
+ take_back is not False and line_id not in undone,
304
+ check.fewest(line_id),
305
+ )
306
+ # The conductors the type change leaves: those of the option, if it
307
+ # takes back some the action has added
308
+ conductors = min(parallel, option.units)
309
+ if option.element_type == current_type or option.units > conductors:
310
+ # One more conductor, or a type change that more conductors
311
+ # will follow: not checked
312
+ break
313
+ info = (chosen_on, overload_factor, option.element_type, conductors)
314
+ if not check.save(line_id, info):
315
+ if conductors < parallel:
316
+ # No take-back that could not be undone
317
+ take_back = False
318
+ continue
319
+ break
320
+ if conductors < parallel:
321
+ try:
322
+ pf_engine.set_line_parallel(line_id, conductors)
323
+ take_back = True
324
+ except NotImplementedError:
325
+ check.forget(line_id)
326
+ take_back = False
327
+ continue
328
+ break
329
+ return self._thermal_step(option, conductors, chosen_on, overload_factor)
330
+
331
+ while line_violations and iteration < self.max_iterations:
332
+ grid_state_str = self._format_grid_state(line_violations)
333
+ violation_of = {v.element_id: v.violation_value for v in line_violations}
334
+ # The place of the entry of each line of this iteration
335
+ entry_of: dict[str, int] = {}
336
+ for line_id, overload_factor, intensity in self._identify_critical_elements(
337
+ line_violations
338
+ ):
339
+ # None for a line that has no type, which is given conductors of
340
+ # its own kind, priced under the key None
341
+ current_type = type_in_place(pf_engine.get_line_type(line_id))
342
+ parallel = max(1, int(pf_engine.get_line_parallel(line_id)))
343
+ before.setdefault(line_id, (current_type, parallel))
344
+ # What the step is chosen on, to choose it again if it is undone
345
+ chosen_on = (
346
+ line_id,
347
+ current_type,
348
+ parallel,
349
+ # The loading the engine reports, over the limit
350
+ 1.0 + overload_factor,
351
+ intensity / (max_loading / 100.0),
352
+ before[line_id],
353
+ pf_engine,
354
+ )
355
+ upgrade, action_str = step(chosen_on, overload_factor)
356
+ entry_of[line_id] = len(line_upgrades)
357
+ line_upgrades.append(upgrade)
358
+ action_count += 1
359
+
360
+ self._log_iteration(
361
+ action_count,
362
+ grid_state_str,
363
+ f"Line {line_id} (Loading) - Violation: {violation_of[line_id]:.4f} %",
364
+ f"Line {line_id} overloaded by {overload_factor * 100:.1f}%. "
365
+ f"Current capacity insufficient for {intensity:.2f} A.",
366
+ action_str,
367
+ )
368
+ # Run power flow again: the lines still overloaded, or overloaded since
369
+ line_violations = self._rerun_and_filter_violations(
370
+ pf_engine, ConstraintType.LINE_LOADING
371
+ )
372
+ while failed := check.failed({v.element_id for v in line_violations}):
373
+ # The type change left its line overloaded: in a mesh, one conductor of
374
+ # lower impedance draws more current than the conductors it replaces,
375
+ # and under generation a conductor of lower impedance lowers the
376
+ # voltage at the generators, which inject more current. Undone, the
377
+ # line takes the step chosen on the same power flow without that type
378
+ # for as few conductors, and a line whose take-back is undone takes no
379
+ # other: the iteration ends as if that option had never been offered
380
+ check.note_failed(failed)
381
+ refused = []
382
+ for line_id in failed:
383
+ chosen_on, overload_factor, new_type, conductors = check.undo(
384
+ line_id
385
+ )
386
+ check.refuse(line_id, new_type, conductors)
387
+ if conductors < chosen_on[2]:
388
+ undone.add(line_id)
389
+ refused.append((chosen_on, overload_factor))
390
+ # The power flow below starts from the solution the iteration was
391
+ # decided on, as it would have without the steps undone
392
+ check.restore_solution()
393
+ for chosen_on, overload_factor in refused:
394
+ line_id = chosen_on[0]
395
+ upgrade, action_str = step(chosen_on, overload_factor)
396
+ line_upgrades[entry_of[line_id]] = upgrade
397
+ action_count += 1
398
+ self._log_iteration(
399
+ action_count,
400
+ grid_state_str,
401
+ f"Line {line_id} (Loading)",
402
+ f"Line {line_id} still overloaded after a type change sized "
403
+ "to carry it: the type change is undone.",
404
+ action_str,
405
+ )
406
+ if check.taken_again():
407
+ # The type refused, chosen again with more units: the power flow
408
+ # that refused it stands for the steps taken in its place
409
+ break
410
+ line_violations = self._rerun_and_filter_violations(
411
+ pf_engine, ConstraintType.LINE_LOADING
412
+ )
413
+ check.end_round()
414
+ iteration += 1
415
+
416
+ return line_upgrades
417
+
418
+ @staticmethod
419
+ def _thermal_step(
420
+ option: SizingOption,
421
+ conductors: int,
422
+ chosen_on: tuple[Any, ...],
423
+ overload_factor: float,
424
+ ) -> tuple[dict[str, Any], str]:
425
+ """
426
+ Take a line one step towards `option`: the type change, which leaves it
427
+ `conductors` (those in place, or fewer if it takes back some, which the engine
428
+ has set already), or one more conductor of the type in place. Returns the
429
+ entry of the step and its description for the log.
430
+ """
431
+ line_id, current_type, parallel = chosen_on[:3]
432
+ pf_engine = chosen_on[-1]
433
+ new_line_type = option.element_type
434
+ upgrade = {
435
+ "line_id": line_id,
436
+ "old_type": current_type,
437
+ "new_type": new_line_type,
438
+ "length": pf_engine.get_line_length(line_id),
439
+ "overload_factor": overload_factor,
440
+ }
441
+ if new_line_type != current_type:
442
+ pf_engine.upgrade_line(line_id, new_line_type)
443
+ # The type change replaces every conductor of the line, and takes back
444
+ # those it does not replace
445
+ upgrade["conductors"] = conductors
446
+ action_str = f"Upgrade Line {line_id}: {current_type} -> {new_line_type}"
447
+ if conductors < parallel:
448
+ upgrade["conductors_removed"] = parallel - conductors
449
+ action_str += f", {parallel} conductors replaced by {conductors}"
450
+ else:
451
+ upgrade["parallel_count"] = int(pf_engine.add_parallel_line(line_id))
452
+ action_str = f"Add parallel line to {line_id}: {current_type}"
453
+ return upgrade, action_str
454
+
455
+ def _handle_voltage_violations(
456
+ self, violations: list[ConstraintViolation], pf_engine: PowerFlowEngine
457
+ ) -> list[dict[str, Any]]:
458
+ """
459
+ Handle voltage violations by iteratively upgrading lines based on sensitivity analysis.
460
+
461
+ Without prices (`cost_model` None), each iteration takes the line whose next
462
+ step of the ladder (`_get_next_lower_impedance_type`: the next conductor type,
463
+ or one more parallel conductor) brings the violated buses the most voltage per
464
+ km of line (`_identify_critical_lines_by_sensitivity`).
465
+
466
+ With prices, each iteration takes the step, of any line, that brings the
467
+ violated buses the most voltage within their limits per euro the run is
468
+ charged for it (`_rank_priced_voltage_steps`): one more conductor of the type
469
+ in place, or a configured type of lower resistance for every conductor of the
470
+ line, or for fewer of them, taking back conductors the run has laid on it.
471
+ Unless the engine can set the conductors of a line and check a step (below),
472
+ which the first ranking of the action tries, no conductor is taken back.
473
+
474
+ Every type change, with prices or without, is checked by the power flow that
475
+ follows it (see `StepCheck`). If the line is over its limit, the
476
+ step is undone: the engine gives the line back what it was (`save_line`,
477
+ `restore_line`), its entry is dropped, the type is offered to that line with
478
+ at least one more conductor for the rest of the action, and a line whose
479
+ take-back is undone takes no other take-back. When no step of the iteration is
480
+ left, the engine puts back the solution it was decided on (`save_solution`,
481
+ `restore_solution`), with no power flow, and the iteration is decided again,
482
+ as if the step had never been offered; it does not count against
483
+ `max_iterations`. When steps of the iteration are kept, the network is solved
484
+ again from that solution and they are checked again. On an engine that cannot
485
+ do all four operations, the steps are not checked.
486
+
487
+ Args:
488
+ violations (List[ConstraintViolation]): List of voltage constraint violations.
489
+ pf_engine (PowerFlowEngine): Power flow engine instance.
490
+
491
+ Returns:
492
+ List[Dict[str, Any]]: List of line upgrade actions performed.
493
+ """
494
+ line_upgrades: list[dict[str, Any]] = []
495
+ voltage_violations = violations
496
+
497
+ # Iteratively upgrade lines until violations are eliminated or no more upgrades possible
498
+ iteration = 0
499
+ action_count = 0
500
+ priced = getattr(self, "cost_model", None) is not None
501
+ # With prices: the state of each line before this action, from which it is
502
+ # charged when the strategy does not hold the state at the start of the run,
503
+ # with those its thermal steps recorded if the action had any
504
+ before = self._states_before_the_action()
505
+ # The steps that must leave their line within its loading limit, checked by
506
+ # the power flow that follows them
507
+ check = StepCheck(pf_engine, "line")
508
+ # Whether conductors may be taken back: None until the engine has shown it
509
+ # can set the conductors of a line and check a step
510
+ take_back: bool | None = None if priced else False
511
+ # The lines whose take-back has been undone, which take no other one
512
+ undone: set[str] = set()
513
+ # Whether the violations are those of the latest power flow: a step makes
514
+ # them no longer
515
+ solved = True
516
+ decided_on = voltage_violations
517
+ # The entries of the action before the steps of the iteration, which are those
518
+ # after them: a step undone takes its entry out
519
+ round_start = len(line_upgrades)
520
+ # Whether the solution put back is that of the network before steps of the
521
+ # iteration that are kept, which must be solved again
522
+ stale = False
523
+
524
+ while True:
525
+ if not solved:
526
+ if not (check.pending or stale) and iteration >= self.max_iterations:
527
+ # No power flow after the last step, unless it must be checked
528
+ break
529
+ found, refused = self._check_voltage_steps(
530
+ pf_engine, check, line_upgrades, undone, action_count
531
+ )
532
+ solved, stale = True, False
533
+ if refused and len(line_upgrades) > round_start:
534
+ # Steps of the iteration are kept, checked or not (one more
535
+ # conductor is not): solved again with them alone, from the
536
+ # solution the iteration was decided on, and checked again
537
+ solved, stale = False, True
538
+ continue
539
+ if refused:
540
+ # None is left: the network and its solution are those the
541
+ # iteration was decided on, which is decided again
542
+ voltage_violations = decided_on
543
+ iteration -= 1
544
+ else:
545
+ voltage_violations = [
546
+ v
547
+ for v in found
548
+ if v.constraint_type
549
+ in (ConstraintType.OVER_VOLTAGE, ConstraintType.UNDER_VOLTAGE)
550
+ ]
551
+ check.end_round()
552
+ if not voltage_violations or iteration >= self.max_iterations:
553
+ break
554
+
555
+ # The state this iteration decides on, after the power flow re-run
556
+ grid_state_str = self._format_grid_state(voltage_violations)
557
+
558
+ # Buses with voltage violations and the direction their voltage must move
559
+ directions = {
560
+ v.element_id: -1.0
561
+ if v.constraint_type == ConstraintType.OVER_VOLTAGE
562
+ else 1.0
563
+ for v in voltage_violations
564
+ }
565
+ violation_buses = list(directions)
566
+ # What each violated bus exceeds its limit by (p.u.)
567
+ excesses = {
568
+ v.element_id: abs(v.violation_value) for v in voltage_violations
569
+ }
570
+
571
+ # Calculate sensitivities and identify critical lines
572
+ steps: dict[str, tuple[str, int]] = {}
573
+ try:
574
+ if priced:
575
+ if take_back is None:
576
+ take_back = self._can_take_back(pf_engine, check)
577
+ ranked = self._rank_priced_voltage_steps(
578
+ violation_buses,
579
+ pf_engine,
580
+ directions,
581
+ excesses,
582
+ before,
583
+ take_back,
584
+ undone,
585
+ check.refused,
586
+ )
587
+ steps = {line_id: step for line_id, _, step in ranked}
588
+ critical_lines = [(line_id, score) for line_id, score, _ in ranked]
589
+ else:
590
+ critical_lines = self._identify_critical_lines_by_sensitivity(
591
+ violation_buses,
592
+ pf_engine,
593
+ directions,
594
+ excesses,
595
+ check.refused,
596
+ )
597
+ except NotImplementedError:
598
+ _logger.warning(
599
+ f"{type(pf_engine).__name__} does not provide line change effects: "
600
+ "no line upgrade for voltage violations."
601
+ )
602
+ break
603
+
604
+ if not critical_lines:
605
+ # No line left to upgrade, or none whose next step is worth its works
606
+ _logger.info(
607
+ f"No line upgrade step is predicted to move a violated bus by "
608
+ f"{self.min_voltage_sensitivity:g} p.u. or to its limit: "
609
+ f"{len(voltage_violations)} voltage violation(s) left to the other "
610
+ "strategies."
611
+ )
612
+ break
613
+
614
+ selected = critical_lines[:1]
615
+ if self.one_upgrade_per_zone:
616
+ # Best line of each zone holding a violated bus (not of every zone with a
617
+ # positive effect, e.g. the MV trunk for LV over-voltages); the single best
618
+ # line when no violated zone has a candidate.
619
+ zone_of_line = self._zone_of_lines(pf_engine)
620
+ zone_lines = self._lines_in_violation_zones(violation_buses, pf_engine)
621
+ selected, seen = [], set()
622
+ for line_id, score in critical_lines:
623
+ zone = zone_of_line.get(line_id)
624
+ if line_id not in zone_lines or zone in seen:
625
+ continue
626
+ seen.add(zone)
627
+ selected.append((line_id, score))
628
+ selected = selected or critical_lines[:1]
629
+
630
+ max_violation = max(
631
+ voltage_violations, key=lambda v: abs(v.violation_value)
632
+ )
633
+ # The violations the steps of this iteration are decided on
634
+ decided_on = voltage_violations
635
+ round_start = len(line_upgrades)
636
+ for line_id, sensitivity in selected:
637
+ action_count += 1
638
+ step = steps.get(line_id)
639
+ if step is not None:
640
+ before.setdefault(
641
+ line_id,
642
+ (
643
+ type_in_place(pf_engine.get_line_type(line_id)),
644
+ max(1, int(pf_engine.get_line_parallel(line_id))),
645
+ ),
646
+ )
647
+ line_upgrades.append(
648
+ self._upgrade_line_for_voltage(
649
+ line_id,
650
+ sensitivity,
651
+ pf_engine,
652
+ action_count,
653
+ grid_state_str,
654
+ len(violation_buses),
655
+ max_violation.violation_value,
656
+ step,
657
+ check,
658
+ )
659
+ )
660
+
661
+ iteration += 1
662
+ solved = False
663
+
664
+ return line_upgrades
665
+
666
+ def _check_voltage_steps(
667
+ self,
668
+ pf_engine: PowerFlowEngine,
669
+ check: StepCheck,
670
+ line_upgrades: list[dict[str, Any]],
671
+ undone: set[str],
672
+ action_count: int,
673
+ ) -> tuple[list[ConstraintViolation], bool]:
674
+ """
675
+ Run the power flow after voltage steps, and undo those of `check` that leave
676
+ their line over its limit: each such line is given back what it was, its entry
677
+ is dropped from `line_upgrades`, its type is refused it with as few
678
+ conductors, a line whose take-back is undone is added to `undone`, and the
679
+ solution the steps were decided on is put back. Returns the violations of the
680
+ power flow, and whether a step was undone.
681
+ """
682
+ pf_engine.run_power_flow(warm_start=True)
683
+ found = pf_engine.check_violations()
684
+ failed = check.failed(
685
+ {
686
+ v.element_id
687
+ for v in found
688
+ if v.constraint_type == ConstraintType.LINE_LOADING
689
+ }
690
+ )
691
+ for line_id in failed:
692
+ # Under generation, a conductor of lower impedance lowers the voltage at
693
+ # the generators, which inject more current, and in a mesh it draws
694
+ # current from the other paths
695
+ entry, new_type, conductors, in_place = check.undo(line_id)
696
+ del line_upgrades[
697
+ next(i for i, u in enumerate(line_upgrades) if u is entry)
698
+ ]
699
+ check.refuse(line_id, new_type, conductors)
700
+ if conductors < in_place:
701
+ undone.add(line_id)
702
+ self._log_iteration(
703
+ action_count,
704
+ self._format_grid_state(found),
705
+ f"Line '{line_id}' (Loading)",
706
+ f"Line '{line_id}' overloaded after its step to {new_type} for a "
707
+ "voltage violation: the step is undone.",
708
+ f"Restore line '{line_id}'",
709
+ )
710
+ if failed:
711
+ check.restore_solution()
712
+ return found, bool(failed)
713
+
714
+ def _states_before_the_action(self) -> dict[str, tuple[str | None, int]]:
715
+ """
716
+ The type and conductors of each line before the action under way, which its
717
+ steps fill as they first change a line: shared by the thermal and the voltage
718
+ steps of one `apply_to_group` call, so that the voltage steps of a call that
719
+ also has thermal ones are priced from the state before the action, as
720
+ `calculate_cost` charges it. A new mapping outside `apply_to_group`.
721
+ """
722
+ states = getattr(self, "_before_action", None)
723
+ return states if states is not None else {}
724
+
725
+ @staticmethod
726
+ def _can_take_back(pf_engine: PowerFlowEngine, check: StepCheck) -> bool:
727
+ """
728
+ Whether the engine can set the conductors of a line and check a step on it
729
+ (`StepCheck.can_check`), tried on a line of the network without changing it.
730
+ """
731
+ try:
732
+ line_ids = pf_engine.get_line_ids()
733
+ if not line_ids:
734
+ return False
735
+ line_id = line_ids[0]
736
+ if not check.can_check(line_id):
737
+ return False
738
+ pf_engine.set_line_parallel(
739
+ line_id, max(1, int(pf_engine.get_line_parallel(line_id)))
740
+ )
741
+ except NotImplementedError:
742
+ return False
743
+ return True
744
+
745
+ def _upgrade_line_for_voltage(
746
+ self,
747
+ line_id: str,
748
+ sensitivity: float,
749
+ pf_engine: PowerFlowEngine,
750
+ action_count: int,
751
+ grid_state_str: str,
752
+ n_violation_buses: int,
753
+ max_violation_value: float,
754
+ step: tuple[str, int] | None = None,
755
+ check: StepCheck | None = None,
756
+ ) -> dict[str, Any]:
757
+ """
758
+ Apply a step to one line and log it: `step` (type, conductors) when the step
759
+ was chosen with prices, the next step of the ladder otherwise (next conductor
760
+ type, or one more parallel conductor). A step to a type of fewer conductors
761
+ than the line has takes back the others, which it records in
762
+ `conductors_removed`.
763
+
764
+ With `check`, a type change, of the ladder or chosen with prices, is saved
765
+ first, to be checked by the power flow that follows; the ladder does not give
766
+ a line a type that `check` has refused it with the conductors in place.
767
+ """
768
+ current_type = pf_engine.get_line_type(line_id)
769
+ in_place = max(1, int(pf_engine.get_line_parallel(line_id)))
770
+ conductors = in_place
771
+ if step is None:
772
+ new_line_type = self._get_next_lower_impedance_type(
773
+ current_type,
774
+ pf_engine,
775
+ self._required_rating_of_line(line_id, pf_engine),
776
+ self._refused_types(check, line_id, in_place),
777
+ )
778
+ checked = bool(new_line_type) and new_line_type != current_type
779
+ justification = (
780
+ f"Voltage violations at {n_violation_buses} buses. "
781
+ f"Line '{line_id}' has highest predicted improvement {sensitivity:.4f} p.u./km."
782
+ )
783
+ else:
784
+ new_line_type, conductors = step
785
+ checked = new_line_type != current_type
786
+ justification = (
787
+ f"Voltage violations at {n_violation_buses} buses. "
788
+ f"Line '{line_id}' has the step of highest predicted improvement per "
789
+ f"euro, {sensitivity:.4g} p.u./EUR."
790
+ )
791
+ if new_line_type and new_line_type != current_type:
792
+ upgrade = {
793
+ "line_id": line_id,
794
+ "old_type": current_type,
795
+ "new_type": new_line_type,
796
+ # The type change replaces every conductor of the line, and takes
797
+ # back those it does not replace
798
+ "conductors": conductors,
799
+ "length": pf_engine.get_line_length(line_id),
800
+ "sensitivity": sensitivity,
801
+ }
802
+ action_str = f"Upgrade line '{line_id}': {current_type} -> {new_line_type}"
803
+ if conductors < in_place:
804
+ upgrade["conductors_removed"] = in_place - conductors
805
+ action_str += f", {in_place} conductors replaced by {conductors}"
806
+ if checked and check is not None:
807
+ check.save(line_id, (upgrade, new_line_type, conductors, in_place))
808
+ pf_engine.upgrade_line(line_id, new_line_type)
809
+ if conductors != in_place:
810
+ pf_engine.set_line_parallel(line_id, conductors)
811
+ else:
812
+ parallel_count = int(pf_engine.add_parallel_line(line_id))
813
+ upgrade = {
814
+ "line_id": line_id,
815
+ "old_type": current_type,
816
+ "new_type": new_line_type,
817
+ "parallel_count": parallel_count,
818
+ "length": pf_engine.get_line_length(line_id),
819
+ "sensitivity": sensitivity,
820
+ }
821
+ action_str = f"Add parallel line to {line_id}: {current_type}"
822
+ self._log_iteration(
823
+ action_count,
824
+ grid_state_str,
825
+ f"Line '{line_id}' (Voltage Sensitivity) - Max Violation: {max_violation_value:.4f} p.u.",
826
+ justification,
827
+ action_str,
828
+ )
829
+ return upgrade
830
+
831
+ @staticmethod
832
+ def _zone_of_lines(pf_engine: PowerFlowEngine) -> dict[str, int]:
833
+ partition = pf_engine.network_partition or pf_engine.partition_network()
834
+ return {
835
+ line: component_id
836
+ for component_id, component in partition.items()
837
+ for line in component.get("lines", [])
838
+ }
839
+
840
+ def calculate_cost(self, action: dict[str, Any], cost_model: CostModel) -> float:
841
+ """
842
+ Calculate the cost of the line upgrade actions.
843
+
844
+ A line is charged once, for what is laid, however many steps took it there: a
845
+ line taken from one type to the next and then to a third is charged for the
846
+ third only, not for the type in between, which is never laid, and a line
847
+ given a conductor that a type change then takes back (`conductors_removed`)
848
+ is charged for the conductors of the new type only. What a line
849
+ costs, from the state it had at first to the state it is left in, is:
850
+
851
+ - if the type has changed, the `line_upgrade` price of the final type for
852
+ every conductor the line had at first, as they are all replaced;
853
+ - the `new_line` price of the final type for every conductor added.
854
+
855
+ The state at first is that of the line when the run started, which
856
+ `GridEnhancementAlgorithm` records in the upgrades (`origin_type`,
857
+ `origin_conductors`). The action is then charged the difference between what
858
+ the line costs after it and what it cost before it, so that a line upgraded
859
+ by several actions of a run (for its loading, then for its voltage) is charged
860
+ in all for what the run lays. Without that record, the state at first is the
861
+ one before the action.
862
+
863
+ The state of a line before the action is read from its first step, and the
864
+ state after it from its last: a type change gives the conductors it leaves
865
+ (`conductors`) and those it takes back (`conductors_removed`), so that a
866
+ line whose first step takes back conductors laid by an earlier action of the
867
+ run had them all before the action, and one whose last step is a type change
868
+ is left with the conductors that step gives, fewer than before the action if
869
+ a step of it took some back. An entry that does not give its conductors is
870
+ read as leaving the line at least the conductors it had before the action.
871
+
872
+ Args:
873
+ action (Dict[str, Any]): The action dictionary.
874
+ cost_model (CostModel): The cost model.
875
+
876
+ Returns:
877
+ float: The total cost of the upgrades.
878
+ """
879
+ first_step: dict[str, dict[str, Any]] = {}
880
+ last_step: dict[str, dict[str, Any]] = {}
881
+ for line_upgrade in action.get("lines", []):
882
+ line_id = line_upgrade.get("line_id", "")
883
+ first_step.setdefault(line_id, line_upgrade)
884
+ last_step[line_id] = line_upgrade
885
+
886
+ total_cost = 0.0
887
+ for line_id, first in first_step.items():
888
+ last = last_step[line_id]
889
+ length = last.get("length", 0.0)
890
+ # A line that has no type (None, NaN or '') is priced under the key None
891
+ before = (
892
+ type_in_place(first.get("old_type")),
893
+ self._conductors(first, before=True),
894
+ )
895
+ # A parallel conductor keeps the type in place, which `new_type` may not give
896
+ after = (
897
+ type_in_place(last.get("new_type") or last.get("old_type")),
898
+ self._conductors(last)
899
+ if last.get("conductors") or last.get("parallel_count")
900
+ else max(self._conductors(last), before[1]),
901
+ )
902
+ origin = (
903
+ type_in_place(first.get("origin_type", before[0])),
904
+ max(1, int(first.get("origin_conductors") or before[1])),
905
+ )
906
+ total_cost += self._charge(
907
+ cost_model, line_id, origin, before, after, length
908
+ )
909
+ return float(total_cost)
910
+
911
+ @staticmethod
912
+ def _works_cost(
913
+ cost_model: CostModel,
914
+ line_id: str,
915
+ origin: tuple[Any, int],
916
+ state: tuple[Any, int],
917
+ length: float,
918
+ ) -> float:
919
+ """
920
+ Cost of taking a line from its state at first, `origin`, to `state` (type,
921
+ conductors): the `line_upgrade` price of the type of `state` for every
922
+ conductor of `origin` if the type has changed, and its `new_line` price for
923
+ every conductor added.
924
+ """
925
+ (origin_type, origin_conductors), (line_type, conductors) = origin, state
926
+ cost = 0.0
927
+ if line_type != origin_type:
928
+ cost += origin_conductors * cost_model.calculate_line_upgrade_cost(
929
+ line_id, line_type, length
930
+ )
931
+ added = max(0, conductors - origin_conductors)
932
+ if added:
933
+ cost += added * cost_model.calculate_new_line_cost(line_type, length)
934
+ return cost
935
+
936
+ @classmethod
937
+ def _charge(
938
+ cls,
939
+ cost_model: CostModel,
940
+ line_id: str,
941
+ origin: tuple[Any, int],
942
+ before: tuple[Any, int],
943
+ after: tuple[Any, int],
944
+ length: float,
945
+ ) -> float:
946
+ """
947
+ What an action that takes a line from `before` to `after` is charged: what the
948
+ line costs after it, from its state at first `origin`, less what it cost before
949
+ it, which the earlier actions of the run were charged.
950
+ """
951
+ return charge(
952
+ lambda first, state: cls._works_cost(
953
+ cost_model, line_id, first, state, length
954
+ ),
955
+ origin,
956
+ before,
957
+ after,
958
+ )
959
+
960
+ @staticmethod
961
+ def _conductors(line_upgrade: dict[str, Any], before: bool = False) -> int:
962
+ """Number of conductors of a line after one of its upgrades, or before it."""
963
+ parallel_count = int(line_upgrade.get("parallel_count") or 0)
964
+ if parallel_count > 0:
965
+ # The upgrade added one conductor
966
+ return parallel_count - 1 if before else parallel_count
967
+ conductors = max(1, int(line_upgrade.get("conductors") or 1))
968
+ if before:
969
+ # A type change that takes back conductors had them before it
970
+ conductors += int(line_upgrade.get("conductors_removed") or 0)
971
+ return conductors
972
+
973
+ def required_unit_costs(self, pf_engine: PowerFlowEngine) -> set[tuple[str, ...]]:
974
+ """
975
+ List the upgrade price of every configured line type.
976
+
977
+ Args:
978
+ pf_engine (PowerFlowEngine): The power flow engine.
979
+
980
+ Returns:
981
+ Set[Tuple[str, ...]]: The keys of the prices in `CostModel.unit_costs`.
982
+ """
983
+ return {("line_upgrade", line_type) for line_type in self.line_types}
984
+
985
+ def possible_unit_costs(self, pf_engine: PowerFlowEngine) -> set[tuple[str, ...]]:
986
+ """
987
+ List the price of a new conductor of every line type in place on the network.
988
+
989
+ A line can be given a parallel conductor of the type it has, whether or not
990
+ that type is one of the configured ones, and the conductor is charged at the
991
+ `new_line` price of that type, or at its `line_upgrade` price. That of a line
992
+ that has no type (a `std_type` of None, NaN or '', like a line created from
993
+ its parameters) is the price under the key None. Whether a run adds one is not
994
+ known before it: the run starts without these prices, and stops if it needs a
995
+ missing one. Only the lines that conduct are listed.
996
+
997
+ Args:
998
+ pf_engine (PowerFlowEngine): The power flow engine.
999
+
1000
+ Returns:
1001
+ Set[Tuple[str, ...]]: The keys of the prices in `CostModel.unit_costs`.
1002
+ """
1003
+ return {
1004
+ ("new_line", line_type)
1005
+ for line_type in self._line_types_in_place(pf_engine)
1006
+ }
1007
+
1008
+ @staticmethod
1009
+ def _line_types_in_place(pf_engine: PowerFlowEngine) -> set[str | None]:
1010
+ """
1011
+ Types of the lines of the network that conduct, None for those that have no
1012
+ type (`type_in_place`); none if the engine cannot list them.
1013
+ """
1014
+ if getattr(pf_engine, "network", True) is None:
1015
+ return set()
1016
+ try:
1017
+ line_types = pf_engine.get_lines_info(pf_engine.get_line_ids())["std_type"]
1018
+ except NotImplementedError:
1019
+ return set()
1020
+ return {type_in_place(t) for t in line_types.unique()}
1021
+
1022
+ def _identify_critical_lines_by_sensitivity(
1023
+ self,
1024
+ violation_buses: list[str],
1025
+ pf_engine: PowerFlowEngine,
1026
+ directions: dict[str, float] | None = None,
1027
+ excesses: dict[str, float] | None = None,
1028
+ refused: Mapping[str, Mapping[str, int]] | None = None,
1029
+ ) -> list[tuple[str, float]]:
1030
+ """
1031
+ Rank upgradable lines by the predicted voltage improvement of their next upgrade step.
1032
+
1033
+ For each candidate line the next step (next conductor type, or one more parallel
1034
+ conductor) is evaluated with `calculate_voltage_line_change_effects` (response
1035
+ linearised in the finite impedance change); the score is the mean predicted voltage
1036
+ improvement at the violated buses per km of line (benefit per unit of works).
1037
+
1038
+ A line is only ranked if its step moves the violated buses the right way on
1039
+ average, and at least one of them by `min_voltage_sensitivity` (p.u.), or by
1040
+ what that bus exceeds its limit by if that is less: a step is judged on the
1041
+ buses it helps, so that violations elsewhere on the network do not dilute it,
1042
+ and a step that brings a bus within its limit is always worth considering. The
1043
+ list is empty when no line has such a step.
1044
+
1045
+ Parameters
1046
+ ----------
1047
+ violation_buses : List[str]
1048
+ List of bus IDs where voltage violations occur
1049
+ pf_engine : PowerFlowEngine
1050
+ Power flow engine instance
1051
+ directions : Optional[Dict[str, float]]
1052
+ Desired sign of the voltage change per violated bus (-1 for an over-voltage, +1
1053
+ for an under-voltage): a step that moves a bus the wrong way counts against the
1054
+ line. When omitted, the magnitude |dV| is used.
1055
+ excesses : Optional[Dict[str, float]]
1056
+ What each violated bus exceeds its limit by (p.u.). When omitted, a step
1057
+ must reach `min_voltage_sensitivity` at a bus whatever its excess.
1058
+ refused : Optional[Mapping[str, Mapping[str, int]]]
1059
+ For each line, the fewest conductors of each type it may be given
1060
+ (`StepCheck.refused`): the next step of a line refused a type with the
1061
+ conductors it has is the one of a catalogue without that type.
1062
+
1063
+ Returns
1064
+ -------
1065
+ List[Tuple[str, float]]
1066
+ List of tuples (line_id, score) sorted by score (highest first)
1067
+ """
1068
+ if not violation_buses:
1069
+ return []
1070
+
1071
+ # Candidate lines: those of the galvanic zones of the violated buses when requested
1072
+ line_ids = None
1073
+ if self.restrict_to_violation_zone:
1074
+ zone_lines = self._lines_in_violation_zones(violation_buses, pf_engine)
1075
+ if zone_lines:
1076
+ line_ids = sorted(zone_lines)
1077
+ if line_ids is None:
1078
+ line_ids = pf_engine.get_line_ids()
1079
+
1080
+ # Next upgrade step of each candidate (one lookup per line type, vectorised line data).
1081
+ # A line whose type is not one of the configured ones (or that has none, like a
1082
+ # line created from its parameters) has no next step: it is left as it is.
1083
+ info = pf_engine.get_lines_info(line_ids)
1084
+ next_type_of: dict[str, str | None] = {
1085
+ line_type: self._get_next_lower_impedance_type(line_type, pf_engine)
1086
+ for line_type in info["std_type"].unique()
1087
+ if isinstance(line_type, str)
1088
+ }
1089
+ # Impedance of the types the lines can change to. That of a line that keeps its
1090
+ # type is read from the line itself, not from the catalogue.
1091
+ rx_of = {
1092
+ next_type: (
1093
+ pf_engine.get_line_r_ohm_per_km(next_type),
1094
+ pf_engine.get_line_x_ohm_per_km(next_type),
1095
+ )
1096
+ for line_type, next_type in next_type_of.items()
1097
+ if next_type and next_type != line_type
1098
+ }
1099
+ has_impedance = {"r_ohm_per_km", "x_ohm_per_km"} <= set(info.columns)
1100
+ has_current = "current_a" in info.columns
1101
+ has_df = "df" in info.columns
1102
+ refused = refused or {}
1103
+ buries: dict[tuple[str, str], bool] = {}
1104
+ next_steps: dict[str, tuple[float, float, int]] = {}
1105
+ for line_id, row in info.iterrows():
1106
+ current_type = row["std_type"]
1107
+ next_type = next_type_of.get(current_type)
1108
+ # A line of zero length has no works to rate the improvement on
1109
+ if not next_type or not row["length_km"] > 0.0:
1110
+ continue
1111
+ n = max(1, int(row["parallel"]))
1112
+ refused_types = {
1113
+ line_type
1114
+ for line_type, fewest in refused.get(line_id, {}).items()
1115
+ if fewest > n
1116
+ }
1117
+ if refused_types:
1118
+ # The next type as if the catalogue had not the types refused
1119
+ next_type = self._get_next_lower_impedance_type(
1120
+ current_type, pf_engine, refused=refused_types
1121
+ )
1122
+ if not next_type:
1123
+ continue
1124
+ if next_type != current_type and next_type not in rx_of:
1125
+ rx_of[next_type] = (
1126
+ pf_engine.get_line_r_ohm_per_km(next_type),
1127
+ pf_engine.get_line_x_ohm_per_km(next_type),
1128
+ )
1129
+ if next_type != current_type:
1130
+ key = (current_type, next_type)
1131
+ if key not in buries:
1132
+ buries[key] = self._buries(*key)
1133
+ if (
1134
+ buries[key]
1135
+ and has_current
1136
+ and not self._carries(
1137
+ next_type,
1138
+ self._required_rating(
1139
+ row["current_a"],
1140
+ n,
1141
+ pf_engine,
1142
+ row["df"] if has_df else 1.0,
1143
+ ),
1144
+ pf_engine,
1145
+ )
1146
+ ):
1147
+ # A cable that cannot carry the line is not a step: one more
1148
+ # conductor of the type in place is
1149
+ next_type = current_type
1150
+ if next_type != current_type:
1151
+ next_steps[line_id] = (*rx_of[next_type], n)
1152
+ elif has_impedance:
1153
+ next_steps[line_id] = (
1154
+ float(row["r_ohm_per_km"]),
1155
+ float(row["x_ohm_per_km"]),
1156
+ n + 1,
1157
+ )
1158
+ else:
1159
+ next_steps[line_id] = (
1160
+ pf_engine.get_line_r_ohm_per_km(current_type),
1161
+ pf_engine.get_line_x_ohm_per_km(current_type),
1162
+ n + 1,
1163
+ )
1164
+ if not next_steps:
1165
+ return []
1166
+
1167
+ effects = pf_engine.calculate_voltage_line_change_effects(
1168
+ next_steps, buses=violation_buses
1169
+ )
1170
+ if effects.empty:
1171
+ return []
1172
+ if directions is None:
1173
+ gains = effects.abs()
1174
+ else:
1175
+ signs = [directions.get(bus, 0.0) for bus in effects.index]
1176
+ gains = effects.mul(signs, axis=0)
1177
+ improvement = gains.mean()
1178
+ lengths = info["length_km"]
1179
+
1180
+ # No fallback when no line passes the threshold: the strategy then stops, rather
1181
+ # than pay for steps that each move the voltages by next to nothing. A step
1182
+ # that makes the violated buses worse on average never passes.
1183
+ threshold = max(self.min_voltage_sensitivity, 0.0)
1184
+ # What a step must bring to a bus to be worth its works: the threshold, or
1185
+ # less where less brings the bus within its limit
1186
+ needed = pd.Series(threshold, index=gains.index)
1187
+ if excesses is not None:
1188
+ excess = pd.Series(
1189
+ [abs(excesses.get(bus, threshold)) for bus in gains.index],
1190
+ index=gains.index,
1191
+ )
1192
+ needed = needed.clip(upper=excess)
1193
+ worth = gains.ge(needed, axis=0).any()
1194
+ ranked_lines = [
1195
+ (line_id, effect / lengths[line_id])
1196
+ for line_id, effect in improvement.items()
1197
+ if effect > 0.0 and worth[line_id]
1198
+ ]
1199
+
1200
+ # Sort by score (highest first)
1201
+ return sorted(ranked_lines, key=lambda x: x[1], reverse=True)
1202
+
1203
+ def _rank_priced_voltage_steps(
1204
+ self,
1205
+ violation_buses: list[str],
1206
+ pf_engine: PowerFlowEngine,
1207
+ directions: dict[str, float],
1208
+ excesses: dict[str, float],
1209
+ before: dict[str, tuple[str | None, int]] | None = None,
1210
+ take_back: bool = True,
1211
+ undone: set[str] | frozenset[str] = frozenset(),
1212
+ refused: Mapping[str, Mapping[str, int]] | None = None,
1213
+ ) -> list[tuple[str, float, tuple[str, int]]]:
1214
+ """
1215
+ Rank the lines by the best of their steps, with the prices of the run
1216
+ (`cost_model`): the voltage a step brings the violated buses within their
1217
+ limits, per euro the run is charged for it.
1218
+
1219
+ The steps of a line of a configured type, in state (type, n conductors), are:
1220
+
1221
+ - one more conductor of the type in place, rated on the impedance of the line
1222
+ in place, as without prices;
1223
+ - each configured type of the same voltage level and of lower resistance than
1224
+ the type in place (an overhead or underground type for an overhead line, an
1225
+ underground type for an underground line), for m conductors, from the fewest
1226
+ that carry the current of the line within the loading limit (as
1227
+ `_required_rating` reads it, on the rating of the type times the derating
1228
+ factor of the line) up to n. m is never below the conductors the line had
1229
+ at the start of the run (`line_origins`, or its state `before` the action
1230
+ for a strategy that does not hold them), nor below n unless `take_back`,
1231
+ and not for a line of `undone`, nor below the fewest conductors of that
1232
+ type that `refused` gives the line (`StepCheck.refused`). A type change to
1233
+ fewer than n conductors takes back the others.
1234
+
1235
+ A step is charged as `calculate_cost` charges it: what the line costs after
1236
+ it, from its state at the start of the run, less what it cost before it. Its
1237
+ gain is the mean, over the violated buses, of its predicted effect
1238
+ (`calculate_voltage_line_change_effects_of_steps`, every step of every line
1239
+ in one call, which the pandapower engine makes with one solve, however many
1240
+ conductors a line has) towards the limit of each, counted
1241
+ up to what the bus exceeds its limit by: a voltage beyond the limit is worth
1242
+ nothing. A step is only ranked if it is worth its works by the rule of
1243
+ `_identify_critical_lines_by_sensitivity` (it moves the violated buses the
1244
+ right way on average, and one of them by `min_voltage_sensitivity` or by its
1245
+ excess if less) and its gain is positive. A step whose price is missing is
1246
+ left out.
1247
+
1248
+ The steps charged nothing or less (a type that costs no more than the
1249
+ conductors it replaces, from the start of the run) come first, the highest
1250
+ gain first, then the cheapest; the others follow, by gain per euro, then the
1251
+ cheapest. Ties go to the order of the steps above (the conductor added, then
1252
+ the types in the order of the catalogue, fewer conductors first), then of
1253
+ the lines.
1254
+
1255
+ Every step either adds a conductor to the type in place or changes the type
1256
+ to one of lower resistance, so that a line never comes back to a state it
1257
+ has had: the steps are finite, the number of conductors added being bounded
1258
+ by `max_iterations`.
1259
+
1260
+ Returns:
1261
+ List[Tuple[str, float, Tuple[str, int]]]: (line, score, step) for each
1262
+ line that has a step ranked, its best step (type, conductors), best
1263
+ first. The score is the gain per euro, infinite for a step charged
1264
+ nothing or less.
1265
+ """
1266
+ if not violation_buses:
1267
+ return []
1268
+ cost_model = self.cost_model
1269
+ info = pf_engine.get_lines_info(
1270
+ self._candidate_line_ids(violation_buses, pf_engine)
1271
+ )
1272
+ if info.empty:
1273
+ return []
1274
+ max_loading = getattr(
1275
+ getattr(pf_engine, "constraints", None), "max_line_loading", 100.0
1276
+ )
1277
+ origins = getattr(self, "line_origins", None) or {}
1278
+ before = before or {}
1279
+ refused = refused or {}
1280
+ has_current = "current_a" in info.columns
1281
+ has_impedance = {"r_ohm_per_km", "x_ohm_per_km"} <= set(info.columns)
1282
+
1283
+ # The level and category of each candidate line, as the ladder reads them, and
1284
+ # the configured types of each of those levels, in the order of the catalogue:
1285
+ # a line is offered the types of its own level, whatever the other lines. The
1286
+ # types of other levels are not looked up: the network need not know them, as
1287
+ # without prices
1288
+ line_info = {
1289
+ line_type: self._get_line_info(line_type)
1290
+ for line_type in info["std_type"].unique()
1291
+ if isinstance(line_type, str)
1292
+ }
1293
+ levels = {level for level, _ in line_info.values() if level is not None}
1294
+ types_of_level: dict[str, list[tuple[str, str]]] = {}
1295
+ for level in self.line_types_dict:
1296
+ if level not in levels:
1297
+ continue
1298
+ listed = types_of_level.setdefault(level, [])
1299
+ for category, types in self.line_types_dict[level].items():
1300
+ for line_type in types:
1301
+ if all(line_type != known for known, _ in listed):
1302
+ listed.append((line_type, category))
1303
+ # What a step needs of each of those types: resistance, reactance, rating, and
1304
+ # the prices per km of a conductor that replaces one in place and of one added
1305
+ # (None where missing)
1306
+ catalogue: dict[str, tuple[Any, ...]] = {}
1307
+ with unlogged(cost_model):
1308
+ for listed in types_of_level.values():
1309
+ for line_type, _ in listed:
1310
+ if line_type in catalogue:
1311
+ continue
1312
+ try:
1313
+ replace = cost_model.calculate_line_upgrade_cost(
1314
+ "", line_type, 1.0
1315
+ )
1316
+ except MissingUnitCostError:
1317
+ replace = None
1318
+ try:
1319
+ add = cost_model.calculate_new_line_cost(line_type, 1.0)
1320
+ except MissingUnitCostError:
1321
+ add = None
1322
+ catalogue[line_type] = (
1323
+ pf_engine.get_line_r_ohm_per_km(line_type),
1324
+ pf_engine.get_line_x_ohm_per_km(line_type),
1325
+ pf_engine.get_line_imax(line_type),
1326
+ replace,
1327
+ add,
1328
+ )
1329
+
1330
+ def works(origin: tuple[Any, int], state: tuple[Any, int]) -> float | None:
1331
+ """`_works_cost` per km, None for a price missing."""
1332
+ (origin_type, origin_conductors), (line_type, conductors) = origin, state
1333
+ cost = 0.0
1334
+ if line_type != origin_type:
1335
+ replace = catalogue[line_type][3]
1336
+ if replace is None:
1337
+ return None
1338
+ cost += origin_conductors * replace
1339
+ added = max(0, conductors - origin_conductors)
1340
+ if added:
1341
+ add = catalogue[line_type][4]
1342
+ if add is None:
1343
+ return None
1344
+ cost += added * add
1345
+ return cost
1346
+
1347
+ # The steps of each line, in order: (line, type, conductors, r, x, charge)
1348
+ candidates: dict[str, list[tuple[str, int, float, float, float]]] = {}
1349
+ names = info.index.tolist()
1350
+ rows = zip(
1351
+ names,
1352
+ info["std_type"].tolist(),
1353
+ info["length_km"].tolist(),
1354
+ info["parallel"].tolist(),
1355
+ info["current_a"].tolist() if has_current else [None] * len(names),
1356
+ info["r_ohm_per_km"].tolist() if has_impedance else [None] * len(names),
1357
+ info["x_ohm_per_km"].tolist() if has_impedance else [None] * len(names),
1358
+ info["df"].tolist() if "df" in info.columns else [1.0] * len(names),
1359
+ strict=True,
1360
+ )
1361
+ for line_id, line_type, length, parallel, current, r_line, x_line, df in rows:
1362
+ # Only a line of a configured type has steps, and one of zero length has
1363
+ # no works to rate them on
1364
+ if line_type not in line_info or not length > 0.0:
1365
+ continue
1366
+ level, category = line_info[line_type]
1367
+ if level is None:
1368
+ continue
1369
+ r_type = catalogue[line_type][0]
1370
+ n = max(1, int(parallel))
1371
+ state = (line_type, n)
1372
+ origin = origins.get(line_id) or before.get(line_id) or state
1373
+ origin = (type_in_place(origin[0]), max(1, int(origin[1])))
1374
+ spent = works(origin, state)
1375
+ if spent is None:
1376
+ continue
1377
+ fewest = n
1378
+ if take_back and line_id not in undone:
1379
+ fewest = min(n, origin[1])
1380
+ # The current the conductors must carry within the loading limit, in
1381
+ # the rating of their type, which the derating factor of the line, kept
1382
+ # by a type change, lowers
1383
+ required = None
1384
+ if current is not None and current >= 0.0:
1385
+ required = current / (max_loading / 100.0) / self._derating(df)
1386
+ fewest_of = refused.get(line_id, {})
1387
+ steps = []
1388
+ if r_line is None or x_line is None:
1389
+ r_line, x_line = r_type, catalogue[line_type][1]
1390
+ added = works(origin, (line_type, n + 1))
1391
+ if added is not None:
1392
+ steps.append(
1393
+ (line_type, n + 1, r_line, x_line, (added - spent) * length)
1394
+ )
1395
+ for new_type, new_category in types_of_level[level]:
1396
+ r_new, x_new, rating = catalogue[new_type][:3]
1397
+ if (
1398
+ new_type == line_type
1399
+ or (category == "underground" and new_category != "underground")
1400
+ or not r_new < r_type
1401
+ ):
1402
+ continue
1403
+ lowest = fewest
1404
+ if required is not None:
1405
+ lowest = units_to_carry(required, rating, fewest)
1406
+ lowest = max(lowest, fewest_of.get(new_type, 0))
1407
+ for m in range(lowest, n + 1):
1408
+ cost = works(origin, (new_type, m))
1409
+ if cost is not None:
1410
+ steps.append(
1411
+ (new_type, m, r_new, x_new, (cost - spent) * length)
1412
+ )
1413
+ if steps:
1414
+ candidates[line_id] = steps
1415
+ if not candidates:
1416
+ return []
1417
+
1418
+ threshold = max(self.min_voltage_sensitivity, 0.0)
1419
+ buses = list(violation_buses)
1420
+ best: dict[str, tuple[tuple[Any, ...], float, tuple[str, int]]] = {}
1421
+ order = {line_id: i for i, line_id in enumerate(candidates)}
1422
+ # Every step of every line in one call of the engine: the k-th step of a line
1423
+ # is at the position `flat` gives it
1424
+ flat = [
1425
+ (line_id, k)
1426
+ for line_id, steps in candidates.items()
1427
+ for k in range(len(steps))
1428
+ ]
1429
+ effects = pf_engine.calculate_voltage_line_change_effects_of_steps(
1430
+ [
1431
+ (line_id, candidates[line_id][k][2], candidates[line_id][k][3])
1432
+ + (candidates[line_id][k][1],)
1433
+ for line_id, k in flat
1434
+ ],
1435
+ buses=buses,
1436
+ )
1437
+ if effects.empty or effects.shape[1] == 0:
1438
+ return []
1439
+ index = effects.index.tolist()
1440
+ signs = np.array([directions.get(bus, 0.0) for bus in index])
1441
+ excess = np.array([abs(excesses.get(bus, threshold)) for bus in index])
1442
+ gains = effects.to_numpy() * signs[:, None]
1443
+ # What a step must bring to a bus to be worth its works
1444
+ needed = np.minimum(threshold, excess)
1445
+ worth = (gains >= needed[:, None]).any(axis=0)
1446
+ mean = gains.mean(axis=0)
1447
+ useful = np.minimum(gains, excess[:, None]).mean(axis=0)
1448
+ for column, position in enumerate(effects.columns):
1449
+ if not (worth[column] and mean[column] > 0.0 and useful[column] > 0.0):
1450
+ continue
1451
+ line_id, k = flat[position]
1452
+ new_type, m, _, _, charge = candidates[line_id][k]
1453
+ gain = float(useful[column])
1454
+ if charge > 0.0:
1455
+ score = gain / charge
1456
+ key = (1, -score, charge, k)
1457
+ else:
1458
+ score = math.inf
1459
+ key = (0, -gain, charge, k)
1460
+ if line_id not in best or key < best[line_id][0]:
1461
+ best[line_id] = (key, score, (new_type, m))
1462
+ ranked = sorted(best.items(), key=lambda item: (item[1][0], order[item[0]]))
1463
+ return [(line_id, score, step) for line_id, (_, score, step) in ranked]
1464
+
1465
+ def _candidate_line_ids(
1466
+ self, violation_buses: list[str], pf_engine: PowerFlowEngine
1467
+ ) -> list[str]:
1468
+ """
1469
+ The lines whose steps are considered for voltage violations at
1470
+ `violation_buses`: those of their galvanic zones with
1471
+ `restrict_to_violation_zone` (all if no zone holds a line), all otherwise.
1472
+ """
1473
+ if self.restrict_to_violation_zone:
1474
+ zone_lines = self._lines_in_violation_zones(violation_buses, pf_engine)
1475
+ if zone_lines:
1476
+ return sorted(zone_lines)
1477
+ return pf_engine.get_line_ids()
1478
+
1479
+ @staticmethod
1480
+ def _lines_in_violation_zones(
1481
+ violation_buses: list[str], pf_engine: PowerFlowEngine
1482
+ ) -> set[str]:
1483
+ """
1484
+ Names of the lines belonging to the galvanic zones of the given buses.
1485
+
1486
+ Returns an empty set when no zone of a violated bus contains a line (e.g. a bus
1487
+ directly on a transformer secondary), in which case the caller keeps all lines.
1488
+ """
1489
+ partition = pf_engine.network_partition or pf_engine.partition_network()
1490
+ zone_of_bus = {
1491
+ bus: component_id
1492
+ for component_id, component in partition.items()
1493
+ for bus in component.get("buses", [])
1494
+ }
1495
+ zones = {zone_of_bus[b] for b in violation_buses if b in zone_of_bus}
1496
+ allowed: set[str] = set()
1497
+ for zone in zones:
1498
+ allowed.update(partition[zone].get("lines", []))
1499
+ return allowed
1500
+
1501
+ def _get_line_info(self, line_type: str) -> tuple[str | None, str | None]:
1502
+ """
1503
+ Get the voltage level and category (overhead/underground) of a line type.
1504
+
1505
+ Args:
1506
+ line_type (str): The line type string.
1507
+
1508
+ Returns:
1509
+ Tuple[Optional[str], Optional[str]]: (voltage_level, category) or (None, None) if not found.
1510
+ """
1511
+ for voltage_level, categories in self.line_types_dict.items():
1512
+ for category, types in categories.items():
1513
+ if line_type in types:
1514
+ return voltage_level, category
1515
+ return None, None
1516
+
1517
+ def _buries(self, current_type: str, new_type: str) -> bool:
1518
+ """Whether changing a line from `current_type` to `new_type` buries an overhead line."""
1519
+ return (
1520
+ self._get_line_info(current_type)[1] == "overhead"
1521
+ and self._get_line_info(new_type)[1] == "underground"
1522
+ )
1523
+
1524
+ @staticmethod
1525
+ def _derating(df: Any) -> float:
1526
+ """The derating factor of a line, 1 if it has none that is positive."""
1527
+ try:
1528
+ df = float(df)
1529
+ except (TypeError, ValueError):
1530
+ return 1.0
1531
+ return df if df > 0.0 else 1.0
1532
+
1533
+ @classmethod
1534
+ def _required_rating(
1535
+ cls,
1536
+ current: float | None,
1537
+ parallel: int,
1538
+ pf_engine: PowerFlowEngine,
1539
+ df: float = 1.0,
1540
+ ) -> float | None:
1541
+ """
1542
+ Rating (A) the type of each conductor of a line must have for the line to carry
1543
+ `current` (A) within the loading limit, its derating factor `df` applied to that
1544
+ rating, as the engine computes the loading: a type change keeps the factor. None
1545
+ when the current is not known.
1546
+ """
1547
+ if current is None or not current >= 0.0:
1548
+ return None
1549
+ max_loading = getattr(
1550
+ getattr(pf_engine, "constraints", None), "max_line_loading", 100.0
1551
+ )
1552
+ return (
1553
+ current / max(1, int(parallel)) / (max_loading / 100.0) / cls._derating(df)
1554
+ )
1555
+
1556
+ def _required_rating_of_line(
1557
+ self, line_id: str, pf_engine: PowerFlowEngine
1558
+ ) -> float | None:
1559
+ """`_required_rating` of a line for the current it carries in the latest power flow."""
1560
+ try:
1561
+ info = pf_engine.get_lines_info([line_id])
1562
+ except NotImplementedError:
1563
+ return None
1564
+ if line_id not in info.index or "current_a" not in info.columns:
1565
+ return None
1566
+ row = info.loc[line_id]
1567
+ return self._required_rating(
1568
+ float(row["current_a"]),
1569
+ max(1, int(row["parallel"])),
1570
+ pf_engine,
1571
+ row["df"] if "df" in info.columns else 1.0,
1572
+ )
1573
+
1574
+ @staticmethod
1575
+ def _carries(
1576
+ line_type: str, required_rating: float | None, pf_engine: PowerFlowEngine
1577
+ ) -> bool:
1578
+ """Whether a conductor of `line_type` has the rating a line needs (always if unknown)."""
1579
+ return required_rating is None or pf_engine.get_line_imax(line_type) >= (
1580
+ required_rating
1581
+ )
1582
+
1583
+ @staticmethod
1584
+ def _refused_types(
1585
+ check: StepCheck | None, line_id: str, conductors: int
1586
+ ) -> set[str]:
1587
+ """The types `check` has refused `line_id` with `conductors` conductors."""
1588
+ if check is None:
1589
+ return set()
1590
+ return {
1591
+ line_type
1592
+ for line_type, fewest in check.fewest(line_id).items()
1593
+ if fewest > conductors
1594
+ }
1595
+
1596
+ def _get_next_lower_impedance_type(
1597
+ self,
1598
+ current_type: str,
1599
+ pf_engine: PowerFlowEngine,
1600
+ required_rating: float | None = None,
1601
+ refused: Container[str] = (),
1602
+ ) -> str | None:
1603
+ """
1604
+ Find the next lower impedance line type.
1605
+
1606
+ Parameters
1607
+ ----------
1608
+ current_type : str
1609
+ Current line type
1610
+ pf_engine : PowerFlowEngine
1611
+ Power flow engine instance
1612
+ required_rating : Optional[float]
1613
+ Rating (A) each conductor of the line must have to carry its current within
1614
+ the loading limit. An overhead line is only buried into a cable that has it;
1615
+ otherwise it keeps its type, and the step is one more conductor. When omitted,
1616
+ the line is buried whatever the cable carries.
1617
+ refused : Container[str]
1618
+ Types the line is not given: those that a step of the line to them was
1619
+ undone from (see `StepCheck`). The next type of the category of the line
1620
+ is the next one that is not refused, as if the catalogue had not the
1621
+ others; a line refused the best cable is not buried, and the step is one
1622
+ more conductor, as for a cable that cannot carry it: a cable of higher
1623
+ impedance would carry the line no better.
1624
+
1625
+ Returns
1626
+ -------
1627
+ Optional[str]
1628
+ Next lower impedance line type, or None if already at lowest impedance
1629
+ """
1630
+ voltage_level, category = self._get_line_info(current_type)
1631
+
1632
+ if not voltage_level:
1633
+ return None
1634
+
1635
+ def offered(types: list[str], own: bool) -> list[str]:
1636
+ # The types refused are left out of the category of the line only
1637
+ if not own:
1638
+ return types
1639
+ return [t for t in types if t == current_type or t not in refused]
1640
+
1641
+ overhead_types = offered(
1642
+ self.line_types_dict[voltage_level].get("overhead", []),
1643
+ category == "overhead",
1644
+ )
1645
+ underground_types = offered(
1646
+ self.line_types_dict[voltage_level].get("underground", []),
1647
+ category == "underground",
1648
+ )
1649
+
1650
+ def get_lines_by_r(types):
1651
+ return sorted(
1652
+ types, key=lambda x: pf_engine.get_line_r_ohm_per_km(x), reverse=True
1653
+ )
1654
+
1655
+ sorted_oh = get_lines_by_r(overhead_types)
1656
+ sorted_ug = get_lines_by_r(underground_types)
1657
+
1658
+ if category == "underground":
1659
+ # Underground: only upgrade to underground
1660
+ if current_type in sorted_ug:
1661
+ idx = sorted_ug.index(current_type)
1662
+ if idx < len(sorted_ug) - 1:
1663
+ return sorted_ug[idx + 1]
1664
+ else:
1665
+ return current_type
1666
+ return None
1667
+
1668
+ if category == "overhead":
1669
+ # Overhead: next overhead conductor, then bury, then parallel conductors
1670
+ if current_type in sorted_oh:
1671
+ idx = sorted_oh.index(current_type)
1672
+ if idx < len(sorted_oh) - 1:
1673
+ return sorted_oh[idx + 1]
1674
+
1675
+ # Burying is a new line: go straight to the lowest-impedance underground type
1676
+ # (one-step-at-a-time burying would pay the trench several times).
1677
+ current_r = pf_engine.get_line_r_ohm_per_km(current_type)
1678
+ if sorted_ug:
1679
+ best_ug = sorted_ug[-1]
1680
+ if (
1681
+ pf_engine.get_line_r_ohm_per_km(best_ug) < current_r
1682
+ and self._carries(best_ug, required_rating, pf_engine)
1683
+ and best_ug not in refused
1684
+ ):
1685
+ return best_ug
1686
+ return current_type if current_type in sorted_oh else None
1687
+
1688
+ return None
1689
+
1690
+ def _thermal_options(
1691
+ self,
1692
+ line_id: str,
1693
+ current_type: str,
1694
+ parallel: int,
1695
+ loading_ratio: float,
1696
+ current_needed: float,
1697
+ pf_engine: PowerFlowEngine,
1698
+ at_least: int | None = None,
1699
+ fewest: dict[str, int] | None = None,
1700
+ ) -> list[SizingOption]:
1701
+ """
1702
+ The ways to make an overloaded line carry its current within the loading limit.
1703
+
1704
+ The line needs `loading_ratio` (the loading the engine reports over the limit)
1705
+ times the rating of its conductors in place, the rating the engine computes its
1706
+ loading with: that of the line table (`get_line_rating`), or that of its type if
1707
+ the engine does not give it. A type change keeps the derating factor and gives
1708
+ the conductors the rating of the new type, so this holds whatever the derating
1709
+ factor, or a rating of the line that is not that of its type.
1710
+
1711
+ Args:
1712
+ line_id (str): The line.
1713
+ current_type (str): Its type.
1714
+ parallel (int): Its conductors.
1715
+ loading_ratio (float): The loading the engine reports, over the limit.
1716
+ current_needed (float): Its current over the limit (A), what the conductors
1717
+ need when neither the rating of the line nor that of its type is known.
1718
+ pf_engine (PowerFlowEngine): The power flow engine.
1719
+ at_least (int, optional): The fewest conductors a type change leaves,
1720
+ fewer than `parallel` for one that takes back conductors. Defaults to
1721
+ `parallel`.
1722
+ fewest (dict, optional): The fewest conductors of a type that the line
1723
+ may take, for a type that fewer conductors of did not carry it after
1724
+ the change (see `StepCheck`).
1725
+
1726
+ Returns:
1727
+ List[SizingOption]: The configured types rated above the line (by the table
1728
+ and by its type, so that a line is never replaced by a weaker one), each
1729
+ with as many conductors as carry the line, at least `at_least`: for
1730
+ an overhead line the overhead types, smallest first, then the
1731
+ underground ones; for an underground line the underground ones. Then
1732
+ the conductors in place with as many more of the type in place as carry
1733
+ the line. Only the latter for a type that is not one of the configured
1734
+ ones.
1735
+ """
1736
+ voltage_level, category = self._get_line_info(current_type)
1737
+ catalogue_rating = None
1738
+ try:
1739
+ catalogue_rating = pf_engine.get_line_imax(current_type)
1740
+ except (ValueError, KeyError, TypeError):
1741
+ pass
1742
+ rating = getattr(pf_engine, "get_line_rating", lambda _: None)(line_id)
1743
+ if rating is None:
1744
+ rating = catalogue_rating
1745
+ required = (
1746
+ loading_ratio * parallel * rating if rating is not None else current_needed
1747
+ )
1748
+
1749
+ options = []
1750
+ if voltage_level:
1751
+ floor = max(rating or 0.0, catalogue_rating or 0.0)
1752
+ categories = ["underground"]
1753
+ if category != "underground":
1754
+ # An overhead line: an overhead type, before burying it
1755
+ categories.insert(0, "overhead")
1756
+ fewest = fewest or {}
1757
+ for line_category in categories:
1758
+ ratings = sorted(
1759
+ (pf_engine.get_line_imax(t), t)
1760
+ for t in self.line_types_dict[voltage_level].get(line_category, [])
1761
+ )
1762
+ options.extend(
1763
+ type_change_option(
1764
+ line_type,
1765
+ type_rating,
1766
+ max(
1767
+ parallel if at_least is None else at_least,
1768
+ fewest.get(line_type, 0),
1769
+ ),
1770
+ required,
1771
+ )
1772
+ for type_rating, line_type in ratings
1773
+ if type_rating > floor
1774
+ )
1775
+ options.append(keep_type_option(current_type, parallel, rating, required))
1776
+ return options
1777
+
1778
+ def _choose_thermal_upgrade(
1779
+ self,
1780
+ line_id: str,
1781
+ current_type: str | None,
1782
+ parallel: int,
1783
+ loading_ratio: float,
1784
+ current_needed: float,
1785
+ before: tuple[str | None, int],
1786
+ pf_engine: PowerFlowEngine,
1787
+ take_back: bool = True,
1788
+ fewest: dict[str, int] | None = None,
1789
+ ) -> SizingOption:
1790
+ """
1791
+ Choose how to reinforce an overloaded line, among `_thermal_options`.
1792
+
1793
+ With the prices of the run (`cost_model`), the cheapest option, priced as
1794
+ `calculate_cost` charges the action that takes the line from its state
1795
+ `before` the action (type, conductors) to the option: what the line costs
1796
+ after it, from its state at the start of the run (`line_origins`), less what
1797
+ it cost before it. A line that no earlier action of the run has changed, or a
1798
+ strategy used without `line_origins`, is priced from its state before the
1799
+ action: the `line_upgrade` price of the new type for every conductor it had
1800
+ then, if the type changes, and the `new_line` price for every conductor
1801
+ added. Without prices, the smallest type that carries the line with the
1802
+ conductors it had before the action, and when none does, the option that lays
1803
+ the fewest conductors since then, then the least rating (see `choose_option`).
1804
+
1805
+ With prices, and unless `take_back` is False, a type change is sized from the
1806
+ conductors the line had before the action, not from those in place: a line
1807
+ that the action has given conductors of a type can still take fewer conductors
1808
+ of a larger type, as the current they were sized on has fallen, and the type
1809
+ change takes back the conductors the action laid. Never those the line had
1810
+ before the action, which the network or an earlier action laid. Without
1811
+ prices, a type change keeps at least the conductors in place, as nothing tells
1812
+ whether the larger type costs less than the conductors it takes back.
1813
+
1814
+ A type is offered with at least the conductors of `fewest`, for a type change
1815
+ that fewer conductors of did not carry the line (see `StepCheck`).
1816
+ """
1817
+ cost_model = getattr(self, "cost_model", None)
1818
+ options = self._thermal_options(
1819
+ line_id,
1820
+ current_type,
1821
+ parallel,
1822
+ loading_ratio,
1823
+ current_needed,
1824
+ pf_engine,
1825
+ before[1] if cost_model is not None and take_back else parallel,
1826
+ fewest,
1827
+ )
1828
+ price = None
1829
+ if cost_model is not None:
1830
+ length = pf_engine.get_line_length(line_id)
1831
+ origins = getattr(self, "line_origins", None)
1832
+ origin = origins.get(line_id, before) if origins else before
1833
+ origin = (type_in_place(origin[0]), origin[1])
1834
+
1835
+ def price(option: SizingOption) -> float:
1836
+ with unlogged(cost_model):
1837
+ return self._charge(
1838
+ cost_model,
1839
+ line_id,
1840
+ origin,
1841
+ before,
1842
+ (option.element_type, option.units),
1843
+ length,
1844
+ )
1845
+
1846
+ return choose_option(options, before, price)