"""Produce the iit:result/albantakis-2023-fig6b-modular canon entry.

The modular network of the IIT 4.0 paper (Albantakis et al. 2023, PLoS Comput
Biol 19(10):e1011465), Fig 6B, in state Abcdef. Six logistic units
(Eq 60, k = 4) in three modules of two strongly coupled units (ab, cd,
ef), with weak connections between modules. PyPhi ships the
substrate, with weights supplied by the authors, as
``pyphi.examples.iit4_2023_fig6b_substrate``.

The script finds the complexes and unfolds the Φ-structure of each, under the
current formulation (iit-4.0-2026) and under the formulation as published
(iit-4.0-2023). For each complex it also prints the terms whose minimum is
φ_s: φ_c, φ_e, and the intrinsic differentiation and intrinsic specification
of the cause and effect. Relations are summed analytically (PyPhi's default).

Run with uv, which installs PyPhi 2.0.0rc4 for the run (a few seconds):

    uv run --with "pyphi==2.0.0rc4" python canon/albantakis-2023-fig6b-modular.py
"""

from importlib.metadata import version

import pyphi
from pyphi.conf import presets
from pyphi.substrate import complexes

SUBSTRATE = pyphi.examples.iit4_2023_fig6b_substrate
LABELS = "ABCDEF"
STATE = (1, 0, 0, 0, 0, 0)  # Abcdef; PyPhi codes the paper's -1 as 0


def label(units, states=None):
    """Units as letters, uppercase for ON: label((0, 1)) == "Ab"."""
    states = dict(enumerate(STATE)) if states is None else states
    return "".join(
        LABELS[u] if states[u] else LABELS[u].lower() for u in sorted(units)
    )


def cut(partition, cm):
    """The existing connections a system partition severs, e.g. "A→B"."""
    return " ".join(f"{LABELS[i]}→{LABELS[j]}"
                    for i, j in sorted(partition.removed_edges()) if cm[i][j])


def report(substrate, formalism):
    print("formalism", formalism)
    for c in complexes(substrate, STATE, formalism=formalism):
        units = c.sia.node_indices
        with presets.use(formalism):
            structure = pyphi.System(substrate, state=STATE, subset=units).ces()
        relations = structure.relations
        print(f"  complex {label(units)} phi_s {float(c.sia.phi)!r}",
              f"cut {cut(c.sia.partition, substrate.cm)}",
              f"distinctions {len(structure.distinctions)}",
              f"sum_phi_d {float(structure.sum_phi_distinctions):.4f}",
              f"relations {relations.num_relations()}",
              f"sum_phi_r {float(relations.sum_phi()):.4f}",
              f"Phi {float(structure.big_phi):.4f}")
        sia = c.sia
        cause, effect = pyphi.Direction.CAUSE, pyphi.Direction.EFFECT
        print(f"    phi_c {float(sia.cause.phi):.4f}",
              f"phi_e {float(sia.effect.phi):.4f}",
              f"i_diff_c {float(sia.intrinsic_differentiation[cause]):.4f}",
              f"i_diff_e {float(sia.intrinsic_differentiation[effect]):.4f}",
              f"i_spec_c {float(sia.intrinsic_specification[cause]):.4f}",
              f"i_spec_e {float(sia.intrinsic_specification[effect]):.4f}",
              f"p(effect state) {float(sia.effect.selectivity):.4f}")
        for d in sorted(structure.distinctions,
                        key=lambda d: (len(d.mechanism), d.mechanism)):
            cause = dict(zip(d.cause.purview, d.cause.specified_state.state))
            effect = dict(zip(d.effect.purview, d.effect.specified_state.state))
            print(f"    {label(d.mechanism):>6} {label(cause, cause):>6} "
                  f"{label(effect, effect):>6} {float(d.phi):.4f}")


if __name__ == "__main__":
    pyphi.config.progress_bars = False
    print("pyphi", version("pyphi"))
    print("state", label(range(len(STATE))))
    for formalism in ("IIT_4_0_2026", "IIT_4_0_2023"):
        report(SUBSTRATE(), formalism)
