.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/01_basics/plot_05_interoperability.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code or to run this example in your browser via Binder. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_01_basics_plot_05_interoperability.py: 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 :func:`nocad.viz.plot_annotation`. .. GENERATED FROM PYTHON SOURCE LINES 17-24 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. .. GENERATED FROM PYTHON SOURCE LINES 24-54 .. code-block:: Python 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] .. rst-class:: sphx-glr-script-out .. code-block:: none 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] .. GENERATED FROM PYTHON SOURCE LINES 55-60 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. .. GENERATED FROM PYTHON SOURCE LINES 60-79 .. code-block:: Python 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() .. image-sg:: /auto_examples/01_basics/images/sphx_glr_plot_05_interoperability_001.png :alt: NetworkX drawing of the annotated graph (layers: control_level) :srcset: /auto_examples/01_basics/images/sphx_glr_plot_05_interoperability_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 80-85 The same roles in nocad, with a NetworkX layout ----------------------------------------------- :func:`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. .. GENERATED FROM PYTHON SOURCE LINES 85-91 .. code-block:: Python 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() .. image-sg:: /auto_examples/01_basics/images/sphx_glr_plot_05_interoperability_002.png :alt: control depth, part of the control cactus :srcset: /auto_examples/01_basics/images/sphx_glr_plot_05_interoperability_002.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 92-98 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. .. GENERATED FROM PYTHON SOURCE LINES 98-107 .. code-block:: Python 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") .. rst-class:: sphx-glr-script-out .. code-block:: none 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 .. GENERATED FROM PYTHON SOURCE LINES 108-111 **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. .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.863 seconds) .. _sphx_glr_download_auto_examples_01_basics_plot_05_interoperability.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/ComplexSystemsIntelligence/nocad/main?urlpath=lab/tree/notebooks/auto_examples/01_basics/plot_05_interoperability.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_05_interoperability.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_05_interoperability.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_05_interoperability.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_