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

The non-directed 1D grid of Comolatti, Grasso & Tononi (2025, iScience
28:113434), Fig 12B, all units OFF. It is the directed grid of the
comolatti-2025-time-grid entry with its lateral connections made symmetric:
seven binary units, each with a self-connection (0.3) and a connection of 0.2
to each neighbour, through a logistic with determinism 1 and no threshold.
The paper does not print the space grid's weights; these are chosen to match
the time grid's form.

Mechanism integrated information is computed over wedge tripartitions of each
mechanism, as in the time grid entry; everything else is the default IIT 4.0
(2026) configuration.

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

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

from importlib.metadata import version

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

LABELS = "abcdefg"
STATE = (0, 0, 0, 0, 0, 0, 0)  # abcdefg, all OFF


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.2 * (np.eye(n, k=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))


def interior(mechanism):
    """The mechanism itself up to two units, else the mechanism minus its ends."""
    return tuple(mechanism) if len(mechanism) <= 2 else tuple(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)]

    def reflexive(d):
        return set(d.cause.purview) == set(d.effect.purview)

    print("distinctions", len(ds), "reflexive", sum(map(reflexive, ds)))
    print("contiguous", len(contiguous), "reflexive",
          sum(map(reflexive, contiguous)), "interior",
          sum(tuple(d.cause.purview) == tuple(d.effect.purview)
              == interior(d.mechanism) for d in 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}")
    print("non-reflexive:")
    for d in ds:
        if not reflexive(d):
            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}")
