"""Produce the iit:result/albantakis-2023-fig6d-lattice canon entry.

The specialized lattice of the IIT 4.0 paper (Albantakis et al. 2023, PLoS Comput
Biol 19(10):e1011465), Fig 6D, in state Abcdef. Six logistic units
(Eq 60, k = 4), heterogeneously connected. PyPhi ships the
substrate, with weights supplied by the authors, as
``pyphi.examples.iit4_2023_fig6d_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).

The cause purview of the distinction ef is tied between ab and cd (equal
φ_d). S1 Text of the paper resolves such ties by selecting the purview that
maximizes Φ, which is cd; PyPhi does the same. The figure, computed with the
2023 version of PyPhi, corresponds to ab. The canon reports the S1 Text
resolution and lists its distinctions; the script also substitutes the
reading ab and prints the values that reproduce the figure.

Run with uv, which installs PyPhi 2.0.0rc4 for the run (several minutes on a multicore machine):

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

from importlib.metadata import version

import pyphi
from pyphi.conf import presets
from pyphi.models.distinctions import ResolvedDistinctions
from pyphi.relations import AnalyticalRelations
from pyphi.substrate import complexes

SUBSTRATE = pyphi.examples.iit4_2023_fig6d_substrate
LABELS = "ABCDEF"
STATE = (1, 0, 0, 0, 0, 0)  # Abcdef; PyPhi codes the paper's -1 as 0
TIE_2023 = ((4, 5), (0, 1))  # mechanism ef: cause purview ab, as in Fig 6D


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 resolve_2023(distinctions):
    """Substitute the tied cause reading that the 2023 figure uses."""
    mechanism, purview = TIE_2023
    resolved = []
    for d in distinctions:
        if tuple(d.mechanism) == mechanism:
            cause = next(r for r in d.cause.purview_ties
                         if tuple(r.purview) == purview)
            d = type(d)(mechanism=d.mechanism, cause=cause, effect=d.effect)
        resolved.append(d)
    return ResolvedDistinctions(resolved)


def summary(distinctions):
    relations = AnalyticalRelations(distinctions)
    sum_phi_d = sum(float(d.phi) for d in distinctions)
    return (f"distinctions {len(distinctions)} sum_phi_d {sum_phi_d:.4f} "
            f"relations {relations.num_relations()} "
            f"sum_phi_r {float(relations.sum_phi()):.4f} "
            f"Phi {sum_phi_d + float(relations.sum_phi()):.4f}")


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()
        print(f"  complex {label(units)} phi_s {float(c.sia.phi)!r}",
              f"cut {cut(c.sia.partition, substrate.cm)}")
        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}")
        print("    maximal-Phi tie resolution (S1 Text; PyPhi default):",
              summary(structure.distinctions))
        print("    figure's tie resolution (2023 code):",
              summary(resolve_2023(structure.distinctions)))
        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)
