"""Produce the iit:result/comolatti-2025-time-grid canon entry.

The directed 1D grid of Comolatti, Grasso & Tononi (2025, iScience 28:113434),
Fig 3A, in its Fig 3B state abcDefG (units D and G ON). Seven binary units,
each with a self-connection (0.3), a strong lateral connection (0.6) to its
neighbour toward a (the "then") and a weak one (0.1) toward G (the "now",
where the input array enters). Each unit endorses the grid's current macro
state (STAR Methods): an input is excitatory when its unit and the target
agree in that state and inhibitory otherwise, through a logistic with
determinism 1 and no threshold, as in the paper's printed activation
function. The input array lies outside the system and matches the state, so
its drive is non-selective and drops out of the TPM.

The authors' notebook computes mechanism integrated information over wedge
tripartitions of each mechanism, not over all joint partitions (the 2026
default); the paper does not state the scheme. This script sets that scheme;
everything else is the default IIT 4.0 (2026) configuration.

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

    uv run --with "pyphi==2.0.0rc4" python canon/comolatti-2025-time-grid.py
"""

from importlib.metadata import version

import numpy as np
import pyphi
from pyphi.relations import all_relations
from pyphi.substrate_generator import build_substrate, ising

LABELS = "abcdefg"
STATE = (0, 0, 0, 1, 0, 0, 1)  # abcDefG


def substrate(state=STATE):
    """The grid's substrate; its TPM depends on the endorsed ``state``."""
    n = len(LABELS)
    # weights[j, k]: connection from unit j to unit k
    weights = 0.3 * np.eye(n) + 0.6 * np.eye(n, k=-1) + 0.1 * np.eye(n, k=1)
    spins = 2 * np.asarray(state) - 1
    return build_substrate(
        ising.probability,  # logistic of the weighted ±1 inputs, minus `field`
        weights * np.outer(spins, spins),  # endorsement: sign set by agreement
        node_labels=pyphi.labels.NodeLabels(LABELS, range(n)),
        field=0.0,  # no threshold; temperature 1 = determinism 1
    )


def label(units, states):
    """Units as letters, uppercase for ON: label((3, 4), {3: 1, 4: 0}) == "De"."""
    return "".join(
        LABELS[u].upper() if states[u] else LABELS[u] for u in sorted(units)
    )


def is_contiguous(mechanism):
    return list(mechanism) == list(range(mechanism[0], mechanism[-1] + 1))


if __name__ == "__main__":
    pyphi.config["iit.mechanism_partition_scheme"] = "WEDGE_TRIPARTITION"
    pyphi.config.progress_bars = False
    print("pyphi", version("pyphi"))
    print("formalism", pyphi.config.formalism.iit.version, "with",
          pyphi.config.formalism.iit.mechanism_partition_scheme)
    print("state", label(range(len(STATE)), dict(enumerate(STATE))))

    system = pyphi.System(substrate(), state=STATE)
    parallel = {"parallel": True, "sequential_threshold": 1}
    with pyphi.config.override(
        parallel=True, parallel_distinction_evaluation=parallel
    ):
        sia = system.sia()
        distinctions = system.distinctions(congruent=True)
    print("phi_s", sia.phi)
    print("partition", sia.partition)

    ds = sorted(distinctions, key=lambda d: (len(d.mechanism), d.mechanism))
    contiguous = [d for d in ds if is_contiguous(d.mechanism)]
    print("distinctions", len(ds), "contiguous", len(contiguous))
    print(f"{'mechanism':>9} {'cause':>8} {'effect':>8} {'phi_d':>8}")
    for d in contiguous:
        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, STATE):>9} {label(cause, cause):>8} "
              f"{label(effect, effect):>8} {float(d.phi):8.5f}")

    # Relations binding two distinctions, plus self-relations (one distinction
    # whose cause and effect purviews overlap congruently) — the count
    # reported as "2-Relations" in the paper's Fig 3B.
    for name, subset in (("all", ds), ("contiguous", contiguous)):
        rels = list(all_relations(subset, min_degree=2, max_degree=2))
        pairs = sum(1 for r in rels if len(r) == 2)
        selves = sum(1 for r in rels if len(r) == 1)
        print(f"2-relations ({name}): {pairs} pairs + {selves} self = "
              f"{pairs + selves}")
