Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,35 @@
# Changelog

## [Unreleased]

### Added

- **Evacuation antennas in the overflow graph drawing.** An evacuation antenna
is a part of the grid whose net production leaves through a single node of
the constrained path (or several, when insensitive). Its report is
insignificant, so its edges are gray, yet it is a lever.
expert_op4grid_recommender detects these antennas and stamps
`in_evacuation_antenna` on their nodes and branches.
- `OverflowGraphRenderer.prepare_for_plot` builds the graph actually drawn.
The reduced view (`without_gray_edges`) keeps the flagged gray edges and
the antenna nodes, with their injection colours like every other node.
The edges are drawn in an ochre yellow, `EVACUATION_ANTENNA_COLOR`
(`darkgoldenrod`), and keep the same conventions as the other edges:
report label and arrow.
- Everything happens on a copy: the model's colours are analysis data
(`Structured_Overload_Distribution_Graph` builds its views from them), so
they are never repainted. A drawn antenna edge keeps `base_color="gray"`,
and an antenna edge with a significant report keeps its colour.
- `delete_color_edges` gains `keep_flags`, which spares the edges carrying
one of the given boolean flags. The analysis views do not pass it.
- The interactive viewer gains an **Evacuation antennas** layer in the
*Structural Paths* section, with a dedicated glyph. A test now checks that
every semantic layer's swatch has a glyph in `viewer.js`.

On a full-France snapshot (contingency `MERLAL62SOULL`), the reduced view
goes from 26 to 33 nodes: the 7 substations and 14 branches of the Vent des
Îles offshore park antenna (231 MW) were dropped before and are now drawn.

## [0.3.3] - 2026-07-16

Large architecture-review pass over the `alphaDeesp` graph layer: correctness
Expand Down
10 changes: 9 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,17 @@ OverFlowGraph, ...`; new code should import from `alphaDeesp.core.graphs`.
insignificant), and the boolean semantic flags consumed downstream
(`is_overload`, `is_monitored`, `on_constrained_path`, `in_red_loop`,
`is_hub`, `is_extra_cut`). The public method signatures are unchanged.
Callers may also stamp `in_evacuation_antenna` on the evacuation antennas
they detect (expert_op4grid_recommender does).
- `graphs/overflow_renderer.py::OverflowGraphRenderer` owns all Graphviz
*presentation* (penwidth scaling, node shapes, tapered swap styling, the
compound `"colour:yellow:colour"` highlight strings and HTML loading
labels, and plotting). It is **stateless** (static methods over a passed-in
graph) so downstream repos can reuse it on any compatible `MultiDiGraph`.
`prepare_for_plot` builds the graph actually drawn: the reduced view
(`without_gray_edges`) keeps the gray edges flagged `in_evacuation_antenna`,
drawn in `EVACUATION_ANTENNA_COLOR` (ochre) with their report label, on a
copy (the model's colours are analysis data and are never repainted).

The public surface of the package is pinned by `tests/test_graphs_package.py`
(`EXPECTED_PUBLIC_NAMES` / `EXPECTED_SUBMODULES`) — update those sets when you
Expand Down Expand Up @@ -226,7 +232,9 @@ Python binding). On Debian/Ubuntu: `apt-get install graphviz`.
the "codebase is untyped" assumption.
- `graphs/graph_utils.delete_color_edges` accepts a single colour **or an
iterable of colours** and removes them in one graph copy — prefer the
multi-colour form to avoid chained full-graph copies.
multi-colour form to avoid chained full-graph copies. `keep_flags` spares
the edges carrying one of the given boolean flags (the renderer uses it for
evacuation antennas); the analysis views never pass it.
- `Structured_Overload_Distribution_Graph.find_loops` can bound simple-path
enumeration with `loop_path_cutoff` to avoid hangs on very large grids, but
it is **opt-in**: the default is `None` (unbounded = original behaviour)
Expand Down
25 changes: 22 additions & 3 deletions alphaDeesp/core/graphs/graph_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,19 @@ def from_edges_get_nodes(edges: Iterable[Any], amont_or_aval: str, constrained_e
else:
raise ValueError("Error in function from_edges_get_nodes")

def delete_color_edges(_g: nx.MultiDiGraph, edge_color: Union[str, Iterable[str]]) -> nx.MultiDiGraph:
def is_flag_set(value: Any) -> bool:
"""Whether a boolean graph attribute is set: ``True`` (or any truthy
value), or the string ``"True"`` it becomes once it went through DOT."""
if isinstance(value, str):
return value.strip().lower() == "true"
return bool(value)


def delete_color_edges(
_g: nx.MultiDiGraph,
edge_color: Union[str, Iterable[str]],
keep_flags: Iterable[str] = (),
) -> nx.MultiDiGraph:
"""
Returns a copy of a graph without edges of the given colour(s).

Expand All @@ -50,6 +62,11 @@ def delete_color_edges(_g: nx.MultiDiGraph, edge_color: Union[str, Iterable[str]
edge_color: ``str`` or iterable of ``str``
colour(s) of edges to delete from the graph

keep_flags: iterable of ``str``, optional
boolean edge attributes that spare an edge whatever its colour: an
edge with one of them set (see :func:`is_flag_set`) survives. Empty
by default, so every edge of the colour(s) is deleted.

Returns
----------

Expand All @@ -58,12 +75,14 @@ def delete_color_edges(_g: nx.MultiDiGraph, edge_color: Union[str, Iterable[str]

"""
colors_to_delete = {edge_color} if isinstance(edge_color, str) else set(edge_color)
flags = tuple(keep_flags)
g = _g.copy()

target_edges = [
(u, v, idx)
for u, v, idx, color in g.edges(keys=True, data="color")
if color in colors_to_delete
for u, v, idx, data in g.edges(keys=True, data=True)
if data.get("color") in colors_to_delete
and not any(is_flag_set(data.get(flag)) for flag in flags)
]

if target_edges:
Expand Down
4 changes: 3 additions & 1 deletion alphaDeesp/core/graphs/overflow_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
a base colour (``black`` overload / ``blue`` negative / ``coral`` positive /
``gray`` insignificant), and the boolean semantic flags consumed downstream
(``is_overload``, ``is_monitored``, ``on_constrained_path``, ``in_red_loop``,
``is_hub``, ``is_extra_cut``).
``is_hub``, ``is_extra_cut``). Callers may also stamp
``in_evacuation_antenna`` on the evacuation antennas they detect; the renderer
draws them.

Everything that is *purely Graphviz presentation* — penwidth scaling, node
shapes, tapered swap styling, the compound ``"colour:yellow:colour"``
Expand Down
55 changes: 48 additions & 7 deletions alphaDeesp/core/graphs/overflow_renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
* tapered styling for flow-direction swaps,
* the compound ``"colour:yellow:colour"`` highlight strings and the HTML
``before% → after%`` loading labels,
* the drawing of evacuation antennas (kept in the reduced view, in their own
colour),
* the actual plotting via :class:`~alphaDeesp.core.printer.Printer`.

Keeping it separate draws a clean line between the **semantic model** —
Expand All @@ -29,10 +31,19 @@
import networkx as nx

from alphaDeesp.core.printer import Printer
from alphaDeesp.core.graphs.graph_utils import delete_color_edges
from alphaDeesp.core.graphs.graph_utils import delete_color_edges, is_flag_set

logger = logging.getLogger(__name__)

# Evacuation antennas: parts of the grid tied to the constrained path through
# a single node (or several, when insensitive), whose net production leaves
# through it. The caller stamps them (expert_op4grid_recommender's
# structural-antenna detection) with the ``in_evacuation_antenna`` flag. Their
# report is insignificant, so their edges are gray, yet they are a lever: the
# drawing keeps them, in an ochre yellow (see ``prepare_for_plot``).
EVACUATION_ANTENNA_FLAG = "in_evacuation_antenna"
EVACUATION_ANTENNA_COLOR = "darkgoldenrod"

# Penwidth thresholds used when stamping edge thickness.
# The floor is dynamic: at least the width equivalent to 1 MW of flow
# (``scaling_factor`` applied to 1.0), and at least 10 % of the largest
Expand Down Expand Up @@ -174,6 +185,35 @@ def highlight_color(current_edge_color: Any) -> str:
# Plotting
# ------------------------------------------------------------------

@staticmethod
def prepare_for_plot(
g: nx.MultiDiGraph, without_gray_edges: bool = False
) -> nx.MultiDiGraph:
"""Return the graph to draw: *g* itself, or a copy when the drawing
differs from it. *g* is never modified.

``without_gray_edges`` drops the gray (insignificant) edges and the
nodes they leave isolated, except the edges of evacuation antennas
(``in_evacuation_antenna``). The gray edges of an antenna are drawn in
``EVACUATION_ANTENNA_COLOR``; like every other edge they keep their
report label and arrow, and their ``base_color`` keeps the gray role.
An antenna edge with a significant report keeps its colour.
"""
antenna_edges = [
(u, v, k)
for u, v, k, data in g.edges(keys=True, data=True)
if is_flag_set(data.get(EVACUATION_ANTENNA_FLAG)) and data.get("color") == "gray"
]
if without_gray_edges:
g = delete_color_edges(g, "gray", keep_flags=(EVACUATION_ANTENNA_FLAG,))
elif antenna_edges:
g = g.copy()
for edge in antenna_edges:
data = g.edges[edge]
data.setdefault("base_color", data["color"])
data["color"] = EVACUATION_ANTENNA_COLOR
return g

@staticmethod
def plot(
g: nx.MultiDiGraph,
Expand All @@ -185,14 +225,15 @@ def plot(
save_folder: str = "",
without_gray_edges: bool = False,
) -> Any:
"""Render *g* with Graphviz, optionally dropping gray edges first."""
"""Render *g* with Graphviz, optionally dropping gray edges first
(see :meth:`prepare_for_plot`)."""
printer = Printer(save_folder)

if without_gray_edges:
layout_dict = {n: c for n, c in zip(g.nodes, layout)} if layout is not None else None
g = delete_color_edges(g, "gray")
if layout_dict is not None:
layout = [layout_dict[node] for node in g.nodes]
drawn = OverflowGraphRenderer.prepare_for_plot(g, without_gray_edges)
if layout is not None and drawn.number_of_nodes() != g.number_of_nodes():
layout_dict = {n: c for n, c in zip(g.nodes, layout)}
layout = [layout_dict[node] for node in drawn.nodes]
g = drawn

kwargs = dict(rescale_factor=rescale_factor, fontsize=fontsize,
node_thickness=node_thickness, name="g_overflow_print")
Expand Down
2 changes: 2 additions & 0 deletions alphaDeesp/core/interactive_html/assets/viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,8 @@ const MODEL = __MODEL_JSON__;
if (swatch === 'diamond') return '<svg viewBox="0 0 10 10"><polygon points="5,0 10,5 5,10 0,5" fill="#444"/></svg>';
if (swatch === 'red-loop') return '<svg viewBox="0 0 10 10"><circle cx="5" cy="5" r="2" fill="coral"/><circle cx="5" cy="5" r="4" fill="none" stroke="coral" stroke-width="1"/></svg>';
if (swatch === 'constrained-path') return '<svg viewBox="0 0 14 6"><line x1="0" y1="3" x2="14" y2="3" stroke="black" stroke-width="2"/></svg>';
// Same colour as the renderer's EVACUATION_ANTENNA_COLOR.
if (swatch === 'evacuation-antenna') return '<svg viewBox="0 0 14 6"><line x1="0" y1="3" x2="14" y2="3" stroke="darkgoldenrod" stroke-width="2"/></svg>';
if (swatch === 'overload') return '<svg viewBox="0 0 14 6"><line x1="0" y1="3" x2="14" y2="3" stroke="black" stroke-width="2.5"/><line x1="0" y1="3" x2="14" y2="3" stroke="yellow" stroke-width="0.8"/></svg>';
if (swatch === 'monitored') return '<svg viewBox="0 0 14 6"><line x1="0" y1="3" x2="14" y2="3" stroke="coral" stroke-width="2.5"/><line x1="0" y1="3" x2="14" y2="3" stroke="yellow" stroke-width="0.8"/></svg>';
if (swatch === 'extra-cut') return '<svg viewBox="0 0 14 6"><line x1="0" y1="3" x2="14" y2="3" stroke="blue" stroke-width="2" stroke-dasharray="3 2"/></svg>';
Expand Down
6 changes: 6 additions & 0 deletions alphaDeesp/core/interactive_html/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@
_SEMANTIC_LAYERS: List[Dict[str, str]] = [
{"key": "on_constrained_path", "label": "Constrained path", "swatch": "constrained-path", "scope": "both"},
{"key": "in_red_loop", "label": "Red-loop paths", "swatch": "red-loop", "scope": "both"},
# Evacuation antennas (stamped by expert_op4grid_recommender): parts of
# the grid whose net production leaves through a single node of the
# constrained path. Their report is insignificant, yet they are a lever;
# the renderer keeps them in the reduced view.
{"key": "in_evacuation_antenna", "label": "Evacuation antennas", "swatch": "evacuation-antenna", "scope": "both"},
{"key": "is_overload", "label": "Overloads", "swatch": "overload", "scope": "edge"},
{"key": "is_monitored", "label": "Low margin lines", "swatch": "monitored", "scope": "edge"},
# Operator-supplied extras (ExpertAgent's `additionalLinesToCut`):
Expand Down Expand Up @@ -87,6 +92,7 @@
# Structural paths — multi-edge structures.
"semantic:on_constrained_path": _SECTION_STRUCTURAL,
"semantic:in_red_loop": _SECTION_STRUCTURAL,
"semantic:in_evacuation_antenna": _SECTION_STRUCTURAL,
# Individual entities properties — per-edge / per-node flags.
"semantic:is_overload": _SECTION_PROPERTIES,
"semantic:is_monitored": _SECTION_PROPERTIES,
Expand Down
20 changes: 20 additions & 0 deletions alphaDeesp/tests/test_graph_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,26 @@ def test_all_same_color_removes_everything(self):
assert result.number_of_edges() == 0
assert result.number_of_nodes() == 0

def test_keep_flags_spare_flagged_edges_and_their_nodes(self):
"""A flagged gray edge survives, and so does the node it alone connects."""
g = nx.MultiDiGraph()
g.add_edge("A", "B", color="blue", capacity=-5., name="line_AB")
g.add_edge("B", "C", color="gray", capacity=0., name="line_BC",
in_evacuation_antenna=True)
g.add_edge("B", "D", color="gray", capacity=0., name="line_BD")
result = delete_color_edges(g, "gray", keep_flags=("in_evacuation_antenna",))
assert set(result.edges()) == {("A", "B"), ("B", "C")}
assert "C" in result.nodes() and "D" not in result.nodes()

def test_keep_flags_read_flags_that_went_through_dot(self):
"""``"True"`` (a flag after DOT) spares an edge; ``False`` and ``"False"`` do not."""
g = nx.MultiDiGraph()
g.add_edge("A", "B", color="gray", name="l1", in_evacuation_antenna="True")
g.add_edge("B", "C", color="gray", name="l2", in_evacuation_antenna=False)
g.add_edge("C", "D", color="gray", name="l3", in_evacuation_antenna="False")
result = delete_color_edges(g, "gray", keep_flags=("in_evacuation_antenna",))
assert [name for _, _, name in result.edges(data="name")] == ["l1"]


# ──────────────────────────────────────────────────────────────────────
# nodepath_to_edgepath
Expand Down
39 changes: 39 additions & 0 deletions alphaDeesp/tests/test_interactive_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,45 @@ def test_layer_index_emits_extra_cut_layer_with_endpoints():
assert layer["section"] == "Individual entities properties"


def test_layer_index_emits_evacuation_antenna_layer_in_structural_paths():
"""``in_evacuation_antenna`` flags antenna nodes and branches; the layer
sits with the other structural elements, and the renderer's antenna
colour does not become a flow-polarity layer."""
edges = [
{"id": "edge1", "source": "P1", "target": "B",
"attrs": {"color": "darkgoldenrod", "in_evacuation_antenna": "True"}},
{"id": "edge2", "source": "B", "target": "C",
"attrs": {"color": "blue", "on_constrained_path": True}},
]
nodes = [
{"name": "P1", "attrs": {"in_evacuation_antenna": "True"}},
{"name": "B", "attrs": {"is_antenna_attachment": "True"}},
{"name": "C", "attrs": {}},
]
by_key = {l["key"]: l for l in _build_layer_index(edges, nodes)}

layer = by_key["semantic:in_evacuation_antenna"]
assert layer["edges"] == ["edge1"]
assert layer["nodes"] == ["P1"]
assert layer["swatch"] == "evacuation-antenna"
assert layer["label"] == "Evacuation antennas"
assert layer["section"] == "Structural Paths"
assert "color:darkgoldenrod" not in by_key


def test_every_semantic_layer_swatch_has_a_glyph_in_the_viewer():
"""The JS draws each semantic layer's swatch by name; a layer added
without its glyph would show an empty chip."""
from pathlib import Path

import alphaDeesp.core.interactive_html as ih_pkg
from alphaDeesp.core.interactive_html.constants import _SEMANTIC_LAYERS

js = (Path(ih_pkg.__file__).parent / "assets" / "viewer.js").read_text(encoding="utf-8")
for cfg in _SEMANTIC_LAYERS:
assert f"swatch === '{cfg['swatch']}'" in js, cfg["key"]


def test_layer_index_skips_semantic_layer_when_no_match():
"""No noise: empty semantic buckets do NOT produce a layer entry."""
edges = [
Expand Down
Loading
Loading