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,700 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
|
|
4
|
+
import folium
|
|
5
|
+
from shapely.geometry import LineString, Point, mapping
|
|
6
|
+
|
|
7
|
+
from gridforge.core.grid_enhancement import GridEnhancementAlgorithm
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def create_enhancement_visualisation(
|
|
13
|
+
algorithm: GridEnhancementAlgorithm, output_path: str
|
|
14
|
+
):
|
|
15
|
+
"""
|
|
16
|
+
Generates an HTML file with an interactive visualization of the grid enhancement process.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
algorithm (GridEnhancementAlgorithm): The executed algorithm instance with history.
|
|
20
|
+
output_path (str): The path where the HTML file will be saved.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
if not algorithm.history:
|
|
24
|
+
print("No history found in algorithm. Make sure to run the algorithm first.")
|
|
25
|
+
return
|
|
26
|
+
|
|
27
|
+
network = algorithm.pf_engine.network
|
|
28
|
+
|
|
29
|
+
# 1. Prepare GeoJSON Data
|
|
30
|
+
geojson_data = create_geojson_data(network)
|
|
31
|
+
|
|
32
|
+
# 2. Prepare Step Data (Styles and Stats)
|
|
33
|
+
step_data, stats_data = create_step_data(algorithm)
|
|
34
|
+
|
|
35
|
+
# 3. Generate HTML
|
|
36
|
+
create_html(geojson_data, step_data, stats_data, output_path, network)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def bus_load_mw(network) -> dict[int, float]:
|
|
40
|
+
"""
|
|
41
|
+
Active power (MW) of the loads in service at each bus (by index in the bus table),
|
|
42
|
+
at their scaling, as the power flow takes them. A bus with no such load is not
|
|
43
|
+
listed.
|
|
44
|
+
"""
|
|
45
|
+
loads = getattr(network, "load", None)
|
|
46
|
+
if loads is None or loads.empty:
|
|
47
|
+
return {}
|
|
48
|
+
power = loads["p_mw"].astype(float)
|
|
49
|
+
if "scaling" in loads:
|
|
50
|
+
power = power * loads["scaling"].fillna(1.0)
|
|
51
|
+
if "in_service" in loads:
|
|
52
|
+
power = power[loads["in_service"].astype(bool)]
|
|
53
|
+
return power.groupby(loads.loc[power.index, "bus"]).sum().to_dict()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def count_reinforcements(actions, line_lengths) -> dict:
|
|
57
|
+
"""
|
|
58
|
+
What a list of actions reinforced, counted as the results summary of the algorithm
|
|
59
|
+
counts it: a line or a transformer whose type changes in several steps is one
|
|
60
|
+
upgrade (the length of the line counts once), and each conductor or unit added is
|
|
61
|
+
one more, less the conductors a type change takes back.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
actions: The actions applied, as `GridEnhancementAlgorithm.history` keeps them.
|
|
65
|
+
line_lengths: Length (km) of each line, by name.
|
|
66
|
+
|
|
67
|
+
Returns:
|
|
68
|
+
dict: `upgraded_line_length_km`, `added_line_length_km`, `upgraded_trafo_count`,
|
|
69
|
+
`added_trafo_count`, and `reinforced`, the names of the lines and
|
|
70
|
+
transformers that the actions upgraded or added to.
|
|
71
|
+
"""
|
|
72
|
+
upgraded_lines = set()
|
|
73
|
+
upgraded_trafos = set()
|
|
74
|
+
added_line_length_km = 0
|
|
75
|
+
added_trafo_count = 0
|
|
76
|
+
reinforced = set()
|
|
77
|
+
|
|
78
|
+
for action in actions:
|
|
79
|
+
action_type = action.get("type")
|
|
80
|
+
if action_type == "line_upgrade":
|
|
81
|
+
for line in action.get("lines", []):
|
|
82
|
+
line_id = line.get("line_id")
|
|
83
|
+
length = line_lengths.get(line_id, 0)
|
|
84
|
+
parallel_count = line.get("parallel_count", 0)
|
|
85
|
+
|
|
86
|
+
if parallel_count > 0:
|
|
87
|
+
added_line_length_km += length
|
|
88
|
+
else:
|
|
89
|
+
upgraded_lines.add(line_id)
|
|
90
|
+
# Conductors added earlier, taken back by a type change
|
|
91
|
+
removed = int(line.get("conductors_removed") or 0)
|
|
92
|
+
added_line_length_km -= removed * length
|
|
93
|
+
|
|
94
|
+
reinforced.add(line_id)
|
|
95
|
+
elif action_type == "transformer_upgrade":
|
|
96
|
+
for trafo in action.get("transformers", []):
|
|
97
|
+
trafo_id = trafo.get("transformer_id")
|
|
98
|
+
parallel_count = trafo.get("parallel_count", 0)
|
|
99
|
+
|
|
100
|
+
if parallel_count > 0:
|
|
101
|
+
added_trafo_count += 1
|
|
102
|
+
else:
|
|
103
|
+
upgraded_trafos.add(trafo_id)
|
|
104
|
+
|
|
105
|
+
reinforced.add(trafo_id)
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
"upgraded_line_length_km": sum(
|
|
109
|
+
line_lengths.get(line_id, 0) for line_id in upgraded_lines
|
|
110
|
+
),
|
|
111
|
+
"added_line_length_km": added_line_length_km,
|
|
112
|
+
"upgraded_trafo_count": len(upgraded_trafos),
|
|
113
|
+
"added_trafo_count": added_trafo_count,
|
|
114
|
+
"reinforced": reinforced,
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def create_geojson_data(network):
|
|
119
|
+
"""Creates GeoJSON features for buses, lines, and transformers."""
|
|
120
|
+
features = []
|
|
121
|
+
bus_loads = bus_load_mw(network)
|
|
122
|
+
|
|
123
|
+
# Helper to get bus coordinates
|
|
124
|
+
bus_coords = {}
|
|
125
|
+
|
|
126
|
+
# Buses
|
|
127
|
+
if "geo" in network.bus.columns:
|
|
128
|
+
for idx, row in network.bus.iterrows():
|
|
129
|
+
geo = row["geo"]
|
|
130
|
+
geometry = None
|
|
131
|
+
if geo:
|
|
132
|
+
if isinstance(geo, str):
|
|
133
|
+
try:
|
|
134
|
+
geometry = json.loads(geo)
|
|
135
|
+
except json.JSONDecodeError:
|
|
136
|
+
logger.debug(
|
|
137
|
+
"Skipping element with unparseable geo JSON: %r", geo
|
|
138
|
+
)
|
|
139
|
+
elif isinstance(geo, dict):
|
|
140
|
+
geometry = geo
|
|
141
|
+
elif hasattr(geo, "geom_type"): # Shapely object
|
|
142
|
+
geometry = mapping(geo)
|
|
143
|
+
|
|
144
|
+
if geometry:
|
|
145
|
+
# Load at bus
|
|
146
|
+
load_mw = bus_loads.get(idx, 0.0)
|
|
147
|
+
|
|
148
|
+
features.append(
|
|
149
|
+
{
|
|
150
|
+
"type": "Feature",
|
|
151
|
+
"geometry": geometry,
|
|
152
|
+
"properties": {
|
|
153
|
+
"id": str(row["name"]),
|
|
154
|
+
"type": "bus",
|
|
155
|
+
"voltage_kv": float(row["vn_kv"]),
|
|
156
|
+
"load_mw": float(load_mw),
|
|
157
|
+
},
|
|
158
|
+
}
|
|
159
|
+
)
|
|
160
|
+
if geometry["type"] == "Point":
|
|
161
|
+
bus_coords[idx] = geometry["coordinates"]
|
|
162
|
+
|
|
163
|
+
elif hasattr(network, "bus_geodata") and not network.bus_geodata.empty:
|
|
164
|
+
for idx, row in network.bus_geodata.iterrows():
|
|
165
|
+
bus_name = network.bus.at[idx, "name"]
|
|
166
|
+
point = Point(row["x"], row["y"])
|
|
167
|
+
|
|
168
|
+
# Load at bus
|
|
169
|
+
load_mw = bus_loads.get(idx, 0.0)
|
|
170
|
+
|
|
171
|
+
features.append(
|
|
172
|
+
{
|
|
173
|
+
"type": "Feature",
|
|
174
|
+
"geometry": mapping(point),
|
|
175
|
+
"properties": {
|
|
176
|
+
"id": str(bus_name),
|
|
177
|
+
"type": "bus",
|
|
178
|
+
"voltage_kv": float(network.bus.at[idx, "vn_kv"]),
|
|
179
|
+
"load_mw": float(load_mw),
|
|
180
|
+
},
|
|
181
|
+
}
|
|
182
|
+
)
|
|
183
|
+
bus_coords[idx] = [row["x"], row["y"]]
|
|
184
|
+
|
|
185
|
+
# Lines
|
|
186
|
+
if "geo" in network.line.columns:
|
|
187
|
+
for _idx, row in network.line.iterrows():
|
|
188
|
+
geo = row["geo"]
|
|
189
|
+
geometry = None
|
|
190
|
+
if geo:
|
|
191
|
+
if isinstance(geo, str):
|
|
192
|
+
try:
|
|
193
|
+
geometry = json.loads(geo)
|
|
194
|
+
except json.JSONDecodeError:
|
|
195
|
+
logger.debug(
|
|
196
|
+
"Skipping element with unparseable geo JSON: %r", geo
|
|
197
|
+
)
|
|
198
|
+
elif isinstance(geo, dict):
|
|
199
|
+
geometry = geo
|
|
200
|
+
elif hasattr(geo, "geom_type"): # Shapely object
|
|
201
|
+
geometry = mapping(geo)
|
|
202
|
+
|
|
203
|
+
if geometry:
|
|
204
|
+
# Determine voltage level
|
|
205
|
+
from_bus = row["from_bus"]
|
|
206
|
+
vn_kv = network.bus.at[from_bus, "vn_kv"]
|
|
207
|
+
voltage_level = "mv" if vn_kv > 1.0 else "lv"
|
|
208
|
+
|
|
209
|
+
features.append(
|
|
210
|
+
{
|
|
211
|
+
"type": "Feature",
|
|
212
|
+
"geometry": geometry,
|
|
213
|
+
"properties": {
|
|
214
|
+
"id": str(row["name"]),
|
|
215
|
+
"type": "line",
|
|
216
|
+
"voltage_level": voltage_level,
|
|
217
|
+
"length_km": float(row["length_km"]),
|
|
218
|
+
},
|
|
219
|
+
}
|
|
220
|
+
)
|
|
221
|
+
elif hasattr(network, "line_geodata") and not network.line_geodata.empty:
|
|
222
|
+
for idx, row in network.line_geodata.iterrows():
|
|
223
|
+
line_name = network.line.at[idx, "name"]
|
|
224
|
+
coords = row["coords"]
|
|
225
|
+
if coords:
|
|
226
|
+
line = LineString(coords)
|
|
227
|
+
|
|
228
|
+
# Determine voltage level
|
|
229
|
+
from_bus = network.line.at[idx, "from_bus"]
|
|
230
|
+
vn_kv = network.bus.at[from_bus, "vn_kv"]
|
|
231
|
+
voltage_level = "mv" if vn_kv > 1.0 else "lv"
|
|
232
|
+
|
|
233
|
+
features.append(
|
|
234
|
+
{
|
|
235
|
+
"type": "Feature",
|
|
236
|
+
"geometry": mapping(line),
|
|
237
|
+
"properties": {
|
|
238
|
+
"id": str(line_name),
|
|
239
|
+
"type": "line",
|
|
240
|
+
"voltage_level": voltage_level,
|
|
241
|
+
"length_km": float(network.line.at[idx, "length_km"]),
|
|
242
|
+
},
|
|
243
|
+
}
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
# Transformers
|
|
247
|
+
for _idx, row in network.trafo.iterrows():
|
|
248
|
+
hv_bus = row["hv_bus"]
|
|
249
|
+
lv_bus = row["lv_bus"]
|
|
250
|
+
|
|
251
|
+
if hv_bus in bus_coords and lv_bus in bus_coords:
|
|
252
|
+
hv_coord = bus_coords[hv_bus]
|
|
253
|
+
lv_coord = bus_coords[lv_bus]
|
|
254
|
+
|
|
255
|
+
mid_x = (hv_coord[0] + lv_coord[0]) / 2
|
|
256
|
+
mid_y = (hv_coord[1] + lv_coord[1]) / 2
|
|
257
|
+
point = Point(mid_x, mid_y)
|
|
258
|
+
|
|
259
|
+
features.append(
|
|
260
|
+
{
|
|
261
|
+
"type": "Feature",
|
|
262
|
+
"geometry": mapping(point),
|
|
263
|
+
"properties": {
|
|
264
|
+
"id": str(row["name"]),
|
|
265
|
+
"type": "transformer",
|
|
266
|
+
"sn_mva": float(row["sn_mva"]),
|
|
267
|
+
},
|
|
268
|
+
}
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
return {"type": "FeatureCollection", "features": features}
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def create_step_data(algorithm):
|
|
275
|
+
"""Creates style data and detailed statistics for each step of the algorithm."""
|
|
276
|
+
history = algorithm.history
|
|
277
|
+
network = algorithm.pf_engine.network
|
|
278
|
+
|
|
279
|
+
# Pre-calculate static info
|
|
280
|
+
total_load_mw = algorithm.initial_total_load_mw
|
|
281
|
+
line_lengths = network.line.set_index("name")["length_km"].to_dict()
|
|
282
|
+
|
|
283
|
+
step_data = {}
|
|
284
|
+
stats_data = {"steps": [], "total_load_mw": total_load_mw, "details": {}}
|
|
285
|
+
|
|
286
|
+
# Several entries can belong to the same pass, so they are keyed by their position
|
|
287
|
+
for step, step_entry in enumerate(history):
|
|
288
|
+
violations = step_entry["violations"]
|
|
289
|
+
actions = step_entry["actions"]
|
|
290
|
+
cost = step_entry["total_cost"]
|
|
291
|
+
|
|
292
|
+
stats_data["steps"].append(step)
|
|
293
|
+
|
|
294
|
+
# --- Calculate detailed stats for this step ---
|
|
295
|
+
|
|
296
|
+
# 1. Violations by type
|
|
297
|
+
# Initialize with 0 for all expected types
|
|
298
|
+
violations_by_type = {
|
|
299
|
+
"LINE_LOADING": 0,
|
|
300
|
+
"TRANSFORMER_LOADING": 0,
|
|
301
|
+
"UNDER_VOLTAGE": 0,
|
|
302
|
+
"OVER_VOLTAGE": 0,
|
|
303
|
+
}
|
|
304
|
+
for v in violations:
|
|
305
|
+
v_type_str = str(v.constraint_type).split(".")[
|
|
306
|
+
-1
|
|
307
|
+
] # Get "LINE_LOADING" from "ConstraintType.LINE_LOADING"
|
|
308
|
+
violations_by_type[v_type_str] = violations_by_type.get(v_type_str, 0) + 1
|
|
309
|
+
|
|
310
|
+
# 2. Enhancement details
|
|
311
|
+
counted = count_reinforcements(actions, line_lengths)
|
|
312
|
+
upgraded_line_length_km = counted["upgraded_line_length_km"]
|
|
313
|
+
added_line_length_km = counted["added_line_length_km"]
|
|
314
|
+
upgraded_trafo_count = counted["upgraded_trafo_count"]
|
|
315
|
+
added_trafo_count = counted["added_trafo_count"]
|
|
316
|
+
load_shed_mw = 0
|
|
317
|
+
current_reinforced = counted["reinforced"]
|
|
318
|
+
current_flexibility = set()
|
|
319
|
+
|
|
320
|
+
for action in actions:
|
|
321
|
+
action_type = action.get("type")
|
|
322
|
+
if action_type == "flexibility_management":
|
|
323
|
+
for bus_mod in action.get("buses", []):
|
|
324
|
+
if bus_mod.get("action_type") == "load_shedding":
|
|
325
|
+
delta = bus_mod.get("old_power", 0) - bus_mod.get(
|
|
326
|
+
"new_power", 0
|
|
327
|
+
)
|
|
328
|
+
load_shed_mw += delta
|
|
329
|
+
|
|
330
|
+
# Find bus name for styling
|
|
331
|
+
element_type = bus_mod.get("element_type")
|
|
332
|
+
element_index = bus_mod.get("element_index")
|
|
333
|
+
bus_name = None
|
|
334
|
+
try:
|
|
335
|
+
if (
|
|
336
|
+
element_type == "load"
|
|
337
|
+
and hasattr(network, "load")
|
|
338
|
+
and element_index in network.load.index
|
|
339
|
+
):
|
|
340
|
+
bus_idx = network.load.at[element_index, "bus"]
|
|
341
|
+
bus_name = network.bus.at[bus_idx, "name"]
|
|
342
|
+
elif (
|
|
343
|
+
element_type == "sgen"
|
|
344
|
+
and hasattr(network, "sgen")
|
|
345
|
+
and element_index in network.sgen.index
|
|
346
|
+
):
|
|
347
|
+
bus_idx = network.sgen.at[element_index, "bus"]
|
|
348
|
+
bus_name = network.bus.at[bus_idx, "name"]
|
|
349
|
+
except (KeyError, IndexError):
|
|
350
|
+
logger.debug(
|
|
351
|
+
"Could not resolve bus name for %s element %s",
|
|
352
|
+
element_type,
|
|
353
|
+
element_index,
|
|
354
|
+
)
|
|
355
|
+
if bus_name:
|
|
356
|
+
current_flexibility.add(str(bus_name))
|
|
357
|
+
|
|
358
|
+
stats_data["details"][step] = {
|
|
359
|
+
"cost": cost,
|
|
360
|
+
"total_violations": len(violations),
|
|
361
|
+
"violations_by_type": violations_by_type,
|
|
362
|
+
"upgraded_line_length_km": upgraded_line_length_km,
|
|
363
|
+
"added_line_length_km": added_line_length_km,
|
|
364
|
+
"upgraded_trafo_count": upgraded_trafo_count,
|
|
365
|
+
"added_trafo_count": added_trafo_count,
|
|
366
|
+
"load_shed_mw": load_shed_mw,
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
# --- Calculate styles for this step ---
|
|
370
|
+
current_step_styles = {}
|
|
371
|
+
violated_elements = {v.element_id for v in violations}
|
|
372
|
+
|
|
373
|
+
# Lines
|
|
374
|
+
for name in network.line["name"]:
|
|
375
|
+
style_code = 2 if name in current_reinforced else 0
|
|
376
|
+
if name in violated_elements:
|
|
377
|
+
style_code = 3 if style_code == 2 else 1
|
|
378
|
+
current_step_styles[str(name)] = [style_code]
|
|
379
|
+
|
|
380
|
+
# Buses
|
|
381
|
+
for name in network.bus["name"]:
|
|
382
|
+
style_code = 4 if name in current_flexibility else 0
|
|
383
|
+
if name in violated_elements:
|
|
384
|
+
style_code = 5 if style_code == 4 else 1
|
|
385
|
+
current_step_styles[str(name)] = [style_code]
|
|
386
|
+
|
|
387
|
+
# Transformers
|
|
388
|
+
for name in network.trafo["name"]:
|
|
389
|
+
style_code = 2 if name in current_reinforced else 0
|
|
390
|
+
if name in violated_elements:
|
|
391
|
+
style_code = 3 if style_code == 2 else 1
|
|
392
|
+
current_step_styles[str(name)] = [style_code]
|
|
393
|
+
|
|
394
|
+
step_data[step] = current_step_styles
|
|
395
|
+
|
|
396
|
+
return step_data, stats_data
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def create_html(geojson_data, step_data, stats_data, output_path, network):
|
|
400
|
+
"""Generates the HTML file."""
|
|
401
|
+
|
|
402
|
+
# Calculate map center
|
|
403
|
+
lats, lons = [], []
|
|
404
|
+
for feature in geojson_data["features"]:
|
|
405
|
+
geom = feature["geometry"]
|
|
406
|
+
if geom["type"] == "Point":
|
|
407
|
+
lons.append(geom["coordinates"][0])
|
|
408
|
+
lats.append(geom["coordinates"][1])
|
|
409
|
+
elif geom["type"] == "LineString":
|
|
410
|
+
for coord in geom["coordinates"]:
|
|
411
|
+
lons.append(coord[0])
|
|
412
|
+
lats.append(coord[1])
|
|
413
|
+
mean_y, mean_x = (
|
|
414
|
+
(sum(lats) / len(lats), sum(lons) / len(lons))
|
|
415
|
+
if lats and lons
|
|
416
|
+
else (48.8566, 2.3522)
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
m = folium.Map(
|
|
420
|
+
location=[mean_y, mean_x],
|
|
421
|
+
zoom_start=14,
|
|
422
|
+
tiles="CartoDB positron",
|
|
423
|
+
zoom_snap=0,
|
|
424
|
+
zoom_delta=0.1,
|
|
425
|
+
wheel_debounce_time=20,
|
|
426
|
+
wheel_px_per_zoom_level=60,
|
|
427
|
+
)
|
|
428
|
+
m.get_root().header.add_child(
|
|
429
|
+
folium.Element('<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>')
|
|
430
|
+
)
|
|
431
|
+
|
|
432
|
+
folium.GeoJson(
|
|
433
|
+
geojson_data,
|
|
434
|
+
name="Network Data",
|
|
435
|
+
style_function=lambda x: {"opacity": 0.5, "weight": 2, "color": "#888"},
|
|
436
|
+
point_to_layer=folium.JsCode("""
|
|
437
|
+
function(feature, latlng) {
|
|
438
|
+
if (feature.properties.type === 'transformer') {
|
|
439
|
+
return L.marker(latlng, { icon: L.divIcon({ className: 'trafo-icon', html: '<div style="width:12px;height:12px;background-color:#888;border:1px solid #333;"></div>', iconSize: [12, 12], iconAnchor: [6, 6] }) });
|
|
440
|
+
}
|
|
441
|
+
var radius = 4 + (feature.properties.load_mw > 0 ? Math.sqrt(feature.properties.load_mw) * 5 : 0);
|
|
442
|
+
return L.circleMarker(latlng, {radius: radius, color: '#888', fillColor: '#888', fillOpacity: 0.5});
|
|
443
|
+
}
|
|
444
|
+
"""),
|
|
445
|
+
).add_to(m)
|
|
446
|
+
|
|
447
|
+
viz_data = {
|
|
448
|
+
"steps": stats_data["steps"],
|
|
449
|
+
"details": stats_data["details"],
|
|
450
|
+
"styles": step_data,
|
|
451
|
+
}
|
|
452
|
+
viz_data_json = json.dumps(viz_data)
|
|
453
|
+
|
|
454
|
+
control_html = f"""
|
|
455
|
+
<style>
|
|
456
|
+
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');
|
|
457
|
+
body {{ font-family: 'Roboto', sans-serif; }}
|
|
458
|
+
|
|
459
|
+
.panel {{
|
|
460
|
+
background-color: rgba(255, 255, 255, 0.95);
|
|
461
|
+
border-radius: 8px;
|
|
462
|
+
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
|
|
463
|
+
padding: 20px;
|
|
464
|
+
z-index: 9999;
|
|
465
|
+
backdrop-filter: blur(5px);
|
|
466
|
+
}}
|
|
467
|
+
|
|
468
|
+
#slider-panel {{
|
|
469
|
+
position: fixed; bottom: 30px; left: 50%; transform: translateX(-50%);
|
|
470
|
+
width: 90%; max-width: 800px;
|
|
471
|
+
display: flex; align-items: center; gap: 20px;
|
|
472
|
+
}}
|
|
473
|
+
|
|
474
|
+
#info-panel {{
|
|
475
|
+
position: fixed; top: 20px; right: 20px;
|
|
476
|
+
width: 340px;
|
|
477
|
+
max-height: 90vh;
|
|
478
|
+
overflow-y: auto;
|
|
479
|
+
}}
|
|
480
|
+
|
|
481
|
+
/* Scrollbar */
|
|
482
|
+
#info-panel::-webkit-scrollbar {{ width: 6px; }}
|
|
483
|
+
#info-panel::-webkit-scrollbar-track {{ background: #f1f1f1; }}
|
|
484
|
+
#info-panel::-webkit-scrollbar-thumb {{ background: #bdc3c7; border-radius: 3px; }}
|
|
485
|
+
|
|
486
|
+
h4 {{ margin: 0 0 15px 0; color: #2c3e50; font-weight: 500; text-align: center; border-bottom: 2px solid #eee; padding-bottom: 10px; }}
|
|
487
|
+
|
|
488
|
+
.stat-grid {{
|
|
489
|
+
display: grid;
|
|
490
|
+
grid-template-columns: 1fr 1fr;
|
|
491
|
+
gap: 10px;
|
|
492
|
+
margin-bottom: 15px;
|
|
493
|
+
}}
|
|
494
|
+
|
|
495
|
+
.stat-box {{
|
|
496
|
+
background: #f8f9fa;
|
|
497
|
+
padding: 10px;
|
|
498
|
+
border-radius: 6px;
|
|
499
|
+
text-align: center;
|
|
500
|
+
}}
|
|
501
|
+
|
|
502
|
+
.stat-label {{ font-size: 11px; color: #7f8c8d; text-transform: uppercase; letter-spacing: 0.5px; display: block; margin-bottom: 4px; }}
|
|
503
|
+
.stat-value {{ font-size: 16px; font-weight: 700; color: #2c3e50; }}
|
|
504
|
+
.stat-value.highlight {{ color: #e74c3c; }}
|
|
505
|
+
|
|
506
|
+
.section-title {{
|
|
507
|
+
font-size: 12px; font-weight: 700; color: #34495e;
|
|
508
|
+
margin: 15px 0 10px 0; text-transform: uppercase;
|
|
509
|
+
border-bottom: 1px solid #eee; padding-bottom: 5px;
|
|
510
|
+
}}
|
|
511
|
+
|
|
512
|
+
.list-item {{
|
|
513
|
+
display: flex; justify-content: space-between; align-items: center;
|
|
514
|
+
font-size: 13px; color: #555; margin-bottom: 6px;
|
|
515
|
+
}}
|
|
516
|
+
|
|
517
|
+
#violations-by-type-container {{
|
|
518
|
+
min-height: 60px; /* Reserve space for violations list */
|
|
519
|
+
display: flex;
|
|
520
|
+
flex-direction: column;
|
|
521
|
+
justify-content: center;
|
|
522
|
+
}}
|
|
523
|
+
|
|
524
|
+
.legend-row {{ display: flex; align-items: center; margin-bottom: 6px; font-size: 12px; color: #555; }}
|
|
525
|
+
.legend-symbol {{ margin-right: 10px; display: flex; justify-content: center; align-items: center; width: 20px; }}
|
|
526
|
+
|
|
527
|
+
/* Custom Slider */
|
|
528
|
+
input[type=range] {{ -webkit-appearance: none; width: 100%; background: transparent; }}
|
|
529
|
+
input[type=range]::-webkit-slider-thumb {{ -webkit-appearance: none; height: 20px; width: 20px; border-radius: 50%; background: #3498db; cursor: pointer; margin-top: -8px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); }}
|
|
530
|
+
input[type=range]::-webkit-slider-runnable-track {{ width: 100%; height: 4px; cursor: pointer; background: #bdc3c7; border-radius: 2px; }}
|
|
531
|
+
|
|
532
|
+
#play-pause-button {{
|
|
533
|
+
width: 44px; height: 44px; border-radius: 50%;
|
|
534
|
+
background: #3498db; color: white; border: none;
|
|
535
|
+
font-size: 18px; cursor: pointer; transition: all 0.2s;
|
|
536
|
+
display: flex; justify-content: center; align-items: center;
|
|
537
|
+
box-shadow: 0 4px 6px rgba(52, 152, 219, 0.3);
|
|
538
|
+
flex-shrink: 0;
|
|
539
|
+
}}
|
|
540
|
+
#play-pause-button:hover {{ background: #2980b9; transform: scale(1.05); }}
|
|
541
|
+
|
|
542
|
+
/* Legend Symbols */
|
|
543
|
+
.l-line-mv {{ height: 4px; width: 20px; background-color: #264653; }}
|
|
544
|
+
.l-line-lv {{ height: 2px; width: 20px; background-color: #264653; }}
|
|
545
|
+
.l-square {{ width: 12px; height: 12px; border: 1px solid #333; background-color: #264653; }}
|
|
546
|
+
.l-circle {{ width: 10px; height: 10px; border-radius: 50%; border: 1px solid #333; background-color: #264653; }}
|
|
547
|
+
.l-color {{ width: 14px; height: 14px; border-radius: 3px; }}
|
|
548
|
+
</style>
|
|
549
|
+
|
|
550
|
+
<div id="slider-panel" class="panel">
|
|
551
|
+
<button id="play-pause-button">►</button>
|
|
552
|
+
<div style="flex-grow: 1;">
|
|
553
|
+
<div style="display: flex; justify-content: space-between; margin-bottom: 5px; font-size: 13px; color: #555;">
|
|
554
|
+
<span>Step</span>
|
|
555
|
+
<span id="slider_step_label" style="font-weight: bold; color: #2c3e50;">0</span>
|
|
556
|
+
</div>
|
|
557
|
+
<input type="range" id="step_slider" min="0" max="{len(stats_data["steps"]) - 1}" value="0" step="1">
|
|
558
|
+
</div>
|
|
559
|
+
</div>
|
|
560
|
+
|
|
561
|
+
<div id="info-panel" class="panel">
|
|
562
|
+
<h4>Grid Enhancement</h4>
|
|
563
|
+
|
|
564
|
+
<div class="stat-box" style="margin-bottom: 15px;">
|
|
565
|
+
<span class="stat-label">Total Network Load</span>
|
|
566
|
+
<span class="stat-value">{stats_data["total_load_mw"]:.2f} MW</span>
|
|
567
|
+
</div>
|
|
568
|
+
|
|
569
|
+
<div class="stat-grid">
|
|
570
|
+
<div class="stat-box">
|
|
571
|
+
<span class="stat-label">Cost</span>
|
|
572
|
+
<span id="cost-display" class="stat-value">0.00 €</span>
|
|
573
|
+
</div>
|
|
574
|
+
<div class="stat-box">
|
|
575
|
+
<span class="stat-label">Violations</span>
|
|
576
|
+
<span id="total-violations-display" class="stat-value highlight">0</span>
|
|
577
|
+
</div>
|
|
578
|
+
</div>
|
|
579
|
+
|
|
580
|
+
<div id="violations-by-type-container"></div>
|
|
581
|
+
|
|
582
|
+
<div class="section-title">Cumulative Actions</div>
|
|
583
|
+
<div class="list-item"><span>Upgraded Lines</span><span id="upgraded-line-length" style="font-weight: 600;">0.00 km</span></div>
|
|
584
|
+
<div class="list-item"><span>Added Lines</span><span id="added-line-length" style="font-weight: 600;">0.00 km</span></div>
|
|
585
|
+
<div class="list-item"><span>Upgraded Trafos</span><span id="upgraded-trafo-count" style="font-weight: 600;">0</span></div>
|
|
586
|
+
<div class="list-item"><span>Added Trafos</span><span id="added-trafo-count" style="font-weight: 600;">0</span></div>
|
|
587
|
+
<div class="list-item"><span>Load Shed</span><span id="load-shed-mw" style="font-weight: 600;">0.00 MW</span></div>
|
|
588
|
+
|
|
589
|
+
<div class="section-title">Legend</div>
|
|
590
|
+
<div class="legend-row"><div class="legend-symbol"><div class="l-line-mv"></div></div>MV Line</div>
|
|
591
|
+
<div class="legend-row"><div class="legend-symbol"><div class="l-line-lv"></div></div>LV Line</div>
|
|
592
|
+
<div class="legend-row"><div class="legend-symbol"><div class="l-square"></div></div>Transformer</div>
|
|
593
|
+
<div class="legend-row"><div class="legend-symbol"><div class="l-circle"></div></div>Bus (Size ~ Load)</div>
|
|
594
|
+
|
|
595
|
+
<div style="margin-top: 10px;"></div>
|
|
596
|
+
<div class="legend-row"><div class="legend-symbol"><div class="l-color" style="background-color: #264653;"></div></div>Normal</div>
|
|
597
|
+
<div class="legend-row"><div class="legend-symbol"><div class="l-color" style="background-color: #e76f51;"></div></div>Violated</div>
|
|
598
|
+
<div class="legend-row"><div class="legend-symbol"><div class="l-color" style="background-color: #2a9d8f;"></div></div>Reinforced</div>
|
|
599
|
+
<div class="legend-row"><div class="legend-symbol"><div class="l-color" style="background-color: #e9c46a;"></div></div>Flexibility Activated</div>
|
|
600
|
+
</div>
|
|
601
|
+
|
|
602
|
+
<script>
|
|
603
|
+
var vizData = {viz_data_json};
|
|
604
|
+
var slider = document.getElementById('step_slider');
|
|
605
|
+
var isPlaying = false;
|
|
606
|
+
var playInterval;
|
|
607
|
+
|
|
608
|
+
var styles = {{
|
|
609
|
+
'line_mv': [{{color: '#264653', weight: 4, opacity: 0.8}}, {{color: '#e76f51', weight: 5, opacity: 1.0}}, {{color: '#2a9d8f', weight: 5, opacity: 1.0}}, {{color: '#d62828', weight: 6, opacity: 1.0}}],
|
|
610
|
+
'line_lv': [{{color: '#264653', weight: 2, opacity: 0.8}}, {{color: '#e76f51', weight: 3, opacity: 1.0}}, {{color: '#2a9d8f', weight: 3, opacity: 1.0}}, {{color: '#d62828', weight: 4, opacity: 1.0}}],
|
|
611
|
+
'bus': [{{color: '#264653', fillColor: '#264653', fillOpacity: 0.6}}, {{color: '#e76f51', fillColor: '#e76f51', fillOpacity: 0.8}}, {{color: '#2a9d8f', fillColor: '#2a9d8f', fillOpacity: 0.8}}, {{color: '#d62828', fillColor: '#d62828', fillOpacity: 0.8}}, {{color: '#e9c46a', fillColor: '#e9c46a', fillOpacity: 0.8}}, {{color: '#d62828', fillColor: '#d62828', fillOpacity: 0.8}}],
|
|
612
|
+
'transformer': [{{color: '#264653'}}, {{color: '#e76f51'}}, {{color: '#2a9d8f'}}, {{color: '#d62828'}}]
|
|
613
|
+
}};
|
|
614
|
+
|
|
615
|
+
function updateDetails(step) {{
|
|
616
|
+
const details = vizData.details[step];
|
|
617
|
+
document.getElementById('slider_step_label').innerText = step;
|
|
618
|
+
document.getElementById('cost-display').innerText = details.cost.toLocaleString('en-US', {{ style: 'currency', currency: 'EUR' }});
|
|
619
|
+
document.getElementById('total-violations-display').innerText = details.total_violations;
|
|
620
|
+
|
|
621
|
+
const violationsContainer = document.getElementById('violations-by-type-container');
|
|
622
|
+
violationsContainer.innerHTML = '';
|
|
623
|
+
|
|
624
|
+
// Always show all violation types, even if count is 0
|
|
625
|
+
const violationEntries = Object.entries(details.violations_by_type);
|
|
626
|
+
for (const [type, count] of violationEntries) {{
|
|
627
|
+
// Style 0 counts differently (greyed out)
|
|
628
|
+
const style = count === 0 ? 'color: #bdc3c7;' : 'color: #555;';
|
|
629
|
+
const valueStyle = count === 0 ? 'color: #bdc3c7;' : 'font-weight: 600;';
|
|
630
|
+
violationsContainer.innerHTML += `<div class="list-item" style="${{style}}"><span style="padding-left:10px;">• ${{type.replace('_', ' ')}}</span><span style="${{valueStyle}}">${{count}}</span></div>`;
|
|
631
|
+
}}
|
|
632
|
+
|
|
633
|
+
document.getElementById('upgraded-line-length').innerText = `${{details.upgraded_line_length_km.toFixed(2)}} km`;
|
|
634
|
+
document.getElementById('added-line-length').innerText = `${{details.added_line_length_km.toFixed(2)}} km`;
|
|
635
|
+
document.getElementById('upgraded-trafo-count').innerText = details.upgraded_trafo_count;
|
|
636
|
+
document.getElementById('added-trafo-count').innerText = details.added_trafo_count;
|
|
637
|
+
document.getElementById('load-shed-mw').innerText = `${{details.load_shed_mw.toFixed(3)}} MW`;
|
|
638
|
+
}}
|
|
639
|
+
|
|
640
|
+
function updateMap(step) {{
|
|
641
|
+
const currentStyles = vizData.styles[step];
|
|
642
|
+
if (typeof map !== 'undefined') {{
|
|
643
|
+
map.eachLayer(function(layer) {{
|
|
644
|
+
if (layer.feature && layer.feature.properties) {{
|
|
645
|
+
const props = layer.feature.properties;
|
|
646
|
+
let type = props.type;
|
|
647
|
+
if (type === 'line') {{ type = 'line_' + (props.voltage_level || 'mv'); }}
|
|
648
|
+
|
|
649
|
+
const styleCode = (currentStyles && currentStyles[props.id]) ? currentStyles[props.id][0] : 0;
|
|
650
|
+
const styleDef = styles[type][styleCode];
|
|
651
|
+
|
|
652
|
+
if (props.type === 'transformer') {{
|
|
653
|
+
const size = 14;
|
|
654
|
+
const html = `<div style="width:${{size}}px;height:${{size}}px;background-color:${{styleDef.color}};border:1px solid #333;"></div>`;
|
|
655
|
+
layer.setIcon(L.divIcon({{ className: '', html: html, iconSize: [size, size], iconAnchor: [size/2, size/2] }}));
|
|
656
|
+
}} else if (layer.setStyle) {{
|
|
657
|
+
layer.setStyle(styleDef);
|
|
658
|
+
}}
|
|
659
|
+
}}
|
|
660
|
+
}});
|
|
661
|
+
}}
|
|
662
|
+
updateDetails(step);
|
|
663
|
+
}}
|
|
664
|
+
|
|
665
|
+
function togglePlay() {{
|
|
666
|
+
if (isPlaying) {{
|
|
667
|
+
clearInterval(playInterval);
|
|
668
|
+
document.getElementById('play-pause-button').innerHTML = '►';
|
|
669
|
+
}} else {{
|
|
670
|
+
document.getElementById('play-pause-button').innerHTML = '❚❚';
|
|
671
|
+
playInterval = setInterval(function() {{
|
|
672
|
+
let currentVal = parseInt(slider.value);
|
|
673
|
+
let nextVal = (currentVal + 1) % vizData.steps.length;
|
|
674
|
+
slider.value = nextVal;
|
|
675
|
+
updateMap(vizData.steps[nextVal]);
|
|
676
|
+
}}, 1000);
|
|
677
|
+
}}
|
|
678
|
+
isPlaying = !isPlaying;
|
|
679
|
+
}}
|
|
680
|
+
|
|
681
|
+
slider.addEventListener('input', (e) => {{
|
|
682
|
+
if (isPlaying) togglePlay();
|
|
683
|
+
updateMap(vizData.steps[parseInt(e.target.value)]);
|
|
684
|
+
}});
|
|
685
|
+
document.getElementById('play-pause-button').addEventListener('click', togglePlay);
|
|
686
|
+
|
|
687
|
+
var map = null;
|
|
688
|
+
function findMap() {{
|
|
689
|
+
for (var key in window) {{
|
|
690
|
+
if (key.startsWith('map_') && window[key] && window[key].eachLayer) {{ map = window[key]; break; }}
|
|
691
|
+
}}
|
|
692
|
+
if (map) {{ updateMap(vizData.steps[0]); }} else {{ setTimeout(findMap, 100); }}
|
|
693
|
+
}}
|
|
694
|
+
findMap();
|
|
695
|
+
</script>
|
|
696
|
+
"""
|
|
697
|
+
|
|
698
|
+
m.get_root().html.add_child(folium.Element(control_html))
|
|
699
|
+
|
|
700
|
+
m.save(output_path)
|