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.
- distgridforge-0.3.0.dist-info/METADATA +266 -0
- distgridforge-0.3.0.dist-info/RECORD +38 -0
- distgridforge-0.3.0.dist-info/WHEEL +5 -0
- distgridforge-0.3.0.dist-info/licenses/LICENCE.txt +21 -0
- distgridforge-0.3.0.dist-info/top_level.txt +1 -0
- gridforge/__init__.py +32 -0
- gridforge/case_study/config.py +158 -0
- gridforge/case_study/dickert_lv_network_script.py +109 -0
- gridforge/case_study/mv_lv_feeder.py +314 -0
- gridforge/case_study/simbench_network_test_case.py +168 -0
- gridforge/core/__init__.py +0 -0
- gridforge/core/constraints.py +421 -0
- gridforge/core/cost_model.py +363 -0
- gridforge/core/grid_enhancement.py +1932 -0
- gridforge/core/power_flow.py +1146 -0
- gridforge/core/strategy.py +297 -0
- gridforge/engines/__init__.py +0 -0
- gridforge/engines/gridlabd_engine.py +527 -0
- gridforge/engines/opendss_engine.py +885 -0
- gridforge/engines/pandapower_engine.py +3766 -0
- gridforge/engines/roseau_engine.py +1234 -0
- gridforge/examples/__init__.py +0 -0
- gridforge/examples/quick_start.py +85 -0
- gridforge/main.py +0 -0
- gridforge/strategies/__init__.py +0 -0
- gridforge/strategies/flexibility.py +1476 -0
- gridforge/strategies/line_upgrade.py +1846 -0
- gridforge/strategies/path_to_source.py +596 -0
- gridforge/strategies/sizing.py +210 -0
- gridforge/strategies/step_check.py +183 -0
- gridforge/strategies/tap_change.py +267 -0
- gridforge/strategies/transformer_upgrade.py +622 -0
- gridforge/utils/__init__.py +0 -0
- gridforge/utils/config.py +55 -0
- gridforge/utils/interactive_plot.py +700 -0
- gridforge/utils/logging.py +86 -0
- gridforge/utils/plot.py +1078 -0
- gridforge/utils/reporting.py +0 -0
|
@@ -0,0 +1,622 @@
|
|
|
1
|
+
import math
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from gridforge import ConstraintType, ConstraintViolation, CostModel, PowerFlowEngine
|
|
5
|
+
from gridforge.core.power_flow import type_in_place
|
|
6
|
+
from gridforge.core.strategy import EnhancementStrategy, note_origins
|
|
7
|
+
from gridforge.strategies.sizing import (
|
|
8
|
+
SizingOption,
|
|
9
|
+
charge,
|
|
10
|
+
choose_option,
|
|
11
|
+
keep_type_option,
|
|
12
|
+
type_change_option,
|
|
13
|
+
units_laid,
|
|
14
|
+
unlogged,
|
|
15
|
+
)
|
|
16
|
+
from gridforge.strategies.step_check import StepCheck
|
|
17
|
+
from gridforge.utils.logging import logger as _logger
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class TransformerUpgradeStrategy(EnhancementStrategy):
|
|
21
|
+
"""
|
|
22
|
+
Strategy to upgrade transformers to address transformer loading violations.
|
|
23
|
+
|
|
24
|
+
This strategy identifies overloaded transformers and replaces their units with a
|
|
25
|
+
type of higher rating, or adds units of the type in place in parallel. The units
|
|
26
|
+
are sized on the loading the engine reports, and the choice between a larger type
|
|
27
|
+
and units in parallel is made on the prices of the run, if it has some (see
|
|
28
|
+
`_choose_upgrade`).
|
|
29
|
+
|
|
30
|
+
Attributes:
|
|
31
|
+
transformer_types (List[str]): List of available transformer types.
|
|
32
|
+
logs (List[str]): List of log messages generated during execution.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(self, transformer_types: list[str]):
|
|
36
|
+
"""
|
|
37
|
+
Initialize the TransformerUpgradeStrategy.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
transformer_types (List[str]): List of available transformer types.
|
|
41
|
+
"""
|
|
42
|
+
super().__init__()
|
|
43
|
+
self.transformer_types = transformer_types
|
|
44
|
+
self.max_iterations = 50
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def name(self) -> str:
|
|
48
|
+
"""
|
|
49
|
+
Get the name of the strategy.
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
str: The name of the strategy ("Transformer Upgrade").
|
|
53
|
+
"""
|
|
54
|
+
return "Transformer Upgrade"
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def cost_level(self) -> int:
|
|
58
|
+
"""
|
|
59
|
+
Get the cost level of the strategy.
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
int: The cost level (4 for transformer upgrades).
|
|
63
|
+
"""
|
|
64
|
+
return 4
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def stage(self) -> str:
|
|
68
|
+
"""
|
|
69
|
+
Get the stage of the strategy.
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
str: The stage ("planning").
|
|
73
|
+
"""
|
|
74
|
+
return "planning"
|
|
75
|
+
|
|
76
|
+
def applicable_constraints(self) -> set[ConstraintType]:
|
|
77
|
+
"""
|
|
78
|
+
Get the set of applicable constraint types.
|
|
79
|
+
|
|
80
|
+
Returns:
|
|
81
|
+
Set[ConstraintType]: The set of applicable constraint types.
|
|
82
|
+
"""
|
|
83
|
+
return {ConstraintType.TRANSFORMER_LOADING}
|
|
84
|
+
|
|
85
|
+
def apply_to_group(
|
|
86
|
+
self, violations: list[ConstraintViolation], pf_engine: PowerFlowEngine
|
|
87
|
+
) -> dict[str, Any] | None:
|
|
88
|
+
"""
|
|
89
|
+
Apply transformer upgrades to address a group of transformer loading violations.
|
|
90
|
+
|
|
91
|
+
The strategy identifies overloaded transformers and upgrades them based on loading levels.
|
|
92
|
+
A transformer whose loading the last unit added in parallel did not lower gets
|
|
93
|
+
no more units (see `_stalled`).
|
|
94
|
+
|
|
95
|
+
A type change sized to carry the transformer with the units in place is checked
|
|
96
|
+
by the power flow that follows the iteration: a larger unit has a lower
|
|
97
|
+
impedance, which under export lowers the voltage on the LV side and raises the
|
|
98
|
+
current. If the transformer is over its limit, the type change is undone (the
|
|
99
|
+
engine gives the transformer back what it was, `save_transformer`,
|
|
100
|
+
`restore_transformer`, and puts back the solution the iteration was decided
|
|
101
|
+
on, `save_solution`, `restore_solution`), and the transformer takes, in the
|
|
102
|
+
same iteration, the step chosen on the same power flow with that type offered
|
|
103
|
+
with one more unit for the rest of the action (see `StepCheck`), at the cost
|
|
104
|
+
of one more power flow. On an engine that cannot do all four operations, the
|
|
105
|
+
type changes are not checked: a transformer still overloaded takes its next
|
|
106
|
+
step at the next iteration.
|
|
107
|
+
|
|
108
|
+
Args:
|
|
109
|
+
violations (List[ConstraintViolation]): List of transformer loading violations.
|
|
110
|
+
pf_engine (PowerFlowEngine): Power flow engine instance.
|
|
111
|
+
|
|
112
|
+
Returns:
|
|
113
|
+
Optional[Dict[str, Any]]: Dictionary with details of the transformer upgrade actions performed, or None if no actions could be applied.
|
|
114
|
+
"""
|
|
115
|
+
self.logs = []
|
|
116
|
+
if not violations:
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
# Track upgrade actions
|
|
120
|
+
transformer_upgrades = []
|
|
121
|
+
|
|
122
|
+
action_count = 0
|
|
123
|
+
iteration = 0
|
|
124
|
+
transfo_violations = violations
|
|
125
|
+
# A unit may be loaded up to the limit (%) of its rating: a 110 % limit lets a
|
|
126
|
+
# 250 kVA unit carry 275 kVA
|
|
127
|
+
max_loading = getattr(
|
|
128
|
+
getattr(pf_engine, "constraints", None), "max_transformer_loading", 100.0
|
|
129
|
+
)
|
|
130
|
+
get_parallel = getattr(pf_engine, "get_transformer_parallel", lambda _: 1)
|
|
131
|
+
# Type and units of each transformer before this action, from which its
|
|
132
|
+
# options are chosen at every step
|
|
133
|
+
before: dict[str, tuple[str | None, int]] = {}
|
|
134
|
+
# The transformers given a unit in parallel at this iteration, with their
|
|
135
|
+
# overload before it, and those to which a unit did not lower it
|
|
136
|
+
added: dict[str, float] = {}
|
|
137
|
+
stalled: set[str] = set()
|
|
138
|
+
|
|
139
|
+
# The type changes sized to carry their transformer, checked by the power flow
|
|
140
|
+
# that follows them (see `StepCheck`)
|
|
141
|
+
check = StepCheck(pf_engine, "transformer")
|
|
142
|
+
|
|
143
|
+
def step(chosen_on: tuple[Any, ...]) -> tuple[dict[str, Any], str]:
|
|
144
|
+
"""
|
|
145
|
+
Take a transformer one step towards the option chosen for it, on the
|
|
146
|
+
loading `chosen_on` holds: the type change, then one unit at a time, each
|
|
147
|
+
judged again on the loading it leaves. A type change sized to carry the
|
|
148
|
+
transformer by itself is saved first, to be checked.
|
|
149
|
+
"""
|
|
150
|
+
transformer_id, current_type, units, overload_factor = chosen_on[:4]
|
|
151
|
+
option = self._choose_upgrade(
|
|
152
|
+
transformer_id,
|
|
153
|
+
current_type,
|
|
154
|
+
units,
|
|
155
|
+
# The loading the engine reports, over the limit
|
|
156
|
+
1.0 + overload_factor,
|
|
157
|
+
chosen_on[4] / (max_loading / 100.0),
|
|
158
|
+
pf_engine,
|
|
159
|
+
before[transformer_id],
|
|
160
|
+
check.fewest(transformer_id),
|
|
161
|
+
)
|
|
162
|
+
new_transformer_type = option.element_type if option.changes_type else None
|
|
163
|
+
upgrade = {
|
|
164
|
+
"transformer_id": transformer_id,
|
|
165
|
+
"old_type": current_type,
|
|
166
|
+
# A unit added in parallel is of the kind in place
|
|
167
|
+
"new_type": new_transformer_type or current_type,
|
|
168
|
+
"overload_factor": overload_factor,
|
|
169
|
+
}
|
|
170
|
+
# What a step adds is read from the rating of the unit, which a unit
|
|
171
|
+
# without a catalogued type has only in the table
|
|
172
|
+
unit_rating = self._unit_rating(pf_engine, transformer_id)
|
|
173
|
+
if unit_rating is not None and math.isfinite(unit_rating):
|
|
174
|
+
upgrade["old_rating"] = unit_rating
|
|
175
|
+
if new_transformer_type is not None:
|
|
176
|
+
if option.units <= units:
|
|
177
|
+
check.save(transformer_id, (chosen_on, new_transformer_type))
|
|
178
|
+
pf_engine.upgrade_transformer(transformer_id, new_transformer_type)
|
|
179
|
+
# The type change replaces every unit of the transformer
|
|
180
|
+
upgrade["units"] = units
|
|
181
|
+
action_str = f"Upgrade transformer '{transformer_id}': {current_type} -> {new_transformer_type}"
|
|
182
|
+
else:
|
|
183
|
+
upgrade["parallel_count"] = int(
|
|
184
|
+
pf_engine.add_parallel_transformer(transformer_id)
|
|
185
|
+
)
|
|
186
|
+
added[transformer_id] = overload_factor
|
|
187
|
+
action_str = (
|
|
188
|
+
f"Add parallel transformer to '{transformer_id}': {current_type}"
|
|
189
|
+
)
|
|
190
|
+
return upgrade, action_str
|
|
191
|
+
|
|
192
|
+
while transfo_violations and iteration < self.max_iterations:
|
|
193
|
+
grid_state_str = self._format_grid_state(transfo_violations)
|
|
194
|
+
critical = self._identify_critical_elements(transfo_violations)
|
|
195
|
+
stalled |= self._stalled(added, critical)
|
|
196
|
+
added = {}
|
|
197
|
+
# The transformers overloaded now, most overloaded first: one that an earlier
|
|
198
|
+
# iteration brought within its limit gets nothing more, nor one that the
|
|
199
|
+
# last unit added did not relieve
|
|
200
|
+
critical = [element for element in critical if element[0] not in stalled]
|
|
201
|
+
if not critical:
|
|
202
|
+
break
|
|
203
|
+
# The place of the entry of each transformer of this iteration
|
|
204
|
+
entry_of: dict[str, int] = {}
|
|
205
|
+
for (
|
|
206
|
+
transformer_id,
|
|
207
|
+
overload_factor,
|
|
208
|
+
power,
|
|
209
|
+
) in critical:
|
|
210
|
+
current_type = self._type_in_place(
|
|
211
|
+
pf_engine.get_transformer_type(transformer_id)
|
|
212
|
+
)
|
|
213
|
+
units = max(1, int(get_parallel(transformer_id)))
|
|
214
|
+
before.setdefault(transformer_id, (current_type, units))
|
|
215
|
+
chosen_on = (
|
|
216
|
+
transformer_id,
|
|
217
|
+
current_type,
|
|
218
|
+
units,
|
|
219
|
+
overload_factor,
|
|
220
|
+
power,
|
|
221
|
+
)
|
|
222
|
+
upgrade, action_str = step(chosen_on)
|
|
223
|
+
entry_of[transformer_id] = len(transformer_upgrades)
|
|
224
|
+
transformer_upgrades.append(upgrade)
|
|
225
|
+
action_count += 1
|
|
226
|
+
|
|
227
|
+
self._log_iteration(
|
|
228
|
+
action_count,
|
|
229
|
+
grid_state_str,
|
|
230
|
+
f"Transformer '{transformer_id}' (Loading) - Violation: {overload_factor * 100:.2f} %",
|
|
231
|
+
f"Transformer '{transformer_id}' overloaded by {overload_factor * 100:.2f}%. "
|
|
232
|
+
f"Current capacity insufficient for {power:.4f} MVA.",
|
|
233
|
+
action_str,
|
|
234
|
+
)
|
|
235
|
+
# Run power flow again to check if violations are resolved
|
|
236
|
+
transfo_violations = self._rerun_and_filter_violations(
|
|
237
|
+
pf_engine, ConstraintType.TRANSFORMER_LOADING
|
|
238
|
+
)
|
|
239
|
+
# A type change sized to carry its transformer that leaves it over its
|
|
240
|
+
# limit is undone, the transformer given back what it was, and it takes
|
|
241
|
+
# in its place the step chosen on the same power flow without that type
|
|
242
|
+
# for as few units: the iteration ends as if that option had never been
|
|
243
|
+
# offered, at the cost of one more power flow
|
|
244
|
+
while failed := check.failed({v.element_id for v in transfo_violations}):
|
|
245
|
+
check.note_failed(failed)
|
|
246
|
+
refused = []
|
|
247
|
+
for transformer_id in failed:
|
|
248
|
+
chosen_on, new_type = check.undo(transformer_id)
|
|
249
|
+
check.refuse(transformer_id, new_type, chosen_on[2])
|
|
250
|
+
refused.append(chosen_on)
|
|
251
|
+
# The power flow below starts from the solution the iteration was
|
|
252
|
+
# decided on, as it would have without the type changes undone
|
|
253
|
+
check.restore_solution()
|
|
254
|
+
for chosen_on in refused:
|
|
255
|
+
transformer_id = chosen_on[0]
|
|
256
|
+
upgrade, action_str = step(chosen_on)
|
|
257
|
+
transformer_upgrades[entry_of[transformer_id]] = upgrade
|
|
258
|
+
action_count += 1
|
|
259
|
+
self._log_iteration(
|
|
260
|
+
action_count,
|
|
261
|
+
grid_state_str,
|
|
262
|
+
f"Transformer '{transformer_id}' (Loading)",
|
|
263
|
+
f"Transformer '{transformer_id}' still overloaded after a type "
|
|
264
|
+
"change sized to carry it: the type change is undone.",
|
|
265
|
+
action_str,
|
|
266
|
+
)
|
|
267
|
+
if check.taken_again():
|
|
268
|
+
# The type refused, chosen again with more units: the power flow
|
|
269
|
+
# that refused it stands for the steps taken in its place
|
|
270
|
+
break
|
|
271
|
+
transfo_violations = self._rerun_and_filter_violations(
|
|
272
|
+
pf_engine, ConstraintType.TRANSFORMER_LOADING
|
|
273
|
+
)
|
|
274
|
+
check.end_round()
|
|
275
|
+
iteration += 1
|
|
276
|
+
|
|
277
|
+
# The state each transformer is charged from, if the strategy holds it, so
|
|
278
|
+
# that the action is charged as its options were priced
|
|
279
|
+
note_origins(
|
|
280
|
+
transformer_upgrades,
|
|
281
|
+
getattr(self, "transformer_origins", None),
|
|
282
|
+
"transformer_id",
|
|
283
|
+
"origin_units",
|
|
284
|
+
)
|
|
285
|
+
if transformer_upgrades:
|
|
286
|
+
return {
|
|
287
|
+
"type": "transformer_upgrade",
|
|
288
|
+
"transformers": transformer_upgrades,
|
|
289
|
+
"violation_type": violations[0].constraint_type.value,
|
|
290
|
+
"total_violations_addressed": len(violations),
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
return None
|
|
294
|
+
|
|
295
|
+
def _stalled(
|
|
296
|
+
self,
|
|
297
|
+
added: dict[str, float],
|
|
298
|
+
critical: list[tuple[str, float, float]],
|
|
299
|
+
) -> set[str]:
|
|
300
|
+
"""
|
|
301
|
+
The transformers whose loading the unit `added` to each (with its overload
|
|
302
|
+
before it) did not lower, among those overloaded now (`critical`).
|
|
303
|
+
|
|
304
|
+
One more unit in parallel shares the current of a transformer between more
|
|
305
|
+
units: the loading of `n` units falls by about ``1 / (n + 1)`` of itself, the
|
|
306
|
+
current changing only by the small rise of the voltage that the lower
|
|
307
|
+
impedance brings. It falls by less where the network drives a current through
|
|
308
|
+
the transformer that grows as its impedance falls, as a flow between two
|
|
309
|
+
sources that it joins: in one such loop, 59.1 % to 46.4 % from one unit to
|
|
310
|
+
two, rather than about half. A loading that does not fall at all has one of two causes, which
|
|
311
|
+
the strategy cannot tell apart: the power flow has not reached the operating
|
|
312
|
+
solution, as after a warm start onto a spurious solution (#56), or the
|
|
313
|
+
transformer carries a flow between two sources stiff enough to drive it
|
|
314
|
+
whatever its units. Either way, more units of the same kind would be sized on
|
|
315
|
+
a loading they do not lower, as many as the strategy may take: the transformer
|
|
316
|
+
gets no more, with a warning. The comparison needs no margin. The unit is
|
|
317
|
+
kept, as the action took it.
|
|
318
|
+
"""
|
|
319
|
+
stalled = set()
|
|
320
|
+
for transformer_id, overload_factor, _ in critical:
|
|
321
|
+
if transformer_id in added and overload_factor >= added[transformer_id]:
|
|
322
|
+
stalled.add(transformer_id)
|
|
323
|
+
message = (
|
|
324
|
+
f"Transformer '{transformer_id}': the unit added in parallel did "
|
|
325
|
+
f"not lower its loading ({(1.0 + added[transformer_id]) * 100:.2f} "
|
|
326
|
+
f"% of the limit before, {(1.0 + overload_factor) * 100:.2f} % "
|
|
327
|
+
"after). Either the power flow has not reached the operating "
|
|
328
|
+
"solution, or the network drives a current through the "
|
|
329
|
+
"transformer that grows with its units, as a flow between two "
|
|
330
|
+
"sources it joins. No more units are added to it."
|
|
331
|
+
)
|
|
332
|
+
_logger.warning(message)
|
|
333
|
+
self.logs.append(message)
|
|
334
|
+
return stalled
|
|
335
|
+
|
|
336
|
+
def calculate_cost(self, action: dict[str, Any], cost_model: CostModel) -> float:
|
|
337
|
+
"""
|
|
338
|
+
Calculate the cost of the transformer upgrade actions.
|
|
339
|
+
|
|
340
|
+
A transformer is charged once, for the units laid, however many steps took it
|
|
341
|
+
there: a unit taken from one type to the next and then to a third is charged
|
|
342
|
+
for a unit of the third only, not for the type in between, which is never
|
|
343
|
+
laid, and a unit added in parallel and then replaced, with the others, by a
|
|
344
|
+
unit of another type is charged at that type only. What a transformer costs,
|
|
345
|
+
from the state it had at first to the state it is left in, is the
|
|
346
|
+
`transformer_upgrade` price of its final type for every unit it has then, if
|
|
347
|
+
the type has changed, as they are all replaced, and for every unit added
|
|
348
|
+
otherwise. A transformer that has no type is priced under the key None.
|
|
349
|
+
|
|
350
|
+
The state at first is that of the transformer when the run started, which
|
|
351
|
+
`GridEnhancementAlgorithm` records in the upgrades (`origin_type`,
|
|
352
|
+
`origin_units`). The action is then charged the difference between what the
|
|
353
|
+
transformer costs after it and what it cost before it, so that a transformer
|
|
354
|
+
upgraded by several actions of a run is charged in all for what the run lays
|
|
355
|
+
(see `sizing.charge`). Without that record, the state at first is the one
|
|
356
|
+
before the action.
|
|
357
|
+
|
|
358
|
+
Args:
|
|
359
|
+
action (Dict[str, Any]): The action dictionary.
|
|
360
|
+
cost_model (CostModel): The cost model.
|
|
361
|
+
|
|
362
|
+
Returns:
|
|
363
|
+
float: The total cost of the upgrades.
|
|
364
|
+
"""
|
|
365
|
+
first_step: dict[str, dict[str, Any]] = {}
|
|
366
|
+
last_step: dict[str, dict[str, Any]] = {}
|
|
367
|
+
for transformer_upgrade in action.get("transformers", []):
|
|
368
|
+
transformer_id = transformer_upgrade.get("transformer_id", "")
|
|
369
|
+
first_step.setdefault(transformer_id, transformer_upgrade)
|
|
370
|
+
last_step[transformer_id] = transformer_upgrade
|
|
371
|
+
|
|
372
|
+
total_cost = 0.0
|
|
373
|
+
for transformer_id, first in first_step.items():
|
|
374
|
+
last = last_step[transformer_id]
|
|
375
|
+
before = (
|
|
376
|
+
self._type_in_place(first.get("old_type")),
|
|
377
|
+
self._units(first, before=True),
|
|
378
|
+
)
|
|
379
|
+
# A unit added in parallel is of the type in place
|
|
380
|
+
after = (
|
|
381
|
+
self._type_in_place(last.get("new_type") or last.get("old_type")),
|
|
382
|
+
max(self._units(last), before[1]),
|
|
383
|
+
)
|
|
384
|
+
origin = (
|
|
385
|
+
self._type_in_place(first.get("origin_type", before[0])),
|
|
386
|
+
max(1, int(first.get("origin_units") or before[1])),
|
|
387
|
+
)
|
|
388
|
+
total_cost += self._charge(
|
|
389
|
+
cost_model, transformer_id, origin, before, after
|
|
390
|
+
)
|
|
391
|
+
return float(total_cost)
|
|
392
|
+
|
|
393
|
+
@staticmethod
|
|
394
|
+
def _units(transformer_upgrade: dict[str, Any], before: bool = False) -> int:
|
|
395
|
+
"""Number of units of a transformer after one of its upgrades, or before it."""
|
|
396
|
+
parallel_count = int(transformer_upgrade.get("parallel_count") or 0)
|
|
397
|
+
if parallel_count > 0:
|
|
398
|
+
# The upgrade added one unit
|
|
399
|
+
return parallel_count - 1 if before else parallel_count
|
|
400
|
+
# A type change keeps the number of units
|
|
401
|
+
return max(1, int(transformer_upgrade.get("units") or 1))
|
|
402
|
+
|
|
403
|
+
@staticmethod
|
|
404
|
+
def _charge(
|
|
405
|
+
cost_model: CostModel,
|
|
406
|
+
transformer_id: str,
|
|
407
|
+
origin: tuple[Any, int],
|
|
408
|
+
before: tuple[Any, int],
|
|
409
|
+
after: tuple[Any, int],
|
|
410
|
+
) -> float:
|
|
411
|
+
"""
|
|
412
|
+
What an action that takes a transformer from `before` to `after` (type,
|
|
413
|
+
units) is charged: what the units laid on it from its state at first,
|
|
414
|
+
`origin`, cost after the action, less what they cost before it.
|
|
415
|
+
"""
|
|
416
|
+
|
|
417
|
+
def works_cost(first: tuple[Any, int], state: tuple[Any, int]) -> float:
|
|
418
|
+
laid = units_laid(first, state)
|
|
419
|
+
if not laid:
|
|
420
|
+
return 0.0
|
|
421
|
+
return laid * cost_model.calculate_transformer_upgrade_cost(
|
|
422
|
+
transformer_id, state[0]
|
|
423
|
+
)
|
|
424
|
+
|
|
425
|
+
return charge(works_cost, origin, before, after)
|
|
426
|
+
|
|
427
|
+
def required_unit_costs(self, pf_engine: PowerFlowEngine) -> set[tuple[str, ...]]:
|
|
428
|
+
"""
|
|
429
|
+
List the upgrade price of every configured transformer type.
|
|
430
|
+
|
|
431
|
+
Args:
|
|
432
|
+
pf_engine (PowerFlowEngine): The power flow engine.
|
|
433
|
+
|
|
434
|
+
Returns:
|
|
435
|
+
Set[Tuple[str, ...]]: The keys of the prices in `CostModel.unit_costs`.
|
|
436
|
+
"""
|
|
437
|
+
return {
|
|
438
|
+
("transformer_upgrade", transformer_type)
|
|
439
|
+
for transformer_type in self.transformer_types
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
def possible_unit_costs(self, pf_engine: PowerFlowEngine) -> set[tuple[str, ...]]:
|
|
443
|
+
"""
|
|
444
|
+
List the upgrade price of every transformer type in place on the network.
|
|
445
|
+
|
|
446
|
+
A transformer can be given a unit in parallel of the type it has, whether or
|
|
447
|
+
not that type is one of the configured ones: when no configured type is larger,
|
|
448
|
+
or when its rating is enough for the power it carries. The unit is charged at
|
|
449
|
+
the price of that type, and that of a transformer that has no type (a `std_type`
|
|
450
|
+
of None, NaN or '', like a unit created from its parameters) at the price under
|
|
451
|
+
the key None. Whether a run adds one is not known before it: the run starts
|
|
452
|
+
without these prices, and stops if it needs a missing one.
|
|
453
|
+
|
|
454
|
+
Args:
|
|
455
|
+
pf_engine (PowerFlowEngine): The power flow engine.
|
|
456
|
+
|
|
457
|
+
Returns:
|
|
458
|
+
Set[Tuple[str, ...]]: The keys of the prices in `CostModel.unit_costs`.
|
|
459
|
+
"""
|
|
460
|
+
in_place = getattr(pf_engine, "get_transformer_types_in_place", set)()
|
|
461
|
+
return {
|
|
462
|
+
("transformer_upgrade", self._type_in_place(transformer_type))
|
|
463
|
+
for transformer_type in in_place
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
@staticmethod
|
|
467
|
+
def _type_in_place(transformer_type: Any) -> str | None:
|
|
468
|
+
"""
|
|
469
|
+
The type of a transformer as the network gives it, None for a unit that has no
|
|
470
|
+
type: a `std_type` of None, NaN or '' (pandapower writes NaN or '' for a unit
|
|
471
|
+
created from its parameters, depending on the units already in the table).
|
|
472
|
+
|
|
473
|
+
A name absent from the standard types is kept: a unit added in parallel is
|
|
474
|
+
charged at its price.
|
|
475
|
+
"""
|
|
476
|
+
return type_in_place(transformer_type)
|
|
477
|
+
|
|
478
|
+
@staticmethod
|
|
479
|
+
def _unit_rating(pf_engine: PowerFlowEngine, transformer_id: str) -> float | None:
|
|
480
|
+
"""
|
|
481
|
+
The rating (VA) of one unit of a transformer, as the network table holds it.
|
|
482
|
+
|
|
483
|
+
Returns None if the engine does not give it.
|
|
484
|
+
"""
|
|
485
|
+
get_rating = getattr(pf_engine, "get_transformer_rating", None)
|
|
486
|
+
if get_rating is None:
|
|
487
|
+
return None
|
|
488
|
+
return get_rating(transformer_id)
|
|
489
|
+
|
|
490
|
+
def _upgrade_options(
|
|
491
|
+
self,
|
|
492
|
+
current_type: str | None,
|
|
493
|
+
units: int,
|
|
494
|
+
loading_ratio: float,
|
|
495
|
+
power_needed: float,
|
|
496
|
+
unit_rating: float | None,
|
|
497
|
+
pf_engine: PowerFlowEngine,
|
|
498
|
+
fewest: dict[str, int] | None = None,
|
|
499
|
+
) -> list[SizingOption]:
|
|
500
|
+
"""
|
|
501
|
+
The ways to make an overloaded transformer carry what it carries, within the
|
|
502
|
+
loading limit.
|
|
503
|
+
|
|
504
|
+
The transformer needs `loading_ratio` (the loading the engine reports over the
|
|
505
|
+
limit) times the rating of its units in place, the rating the engine computes
|
|
506
|
+
its loading with: that of the transformer table. A type change keeps the
|
|
507
|
+
derating factor and gives the units the rating of the new type, so this holds
|
|
508
|
+
for any type, while the apparent power it carries can be within the rating of
|
|
509
|
+
a unit overloaded in current at a low voltage.
|
|
510
|
+
|
|
511
|
+
Args:
|
|
512
|
+
current_type (Optional[str]): The type in place, None for a unit that has
|
|
513
|
+
none.
|
|
514
|
+
units (int): The units in place.
|
|
515
|
+
loading_ratio (float): The loading the engine reports, over the limit.
|
|
516
|
+
power_needed (float): The apparent power it carries over the limit (VA),
|
|
517
|
+
what the units need when the rating of the unit in place is not known.
|
|
518
|
+
unit_rating (Optional[float]): The rating (VA) of a unit in place, as the
|
|
519
|
+
transformer table holds it, None if the engine does not give it.
|
|
520
|
+
pf_engine (PowerFlowEngine): The power flow engine.
|
|
521
|
+
fewest (dict, optional): The fewest units of a type that the transformer
|
|
522
|
+
may take, for a type that fewer units of did not carry it after the
|
|
523
|
+
change (see `StepCheck`).
|
|
524
|
+
|
|
525
|
+
Returns:
|
|
526
|
+
List[SizingOption]: The configured types rated above the unit in place
|
|
527
|
+
(by the table and by its type, so that a unit is never replaced by a
|
|
528
|
+
smaller one), smallest first, each with as many units as carry the
|
|
529
|
+
transformer, at least those in place and those of `fewest`; then the
|
|
530
|
+
units in place with as many more of their kind as carry it. A type
|
|
531
|
+
change only if the rating of the unit in place is known.
|
|
532
|
+
"""
|
|
533
|
+
catalogue_rating = None
|
|
534
|
+
if current_type is not None:
|
|
535
|
+
try:
|
|
536
|
+
catalogue_rating = pf_engine.get_transformer_max_power(current_type)
|
|
537
|
+
except ValueError:
|
|
538
|
+
pass
|
|
539
|
+
rating = unit_rating if unit_rating is not None else catalogue_rating
|
|
540
|
+
if rating is not None:
|
|
541
|
+
required = loading_ratio * units * rating
|
|
542
|
+
floor = max(rating, catalogue_rating or 0.0)
|
|
543
|
+
else:
|
|
544
|
+
# A unit without a catalogued type, on an engine that does not give its
|
|
545
|
+
# rating: sized on its power, with any configured type to change to
|
|
546
|
+
required, floor = power_needed, 0.0
|
|
547
|
+
|
|
548
|
+
available = sorted(
|
|
549
|
+
(pf_engine.get_transformer_max_power(transformer_type), transformer_type)
|
|
550
|
+
for transformer_type in self.transformer_types
|
|
551
|
+
)
|
|
552
|
+
fewest = fewest or {}
|
|
553
|
+
options = [
|
|
554
|
+
type_change_option(
|
|
555
|
+
transformer_type,
|
|
556
|
+
type_rating,
|
|
557
|
+
max(units, fewest.get(transformer_type, 0)),
|
|
558
|
+
required,
|
|
559
|
+
)
|
|
560
|
+
for type_rating, transformer_type in available
|
|
561
|
+
if type_rating > floor
|
|
562
|
+
]
|
|
563
|
+
options.append(keep_type_option(current_type, units, rating, required))
|
|
564
|
+
return options
|
|
565
|
+
|
|
566
|
+
def _choose_upgrade(
|
|
567
|
+
self,
|
|
568
|
+
transformer_id: str,
|
|
569
|
+
current_type: str | None,
|
|
570
|
+
units: int,
|
|
571
|
+
loading_ratio: float,
|
|
572
|
+
power_needed: float,
|
|
573
|
+
pf_engine: PowerFlowEngine,
|
|
574
|
+
before: tuple[str | None, int] | None = None,
|
|
575
|
+
fewest: dict[str, int] | None = None,
|
|
576
|
+
) -> SizingOption:
|
|
577
|
+
"""
|
|
578
|
+
Choose how to reinforce an overloaded transformer, among `_upgrade_options`.
|
|
579
|
+
|
|
580
|
+
With the prices of the run (`cost_model`), the cheapest option, priced as
|
|
581
|
+
`calculate_cost` charges the action that takes the transformer from its state
|
|
582
|
+
`before` the action to the option: what the transformer costs after it, from
|
|
583
|
+
its state at the start of the run (`transformer_origins`), less what it cost
|
|
584
|
+
before it. A transformer that no earlier action of the run has changed, or a
|
|
585
|
+
strategy used without `transformer_origins`, is priced from its state before
|
|
586
|
+
the action: a unit of the final type for every unit of the transformer if the
|
|
587
|
+
type changes, one of the type in place for every unit added otherwise, the
|
|
588
|
+
steps already taken by the action being charged nothing of their own.
|
|
589
|
+
Without, the smallest type that carries it with the units it had `before` the
|
|
590
|
+
action (type, units; those in place if not given), and when none does, the
|
|
591
|
+
option that lays the fewest units since then, then the least rating (see
|
|
592
|
+
`choose_option`). A type is offered with at least the units of `fewest`.
|
|
593
|
+
"""
|
|
594
|
+
options = self._upgrade_options(
|
|
595
|
+
current_type,
|
|
596
|
+
units,
|
|
597
|
+
loading_ratio,
|
|
598
|
+
power_needed,
|
|
599
|
+
self._unit_rating(pf_engine, transformer_id),
|
|
600
|
+
pf_engine,
|
|
601
|
+
fewest,
|
|
602
|
+
)
|
|
603
|
+
if before is None:
|
|
604
|
+
before = (current_type, units)
|
|
605
|
+
cost_model = getattr(self, "cost_model", None)
|
|
606
|
+
price = None
|
|
607
|
+
if cost_model is not None:
|
|
608
|
+
origins = getattr(self, "transformer_origins", None)
|
|
609
|
+
origin = origins.get(transformer_id, before) if origins else before
|
|
610
|
+
origin = (self._type_in_place(origin[0]), origin[1])
|
|
611
|
+
|
|
612
|
+
def price(option: SizingOption) -> float:
|
|
613
|
+
with unlogged(cost_model):
|
|
614
|
+
return self._charge(
|
|
615
|
+
cost_model,
|
|
616
|
+
transformer_id,
|
|
617
|
+
origin,
|
|
618
|
+
before,
|
|
619
|
+
(option.element_type, option.units),
|
|
620
|
+
)
|
|
621
|
+
|
|
622
|
+
return choose_option(options, before, price)
|
|
File without changes
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Configuration utilities for the reinforcement framework.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import yaml
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def load_config(config_path: str) -> dict[str, Any]:
|
|
13
|
+
"""
|
|
14
|
+
Load configuration from YAML or JSON file.
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
config_path: Path to configuration file
|
|
18
|
+
|
|
19
|
+
Returns:
|
|
20
|
+
Configuration dictionary
|
|
21
|
+
"""
|
|
22
|
+
if not os.path.exists(config_path):
|
|
23
|
+
raise FileNotFoundError(f"Configuration file not found: {config_path}")
|
|
24
|
+
|
|
25
|
+
if config_path.endswith((".yaml", ".yml")):
|
|
26
|
+
with open(config_path) as file:
|
|
27
|
+
return yaml.safe_load(file)
|
|
28
|
+
elif config_path.endswith(".json"):
|
|
29
|
+
with open(config_path) as file:
|
|
30
|
+
return json.load(file)
|
|
31
|
+
else:
|
|
32
|
+
raise ValueError(f"Unsupported configuration format: {config_path}")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def save_config(config: dict[str, Any], config_path: str) -> None:
|
|
36
|
+
"""
|
|
37
|
+
Save configuration to YAML or JSON file.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
config: Configuration dictionary
|
|
41
|
+
config_path: Path to save configuration
|
|
42
|
+
"""
|
|
43
|
+
# Create directory if it doesn't exist
|
|
44
|
+
config_dir = os.path.dirname(config_path)
|
|
45
|
+
if config_dir and not os.path.exists(config_dir):
|
|
46
|
+
os.makedirs(config_dir)
|
|
47
|
+
|
|
48
|
+
if config_path.endswith((".yaml", ".yml")):
|
|
49
|
+
with open(config_path, "w") as file:
|
|
50
|
+
yaml.dump(config, file, default_flow_style=False)
|
|
51
|
+
elif config_path.endswith(".json"):
|
|
52
|
+
with open(config_path, "w") as file:
|
|
53
|
+
json.dump(config, file, indent=2)
|
|
54
|
+
else:
|
|
55
|
+
raise ValueError(f"Unsupported configuration format: {config_path}")
|