"""
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`.
"""

# %%
# 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]

# %%
# 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()

# %%
# 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.
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()

# %%
# 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")

# %%
# **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.
