Interoperability: NetworkX, files and role annotations#

nocad takes networks from NetworkX, igraph, pandas edge lists, state-space matrices, python-control systems and a dozen file formats, and gives them back with every node and edge labelled by its role: driver or sensor node, critical, intermittent or redundant across all maximum matchings, driver type, strongly connected component and level of the hierarchy, control and observation depth, stem or bud of a cactus, matched edge, edge class, connection type. A small process with named state variables is built in NetworkX, designed, annotated, written to GraphML, GEXF (Gephi), Cytoscape JSON, Graphviz DOT, CSV, Excel and MATLAB files, read back, and drawn both with NetworkX’s own functions and with nocad.viz.plot_annotation().

A named process network in NetworkX#

A reactor with a cooling jacket and a separator whose bottom stream is recycled: levels hR, hS, concentrations cR, cS, cP, temperatures TR, TJ. Every balance depends on its own state (self-loops); the reaction couples concentration and temperature in both directions, the jacket exchanges heat with the reactor, and the recycle closes a loop between the two units.

import pathlib
import tempfile

import matplotlib.pyplot as plt
import networkx as nx

import nocad
from nocad.plotting import ROLE_COLORS
from nocad.viz import plot_annotation

G = nx.DiGraph()
G.add_edges_from([("hR", "hS"), ("hS", "hR"), ("hR", "cR"), ("cR", "TR"), ("TR", "cR"), ("TJ", "TR"),
                  ("TR", "TJ"), ("cR", "cS"), ("cS", "cR"), ("cS", "cP"), ("hS", "cS")])
G.add_edges_from((v, v) for v in ["hR", "hS", "cR", "cS", "TR", "TJ"])

# [snippet:interop]
design = nocad.InputOutputDesign("minimum").fit(G)  # node names are kept
print("drivers:", [design.labels_[v] for v in design.driver_nodes_],
      " sensors:", [design.labels_[v] for v in design.sensor_nodes_])
ann = design.annotate()                             # node and edge tables (pandas)
print(ann.nodes[["label", "io_role", "control_role", "scc", "control_level", "control_depth",
                 "control_cactus"]].to_string(index=False))
out = pathlib.Path(tempfile.mkdtemp())
for ext in (".graphml", ".gexf", ".cyjs", ".dot", ".csv", ".xlsx", ".mat"):
    files = design.write(out / f"process{ext}")    # annotations become attributes
    print(f"{ext:9s}", ", ".join(f"{p.name} ({p.stat().st_size} B)" for p in files))
net = nocad.read_network(out / "process.graphml")   # the configuration comes back
print("read back:", net.labels, "drivers", net.drivers.tolist(), "sensors", net.sensors.tolist())
# [/snippet:interop]
drivers: ['hS']  sensors: ['cP']
label io_role control_role  scc  control_level  control_depth control_cactus
   hR   state intermittent    0              0              1            bud
   hS  driver intermittent    0              0              0           stem
   cR   state intermittent    1              1              2            bud
   TR   state intermittent    1              1              3            bud
   TJ   state intermittent    1              1              4            bud
   cS   state intermittent    1              1              1           stem
   cP  sensor intermittent    2              2              2           stem
.graphml  process.graphml (19580 B)
.gexf     process.gexf (24347 B)
.cyjs     process.cyjs (17212 B)
.dot      process.dot (2049 B)
.csv      process.csv (2459 B), process_nodes.csv (1542 B)
.xlsx     process.xlsx (8260 B)
.mat      process.mat (616 B)
read back: ['hR', 'hS', 'cR', 'TR', 'TJ', 'cS', 'cP'] drivers [1] sensors [6]

Drawing with NetworkX from the annotations#

The annotated digraph carries everything NetworkX needs to draw the hierarchy itself: the multipartite layout uses the control_level attribute as layer, the node colors come from io_role, matched edges are thick and green.

H = design.to_networkx()
pos = nx.multipartite_layout(H, subset_key="control_level", align="horizontal")
pos = {v: (x, -H.nodes[v]["control_level"]) for v, (x, _) in pos.items()}
colors = {"driver": ROLE_COLORS["driver"], "sensor": ROLE_COLORS["sensor"],
          "driver+sensor": ROLE_COLORS["both"], "state": ROLE_COLORS["state"]}
fig, ax = plt.subplots(figsize=(5.6, 4.2))
nx.draw_networkx_nodes(H, pos, ax=ax, node_size=620, edgecolors="white",
                       node_color=[colors[H.nodes[v]["io_role"]] for v in H])
nx.draw_networkx_labels(H, pos, ax=ax, font_size=9, font_color="white", font_weight="bold")
matched = [(a, b) for a, b, d in H.edges(data=True) if d["control_matched"]]
other = [(a, b) for a, b, d in H.edges(data=True) if not d["control_matched"]]
nx.draw_networkx_edges(H, pos, ax=ax, edgelist=other, edge_color="#8A96A3", arrowsize=12, node_size=620,
                       connectionstyle="arc3,rad=0.12")
nx.draw_networkx_edges(H, pos, ax=ax, edgelist=matched, edge_color=ROLE_COLORS["matched"], width=2.4,
                       arrowsize=14, node_size=620, connectionstyle="arc3,rad=0.12")
ax.set_title("NetworkX drawing of the annotated graph (layers: control_level)", fontsize=10)
ax.axis("off")
fig.tight_layout()
NetworkX drawing of the annotated graph (layers: control_level)

The same roles in nocad, with a NetworkX layout#

nocad.viz.plot_annotation() colors the nodes by any column of the annotation: numeric columns on a sequential scale, categorical ones with fixed colors. Positions may be a NetworkX pos dictionary keyed by the node names.

layout = nx.kamada_kawai_layout(G)
fig, axes = plt.subplots(1, 2, figsize=(9.6, 4.0))
plot_annotation(G, "control_depth", ann, pos=layout, ax=axes[0], node_size=650, title="control depth")
plot_annotation(G, "control_cactus", ann, pos=layout, ax=axes[1], node_size=650, title="part of the control cactus")
fig.tight_layout()
control depth, part of the control cactus

Parameter study: annotations of a larger network#

For the 131 frontal neurons of C. elegans the tables answer questions that would otherwise need several function calls: how the driver nodes split by type, and which part of the cacti the redundant neurons belong to. The GEXF file opens in Gephi with the role colors and the anatomical positions.

import pandas as pd

worm = nocad.datasets.load_network("celegans131")
wann = nocad.annotate(worm.adj, labels=worm.labels)
print(pd.crosstab(wann.nodes.control_role, wann.nodes.control_cactus))
print(wann.nodes.loc[wann.nodes.driver, "driver_type"].value_counts().to_string())
files = nocad.write_network(worm.adj, out / "celegans.gexf", labels=worm.labels, layout=worm.positions)
print(files[0].name, files[0].stat().st_size, "bytes")
control_cactus  bud  stem
control_role
critical          0    10
intermittent     12    18
redundant         9    82
driver_type
source      10
internal     2
celegans.gexf 677318 bytes

Take-away. The annotation tables are the common language of the toolbox and of other software: every file written by nocad carries the roles of the nodes and edges, and every file read back restores the network and its configuration.

Total running time of the script: (0 minutes 0.863 seconds)

Gallery generated by Sphinx-Gallery