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,527 @@
1
+ """
2
+ GridLab-D engine implementation for power flow analysis in GridForge.
3
+ """
4
+
5
+ import os
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+
11
+ from gridforge.core.constraints import ConstraintViolation
12
+ from gridforge.core.power_flow import PowerFlowEngine
13
+ from gridforge.utils.logging import logger
14
+
15
+
16
+ class GridLabDEngine(PowerFlowEngine):
17
+ """
18
+ Interface to GridLab-D for power flow calculations and network analysis.
19
+
20
+ This engine provides methods to:
21
+ 1. Load network models
22
+ 2. Run power flow calculations
23
+ 3. Apply network modifications
24
+ 4. Check constraint violations
25
+ 5. Extract results and metrics
26
+ """
27
+
28
+ def __init__(self, config: dict[str, Any] | None = None):
29
+ """
30
+ Initialize GridLab-D engine.
31
+
32
+ Args:
33
+ config: Configuration dictionary with GridLab-D specific settings
34
+ """
35
+ super().__init__(config)
36
+ self.network = None
37
+ self.config = config or {}
38
+ self.logger = logger
39
+ self.logger.info("Initialized GridLab-D engine")
40
+
41
+ # Default power flow settings
42
+ self.pf_settings = {
43
+ "algorithm": "nr", # Newton-Raphson
44
+ "max_iteration": 20,
45
+ "tolerance_mva": 1e-8,
46
+ }
47
+
48
+ # Update with user settings if provided
49
+ if "pf_settings" in self.config:
50
+ self.pf_settings.update(self.config["pf_settings"])
51
+
52
+ self.latest_results = None
53
+
54
+ def create_empty_network(
55
+ self, name: str = "gridforge_network", f_hz: float = 50.0
56
+ ) -> None:
57
+ """
58
+ Create an empty GridLab-D network.
59
+
60
+ Args:
61
+ name: Name of the network
62
+ f_hz: System frequency in Hz
63
+ """
64
+ # GridLab-D doesn't have a direct "create empty network" API in the same way
65
+ # We'll initialize an internal structure to hold the model
66
+ self.network = {"name": name, "frequency": f_hz, "objects": []}
67
+ self.logger.info(f"Created empty network: {name}")
68
+
69
+ def load_network(self, source: str | dict) -> None:
70
+ """
71
+ Load a network from file or dictionary.
72
+
73
+ Args:
74
+ source: Path to network file (.glm) or network dictionary
75
+ """
76
+ self.logger.info("Loading network")
77
+
78
+ if isinstance(source, str):
79
+ if source.endswith(".glm"):
80
+ # Parse GLM file (simplified implementation)
81
+ self.network = self._parse_glm(source)
82
+ else:
83
+ raise ValueError(f"Unsupported file format: {source}")
84
+
85
+ elif isinstance(source, dict):
86
+ self.network = source
87
+
88
+ else:
89
+ raise TypeError("Source must be a file path or network dictionary")
90
+
91
+ self.logger.info(
92
+ f"Loaded network with {len(self.network.get('objects', []))} objects"
93
+ )
94
+
95
+ def save_network(self, target: str) -> None:
96
+ """
97
+ Save the current network to a file.
98
+
99
+ Args:
100
+ target: Path where to save the network (.glm)
101
+ """
102
+ if not self.network:
103
+ raise ValueError("No network loaded to save")
104
+
105
+ if target.endswith(".glm"):
106
+ self._write_glm(self.network, target)
107
+ else:
108
+ raise ValueError(f"Unsupported file format: {target}")
109
+
110
+ self.logger.info(f"Network saved to {target}")
111
+
112
+ def run_power_flow(self, warm_start: bool = False) -> dict[str, Any]:
113
+ """
114
+ Run power flow calculation on the current network.
115
+
116
+ Args:
117
+ warm_start: Whether to use warm start (not applicable for GridLab-D CLI)
118
+
119
+ Returns:
120
+ Dictionary with power flow results and statistics
121
+ """
122
+ if not self.network:
123
+ raise ValueError("No network loaded for power flow calculation")
124
+
125
+ self.logger.info("Running power flow calculation")
126
+
127
+ try:
128
+ # Write temporary GLM file
129
+ temp_glm = "temp_simulation.glm"
130
+ self._write_glm(self.network, temp_glm)
131
+
132
+ # Run GridLab-D command
133
+ # This is a placeholder for actual execution logic
134
+ # In a real implementation, we would use subprocess to run 'gridlabd'
135
+ # and parse the output XML or CSV files
136
+
137
+ # Simulate results for now
138
+ self.latest_results = {
139
+ "converged": True,
140
+ "iterations": 10,
141
+ "time": 1.5,
142
+ }
143
+
144
+ self.logger.info(
145
+ f"Power flow calculation finished: converged={self.latest_results['converged']}"
146
+ )
147
+
148
+ # Clean up
149
+ if os.path.exists(temp_glm):
150
+ os.remove(temp_glm)
151
+
152
+ return self.latest_results
153
+
154
+ except Exception as e:
155
+ self.logger.error(f"Power flow calculation failed: {str(e)}")
156
+ raise
157
+
158
+ def check_violations(self) -> list[ConstraintViolation]:
159
+ """
160
+ Check if the network violates specified constraints.
161
+
162
+ Returns:
163
+ List of constraint violations
164
+ """
165
+ if (
166
+ not self.network
167
+ or not self.latest_results
168
+ or not self.latest_results.get("converged", False)
169
+ ):
170
+ raise ValueError("Need a converged power flow solution to check violations")
171
+
172
+ self.logger.info("Checking network constraint violations")
173
+
174
+ violations = []
175
+
176
+ # Placeholder for violation checking logic
177
+ # In a real implementation, we would parse the results and check against limits
178
+
179
+ return violations
180
+
181
+ def analyze_violations(self) -> Any:
182
+ """
183
+ Analyze and summarize network constraint violations.
184
+
185
+ Returns:
186
+ Any: Summary of violations (format depends on implementation).
187
+ """
188
+ return {}
189
+
190
+ def apply_tap_change(self, trafo_id: str, tap_pos_shift: int) -> bool:
191
+ """
192
+ Change the tap position of a transformer.
193
+
194
+ Args:
195
+ trafo_id (str): Name of the transformer.
196
+ tap_pos_shift (int): Number of steps added to the tap position.
197
+
198
+ Returns:
199
+ bool: Always False: this engine does not change tap positions.
200
+ """
201
+ # Placeholder implementation
202
+ return False
203
+
204
+ def upgrade_line(self, line_id: str, new_type: str) -> None:
205
+ """
206
+ Upgrade a line with new parameters.
207
+
208
+ Args:
209
+ line_id (int): ID of the line to upgrade.
210
+ new_type (str): Type of the new line (must exist in standard_types).
211
+ """
212
+ # Placeholder implementation
213
+ pass
214
+
215
+ def add_parallel_line(self, line_id: str) -> int:
216
+ """
217
+ Add a parallel line.
218
+
219
+ Args:
220
+ line_id (int): ID of the line to upgrade.
221
+
222
+ Returns:
223
+ int: Count of parallel lines
224
+ """
225
+ # Placeholder implementation
226
+ return 0
227
+
228
+ def upgrade_transformer(self, trafo_id: str, new_type: str) -> None:
229
+ """
230
+ Upgrade a transformer with new parameters.
231
+
232
+ Args:
233
+ trafo_id (int): ID of the transformer to upgrade.
234
+ new_type (str): Type of the new transformer (must exist in standard_types).
235
+ """
236
+ # Placeholder implementation
237
+ pass
238
+
239
+ def add_parallel_transformer(self, trafo_id: str) -> int:
240
+ """
241
+ Add a parallel transformer.
242
+
243
+ Args:
244
+ trafo_id (int): ID of the transformer to upgrade.
245
+
246
+ Returns:
247
+ int: Count of parallel transformers
248
+ """
249
+ # Placeholder implementation
250
+ return 0
251
+
252
+ def get_losses(self) -> dict[str, float]:
253
+ """
254
+ Calculate network losses.
255
+
256
+ Returns:
257
+ Dict[str, float]: Dictionary with active and reactive power losses.
258
+ """
259
+ return {"p_loss_mw": 0.0, "q_loss_mvar": 0.0}
260
+
261
+ def get_network_metrics(self) -> dict[str, Any]:
262
+ """
263
+ Get various network metrics.
264
+
265
+ Returns:
266
+ Dict[str, Any]: Dictionary with network metrics.
267
+ """
268
+ return {}
269
+
270
+ def create_topology_graph(self) -> Any:
271
+ """
272
+ Create a NetworkX graph representing the network topology.
273
+
274
+ Returns:
275
+ Any: NetworkX graph object.
276
+ """
277
+ return None
278
+
279
+ def get_line_imax(self, line_type) -> float:
280
+ """
281
+ Abstract method for retrieving the maximum current limit of a specified line type.
282
+
283
+ Args:
284
+ line_type (str): The type of the line.
285
+
286
+ Returns:
287
+ float: The maximum current limit (IMAX) for the specified line type.
288
+ """
289
+ return 0.0
290
+
291
+ def get_line_r_ohm_per_km(self, line_type: str) -> float:
292
+ """
293
+ Abstract method for retrieving the resistance per unit length of a specified line type.
294
+
295
+ Args:
296
+ line_type (str): The type of the line.
297
+
298
+ Returns:
299
+ float: The resistance per unit length (Ohm/km).
300
+ """
301
+ return 0.0
302
+
303
+ def get_line_type(self, line_id: str) -> str:
304
+ """
305
+ Abstract method for retrieving the type of a specified line.
306
+
307
+ Args:
308
+ line_id (str): The ID of the line.
309
+
310
+ Returns:
311
+ str: The type of the line.
312
+ """
313
+ return ""
314
+
315
+ def get_line_length(self, line_id: int | str) -> float:
316
+ """
317
+ Get the length of a line by its ID.
318
+
319
+ Args:
320
+ line_id (Union[int, str]): The ID of the line.
321
+
322
+ Returns:
323
+ float: The length of the line in kilometers.
324
+ """
325
+ return 0.0
326
+
327
+ def get_transformer_type(self, transformer_id: str) -> str:
328
+ """
329
+ Abstract method for retrieving the type of a specified transformer.
330
+
331
+ Args:
332
+ transformer_id (str): The ID of the transformer.
333
+
334
+ Returns:
335
+ str: The type of the transformer.
336
+ """
337
+ return ""
338
+
339
+ def get_transformer_max_power(self, transformer_type: str) -> float:
340
+ """
341
+ Abstract method for retrieving the maximum power rating of a specified transformer type.
342
+
343
+ Args:
344
+ transformer_type (str): The type of the transformer.
345
+
346
+ Returns:
347
+ float: The maximum power rating for the specified transformer type.
348
+ """
349
+ return 0.0
350
+
351
+ def partition_network(self) -> dict[int, Any]:
352
+ """
353
+ Partition the network into galvanically connected components.
354
+
355
+ Returns:
356
+ Dict[int, Any]: Dictionary mapping component IDs to lists of elements.
357
+ """
358
+ return {}
359
+
360
+ def get_voltage_magnitude_range(self, component_id: int) -> dict[str, float]:
361
+ """
362
+ Get the minimum and maximum voltage magnitudes in a specific network component.
363
+
364
+ Args:
365
+ component_id (int): The ID of the component to analyze.
366
+
367
+ Returns:
368
+ Dict[str, float]: Dictionary containing 'min' and 'max' voltage magnitude values in per unit.
369
+ """
370
+ return {"min": 0.0, "max": 0.0}
371
+
372
+ def get_transformer_tap_positions(self, transformer_id: int | str) -> np.ndarray:
373
+ """
374
+ Get all available tap positions for a given transformer in per unit voltage values.
375
+
376
+ Args:
377
+ transformer_id (Union[int, str]): The ID of the transformer.
378
+
379
+ Returns:
380
+ np.ndarray: Array of all available tap positions as per unit voltage values.
381
+ """
382
+ return np.array([])
383
+
384
+ def calculate_voltage_line_resistance_sensitivities(
385
+ self, line_names: list[str] | None = None
386
+ ) -> dict[str, np.ndarray]:
387
+ """
388
+ Calculate the sensitivities of bus voltages to line impedance changes.
389
+
390
+ Returns:
391
+ Dict[str, np.ndarray]: Dictionary mapping line IDs to arrays of sensitivity values.
392
+ """
393
+ return {}
394
+
395
+ def get_flexibility_data(self, element_type: str) -> pd.DataFrame:
396
+ """
397
+ Get flexibility data for loads or static generators.
398
+
399
+ Args:
400
+ element_type (str): 'load' or 'sgen'.
401
+
402
+ Returns:
403
+ pd.DataFrame: DataFrame with columns ['name', 'bus', 'p_mw', 'max_flex_pct'].
404
+ """
405
+ return pd.DataFrame()
406
+
407
+ def apply_flexibility_action(
408
+ self,
409
+ element_type: str,
410
+ element_index: int,
411
+ new_p_mw: float,
412
+ new_q_mvar: float | None = None,
413
+ ) -> None:
414
+ """
415
+ Apply a flexibility action (change active power) to an element.
416
+
417
+ Args:
418
+ element_type (str): 'load' or 'sgen'.
419
+ element_index (int): Index of the element.
420
+ new_p_mw (float): New active power value in MW.
421
+ new_q_mvar (Optional[float], optional): New reactive power of a load, in MVAr.
422
+ """
423
+ pass
424
+
425
+ def calculate_voltage_power_sensitivities(
426
+ self, buses: list[str] | None = None
427
+ ) -> pd.DataFrame:
428
+ """
429
+ Calculate the sensitivities of bus voltage magnitudes to active power injections.
430
+
431
+ Returns:
432
+ pd.DataFrame: DataFrame where index and columns are bus names.
433
+ """
434
+ return pd.DataFrame()
435
+
436
+ def analyze_thermal_violation(
437
+ self, element_type: str, element_id: str
438
+ ) -> dict[str, Any]:
439
+ """
440
+ Analyze a thermal violation to determine downstream topology and flow conditions.
441
+
442
+ Args:
443
+ element_type (str): "Line" or "Transformer".
444
+ element_id (str): Name of the element.
445
+
446
+ Returns:
447
+ Dict[str, Any]: Dictionary containing analysis results.
448
+ """
449
+ return {}
450
+
451
+ def calculate_branch_loading_sensitivities(
452
+ self, element_type: str, element_name: str
453
+ ) -> pd.Series:
454
+ """
455
+ Calculate sensitivity of a branch's loading (current) to active power injections.
456
+
457
+ Args:
458
+ element_type (str): "Line" or "Transformer".
459
+ element_name (str): Name of the element.
460
+
461
+ Returns:
462
+ pd.Series: Series with index=bus_names and values = d(Loading_pct)/d(P_mw).
463
+ """
464
+ return pd.Series()
465
+
466
+ # Helper methods for GLM parsing/writing
467
+ def _parse_glm(self, file_path: str) -> dict[str, Any]:
468
+ """Parse a GLM file into a dictionary structure."""
469
+ # Simplified parser
470
+ return {"objects": []}
471
+
472
+ def _write_glm(self, network: dict[str, Any], file_path: str) -> None:
473
+ """Write a network dictionary to a GLM file."""
474
+ # Simplified writer
475
+ with open(file_path, "w") as f:
476
+ f.write("// Generated by GridForge\n")
477
+ # Write objects...
478
+
479
+ # Implement abstract methods from PowerFlowEngine
480
+ def create_bus(self, name: str, nominal_voltage_v: float, **kwargs: Any) -> int:
481
+ return 0
482
+
483
+ def create_load(
484
+ self,
485
+ bus_name: int,
486
+ name: str,
487
+ active_power_w: float,
488
+ reactive_power_var: float,
489
+ **kwargs: Any,
490
+ ) -> int:
491
+ return 0
492
+
493
+ def create_generator(
494
+ self,
495
+ bus_name: str,
496
+ name: str,
497
+ active_power_w: float,
498
+ reactive_power_var: float,
499
+ **kwargs: Any,
500
+ ) -> int:
501
+ return 0
502
+
503
+ def create_line(
504
+ self,
505
+ name: str,
506
+ from_bus: str,
507
+ to_bus: str,
508
+ length_km: float,
509
+ line_type: str,
510
+ **kwargs: Any,
511
+ ) -> int:
512
+ return 0
513
+
514
+ def create_ext_grid(
515
+ self,
516
+ bus_name: str,
517
+ name: str,
518
+ voltage_reference_pu: float,
519
+ angle_reference_degree: float = 0,
520
+ **kwargs: Any,
521
+ ) -> int:
522
+ return 0
523
+
524
+ def create_transformer(
525
+ self, name: str, hv_bus: str, lv_bus: str, transformer_type: str, **kwargs: Any
526
+ ) -> int:
527
+ return 0