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,1146 @@
1
+ """
2
+ Core interfaces for power flow engines.
3
+ """
4
+
5
+ from abc import ABC, abstractmethod
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ from gridforge.core.constraints import ConstraintViolation, NetworkConstraints
13
+ from gridforge.utils.logging import logger
14
+
15
+
16
+ def type_in_place(element_type: Any) -> str | None:
17
+ """
18
+ The type of a line or a transformer as the network gives it, None for one that has
19
+ no type: a `std_type` of None, NaN or '' (pandapower writes NaN or '' for an
20
+ element created from its parameters, depending on the elements already in the
21
+ table). The price of a conductor or a unit added to such an element is that under
22
+ the key None of `CostModel.unit_costs`.
23
+
24
+ A name absent from the standard types is kept: an element added in parallel is
25
+ charged at its price.
26
+ """
27
+ if isinstance(element_type, str) and element_type:
28
+ return element_type
29
+ return None
30
+
31
+
32
+ class PowerFlowNotConverged(RuntimeError):
33
+ """
34
+ Raised by `PowerFlowEngine.run_power_flow` when the solver does not converge.
35
+
36
+ Engines translate their own non-convergence error into this exception, so that
37
+ callers such as `GridEnhancementAlgorithm` can handle a diverging power flow
38
+ without depending on a specific engine library.
39
+ """
40
+
41
+
42
+ class PowerFlowEngine(ABC):
43
+ """
44
+ Abstract base class for power flow engines.
45
+
46
+ This class defines the standard interface that any power flow engine (e.g., PandaPower, OpenDSS)
47
+ must implement to be compatible with the GridForge framework. It handles network creation,
48
+ modification, simulation, and results retrieval.
49
+
50
+ Attributes:
51
+ network (Any): The underlying network model object (engine-specific).
52
+ pf_settings (Dict[str, Any]): Configuration settings for power flow calculations.
53
+ network_partition (Optional[Dict[int, Any]]): Cached network partition data.
54
+ latest_results (Optional[Dict[str, Any]]): Results from the most recent power flow run.
55
+ config (Dict[str, Any]): General configuration dictionary.
56
+ logger (logging.Logger): Logger instance.
57
+ flexibility_settings (Dict[str, Dict[str, float]]): Settings for flexible assets (loads/sgens).
58
+ constraints (NetworkConstraints): Object managing network operational limits.
59
+ """
60
+
61
+ def __init__(self, config: dict[str, Any] | None = None):
62
+ """
63
+ Initialize the power flow engine.
64
+
65
+ Args:
66
+ config (Optional[Dict[str, Any]], optional): Configuration dictionary. Defaults to None.
67
+ """
68
+ self.network = None
69
+ self.pf_settings = {"generic": {}, "specific": {}}
70
+ self.network_partition = None
71
+ self.latest_results: dict[str, Any] | None = None
72
+ self.config = config if config is not None else {}
73
+ self.logger = logger
74
+ self.logger.info("Initialized PowerFlow engine")
75
+ self.set_config(config)
76
+ self.flexibility_settings = {"load": {}, "sgen": {}}
77
+
78
+ def _initialize_constraints(self):
79
+ """
80
+ Create and initialize NetworkConstraints based on default config values.
81
+ """
82
+ self.constraints = NetworkConstraints(
83
+ mv_max_voltage=self.config.get("mv_max_voltage", 1.05),
84
+ mv_min_voltage=self.config.get("mv_min_voltage", 0.95),
85
+ lv_max_voltage=self.config.get("lv_max_voltage", 1.1),
86
+ lv_min_voltage=self.config.get("lv_min_voltage", 0.9),
87
+ max_line_loading=self.config.get("max_line_loading", 100),
88
+ max_transformer_loading=self.config.get("max_transformer_loading", 120),
89
+ )
90
+
91
+ def set_config(self, new_config: dict[str, Any]) -> None:
92
+ """
93
+ Set a new configuration dictionary and update dependent attributes.
94
+
95
+ Args:
96
+ new_config (Dict[str, Any]): New configuration dictionary.
97
+ """
98
+ self.config = new_config if new_config is not None else self.config
99
+ self._initialize_constraints()
100
+ self._set_power_flow_params()
101
+ self.logger.info("Configuration updated successfully")
102
+
103
+ def get_config(self) -> dict[str, Any]:
104
+ """
105
+ Get the current configuration dictionary.
106
+
107
+ Returns:
108
+ Dict[str, Any]: Current configuration dictionary.
109
+ """
110
+ return self.config
111
+
112
+ def update_config(self, updates: dict[str, Any]) -> None:
113
+ """
114
+ Partially update the configuration dictionary and dependent attributes.
115
+
116
+ Args:
117
+ updates (Dict[str, Any]): Key-value pairs to update in the configuration.
118
+ """
119
+ self.config.update(updates)
120
+ self._initialize_constraints()
121
+ self._set_power_flow_params()
122
+ self.logger.info("Configuration partially updated successfully")
123
+
124
+ def _set_power_flow_params(self):
125
+ """
126
+ Sets the internal power flow parameters for the system configuration.
127
+
128
+ This is an internal utility function.
129
+ """
130
+
131
+ # "tolerance" is in the unit of the engine that reads it: pandapower compares
132
+ # it in per unit of the base power of the network (sn_mva), not in MVA
133
+ default_generic_params = {"max_iterations": 50, "tolerance": 1.0e-8}
134
+
135
+ self.pf_settings["generic"] = self.config.get(
136
+ "power_flow_generic_settings", default_generic_params
137
+ )
138
+ self.pf_settings["specific"] = self.config.get(
139
+ "power_flow_specific_settings", {}
140
+ )
141
+
142
+ @abstractmethod
143
+ def load_network(self, source: str | dict) -> None:
144
+ """
145
+ Load a network from file or dictionary.
146
+
147
+ Args:
148
+ source (Union[str, Dict]): Path to network file (.json, .p) or network dictionary.
149
+ """
150
+ pass
151
+
152
+ @abstractmethod
153
+ def save_network(self, target: str) -> None:
154
+ """
155
+ Save the current network to a file.
156
+
157
+ Args:
158
+ target (str): Path where to save the network (.json, .p).
159
+ """
160
+ pass
161
+
162
+ @abstractmethod
163
+ def create_empty_network(
164
+ self, name: str | None = None, f_hz: float | None = 50.0
165
+ ) -> None:
166
+ """
167
+ Create an empty network with a given name and frequency.
168
+
169
+ Args:
170
+ name (Optional[str], optional): Name of the network. Defaults to None.
171
+ f_hz (Optional[float], optional): System frequency in Hz. Defaults to 50.0.
172
+ """
173
+ pass
174
+
175
+ @abstractmethod
176
+ def create_bus(self, name: str, nominal_voltage_v: float, **kwargs: Any) -> int:
177
+ """
178
+ Create a new bus in the network.
179
+
180
+ Args:
181
+ name (str): Name of the bus.
182
+ nominal_voltage_v (float): Nominal voltage of the bus in V.
183
+ **kwargs: Additional parameters for the bus.
184
+
185
+ Returns:
186
+ int: Index of the created bus.
187
+ """
188
+ pass
189
+
190
+ @abstractmethod
191
+ def create_load(
192
+ self,
193
+ bus_name: int,
194
+ name: str,
195
+ active_power_w: float,
196
+ reactive_power_var: float,
197
+ **kwargs: Any,
198
+ ) -> int:
199
+ """
200
+ Create a new load in the network.
201
+
202
+ Args:
203
+ bus_name (str): Name of the bus where the load is connected.
204
+ name (str): Name of the load.
205
+ active_power_w (float): Active power of the load in W.
206
+ reactive_power_var (float): Reactive power of the load in VAr.
207
+ **kwargs: Additional parameters for the load.
208
+
209
+ Returns:
210
+ int: Index of the created load.
211
+ """
212
+ pass
213
+
214
+ @abstractmethod
215
+ def create_generator(
216
+ self,
217
+ bus_name: str,
218
+ name: str,
219
+ active_power_w: float,
220
+ reactive_power_var: float,
221
+ **kwargs: Any,
222
+ ) -> int:
223
+ """
224
+ Create a new static generator in the network.
225
+
226
+ Args:
227
+ bus_name (str): Name of the bus where the generator is connected.
228
+ name (str): Name of the generator.
229
+ active_power_w (float): Active power of the generator in W.
230
+ reactive_power_var (float): Reactive power of the generator in VAr.
231
+ **kwargs: Additional parameters for the generator.
232
+
233
+ Returns:
234
+ int: Index of the created generator.
235
+ """
236
+ pass
237
+
238
+ @abstractmethod
239
+ def create_line(
240
+ self,
241
+ name: str,
242
+ from_bus: str,
243
+ to_bus: str,
244
+ length_km: float,
245
+ line_type: str,
246
+ **kwargs: Any,
247
+ ) -> int:
248
+ """
249
+ Create a new line in the network.
250
+
251
+ Args:
252
+ name (str): Name of the line.
253
+ from_bus (str): Name of the starting bus.
254
+ to_bus (str): Name of the ending bus.
255
+ length_km (float): Length of the line in kilometers.
256
+ line_type (str): Type of the line (refers to standard types in the network model).
257
+ **kwargs: Additional parameters for the line.
258
+
259
+ Returns:
260
+ int: Index of the created line.
261
+ """
262
+ pass
263
+
264
+ @abstractmethod
265
+ def create_ext_grid(
266
+ self,
267
+ bus_name: str,
268
+ name: str,
269
+ voltage_reference_pu: float,
270
+ angle_reference_degree: float = 0,
271
+ **kwargs: Any,
272
+ ) -> int:
273
+ """
274
+ Create a new external grid connection in the network.
275
+
276
+ Args:
277
+ bus_name (str): Name of the bus where the external grid is connected.
278
+ name (str): Name of the external grid.
279
+ voltage_reference_pu (float): Voltage magnitude in per unit.
280
+ angle_reference_degree (float, optional): Voltage angle in degrees. Defaults to 0.
281
+ **kwargs: Additional parameters for the external grid.
282
+
283
+ Returns:
284
+ int: Index of the created external grid.
285
+ """
286
+ pass
287
+
288
+ @abstractmethod
289
+ def create_transformer(
290
+ self, name: str, hv_bus: str, lv_bus: str, transformer_type: str, **kwargs: Any
291
+ ) -> int:
292
+ """
293
+ Create a new transformer in the network.
294
+
295
+ Args:
296
+ name (str): Name of the transformer.
297
+ hv_bus (str): Name of the high voltage bus.
298
+ lv_bus (str): Name of the low voltage bus.
299
+ transformer_type (str): Type of the transformer (refers to standard types in the network model).
300
+ **kwargs: Additional parameters for the transformer.
301
+
302
+ Returns:
303
+ int: Index of the created transformer.
304
+ """
305
+ pass
306
+
307
+ @abstractmethod
308
+ def run_power_flow(self, warm_start: bool = False) -> dict[str, Any]:
309
+ """
310
+ Run power flow calculation on the current network.
311
+
312
+ Args:
313
+ warm_start (bool, optional): If True, use previous solution as initial guess. Defaults to False.
314
+ An engine may refuse a requested warm start and solve from a flat start
315
+ instead, when there is no previous solution to start from, or in the
316
+ other cases its implementation documents (the pandapower engine refuses
317
+ one when an angle that a transformer or an external grid applies has
318
+ changed since the previous solution, or when the warm start fails before
319
+ any controller has acted). The result of a refused warm start is that of a
320
+ cold run.
321
+
322
+ Returns:
323
+ Dict[str, Any]: Dictionary with power flow results and statistics.
324
+
325
+ Raises:
326
+ PowerFlowNotConverged: If the solver does not converge. Implementations must
327
+ raise rather than return a result flagged as not converged, and must
328
+ leave `latest_results["converged"]` False so that the results of an
329
+ earlier run are never mistaken for the current state. Of the engines
330
+ shipped with gridforge, only `PandaPowerEngine` does so for now: the
331
+ OpenDSS and Roseau engines return `converged=False` in their results,
332
+ and the GridLab-D engine always reports convergence.
333
+ """
334
+ pass
335
+
336
+ def unresolved_power_mva(self) -> float | None:
337
+ """
338
+ The largest power mismatch, in MVA, that the last run of the engine left at a
339
+ bus: the power that its solution does not resolve.
340
+
341
+ `GridEnhancementAlgorithm` takes two costs that differ by less than the price of
342
+ flexibility on the largest such power of its run for equal. None (the default)
343
+ if the engine does not tell: the costs are then compared exactly.
344
+ """
345
+ return None
346
+
347
+ @abstractmethod
348
+ def check_violations(self) -> list[ConstraintViolation]:
349
+ """
350
+ Check if the network violates specified constraints.
351
+
352
+ Returns:
353
+ List[ConstraintViolation]: List of constraint violations.
354
+ """
355
+ pass
356
+
357
+ @abstractmethod
358
+ def analyze_violations(self) -> Any:
359
+ """
360
+ Analyze and summarize network constraint violations.
361
+
362
+ Returns:
363
+ Any: Summary of violations (format depends on implementation).
364
+ """
365
+ pass
366
+
367
+ @abstractmethod
368
+ def apply_tap_change(self, trafo_id: str, tap_pos_shift: int) -> bool:
369
+ """
370
+ Change the tap position of a transformer by a number of steps.
371
+
372
+ The shift is applied whole or not at all: an engine refuses a shift that would
373
+ take the position outside the tap range of the unit, and changes nothing then.
374
+
375
+ Args:
376
+ trafo_id (str): Name of the transformer.
377
+ tap_pos_shift (int): Number of steps added to the current tap position,
378
+ negative to lower it (`TapChangeStrategy` passes shifts of several
379
+ steps).
380
+
381
+ Returns:
382
+ bool: True if the position moved by `tap_pos_shift`, False if nothing
383
+ changed, the new position being outside the range.
384
+ """
385
+ pass
386
+
387
+ def get_transformer_tap_position(self, transformer_id: str) -> float | None:
388
+ """
389
+ The tap position of a transformer, None if it has none or the engine does not
390
+ tell it (the default).
391
+
392
+ `TapChangeStrategy` records the positions before and after its tap changes, and
393
+ `GridEnhancementAlgorithm` reverts a tap change to the position it started
394
+ from, which a transformer upgrade made since may have moved; without them it
395
+ reverts the change by its number of steps.
396
+
397
+ Args:
398
+ transformer_id (str): Name of the transformer.
399
+ """
400
+ return None
401
+
402
+ @abstractmethod
403
+ def upgrade_line(self, line_id: str, new_type: str) -> None:
404
+ """
405
+ Upgrade a line with new parameters.
406
+
407
+ Args:
408
+ line_id (str): Name of the line to upgrade.
409
+ new_type (str): Type of the new line (must exist in standard_types).
410
+ """
411
+ pass
412
+
413
+ @abstractmethod
414
+ def add_parallel_line(self, line_id: str) -> int:
415
+ """
416
+ Add a parallel line.
417
+
418
+ Args:
419
+ line_id (str): Name of the line to add a conductor to.
420
+
421
+ Returns:
422
+ int: Number of parallel conductors of the line after the addition.
423
+ """
424
+ pass
425
+
426
+ def set_line_parallel(self, line_id: int | str, parallel: int) -> int:
427
+ """
428
+ Set the number of parallel conductors of a line, fewer than it has or more.
429
+
430
+ A thermal upgrade with prices uses it to replace the conductors it has laid on
431
+ a line by fewer conductors of a larger type (see "Thermal Sizing" in the
432
+ methodology). Engines that cannot set it raise NotImplementedError, the
433
+ default: the line strategies then never take a conductor back, and choose as
434
+ they did before this operation existed.
435
+
436
+ Args:
437
+ line_id (int | str): The line.
438
+ parallel (int): Its number of conductors, 1 or more.
439
+
440
+ Returns:
441
+ int: The number of conductors of the line.
442
+ """
443
+ raise NotImplementedError(
444
+ f"{type(self).__name__} cannot set the number of conductors of a line"
445
+ )
446
+
447
+ def save_line(self, line_id: int | str) -> Any:
448
+ """
449
+ Save what a line is (its type, conductors and every parameter the engine holds
450
+ for it), for `restore_line` to give it back exactly.
451
+
452
+ The line strategies save a line before a step that must leave it within its
453
+ loading limit, to undo the step if the power flow that follows shows it over
454
+ that limit (see "Steps Checked After the Power Flow" in the methodology).
455
+ Engines that cannot raise NotImplementedError, the default: the line
456
+ strategies then take those steps unchecked, and never take a conductor back.
457
+
458
+ Args:
459
+ line_id (int | str): The line.
460
+
461
+ Returns:
462
+ Any: What `restore_line` takes, for this engine only.
463
+ """
464
+ raise NotImplementedError(f"{type(self).__name__} cannot save a line")
465
+
466
+ def restore_line(self, line_id: int | str, saved: Any) -> None:
467
+ """
468
+ Give a line back what it was when `save_line` saved it.
469
+
470
+ Args:
471
+ line_id (int | str): The line.
472
+ saved (Any): What `save_line` returned for that line.
473
+ """
474
+ raise NotImplementedError(f"{type(self).__name__} cannot restore a line")
475
+
476
+ def save_solution(self) -> Any:
477
+ """
478
+ Save the solution of the latest power flow (its results, and what the engine
479
+ keeps of it: the starting point of a warm start, the Jacobian), for
480
+ `restore_solution` to put it back exactly.
481
+
482
+ A strategy saves it before steps it checks with the power flow that follows
483
+ them, so that undoing them leaves the results as they were, bit for bit, with
484
+ no power flow (see "Steps Checked After the Power Flow" in the methodology).
485
+ Engines that cannot raise NotImplementedError, the default: the strategies
486
+ then take those steps unchecked.
487
+
488
+ Returns:
489
+ Any: What `restore_solution` takes, for this engine only.
490
+ """
491
+ raise NotImplementedError(f"{type(self).__name__} cannot save a solution")
492
+
493
+ def restore_solution(self, saved: Any) -> None:
494
+ """
495
+ Put back the solution that `save_solution` saved, as the solution of the
496
+ latest power flow: a network given back the state it was solved in then is
497
+ solved again by it, exactly. The same saved solution can be put back several
498
+ times.
499
+
500
+ Args:
501
+ saved (Any): What `save_solution` returned.
502
+ """
503
+ raise NotImplementedError(f"{type(self).__name__} cannot restore a solution")
504
+
505
+ @abstractmethod
506
+ def upgrade_transformer(self, trafo_id: str, new_type: str) -> None:
507
+ """
508
+ Upgrade a transformer with new parameters.
509
+
510
+ Args:
511
+ trafo_id (str): Name of the transformer to upgrade.
512
+ new_type (str): Type of the new transformer (must exist in standard_types).
513
+ """
514
+ pass
515
+
516
+ @abstractmethod
517
+ def add_parallel_transformer(self, trafo_id: str) -> int:
518
+ """
519
+ Add a parallel transformer.
520
+
521
+ Args:
522
+ trafo_id (str): Name of the transformer to add a unit to.
523
+
524
+ Returns:
525
+ int: Number of parallel units of the transformer after the addition.
526
+ """
527
+ pass
528
+
529
+ def save_transformer(self, transformer_id: int | str) -> Any:
530
+ """
531
+ Save what a transformer is (its type, units and every parameter the engine
532
+ holds for it), for `restore_transformer` to give it back exactly.
533
+
534
+ The transformer upgrade saves a transformer before a type change sized to
535
+ carry it, to undo the change if the power flow that follows shows it over its
536
+ loading limit. Engines that cannot raise NotImplementedError, the default: the
537
+ strategy then takes those type changes unchecked.
538
+
539
+ Args:
540
+ transformer_id (int | str): The transformer.
541
+
542
+ Returns:
543
+ Any: What `restore_transformer` takes, for this engine only.
544
+ """
545
+ raise NotImplementedError(f"{type(self).__name__} cannot save a transformer")
546
+
547
+ def restore_transformer(self, transformer_id: int | str, saved: Any) -> None:
548
+ """
549
+ Give a transformer back what it was when `save_transformer` saved it.
550
+
551
+ Args:
552
+ transformer_id (int | str): The transformer.
553
+ saved (Any): What `save_transformer` returned for that transformer.
554
+ """
555
+ raise NotImplementedError(f"{type(self).__name__} cannot restore a transformer")
556
+
557
+ @abstractmethod
558
+ def get_losses(self) -> dict[str, float]:
559
+ """
560
+ Calculate network losses.
561
+
562
+ Returns:
563
+ Dict[str, float]: Dictionary with active and reactive power losses.
564
+ """
565
+ pass
566
+
567
+ @abstractmethod
568
+ def get_network_metrics(self) -> dict[str, Any]:
569
+ """
570
+ Get various network metrics.
571
+
572
+ Returns:
573
+ Dict[str, Any]: Dictionary with network metrics.
574
+ """
575
+ pass
576
+
577
+ @abstractmethod
578
+ def create_topology_graph(self) -> Any:
579
+ """
580
+ Create a NetworkX graph representing the network topology.
581
+
582
+ Returns:
583
+ Any: NetworkX graph object.
584
+ """
585
+ pass
586
+
587
+ @abstractmethod
588
+ def get_line_imax(self, line_type) -> float:
589
+ """
590
+ Abstract method for retrieving the maximum current limit of a specified line type.
591
+
592
+ Args:
593
+ line_type (str): The type of the line.
594
+
595
+ Returns:
596
+ float: The maximum current limit (IMAX) for the specified line type.
597
+ """
598
+ pass
599
+
600
+ @abstractmethod
601
+ def get_line_r_ohm_per_km(self, line_type: str) -> float:
602
+ """
603
+ Abstract method for retrieving the resistance per unit length of a specified line type.
604
+
605
+ Args:
606
+ line_type (str): The type of the line.
607
+
608
+ Returns:
609
+ float: The resistance per unit length (Ohm/km).
610
+ """
611
+ pass
612
+
613
+ @abstractmethod
614
+ def get_line_type(self, line_id: str) -> str:
615
+ """
616
+ Abstract method for retrieving the type of a specified line.
617
+
618
+ Args:
619
+ line_id (str): The ID of the line.
620
+
621
+ Returns:
622
+ str: The type of the line.
623
+ """
624
+ pass
625
+
626
+ @abstractmethod
627
+ def get_line_length(self, line_id: int | str) -> float:
628
+ """
629
+ Get the length of a line by its ID.
630
+
631
+ Args:
632
+ line_id (Union[int, str]): The ID of the line.
633
+
634
+ Returns:
635
+ float: The length of the line in kilometers.
636
+ """
637
+ pass
638
+
639
+ def get_line_ids(self) -> list[str]:
640
+ """
641
+ Names of the lines that conduct: in service, not opened by a switch, and between buses that are in service and supplied.
642
+ """
643
+ raise NotImplementedError
644
+
645
+ def get_line_x_ohm_per_km(self, line_type: str) -> float:
646
+ """
647
+ Reactance per unit length (Ohm/km) of a line type.
648
+ """
649
+ raise NotImplementedError
650
+
651
+ def calculate_voltage_line_change_effects(
652
+ self,
653
+ changes: dict[str, tuple[float, float, int]],
654
+ buses: list[str] | None = None,
655
+ ) -> pd.DataFrame:
656
+ """
657
+ Predicted bus voltage-magnitude change (p.u.) for a finite change of each line:
658
+ line name -> (new r_ohm_per_km, new x_ohm_per_km, new parallel count).
659
+ Returns a DataFrame (index = bus names, or `buses` when given; columns = line names).
660
+ """
661
+ raise NotImplementedError
662
+
663
+ def calculate_voltage_line_change_effects_of_steps(
664
+ self,
665
+ steps: list[tuple[str, float, float, int]],
666
+ buses: list[str] | None = None,
667
+ ) -> pd.DataFrame:
668
+ """
669
+ Predicted bus voltage-magnitude change (p.u.) for each of `steps`, each a
670
+ finite change of one line, taken alone: (line name, new r_ohm_per_km, new
671
+ x_ohm_per_km, new parallel count). Unlike `calculate_voltage_line_change_effects`,
672
+ a line can have several steps, so that every step of every line is predicted in
673
+ one call.
674
+
675
+ By default, the steps are given to `calculate_voltage_line_change_effects` in
676
+ as many calls as a line has steps, the k-th step of every line in the k-th
677
+ call. An engine whose prediction of one step does not depend on the other steps
678
+ of the call can predict them all at once.
679
+
680
+ Returns:
681
+ pd.DataFrame: index = bus names, or `buses` when given; columns = the
682
+ positions in `steps` of the steps whose line conducts, in order.
683
+ """
684
+ rounds: list[dict[str, tuple[float, float, int]]] = []
685
+ positions: list[dict[str, int]] = []
686
+ for position, (line, r_ohm_per_km, x_ohm_per_km, parallel) in enumerate(steps):
687
+ k = 0
688
+ while k < len(rounds) and line in rounds[k]:
689
+ k += 1
690
+ if k == len(rounds):
691
+ rounds.append({})
692
+ positions.append({})
693
+ rounds[k][line] = (r_ohm_per_km, x_ohm_per_km, parallel)
694
+ positions[k][line] = position
695
+ if not rounds:
696
+ # No step: the buses as the engine gives them for no change
697
+ return self.calculate_voltage_line_change_effects({}, buses=buses)
698
+ frames = []
699
+ for changes, position_of in zip(rounds, positions, strict=True):
700
+ effects = self.calculate_voltage_line_change_effects(changes, buses=buses)
701
+ frames.append(effects.rename(columns=lambda line, p=position_of: p[line]))
702
+ # The rounds whose lines conduct give the buses of the solution; one in which
703
+ # none conducts gives the buses as asked for, which then add no row
704
+ with_columns = [effects for effects in frames if effects.shape[1] > 0]
705
+ if not with_columns:
706
+ return frames[0]
707
+ index = with_columns[0].index
708
+ effects = pd.concat(
709
+ [effects.reindex(index) for effects in with_columns], axis=1
710
+ )
711
+ return effects[sorted(effects.columns)]
712
+
713
+ def get_lines_info(self, line_ids: list[str] | None = None) -> pd.DataFrame:
714
+ """
715
+ Type (`std_type`), length (`length_km`) and parallel count (`parallel`) of lines, indexed by name.
716
+ An engine that has it also gives `current_a`, the current (A) the whole line
717
+ carries in the latest power flow, which the strategies that bury lines use to
718
+ keep them within the rating of the cable; without it they do not check that.
719
+ And `df`, the derating factor of the line, which a type change keeps and the
720
+ loading of the line is relative to; without it, a factor of 1 is assumed.
721
+ """
722
+ raise NotImplementedError
723
+
724
+ def get_transformers_info(self) -> pd.DataFrame:
725
+ """
726
+ Type (`std_type`) and number of units in parallel (`parallel`) of the
727
+ transformers, indexed by name. An engine that does not give it raises
728
+ NotImplementedError: a run with a cost model then charges each transformer
729
+ upgrade from the state of the transformer before the action, instead of its
730
+ state at the start of the run.
731
+ """
732
+ raise NotImplementedError
733
+
734
+ def get_line_parallel(self, line_id: int | str) -> int:
735
+ """
736
+ Number of parallel conductors of a line. Engines without this notion return 1.
737
+ """
738
+ return 1
739
+
740
+ def get_line_rating(self, line_id: int | str) -> float | None:
741
+ """
742
+ Rating (A) of one conductor of a line, the one the loading the engine reports
743
+ is relative to. Engines that do not give it return None: the thermal upgrade
744
+ then takes the rating of the type of the line.
745
+ """
746
+ return None
747
+
748
+ def get_line_base_impedance(self, line_id: int | str) -> float:
749
+ """
750
+ Per-unit base impedance (ohm) of a line. Engines without per-unit data return 1.0.
751
+ """
752
+ return 1.0
753
+
754
+ def get_line_endpoints(self, line_ids: list[str] | None = None) -> pd.DataFrame:
755
+ """
756
+ Names of the end buses (columns `from_bus`, `to_bus`) of the lines that conduct (in service, not opened by a switch, between buses that are in service and supplied), indexed by line name.
757
+ """
758
+ raise NotImplementedError
759
+
760
+ def get_closed_bus_switches(self) -> list[tuple[str, str]]:
761
+ """
762
+ Pairs of bus names joined by a closed bus-bus switch (galvanic links that are not lines).
763
+ Engines without bus-bus switches return an empty list.
764
+ """
765
+ return []
766
+
767
+ def get_source_buses(self) -> set[str]:
768
+ """
769
+ Names of the buses that feed a galvanic zone: external grid buses and transformer LV buses.
770
+ """
771
+ raise NotImplementedError
772
+
773
+ @abstractmethod
774
+ def get_transformer_type(self, transformer_id: str) -> str:
775
+ """
776
+ Abstract method for retrieving the type of a specified transformer.
777
+
778
+ Args:
779
+ transformer_id (str): The ID of the transformer.
780
+
781
+ Returns:
782
+ str: The type of the transformer.
783
+ """
784
+ pass
785
+
786
+ @abstractmethod
787
+ def get_transformer_max_power(self, transformer_type: str) -> float:
788
+ """
789
+ Abstract method for retrieving the maximum power rating of a specified transformer type.
790
+
791
+ Args:
792
+ transformer_type (str): The type of the transformer.
793
+
794
+ Returns:
795
+ float: The maximum power rating for the specified transformer type.
796
+ """
797
+ pass
798
+
799
+ @abstractmethod
800
+ def partition_network(self) -> dict[int, Any]:
801
+ """
802
+ Partition the network into galvanically connected components.
803
+
804
+ This method identifies separate electrical areas in the network that are not
805
+ connected to each other by power lines or other conducting elements, but can
806
+ be connected by transformers.
807
+
808
+ Returns:
809
+ Dict[int, Any]: Dictionary mapping component IDs to lists of elements (buses, lines, etc.)
810
+ in each connected component.
811
+ """
812
+ pass
813
+
814
+ @abstractmethod
815
+ def get_voltage_magnitude_range(self, component_id: int) -> dict[str, float]:
816
+ """
817
+ Get the minimum and maximum voltage magnitudes in a specific network component.
818
+
819
+ Args:
820
+ component_id (int): The ID of the component to analyze.
821
+
822
+ Returns:
823
+ Dict[str, float]: Dictionary containing 'min' and 'max' voltage magnitude values in per unit.
824
+ """
825
+ pass
826
+
827
+ @abstractmethod
828
+ def get_transformer_tap_positions(self, transformer_id: int | str) -> np.ndarray:
829
+ """
830
+ Get all available tap positions for a given transformer in per unit voltage values.
831
+
832
+ Args:
833
+ transformer_id (Union[int, str]): The ID of the transformer.
834
+
835
+ Returns:
836
+ np.ndarray: Array of all available tap positions as per unit voltage values,
837
+ typically sorted from lowest to highest.
838
+ """
839
+ pass
840
+
841
+ @abstractmethod
842
+ def calculate_voltage_line_resistance_sensitivities(
843
+ self, line_names: list[str] | None = None
844
+ ) -> dict[str, np.ndarray]:
845
+ """
846
+ Calculate the sensitivities of bus voltages to line impedance changes.
847
+
848
+ Args:
849
+ line_names (Optional[List[str]], optional): Restrict the computation to these lines.
850
+
851
+ Returns:
852
+ Dict[str, np.ndarray]: Dictionary mapping line IDs to arrays of sensitivity values.
853
+ Each array contains the sensitivity of that line's impedance to
854
+ voltage changes at each bus in the network.
855
+ """
856
+ pass
857
+
858
+ @abstractmethod
859
+ def get_flexibility_data(self, element_type: str) -> pd.DataFrame:
860
+ """
861
+ Get flexibility data for loads or static generators.
862
+
863
+ Only the elements that carry power are returned: those in service, and at a bus
864
+ that is energised (in service, and not in an island without a source). The
865
+ elements left out have no power to shed or curtail, and are not part of the load
866
+ or the generation of the network. `FlexibilityStrategy` relies on this: what the
867
+ data lists is what it may act on, charges, and counts in the totals and the
868
+ shares of a run, so an engine must not return the others. The index of the rows
869
+ is the engine's own for the element, whatever is left out.
870
+
871
+ Args:
872
+ element_type (str): 'load' or 'sgen'.
873
+
874
+ Returns:
875
+ pd.DataFrame: DataFrame with columns ['name', 'bus', 'p_mw', 'max_flex_pct'].
876
+ """
877
+ pass
878
+
879
+ @abstractmethod
880
+ def apply_flexibility_action(
881
+ self,
882
+ element_type: str,
883
+ element_index: int,
884
+ new_p_mw: float,
885
+ new_q_mvar: float | None = None,
886
+ ) -> None:
887
+ """
888
+ Apply a flexibility action (change active power) to an element.
889
+
890
+ The method does not check the service state of the element, nor whether its bus
891
+ is energised: it writes to the element it is given, even when that element is out
892
+ of service or at a de-energised bus. A caller acting outside `FlexibilityStrategy`,
893
+ which never selects such an element, must filter them out itself.
894
+
895
+ Args:
896
+ element_type (str): 'load' or 'sgen'.
897
+ element_index (int): Index of the element.
898
+ new_p_mw (float): New active power value in MW.
899
+ new_q_mvar (Optional[float], optional): New reactive power of a load, in MVAr.
900
+ Defaults to None, which keeps the power factor of the load. Passing it is
901
+ needed to restore a load that was shed down to zero, as its power factor
902
+ is lost with its active power.
903
+ """
904
+ pass
905
+
906
+ @abstractmethod
907
+ def calculate_voltage_power_sensitivities(
908
+ self, buses: list[str] | None = None
909
+ ) -> pd.DataFrame:
910
+ """
911
+ Calculate the sensitivities of bus voltage magnitudes to active power injections.
912
+
913
+ Used for linearized sensitivity analysis: dV ~ (dV/dP) * dP
914
+
915
+ Args:
916
+ buses (Optional[List[str]]): Names of the buses whose voltage sensitivities
917
+ are needed, which can be much cheaper than all of them. Defaults to
918
+ None, for all buses.
919
+
920
+ Returns:
921
+ pd.DataFrame: DataFrame where index and columns are bus names.
922
+ Values represent d|V|_i / dP_j (change in voltage at bus i per unit change in P at bus j).
923
+ """
924
+ pass
925
+
926
+ @abstractmethod
927
+ def analyze_thermal_violation(
928
+ self, element_type: str, element_id: str
929
+ ) -> dict[str, Any]:
930
+ """
931
+ Analyze a thermal violation to determine downstream topology and flow conditions.
932
+
933
+ Args:
934
+ element_type (str): "Line" or "Transformer".
935
+ element_id (str): Name of the element.
936
+
937
+ Returns:
938
+ Dict[str, Any]: Dictionary containing:
939
+ - "downstream_buses": List[str] of bus names downstream of the element
940
+ - "flow_mw": Active power flow through the element (at upstream end)
941
+ - "rated_mva": Rated capacity of the element
942
+ - "is_flow_towards_downstream": Boolean indicating if power flows towards downstream
943
+ """
944
+ pass
945
+
946
+ @abstractmethod
947
+ def calculate_branch_loading_sensitivities(
948
+ self, element_type: str, element_name: str
949
+ ) -> pd.DataFrame:
950
+ """
951
+ Calculate sensitivity of a branch's loading (current) to active power injections.
952
+
953
+ Args:
954
+ element_type (str): "Line" or "Transformer".
955
+ element_name (str): Name of the element.
956
+
957
+ Returns:
958
+ pd.DataFrame: DataFrame with index=bus_names and one column, "sensitivity",
959
+ with values = d(Loading_pct)/d(P_mw): the change of the loading of the
960
+ branch, in %, per MW of active power injected at the bus, at constant
961
+ reactive injection. Empty if the sensitivities are not available.
962
+ Positive value means injecting more at the bus increases the loading.
963
+ Negative value means injecting more at the bus decreases the loading.
964
+ The sign does not depend on the direction of the flow in the branch.
965
+ """
966
+ pass
967
+
968
+ def get_component_id_for_bus(self, bus_id: int | str) -> int | None:
969
+ """
970
+ Retrieve the component ID for a given bus ID.
971
+
972
+ This method looks up which network partition component contains the specified bus.
973
+
974
+ Args:
975
+ bus_id (Union[int, str]): The ID of the bus to find the component for.
976
+
977
+ Returns:
978
+ Optional[int]: The ID of the component containing the bus, or None if the bus is not found
979
+ or if the network has not been partitioned.
980
+ """
981
+ if self.network_partition is None:
982
+ self.logger.warning(
983
+ "Network has not been partitioned. Call partition_network() first."
984
+ )
985
+ return None
986
+
987
+ for component_id, component_data in self.network_partition.items():
988
+ # Check if component_data contains buses and if the specified bus_id is among them
989
+ if "buses" in component_data and bus_id in component_data["buses"]:
990
+ return component_id
991
+
992
+ self.logger.warning(f"Bus ID {bus_id} not found in any network component")
993
+ return None
994
+
995
+ def get_transformer_for_component(self, component_id: int) -> str | None:
996
+ """
997
+ Retrieve the name of the transformer for a specific network component.
998
+
999
+ Since each galvanically connected component can have only one transformer,
1000
+ this method returns that transformer's name, which is how the engine
1001
+ identifies it (`apply_tap_change`, `get_transformer_tap_positions`...).
1002
+
1003
+ Args:
1004
+ component_id (int): The ID of the component to find the transformer for.
1005
+
1006
+ Returns:
1007
+ Optional[str]: The name of the transformer for the component, or None if no transformer exists
1008
+ or if the component ID is invalid.
1009
+ """
1010
+ if self.network_partition is None:
1011
+ self.logger.warning(
1012
+ "Network has not been partitioned. Call partition_network() first."
1013
+ )
1014
+ return None
1015
+
1016
+ if component_id not in self.network_partition:
1017
+ self.logger.warning(
1018
+ f"Component ID {component_id} not found in network partition"
1019
+ )
1020
+ return None
1021
+
1022
+ component = self.network_partition[component_id]
1023
+
1024
+ if "transformers" not in component or not component["transformers"]:
1025
+ self.logger.info(f"No transformer found in component {component_id}")
1026
+ return None
1027
+
1028
+ # Since there can only be one transformer per component, return the first (and only) one
1029
+ return component["transformers"][0]
1030
+
1031
+ def get_supplying_transformer_for_bus(self, bus_id: int | str) -> str | None:
1032
+ """
1033
+ Retrieve the name of the transformer supplying a given bus.
1034
+
1035
+ This method finds the component containing the bus and returns the transformer
1036
+ associated with that component.
1037
+
1038
+ Args:
1039
+ bus_id (Union[int, str]): The ID of the bus to find the supplying transformer for.
1040
+
1041
+ Returns:
1042
+ Optional[str]: The name of the transformer supplying the bus, or None if no transformer is found
1043
+ or if the bus is not present in the network.
1044
+ """
1045
+ if self.network is None:
1046
+ self.logger.warning("No network loaded. Load a network first.")
1047
+ return None
1048
+
1049
+ # Ensure network is partitioned
1050
+ if self.network_partition is None:
1051
+ self.logger.info("Network not yet partitioned. Partitioning now.")
1052
+ self.partition_network()
1053
+
1054
+ # Find which component contains this bus
1055
+ component_id = self.get_component_id_for_bus(bus_id)
1056
+ if component_id is None:
1057
+ self.logger.warning(f"Bus ID {bus_id} not found in any network component")
1058
+ return None
1059
+
1060
+ # Get the transformer for this component
1061
+ return self.get_transformer_for_component(component_id)
1062
+
1063
+ def group_violations_by_component(
1064
+ self,
1065
+ violations: list[ConstraintViolation],
1066
+ ) -> dict[int, list[ConstraintViolation]]:
1067
+ """
1068
+ Group violations by connected components from the network partition.
1069
+
1070
+ This method uses the network partition information from the power flow engine
1071
+ to group voltage violations by their respective galvanically connected components.
1072
+ Each component typically has one main transformer, making this grouping ideal
1073
+ for applying tap changes effectively.
1074
+
1075
+ Args:
1076
+ violations (List[ConstraintViolation]): List of constraint violations to group.
1077
+
1078
+ Returns:
1079
+ Dict[int, List[ConstraintViolation]]: Dictionary mapping component IDs to lists of violations in that component.
1080
+ """
1081
+ # Ensure network is partitioned
1082
+ if self.network_partition is None:
1083
+ self.logger.info("Network not yet partitioned. Partitioning now.")
1084
+ self.partition_network()
1085
+
1086
+ # Initialize result dictionary
1087
+ component_violations = {}
1088
+
1089
+ # Process each violation
1090
+ for violation in violations:
1091
+ # Get the bus ID from the violation
1092
+ bus_id = violation.element_id
1093
+
1094
+ # Find which component contains this bus
1095
+ component_id = self.get_component_id_for_bus(bus_id)
1096
+
1097
+ if component_id is None:
1098
+ self.logger.warning(
1099
+ f"Bus ID {bus_id} not found in any network component"
1100
+ )
1101
+ continue
1102
+
1103
+ # Add to the appropriate component group
1104
+ if component_id not in component_violations:
1105
+ component_violations[component_id] = []
1106
+
1107
+ component_violations[component_id].append(violation)
1108
+
1109
+ return component_violations
1110
+
1111
+ def plot_network_violations(
1112
+ self,
1113
+ violations: list[ConstraintViolation] | None = None,
1114
+ show_ids: bool = False,
1115
+ enhancement_results: dict[str, Any] | None = None,
1116
+ save_path: str | Path | None = None,
1117
+ filename: str | None = None,
1118
+ rc_params: dict[str, Any] | None = None,
1119
+ ) -> None:
1120
+ """
1121
+ Plot the network topology with violation and action overlays.
1122
+
1123
+ This method intentionally stays generic and delegates all rendering
1124
+ logic to `gridforge.utils.plot.plot_network_violations`.
1125
+
1126
+ Args:
1127
+ violations (Optional[List[ConstraintViolation]], optional): Optional explicit list of violations. If None, use `self.constraints.violations`.
1128
+ show_ids (bool, optional): Show IDs for buses, lines, and transformers. Defaults to False.
1129
+ enhancement_results (Optional[Dict[str, Any]], optional): Results produced by `GridEnhancementAlgorithm.run()` used to highlight modified elements.
1130
+ save_path (Optional[Union[str, Path]], optional): Path to save the plot.
1131
+ filename (Optional[str], optional): Filename for the saved plot.
1132
+ rc_params (Optional[Dict[str, Any]], optional): Optional style overrides passed to plotting utilities.
1133
+ """
1134
+ from gridforge.utils.plot import (
1135
+ plot_network_violations as _plot_network_violations,
1136
+ )
1137
+
1138
+ _plot_network_violations(
1139
+ engine=self,
1140
+ violations=violations,
1141
+ show_ids=show_ids,
1142
+ enhancement_results=enhancement_results,
1143
+ save_path=save_path,
1144
+ filename=filename,
1145
+ rc_params=rc_params,
1146
+ )