"""
The frontal neural network of C. elegans
========================================

The NOCAD software paper analysed the 131 frontal neurons of *C. elegans* (positions
and labels from Kaiser and Hilgetag). The network has 764 connections; its
condensation is a bow tie: a few source neurons feed one large strongly connected
core, which feeds a few sinks. Maximum matching, path finding and the exact minimum
agree on twelve driver neurons; the neurons' anatomical positions show where control
enters and how far it has to travel.
"""

# %%
# Design and hierarchy
# --------------------
import matplotlib.pyplot as plt
import numpy as np

import nocad
from nocad.datasets import load_network
from nocad.viz import plot_depth_map, plot_scc_hierarchy

net = load_network("celegans131")
# [snippet:celegans]
design = nocad.InputOutputDesign().fit(net.adj)
cond = nocad.condensation(net.adj)
print(f"{net.n_states} neurons, {net.n_edges} connections, {cond.n_components} components, "
      f"largest {cond.sizes.max()}")
print("driver neurons:", [net.labels[v] for v in design.driver_nodes_])
print("sensor neurons:", [net.labels[v] for v in design.sensor_nodes_])
# [/snippet:celegans]
fig, ax = plt.subplots(figsize=(7.4, 5.6))
plot_scc_hierarchy(net.adj, design.driver_nodes_, design.sensor_nodes_, ax=ax, labels=False, node_size=60,
                   legend=False, title="condensation of the frontal network: a bow tie")

# %%
# Control depth on the anatomical layout
# --------------------------------------
pos = (net.positions - net.positions.mean(axis=0)) * np.array([60.0, 160.0])
fig, ax = plt.subplots(figsize=(9.0, 4.2))
plot_depth_map(net.adj, design.driver_nodes_, pos=pos, ax=ax, labels=False, node_size=55, regions=False,
               title="control depth of the neurons (anatomical positions)")

# %%
# Parameter study: methods and roles
# ----------------------------------
for method in ("matching", "signal_sharing", "path_finding", "minimum"):
    d = nocad.InputOutputDesign(method).fit(net.adj)
    print(f"{method:15s} inputs={d.n_inputs_:2d} drivers={d.n_drivers_:2d} sensors={d.n_sensors_:2d}")
roles = nocad.node_roles(net.adj)
print({r: int((roles == r).sum()) for r in ("critical", "intermittent", "redundant")})

# %%
# **Take-away.** In the frontal network the inputs are dictated by its source neurons
# and the outputs by its sinks; the large core is controlled through them in at most a
# few steps.
