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,1078 @@
1
+ """Plotting utilities for grid visualization."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ import numpy as np
9
+
10
+ from gridforge.core.constraints import ConstraintViolation
11
+ from gridforge.utils.logging import logger
12
+
13
+ if TYPE_CHECKING:
14
+ from gridforge.core.power_flow import PowerFlowEngine
15
+
16
+
17
+ # -------------------------------------------------------------------------
18
+ # Plotting the network topology with violation and action overlays
19
+ # -------------------------------------------------------------------------
20
+
21
+
22
+ def plot_network_violations(
23
+ engine: PowerFlowEngine,
24
+ violations: list[ConstraintViolation] | None = None,
25
+ show_ids: bool = False,
26
+ enhancement_results: dict[str, Any] | None = None,
27
+ save_path: str | Path | None = None,
28
+ filename: str | None = None,
29
+ rc_params: dict[str, Any] | None = None,
30
+ ) -> None:
31
+ """
32
+ Plot topology with violations and optional enhancement overlays.
33
+
34
+ Rendering follows a fixed staged flow:
35
+
36
+ 1. Collect violated element IDs.
37
+ 2. Collect modified element IDs.
38
+ 3. Create graph and resolve positions.
39
+ 4. Draw buses.
40
+ 5. Draw lines.
41
+ 6. Draw transformers.
42
+ 7. Highlight modified elements.
43
+ 8. Draw legend and cosmetic layers.
44
+ 9. Show and optionally save.
45
+
46
+ Args:
47
+ engine (PowerFlowEngine): Engine instance that provides network state and topology graph.
48
+ violations (Optional[List[ConstraintViolation]], optional): Optional explicit violations list; fallback is engine constraints state. Defaults to None.
49
+ show_ids (bool, optional): Display IDs for buses, lines, and transformers. Defaults to False.
50
+ enhancement_results (Optional[Dict[str, Any]], optional): Output from GridEnhancementAlgorithm to mark modified elements. Defaults to None.
51
+ save_path (Optional[Union[str, Path]], optional): Directory path to save the plot image. Defaults to None.
52
+ filename (Optional[str], optional): Filename for the saved image. Defaults to None.
53
+ rc_params (Optional[Dict[str, Any]], optional): Optional plot style overrides. Missing keys are filled from defaults.
54
+ See `_default_plot_rc_params()` for the full schema. Defaults to None.
55
+ """
56
+ import matplotlib.pyplot as plt
57
+
58
+ logger.info("Plotting network violations.")
59
+
60
+ if engine.latest_results is not None and not engine.latest_results.get(
61
+ "converged", False
62
+ ):
63
+ logger.warning("Network is not converged, cannot plot violations.")
64
+ return
65
+
66
+ if engine.network is None:
67
+ logger.warning("No network loaded, cannot plot violations.")
68
+ return
69
+
70
+ try:
71
+ import networkx as nx
72
+ except ImportError:
73
+ logger.error("NetworkX is required for plotting but not installed.")
74
+ raise ImportError("NetworkX is required for plotting")
75
+
76
+ if violations is None:
77
+ violations = getattr(engine.constraints, "violations", None) or []
78
+
79
+ style = _build_plot_rc_params(rc_params)
80
+
81
+ # 1) Extract violated element IDs.
82
+ violated_bus_ids, violated_line_ids, violated_trafo_ids = (
83
+ _extract_violated_element_ids(violations)
84
+ )
85
+
86
+ # 2) Extract modified element IDs.
87
+ (
88
+ modified_bus_ids,
89
+ modified_line_ids,
90
+ modified_trafo_ids,
91
+ ) = _extract_action_highlights(enhancement_results)
92
+
93
+ # 3) Create graph and resolve mappings/positions.
94
+ graph = engine.create_topology_graph()
95
+ node_id_map, node_name_map = _build_node_lookup_maps(graph)
96
+ positions = _resolve_node_positions(graph=graph, nx_module=nx)
97
+
98
+ violated_bus_nodes = _resolve_bus_nodes(
99
+ bus_ids=violated_bus_ids,
100
+ node_id_map=node_id_map,
101
+ node_name_map=node_name_map,
102
+ )
103
+ modified_bus_nodes = _resolve_bus_nodes(
104
+ bus_ids=modified_bus_ids,
105
+ node_id_map=node_id_map,
106
+ node_name_map=node_name_map,
107
+ )
108
+
109
+ line_visuals = _build_edge_visuals_for_type(
110
+ graph=graph,
111
+ element_type="line",
112
+ violated_ids=violated_line_ids,
113
+ modified_ids=modified_line_ids,
114
+ rc_params=style,
115
+ )
116
+ transformer_visuals = _build_edge_visuals_for_type(
117
+ graph=graph,
118
+ element_type="transformer",
119
+ violated_ids=violated_trafo_ids,
120
+ modified_ids=modified_trafo_ids,
121
+ rc_params=style,
122
+ )
123
+
124
+ _, ax = plt.subplots(
125
+ figsize=tuple(style["figure"]["size"]),
126
+ layout=style["figure"]["layout"],
127
+ )
128
+
129
+ # 4) Plot buses with optional IDs.
130
+ _plot_buses(
131
+ graph=graph,
132
+ positions=positions,
133
+ nx_module=nx,
134
+ axis=ax,
135
+ violated_bus_nodes=violated_bus_nodes,
136
+ show_ids=show_ids,
137
+ rc_params=style,
138
+ )
139
+
140
+ # 5) Plot lines with optional IDs and violation-aware colors.
141
+ line_draw_data = _prepare_edge_draw_data(
142
+ edge_visuals=line_visuals,
143
+ positions=positions,
144
+ axis=ax,
145
+ show_ids=show_ids,
146
+ modified_extra_width=float(style["highlight"]["edge_extra_width"]),
147
+ modified_style=str(style["highlight"]["edge_line_style"]),
148
+ )
149
+ _draw_edges(
150
+ graph=graph,
151
+ positions=positions,
152
+ nx_module=nx,
153
+ axis=ax,
154
+ edge_draw_data=line_draw_data,
155
+ rc_params=style,
156
+ )
157
+
158
+ # 6) Plot transformers with optional IDs and violation-aware colors.
159
+ transformer_draw_data = _prepare_edge_draw_data(
160
+ edge_visuals=transformer_visuals,
161
+ positions=positions,
162
+ axis=ax,
163
+ show_ids=show_ids,
164
+ modified_extra_width=float(style["highlight"]["edge_extra_width"]),
165
+ modified_style=str(style["highlight"]["edge_line_style"]),
166
+ )
167
+ _draw_edges(
168
+ graph=graph,
169
+ positions=positions,
170
+ nx_module=nx,
171
+ axis=ax,
172
+ edge_draw_data=transformer_draw_data,
173
+ rc_params=style,
174
+ )
175
+
176
+ _plot_transformer_markers(
177
+ axis=ax,
178
+ markers=transformer_draw_data["transformer_markers"],
179
+ marker_colors=transformer_draw_data["transformer_marker_colors"],
180
+ rc_params=style,
181
+ )
182
+
183
+ # 7) Highlight modified buses and transformers. Modified edges are
184
+ # highlighted in `_draw_edges` via contour lines.
185
+ _draw_modification_halos(
186
+ axis=ax,
187
+ positions=positions,
188
+ modified_bus_nodes=modified_bus_nodes,
189
+ modified_transformer_markers=transformer_draw_data[
190
+ "modified_transformer_markers"
191
+ ],
192
+ rc_params=style,
193
+ )
194
+
195
+ combined_edge_annotations = (
196
+ line_draw_data["edge_id_annotations"]
197
+ + transformer_draw_data["edge_id_annotations"]
198
+ )
199
+ _draw_edge_id_annotations(
200
+ axis=ax,
201
+ annotations=combined_edge_annotations,
202
+ rc_params=style,
203
+ )
204
+ if (
205
+ graph.number_of_nodes() <= int(style["labels"]["name_threshold"])
206
+ and not show_ids
207
+ ):
208
+ _draw_bus_name_labels(
209
+ graph=graph,
210
+ positions=positions,
211
+ nx_module=nx,
212
+ axis=ax,
213
+ rc_params=style,
214
+ )
215
+
216
+ # 8) Build legend and finalize cosmetics.
217
+ _draw_legends(ax, rc_params=style)
218
+ ax.set_axis_off()
219
+
220
+ # 9) Show and optional save.
221
+ if save_path:
222
+ filename = "network_violations_graph.png" if filename is None else filename
223
+ plt.savefig(Path(save_path) / filename, dpi=int(style["figure"]["save_dpi"]))
224
+ logger.info(f"Plot {filename} saved in {save_path}")
225
+
226
+ plt.show()
227
+
228
+
229
+ def _build_node_lookup_maps(graph: Any) -> tuple[dict[str, Any], dict[str, Any]]:
230
+ """Map node IDs and names to graph node keys."""
231
+ node_id_map: dict[str, Any] = {}
232
+ node_name_map: dict[str, Any] = {}
233
+
234
+ for node_id, node_data in graph.nodes(data=True):
235
+ node_id_map[str(node_id)] = node_id
236
+ node_name = node_data.get("name")
237
+ if node_name is not None:
238
+ node_name_map[str(node_name)] = node_id
239
+
240
+ return node_id_map, node_name_map
241
+
242
+
243
+ def _build_plot_rc_params(rc_params: dict[str, Any] | None) -> dict[str, Any]:
244
+ """Build the effective plot style dictionary from defaults and overrides."""
245
+ defaults = _default_plot_rc_params()
246
+ if rc_params is None:
247
+ return defaults
248
+ return _merge_plot_rc_params(defaults, rc_params)
249
+
250
+
251
+ def _default_plot_rc_params() -> dict[str, Any]:
252
+ """Default style configuration for `plot_network_violations`."""
253
+ return {
254
+ "figure": {
255
+ "size": [10.0, 5.0],
256
+ "layout": "constrained",
257
+ "save_dpi": 300,
258
+ },
259
+ "colors": {
260
+ "ok": "tab:green",
261
+ "violated": "tab:red",
262
+ "highlight": "tab:orange",
263
+ "bus_edge": "grey",
264
+ "transformer_edge": "grey",
265
+ "bus_id": "white",
266
+ "edge_id": "black",
267
+ },
268
+ "bus": {
269
+ "marker": "o",
270
+ "size": 200.0,
271
+ "edge_width": 0.5,
272
+ },
273
+ "line": {
274
+ "width": 2.0,
275
+ "line_style": "solid",
276
+ },
277
+ "transformer": {
278
+ "marker": "D",
279
+ "size": 80.0,
280
+ "edge_width": 0.5,
281
+ "width": 2.5,
282
+ "line_style": "dashed",
283
+ },
284
+ "highlight": {
285
+ "edge_extra_width": 7.0,
286
+ "edge_line_style": "solid",
287
+ "node_size_ratio": 1.5,
288
+ "contour_width": 2.5,
289
+ "alpha": 0.9,
290
+ },
291
+ "legend": {
292
+ "loc": "best",
293
+ "fontsize": 16,
294
+ "title_fontsize": 12,
295
+ "ncol": 1,
296
+ },
297
+ "labels": {
298
+ "name_threshold": 30,
299
+ "name_fontsize": 8,
300
+ "bus_id_fontsize": 7,
301
+ "bus_id_fontweight": "bold",
302
+ "edge_id_fontsize": 7,
303
+ "edge_id_fontweight": "bold",
304
+ },
305
+ }
306
+
307
+
308
+ def _merge_plot_rc_params(
309
+ base: dict[str, Any], override: dict[str, Any]
310
+ ) -> dict[str, Any]:
311
+ """Recursively merge user style overrides into base style dictionary."""
312
+ merged: dict[str, Any] = dict(base)
313
+ for key, value in override.items():
314
+ if key in merged and isinstance(merged[key], dict) and isinstance(value, dict):
315
+ merged[key] = _merge_plot_rc_params(merged[key], value)
316
+ else:
317
+ merged[key] = value
318
+ return merged
319
+
320
+
321
+ def _plot_buses(
322
+ graph: Any,
323
+ positions: dict[Any, tuple[float, float]],
324
+ nx_module: Any,
325
+ axis: Any,
326
+ violated_bus_nodes: set[Any],
327
+ show_ids: bool,
328
+ rc_params: dict[str, Any],
329
+ ) -> None:
330
+ """Draw bus nodes and optional bus ID labels."""
331
+ bus_style = rc_params["bus"]
332
+ colors = rc_params["colors"]
333
+ label_style = rc_params["labels"]
334
+
335
+ node_colors = [
336
+ colors["violated"] if node in violated_bus_nodes else colors["ok"]
337
+ for node in graph.nodes()
338
+ ]
339
+ node_sizes = [float(bus_style["size"]) for _ in graph.nodes()]
340
+ node_linewidths = [float(bus_style["edge_width"]) for _ in graph.nodes()]
341
+ node_edgecolors = [colors["bus_edge"] for _ in graph.nodes()]
342
+
343
+ nx_module.draw_networkx_nodes(
344
+ graph,
345
+ positions,
346
+ node_shape=str(bus_style["marker"]),
347
+ edgecolors=node_edgecolors,
348
+ linewidths=node_linewidths,
349
+ node_color=node_colors,
350
+ node_size=node_sizes,
351
+ ax=axis,
352
+ )
353
+
354
+ if show_ids:
355
+ bus_id_labels = {
356
+ node_id: str(node_id) for node_id in graph.nodes() if node_id in positions
357
+ }
358
+ nx_module.draw_networkx_labels(
359
+ graph,
360
+ positions,
361
+ labels=bus_id_labels,
362
+ font_size=float(label_style["bus_id_fontsize"]),
363
+ font_weight=str(label_style["bus_id_fontweight"]),
364
+ font_color=colors["bus_id"],
365
+ ax=axis,
366
+ )
367
+
368
+
369
+ def _plot_transformer_markers(
370
+ axis: Any,
371
+ markers: list[tuple[float, float]],
372
+ marker_colors: list[str],
373
+ rc_params: dict[str, Any],
374
+ ) -> None:
375
+ """Draw transformer markers at edge midpoints."""
376
+ if not markers:
377
+ return
378
+
379
+ transformer_style = rc_params["transformer"]
380
+ colors = rc_params["colors"]
381
+ xs, ys = zip(*markers, strict=False)
382
+ axis.scatter(
383
+ xs,
384
+ ys,
385
+ s=float(transformer_style["size"]),
386
+ marker=str(transformer_style["marker"]),
387
+ edgecolors=colors["transformer_edge"],
388
+ linewidths=float(transformer_style["edge_width"]),
389
+ c=marker_colors,
390
+ zorder=3,
391
+ )
392
+
393
+
394
+ def _draw_edge_id_annotations(
395
+ axis: Any,
396
+ annotations: list[tuple[tuple[float, float], str, tuple[float, float]]],
397
+ rc_params: dict[str, Any],
398
+ ) -> None:
399
+ """Draw line/transformer ID labels with geometry-aware offsets."""
400
+ label_style = rc_params["labels"]
401
+ colors = rc_params["colors"]
402
+ for (x_coord, y_coord), label_text, offset in annotations:
403
+ axis.annotate(
404
+ label_text,
405
+ (x_coord, y_coord),
406
+ xytext=offset,
407
+ textcoords="offset points",
408
+ fontsize=float(label_style["edge_id_fontsize"]),
409
+ fontweight=str(label_style["edge_id_fontweight"]),
410
+ color=colors["edge_id"],
411
+ ha="center",
412
+ va="bottom",
413
+ zorder=5,
414
+ )
415
+
416
+
417
+ def _draw_bus_name_labels(
418
+ graph: Any,
419
+ positions: dict[Any, tuple[float, float]],
420
+ nx_module: Any,
421
+ axis: Any,
422
+ rc_params: dict[str, Any],
423
+ ) -> None:
424
+ """Draw bus name labels when the graph is small enough."""
425
+ labels = {}
426
+ for node_id, node_data in graph.nodes(data=True):
427
+ node_name = node_data.get("name")
428
+ labels[node_id] = str(node_name) if node_name else str(node_id)
429
+ nx_module.draw_networkx_labels(
430
+ graph,
431
+ positions,
432
+ labels=labels,
433
+ font_size=float(rc_params["labels"]["name_fontsize"]),
434
+ ax=axis,
435
+ )
436
+
437
+
438
+ def _build_edge_visuals_for_type(
439
+ graph: Any,
440
+ element_type: str,
441
+ violated_ids: set[str],
442
+ modified_ids: set[str],
443
+ rc_params: dict[str, Any],
444
+ ) -> list[dict[str, Any]]:
445
+ """Create visual payloads for one edge type (`line` or `transformer`)."""
446
+ normalized_type = element_type.lower()
447
+ if normalized_type not in {"line", "transformer"}:
448
+ return []
449
+
450
+ style_section_name = "line" if normalized_type == "line" else "transformer"
451
+ style = rc_params[style_section_name]
452
+
453
+ visuals: list[dict[str, Any]] = []
454
+ for u, v, edge_data in graph.edges(data=True):
455
+ edge_type = str(edge_data.get("type", "")).lower()
456
+ if normalized_type == "line" and edge_type != "line":
457
+ continue
458
+ if normalized_type == "transformer" and edge_type not in {
459
+ "transformer",
460
+ "trafo",
461
+ }:
462
+ continue
463
+
464
+ is_violated = _edge_matches_ids(edge_data, violated_ids)
465
+ is_modified = _edge_matches_ids(edge_data, modified_ids)
466
+ visuals.append(
467
+ {
468
+ "u": u,
469
+ "v": v,
470
+ "edge_data": edge_data,
471
+ "is_line": normalized_type == "line",
472
+ "is_transformer": normalized_type == "transformer",
473
+ "is_modified": is_modified,
474
+ "color": rc_params["colors"]["violated"]
475
+ if is_violated
476
+ else rc_params["colors"]["ok"],
477
+ "width": float(style["width"]),
478
+ "style": str(style["line_style"]),
479
+ }
480
+ )
481
+ return visuals
482
+
483
+
484
+ def _prepare_edge_draw_data(
485
+ edge_visuals: list[dict[str, Any]],
486
+ positions: dict[Any, tuple[float, float]],
487
+ axis: Any,
488
+ show_ids: bool,
489
+ modified_extra_width: float,
490
+ modified_style: str,
491
+ ) -> dict[str, Any]:
492
+ """Split edge rendering by geometry and collect labels/halo data."""
493
+ draw_data: dict[str, Any] = {
494
+ "edges_with_coords": [],
495
+ "edges_with_coords_colors": [],
496
+ "edges_with_coords_widths": [],
497
+ "edges_with_coords_styles": [],
498
+ "modified_edges_with_coords": [],
499
+ "modified_edges_with_coords_widths": [],
500
+ "modified_edges_with_coords_styles": [],
501
+ "edges_without_coords": [],
502
+ "edges_without_coords_colors": [],
503
+ "edges_without_coords_widths": [],
504
+ "edges_without_coords_styles": [],
505
+ "modified_edges_without_coords": [],
506
+ "modified_edges_without_coords_widths": [],
507
+ "modified_edges_without_coords_styles": [],
508
+ "transformer_markers": [],
509
+ "transformer_marker_colors": [],
510
+ "modified_transformer_markers": [],
511
+ "edge_id_annotations": [],
512
+ }
513
+
514
+ for visual in edge_visuals:
515
+ u = visual["u"]
516
+ v = visual["v"]
517
+ edge_data = visual["edge_data"]
518
+ coords = edge_data.get("coords")
519
+
520
+ if _has_geometry_coords(coords):
521
+ draw_data["edges_with_coords"].append(coords)
522
+ draw_data["edges_with_coords_colors"].append(visual["color"])
523
+ draw_data["edges_with_coords_widths"].append(visual["width"])
524
+ draw_data["edges_with_coords_styles"].append(visual["style"])
525
+ if visual["is_modified"]:
526
+ draw_data["modified_edges_with_coords"].append(coords)
527
+ draw_data["modified_edges_with_coords_widths"].append(
528
+ visual["width"] + modified_extra_width
529
+ )
530
+ draw_data["modified_edges_with_coords_styles"].append(modified_style)
531
+ else:
532
+ draw_data["edges_without_coords"].append((u, v))
533
+ draw_data["edges_without_coords_colors"].append(visual["color"])
534
+ draw_data["edges_without_coords_widths"].append(visual["width"])
535
+ draw_data["edges_without_coords_styles"].append(visual["style"])
536
+ if visual["is_modified"]:
537
+ draw_data["modified_edges_without_coords"].append((u, v))
538
+ draw_data["modified_edges_without_coords_widths"].append(
539
+ visual["width"] + modified_extra_width
540
+ )
541
+ draw_data["modified_edges_without_coords_styles"].append(modified_style)
542
+
543
+ midpoint = _resolve_edge_midpoint(
544
+ edge_data=edge_data,
545
+ positions=positions,
546
+ u=u,
547
+ v=v,
548
+ coords=coords,
549
+ )
550
+ if midpoint is None:
551
+ continue
552
+
553
+ if visual["is_transformer"]:
554
+ draw_data["transformer_markers"].append(midpoint)
555
+ draw_data["transformer_marker_colors"].append(visual["color"])
556
+
557
+ if visual["is_transformer"] and visual["is_modified"]:
558
+ draw_data["modified_transformer_markers"].append(midpoint)
559
+
560
+ if show_ids and (visual["is_line"] or visual["is_transformer"]):
561
+ edge_identifier = edge_data.get("id")
562
+ if edge_identifier is None:
563
+ edge_identifier = edge_data.get("name")
564
+ if edge_identifier is not None:
565
+ tangent_point_a, tangent_point_b = _resolve_edge_tangent(
566
+ coords=coords,
567
+ positions=positions,
568
+ u=u,
569
+ v=v,
570
+ )
571
+ edge_offset = _compute_geometry_aware_offset(
572
+ axis,
573
+ tangent_point_a,
574
+ tangent_point_b,
575
+ )
576
+ draw_data["edge_id_annotations"].append(
577
+ (midpoint, str(edge_identifier), edge_offset)
578
+ )
579
+
580
+ return draw_data
581
+
582
+
583
+ def _draw_edges(
584
+ graph: Any,
585
+ positions: dict[Any, tuple[float, float]],
586
+ nx_module: Any,
587
+ axis: Any,
588
+ edge_draw_data: dict[str, Any],
589
+ rc_params: dict[str, Any],
590
+ ) -> None:
591
+ """Draw edges with and without explicit geometry coordinates."""
592
+ highlight_color = rc_params["colors"]["highlight"]
593
+ highlight_alpha = float(rc_params["highlight"]["alpha"])
594
+
595
+ if edge_draw_data["edges_with_coords"]:
596
+ from matplotlib.collections import LineCollection
597
+
598
+ if edge_draw_data["modified_edges_with_coords"]:
599
+ halo_collection = LineCollection(
600
+ edge_draw_data["modified_edges_with_coords"],
601
+ colors=highlight_color,
602
+ linewidths=edge_draw_data["modified_edges_with_coords_widths"],
603
+ linestyles=edge_draw_data["modified_edges_with_coords_styles"],
604
+ alpha=highlight_alpha,
605
+ zorder=0.7,
606
+ )
607
+ axis.add_collection(halo_collection)
608
+
609
+ collection = LineCollection(
610
+ edge_draw_data["edges_with_coords"],
611
+ colors=edge_draw_data["edges_with_coords_colors"],
612
+ linewidths=edge_draw_data["edges_with_coords_widths"],
613
+ linestyles=edge_draw_data["edges_with_coords_styles"],
614
+ zorder=1,
615
+ )
616
+ axis.add_collection(collection)
617
+ axis.autoscale()
618
+
619
+ if edge_draw_data["edges_without_coords"]:
620
+ if edge_draw_data["modified_edges_without_coords"]:
621
+ nx_module.draw_networkx_edges(
622
+ graph,
623
+ positions,
624
+ edgelist=edge_draw_data["modified_edges_without_coords"],
625
+ edge_color=highlight_color,
626
+ width=edge_draw_data["modified_edges_without_coords_widths"],
627
+ style=edge_draw_data["modified_edges_without_coords_styles"],
628
+ alpha=highlight_alpha,
629
+ ax=axis,
630
+ )
631
+
632
+ nx_module.draw_networkx_edges(
633
+ graph,
634
+ positions,
635
+ edgelist=edge_draw_data["edges_without_coords"],
636
+ edge_color=edge_draw_data["edges_without_coords_colors"],
637
+ width=edge_draw_data["edges_without_coords_widths"],
638
+ style=edge_draw_data["edges_without_coords_styles"],
639
+ ax=axis,
640
+ )
641
+
642
+
643
+ def _draw_modification_halos(
644
+ axis: Any,
645
+ positions: dict[Any, tuple[float, float]],
646
+ modified_bus_nodes: set[Any],
647
+ modified_transformer_markers: list[tuple[float, float]],
648
+ rc_params: dict[str, Any],
649
+ ) -> None:
650
+ """Draw halo markers around modified buses and transformers."""
651
+ highlight = rc_params["highlight"]
652
+ colors = rc_params["colors"]
653
+ bus_style = rc_params["bus"]
654
+ transformer_style = rc_params["transformer"]
655
+
656
+ bus_halo_points: list[tuple[float, float]] = []
657
+ for node_id in modified_bus_nodes:
658
+ if node_id in positions:
659
+ bus_halo_points.append(positions[node_id])
660
+
661
+ if bus_halo_points:
662
+ xs, ys = zip(*bus_halo_points, strict=False)
663
+ axis.scatter(
664
+ xs,
665
+ ys,
666
+ s=float(bus_style["size"]) * float(highlight["node_size_ratio"]),
667
+ marker=str(bus_style["marker"]),
668
+ facecolors="none",
669
+ edgecolors=colors["highlight"],
670
+ linewidths=float(highlight["contour_width"]),
671
+ alpha=float(highlight["alpha"]),
672
+ zorder=2.6,
673
+ )
674
+
675
+ if modified_transformer_markers:
676
+ xs, ys = zip(*modified_transformer_markers, strict=False)
677
+ axis.scatter(
678
+ xs,
679
+ ys,
680
+ s=float(transformer_style["size"]) * float(highlight["node_size_ratio"]),
681
+ marker=str(transformer_style["marker"]),
682
+ facecolors="none",
683
+ edgecolors=colors["highlight"],
684
+ linewidths=float(highlight["contour_width"]),
685
+ alpha=float(highlight["alpha"]),
686
+ zorder=2.8,
687
+ )
688
+
689
+
690
+ def _draw_legends(axis: Any, rc_params: dict[str, Any]) -> None:
691
+ """Draw a single combined legend for status and element type."""
692
+ from matplotlib.lines import Line2D
693
+ from matplotlib.patches import Patch
694
+
695
+ colors = rc_params["colors"]
696
+ bus_style = rc_params["bus"]
697
+ line_style = rc_params["line"]
698
+ transformer_style = rc_params["transformer"]
699
+ highlight = rc_params["highlight"]
700
+ legend_style = rc_params["legend"]
701
+
702
+ combined_legend = [
703
+ Line2D(
704
+ [0],
705
+ [0],
706
+ linestyle="None",
707
+ label=r"$\mathbf{Element\ status}$",
708
+ ),
709
+ Patch(facecolor=colors["ok"], edgecolor="black", label="No Violation"),
710
+ Patch(facecolor=colors["violated"], edgecolor="black", label="Violated"),
711
+ Line2D(
712
+ [0],
713
+ [0],
714
+ marker="s",
715
+ color=colors["highlight"],
716
+ markerfacecolor="none",
717
+ markeredgecolor=colors["highlight"],
718
+ markeredgewidth=float(highlight["contour_width"]),
719
+ linestyle="None",
720
+ markersize=11,
721
+ label="Modified element",
722
+ ),
723
+ Line2D([0], [0], linestyle="None", label=r"$\mathbf{Element\ type}$"),
724
+ Line2D(
725
+ [0],
726
+ [0],
727
+ marker=str(bus_style["marker"]),
728
+ color="black",
729
+ linestyle="None",
730
+ markersize=8,
731
+ label="Bus",
732
+ ),
733
+ Line2D(
734
+ [0],
735
+ [0],
736
+ color="black",
737
+ linewidth=float(line_style["width"]),
738
+ linestyle=str(line_style["line_style"]),
739
+ label="Line",
740
+ ),
741
+ Line2D(
742
+ [0],
743
+ [0],
744
+ marker=str(transformer_style["marker"]),
745
+ color="black",
746
+ linestyle="None",
747
+ markersize=8,
748
+ label="Transformer",
749
+ ),
750
+ ]
751
+
752
+ axis.legend(
753
+ handles=combined_legend,
754
+ loc=str(legend_style["loc"]),
755
+ fontsize=float(legend_style["fontsize"]),
756
+ title_fontsize=float(legend_style["title_fontsize"]),
757
+ ncol=int(legend_style["ncol"]),
758
+ )
759
+
760
+
761
+ def _edge_matches_ids(edge_data: dict[str, Any], target_ids: set[str]) -> bool:
762
+ """Match an edge against ID or name identifiers."""
763
+ if not target_ids:
764
+ return False
765
+
766
+ edge_id = edge_data.get("id")
767
+ edge_name = edge_data.get("name")
768
+ if edge_id is not None and str(edge_id) in target_ids:
769
+ return True
770
+ if edge_name is not None and str(edge_name) in target_ids:
771
+ return True
772
+ return False
773
+
774
+
775
+ def _has_geometry_coords(coords: Any) -> bool:
776
+ """Check if edge geometry coordinates are present and non-empty."""
777
+ if not isinstance(coords, list | tuple | np.ndarray):
778
+ return False
779
+ try:
780
+ return len(coords) > 0
781
+ except TypeError:
782
+ return False
783
+
784
+
785
+ def _as_point(candidate: Any) -> tuple[float, float] | None:
786
+ """Convert a candidate object to an (x, y) point tuple."""
787
+ if not isinstance(candidate, list | tuple | np.ndarray):
788
+ return None
789
+ if len(candidate) < 2:
790
+ return None
791
+
792
+ try:
793
+ return float(candidate[0]), float(candidate[1])
794
+ except (TypeError, ValueError):
795
+ return None
796
+
797
+
798
+ def _resolve_edge_midpoint(
799
+ edge_data: dict[str, Any],
800
+ positions: dict[Any, tuple[float, float]],
801
+ u: Any,
802
+ v: Any,
803
+ coords: Any,
804
+ ) -> tuple[float, float] | None:
805
+ """Resolve midpoint from metadata, geometry, or endpoint average."""
806
+ midpoint = _as_point(edge_data.get("midpoint"))
807
+ if midpoint is not None:
808
+ return midpoint
809
+
810
+ if _has_geometry_coords(coords):
811
+ geometry_midpoint = _as_point(coords[len(coords) // 2])
812
+ if geometry_midpoint is not None:
813
+ return geometry_midpoint
814
+
815
+ if u in positions and v in positions:
816
+ return (
817
+ (positions[u][0] + positions[v][0]) / 2.0,
818
+ (positions[u][1] + positions[v][1]) / 2.0,
819
+ )
820
+ return None
821
+
822
+
823
+ def _resolve_edge_tangent(
824
+ coords: Any,
825
+ positions: dict[Any, tuple[float, float]],
826
+ u: Any,
827
+ v: Any,
828
+ ) -> tuple[tuple[float, float] | None, tuple[float, float] | None]:
829
+ """Resolve two points that define the local edge tangent."""
830
+ if _has_geometry_coords(coords) and len(coords) >= 2:
831
+ mid_index = len(coords) // 2
832
+ left_point = _as_point(coords[max(mid_index - 1, 0)])
833
+ right_point = _as_point(coords[min(mid_index + 1, len(coords) - 1)])
834
+ if left_point is not None and right_point is not None:
835
+ return left_point, right_point
836
+
837
+ if u in positions and v in positions:
838
+ return (positions[u][0], positions[u][1]), (positions[v][0], positions[v][1])
839
+ return None, None
840
+
841
+
842
+ def _extract_violated_element_ids(
843
+ violations: list[ConstraintViolation],
844
+ ) -> tuple[set[str], set[str], set[str]]:
845
+ """Collect violated IDs by element type (bus, line, transformer)."""
846
+ violated_bus_ids: set[str] = set()
847
+ violated_line_ids: set[str] = set()
848
+ violated_trafo_ids: set[str] = set()
849
+
850
+ for violation in violations:
851
+ element_type: str | None = None
852
+ element_id: Any | None = None
853
+
854
+ if hasattr(violation, "element_type") and hasattr(violation, "element_id"):
855
+ element_type = str(violation.element_type)
856
+ element_id = violation.element_id
857
+ elif isinstance(violation, dict):
858
+ raw_type = violation.get("element_type")
859
+ if raw_type is not None:
860
+ element_type = str(raw_type)
861
+ element_id = violation.get("element_id")
862
+
863
+ if element_type is None or element_id is None:
864
+ continue
865
+
866
+ element_type_norm = element_type.lower()
867
+ element_id_str = str(element_id)
868
+
869
+ if element_type_norm == "bus":
870
+ violated_bus_ids.add(element_id_str)
871
+ elif element_type_norm == "line":
872
+ violated_line_ids.add(element_id_str)
873
+ elif element_type_norm in {"transformer", "trafo"}:
874
+ violated_trafo_ids.add(element_id_str)
875
+
876
+ return violated_bus_ids, violated_line_ids, violated_trafo_ids
877
+
878
+
879
+ def _resolve_bus_nodes(
880
+ bus_ids: set[str],
881
+ node_id_map: dict[str, Any],
882
+ node_name_map: dict[str, Any],
883
+ ) -> set[Any]:
884
+ """Resolve bus IDs/names to graph node identifiers."""
885
+ resolved_nodes: set[Any] = set()
886
+ for bus_id in bus_ids:
887
+ if bus_id in node_id_map:
888
+ resolved_nodes.add(node_id_map[bus_id])
889
+ elif bus_id in node_name_map:
890
+ resolved_nodes.add(node_name_map[bus_id])
891
+ return resolved_nodes
892
+
893
+
894
+ def _resolve_node_positions(
895
+ graph: Any, nx_module: Any
896
+ ) -> dict[Any, tuple[float, float]]:
897
+ """Resolve node positions from explicit coordinates or deterministic layout."""
898
+ pos = nx_module.get_node_attributes(graph, "pos")
899
+ if len(pos) == graph.number_of_nodes():
900
+ return pos
901
+ elif len(pos) == (graph.number_of_nodes() - 1):
902
+ pos[0] = pos[1]
903
+ return pos
904
+
905
+ x = nx_module.get_node_attributes(graph, "x")
906
+ y = nx_module.get_node_attributes(graph, "y")
907
+ if len(x) == graph.number_of_nodes() and len(y) == graph.number_of_nodes():
908
+ return {node: (x[node], y[node]) for node in graph.nodes()}
909
+
910
+ if pos:
911
+ return nx_module.spring_layout(graph, seed=42, pos=pos, fixed=list(pos.keys()))
912
+ return nx_module.spring_layout(graph, seed=42)
913
+
914
+
915
+ def _extract_action_highlights(
916
+ results_obj: dict[str, Any] | None,
917
+ ) -> tuple[set[str], set[str], set[str]]:
918
+ """
919
+ Extract element IDs that were modified by enhancement actions.
920
+
921
+ Returns
922
+ -------
923
+ tuple[set[str], set[str], set[str]]
924
+ Three ID sets: (bus_ids, line_ids, transformer_ids).
925
+ """
926
+ highlighted_buses: set[str] = set()
927
+ highlighted_lines: set[str] = set()
928
+ highlighted_transformers: set[str] = set()
929
+
930
+ if not results_obj:
931
+ return highlighted_buses, highlighted_lines, highlighted_transformers
932
+
933
+ parsed_results = results_obj
934
+
935
+ # Accept either a plain results dictionary or a (success, results) tuple.
936
+ if (
937
+ isinstance(results_obj, tuple)
938
+ and len(results_obj) == 2
939
+ and isinstance(results_obj[1], dict)
940
+ ):
941
+ parsed_results = results_obj[1]
942
+
943
+ # Accept direct list payloads in addition to {"actions_applied": [...]}.
944
+ if isinstance(parsed_results, list):
945
+ actions_applied = parsed_results
946
+ elif isinstance(parsed_results, dict):
947
+ actions_applied = parsed_results.get("actions_applied", [])
948
+ else:
949
+ return highlighted_buses, highlighted_lines, highlighted_transformers
950
+ if not isinstance(actions_applied, list):
951
+ return highlighted_buses, highlighted_lines, highlighted_transformers
952
+
953
+ def _collect_id(candidates: dict[str, Any], keys: list[str]) -> str | None:
954
+ for key in keys:
955
+ value = candidates.get(key)
956
+ if value is not None:
957
+ return str(value)
958
+ return None
959
+
960
+ def _add_by_type(element_type: str, element_id: Any) -> None:
961
+ if element_id is None:
962
+ return
963
+ element_id_str = str(element_id)
964
+ element_type_norm = str(element_type).lower()
965
+ if element_type_norm == "line":
966
+ highlighted_lines.add(element_id_str)
967
+ elif element_type_norm in {"transformer", "trafo"}:
968
+ highlighted_transformers.add(element_id_str)
969
+ elif element_type_norm == "bus":
970
+ highlighted_buses.add(element_id_str)
971
+
972
+ def _ingest_typed_item(value: Any, default_type: str) -> None:
973
+ if isinstance(value, dict):
974
+ typed_id = _collect_id(
975
+ value, ["id", "name", "element_id", f"{default_type}_id"]
976
+ )
977
+ if typed_id is not None:
978
+ _add_by_type(default_type, typed_id)
979
+ elif value is not None:
980
+ _add_by_type(default_type, value)
981
+
982
+ for action in actions_applied:
983
+ if not isinstance(action, dict):
984
+ continue
985
+
986
+ # Known line action schemas.
987
+ for line_data in action.get("lines", []):
988
+ _ingest_typed_item(line_data, "line")
989
+
990
+ for bus_data in action.get("buses", []):
991
+ _ingest_typed_item(bus_data, "bus")
992
+
993
+ # Known transformer action schemas (upgrade and tap change).
994
+ for transformer_data in action.get("transformers", []):
995
+ if isinstance(transformer_data, dict):
996
+ transformer_id = _collect_id(
997
+ transformer_data,
998
+ ["transformer_id", "trafo_id", "id", "name", "element_id"],
999
+ )
1000
+ if transformer_id is not None:
1001
+ highlighted_transformers.add(transformer_id)
1002
+ elif transformer_data is not None:
1003
+ highlighted_transformers.add(str(transformer_data))
1004
+
1005
+ # Support compact one-element action schemas.
1006
+ top_level_line_id = _collect_id(action, ["line_id"])
1007
+ if top_level_line_id is not None:
1008
+ highlighted_lines.add(top_level_line_id)
1009
+ top_level_transformer_id = _collect_id(action, ["transformer_id", "trafo_id"])
1010
+ if top_level_transformer_id is not None:
1011
+ highlighted_transformers.add(top_level_transformer_id)
1012
+ top_level_bus_id = _collect_id(action, ["bus_id"])
1013
+ if top_level_bus_id is not None:
1014
+ highlighted_buses.add(top_level_bus_id)
1015
+
1016
+ # Generic fallback schema with one element per action.
1017
+ element_type = str(action.get("element_type", "")).lower()
1018
+ element_id = action.get("element_id")
1019
+ _add_by_type(element_type, element_id)
1020
+
1021
+ # Generic fallback schema with many elements per action.
1022
+ for element_data in action.get("elements", []):
1023
+ if not isinstance(element_data, dict):
1024
+ continue
1025
+ generic_type = str(element_data.get("element_type", "")).lower()
1026
+ generic_id = element_data.get("element_id")
1027
+ if generic_id is None:
1028
+ continue
1029
+
1030
+ generic_id_str = str(generic_id)
1031
+ if generic_type == "line":
1032
+ highlighted_lines.add(generic_id_str)
1033
+ elif generic_type in {"transformer", "trafo"}:
1034
+ highlighted_transformers.add(generic_id_str)
1035
+ elif generic_type == "bus":
1036
+ highlighted_buses.add(generic_id_str)
1037
+
1038
+ return highlighted_buses, highlighted_lines, highlighted_transformers
1039
+
1040
+
1041
+ def _compute_geometry_aware_offset(
1042
+ axis: Any,
1043
+ point_a: tuple[float, float] | None,
1044
+ point_b: tuple[float, float] | None,
1045
+ magnitude_points: float = 6.0,
1046
+ ) -> tuple[float, float]:
1047
+ """
1048
+ Compute a text offset perpendicular to local element geometry.
1049
+
1050
+ The offset is computed in display space, not data space, so the visual
1051
+ displacement remains stable with different axis scales.
1052
+ """
1053
+ if point_a is None or point_b is None:
1054
+ return (0.0, 4.0)
1055
+
1056
+ try:
1057
+ ax_x1, ax_y1 = axis.transData.transform(point_a)
1058
+ ax_x2, ax_y2 = axis.transData.transform(point_b)
1059
+ except Exception:
1060
+ return (0.0, 4.0)
1061
+
1062
+ dx = ax_x2 - ax_x1
1063
+ dy = ax_y2 - ax_y1
1064
+ norm = float(np.hypot(dx, dy))
1065
+
1066
+ if norm < 1.0e-12:
1067
+ return (0.0, 4.0)
1068
+
1069
+ # Build a unit normal from tangent (dx, dy): normal = (-dy, dx).
1070
+ normal_x = -dy / norm
1071
+ normal_y = dx / norm
1072
+
1073
+ # Keep the normal pointing upward on the screen.
1074
+ if normal_y < 0:
1075
+ normal_x = -normal_x
1076
+ normal_y = -normal_y
1077
+
1078
+ return (normal_x * magnitude_points, normal_y * magnitude_points)