"""Produce the iit:result/albantakis-2023-fig1-triad canon entry.

The three-unit substrate aBC that the IIT 4.0 paper (Albantakis et al. 2023,
PLoS Comput Biol 19(10):e1011465) uses to introduce the postulates, Fig 1,
in state aBC = (-1, 1, 1). Each unit is a logistic of its weighted inputs
(Eq 60) with k = 4 and the weights of the Fig 1A causal model; PyPhi ships it
as ``pyphi.examples.iit4_2023_fig1a_substrate``.

The script computes φ_s for every candidate system and the complexes, under
the current formulation (iit-4.0-2026) and under the formulation as
published (iit-4.0-2023), to compare with the values in Fig 1E. For each
complex it also prints the terms whose minimum is φ_s: φ_c and φ_e at the
minimum partition (Fig 1D) and the intrinsic differentiation and intrinsic
specification of the cause and effect (Mayner et al. 2026, §2.2-2.4).

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-fig1-triad.py
"""

from importlib.metadata import version

import pyphi
from pyphi.substrate import all_sias, complexes

LABELS = "ABC"
STATE = (0, 1, 1)  # aBC; PyPhi codes the paper's -1 as 0


def label(units):
    """Units as letters, uppercase for ON: label((0, 1)) == "aB"."""
    return "".join(
        LABELS[u] if STATE[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])


if __name__ == "__main__":
    pyphi.config.progress_bars = False
    print("pyphi", version("pyphi"))
    print("state", label(range(len(STATE))))
    substrate = pyphi.examples.iit4_2023_fig1a_substrate()

    for formalism in ("IIT_4_0_2026", "IIT_4_0_2023"):
        print("formalism", formalism)
        sias = all_sias(substrate, STATE, formalism=formalism)
        for sia in sorted(sias, key=lambda s: -s.phi):
            print(f"  {label(sia.node_indices):>4} phi_s {float(sia.phi):.4f}")
        for i, c in enumerate(complexes(substrate, STATE, formalism=formalism)):
            sia = c.sia
            print(f"  complex {i + 1}: {label(sia.node_indices)}",
                  f"phi_s {float(sia.phi)!r}",
                  f"cut {cut(sia.partition, substrate.cm)}")
            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}")
