# SPDX-License-Identifier: MIT
# Copyright (c) 2026 János Abonyi, Dániel Leitold, Ágnes Vathy-Fogarassy
r"""Import and export of networks, systems and annotated configurations.
``nocad`` works on the adjacency matrix of the network of state variables, but the
networks come from, and the results go to, other software. This module converts in
both directions:
* **Python objects**: NetworkX digraphs (:func:`from_networkx`, :func:`to_networkx`),
igraph graphs (:func:`from_igraph`, :func:`to_igraph`), pandas edge lists
(:func:`from_pandas_edgelist`, :func:`to_pandas`), state-space matrices
(:func:`from_state_space`) and python-control ``StateSpace`` systems
(:func:`from_control`, :func:`to_control`);
* **files** (:func:`read`, :func:`write`, chosen by the file extension):
========= ============= ==== ===== ===============================================
format extension read write typical use
========= ============= ==== ===== ===============================================
GraphML ``.graphml`` yes yes yEd, Cytoscape, NetworkX, igraph
GEXF ``.gexf`` yes yes Gephi, with role colors and positions
GML ``.gml`` yes yes igraph and other network tools
Cytoscape ``.cyjs`` yes yes Cytoscape and Cytoscape.js (classes, positions)
node-link ``.json`` yes yes D3.js and web applications
DOT ``.dot`` no yes Graphviz; components of one level share a rank
Pajek ``.net`` yes yes Pajek
edge list ``.edgelist`` yes yes plain text with the node order in a header
CSV / TSV ``.csv`` yes yes spreadsheets; node table in ``*_nodes.csv``
Excel ``.xlsx`` yes yes node, edge and summary sheets
MATLAB ``.mat`` yes yes the NOCAD MATLAB toolbox: A, B, C, D, labels
NumPy ``.npz`` yes yes compact binary storage
========= ============= ==== ===== ===============================================
Every export carries the annotations of :func:`nocad.annotation.annotate` as node and
edge attributes (driver and sensor nodes, roles, types, components, levels, depths,
regions, matched edges, edge classes, cactus parts, connection types), unless
``annotate=False``. Files written by ``nocad`` are read back with their configuration:
:func:`read` returns the driver and sensor nodes stored in the ``driver`` and
``sensor`` attributes.
"""
from __future__ import annotations
import json
import pathlib
import numpy as np
import pandas as pd
import scipy.sparse as sp
from ._graph import as_adjacency, edge_list, node_labels
from ._utils import Bunch
__all__ = [
"from_networkx",
"to_networkx",
"from_igraph",
"to_igraph",
"from_pandas_edgelist",
"to_pandas",
"from_state_space",
"from_control",
"to_control",
"read",
"write",
"read_mat",
"write_mat",
"to_dot",
"FORMATS",
]
#: File formats by extension: (name, readable, writable).
FORMATS = {
".graphml": ("graphml", True, True),
".gexf": ("gexf", True, True),
".gml": ("gml", True, True),
".cyjs": ("cytoscape", True, True),
".json": ("node_link", True, True),
".dot": ("dot", False, True),
".gv": ("dot", False, True),
".net": ("pajek", True, True),
".edgelist": ("edgelist", True, True),
".txt": ("edgelist", True, True),
".csv": ("csv", True, True),
".tsv": ("csv", True, True),
".xlsx": ("excel", True, True),
".mat": ("matlab", True, True),
".npz": ("npz", True, True),
}
# colors of the roles, as in nocad.plotting.ROLE_COLORS
_ROLE_HEX = {"driver": "#0072B2", "sensor": "#D55E00", "driver+sensor": "#CC79A7", "state": "#AEB8C2"}
_MATCHED_HEX, _EDGE_HEX = "#009E73", "#8A96A3"
# --------------------------------------------------------------------------- helpers
def _py(v):
"""Plain Python scalar (GraphML/GEXF writers reject numpy types)."""
if isinstance(v, np.generic):
return v.item()
if v is None or (isinstance(v, float) and np.isnan(v)):
return ""
return v
def _network(obj, labels=None):
"""(adjacency, labels, design or None) from an adjacency-like object, a design or a Bunch."""
from .design import InputOutputDesign
if isinstance(obj, InputOutputDesign):
lab = labels if labels is not None else getattr(obj, "labels_", None) or node_labels(obj.adj_)
return obj.adj_, [str(v) for v in lab], obj
if isinstance(obj, Bunch) and "adj" in obj:
lab = labels if labels is not None else obj.get("labels") or node_labels(obj["adj"])
return as_adjacency(obj["adj"]), [str(v) for v in lab], obj.get("design")
lab = labels if labels is not None else node_labels(obj)
return as_adjacency(obj), [str(v) for v in lab], None
def _result(adj, labels, node_data=None, drivers=None, sensors=None, **extra):
"""Bunch returned by every importer."""
adj = as_adjacency(adj)
n = adj.shape[0]
if node_data is not None and len(node_data) == n:
for key, attr in (("drivers", "driver"), ("sensors", "sensor")):
if (drivers if key == "drivers" else sensors) is None and attr in node_data.columns:
col = node_data[attr]
mask = col.astype(str).str.lower().isin(["true", "1", "yes"]).to_numpy()
if key == "drivers":
drivers = np.flatnonzero(mask)
else:
sensors = np.flatnonzero(mask)
out = Bunch(
adj=adj, labels=list(labels), n_states=n, node_data=node_data, drivers=drivers, sensors=sensors
)
out.update(extra)
return out
def _annotated(adj, labels, design, annotate, method, drivers, sensors, **kw):
if not annotate:
return None
from .annotation import annotate as _annotate
return _annotate(adj, design=design, method=method, drivers=drivers, sensors=sensors, labels=labels, **kw)
def _layout(adj, layout):
"""Positions for exports: ``"hierarchy"``, ``"default"``, an (N, 2) array or None."""
if layout is None or layout is False:
return None
if isinstance(layout, str):
from .plotting import default_layout
return default_layout(adj, method=layout)
return np.asarray(layout, dtype=float)
# --------------------------------------------------------------------------- NetworkX
[docs]
def from_networkx(G, weight: str | None = None, nodes=None) -> Bunch:
"""Network of state variables from a NetworkX graph.
Parameters
----------
G : networkx.DiGraph (an undirected graph is read as symmetric)
weight : str, optional
Edge attribute with the numeric values of :math:`a_{ij}` (structure only if None).
nodes : list, optional
Node order (default: ``G.nodes()``).
Returns
-------
net : Bunch with ``adj`` (sparse adjacency), ``labels`` (node names as strings),
``nodes`` (original node objects), ``node_data`` (DataFrame of node attributes),
``drivers`` / ``sensors`` (from boolean ``driver`` / ``sensor`` attributes, if any)
and ``weights`` (sparse weighted adjacency if ``weight`` is given).
Examples
--------
>>> import networkx as nx
>>> G = nx.DiGraph([("tank1", "tank2"), ("tank2", "tank2")])
>>> net = from_networkx(G)
>>> net.labels, net.adj.toarray().astype(int).tolist()
(['tank1', 'tank2'], [[0, 1], [0, 1]])
"""
import networkx as nx
nodes = list(G.nodes()) if nodes is None else list(nodes)
H = G if G.is_directed() else G.to_directed()
W = sp.csr_array(nx.to_scipy_sparse_array(H, nodelist=nodes, weight=weight))
data = pd.DataFrame([dict(H.nodes[v]) for v in nodes])
adj = as_adjacency(W)
labels = [str(v) for v in nodes]
return _result(
adj, labels, data if data.shape[1] else None, nodes=nodes, weights=W.astype(float) if weight else None
)
[docs]
def to_networkx(
adj,
labels=None,
*,
annotate: bool = True,
design=None,
method: str = "path_finding",
drivers=None,
sensors=None,
node_ids: str = "label",
layout=None,
weights=None,
centrality: bool = False,
robustness: bool = False,
):
"""NetworkX digraph of a network, with the annotations as node and edge attributes.
Parameters
----------
adj : network or InputOutputDesign
labels : list of str, optional
Node names (default: names of the input graph, else ``x1, x2, ...``).
annotate : bool, default=True
Add the columns of :func:`nocad.annotation.annotate` as attributes; graph
attributes hold the network-level values.
design, method, drivers, sensors, centrality, robustness
Passed to :func:`~nocad.annotation.annotate`.
node_ids : {"label", "index"}, default="label"
Use the labels or the integer indices as node identifiers (the label is always
stored in the ``label`` attribute).
layout : {"hierarchy", "default", ...} or ndarray of shape (N, 2), optional
Store positions as ``x`` and ``y`` node attributes.
weights : array-like, optional
Numeric adjacency matrix; its entries are stored as the ``weight`` edge attribute.
Returns
-------
G : networkx.DiGraph
Examples
--------
>>> from nocad.datasets import load_nocad_example
>>> G = to_networkx(load_nocad_example().adj)
>>> G.nodes["x8"]["io_role"], G.edges["x8", "x6"]["control_cactus"], G.graph["n_inputs"]
('driver', 'stem', 1)
"""
import networkx as nx
A, labels, d0 = _network(adj, labels)
design = design if design is not None else d0
n = A.shape[0]
ids = labels if node_ids == "label" else list(range(n))
if node_ids == "label" and len(set(ids)) != n:
raise ValueError("labels are not unique; use node_ids='index'")
ann = _annotated(
A, labels, design, annotate, method, drivers, sensors, centrality=centrality, robustness=robustness
)
G = nx.DiGraph()
if ann is not None:
G.graph.update({k: _py(v) for k, v in ann.graph.items()})
recs = ann.nodes.to_dict("records")
else:
recs = [{"label": lab} for lab in labels]
pos = _layout(A, layout)
for i in range(n):
attrs = {k: _py(v) for k, v in recs[i].items()}
if pos is not None:
attrs["x"], attrs["y"] = float(pos[i, 0]), float(pos[i, 1])
G.add_node(ids[i], **attrs)
Wt = sp.csr_array(weights) if weights is not None else None
E = edge_list(A)
erecs = ann.edges.to_dict("records") if ann is not None else [{} for _ in range(len(E))]
for (j, i), rec in zip(E, erecs, strict=True):
attrs = {
k: _py(v) for k, v in rec.items() if k not in ("source", "target", "source_index", "target_index")
}
if Wt is not None:
attrs["weight"] = float(Wt[j, i])
G.add_edge(ids[j], ids[i], **attrs)
return G
# --------------------------------------------------------------------------- igraph
[docs]
def from_igraph(g, weight: str | None = None, name: str = "name") -> Bunch:
"""Network from a python-igraph graph (vertex attribute ``name`` gives the labels)."""
n = g.vcount()
names = g.vs[name] if name in g.vs.attributes() else [f"x{i + 1}" for i in range(n)]
E = np.asarray(g.get_edgelist(), dtype=int).reshape(-1, 2)
vals = np.asarray(g.es[weight], dtype=float) if weight else np.ones(len(E))
if not g.is_directed():
E, vals = np.vstack([E, E[:, ::-1]]), np.concatenate([vals, vals])
W = sp.csr_array((vals, (E[:, 0], E[:, 1])), shape=(n, n))
data = pd.DataFrame({a: g.vs[a] for a in g.vs.attributes()}) if g.vs.attributes() else None
return _result(W, [str(v) for v in names], data, weights=W if weight else None)
[docs]
def to_igraph(adj, labels=None, **kwargs):
"""python-igraph graph with the annotations of :func:`to_networkx` as attributes."""
try:
import igraph as ig
except ImportError as exc: # pragma: no cover
raise ImportError("to_igraph needs python-igraph: pip install igraph") from exc
G = to_networkx(adj, labels, **kwargs)
g = ig.Graph.from_networkx(G)
if "_nx_name" in g.vs.attributes():
g.vs["name"] = [str(v) for v in g.vs["_nx_name"]]
return g
# --------------------------------------------------------------------------- pandas
[docs]
def from_pandas_edgelist(edges, source="source", target="target", weight=None, nodes=None) -> Bunch:
"""Network from an edge-list DataFrame (one row per edge :math:`x_j\\to x_i`).
``nodes`` (list or DataFrame with a ``label`` column) fixes the node order and adds
isolated nodes; its other columns become ``node_data``.
Examples
--------
>>> import pandas as pd
>>> net = from_pandas_edgelist(pd.DataFrame({"source": ["a", "b"], "target": ["b", "c"]}))
>>> net.labels, int(net.adj.nnz)
(['a', 'b', 'c'], 2)
"""
node_data = None
if nodes is None:
names = list(dict.fromkeys([*map(str, edges[source]), *map(str, edges[target])]))
elif isinstance(nodes, pd.DataFrame):
col = "label" if "label" in nodes.columns else nodes.columns[0]
names = [str(v) for v in nodes[col]]
node_data = nodes.reset_index(drop=True)
else:
names = [str(v) for v in nodes]
index = {v: k for k, v in enumerate(names)}
j = np.array([index[str(v)] for v in edges[source]], dtype=int)
i = np.array([index[str(v)] for v in edges[target]], dtype=int)
vals = np.asarray(edges[weight], dtype=float) if weight else np.ones(len(j))
W = sp.csr_array((vals, (j, i)), shape=(len(names), len(names)))
return _result(W, names, node_data, weights=W if weight else None)
[docs]
def to_pandas(adj, labels=None, *, design=None, method="path_finding", drivers=None, sensors=None, **kw):
"""Node and edge tables (pandas DataFrames) of :func:`nocad.annotation.annotate`."""
A, labels, d0 = _network(adj, labels)
ann = _annotated(A, labels, design if design is not None else d0, True, method, drivers, sensors, **kw)
return ann.nodes, ann.edges
# --------------------------------------------------------------------------- state space
[docs]
def from_state_space(A, B=None, C=None, D=None, labels=None) -> Bunch:
r"""Network of a state-space model: :math:`\mathbf{W}=\mathbf{A}^{\mathsf T}`.
The driver nodes are the non-zero rows of :math:`\mathbf{B}`, the sensor nodes the
non-zero columns of :math:`\mathbf{C}`.
Examples
--------
>>> net = from_state_space([[-1, 0], [1, -1]], B=[[1], [0]], C=[[0, 1]])
>>> net.adj.toarray().astype(int).tolist(), net.drivers.tolist(), net.sensors.tolist()
([[1, 1], [0, 1]], [0], [1])
"""
As = sp.csr_array(A) if sp.issparse(A) else sp.csr_array(np.atleast_2d(np.asarray(A, dtype=float)))
n = As.shape[0]
adj = as_adjacency(sp.csr_array(As.T))
drivers = sensors = None
if B is not None:
Bs = sp.csr_array(B) if sp.issparse(B) else sp.csr_array(np.asarray(B, dtype=float).reshape(n, -1))
drivers = np.flatnonzero(np.asarray((Bs != 0).sum(axis=1)).ravel())
if C is not None:
Cs = sp.csr_array(C) if sp.issparse(C) else sp.csr_array(np.asarray(C, dtype=float).reshape(-1, n))
sensors = np.flatnonzero(np.asarray((Cs != 0).sum(axis=0)).ravel())
labels = [str(v) for v in labels] if labels is not None else [f"x{i + 1}" for i in range(n)]
return _result(adj, labels, None, drivers=drivers, sensors=sensors, A=A, B=B, C=C, D=D)
[docs]
def from_control(sys, labels=None) -> Bunch:
"""Network of a python-control ``StateSpace`` system (state names become labels)."""
if labels is None:
labels = list(getattr(sys, "state_labels", []) or []) or None
return from_state_space(
np.asarray(sys.A), np.asarray(sys.B), np.asarray(sys.C), np.asarray(sys.D), labels=labels
)
[docs]
def to_control(obj, values: str = "random", random_state=0, dt=0):
"""python-control ``StateSpace`` system with the structure of a design.
Parameters
----------
obj : InputOutputDesign or tuple (A, B, C, D) of zero patterns
values : {"random", "pattern"}, default="random"
``"random"``: a random realization of the free parameters of :math:`\\mathbf{A}`
(generic values, as in the structural theory); ``"pattern"``: the 0/1 pattern.
random_state : int or numpy.random.Generator
dt : 0 or True or float
Sampling time (0: continuous time).
Returns
-------
sys : control.StateSpace with state, input and output names.
"""
try:
import control
except ImportError as exc: # pragma: no cover
raise ImportError("to_control needs python-control: pip install control") from exc
from .design import InputOutputDesign
from .structural import random_realization
if isinstance(obj, InputOutputDesign):
A, B, C, D = obj.matrices(dense=False)
labels = list(getattr(obj, "labels_", None) or node_labels(obj.adj_))
else:
A, B, C, D = obj
labels = [f"x{i + 1}" for i in range(np.shape(A)[0])]
A = sp.csr_array(A) if sp.issparse(A) else sp.csr_array(np.asarray(A, dtype=float))
Av = (
random_realization(A, random_state).toarray()
if values == "random"
else (A != 0).toarray().astype(float)
)
B = (sp.csr_array(B).toarray() if sp.issparse(B) else np.asarray(B, dtype=float)) != 0
C = (sp.csr_array(C).toarray() if sp.issparse(C) else np.asarray(C, dtype=float)) != 0
D = sp.csr_array(D).toarray() if sp.issparse(D) else np.asarray(D, dtype=float)
m, p = B.shape[1], C.shape[0]
return control.ss(
Av,
B.astype(float),
C.astype(float),
D.reshape(p, m),
dt,
states=labels,
inputs=[f"u{k + 1}" for k in range(m)],
outputs=[f"y{k + 1}" for k in range(p)],
)
# --------------------------------------------------------------------------- MATLAB
[docs]
def read_mat(path, variable: str | None = None) -> Bunch:
"""Read a MATLAB file: state-space matrices ``A, B, C, D`` or a network matrix.
If the file holds ``A`` it is read as a state matrix (:math:`\\mathbf{W}=\\mathbf{A}^{\\mathsf T}`),
with ``B`` and ``C`` giving the configuration; otherwise ``variable`` (default: the
first square matrix, ``adj``/``W`` preferred) is read as an adjacency matrix. A cell
array ``labels`` gives the node names.
"""
from scipy.io import loadmat
m = loadmat(str(path), squeeze_me=True)
keys = [k for k in m if not k.startswith("__")]
labels = None
if "labels" in m:
labels = [str(v) for v in np.atleast_1d(m["labels"])]
if variable is None and "A" in m:
return from_state_space(m["A"], m.get("B"), m.get("C"), m.get("D"), labels=labels)
if variable is None:
pref = [k for k in ("adj", "W", "network") if k in m]
squares = [
k
for k in keys
if hasattr(m[k], "shape") and len(m[k].shape) == 2 and m[k].shape[0] == m[k].shape[1]
]
if not (pref or squares):
raise ValueError(f"no square matrix in {path}")
variable = (pref or squares)[0]
adj = as_adjacency(m[variable])
if labels is None or len(labels) != adj.shape[0]:
labels = [f"x{i + 1}" for i in range(adj.shape[0])]
return _result(adj, labels, None)
[docs]
def write_mat(path, obj, labels=None, *, method="path_finding", design=None):
"""Write ``A, B, C, D``, the adjacency matrix ``adj``, ``labels`` and the 1-based
``drivers`` / ``sensors`` for the NOCAD MATLAB toolbox."""
from scipy.io import savemat
from .design import InputOutputDesign
A, labels, d0 = _network(obj, labels)
design = design if design is not None else (d0 if d0 is not None else InputOutputDesign(method).fit(A))
As, Bs, Cs, Ds = design.matrices(dense=True)
savemat(
str(path),
{
"A": np.asarray(As, dtype=float),
"B": np.asarray(Bs, dtype=float),
"C": np.asarray(Cs, dtype=float),
"D": np.asarray(Ds, dtype=float),
"adj": A.astype(float).toarray(),
"labels": np.array(labels, dtype=object),
"drivers": design.driver_nodes_ + 1.0,
"sensors": design.sensor_nodes_ + 1.0,
},
do_compression=True,
)
# --------------------------------------------------------------------------- DOT
def _q(s) -> str:
return '"' + str(s).replace("\\", "\\\\").replace('"', '\\"') + '"'
[docs]
def to_dot(
adj, labels=None, *, include_io: bool = True, rank: str | None = "control", annotate_kwargs=None, **kw
) -> str:
"""Graphviz DOT source of an annotated network.
Nodes are colored by role (driver blue, sensor vermilion, both purple), matched edges
are green, inputs and outputs are boxes, and with ``rank="control"`` (or
``"observation"``) the components of one level of the hierarchy share a rank, so that
``dot -Tpdf`` draws the SCC hierarchy.
"""
G = to_networkx(adj, labels, node_ids="index", **(annotate_kwargs or {}), **kw)
lines = [
"digraph nocad {",
' graph [rankdir=TB, splines=true, nodesep=0.35, ranksep=0.55, fontname="Helvetica"];',
' node [shape=circle, style=filled, color=white, fontcolor=white, fontname="Helvetica", '
"fontsize=10, width=0.42, fixedsize=true];",
f' edge [color="{_EDGE_HEX}", arrowsize=0.7];',
]
for v, d in G.nodes(data=True):
col = _ROLE_HEX.get(d.get("io_role", "state"), _ROLE_HEX["state"])
tip = "; ".join(
f"{k}={d[k]}"
for k in ("io_role", "control_role", "observation_role", "scc", "control_depth")
if k in d
)
lines.append(f" n{v} [label={_q(d['label'])}, fillcolor={_q(col)}, tooltip={_q(tip)}];")
if rank and G.number_of_nodes() and f"{rank}_level" in next(iter(G.nodes.values())):
key = f"{rank}_level"
levels = {}
for v, d in G.nodes(data=True):
levels.setdefault(d[key], []).append(v)
for lv in sorted(levels):
lines.append(" { rank=same; " + " ".join(f"n{v};" for v in levels[lv]) + " }")
for j, i, d in G.edges(data=True):
style = f'color="{_MATCHED_HEX}", penwidth=2.0' if d.get("control_matched") else ""
if d.get("control_class") == "redundant" and not d.get("control_matched"):
style = "style=dashed"
lines.append(f" n{j} -> n{i}" + (f" [{style}]" if style else "") + ";")
if include_io and G.number_of_nodes() and "inputs" in next(iter(G.nodes.values())):
io = set()
for v, d in G.nodes(data=True):
for u in filter(None, str(d.get("inputs", "")).split(",")):
io.add((u, "in"))
lines.append(f' {u} -> n{v} [color="{_ROLE_HEX["driver"]}"];')
for y in filter(None, str(d.get("outputs", "")).split(",")):
io.add((y, "out"))
lines.append(f' n{v} -> {y} [color="{_ROLE_HEX["sensor"]}"];')
for name, kind in sorted(io):
col = _ROLE_HEX["driver" if kind == "in" else "sensor"]
lines.append(
f' {name} [shape=box, style="rounded", color="{col}", fontcolor="{col}", fillcolor=white, '
f"width=0.38, height=0.28];"
)
lines.append("}")
return "\n".join(lines) + "\n"
# --------------------------------------------------------------------------- files
def _fmt(path, format):
if format is not None:
return format
ext = pathlib.Path(path).suffix.lower()
if ext not in FORMATS:
raise ValueError(f"unknown file extension {ext!r}; known: {', '.join(sorted(FORMATS))}")
return FORMATS[ext][0]
def _node_link_kwargs(fn):
import inspect
return {"edges": "edges"} if "edges" in inspect.signature(fn).parameters else {}
[docs]
def write(
obj, path, format: str | None = None, *, labels=None, annotate: bool = True, layout="hierarchy", **kwargs
):
"""Write a network, a design or an annotated configuration to a file.
Parameters
----------
obj : network (adjacency, sparse, networkx, DataFrame), InputOutputDesign or a Bunch
with ``adj`` (and ``labels``) such as the result of :func:`read`
path : str or pathlib.Path
Output file; the format follows the extension (see :data:`FORMATS`).
format : str, optional
Override the format name (``"graphml"``, ``"gexf"``, ``"gml"``, ``"cytoscape"``,
``"node_link"``, ``"dot"``, ``"pajek"``, ``"edgelist"``, ``"csv"``, ``"excel"``,
``"matlab"``, ``"npz"``).
annotate : bool, default=True
Include the role annotations of :func:`nocad.annotation.annotate`.
layout : str or ndarray, default="hierarchy"
Node positions stored in GEXF, Cytoscape and GraphML files (``None`` for none).
**kwargs
Passed to :func:`to_networkx` / :func:`nocad.annotation.annotate` (``design``,
``method``, ``drivers``, ``sensors``, ``centrality``, ``robustness``).
Returns
-------
paths : list of pathlib.Path
The files written (CSV writes a node file beside the edge file).
"""
import networkx as nx
path = pathlib.Path(path)
fmt = _fmt(path, format)
A, labels, d0 = _network(obj, labels)
if d0 is not None and "design" not in kwargs:
kwargs["design"] = d0
if fmt == "matlab":
write_mat(path, A, labels, design=kwargs.get("design"), method=kwargs.get("method", "path_finding"))
return [path]
if fmt == "npz":
A0 = sp.coo_array(A)
np.savez_compressed(path, row=A0.row, col=A0.col, shape=np.array(A.shape), labels=np.array(labels))
return [path]
if fmt == "dot":
path.write_text(
to_dot(A, labels, **kwargs) if annotate else to_dot(A, labels, rank=None, annotate=False)
)
return [path]
if fmt in ("csv", "excel"):
keys = ("design", "method", "drivers", "sensors", "centrality", "robustness")
ann = _annotated(
A,
labels,
kwargs.get("design"),
annotate,
kwargs.get("method", "path_finding"),
kwargs.get("drivers"),
kwargs.get("sensors"),
**{k: v for k, v in kwargs.items() if k in keys[4:]},
)
if ann is not None:
nodes, edges = ann.nodes, ann.edges
else:
nodes = pd.DataFrame({"label": labels})
edges = pd.DataFrame(
[(labels[j], labels[i]) for j, i in edge_list(A)], columns=["source", "target"]
)
if fmt == "excel":
with pd.ExcelWriter(path) as xw:
nodes.to_excel(xw, sheet_name="nodes", index=False)
edges.to_excel(xw, sheet_name="edges", index=False)
if ann is not None:
pd.DataFrame({"value": pd.Series(ann.graph)}).to_excel(xw, sheet_name="summary")
return [path]
sep = "\t" if path.suffix.lower() == ".tsv" else ","
node_path = path.with_name(path.stem + "_nodes" + path.suffix)
edges.to_csv(path, index=False, sep=sep)
nodes.to_csv(node_path, index=False, sep=sep)
return [path, node_path]
G = to_networkx(A, labels, annotate=annotate, layout=layout, **kwargs)
if fmt == "graphml":
nx.write_graphml(G, path)
elif fmt == "gexf":
H = G.copy()
for _v, d in H.nodes(data=True):
col = _ROLE_HEX.get(d.get("io_role", "state"), _ROLE_HEX["state"])
viz = {
"color": {"r": int(col[1:3], 16), "g": int(col[3:5], 16), "b": int(col[5:7], 16), "a": 1.0}
}
if "x" in d:
viz["position"] = {"x": 100 * d["x"], "y": 100 * d["y"], "z": 0.0}
d["viz"] = viz
nx.write_gexf(H, path)
elif fmt == "gml":
H = nx.relabel_nodes(G, {v: str(v) for v in G.nodes()})
for _, d in H.nodes(data=True):
d.update({k: int(v) for k, v in d.items() if isinstance(v, bool)})
for _, _, d in H.edges(data=True):
d.update({k: int(v) for k, v in d.items() if isinstance(v, bool)})
H.graph = {k: (int(v) if isinstance(v, bool) else v) for k, v in H.graph.items()}
nx.write_gml(H, path)
elif fmt == "cytoscape":
data = nx.cytoscape_data(G)
for el in data["elements"]["nodes"]:
d = el["data"]
if "classes" in d:
el["classes"] = d["classes"]
if "x" in d:
el["position"] = {"x": 100 * d["x"], "y": -100 * d["y"]}
for el in data["elements"]["edges"]:
if "classes" in el["data"]:
el["classes"] = el["data"]["classes"]
path.write_text(json.dumps(data, indent=1))
elif fmt == "node_link":
path.write_text(json.dumps(nx.node_link_data(G, **_node_link_kwargs(nx.node_link_data)), indent=1))
elif fmt == "pajek":
H = nx.DiGraph()
H.add_nodes_from(str(v) for v in G.nodes())
H.add_edges_from((str(a), str(b)) for a, b in G.edges())
nx.write_pajek(H, path)
elif fmt == "edgelist":
lines = ["# nocad edge list: start<TAB>end, one edge per line", "# nodes:\t" + "\t".join(labels)]
lines += [f"{labels[j]}\t{labels[i]}" for j, i in edge_list(A)]
path.write_text("\n".join(lines) + "\n")
else: # pragma: no cover
raise ValueError(f"cannot write format {fmt!r}")
return [path]
[docs]
def read(path, format: str | None = None, **kwargs) -> Bunch:
"""Read a network (and a stored configuration) from a file.
Returns
-------
net : Bunch with ``adj``, ``labels``, ``n_states``, ``node_data`` (attributes found in
the file), ``drivers`` and ``sensors`` (from ``driver``/``sensor`` attributes or
from B and C, else None); MATLAB files also give ``A, B, C, D``.
Examples
--------
>>> import tempfile, pathlib
>>> from nocad.datasets import load_nocad_example
>>> f = pathlib.Path(tempfile.mkdtemp()) / "example.graphml"
>>> _ = write(load_nocad_example().adj, f)
>>> net = read(f)
>>> net.n_states, net.drivers.tolist(), net.sensors.tolist()
(9, [7], [0, 8])
"""
import networkx as nx
path = pathlib.Path(path)
fmt = _fmt(path, format)
if fmt == "matlab":
return read_mat(path, **kwargs)
if fmt == "npz":
z = np.load(path, allow_pickle=False)
n = int(z["shape"][0])
adj = sp.csr_array((np.ones(z["row"].size, bool), (z["row"], z["col"])), shape=(n, n))
return _result(adj, [str(v) for v in z["labels"]], None)
if fmt in ("csv", "excel"):
if fmt == "excel":
sheets = pd.read_excel(path, sheet_name=None)
edges = sheets.get("edges", next(iter(sheets.values())))
nodes = sheets.get("nodes")
else:
sep = "\t" if path.suffix.lower() == ".tsv" else ","
edges = pd.read_csv(path, sep=sep, dtype={"source": str, "target": str})
node_path = path.with_name(path.stem + "_nodes" + path.suffix)
nodes = pd.read_csv(node_path, sep=sep, dtype={"label": str}) if node_path.exists() else None
src = kwargs.get("source", "source" if "source" in edges.columns else edges.columns[0])
tgt = kwargs.get("target", "target" if "target" in edges.columns else edges.columns[1])
return from_pandas_edgelist(edges, src, tgt, weight=kwargs.get("weight"), nodes=nodes)
if fmt == "graphml":
G = nx.read_graphml(path)
elif fmt == "gexf":
G = nx.read_gexf(path)
elif fmt == "gml":
G = nx.read_gml(path, label="id") if kwargs.get("by_id") else nx.read_gml(path)
elif fmt == "cytoscape":
G = nx.cytoscape_graph(json.loads(path.read_text()))
elif fmt == "node_link":
G = nx.node_link_graph(json.loads(path.read_text()), **_node_link_kwargs(nx.node_link_graph))
elif fmt == "pajek":
G = nx.DiGraph(nx.read_pajek(path))
elif fmt == "edgelist":
order, rows = None, []
for line in path.read_text().splitlines():
if line.startswith("# nodes:"):
order = line.split("\t")[1:] if "\t" in line else line[len("# nodes:") :].split()
elif line.strip() and not line.startswith("#"):
parts = line.split("\t") if "\t" in line else line.split(kwargs.get("delimiter"))
rows.append((parts[0].strip(), parts[1].strip()))
edges = pd.DataFrame(rows, columns=["source", "target"])
return from_pandas_edgelist(edges, nodes=order)
else: # pragma: no cover
raise ValueError(f"cannot read format {fmt!r}")
if not G.is_directed():
G = G.to_directed()
net = from_networkx(G, weight=kwargs.get("weight"))
if net.node_data is not None and "label" in net.node_data.columns:
net.labels = [str(v) for v in net.node_data["label"]]
return net