|
| 1 | +"""GraphML export for vessel skeleton graphs.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from pathlib import Path |
| 6 | +from typing import TYPE_CHECKING |
| 7 | + |
| 8 | +import networkx as nx |
| 9 | +import numpy as np |
| 10 | +from skan.csr import skeleton_to_nx |
| 11 | + |
| 12 | +if TYPE_CHECKING: |
| 13 | + from skan import Skeleton |
| 14 | + |
| 15 | +# Branch-table columns describing topology or node positions; excluded from |
| 16 | +# edge attributes (node positions live on the node elements instead). |
| 17 | +_EXCLUDED_COLUMNS = { |
| 18 | + "node-id-src", |
| 19 | + "node-id-dst", |
| 20 | + "skeleton-id", |
| 21 | +} |
| 22 | + |
| 23 | + |
| 24 | +def _is_missing(value: object) -> bool: |
| 25 | + """True for NaN/Inf floats, which GraphML cannot represent.""" |
| 26 | + if isinstance(value, (float, np.floating)): |
| 27 | + return bool(np.isnan(value) or np.isinf(value)) |
| 28 | + return False |
| 29 | + |
| 30 | + |
| 31 | +def _edge_attributes(row: dict[str, object]) -> dict[str, object]: |
| 32 | + return { |
| 33 | + key: value |
| 34 | + for key, value in row.items() |
| 35 | + if not key.startswith("coord-") |
| 36 | + and not key.startswith("image-coord-") |
| 37 | + and key not in _EXCLUDED_COLUMNS |
| 38 | + and not _is_missing(value) |
| 39 | + } |
| 40 | + |
| 41 | + |
| 42 | +def build_networkx_graph( |
| 43 | + graph: Skeleton, |
| 44 | + branch_data, |
| 45 | + summary_features: dict[str, float] | None = None, |
| 46 | + radius_matrix: np.ndarray | None = None, |
| 47 | +) -> nx.MultiGraph: |
| 48 | + """Convert a skan skeleton graph into a networkx MultiGraph. |
| 49 | +
|
| 50 | + Nodes carry coordinates, degree, node-type flags, and ``radius`` (when |
| 51 | + *radius_matrix* is provided). Edges carry the per-branch features from |
| 52 | + *branch_data*. NaN/Inf attributes are omitted. *summary_features* is |
| 53 | + attached as graph-level attributes. |
| 54 | +
|
| 55 | + Parameters |
| 56 | + ---------- |
| 57 | + graph : Skeleton |
| 58 | + Pre-built skan Skeleton graph (e.g. from ``build_vessel_graph``). |
| 59 | + branch_data : DataFrame |
| 60 | + Pre-computed branch summary (e.g. from ``skan.summarize``). |
| 61 | + summary_features : dict[str, float], optional |
| 62 | + Per-image summary features attached as graph-level attributes. |
| 63 | + radius_matrix : ndarray, optional |
| 64 | + EDT radius array from ``compute_radii``; radius at each node is |
| 65 | + attached as a ``radius`` node attribute when provided. |
| 66 | + """ |
| 67 | + G = skeleton_to_nx(graph, branch_data) |
| 68 | + G.graph.clear() |
| 69 | + |
| 70 | + for summary in (summary_features or {}).items(): |
| 71 | + if not _is_missing(summary[1]): |
| 72 | + G.graph[summary[0]] = summary[1] |
| 73 | + |
| 74 | + for node_id in G.nodes(): |
| 75 | + coords = graph.coordinates[node_id] |
| 76 | + degree = int(graph.degrees[node_id]) |
| 77 | + attrs = {f"coord_{d}": int(c) for d, c in enumerate(coords)} |
| 78 | + attrs["degree"] = degree |
| 79 | + attrs["is_endpoint"] = degree == 1 |
| 80 | + attrs["is_junction"] = degree >= 3 |
| 81 | + attrs["is_pass_through"] = degree == 2 |
| 82 | + if radius_matrix is not None: |
| 83 | + attrs["radius"] = float(radius_matrix[tuple(coords)]) |
| 84 | + G.nodes[node_id].update(attrs) |
| 85 | + |
| 86 | + G.clear_edges() |
| 87 | + for row in branch_data.to_dict(orient="records"): |
| 88 | + G.add_edge( |
| 89 | + int(row["node-id-src"]), |
| 90 | + int(row["node-id-dst"]), |
| 91 | + **_edge_attributes(row), |
| 92 | + ) |
| 93 | + |
| 94 | + return G |
| 95 | + |
| 96 | + |
| 97 | +def write_graphml( |
| 98 | + graph: Skeleton, |
| 99 | + branch_data, |
| 100 | + path: str | Path, |
| 101 | + *, |
| 102 | + summary_features: dict[str, float] | None = None, |
| 103 | + radius_matrix: np.ndarray | None = None, |
| 104 | +) -> None: |
| 105 | + """Write a skeleton graph to a GraphML file. |
| 106 | +
|
| 107 | + Parameters |
| 108 | + ---------- |
| 109 | + graph : Skeleton |
| 110 | + Pre-built skan Skeleton graph (e.g. from ``build_vessel_graph``). |
| 111 | + branch_data : DataFrame |
| 112 | + Pre-computed branch summary (e.g. from ``skan.summarize``). |
| 113 | + path : str or Path |
| 114 | + Destination file path. |
| 115 | + summary_features : dict[str, float], optional |
| 116 | + Per-image summary features attached as graph-level attributes. |
| 117 | + radius_matrix : ndarray, optional |
| 118 | + EDT radius array from ``compute_radii``; radius at each node is |
| 119 | + attached as a ``radius`` node attribute when provided. |
| 120 | + """ |
| 121 | + G = build_networkx_graph( |
| 122 | + graph, |
| 123 | + branch_data, |
| 124 | + summary_features=summary_features, |
| 125 | + radius_matrix=radius_matrix, |
| 126 | + ) |
| 127 | + nx.write_graphml(G, str(path)) |
0 commit comments