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,297 @@
1
+ """
2
+ Enhancement strategies for grid constraint management.
3
+ """
4
+
5
+ from abc import ABC, abstractmethod
6
+ from collections.abc import Iterable, Mapping
7
+ from typing import Any
8
+
9
+ from gridforge.core.constraints import ConstraintType, ConstraintViolation
10
+ from gridforge.core.cost_model import CostModel
11
+ from gridforge.core.power_flow import PowerFlowEngine
12
+ from gridforge.utils.logging import _format_grid_state
13
+ from gridforge.utils.logging import logger as _logger
14
+
15
+
16
+ def note_origins(
17
+ upgrades: Iterable[Any] | None,
18
+ origins: Mapping[str, tuple[Any, int]] | None,
19
+ element_id: str,
20
+ origin_count: str,
21
+ ) -> None:
22
+ """
23
+ Give each upgrade of an action the state of its element at the start of the run,
24
+ from `origins` (name -> type, number of elements in parallel), as `origin_type` and
25
+ `origin_count`, unless it has one: the state the upgrade is charged from (see
26
+ `LineUpgradeStrategy.calculate_cost` and `TransformerUpgradeStrategy.calculate_cost`).
27
+ `element_id` is the key of the name of the element in an upgrade.
28
+ """
29
+ if not origins:
30
+ return
31
+ for upgrade in upgrades or []:
32
+ if not isinstance(upgrade, dict):
33
+ continue
34
+ origin = origins.get(upgrade.get(element_id))
35
+ if origin is not None:
36
+ upgrade.setdefault("origin_type", origin[0])
37
+ upgrade.setdefault(origin_count, origin[1])
38
+
39
+
40
+ class EnhancementStrategy(ABC):
41
+ """
42
+ Abstract base class for all grid enhancement strategies.
43
+
44
+ This class defines the interface that all specific enhancement strategies (e.g., tap changing,
45
+ line upgrades) must implement. It ensures a consistent way to apply strategies, calculate costs,
46
+ and integrate with the main enhancement algorithm.
47
+
48
+ Attributes:
49
+ logs (List[str]): Log messages generated while applying the strategy. Reset by
50
+ subclasses at the start of each `apply_to_group` call.
51
+ cost_model (Optional[CostModel]): The prices a strategy may choose between its
52
+ own options with, such as a larger type or a unit in parallel.
53
+ `GridEnhancementAlgorithm` sets it to its own cost model for the time of
54
+ each run, None in a run without one, and gives the strategy back its own
55
+ value when the run ends, however it ends. None otherwise: a strategy used
56
+ on its own chooses without prices unless it is given one.
57
+ line_origins (Optional[Mapping[str, Tuple[Any, int]]]): The type and number
58
+ of conductors of each line as the run started, from which the
59
+ run charges a line upgrade (see `LineUpgradeStrategy.calculate_cost`).
60
+ The algorithm lends a copy, complete from the start of the run and not
61
+ added to during it, which can be copied and pickled with the strategy.
62
+ `GridEnhancementAlgorithm` sets it for the time of each run with a cost
63
+ model, as it does `cost_model`, for a strategy to price its options as the
64
+ run will charge them. None otherwise: a line is then priced from its state
65
+ before the action.
66
+ transformer_origins (Optional[Mapping[str, Tuple[Any, int]]]): The type and
67
+ number of units of each transformer as the run started, by name, from
68
+ which the run charges a transformer upgrade (see
69
+ `TransformerUpgradeStrategy.calculate_cost`). Lent as `line_origins` is,
70
+ for the time of each run with a cost model. None otherwise: a transformer
71
+ is then priced from its state before the action.
72
+ initial_power (Optional[Mapping[Tuple[str, Any], float]]): The active power
73
+ (MW) of each load and static generator as the run started, by type
74
+ ("load", "sgen") and index in the table of the engine, as
75
+ `get_flexibility_data` gives it, from which the limits of flexibility
76
+ count (see `FlexibilityStrategy`). `GridEnhancementAlgorithm` lends a
77
+ copy for the time of each run, as it does `cost_model`, so that the
78
+ limits hold across every call of the run, whatever the calls before it
79
+ took off, and are those of the network the run is on. None otherwise: a
80
+ strategy used on its own counts from the powers at each call, so that a
81
+ caller calling it several times on one network must set the powers here
82
+ for its limits to hold across the calls (see `FlexibilityStrategy`).
83
+ """
84
+
85
+ def __init__(self) -> None:
86
+ self.logs: list[str] = []
87
+ self.cost_model: CostModel | None = None
88
+ self.line_origins: Mapping[str, tuple[Any, int]] | None = None
89
+ self.transformer_origins: Mapping[str, tuple[Any, int]] | None = None
90
+ self.initial_power: Mapping[tuple[str, Any], float] | None = None
91
+
92
+ @property
93
+ @abstractmethod
94
+ def name(self) -> str:
95
+ """
96
+ Get the name of the strategy.
97
+
98
+ Returns:
99
+ str: The name of the strategy.
100
+ """
101
+ pass
102
+
103
+ @property
104
+ @abstractmethod
105
+ def stage(self) -> str:
106
+ """
107
+ Get the stage of the strategy (e.g., 'operation', 'planning').
108
+
109
+ Returns:
110
+ str: The stage of the strategy.
111
+ """
112
+ pass
113
+
114
+ @property
115
+ @abstractmethod
116
+ def cost_level(self) -> int:
117
+ """
118
+ Get the relative cost level of this strategy.
119
+
120
+ Lower values indicate less expensive strategies that should be tried first.
121
+
122
+ Returns:
123
+ int: The cost level.
124
+ """
125
+ pass
126
+
127
+ @abstractmethod
128
+ def applicable_constraints(self) -> set[str]:
129
+ """
130
+ Get the set of constraint types this strategy can address.
131
+
132
+ Returns:
133
+ Set[str]: A set of ConstraintType values (as strings or enums) that this strategy can resolve.
134
+ """
135
+ pass
136
+
137
+ @abstractmethod
138
+ def apply_to_group(
139
+ self, violations: list[ConstraintViolation], pf_engine: PowerFlowEngine
140
+ ) -> dict[str, Any] | None:
141
+ """
142
+ Apply the strategy to address a group of violations of the same type.
143
+
144
+ Args:
145
+ violations (List[ConstraintViolation]): The constraint violations to address.
146
+ pf_engine (PowerFlowEngine): The power flow engine to use for network analysis and modification.
147
+
148
+ Returns:
149
+ Optional[Dict[str, Any]]: A dictionary describing the action taken if successful, or None if no action could be applied.
150
+ """
151
+ pass
152
+
153
+ @abstractmethod
154
+ def calculate_cost(self, action: dict[str, Any], cost_model: CostModel) -> float:
155
+ """
156
+ Calculate the cost of the applied action.
157
+
158
+ Args:
159
+ action (Dict[str, Any]): The action dictionary returned by `apply_to_group`.
160
+ cost_model (CostModel): The cost model to use for calculation.
161
+
162
+ Returns:
163
+ float: The calculated cost of the action.
164
+ """
165
+ pass
166
+
167
+ def required_unit_costs(self, pf_engine: PowerFlowEngine) -> set[tuple[str, ...]]:
168
+ """
169
+ List the prices this strategy needs on this network, to check them before a run.
170
+
171
+ These are the prices the strategy needs whatever the run does: a run does not
172
+ start without them. The prices it may need, depending on what the run turns
173
+ out to do, are listed by `possible_unit_costs`.
174
+
175
+ Args:
176
+ pf_engine (PowerFlowEngine): The power flow engine.
177
+
178
+ Returns:
179
+ Set[Tuple[str, ...]]: Keys of `CostModel.unit_costs`, like `("tap_change",)` or
180
+ `("line_upgrade", "NAYY 4x120 SE")`.
181
+ """
182
+ return set()
183
+
184
+ def possible_unit_costs(self, pf_engine: PowerFlowEngine) -> set[tuple[str, ...]]:
185
+ """
186
+ List the prices this strategy may need on this network, depending on what the
187
+ run turns out to do, like that of a conductor added in parallel to a line of a
188
+ type outside the configured ones.
189
+
190
+ A run starts without them, with a warning: it stops with `MissingUnitCostError`
191
+ if an action needs one, the network being left as it was before that action.
192
+
193
+ Args:
194
+ pf_engine (PowerFlowEngine): The power flow engine.
195
+
196
+ Returns:
197
+ Set[Tuple[str, ...]]: Keys of `CostModel.unit_costs`, as for
198
+ `required_unit_costs`.
199
+ """
200
+ return set()
201
+
202
+ @staticmethod
203
+ def _format_grid_state(violations: list[ConstraintViolation]) -> str:
204
+ """
205
+ Format the current grid state (violations) into a readable string.
206
+
207
+ Args:
208
+ violations (List[ConstraintViolation]): List of current violations.
209
+
210
+ Returns:
211
+ str: Formatted string describing the violations.
212
+ """
213
+ return _format_grid_state(violations)
214
+
215
+ @staticmethod
216
+ def _identify_critical_elements(
217
+ violations: list[ConstraintViolation],
218
+ ) -> list[tuple[str, float, float]]:
219
+ """
220
+ Rank violated elements (lines, transformers, ...) by how overloaded they are.
221
+
222
+ Args:
223
+ violations (List[ConstraintViolation]): Loading violations to rank.
224
+
225
+ Returns:
226
+ List[Tuple[str, float, float]]: Tuples of (element_id, overload_factor,
227
+ absolute_value), sorted by overload factor (most overloaded first).
228
+ """
229
+ critical_elements = []
230
+ for violation in violations:
231
+ element_id = violation.element_id
232
+ if not element_id:
233
+ continue
234
+
235
+ overload_factor = violation.violation_value / violation.violated_value
236
+ critical_elements.append(
237
+ (element_id, overload_factor, violation.absolute_value)
238
+ )
239
+
240
+ return sorted(critical_elements, key=lambda x: x[1], reverse=True)
241
+
242
+ @staticmethod
243
+ def _rerun_and_filter_violations(
244
+ pf_engine: PowerFlowEngine,
245
+ constraint_types: ConstraintType | tuple[ConstraintType, ...],
246
+ ) -> list[ConstraintViolation]:
247
+ """
248
+ Re-run power flow and return the remaining violations of the given type(s).
249
+
250
+ Args:
251
+ pf_engine (PowerFlowEngine): The power flow engine.
252
+ constraint_types (Union[ConstraintType, Tuple[ConstraintType, ...]]):
253
+ Constraint type(s) to keep.
254
+
255
+ Returns:
256
+ List[ConstraintViolation]: Remaining violations matching `constraint_types`.
257
+ """
258
+ pf_engine.run_power_flow(warm_start=True)
259
+ results = pf_engine.check_violations()
260
+ if isinstance(constraint_types, ConstraintType):
261
+ constraint_types = (constraint_types,)
262
+ return [v for v in results if v.constraint_type in constraint_types]
263
+
264
+ def _log_iteration(
265
+ self,
266
+ iteration: int,
267
+ grid_state: str,
268
+ target: str,
269
+ justification: str,
270
+ action: str,
271
+ extra_msg: str = "",
272
+ ) -> None:
273
+ """
274
+ Record and log one iteration of a strategy's decision-making process.
275
+
276
+ Appends a formatted entry to `self.logs` and emits it at INFO level.
277
+
278
+ Args:
279
+ iteration (int): Iteration or action count.
280
+ grid_state (str): Human-readable summary of the current grid state.
281
+ target (str): The element/violation targeted by this iteration.
282
+ justification (str): Explanation of why the action was chosen.
283
+ action (str): Description of the action executed.
284
+ extra_msg (str, optional): Additional note to append. Defaults to "".
285
+ """
286
+ log_entry = f"""
287
+ Iteration [{iteration}] Log:
288
+ Grid State: {grid_state}
289
+ Target Selected: {target}
290
+ Action Executed: {action}
291
+ Mathematical Justification: {justification}
292
+ """
293
+ if extra_msg:
294
+ log_entry += f" Note: {extra_msg}\n"
295
+
296
+ self.logs.append(log_entry)
297
+ _logger.info(log_entry)
File without changes