distgridforge 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- distgridforge-0.3.0.dist-info/METADATA +266 -0
- distgridforge-0.3.0.dist-info/RECORD +38 -0
- distgridforge-0.3.0.dist-info/WHEEL +5 -0
- distgridforge-0.3.0.dist-info/licenses/LICENCE.txt +21 -0
- distgridforge-0.3.0.dist-info/top_level.txt +1 -0
- gridforge/__init__.py +32 -0
- gridforge/case_study/config.py +158 -0
- gridforge/case_study/dickert_lv_network_script.py +109 -0
- gridforge/case_study/mv_lv_feeder.py +314 -0
- gridforge/case_study/simbench_network_test_case.py +168 -0
- gridforge/core/__init__.py +0 -0
- gridforge/core/constraints.py +421 -0
- gridforge/core/cost_model.py +363 -0
- gridforge/core/grid_enhancement.py +1932 -0
- gridforge/core/power_flow.py +1146 -0
- gridforge/core/strategy.py +297 -0
- gridforge/engines/__init__.py +0 -0
- gridforge/engines/gridlabd_engine.py +527 -0
- gridforge/engines/opendss_engine.py +885 -0
- gridforge/engines/pandapower_engine.py +3766 -0
- gridforge/engines/roseau_engine.py +1234 -0
- gridforge/examples/__init__.py +0 -0
- gridforge/examples/quick_start.py +85 -0
- gridforge/main.py +0 -0
- gridforge/strategies/__init__.py +0 -0
- gridforge/strategies/flexibility.py +1476 -0
- gridforge/strategies/line_upgrade.py +1846 -0
- gridforge/strategies/path_to_source.py +596 -0
- gridforge/strategies/sizing.py +210 -0
- gridforge/strategies/step_check.py +183 -0
- gridforge/strategies/tap_change.py +267 -0
- gridforge/strategies/transformer_upgrade.py +622 -0
- gridforge/utils/__init__.py +0 -0
- gridforge/utils/config.py +55 -0
- gridforge/utils/interactive_plot.py +700 -0
- gridforge/utils/logging.py +86 -0
- gridforge/utils/plot.py +1078 -0
- gridforge/utils/reporting.py +0 -0
|
@@ -0,0 +1,885 @@
|
|
|
1
|
+
"""
|
|
2
|
+
OpenDSS engine implementation for power flow analysis in GridForge.
|
|
3
|
+
|
|
4
|
+
This module provides an interface to OpenDSS via the OpenDSSDirect.py package
|
|
5
|
+
for detailed distribution system modeling and analysis.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import opendssdirect as dss
|
|
13
|
+
|
|
14
|
+
from gridforge.core.constraints import NetworkConstraints
|
|
15
|
+
from gridforge.utils.logging import logger
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class OpenDSSEngine:
|
|
19
|
+
"""
|
|
20
|
+
Interface to OpenDSS for distribution power flow calculations and network analysis.
|
|
21
|
+
|
|
22
|
+
This engine provides methods to:
|
|
23
|
+
1. Load DSS network models
|
|
24
|
+
2. Run power flow calculations
|
|
25
|
+
3. Apply network modifications
|
|
26
|
+
4. Check constraint violations
|
|
27
|
+
5. Extract results and metrics
|
|
28
|
+
|
|
29
|
+
OpenDSS is particularly suited for distribution system analysis,
|
|
30
|
+
including detailed modeling of unbalanced systems and time-series analysis.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, config: dict[str, Any] | None = None):
|
|
34
|
+
"""
|
|
35
|
+
Initialize OpenDSS engine.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
config: Configuration dictionary with OpenDSS specific settings
|
|
39
|
+
"""
|
|
40
|
+
self.config = config or {}
|
|
41
|
+
self.logger = logger
|
|
42
|
+
self.logger.info("Initialized OpenDSS engine")
|
|
43
|
+
|
|
44
|
+
# Default settings
|
|
45
|
+
self.settings = {
|
|
46
|
+
"max_iterations": 15,
|
|
47
|
+
"max_control_iterations": 10,
|
|
48
|
+
"tolerance": 0.0001,
|
|
49
|
+
"solution_mode": "snap", # 'snap', 'yearly', 'daily', 'duty'
|
|
50
|
+
"algorithm": "normal", # 'normal', 'newton'
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
# Update with user settings if provided
|
|
54
|
+
if "dss_settings" in self.config:
|
|
55
|
+
self.settings.update(self.config["dss_settings"])
|
|
56
|
+
|
|
57
|
+
# Flag for circuit loaded status
|
|
58
|
+
self.circuit_loaded = False
|
|
59
|
+
self.latest_results = None
|
|
60
|
+
|
|
61
|
+
def clear(self) -> None:
|
|
62
|
+
"""
|
|
63
|
+
Clear the OpenDSS environment.
|
|
64
|
+
"""
|
|
65
|
+
dss.run_command("Clear")
|
|
66
|
+
self.circuit_loaded = False
|
|
67
|
+
self.logger.info("OpenDSS environment cleared")
|
|
68
|
+
|
|
69
|
+
def load_network(self, master_file: str) -> None:
|
|
70
|
+
"""
|
|
71
|
+
Load a network from DSS master file.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
master_file: Path to the OpenDSS master file (.dss)
|
|
75
|
+
"""
|
|
76
|
+
self.logger.info(f"Loading OpenDSS network from {master_file}")
|
|
77
|
+
|
|
78
|
+
if not os.path.exists(master_file):
|
|
79
|
+
raise FileNotFoundError(f"DSS master file not found: {master_file}")
|
|
80
|
+
|
|
81
|
+
try:
|
|
82
|
+
# Clear any existing circuit
|
|
83
|
+
self.clear()
|
|
84
|
+
|
|
85
|
+
# Load the DSS file
|
|
86
|
+
dss.run_command(f"Redirect '{master_file}'")
|
|
87
|
+
|
|
88
|
+
if not dss.Circuit.Name():
|
|
89
|
+
raise ValueError("Failed to load DSS circuit")
|
|
90
|
+
|
|
91
|
+
self.circuit_loaded = True
|
|
92
|
+
|
|
93
|
+
# Get circuit summary
|
|
94
|
+
nodes = dss.Circuit.NumNodes()
|
|
95
|
+
buses = dss.Circuit.NumBuses()
|
|
96
|
+
elements = dss.Circuit.NumCktElements()
|
|
97
|
+
|
|
98
|
+
self.logger.info(
|
|
99
|
+
f"Loaded DSS circuit: {dss.Circuit.Name()} with "
|
|
100
|
+
f"{buses} buses, {nodes} nodes, and {elements} elements"
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
except Exception as e:
|
|
104
|
+
self.logger.error(f"Error loading DSS circuit: {str(e)}")
|
|
105
|
+
raise
|
|
106
|
+
|
|
107
|
+
def save_network(
|
|
108
|
+
self, output_folder: str, base_name: str = "exported_circuit"
|
|
109
|
+
) -> None:
|
|
110
|
+
"""
|
|
111
|
+
Save the current network to DSS files.
|
|
112
|
+
|
|
113
|
+
Args:
|
|
114
|
+
output_folder: Folder where to save the DSS files
|
|
115
|
+
base_name: Base name for the exported files
|
|
116
|
+
"""
|
|
117
|
+
if not self.circuit_loaded:
|
|
118
|
+
raise ValueError("No circuit loaded to save")
|
|
119
|
+
|
|
120
|
+
try:
|
|
121
|
+
# Create output folder if it doesn't exist
|
|
122
|
+
os.makedirs(output_folder, exist_ok=True)
|
|
123
|
+
|
|
124
|
+
# Create master file path
|
|
125
|
+
master_file = os.path.join(output_folder, f"{base_name}_master.dss")
|
|
126
|
+
|
|
127
|
+
# Save the circuit
|
|
128
|
+
dss.run_command(f"Save Circuit dir='{output_folder}' file='{base_name}'")
|
|
129
|
+
|
|
130
|
+
self.logger.info(f"Circuit saved to {output_folder}")
|
|
131
|
+
|
|
132
|
+
return master_file
|
|
133
|
+
|
|
134
|
+
except Exception as e:
|
|
135
|
+
self.logger.error(f"Error saving DSS circuit: {str(e)}")
|
|
136
|
+
raise
|
|
137
|
+
|
|
138
|
+
def _configure_solution(self) -> None:
|
|
139
|
+
"""
|
|
140
|
+
Configure the OpenDSS solution parameters based on settings.
|
|
141
|
+
"""
|
|
142
|
+
# Set solution parameters
|
|
143
|
+
dss.Solution.MaxIterations(self.settings["max_iterations"])
|
|
144
|
+
dss.Solution.MaxControlIterations(self.settings["max_control_iterations"])
|
|
145
|
+
dss.Solution.Convergence(self.settings["tolerance"])
|
|
146
|
+
|
|
147
|
+
# Set solution algorithm
|
|
148
|
+
if self.settings["algorithm"].lower() == "newton":
|
|
149
|
+
dss.Solution.Algorithm(1) # Newton's method
|
|
150
|
+
else:
|
|
151
|
+
dss.Solution.Algorithm(0) # Normal algorithm
|
|
152
|
+
|
|
153
|
+
# Set solution mode
|
|
154
|
+
mode_map = {"snap": 0, "daily": 1, "yearly": 2, "duty": 3}
|
|
155
|
+
|
|
156
|
+
if self.settings["solution_mode"].lower() in mode_map:
|
|
157
|
+
dss.Solution.Mode(mode_map[self.settings["solution_mode"].lower()])
|
|
158
|
+
else:
|
|
159
|
+
dss.Solution.Mode(0) # Default to snapshot mode
|
|
160
|
+
|
|
161
|
+
def run_power_flow(self) -> dict[str, Any]:
|
|
162
|
+
"""
|
|
163
|
+
Run power flow calculation on the current network.
|
|
164
|
+
|
|
165
|
+
Returns:
|
|
166
|
+
Dictionary with power flow results and statistics
|
|
167
|
+
"""
|
|
168
|
+
if not self.circuit_loaded:
|
|
169
|
+
raise ValueError("No circuit loaded for power flow calculation")
|
|
170
|
+
|
|
171
|
+
self.logger.info("Running OpenDSS power flow calculation")
|
|
172
|
+
|
|
173
|
+
try:
|
|
174
|
+
# Configure solution parameters
|
|
175
|
+
self._configure_solution()
|
|
176
|
+
|
|
177
|
+
# Solve the circuit
|
|
178
|
+
dss.Solution.Solve()
|
|
179
|
+
|
|
180
|
+
# Check convergence
|
|
181
|
+
converged = dss.Solution.Converged()
|
|
182
|
+
|
|
183
|
+
# Gather solution statistics
|
|
184
|
+
iterations = dss.Solution.Iterations()
|
|
185
|
+
total_iterations = dss.Solution.TotalIterations()
|
|
186
|
+
|
|
187
|
+
# Store results for later use
|
|
188
|
+
self.latest_results = {
|
|
189
|
+
"converged": converged,
|
|
190
|
+
"iterations": iterations,
|
|
191
|
+
"total_iterations": total_iterations,
|
|
192
|
+
"algorithm": "Newton" if dss.Solution.Algorithm() == 1 else "Normal",
|
|
193
|
+
"solution_mode": dss.Solution.Mode(),
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
status_msg = "converged" if converged else "did not converge"
|
|
197
|
+
self.logger.info(
|
|
198
|
+
f"Power flow calculation {status_msg} after {iterations} iterations"
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
return self.latest_results
|
|
202
|
+
|
|
203
|
+
except Exception as e:
|
|
204
|
+
self.logger.error(f"Power flow calculation failed: {str(e)}")
|
|
205
|
+
raise
|
|
206
|
+
|
|
207
|
+
def check_violations(self, constraints: NetworkConstraints) -> dict[str, Any]:
|
|
208
|
+
"""
|
|
209
|
+
Check if the network violates specified constraints.
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
constraints: NetworkConstraints object with limits
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
Dictionary with constraint violations
|
|
216
|
+
"""
|
|
217
|
+
if (
|
|
218
|
+
not self.circuit_loaded
|
|
219
|
+
or not self.latest_results
|
|
220
|
+
or not self.latest_results.get("converged", False)
|
|
221
|
+
):
|
|
222
|
+
raise ValueError("Need a converged power flow solution to check violations")
|
|
223
|
+
|
|
224
|
+
self.logger.info("Checking network constraint violations")
|
|
225
|
+
|
|
226
|
+
violations = {"voltage": [], "loading": [], "total_violations": 0}
|
|
227
|
+
|
|
228
|
+
# Check voltage violations
|
|
229
|
+
if hasattr(constraints, "v_min") and hasattr(constraints, "v_max"):
|
|
230
|
+
v_violations = self._check_voltage_violations(
|
|
231
|
+
constraints.v_min, constraints.v_max
|
|
232
|
+
)
|
|
233
|
+
violations["voltage"] = v_violations
|
|
234
|
+
violations["total_violations"] += len(v_violations)
|
|
235
|
+
|
|
236
|
+
# Check line and transformer loading violations
|
|
237
|
+
if hasattr(constraints, "loading_max"):
|
|
238
|
+
l_violations = self._check_loading_violations(constraints.loading_max)
|
|
239
|
+
violations["loading"] = l_violations
|
|
240
|
+
violations["total_violations"] += len(l_violations)
|
|
241
|
+
|
|
242
|
+
self.logger.info(
|
|
243
|
+
f"Found {violations['total_violations']} constraint violations: "
|
|
244
|
+
f"{len(violations['voltage'])} voltage, {len(violations['loading'])} loading"
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
return violations
|
|
248
|
+
|
|
249
|
+
def _check_voltage_violations(self, v_min: float, v_max: float) -> list[dict]:
|
|
250
|
+
"""
|
|
251
|
+
Check for voltage violations in the network.
|
|
252
|
+
|
|
253
|
+
Args:
|
|
254
|
+
v_min: Minimum allowed per unit voltage
|
|
255
|
+
v_max: Maximum allowed per unit voltage
|
|
256
|
+
|
|
257
|
+
Returns:
|
|
258
|
+
List of voltage violations with details
|
|
259
|
+
"""
|
|
260
|
+
violations = []
|
|
261
|
+
|
|
262
|
+
# Get bus voltages
|
|
263
|
+
dss.Circuit.SetActiveBus("") # Reset to first bus
|
|
264
|
+
bus_count = dss.Circuit.NumBuses()
|
|
265
|
+
|
|
266
|
+
for i in range(bus_count):
|
|
267
|
+
bus_name = dss.Circuit.BusNames()[i]
|
|
268
|
+
dss.Circuit.SetActiveBus(bus_name)
|
|
269
|
+
|
|
270
|
+
# Get voltage magnitudes in per unit
|
|
271
|
+
v_pu = dss.Bus.puVmagAngle()[
|
|
272
|
+
::2
|
|
273
|
+
] # Even indices are magnitudes, odd indices are angles
|
|
274
|
+
|
|
275
|
+
# Check each phase
|
|
276
|
+
for phase, v_mag in enumerate(v_pu):
|
|
277
|
+
if v_mag < v_min:
|
|
278
|
+
violations.append(
|
|
279
|
+
{
|
|
280
|
+
"element_type": "bus",
|
|
281
|
+
"element_id": bus_name,
|
|
282
|
+
"phase": phase + 1,
|
|
283
|
+
"value": v_mag,
|
|
284
|
+
"limit": v_min,
|
|
285
|
+
"type": "undervoltage",
|
|
286
|
+
"deviation": v_min - v_mag,
|
|
287
|
+
}
|
|
288
|
+
)
|
|
289
|
+
elif v_mag > v_max:
|
|
290
|
+
violations.append(
|
|
291
|
+
{
|
|
292
|
+
"element_type": "bus",
|
|
293
|
+
"element_id": bus_name,
|
|
294
|
+
"phase": phase + 1,
|
|
295
|
+
"value": v_mag,
|
|
296
|
+
"limit": v_max,
|
|
297
|
+
"type": "overvoltage",
|
|
298
|
+
"deviation": v_mag - v_max,
|
|
299
|
+
}
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
return violations
|
|
303
|
+
|
|
304
|
+
def _check_loading_violations(self, loading_max: float) -> list[dict]:
|
|
305
|
+
"""
|
|
306
|
+
Check for line and transformer loading violations.
|
|
307
|
+
|
|
308
|
+
Args:
|
|
309
|
+
loading_max: Maximum allowed loading in percent
|
|
310
|
+
|
|
311
|
+
Returns:
|
|
312
|
+
List of loading violations with details
|
|
313
|
+
"""
|
|
314
|
+
violations = []
|
|
315
|
+
|
|
316
|
+
# Check line loading violations
|
|
317
|
+
dss.Lines.First()
|
|
318
|
+
while dss.Lines.Name():
|
|
319
|
+
loading = dss.CktElement.OverloadNorm() * 100 # Convert to percentage
|
|
320
|
+
|
|
321
|
+
if loading > loading_max:
|
|
322
|
+
violations.append(
|
|
323
|
+
{
|
|
324
|
+
"element_type": "line",
|
|
325
|
+
"element_id": dss.Lines.Name(),
|
|
326
|
+
"value": loading,
|
|
327
|
+
"limit": loading_max,
|
|
328
|
+
"type": "overloading",
|
|
329
|
+
"deviation": loading - loading_max,
|
|
330
|
+
}
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
dss.Lines.Next()
|
|
334
|
+
|
|
335
|
+
# Check transformer loading violations
|
|
336
|
+
dss.Transformers.First()
|
|
337
|
+
while dss.Transformers.Name():
|
|
338
|
+
# Set transformer as active element to get overload data
|
|
339
|
+
dss.Circuit.SetActiveElement(f"Transformer.{dss.Transformers.Name()}")
|
|
340
|
+
loading = dss.CktElement.OverloadNorm() * 100 # Convert to percentage
|
|
341
|
+
|
|
342
|
+
if loading > loading_max:
|
|
343
|
+
violations.append(
|
|
344
|
+
{
|
|
345
|
+
"element_type": "transformer",
|
|
346
|
+
"element_id": dss.Transformers.Name(),
|
|
347
|
+
"value": loading,
|
|
348
|
+
"limit": loading_max,
|
|
349
|
+
"type": "overloading",
|
|
350
|
+
"deviation": loading - loading_max,
|
|
351
|
+
}
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
dss.Transformers.Next()
|
|
355
|
+
|
|
356
|
+
return violations
|
|
357
|
+
|
|
358
|
+
def apply_tap_change(
|
|
359
|
+
self, transformer_name: str, tap: float, winding: int = 2
|
|
360
|
+
) -> None:
|
|
361
|
+
"""
|
|
362
|
+
Change tap position of a transformer.
|
|
363
|
+
|
|
364
|
+
Args:
|
|
365
|
+
transformer_name: Name of the transformer
|
|
366
|
+
tap: New tap value
|
|
367
|
+
winding: Winding number (default is 2, typically secondary)
|
|
368
|
+
"""
|
|
369
|
+
if not self.circuit_loaded:
|
|
370
|
+
raise ValueError("No circuit loaded")
|
|
371
|
+
|
|
372
|
+
try:
|
|
373
|
+
# Check if the transformer exists
|
|
374
|
+
dss.Transformers.Name(transformer_name)
|
|
375
|
+
if not dss.Transformers.Name():
|
|
376
|
+
raise ValueError(
|
|
377
|
+
f"Transformer '{transformer_name}' not found in the circuit"
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
# Set the tap position
|
|
381
|
+
dss.Transformers.Tap(tap, winding)
|
|
382
|
+
|
|
383
|
+
self.logger.info(
|
|
384
|
+
f"Changed tap position of transformer {transformer_name} to {tap} on winding {winding}"
|
|
385
|
+
)
|
|
386
|
+
except Exception as e:
|
|
387
|
+
self.logger.error(f"Failed to change tap position: {str(e)}")
|
|
388
|
+
raise
|
|
389
|
+
|
|
390
|
+
def modify_line(self, line_name: str, parameters: dict[str, Any]) -> None:
|
|
391
|
+
"""
|
|
392
|
+
Modify line parameters.
|
|
393
|
+
|
|
394
|
+
Args:
|
|
395
|
+
line_name: Name of the line to modify
|
|
396
|
+
parameters: Dictionary with parameters to modify (e.g., r1, x1, c1, length)
|
|
397
|
+
"""
|
|
398
|
+
if not self.circuit_loaded:
|
|
399
|
+
raise ValueError("No circuit loaded")
|
|
400
|
+
|
|
401
|
+
try:
|
|
402
|
+
# Check if the line exists
|
|
403
|
+
dss.Lines.Name(line_name)
|
|
404
|
+
if not dss.Lines.Name():
|
|
405
|
+
raise ValueError(f"Line '{line_name}' not found in the circuit")
|
|
406
|
+
|
|
407
|
+
# Set the line parameters
|
|
408
|
+
for param, value in parameters.items():
|
|
409
|
+
cmd = f"Edit Line.{line_name} {param}={value}"
|
|
410
|
+
dss.run_command(cmd)
|
|
411
|
+
|
|
412
|
+
self.logger.info(f"Modified parameters of line {line_name}")
|
|
413
|
+
|
|
414
|
+
except Exception as e:
|
|
415
|
+
self.logger.error(f"Failed to modify line: {str(e)}")
|
|
416
|
+
raise
|
|
417
|
+
|
|
418
|
+
def upgrade_line(self, line_name: str, new_wiredata: str) -> None:
|
|
419
|
+
"""
|
|
420
|
+
Upgrade a line with new wire data.
|
|
421
|
+
|
|
422
|
+
Args:
|
|
423
|
+
line_name: Name of the line to upgrade
|
|
424
|
+
new_wiredata: Name of the WireData object to use
|
|
425
|
+
"""
|
|
426
|
+
if not self.circuit_loaded:
|
|
427
|
+
raise ValueError("No circuit loaded")
|
|
428
|
+
|
|
429
|
+
try:
|
|
430
|
+
# Check if the line exists
|
|
431
|
+
dss.Lines.Name(line_name)
|
|
432
|
+
if not dss.Lines.Name():
|
|
433
|
+
raise ValueError(f"Line '{line_name}' not found in the circuit")
|
|
434
|
+
|
|
435
|
+
# Set the new wire data
|
|
436
|
+
cmd = f"Edit Line.{line_name} WireData={new_wiredata}"
|
|
437
|
+
dss.run_command(cmd)
|
|
438
|
+
|
|
439
|
+
self.logger.info(
|
|
440
|
+
f"Upgraded line {line_name} to use wire data {new_wiredata}"
|
|
441
|
+
)
|
|
442
|
+
|
|
443
|
+
except Exception as e:
|
|
444
|
+
self.logger.error(f"Failed to upgrade line: {str(e)}")
|
|
445
|
+
raise
|
|
446
|
+
|
|
447
|
+
def modify_transformer(
|
|
448
|
+
self, transformer_name: str, parameters: dict[str, Any]
|
|
449
|
+
) -> None:
|
|
450
|
+
"""
|
|
451
|
+
Modify transformer parameters.
|
|
452
|
+
|
|
453
|
+
Args:
|
|
454
|
+
transformer_name: Name of the transformer to modify
|
|
455
|
+
parameters: Dictionary with parameters to modify (e.g., kva, xhl, %r)
|
|
456
|
+
"""
|
|
457
|
+
if not self.circuit_loaded:
|
|
458
|
+
raise ValueError("No circuit loaded")
|
|
459
|
+
|
|
460
|
+
try:
|
|
461
|
+
# Check if the transformer exists
|
|
462
|
+
dss.Transformers.Name(transformer_name)
|
|
463
|
+
if not dss.Transformers.Name():
|
|
464
|
+
raise ValueError(
|
|
465
|
+
f"Transformer '{transformer_name}' not found in the circuit"
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
# Set the transformer parameters
|
|
469
|
+
for param, value in parameters.items():
|
|
470
|
+
cmd = f"Edit Transformer.{transformer_name} {param}={value}"
|
|
471
|
+
dss.run_command(cmd)
|
|
472
|
+
|
|
473
|
+
self.logger.info(f"Modified parameters of transformer {transformer_name}")
|
|
474
|
+
|
|
475
|
+
except Exception as e:
|
|
476
|
+
self.logger.error(f"Failed to modify transformer: {str(e)}")
|
|
477
|
+
raise
|
|
478
|
+
|
|
479
|
+
def get_losses(self) -> dict[str, float]:
|
|
480
|
+
"""
|
|
481
|
+
Calculate network losses.
|
|
482
|
+
|
|
483
|
+
Returns:
|
|
484
|
+
Dictionary with active and reactive power losses
|
|
485
|
+
"""
|
|
486
|
+
if (
|
|
487
|
+
not self.circuit_loaded
|
|
488
|
+
or not self.latest_results
|
|
489
|
+
or not self.latest_results.get("converged", False)
|
|
490
|
+
):
|
|
491
|
+
raise ValueError("Need a converged power flow solution to calculate losses")
|
|
492
|
+
|
|
493
|
+
try:
|
|
494
|
+
# Get losses from the circuit
|
|
495
|
+
losses = dss.Circuit.Losses()
|
|
496
|
+
|
|
497
|
+
# Convert to MW and Mvar (losses are in VA)
|
|
498
|
+
p_loss_mw = losses[0] / 1e6
|
|
499
|
+
q_loss_mvar = losses[1] / 1e6
|
|
500
|
+
|
|
501
|
+
return {"p_loss_mw": p_loss_mw, "q_loss_mvar": q_loss_mvar}
|
|
502
|
+
|
|
503
|
+
except Exception as e:
|
|
504
|
+
self.logger.error(f"Failed to get losses: {str(e)}")
|
|
505
|
+
raise
|
|
506
|
+
|
|
507
|
+
def get_power_summary(self) -> dict[str, Any]:
|
|
508
|
+
"""
|
|
509
|
+
Get power summary from the circuit.
|
|
510
|
+
|
|
511
|
+
Returns:
|
|
512
|
+
Dictionary with power summary information
|
|
513
|
+
"""
|
|
514
|
+
if (
|
|
515
|
+
not self.circuit_loaded
|
|
516
|
+
or not self.latest_results
|
|
517
|
+
or not self.latest_results.get("converged", False)
|
|
518
|
+
):
|
|
519
|
+
raise ValueError(
|
|
520
|
+
"Need a converged power flow solution to get power summary"
|
|
521
|
+
)
|
|
522
|
+
|
|
523
|
+
try:
|
|
524
|
+
# Total load power
|
|
525
|
+
total_power = dss.Circuit.TotalPower()
|
|
526
|
+
|
|
527
|
+
# Substation power
|
|
528
|
+
dss.Circuit.SetActiveElement("Vsource.source")
|
|
529
|
+
source_power = dss.CktElement.Powers()
|
|
530
|
+
|
|
531
|
+
# Sum source powers (convert to MW and Mvar)
|
|
532
|
+
source_p = sum(source_power[::2]) / 1e6
|
|
533
|
+
source_q = sum(source_power[1::2]) / 1e6
|
|
534
|
+
|
|
535
|
+
# Get losses
|
|
536
|
+
losses = self.get_losses()
|
|
537
|
+
|
|
538
|
+
return {
|
|
539
|
+
"total_load_mw": -total_power[0] / 1e6,
|
|
540
|
+
"total_load_mvar": -total_power[1] / 1e6,
|
|
541
|
+
"source_power_mw": source_p,
|
|
542
|
+
"source_power_mvar": source_q,
|
|
543
|
+
"losses_mw": losses["p_loss_mw"],
|
|
544
|
+
"losses_mvar": losses["q_loss_mvar"],
|
|
545
|
+
"loss_percent": (losses["p_loss_mw"] / abs(source_p)) * 100
|
|
546
|
+
if source_p != 0
|
|
547
|
+
else 0,
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
except Exception as e:
|
|
551
|
+
self.logger.error(f"Failed to get power summary: {str(e)}")
|
|
552
|
+
raise
|
|
553
|
+
|
|
554
|
+
def get_voltage_summary(self) -> dict[str, Any]:
|
|
555
|
+
"""
|
|
556
|
+
Get voltage summary statistics.
|
|
557
|
+
|
|
558
|
+
Returns:
|
|
559
|
+
Dictionary with voltage summary information
|
|
560
|
+
"""
|
|
561
|
+
if (
|
|
562
|
+
not self.circuit_loaded
|
|
563
|
+
or not self.latest_results
|
|
564
|
+
or not self.latest_results.get("converged", False)
|
|
565
|
+
):
|
|
566
|
+
raise ValueError(
|
|
567
|
+
"Need a converged power flow solution to get voltage summary"
|
|
568
|
+
)
|
|
569
|
+
|
|
570
|
+
try:
|
|
571
|
+
all_voltages = []
|
|
572
|
+
dss.Circuit.SetActiveBus("") # Reset to first bus
|
|
573
|
+
|
|
574
|
+
for i in range(dss.Circuit.NumBuses()):
|
|
575
|
+
bus_name = dss.Circuit.BusNames()[i]
|
|
576
|
+
dss.Circuit.SetActiveBus(bus_name)
|
|
577
|
+
|
|
578
|
+
# Get voltage magnitudes in per unit
|
|
579
|
+
v_pu = dss.Bus.puVmagAngle()[::2] # Even indices are magnitudes
|
|
580
|
+
all_voltages.extend(v_pu)
|
|
581
|
+
|
|
582
|
+
# Convert to numpy array for statistics
|
|
583
|
+
v_array = np.array(all_voltages)
|
|
584
|
+
|
|
585
|
+
return {
|
|
586
|
+
"min_voltage_pu": float(np.min(v_array)),
|
|
587
|
+
"max_voltage_pu": float(np.max(v_array)),
|
|
588
|
+
"avg_voltage_pu": float(np.mean(v_array)),
|
|
589
|
+
"std_voltage_pu": float(np.std(v_array)),
|
|
590
|
+
"num_buses": dss.Circuit.NumBuses(),
|
|
591
|
+
"num_nodes": dss.Circuit.NumNodes(),
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
except Exception as e:
|
|
595
|
+
self.logger.error(f"Failed to get voltage summary: {str(e)}")
|
|
596
|
+
raise
|
|
597
|
+
|
|
598
|
+
def get_loading_summary(self) -> dict[str, Any]:
|
|
599
|
+
"""
|
|
600
|
+
Get loading summary statistics for lines and transformers.
|
|
601
|
+
|
|
602
|
+
Returns:
|
|
603
|
+
Dictionary with loading summary information
|
|
604
|
+
"""
|
|
605
|
+
if (
|
|
606
|
+
not self.circuit_loaded
|
|
607
|
+
or not self.latest_results
|
|
608
|
+
or not self.latest_results.get("converged", False)
|
|
609
|
+
):
|
|
610
|
+
raise ValueError(
|
|
611
|
+
"Need a converged power flow solution to get loading summary"
|
|
612
|
+
)
|
|
613
|
+
|
|
614
|
+
try:
|
|
615
|
+
# Get line loadings
|
|
616
|
+
line_loadings = []
|
|
617
|
+
dss.Lines.First()
|
|
618
|
+
while dss.Lines.Name():
|
|
619
|
+
loading = dss.CktElement.OverloadNorm() * 100 # Convert to percentage
|
|
620
|
+
line_loadings.append(loading)
|
|
621
|
+
dss.Lines.Next()
|
|
622
|
+
|
|
623
|
+
# Get transformer loadings
|
|
624
|
+
transformer_loadings = []
|
|
625
|
+
dss.Transformers.First()
|
|
626
|
+
while dss.Transformers.Name():
|
|
627
|
+
# Set transformer as active element to get overload data
|
|
628
|
+
dss.Circuit.SetActiveElement(f"Transformer.{dss.Transformers.Name()}")
|
|
629
|
+
loading = dss.CktElement.OverloadNorm() * 100 # Convert to percentage
|
|
630
|
+
transformer_loadings.append(loading)
|
|
631
|
+
dss.Transformers.Next()
|
|
632
|
+
|
|
633
|
+
# Convert to numpy arrays
|
|
634
|
+
line_array = np.array(line_loadings) if line_loadings else np.array([0])
|
|
635
|
+
transformer_array = (
|
|
636
|
+
np.array(transformer_loadings)
|
|
637
|
+
if transformer_loadings
|
|
638
|
+
else np.array([0])
|
|
639
|
+
)
|
|
640
|
+
|
|
641
|
+
return {
|
|
642
|
+
"lines": {
|
|
643
|
+
"min_loading_pct": float(np.min(line_array)),
|
|
644
|
+
"max_loading_pct": float(np.max(line_array)),
|
|
645
|
+
"avg_loading_pct": float(np.mean(line_array)),
|
|
646
|
+
"std_loading_pct": float(np.std(line_array)),
|
|
647
|
+
"count": len(line_loadings),
|
|
648
|
+
},
|
|
649
|
+
"transformers": {
|
|
650
|
+
"min_loading_pct": float(np.min(transformer_array)),
|
|
651
|
+
"max_loading_pct": float(np.max(transformer_array)),
|
|
652
|
+
"avg_loading_pct": float(np.mean(transformer_array)),
|
|
653
|
+
"std_loading_pct": float(np.std(transformer_array)),
|
|
654
|
+
"count": len(transformer_loadings),
|
|
655
|
+
},
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
except Exception as e:
|
|
659
|
+
self.logger.error(f"Failed to get loading summary: {str(e)}")
|
|
660
|
+
raise
|
|
661
|
+
|
|
662
|
+
def get_network_metrics(self) -> dict[str, Any]:
|
|
663
|
+
"""
|
|
664
|
+
Get comprehensive network metrics.
|
|
665
|
+
|
|
666
|
+
Returns:
|
|
667
|
+
Dictionary with various network metrics
|
|
668
|
+
"""
|
|
669
|
+
if not self.circuit_loaded:
|
|
670
|
+
raise ValueError("No circuit loaded")
|
|
671
|
+
|
|
672
|
+
metrics = {
|
|
673
|
+
"network_size": {
|
|
674
|
+
"buses": dss.Circuit.NumBuses(),
|
|
675
|
+
"nodes": dss.Circuit.NumNodes(),
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
# Count elements by type
|
|
680
|
+
element_count = {}
|
|
681
|
+
dss.Circuit.FirstElement()
|
|
682
|
+
while dss.Circuit.ElementName():
|
|
683
|
+
element_type = dss.Circuit.ElementName().split(".")[0]
|
|
684
|
+
if element_type in element_count:
|
|
685
|
+
element_count[element_type] += 1
|
|
686
|
+
else:
|
|
687
|
+
element_count[element_type] = 1
|
|
688
|
+
dss.Circuit.NextElement()
|
|
689
|
+
|
|
690
|
+
metrics["element_count"] = element_count
|
|
691
|
+
|
|
692
|
+
# Add power flow results if available
|
|
693
|
+
if self.latest_results and self.latest_results.get("converged", False):
|
|
694
|
+
# Add voltage summary
|
|
695
|
+
metrics["voltage"] = self.get_voltage_summary()
|
|
696
|
+
|
|
697
|
+
# Add loading summary
|
|
698
|
+
metrics["loading"] = self.get_loading_summary()
|
|
699
|
+
|
|
700
|
+
# Add power summary
|
|
701
|
+
metrics["power"] = self.get_power_summary()
|
|
702
|
+
|
|
703
|
+
return metrics
|
|
704
|
+
|
|
705
|
+
def run_time_series(self, num_points: int) -> list[dict[str, Any]]:
|
|
706
|
+
"""
|
|
707
|
+
Run a time-series simulation.
|
|
708
|
+
|
|
709
|
+
Args:
|
|
710
|
+
num_points: Number of time points to simulate
|
|
711
|
+
|
|
712
|
+
Returns:
|
|
713
|
+
List of dictionaries with results for each time point
|
|
714
|
+
"""
|
|
715
|
+
if not self.circuit_loaded:
|
|
716
|
+
raise ValueError("No circuit loaded")
|
|
717
|
+
|
|
718
|
+
try:
|
|
719
|
+
# Configure solution for time series
|
|
720
|
+
dss.Solution.Mode(0) # Set to daily mode first to prepare
|
|
721
|
+
self._configure_solution() # Apply general settings
|
|
722
|
+
|
|
723
|
+
# Initialize results list
|
|
724
|
+
results = []
|
|
725
|
+
|
|
726
|
+
# Set number of points
|
|
727
|
+
dss.Solution.Number(num_points)
|
|
728
|
+
dss.Solution.StepSize(1) # Step size in hours
|
|
729
|
+
|
|
730
|
+
dss.Solution.Mode(1) # Set to daily mode
|
|
731
|
+
|
|
732
|
+
# Solve for each time point
|
|
733
|
+
for i in range(num_points):
|
|
734
|
+
dss.Solution.Solve()
|
|
735
|
+
|
|
736
|
+
if dss.Solution.Converged():
|
|
737
|
+
# Collect results for this time point
|
|
738
|
+
time_point_results = {
|
|
739
|
+
"time_point": i + 1,
|
|
740
|
+
"converged": True,
|
|
741
|
+
"losses": self.get_losses(),
|
|
742
|
+
"voltage_summary": self.get_voltage_summary(),
|
|
743
|
+
"loading_summary": self.get_loading_summary(),
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
results.append(time_point_results)
|
|
747
|
+
else:
|
|
748
|
+
results.append(
|
|
749
|
+
{
|
|
750
|
+
"time_point": i + 1,
|
|
751
|
+
"converged": False,
|
|
752
|
+
"message": "Power flow did not converge",
|
|
753
|
+
}
|
|
754
|
+
)
|
|
755
|
+
|
|
756
|
+
return results
|
|
757
|
+
|
|
758
|
+
except Exception as e:
|
|
759
|
+
self.logger.error(f"Time series simulation failed: {str(e)}")
|
|
760
|
+
raise
|
|
761
|
+
|
|
762
|
+
def create_topology_graph(self) -> Any:
|
|
763
|
+
"""
|
|
764
|
+
Create a NetworkX graph representing the network topology.
|
|
765
|
+
|
|
766
|
+
Returns:
|
|
767
|
+
NetworkX graph object
|
|
768
|
+
"""
|
|
769
|
+
try:
|
|
770
|
+
import networkx as nx
|
|
771
|
+
except ImportError:
|
|
772
|
+
self.logger.error(
|
|
773
|
+
"NetworkX is required for topology graph creation but not installed"
|
|
774
|
+
)
|
|
775
|
+
raise ImportError("NetworkX is required for topology graph creation")
|
|
776
|
+
|
|
777
|
+
if not self.circuit_loaded:
|
|
778
|
+
raise ValueError("No circuit loaded")
|
|
779
|
+
|
|
780
|
+
# Create undirected graph
|
|
781
|
+
G = nx.Graph()
|
|
782
|
+
|
|
783
|
+
# Add buses as nodes
|
|
784
|
+
for i in range(dss.Circuit.NumBuses()):
|
|
785
|
+
bus_name = dss.Circuit.BusNames()[i]
|
|
786
|
+
dss.Circuit.SetActiveBus(bus_name)
|
|
787
|
+
|
|
788
|
+
# Get bus kV to use as node attribute
|
|
789
|
+
kv = dss.Bus.kVBase()
|
|
790
|
+
G.add_node(bus_name, type="bus", kv=kv)
|
|
791
|
+
|
|
792
|
+
# Add lines as edges
|
|
793
|
+
dss.Lines.First()
|
|
794
|
+
while dss.Lines.Name():
|
|
795
|
+
line_name = dss.Lines.Name()
|
|
796
|
+
bus1 = dss.Lines.Bus1()
|
|
797
|
+
bus2 = dss.Lines.Bus2()
|
|
798
|
+
|
|
799
|
+
# Clean bus names (remove phase information)
|
|
800
|
+
bus1 = bus1.split(".")[0]
|
|
801
|
+
bus2 = bus2.split(".")[0]
|
|
802
|
+
|
|
803
|
+
G.add_edge(bus1, bus2, type="line", id=line_name)
|
|
804
|
+
dss.Lines.Next()
|
|
805
|
+
|
|
806
|
+
# Add transformers as edges
|
|
807
|
+
dss.Transformers.First()
|
|
808
|
+
while dss.Transformers.Name():
|
|
809
|
+
transformer_name = dss.Transformers.Name()
|
|
810
|
+
|
|
811
|
+
# Get buses from the transformer
|
|
812
|
+
dss.Circuit.SetActiveElement(f"Transformer.{transformer_name}")
|
|
813
|
+
buses = dss.CktElement.BusNames()
|
|
814
|
+
|
|
815
|
+
# Clean bus names (remove phase information)
|
|
816
|
+
bus1 = buses[0].split(".")[0]
|
|
817
|
+
bus2 = buses[1].split(".")[0]
|
|
818
|
+
|
|
819
|
+
G.add_edge(bus1, bus2, type="transformer", id=transformer_name)
|
|
820
|
+
dss.Transformers.Next()
|
|
821
|
+
|
|
822
|
+
return G
|
|
823
|
+
|
|
824
|
+
|
|
825
|
+
if __name__ == "__main__":
|
|
826
|
+
# Example usage
|
|
827
|
+
engine = OpenDSSEngine()
|
|
828
|
+
|
|
829
|
+
# Example DSS script to create a simple network
|
|
830
|
+
simple_circuit = """
|
|
831
|
+
Clear
|
|
832
|
+
New Circuit.test_circuit bus1=sourcebus basekv=12.47 pu=1.0 angle=0
|
|
833
|
+
|
|
834
|
+
! Define line parameters
|
|
835
|
+
New LineCode.code1 nphases=3 r1=0.1 x1=0.2 r0=0.5 x0=1.0
|
|
836
|
+
|
|
837
|
+
! Add lines
|
|
838
|
+
New Line.line1 bus1=sourcebus bus2=bus2 length=1.0 phases=3 units=km linecode=code1
|
|
839
|
+
New Line.line2 bus1=bus2 bus2=bus3 length=0.5 phases=3 units=km linecode=code1
|
|
840
|
+
|
|
841
|
+
! Add loads
|
|
842
|
+
New Load.load1 bus1=bus2 phases=3 kv=12.47 kw=100 kvar=20 model=1
|
|
843
|
+
New Load.load2 bus1=bus3 phases=3 kv=12.47 kw=200 kvar=50 model=1
|
|
844
|
+
|
|
845
|
+
! Set voltage base
|
|
846
|
+
Set voltagebases=[12.47]
|
|
847
|
+
Calcvoltagebases
|
|
848
|
+
|
|
849
|
+
! Solve
|
|
850
|
+
"""
|
|
851
|
+
|
|
852
|
+
# Create temporary DSS file
|
|
853
|
+
import tempfile
|
|
854
|
+
|
|
855
|
+
with tempfile.NamedTemporaryFile(suffix=".dss", delete=False, mode="w") as f:
|
|
856
|
+
f.write(simple_circuit)
|
|
857
|
+
temp_file = f.name
|
|
858
|
+
|
|
859
|
+
try:
|
|
860
|
+
# Load the circuit and run power flow
|
|
861
|
+
engine.load_network(temp_file)
|
|
862
|
+
results = engine.run_power_flow()
|
|
863
|
+
|
|
864
|
+
print(f"Power flow converged: {results['converged']}")
|
|
865
|
+
|
|
866
|
+
# Get network metrics
|
|
867
|
+
metrics = engine.get_network_metrics()
|
|
868
|
+
print("Network metrics:")
|
|
869
|
+
print(f" Number of buses: {metrics['network_size']['buses']}")
|
|
870
|
+
print(f" Element counts: {metrics['element_count']}")
|
|
871
|
+
|
|
872
|
+
# Get power summary
|
|
873
|
+
if results["converged"]:
|
|
874
|
+
power_summary = engine.get_power_summary()
|
|
875
|
+
print("Power summary:")
|
|
876
|
+
print(
|
|
877
|
+
f" Total load: {power_summary['total_load_mw']:.4f} MW, {power_summary['total_load_mvar']:.4f} Mvar"
|
|
878
|
+
)
|
|
879
|
+
print(
|
|
880
|
+
f" Losses: {power_summary['losses_mw']:.4f} MW ({power_summary['loss_percent']:.2f}%)"
|
|
881
|
+
)
|
|
882
|
+
|
|
883
|
+
finally:
|
|
884
|
+
# Clean up temporary file
|
|
885
|
+
os.remove(temp_file)
|