"""Produce the iit:result/albantakis-2023-fig2-ab-structure canon entry.

The Φ-structure of the complex aB in the three-unit substrate of the IIT 4.0
paper (Albantakis et al. 2023, PLoS Comput Biol 19(10):e1011465): its
distinctions (Fig 2) and the relation between distinctions a and aB (Fig 4).
The substrate is ``pyphi.examples.iit4_2023_fig1a_substrate`` in state aBC,
with C as a background condition.

The script unfolds the Φ-structure under the current formulation
(iit-4.0-2026) and under the formulation as published (iit-4.0-2023).
Relations are enumerated (PyPhi's concrete backend) so that the relation
{a, aB} can be read off by its mechanisms.

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-fig2-ab-structure.py
"""

from importlib.metadata import version

import pyphi
from pyphi.conf import presets

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


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)
    )


if __name__ == "__main__":
    pyphi.config.progress_bars = False
    print("pyphi", version("pyphi"))
    print("state", label(range(len(STATE))), "system", label(SYSTEM))
    substrate = pyphi.examples.iit4_2023_fig1a_substrate()
    for formalism in ("IIT_4_0_2026", "IIT_4_0_2023"):
        with presets.use(formalism), pyphi.config.override(
            relation_computation="CONCRETE"
        ):
            structure = pyphi.System(substrate, state=STATE, subset=SYSTEM).ces()
        print("formalism", formalism)
        print(f"  phi_s {float(structure.sia.phi):.4f}",
              f"distinctions {len(structure.distinctions)}",
              f"sum_phi_d {float(structure.sum_phi_distinctions):.4f}",
              f"relations {structure.relations.num_relations()}",
              f"sum_phi_r {float(structure.sum_phi_relations):.4f}",
              f"Phi {float(structure.big_phi):.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):>3} {label(cause, cause):>3} "
                  f"{label(effect, effect):>3} {float(d.phi):.4f}")
        for r in structure.relations:
            mechanisms = sorted(map(tuple, r.mechanisms), key=lambda m: (len(m), m))
            print("    relation", "{" + ", ".join(map(label, mechanisms)) + "}",
                  f"phi_r {float(r.phi):.4f} faces {r.num_faces}")
