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,210 @@
1
+ """
2
+ Thermal sizing shared by the line and transformer upgrades: what an overloaded element
3
+ needs, the ways to give it that, and the choice between them.
4
+
5
+ An element (a line, a transformer) is made of `units` identical units (conductors,
6
+ transformer units) in parallel. The engine reports its loading relative to the rating
7
+ it holds for the element, derating included: pandapower divides the current by
8
+ `max_i_ka * df * parallel` for a line, and by the rated current of `sn_mva * df *
9
+ parallel` for a transformer. A type change keeps the derating factor `df` and the
10
+ number of units, and gives every unit the rating of the new type. So, with the current
11
+ unchanged, units of rating `r` carry the element within the limit when
12
+
13
+ r * units >= loading / limit * units_in_place * rating_in_place
14
+
15
+ whatever the derating factor, the voltage, or the way the engine computes the loading.
16
+ The right-hand side is `required` below, in the unit of the ratings (A for a line, VA
17
+ for a transformer).
18
+ """
19
+
20
+ import logging
21
+ import math
22
+ from collections.abc import Callable, Iterator, Sequence
23
+ from contextlib import contextmanager
24
+ from dataclasses import dataclass
25
+ from typing import Any
26
+
27
+ from gridforge.core.cost_model import MissingUnitCostError
28
+ from gridforge.utils.logging import logger as _logger
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class SizingOption:
33
+ """
34
+ A state an overloaded element can be taken to, to carry what it carries.
35
+
36
+ Attributes:
37
+ element_type: The type of every unit after it (that in place to add units).
38
+ units: Number of units of the element after it.
39
+ laid: Number of units laid from the state in place: those replaced, if the
40
+ type changes, and those added.
41
+ rating: Rating of one unit of `element_type`.
42
+ changes_type: Whether the units in place are replaced.
43
+ """
44
+
45
+ element_type: str | None
46
+ units: int
47
+ laid: int
48
+ rating: float
49
+ changes_type: bool
50
+
51
+
52
+ @contextmanager
53
+ def unlogged(cost_model: Any) -> Iterator[None]:
54
+ """
55
+ Price with `cost_model` without its log lines, which read as what a run is
56
+ charged: an option that is only priced is not.
57
+ """
58
+ logger = getattr(cost_model, "logger", None)
59
+ disabled = getattr(logger, "disabled", None)
60
+ if disabled is None:
61
+ yield
62
+ return
63
+ logger.disabled = True
64
+ try:
65
+ yield
66
+ finally:
67
+ logger.disabled = disabled
68
+
69
+
70
+ def units_to_carry(required: float, rating: float, at_least: int) -> int:
71
+ """
72
+ Smallest number of units of `rating`, `at_least` or more, that carry `required`;
73
+ `at_least` if no number does (a rating of 0, a requirement that is not finite).
74
+ """
75
+ units = max(1, int(at_least))
76
+ if not (rating > 0.0 and math.isfinite(required)):
77
+ return units
78
+ while units * rating < required:
79
+ units += 1
80
+ return units
81
+
82
+
83
+ def keep_type_option(
84
+ element_type: str | None, units: int, rating: float | None, required: float | None
85
+ ) -> SizingOption:
86
+ """
87
+ The units in place, with as many more units of their kind as carry `required`: at
88
+ least one more, the element being overloaded. One more if the rating of a unit or
89
+ what the element needs is not known.
90
+ """
91
+ after = units + 1
92
+ if rating and required is not None and rating > 0.0:
93
+ after = units_to_carry(required, rating, units + 1)
94
+ return SizingOption(element_type, after, after - units, rating or 0.0, False)
95
+
96
+
97
+ def type_change_option(
98
+ element_type: str, rating: float, units: int, required: float | None
99
+ ) -> SizingOption:
100
+ """
101
+ Every unit replaced by one of `element_type`, with as many more as carry `required`.
102
+ """
103
+ after = units if required is None else units_to_carry(required, rating, units)
104
+ return SizingOption(element_type, after, after, rating, True)
105
+
106
+
107
+ def units_laid(before: tuple[Any, int], state: tuple[Any, int]) -> int:
108
+ """
109
+ Number of units of `state` (type, units) that the element did not have in the
110
+ state `before`: all of them if their type is not that of `before`, the units added
111
+ otherwise.
112
+ """
113
+ (before_type, before_units), (element_type, units) = before, state
114
+ if element_type == before_type:
115
+ return max(0, int(units) - int(before_units))
116
+ return int(units)
117
+
118
+
119
+ def laid_since(option: SizingOption, before: tuple[Any, int]) -> int:
120
+ """
121
+ Number of units of `option` that the element did not have in the state `before`
122
+ (type, units): all of them if their type is not that of `before`, the units added
123
+ otherwise.
124
+ """
125
+ return units_laid(before, (option.element_type, option.units))
126
+
127
+
128
+ def charge(
129
+ works_cost: Callable[[tuple[Any, int], tuple[Any, int]], float],
130
+ origin: tuple[Any, int],
131
+ before: tuple[Any, int],
132
+ after: tuple[Any, int],
133
+ ) -> float:
134
+ """
135
+ What an action that takes an element from `before` to `after` (type, units) is
136
+ charged, the run charging an element for what it lays on it from its state at the
137
+ start of the run, `origin`: what the works from `origin` to `after` cost, less
138
+ what those to `before` cost, which the earlier actions of the run were charged.
139
+
140
+ `works_cost(origin, state)` is the cost of the works that take the element from
141
+ `origin` to `state`, 0 for no works. However the steps and the actions of a run
142
+ divide the works on an element, their charges add up to the cost of the works from
143
+ its state at the start of the run to its state at the end, the states in between
144
+ being charged nothing: a type laid and replaced within the run, a unit added and
145
+ then replaced by one of another type. An action can thus be charged less than
146
+ nothing, if the works it replaces cost more than its own.
147
+ """
148
+ cost = works_cost(origin, after)
149
+ if before != origin:
150
+ cost -= works_cost(origin, before)
151
+ return cost
152
+
153
+
154
+ def choose_option(
155
+ options: Sequence[SizingOption],
156
+ before: tuple[Any, int],
157
+ price: Callable[[SizingOption], float] | None = None,
158
+ ) -> SizingOption:
159
+ """
160
+ Choose how to reinforce an overloaded element, among `options` (not empty), sized
161
+ on its loading now, from its state `before` the action (type, units).
162
+
163
+ An action takes the element towards the option chosen one step at a time (the
164
+ type change, then one unit at a time), and chooses again on the loading each step
165
+ leaves. The choice is made from the state before the action, not from the state
166
+ the steps have reached: a step taken towards an option does not turn the next
167
+ choice to another, while an option sized on a loading that the steps have
168
+ lowered can be smaller than the one chosen at first.
169
+
170
+ With prices (`price` given, which prices an option from `before`, as the run
171
+ charges it), the cheapest option. An option whose price is missing is left out,
172
+ unless all are: the choice is then made as without prices, and the action is
173
+ stopped by the missing price when it is charged.
174
+
175
+ Without prices, the first type change that carries the element with the units it
176
+ had before the action, in the order of `options` (the smallest type first): a
177
+ larger type is the usual way to reinforce, and nothing tells whether a parallel
178
+ unit is cheaper. When no type does, units must be added in parallel anyway, and
179
+ the option that lays the fewest units since `before`, then the least rating, is
180
+ taken, rather than the largest type and units of it in parallel.
181
+
182
+ Ties go to the option that lays the fewest units since `before`, then the least
183
+ rating, then to the first in the order of `options`.
184
+ """
185
+
186
+ def laid(option: SizingOption) -> tuple[int, float]:
187
+ units = laid_since(option, before)
188
+ return units, units * option.rating
189
+
190
+ if price is not None:
191
+ priced = []
192
+ for option in options:
193
+ try:
194
+ priced.append((price(option), option))
195
+ except MissingUnitCostError:
196
+ continue
197
+ if _logger.isEnabledFor(logging.DEBUG):
198
+ _logger.debug(
199
+ "Options priced: "
200
+ + ", ".join(
201
+ f"{o.units} x {o.element_type} ({o.laid} laid): {p:.2f}"
202
+ for p, o in priced
203
+ )
204
+ )
205
+ if priced:
206
+ return min(priced, key=lambda p: (p[0], *laid(p[1])))[1]
207
+ for option in options:
208
+ if option.changes_type and option.units == before[1]:
209
+ return option
210
+ return min(options, key=laid)
@@ -0,0 +1,183 @@
1
+ """
2
+ Steps checked against the loading limit of their own element by the power flow that
3
+ follows them (#57).
4
+
5
+ A strategy sizes a step on the current an element carries before it: a cable that a
6
+ line is buried into must carry the line, a larger transformer must carry its power. The
7
+ step itself moves that current: under generation, a conductor or a transformer of lower
8
+ impedance lowers the voltage at the generators, which then inject more current; in a
9
+ mesh, or with separate elements in parallel, an element of lower impedance draws current
10
+ from the others. So the strategies take such a step, read the loading of its element in
11
+ the power flow they run after it anyway, and undo the step if the element is over its
12
+ limit, with the exactness of the limit check itself: no margin, no prediction.
13
+
14
+ `StepCheck` holds what that needs for one round of steps (those taken on one power
15
+ flow): the elements saved before their step, the solution of the power flow the round
16
+ was decided on, and, for the rest of the action, the steps refused, as the fewest units
17
+ of each type an element may take.
18
+ """
19
+
20
+ from collections.abc import Container
21
+ from typing import Any
22
+
23
+ from gridforge.core.power_flow import PowerFlowEngine
24
+
25
+
26
+ def _cannot(*_: Any) -> Any:
27
+ raise NotImplementedError
28
+
29
+
30
+ class StepCheck:
31
+ """
32
+ The steps of a round that are checked after the power flow that follows them.
33
+
34
+ `save(element, info)` is called before a step to check: it saves the element, and
35
+ the solution of the round at its first step. After the power flow, `failed` lists the
36
+ elements checked that are over their limit; `undo` gives each back what it was and
37
+ returns what was noted with it; `restore_solution` puts back the solution the round
38
+ was decided on, so that a round whose steps are all undone leaves the network, its
39
+ result tables and the engine exactly as before it, with no power flow. A round with
40
+ steps kept is solved again from that same solution, so that its results are those
41
+ of the steps kept taken alone. `refuse` records a step refused: an element that did
42
+ not carry `units` units of a type needs at least one more of it, for the rest of the
43
+ action (`fewest`).
44
+
45
+ The checks need an engine that can save an element and give it back, and save its
46
+ solution and put it back, which the first `save` of the action tries before the step
47
+ changes anything; without all four, `save` returns False and the steps are taken
48
+ unchecked, as before the checks existed.
49
+ """
50
+
51
+ def __init__(self, pf_engine: PowerFlowEngine, element: str):
52
+ """
53
+ Args:
54
+ pf_engine (PowerFlowEngine): The engine.
55
+ element (str): The kind of the elements, "line" or "transformer": they are
56
+ saved and given back with the engine's `save_<element>` and
57
+ `restore_<element>`.
58
+ """
59
+ self._save_solution = getattr(pf_engine, "save_solution", _cannot)
60
+ self._restore_solution = getattr(pf_engine, "restore_solution", _cannot)
61
+ self._save_element = getattr(pf_engine, f"save_{element}", _cannot)
62
+ self._restore_element = getattr(pf_engine, f"restore_{element}", _cannot)
63
+ # None until the engine has shown it can do all four operations
64
+ self.available: bool | None = None
65
+ # The solution the round was decided on, saved at its first step checked
66
+ self._solution: Any = None
67
+ # The elements of the round under check: what each was, and what the strategy
68
+ # noted with its step
69
+ self.pending: dict[str, tuple[Any, Any]] = {}
70
+ # For each element, the fewest units of each type a step may give it
71
+ self._fewest: dict[str, dict[Any, int]] = {}
72
+ # The elements refused last, as their step left them, and the solution of
73
+ # the power flow that refused them (`note_failed`)
74
+ self._failed: dict[str, Any] = {}
75
+ self._failed_solution: Any = None
76
+
77
+ def can_check(self, element_id: str) -> bool:
78
+ """
79
+ Whether the engine can check steps: it is tried once, on `element_id`, which
80
+ is saved and given back what it was, as is the solution, without changing
81
+ either.
82
+ """
83
+ if self.available is None:
84
+ try:
85
+ saved = self._save_element(element_id)
86
+ self._restore_element(element_id, saved)
87
+ self._restore_solution(self._save_solution())
88
+ self.available = True
89
+ except NotImplementedError:
90
+ self.available = False
91
+ return self.available
92
+
93
+ def save(self, element_id: str, info: Any = None) -> bool:
94
+ """
95
+ Save `element_id` before a step to check, with `info`, and the solution of the
96
+ round at its first step. False, and nothing saved, if the engine cannot check
97
+ steps.
98
+ """
99
+ if not self.can_check(element_id):
100
+ return False
101
+ saved = self._save_element(element_id)
102
+ if self._solution is None:
103
+ self._solution = self._save_solution()
104
+ self.pending[element_id] = (saved, info)
105
+ return True
106
+
107
+ def forget(self, element_id: str) -> None:
108
+ """Take `element_id` out of the round, its step not taken or not checked."""
109
+ self.pending.pop(element_id, None)
110
+
111
+ def failed(self, overloaded: Container[str]) -> list[str]:
112
+ """The elements of the round that are in `overloaded`, in the order of their steps."""
113
+ return [element for element in self.pending if element in overloaded]
114
+
115
+ def undo(self, element_id: str) -> Any:
116
+ """
117
+ Give `element_id` back what it was before its step, take it out of the round,
118
+ and return what was noted with its step.
119
+ """
120
+ saved, info = self.pending.pop(element_id)
121
+ self._restore_element(element_id, saved)
122
+ return info
123
+
124
+ def restore_solution(self) -> None:
125
+ """Put back the solution the round was decided on."""
126
+ self._restore_solution(self._solution)
127
+
128
+ def note_failed(self, failed: list[str]) -> None:
129
+ """
130
+ Note what the elements of `failed` are after their step, and the solution of
131
+ the power flow that refused them, before they are undone, for
132
+ `taken_again`.
133
+ """
134
+ self._failed = {element: self._save_element(element) for element in failed}
135
+ self._failed_solution = self._save_solution()
136
+
137
+ def taken_again(self) -> bool:
138
+ """
139
+ Whether the steps taken in place of those refused (`note_failed`) leave each
140
+ element as its refused step did, as when the type refused is chosen again
141
+ with more units, to be added one at a time: the network is then the one the
142
+ power flow that refused them solved, from the solution the round was decided
143
+ on, and its solution is put back instead of solving it again.
144
+ """
145
+ same = all(
146
+ self._save_element(element).equals(row)
147
+ for element, row in self._failed.items()
148
+ )
149
+ if same:
150
+ self._restore_solution(self._failed_solution)
151
+ return same
152
+
153
+ def end_round(self) -> None:
154
+ """Forget the round: its steps are kept, the next is decided on a new solution."""
155
+ self.pending.clear()
156
+ self._solution = None
157
+
158
+ def refuse(self, element_id: str, element_type: Any, units: int) -> None:
159
+ """
160
+ Record that `units` units of `element_type` did not carry `element_id`.
161
+
162
+ A refusal must raise the fewest units of that type the element may take: a
163
+ step refused that a refusal had already ruled out means that a decision of
164
+ the strategy ignored it, and would be taken and refused again for ever. It
165
+ raises a RuntimeError instead. The refusals of an action are so bounded by
166
+ the units an element can have, whatever the decisions.
167
+ """
168
+ fewest = self._fewest.setdefault(element_id, {})
169
+ if int(units) < fewest.get(element_type, 0):
170
+ raise RuntimeError(
171
+ f"{units} units of {element_type!r} refused again for {element_id!r}, "
172
+ "though a refusal had ruled them out: a decision ignored it"
173
+ )
174
+ fewest[element_type] = int(units) + 1
175
+
176
+ def fewest(self, element_id: str) -> dict[Any, int]:
177
+ """The fewest units of each type refused that `element_id` may take."""
178
+ return self._fewest.get(element_id, {})
179
+
180
+ @property
181
+ def refused(self) -> dict[str, dict[Any, int]]:
182
+ """`fewest` of every element that has a step refused."""
183
+ return self._fewest
@@ -0,0 +1,267 @@
1
+ from typing import Any
2
+
3
+ import numpy as np
4
+
5
+ from gridforge import ConstraintType, ConstraintViolation, CostModel, PowerFlowEngine
6
+ from gridforge.core.strategy import EnhancementStrategy
7
+ from gridforge.utils.logging import logger
8
+
9
+
10
+ class TapChangeStrategy(EnhancementStrategy):
11
+ """
12
+ Strategy to change transformer tap positions to address voltage violations.
13
+
14
+ This strategy identifies voltage violations in galvanically connected components
15
+ and adjusts the tap position of the supplying transformer to shift the voltage
16
+ profile towards the target value (typically 1.0 p.u.).
17
+
18
+ Attributes:
19
+ logs (List[str]): List of log messages generated during execution.
20
+ """
21
+
22
+ def __init__(self):
23
+ """Initialize the TapChangeStrategy."""
24
+ super().__init__()
25
+
26
+ @property
27
+ def name(self) -> str:
28
+ """
29
+ Get the name of the strategy.
30
+
31
+ Returns:
32
+ str: The name of the strategy ("Transformer Tap Change").
33
+ """
34
+ return "Transformer Tap Change"
35
+
36
+ @property
37
+ def cost_level(self) -> int:
38
+ """
39
+ Get the cost level of the strategy.
40
+
41
+ Returns:
42
+ int: The cost level (1 for tap changes, as they are low-cost).
43
+ """
44
+ # Tap changes are usually low-cost and should be tried early
45
+ return 1
46
+
47
+ @property
48
+ def stage(self) -> str:
49
+ """
50
+ Get the stage of the strategy.
51
+
52
+ Returns:
53
+ str: The stage ("operation").
54
+ """
55
+ return "operation"
56
+
57
+ def applicable_constraints(self) -> set[ConstraintType]:
58
+ """
59
+ Get the set of applicable constraint types.
60
+
61
+ Returns:
62
+ Set[ConstraintType]: The set of applicable constraint types.
63
+ """
64
+ return {ConstraintType.UNDER_VOLTAGE, ConstraintType.OVER_VOLTAGE}
65
+
66
+ def apply_to_group(
67
+ self, violations: list[ConstraintViolation], pf_engine: PowerFlowEngine
68
+ ) -> dict[str, Any] | None:
69
+ """
70
+ Find the optimal tap setting for transformers to address voltage violations.
71
+
72
+ This method analyzes voltage violations in each network component and calculates
73
+ the optimal tap position that will bring the voltages closest to the nominal value
74
+ (typically 1.0 p.u.), while staying within acceptable limits.
75
+
76
+ Args:
77
+ violations (List[ConstraintViolation]): List of voltage-related constraint violations.
78
+ pf_engine (PowerFlowEngine): Power flow engine instance to use for network analysis.
79
+
80
+ Returns:
81
+ Optional[Dict[str, Any]]: Dictionary with details of the tap change actions performed, or None if no
82
+ actions could be applied.
83
+ """
84
+ self.logs = []
85
+ if not violations:
86
+ return None
87
+
88
+ # Group violations by affected component/feeder
89
+ violations_by_component = pf_engine.group_violations_by_component(violations)
90
+
91
+ # Track actions for all components
92
+ transformer_actions = []
93
+
94
+ grid_state_str = self._format_grid_state(violations)
95
+ action_count = 0
96
+
97
+ # Process each component with violations
98
+ for component_id, component_violations in violations_by_component.items():
99
+ # Skip empty violation lists
100
+ if not component_violations:
101
+ continue
102
+
103
+ # Find the transformer for this component
104
+ transformer_id = pf_engine.get_transformer_for_component(component_id)
105
+ if not transformer_id:
106
+ logger.info(f"No transformer found for component {component_id}")
107
+ continue
108
+
109
+ # Get current voltage range in the component
110
+ try:
111
+ voltage_range = pf_engine.get_voltage_magnitude_range(component_id)
112
+ current_min_v = voltage_range["min"]
113
+ current_max_v = voltage_range["max"]
114
+ current_avg_v = (current_min_v + current_max_v) / 2
115
+
116
+ # Target is typically 1.0 p.u., but we could make this configurable
117
+ target_voltage = 1.0
118
+
119
+ # Get available tap positions (as p.u. voltage adjustments)
120
+ tap_positions = pf_engine.get_transformer_tap_positions(transformer_id)
121
+
122
+ # Calculate the ideal tap adjustment to center the voltage range around target
123
+ ideal_adjustment = target_voltage - current_avg_v
124
+
125
+ optimal_tap_idx = np.abs(tap_positions - ideal_adjustment).argmin()
126
+ optimal_tap_value = tap_positions[optimal_tap_idx]
127
+
128
+ # Get current tap position
129
+ current_tap_idx = np.where(np.abs(tap_positions) < 1e-6)[0][
130
+ 0
131
+ ] # Find position closest to 0
132
+
133
+ # Calculate the tap position shift needed
134
+ tap_shift = optimal_tap_idx - current_tap_idx
135
+
136
+ # Skip if no shift is needed
137
+ if tap_shift == 0:
138
+ logger.info(
139
+ f"No tap change needed for transformer {transformer_id}"
140
+ )
141
+ continue
142
+
143
+ # Apply the tap change. The engine refuses a shift that would leave
144
+ # the tap range, which the shift counted from the neutral position
145
+ # can from another position: it is then cut, a step at a time, to
146
+ # what the range allows
147
+ old_position = pf_engine.get_transformer_tap_position(transformer_id)
148
+ step = 1 if tap_shift > 0 else -1
149
+ success = pf_engine.apply_tap_change(transformer_id, tap_shift)
150
+ while not success and tap_shift != step:
151
+ tap_shift -= step
152
+ success = pf_engine.apply_tap_change(transformer_id, tap_shift)
153
+ if success and tap_shift != optimal_tap_idx - current_tap_idx:
154
+ logger.info(
155
+ f"Tap change of transformer {transformer_id} cut to "
156
+ f"{tap_shift} steps by the end of its tap range"
157
+ )
158
+ optimal_tap_value = tap_positions[current_tap_idx + tap_shift]
159
+
160
+ if success:
161
+ action_count += 1
162
+ # Calculate impact and record the action
163
+ estimated_new_min_v = current_min_v + optimal_tap_value
164
+ estimated_new_max_v = current_max_v + optimal_tap_value
165
+ estimated_new_avg_v = (
166
+ estimated_new_min_v + estimated_new_max_v
167
+ ) / 2
168
+
169
+ transformer_actions.append(
170
+ {
171
+ "transformer_id": transformer_id,
172
+ "component": component_id,
173
+ "change": tap_shift,
174
+ # Absolute positions, None if the engine does not tell
175
+ # them: the algorithm reverts the change to the first
176
+ "old_position": old_position,
177
+ "new_position": pf_engine.get_transformer_tap_position(
178
+ transformer_id
179
+ ),
180
+ "violations_addressed": len(component_violations),
181
+ "before": {
182
+ "min_voltage": current_min_v,
183
+ "max_voltage": current_max_v,
184
+ "avg_voltage": current_avg_v,
185
+ },
186
+ "after": {
187
+ "estimated_min_voltage": estimated_new_min_v,
188
+ "estimated_max_voltage": estimated_new_max_v,
189
+ "estimated_avg_voltage": estimated_new_avg_v,
190
+ },
191
+ "target_voltage": target_voltage,
192
+ }
193
+ )
194
+
195
+ justification = (
196
+ f"Voltage deviation in component '{component_id}'. "
197
+ f"Current avg: {current_avg_v:.4f} p.u. Target: {target_voltage:.4f} p.u. "
198
+ f"Ideal adjustment: {ideal_adjustment:.4f} p.u."
199
+ )
200
+
201
+ action_str = (
202
+ f"Tap Change on transformer '{transformer_id}': Shift {tap_shift} steps "
203
+ f"(Voltage change: {optimal_tap_value:.4f} p.u.)"
204
+ )
205
+
206
+ # Find the max violation for logging
207
+ max_violation = max(
208
+ component_violations, key=lambda v: abs(v.violation_value)
209
+ )
210
+
211
+ self._log_iteration(
212
+ action_count,
213
+ grid_state_str,
214
+ f"Transformer '{component_id}' - Violation: {max_violation.violation_value:.4f} p.u.",
215
+ justification,
216
+ action_str,
217
+ )
218
+
219
+ except Exception as e:
220
+ logger.error(
221
+ f"Error calculating optimal tap setting for component {component_id}: {str(e)}"
222
+ )
223
+ continue
224
+
225
+ # If any tap changes were applied
226
+ if transformer_actions:
227
+ return {
228
+ "type": "tap_change",
229
+ "transformers": transformer_actions,
230
+ "violation_type": violations[0].constraint_type.value,
231
+ "total_violations_addressed": sum(
232
+ a["violations_addressed"] for a in transformer_actions
233
+ ),
234
+ }
235
+
236
+ return None
237
+
238
+ def calculate_cost(self, action: dict[str, Any], cost_model: CostModel) -> float:
239
+ """
240
+ Calculate the cost of the tap change actions.
241
+
242
+ Args:
243
+ action (Dict[str, Any]): The action dictionary.
244
+ cost_model (CostModel): The cost model.
245
+
246
+ Returns:
247
+ float: The total cost of the tap changes.
248
+ """
249
+ total_cost = 0.0
250
+ for transformer_action in action.get("transformers", []):
251
+ total_cost += cost_model.calculate_tap_change_cost(
252
+ transformer_action.get("transformer_id", ""),
253
+ transformer_action.get("change", 0),
254
+ )
255
+ return total_cost
256
+
257
+ def required_unit_costs(self, pf_engine: PowerFlowEngine) -> set[tuple[str, ...]]:
258
+ """
259
+ List the price of a tap step.
260
+
261
+ Args:
262
+ pf_engine (PowerFlowEngine): The power flow engine.
263
+
264
+ Returns:
265
+ Set[Tuple[str, ...]]: The key of the price in `CostModel.unit_costs`.
266
+ """
267
+ return {("tap_change",)}