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,1234 @@
1
+ """
2
+ Roseau engine implementation for power flow analysis in GridForge.
3
+ """
4
+
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+
9
+ try:
10
+ import roseau
11
+ except ImportError:
12
+ raise ImportError("Roseau is required for RoseauEngine but not installed")
13
+
14
+ import networkx as nx
15
+ import pandas as pd
16
+
17
+ from gridforge.core.constraints import ConstraintViolation
18
+ from gridforge.core.power_flow import PowerFlowEngine
19
+ from gridforge.utils.logging import logger
20
+
21
+
22
+ class RoseauEngine(PowerFlowEngine):
23
+ """
24
+ Interface to Roseau for power flow calculations and network analysis.
25
+
26
+ This engine provides methods to:
27
+ 1. Load network models
28
+ 2. Run power flow calculations
29
+ 3. Apply network modifications
30
+ 4. Check constraint violations
31
+ 5. Extract results and metrics
32
+ """
33
+
34
+ def __init__(self, config: dict[str, Any] | None = None):
35
+ """
36
+ Initialize Roseau engine.
37
+
38
+ Args:
39
+ config: Configuration dictionary with Roseau specific settings
40
+ """
41
+ super().__init__(config)
42
+ self.network = None
43
+ self.latest_results = None
44
+ self.network_partition = None
45
+ self.logger = logger
46
+
47
+ def create_empty_network(
48
+ self, name: str = "grid-forge-network", f_hz: float = 50.0
49
+ ) -> None:
50
+ """
51
+ Create an empty Roseau network.
52
+
53
+ Args:
54
+ name: Name of the network
55
+ f_hz: System frequency in Hz
56
+ """
57
+ self.network = roseau.Network(name=name, frequency=f_hz)
58
+ self.logger.info(f"Created empty network: {name}")
59
+
60
+ def create_bus(self, name: str, nominal_voltage_v: float, **kwargs: Any):
61
+ """
62
+ Create a new bus in the Roseau network.
63
+
64
+ Parameters
65
+ ----------
66
+ name : str
67
+ Name of the bus
68
+ nominal_voltage_v : float
69
+ Nominal voltage of the bus in V
70
+ **kwargs : dict
71
+ Additional parameters for the bus
72
+
73
+ Returns
74
+ -------
75
+ int
76
+ Index of the created bus
77
+ """
78
+ if self.network is None:
79
+ raise ValueError("Network not initialized. Create or load a network first.")
80
+
81
+ # Convert generic parameters to Roseau-specific parameters
82
+ roseau_params = {"name": name, "nominal_voltage": nominal_voltage_v}
83
+
84
+ # Add any additional parameters
85
+ roseau_params.update(kwargs)
86
+
87
+ # Create the bus in the Roseau network
88
+ bus = self.network.add_bus(**roseau_params)
89
+ return bus.id
90
+
91
+ def create_load(
92
+ self,
93
+ bus_name: str,
94
+ name: str,
95
+ active_power_w: float,
96
+ reactive_power_var: float,
97
+ **kwargs: Any,
98
+ ):
99
+ """
100
+ Create a new load in the Roseau network.
101
+
102
+ Parameters
103
+ ----------
104
+ bus_name : str
105
+ Name of the bus where the load is connected
106
+ name : str
107
+ Name of the load
108
+ active_power_w : float
109
+ Active power of the load in W
110
+ reactive_power_var : float
111
+ Reactive power of the load in VAr
112
+ **kwargs : dict
113
+ Additional parameters for the load
114
+
115
+ Returns
116
+ -------
117
+ int
118
+ Index of the created load
119
+ """
120
+ if self.network is None:
121
+ raise ValueError("Network not initialized. Create or load a network first.")
122
+
123
+ # Find the bus by name
124
+ bus = self.network.get_bus_by_name(bus_name)
125
+ if bus is None:
126
+ raise ValueError(f"Bus with name '{bus_name}' not found in the network")
127
+
128
+ # Convert generic parameters to Roseau-specific parameters
129
+ roseau_params = {
130
+ "name": name,
131
+ "bus": bus,
132
+ "p": active_power_w,
133
+ "q": reactive_power_var,
134
+ }
135
+
136
+ # Add any additional parameters
137
+ roseau_params.update(kwargs)
138
+
139
+ # Create the load in the Roseau network
140
+ load = self.network.add_load(**roseau_params)
141
+ return load.id
142
+
143
+ def create_line(
144
+ self,
145
+ name: str,
146
+ from_bus: str,
147
+ to_bus: str,
148
+ length_km: float,
149
+ line_type: str,
150
+ **kwargs: Any,
151
+ ):
152
+ """
153
+ Create a new line in the Roseau network.
154
+
155
+ Parameters
156
+ ----------
157
+ name : str
158
+ Name of the line
159
+ from_bus : str
160
+ Name of the starting bus
161
+ to_bus : str
162
+ Name of the ending bus
163
+ length_km : float
164
+ Length of the line in kilometers
165
+ line_type : str
166
+ Type of the line (refers to standard types in Roseau)
167
+ **kwargs : dict
168
+ Additional parameters for the line
169
+
170
+ Returns
171
+ -------
172
+ int
173
+ Index of the created line
174
+ """
175
+ if self.network is None:
176
+ raise ValueError("Network not initialized. Create or load a network first.")
177
+
178
+ # Find the buses by name
179
+ from_bus_obj = self.network.get_bus_by_name(from_bus)
180
+ to_bus_obj = self.network.get_bus_by_name(to_bus)
181
+
182
+ if from_bus_obj is None:
183
+ raise ValueError(f"Bus with name '{from_bus}' not found in the network")
184
+ if to_bus_obj is None:
185
+ raise ValueError(f"Bus with name '{to_bus}' not found in the network")
186
+
187
+ # Get line type parameters from standard types
188
+ line_params = self.network.get_line_type(line_type)
189
+ if line_params is None:
190
+ raise ValueError(f"Line type '{line_type}' not found in standard types")
191
+
192
+ # Convert generic parameters to Roseau-specific parameters
193
+ roseau_params = {
194
+ "name": name,
195
+ "from_bus": from_bus_obj,
196
+ "to_bus": to_bus_obj,
197
+ "length": length_km,
198
+ "type": line_type,
199
+ }
200
+
201
+ # Add any additional parameters
202
+ roseau_params.update(kwargs)
203
+
204
+ # Create the line in the Roseau network
205
+ line = self.network.add_line(**roseau_params)
206
+ return line.id
207
+
208
+ def create_ext_grid(
209
+ self,
210
+ bus_name: str,
211
+ name: str,
212
+ voltage_reference_pu: float,
213
+ angle_reference_degree: float = 0,
214
+ **kwargs: Any,
215
+ ):
216
+ """
217
+ Create a new external grid connection in the Roseau network.
218
+
219
+ Parameters
220
+ ----------
221
+ bus_name : str
222
+ Name of the bus where the external grid is connected
223
+ name : str
224
+ Name of the external grid
225
+ voltage_reference_pu : float
226
+ Voltage magnitude in per unit
227
+ angle_reference_degree : float, optional
228
+ Voltage angle in degrees, defaults to 0
229
+ **kwargs : dict
230
+ Additional parameters for the external grid
231
+
232
+ Returns
233
+ -------
234
+ int
235
+ Index of the created external grid
236
+ """
237
+ if self.network is None:
238
+ raise ValueError("Network not initialized. Create or load a network first.")
239
+
240
+ # Find the bus by name
241
+ bus = self.network.get_bus_by_name(bus_name)
242
+ if bus is None:
243
+ raise ValueError(f"Bus with name '{bus_name}' not found in the network")
244
+
245
+ # Convert generic parameters to Roseau-specific parameters
246
+ roseau_params = {
247
+ "name": name,
248
+ "bus": bus,
249
+ "vm_pu": voltage_reference_pu,
250
+ "va_degree": angle_reference_degree,
251
+ }
252
+
253
+ # Add any additional parameters
254
+ roseau_params.update(kwargs)
255
+
256
+ # Create the external grid in the Roseau network
257
+ ext_grid = self.network.add_ext_grid(**roseau_params)
258
+ return ext_grid.id
259
+
260
+ def create_transformer(
261
+ self, name: str, hv_bus: str, lv_bus: str, transformer_type: str, **kwargs: Any
262
+ ):
263
+ """
264
+ Create a new transformer in the Roseau network.
265
+
266
+ Parameters
267
+ ----------
268
+ name : str
269
+ Name of the transformer
270
+ hv_bus : str
271
+ Name of the high voltage bus
272
+ lv_bus : str
273
+ Name of the low voltage bus
274
+ transformer_type : str
275
+ Type of the transformer (refers to standard types in Roseau)
276
+ **kwargs : dict
277
+ Additional parameters for the transformer
278
+
279
+ Returns
280
+ -------
281
+ int
282
+ Index of the created transformer
283
+ """
284
+ if self.network is None:
285
+ raise ValueError("Network not initialized. Create or load a network first.")
286
+
287
+ # Find the buses by name
288
+ hv_bus_obj = self.network.get_bus_by_name(hv_bus)
289
+ lv_bus_obj = self.network.get_bus_by_name(lv_bus)
290
+
291
+ if hv_bus_obj is None:
292
+ raise ValueError(f"Bus with name '{hv_bus}' not found in the network")
293
+ if lv_bus_obj is None:
294
+ raise ValueError(f"Bus with name '{lv_bus}' not found in the network")
295
+
296
+ # Get transformer type parameters from standard types
297
+ trafo_params = self.network.get_transformer_type(transformer_type)
298
+ if trafo_params is None:
299
+ raise ValueError(
300
+ f"Transformer type '{transformer_type}' not found in standard types"
301
+ )
302
+
303
+ # Convert generic parameters to Roseau-specific parameters
304
+ roseau_params = {
305
+ "name": name,
306
+ "hv_bus": hv_bus_obj,
307
+ "lv_bus": lv_bus_obj,
308
+ "type": transformer_type,
309
+ }
310
+
311
+ # Add any additional parameters
312
+ roseau_params.update(kwargs)
313
+
314
+ # Create the transformer in the Roseau network
315
+ transformer = self.network.add_transformer(**roseau_params)
316
+ return transformer.id
317
+
318
+ def load_network(self, source: str | dict) -> None:
319
+ """
320
+ Load a network from file or dictionary.
321
+
322
+ Args:
323
+ source: Path to network file or network dictionary
324
+ """
325
+ self.logger.info("Loading network")
326
+
327
+ if isinstance(source, str):
328
+ self.network = roseau.load_network(source)
329
+ elif isinstance(source, dict):
330
+ self.network = roseau.from_dict(source)
331
+ else:
332
+ raise TypeError("Source must be a file path or network dictionary")
333
+
334
+ self.logger.info(
335
+ f"Loaded network with {len(self.network.buses)} buses, "
336
+ f"{len(self.network.lines)} lines, and {len(self.network.transformers)} transformers"
337
+ )
338
+
339
+ def save_network(self, target: str) -> None:
340
+ """
341
+ Save the current network to a file.
342
+
343
+ Args:
344
+ target: Path where to save the network
345
+ """
346
+ if not self.network:
347
+ raise ValueError("No network loaded to save")
348
+
349
+ roseau.save_network(self.network, target)
350
+ self.logger.info(f"Network saved to {target}")
351
+
352
+ def run_power_flow(self) -> dict[str, Any]:
353
+ """
354
+ Run power flow calculation on the current network.
355
+
356
+ Returns:
357
+ Dictionary with power flow results and statistics
358
+ """
359
+ if not self.network:
360
+ raise ValueError("No network loaded for power flow calculation")
361
+
362
+ self.logger.info("Running power flow calculation")
363
+
364
+ try:
365
+ # Run power flow with specified settings
366
+ results = roseau.run_power_flow(
367
+ self.network,
368
+ max_iterations=self.pf_settings["generic"]["max_iterations"],
369
+ tolerance=self.pf_settings["generic"]["tolerance"],
370
+ **self.pf_settings["specific"],
371
+ )
372
+
373
+ # Check if power flow converged
374
+ if not results.converged:
375
+ self.logger.warning("Power flow did not converge")
376
+
377
+ # Store results for later use
378
+ self.latest_results = {
379
+ "converged": results.converged,
380
+ "iterations": results.iterations,
381
+ "time": results.execution_time,
382
+ }
383
+
384
+ self.logger.info(
385
+ f"Power flow calculation finished: converged={results.converged}, "
386
+ f"iterations={self.latest_results['iterations']}"
387
+ )
388
+
389
+ return self.latest_results
390
+
391
+ except Exception as e:
392
+ self.logger.error(f"Power flow calculation failed: {str(e)}")
393
+ raise
394
+
395
+ def check_violations(self) -> dict[str, Any]:
396
+ """
397
+ Check if the network violates specified constraints.
398
+
399
+ Returns:
400
+ Dictionary with constraint violations
401
+ """
402
+ if (
403
+ not self.network
404
+ or not self.latest_results
405
+ or not self.latest_results.get("converged", False)
406
+ ):
407
+ raise ValueError("Need a converged power flow solution to check violations")
408
+
409
+ # Prepare data for constraint checking
410
+ bus_data = pd.DataFrame(
411
+ {
412
+ "bus_id": [bus.name for bus in self.network.buses],
413
+ "vn_kv": [bus.nominal_voltage / 1000.0 for bus in self.network.buses],
414
+ "vm_pu": [bus.vm_pu for bus in self.network.buses],
415
+ }
416
+ )
417
+ bus_data["voltage_level"] = np.where(bus_data["vn_kv"] <= 1.0, "lv", "mv")
418
+
419
+ line_data = pd.DataFrame(
420
+ {
421
+ "line_id": [line.name for line in self.network.lines],
422
+ "loading_percent": [
423
+ line.loading_percent for line in self.network.lines
424
+ ],
425
+ "current": [line.current_a for line in self.network.lines],
426
+ }
427
+ )
428
+
429
+ transformer_data = pd.DataFrame(
430
+ {
431
+ "transformer_id": [trafo.name for trafo in self.network.transformers],
432
+ "loading_percent": [
433
+ trafo.loading_percent for trafo in self.network.transformers
434
+ ],
435
+ "power": [trafo.power_w for trafo in self.network.transformers],
436
+ }
437
+ )
438
+
439
+ violations = self.constraints.check_violations(
440
+ bus_data=bus_data,
441
+ line_data=line_data,
442
+ transformer_data=transformer_data,
443
+ )
444
+
445
+ return violations
446
+
447
+ def analyze_violations(self):
448
+ """
449
+ Calls the NetworkConstraint analyze_violations method.
450
+
451
+ :return: The summary of violations.
452
+ :rtype: Any
453
+ """
454
+ return self.constraints.analyze_violations()
455
+
456
+ def apply_tap_change(self, trafo_id: str, tap_pos_shift: int) -> bool:
457
+ """
458
+ Change tap position of a transformer.
459
+
460
+ Args:
461
+ trafo_id: ID of the transformer
462
+ tap_pos_shift: New tap position shift
463
+ """
464
+ if not self.network:
465
+ raise ValueError("No network loaded")
466
+
467
+ try:
468
+ # Find the transformer by ID
469
+ transformer = self.network.get_transformer_by_id(trafo_id)
470
+ if transformer is None:
471
+ raise ValueError(
472
+ f"Transformer with ID '{trafo_id}' not found in the network"
473
+ )
474
+
475
+ # Check tap position limits
476
+ if transformer.tap_pos + tap_pos_shift > transformer.tap_max:
477
+ self.logger.info(
478
+ f"Tap position already of transformer {trafo_id} at max setting, cannot increase."
479
+ )
480
+ return False
481
+ elif transformer.tap_pos + tap_pos_shift < transformer.tap_min:
482
+ self.logger.info(
483
+ f"Tap position already of transformer {trafo_id} at min setting, cannot decrease."
484
+ )
485
+ return False
486
+ else:
487
+ current_tap_pos = transformer.tap_pos
488
+ transformer.tap_pos = current_tap_pos + tap_pos_shift
489
+ self.logger.info(
490
+ f"Changed tap position of transformer {trafo_id} from {current_tap_pos} to {current_tap_pos + tap_pos_shift}"
491
+ )
492
+ return True
493
+ except Exception as e:
494
+ self.logger.error(f"Failed to change tap position: {str(e)}")
495
+ raise
496
+
497
+ def upgrade_line(self, line_id: str, new_type: str) -> None:
498
+ """
499
+ Upgrade a line with new parameters.
500
+
501
+ Args:
502
+ line_id: ID of the line to upgrade
503
+ new_type: Type of the new line (must exist in standard_types)
504
+ """
505
+ if not self.network:
506
+ raise ValueError("No network loaded")
507
+
508
+ try:
509
+ # Check if the standard type exists
510
+ if not self.network.has_line_type(new_type):
511
+ raise ValueError(f"Line type '{new_type}' not found in standard types")
512
+
513
+ # Find the line by ID
514
+ line = self.network.get_line_by_id(line_id)
515
+ if line is None:
516
+ raise ValueError(f"Line with ID '{line_id}' not found in the network")
517
+
518
+ current_type = line.type
519
+ # Apply the new type
520
+ line.change_type(new_type)
521
+ self.logger.info(
522
+ f"Upgraded line {line_id} from {current_type} to type {new_type}"
523
+ )
524
+ except Exception as e:
525
+ self.logger.error(f"Failed to upgrade line: {str(e)}")
526
+ raise
527
+
528
+ def add_parallel_line(self, line_id: str) -> int:
529
+ """
530
+ Add a parallel line.
531
+
532
+ Args:
533
+ line_id (int): ID of the line to upgrade.
534
+
535
+ Returns:
536
+ int: Count of parallel lines
537
+ """
538
+ if not self.network:
539
+ raise ValueError("No network loaded")
540
+
541
+ try:
542
+ line = self.network.get_line_by_id(line_id)
543
+ if line is None:
544
+ raise ValueError(f"Line with ID '{line_id}' not found in the network")
545
+
546
+ line.parallel += 1
547
+ self.logger.info(f"Added parallel line to {line_id}")
548
+ return line.parallel
549
+ except Exception as e:
550
+ self.logger.error(f"Failed to add parallel line: {str(e)}")
551
+ raise
552
+
553
+ def upgrade_transformer(self, trafo_id: str, new_type: str) -> None:
554
+ """
555
+ Upgrade a transformer with new parameters.
556
+
557
+ Args:
558
+ trafo_id: ID of the transformer to upgrade
559
+ new_type: Type of the new transformer (must exist in standard_types)
560
+ """
561
+ if not self.network:
562
+ raise ValueError("No network loaded")
563
+
564
+ try:
565
+ # Check if the standard type exists
566
+ if not self.network.has_transformer_type(new_type):
567
+ raise ValueError(
568
+ f"Transformer type '{new_type}' not found in standard types"
569
+ )
570
+
571
+ # Find the transformer by ID
572
+ transformer = self.network.get_transformer_by_id(trafo_id)
573
+ if transformer is None:
574
+ raise ValueError(
575
+ f"Transformer with ID '{trafo_id}' not found in the network"
576
+ )
577
+
578
+ current_type = transformer.type
579
+ # Apply the new type
580
+ transformer.change_type(new_type)
581
+ self.logger.info(
582
+ f"Upgraded transformer {trafo_id} from {current_type} to type {new_type}"
583
+ )
584
+ except Exception as e:
585
+ self.logger.error(f"Failed to upgrade transformer: {str(e)}")
586
+ raise
587
+
588
+ def add_parallel_transformer(self, trafo_id: str) -> int:
589
+ """
590
+ Add a parallel transformer.
591
+
592
+ Args:
593
+ trafo_id (int): ID of the transformer to upgrade.
594
+
595
+ Returns:
596
+ int: Count of parallel transformers
597
+ """
598
+ if not self.network:
599
+ raise ValueError("No network loaded")
600
+
601
+ try:
602
+ transformer = self.network.get_transformer_by_id(trafo_id)
603
+ if transformer is None:
604
+ raise ValueError(
605
+ f"Transformer with ID '{trafo_id}' not found in the network"
606
+ )
607
+
608
+ transformer.parallel += 1
609
+ self.logger.info(f"Added parallel transformer to {trafo_id}")
610
+ return transformer.parallel
611
+ except Exception as e:
612
+ self.logger.error(f"Failed to add parallel transformer: {str(e)}")
613
+ raise
614
+
615
+ def get_losses(self) -> dict[str, float]:
616
+ """
617
+ Calculate network losses.
618
+
619
+ Returns:
620
+ Dictionary with active and reactive power losses
621
+ """
622
+ if (
623
+ not self.network
624
+ or not self.latest_results
625
+ or not self.latest_results.get("converged", False)
626
+ ):
627
+ raise ValueError("Need a converged power flow solution to calculate losses")
628
+
629
+ # Calculate total losses
630
+ p_losses = 0.0
631
+ q_losses = 0.0
632
+
633
+ # Line losses
634
+ for line in self.network.lines:
635
+ p_losses += line.p_loss
636
+ q_losses += line.q_loss
637
+
638
+ # Transformer losses
639
+ for transformer in self.network.transformers:
640
+ p_losses += transformer.p_loss
641
+ q_losses += transformer.q_loss
642
+
643
+ return {"p_loss_mw": p_losses / 1e6, "q_loss_mvar": q_losses / 1e6}
644
+
645
+ def get_network_metrics(self) -> dict[str, Any]:
646
+ """
647
+ Get various network metrics.
648
+
649
+ Returns:
650
+ Dictionary with network metrics
651
+ """
652
+ if not self.network:
653
+ raise ValueError("No network loaded")
654
+
655
+ metrics = {
656
+ "network_size": {
657
+ "buses": len(self.network.buses),
658
+ "lines": len(self.network.lines),
659
+ "transformers": len(self.network.transformers),
660
+ "loads": len(self.network.loads),
661
+ "generators": len(self.network.generators),
662
+ }
663
+ }
664
+
665
+ # Add voltage statistics if power flow results are available
666
+ if self.latest_results and self.latest_results.get("converged", False):
667
+ vm_pu_values = [bus.vm_pu for bus in self.network.buses]
668
+ metrics["voltage"] = {
669
+ "min": min(vm_pu_values),
670
+ "max": max(vm_pu_values),
671
+ "mean": sum(vm_pu_values) / len(vm_pu_values) if vm_pu_values else 0,
672
+ }
673
+
674
+ # Add loading statistics
675
+ line_loading = [line.loading_percent for line in self.network.lines]
676
+ if line_loading:
677
+ metrics["line_loading"] = {
678
+ "min": min(line_loading),
679
+ "max": max(line_loading),
680
+ "mean": sum(line_loading) / len(line_loading)
681
+ if line_loading
682
+ else 0,
683
+ }
684
+
685
+ trafo_loading = [
686
+ trafo.loading_percent for trafo in self.network.transformers
687
+ ]
688
+ if trafo_loading:
689
+ metrics["trafo_loading"] = {
690
+ "min": min(trafo_loading),
691
+ "max": max(trafo_loading),
692
+ "mean": sum(trafo_loading) / len(trafo_loading)
693
+ if trafo_loading
694
+ else 0,
695
+ }
696
+
697
+ # Add loss metrics
698
+ losses = self.get_losses()
699
+ metrics["losses"] = losses
700
+
701
+ return metrics
702
+
703
+ def create_topology_graph(self) -> Any:
704
+ """
705
+ Create a NetworkX graph representing the network topology.
706
+
707
+ Returns:
708
+ NetworkX graph object
709
+ """
710
+ if not self.network:
711
+ raise ValueError("No network loaded")
712
+
713
+ # Create undirected graph
714
+ G = nx.Graph()
715
+
716
+ # Add buses as nodes
717
+ for bus in self.network.buses:
718
+ G.add_node(
719
+ bus.id, type="bus", voltage=bus.nominal_voltage / 1000.0, name=bus.name
720
+ )
721
+
722
+ # Add lines as edges
723
+ for line in self.network.lines:
724
+ G.add_edge(
725
+ line.from_bus.id,
726
+ line.to_bus.id,
727
+ type="line",
728
+ id=line.id,
729
+ name=line.name,
730
+ )
731
+
732
+ # Add transformers as edges
733
+ for trafo in self.network.transformers:
734
+ G.add_edge(
735
+ trafo.hv_bus.id,
736
+ trafo.lv_bus.id,
737
+ type="transformer",
738
+ id=trafo.id,
739
+ name=trafo.name,
740
+ )
741
+
742
+ return G
743
+
744
+ def get_line_imax(self, line_type):
745
+ """
746
+ Fetches and returns the maximum intensity for a given line type.
747
+
748
+ :param line_type: Specifies the type of line for which the maximum value is to be retrieved.
749
+ This is used to identify the line category and retrieve its corresponding maximum value.
750
+ :type line_type: str
751
+ :return: The maximum intensity associated with the specified line type.
752
+ :rtype: float
753
+ """
754
+ try:
755
+ line_std_type = self.network.get_line_type(line_type)
756
+ if line_std_type is None:
757
+ raise ValueError(f"Line type '{line_type}' not found in standard types")
758
+ return line_std_type.max_i_a
759
+ except Exception as e:
760
+ self.logger.error(f"Failed to get line imax: {str(e)}")
761
+ raise
762
+
763
+ def get_line_type(self, line_id: str) -> str:
764
+ """
765
+ Returns the type of a line based on the provided line ID.
766
+
767
+ Parameters
768
+ ----------
769
+ line_id : str
770
+ The unique identifier (name) of the line
771
+
772
+ Returns
773
+ -------
774
+ str
775
+ The standard type of the line
776
+
777
+ Raises
778
+ ------
779
+ ValueError
780
+ If the network is not initialized or if the line is not found
781
+ """
782
+ if self.network is None:
783
+ raise ValueError("Network not initialized. Create or load a network first.")
784
+
785
+ try:
786
+ line = self.network.get_line_by_id(line_id)
787
+ if line is None:
788
+ raise ValueError(f"Line with ID '{line_id}' not found in the network")
789
+ return line.type
790
+ except Exception as e:
791
+ self.logger.error(f"Failed to get line type: {str(e)}")
792
+ raise
793
+
794
+ def get_line_length(self, line_id: int | str) -> float:
795
+ """
796
+ Get the length of a line by its ID.
797
+
798
+ Parameters
799
+ ----------
800
+ line_id : Union[int, str]
801
+ The ID of the line
802
+
803
+ Returns
804
+ -------
805
+ float
806
+ The length of the line in kilometers
807
+
808
+ Raises
809
+ ------
810
+ ValueError
811
+ If the network is not initialized or if the line is not found
812
+ """
813
+ if self.network is None:
814
+ raise ValueError("Network not initialized. Create or load a network first.")
815
+
816
+ try:
817
+ line = self.network.get_line_by_id(line_id)
818
+ if line is None:
819
+ raise ValueError(f"Line with ID '{line_id}' not found in the network")
820
+ return line.length
821
+ except Exception as e:
822
+ self.logger.error(f"Failed to get line length: {str(e)}")
823
+ raise
824
+
825
+ def get_transformer_type(self, transformer_id: str) -> str:
826
+ """
827
+ Returns the type of a transformer based on the provided transformer ID.
828
+
829
+ Parameters
830
+ ----------
831
+ transformer_id : str
832
+ The unique identifier (name) of the transformer
833
+
834
+ Returns
835
+ -------
836
+ str
837
+ The standard type of the transformer
838
+
839
+ Raises
840
+ ------
841
+ ValueError
842
+ If the network is not initialized or if the transformer is not found
843
+ """
844
+ if self.network is None:
845
+ raise ValueError("Network not initialized. Create or load a network first.")
846
+
847
+ try:
848
+ transformer = self.network.get_transformer_by_id(transformer_id)
849
+ if transformer is None:
850
+ raise ValueError(
851
+ f"Transformer with ID '{transformer_id}' not found in the network"
852
+ )
853
+ return transformer.type
854
+ except Exception as e:
855
+ self.logger.error(f"Failed to get transformer type: {str(e)}")
856
+ raise
857
+
858
+ def get_transformer_max_power(self, transformer_type: str) -> float:
859
+ """
860
+ Retrieves the maximum power rating of a specified transformer type.
861
+
862
+ This method returns the maximum power rating (in VA) for the requested transformer type
863
+ by looking up the standard type information in the Roseau network model.
864
+
865
+ Parameters
866
+ ----------
867
+ transformer_type : str
868
+ The type of the transformer for which the maximum power rating has to be determined.
869
+
870
+ Returns
871
+ -------
872
+ float
873
+ The maximum power rating for the specified transformer type in VA.
874
+
875
+ Raises
876
+ ------
877
+ ValueError
878
+ If the transformer type is not found in the standard types.
879
+ """
880
+ if self.network is None:
881
+ raise ValueError("Network not initialized. Create or load a network first.")
882
+
883
+ try:
884
+ trafo_std_type = self.network.get_transformer_type(transformer_type)
885
+ if trafo_std_type is None:
886
+ raise ValueError(
887
+ f"Transformer type '{transformer_type}' not found in standard types"
888
+ )
889
+ return trafo_std_type.sn_va
890
+ except Exception as e:
891
+ self.logger.error(f"Failed to get transformer max power: {str(e)}")
892
+ raise
893
+
894
+ def partition_network(self) -> dict[int, Any]:
895
+ """
896
+ Partition the network into galvanically connected components.
897
+
898
+ This method identifies separate electrical areas in the network that are not
899
+ connected to each other by power lines or other conducting elements, but can
900
+ be connected by transformers.
901
+
902
+ Returns:
903
+ Dictionary mapping component IDs to lists of elements (buses, lines, etc.)
904
+ in each connected component.
905
+ """
906
+ if not self.network:
907
+ raise ValueError("No network loaded")
908
+
909
+ # Create an undirected graph of the network without transformers
910
+ G = nx.Graph()
911
+
912
+ # Add buses as nodes
913
+ for bus in self.network.buses:
914
+ G.add_node(bus.id, name=bus.name)
915
+
916
+ # Add lines as edges (galvanic connections)
917
+ for line in self.network.lines:
918
+ G.add_edge(line.from_bus.id, line.to_bus.id)
919
+
920
+ # Find connected components in the graph
921
+ connected_components = list(nx.connected_components(G))
922
+
923
+ # Create the result dictionary
924
+ result = {}
925
+
926
+ for i, component in enumerate(connected_components):
927
+ component_id = i + 1 # Start component IDs from 1
928
+
929
+ # Get bus IDs in this component
930
+ bus_ids = list(component)
931
+
932
+ # Get bus names
933
+ bus_names = [self.network.get_bus_by_id(bus_id).name for bus_id in bus_ids]
934
+
935
+ # Find lines within this component
936
+ component_lines = []
937
+ for line in self.network.lines:
938
+ if line.from_bus.id in component and line.to_bus.id in component:
939
+ component_lines.append(line.name)
940
+
941
+ # Find transformers connecting to this component
942
+ component_transformers = []
943
+ for trafo in self.network.transformers:
944
+ if trafo.lv_bus.id in component:
945
+ component_transformers.append(trafo.name)
946
+
947
+ # Find loads in this component
948
+ component_loads = []
949
+ for load in self.network.loads:
950
+ if load.bus.id in component:
951
+ component_loads.append(load.name)
952
+
953
+ # Find generators in this component
954
+ component_generators = []
955
+ for gen in self.network.generators:
956
+ if gen.bus.id in component:
957
+ component_generators.append(gen.name)
958
+
959
+ # Add component to result
960
+ result[component_id] = {
961
+ "buses": bus_names,
962
+ "lines": component_lines,
963
+ "transformers": component_transformers,
964
+ "loads": component_loads,
965
+ "generators": component_generators,
966
+ }
967
+
968
+ self.logger.info(
969
+ f"Network partitioned into {len(result)} galvanically connected components"
970
+ )
971
+ self.network_partition = result
972
+ return result
973
+
974
+ def get_voltage_magnitude_range(self, component_id: int) -> dict[str, float]:
975
+ """
976
+ Get the minimum and maximum voltage magnitudes in a specific network component.
977
+
978
+ This method determines the voltage magnitude bounds within a given network
979
+ component identified by its component_id.
980
+
981
+ Parameters
982
+ ----------
983
+ component_id : int
984
+ The ID of the component to analyze
985
+
986
+ Returns
987
+ -------
988
+ Dict[str, float]
989
+ Dictionary containing 'min' and 'max' voltage magnitude values in per unit
990
+
991
+ Raises
992
+ ------
993
+ ValueError
994
+ If the network is not initialized, power flow hasn't been run,
995
+ or if the component ID is invalid
996
+ """
997
+ if self.network is None:
998
+ raise ValueError("Network not initialized. Create or load a network first.")
999
+
1000
+ if not self.latest_results or not self.latest_results.get("converged", False):
1001
+ raise ValueError(
1002
+ "Need a converged power flow solution to get voltage magnitudes"
1003
+ )
1004
+
1005
+ if self.network_partition is None:
1006
+ self.logger.info("Network not yet partitioned. Partitioning now.")
1007
+ self.partition_network()
1008
+
1009
+ if component_id not in self.network_partition:
1010
+ raise ValueError(
1011
+ f"Component ID {component_id} not found in network partition"
1012
+ )
1013
+
1014
+ # Get all bus names in the component
1015
+ component_buses = self.network_partition[component_id]["buses"]
1016
+
1017
+ if not component_buses:
1018
+ raise ValueError(f"No buses found in component {component_id}")
1019
+
1020
+ # Get voltage magnitudes for these buses
1021
+ voltage_magnitudes = []
1022
+ for bus_name in component_buses:
1023
+ bus = self.network.get_bus_by_name(bus_name)
1024
+ if bus is not None:
1025
+ voltage_magnitudes.append(bus.vm_pu)
1026
+
1027
+ if not voltage_magnitudes:
1028
+ raise ValueError(
1029
+ f"No voltage magnitudes found for component {component_id}"
1030
+ )
1031
+
1032
+ # Return min and max values
1033
+ return {
1034
+ "min": min(voltage_magnitudes),
1035
+ "max": max(voltage_magnitudes),
1036
+ }
1037
+
1038
+ def get_transformer_tap_positions(self, transformer_id: int | str) -> np.ndarray:
1039
+ """
1040
+ Get all available tap positions for a given transformer in per unit voltage values.
1041
+
1042
+ This method returns all possible tap positions that can be set for the specified
1043
+ transformer, expressed as per unit voltage values (e.g., [-0.05, -0.025, 0, 0.025, 0.05]).
1044
+
1045
+ Parameters
1046
+ ----------
1047
+ transformer_id : Union[int, str]
1048
+ The ID of the transformer to get tap positions for
1049
+
1050
+ Returns
1051
+ -------
1052
+ numpy.ndarray
1053
+ Array of all available tap positions as per unit voltage values,
1054
+ typically sorted from lowest to highest
1055
+
1056
+ Raises
1057
+ ------
1058
+ ValueError
1059
+ If the transformer does not exist or if tap positions cannot be determined
1060
+ """
1061
+ if self.network is None:
1062
+ raise ValueError("Network not initialized. Create or load a network first.")
1063
+
1064
+ try:
1065
+ # Find the transformer by ID
1066
+ transformer = self.network.get_transformer_by_id(transformer_id)
1067
+ if transformer is None:
1068
+ raise ValueError(
1069
+ f"Transformer with ID '{transformer_id}' not found in the network"
1070
+ )
1071
+
1072
+ # Get transformer parameters related to tap changing
1073
+ tap_min = transformer.tap_min
1074
+ tap_max = transformer.tap_max
1075
+ tap_step_percent = transformer.tap_step_percent
1076
+ tap_neutral = transformer.tap_neutral
1077
+ tap_side = transformer.tap_side
1078
+
1079
+ # Create numpy array of all possible tap positions
1080
+ tap_positions = np.arange(int(tap_min), int(tap_max) + 1)
1081
+
1082
+ # Calculate per unit voltage change for each tap position
1083
+ step_pu = tap_step_percent / 100.0
1084
+ voltage_pu_changes = (tap_positions - tap_neutral) * step_pu
1085
+
1086
+ # For tap changer on the HV side, the voltage effect is inverted
1087
+ # when viewed from the LV side
1088
+ if tap_side == "hv":
1089
+ voltage_pu_changes = -voltage_pu_changes
1090
+
1091
+ # Round to avoid floating point precision issues
1092
+ return np.round(voltage_pu_changes, 6)
1093
+
1094
+ except Exception as e:
1095
+ self.logger.error(f"Failed to get transformer tap positions: {str(e)}")
1096
+ raise ValueError(
1097
+ f"Error retrieving tap positions for transformer '{transformer_id}': {str(e)}"
1098
+ )
1099
+
1100
+ def get_component_id_for_bus(self, bus_id: int | str) -> int:
1101
+ """
1102
+ Get the component ID for a given bus.
1103
+
1104
+ This method determines which galvanically connected component a bus belongs to.
1105
+
1106
+ Parameters
1107
+ ----------
1108
+ bus_id : Union[int, str]
1109
+ The ID or name of the bus
1110
+
1111
+ Returns
1112
+ -------
1113
+ int
1114
+ The component ID that the bus belongs to
1115
+
1116
+ Raises
1117
+ ------
1118
+ ValueError
1119
+ If the network is not initialized, not partitioned, or if the bus is not found
1120
+ """
1121
+ if self.network is None:
1122
+ raise ValueError("Network not initialized. Create or load a network first.")
1123
+
1124
+ if self.network_partition is None:
1125
+ self.logger.info("Network not yet partitioned. Partitioning now.")
1126
+ self.partition_network()
1127
+
1128
+ # If bus_id is a string (name), find the bus object
1129
+ if isinstance(bus_id, str):
1130
+ bus = self.network.get_bus_by_name(bus_id)
1131
+ if bus is None:
1132
+ raise ValueError(f"Bus with name '{bus_id}' not found in the network")
1133
+ bus_id = bus.id
1134
+
1135
+ # Find the component that contains this bus
1136
+ for component_id, component_data in self.network_partition.items():
1137
+ bus_names = component_data["buses"]
1138
+ for bus_name in bus_names:
1139
+ bus = self.network.get_bus_by_name(bus_name)
1140
+ if bus.id == bus_id:
1141
+ return component_id
1142
+
1143
+ raise ValueError(f"Bus with ID '{bus_id}' not found in any network component")
1144
+
1145
+ def group_violations_by_component(
1146
+ self, violations: list[ConstraintViolation]
1147
+ ) -> dict[int, list[ConstraintViolation]]:
1148
+ """
1149
+ Group constraint violations by network component.
1150
+
1151
+ This method organizes violations based on which galvanically connected
1152
+ component they belong to, which is useful for targeted remediation strategies.
1153
+
1154
+ Parameters
1155
+ ----------
1156
+ violations : List[ConstraintViolation]
1157
+ List of constraint violations to group
1158
+
1159
+ Returns
1160
+ -------
1161
+ Dict[int, List[ConstraintViolation]]
1162
+ Dictionary mapping component IDs to lists of violations in that component
1163
+
1164
+ Raises
1165
+ ------
1166
+ ValueError
1167
+ If the network is not initialized or not partitioned
1168
+ """
1169
+ if self.network is None:
1170
+ raise ValueError("Network not initialized. Create or load a network first.")
1171
+
1172
+ if self.network_partition is None:
1173
+ self.logger.info("Network not yet partitioned. Partitioning now.")
1174
+ self.partition_network()
1175
+
1176
+ # Initialize result dictionary
1177
+ result = {}
1178
+
1179
+ # Process each violation
1180
+ for violation in violations:
1181
+ component_id = None
1182
+
1183
+ # Determine which component this violation belongs to
1184
+ if violation.element_type == "bus":
1185
+ # For bus violations, find the component directly
1186
+ try:
1187
+ component_id = self.get_component_id_for_bus(violation.element_id)
1188
+ except ValueError:
1189
+ self.logger.warning(
1190
+ f"Could not determine component for bus violation: {violation.element_id}"
1191
+ )
1192
+ continue
1193
+
1194
+ elif violation.element_type == "line":
1195
+ # For line violations, find the component based on the from_bus
1196
+ try:
1197
+ line = self.network.get_line_by_name(violation.element_id)
1198
+ if line is None:
1199
+ self.logger.warning(
1200
+ f"Line not found for violation: {violation.element_id}"
1201
+ )
1202
+ continue
1203
+ component_id = self.get_component_id_for_bus(line.from_bus.id)
1204
+ except ValueError:
1205
+ self.logger.warning(
1206
+ f"Could not determine component for line violation: {violation.element_id}"
1207
+ )
1208
+ continue
1209
+
1210
+ elif violation.element_type == "transformer":
1211
+ # For transformer violations, find the component based on the lv_bus
1212
+ try:
1213
+ transformer = self.network.get_transformer_by_name(
1214
+ violation.element_id
1215
+ )
1216
+ if transformer is None:
1217
+ self.logger.warning(
1218
+ f"Transformer not found for violation: {violation.element_id}"
1219
+ )
1220
+ continue
1221
+ component_id = self.get_component_id_for_bus(transformer.lv_bus.id)
1222
+ except ValueError:
1223
+ self.logger.warning(
1224
+ f"Could not determine component for transformer violation: {violation.element_id}"
1225
+ )
1226
+ continue
1227
+
1228
+ # Add violation to the appropriate component group
1229
+ if component_id is not None:
1230
+ if component_id not in result:
1231
+ result[component_id] = []
1232
+ result[component_id].append(violation)
1233
+
1234
+ return result