Source code for pyphi.macro.search

"""Bounded search for intrinsic units and complexes (Marshall et al.
2026, "Applying the postulates to units").

The recursion starts from the micro units, which are axiomatically
valid (Eqs. 16-17 gate macroing only). Each level derives candidate
decompositions ``V`` from the previous level's pool of valid units and
judges each ``(V, W)`` pair once per update grain τ_J the candidate can
take, counted in micro updates. The candidate's mapping does not enter
the criteria, but τ_J bounds its competitor set. Each update grain at
which a decomposition is valid emits that grain's mapped variants into
the pool. Footprints are processed smallest-first, so the competitor
set ``f(U^J, W^J, τ_J)`` always draws on every unit already validated
at strictly finer footprints.

``f(U^J, W^J, τ_J)`` is the set of valid systems whose total micro
constituents are a subset (not necessarily strict) of ``U^J``, whose
background apportionments are non-overlapping subsets of ``W^J``, and
whose units all have a micro grain of at most τ_J, excluding the
candidate ``v^J`` itself (the comparison in Eq. 17 is over
``v' != v^J``). Members are assembled from units validated at
strictly finer footprints, so a system whose constituents equal ``U^J``
competes only when it splits them into several smaller meso/micro units
(a same-union reorganization), while a single unit spanning all of
``U^J`` -- the candidate's own grain -- never enters ``f``. The set
``P(u)`` extends the same assembly to the whole universe (Eq. 19), and
a member is a complex if
it strictly beats every other member whose micro constituents overlap
its own (Eq. 20). Candidate systems whose state is unreachable under
their own TPM specify no cause and cannot exist; they are dropped.

All φₛ evaluations within one driver run share a memo keyed on
the hashable :class:`~pyphi.macro.system.MacroSystem`.
"""

from __future__ import annotations

import itertools
from dataclasses import dataclass
from typing import TYPE_CHECKING
from typing import Any

import numpy as np

from pyphi import exceptions
from pyphi import validate
from pyphi.display import Description
from pyphi.display import Displayable
from pyphi.display import Row
from pyphi.display import Section
from pyphi.display.numbers import format_value
from pyphi.display.tables import capped_table
from pyphi.macro.criteria import Reason
from pyphi.macro.criteria import UnitVerdict
from pyphi.macro.criteria import _as_unit
from pyphi.macro.criteria import canonical_units
from pyphi.macro.criteria import judge_candidate
from pyphi.macro.system import MacroSystem
from pyphi.macro.system import _require_marginalized_background
from pyphi.macro.tpm import _normalized_history
from pyphi.macro.tpm import _system_micro_indices
from pyphi.macro.units import MacroUnit
from pyphi.macro.units import blackbox
from pyphi.macro.units import coarse_grain
from pyphi.macro.units import micro_unit
from pyphi.models.pandas import ToPandasMixin
from pyphi.models.pandas import records_to_frame
from pyphi.substrate import Substrate

if TYPE_CHECKING:
    from pyphi.macro.estimate import SearchEstimate

_MAPPING_POLICIES = ("FAMILIES", "EXHAUSTIVE")
_APPORTIONMENT_POLICIES = ("NONE", "ENUMERATE")


def _require_macro_formalism() -> None:
    """The intrinsic-units macro formalism is defined for IIT 4.0 only, with
    the cause-side background causally marginalized."""
    from pyphi.conf import config as _config

    version = _config.formalism.iit.version
    if version == "IIT_3_0":
        raise ValueError(
            "the intrinsic-units macro framework is not defined for "
            f"IIT_3_0; got config.formalism.iit.version={version!r}"
        )
    _require_marginalized_background()


_INT_BOUNDS = (
    "max_constituents",
    "max_update_grain",
    "max_depth",
    "exhaustive_cap",
    "max_background",
)


[docs] @dataclass(frozen=True) class SearchBounds: """Bounds on the intrinsic-unit search space. Attributes ---------- max_constituents : int Cap on ``|U^J|`` per candidate unit. max_update_grain : int Largest update grain ``tau'`` per level. max_depth : int Macroing levels above micro. mappings : str ``"FAMILIES"`` (coarse-grainings and black-boxings) or ``"EXHAUSTIVE"`` (every surjective table, capped). exhaustive_cap : int Largest sequence-state count for EXHAUSTIVE. apportionment : str ``"NONE"`` or ``"ENUMERATE"`` (assign background micro units to derived candidates). max_background : int Cap on apportioned units when enumerating. """ max_constituents: int = 4 max_update_grain: int = 1 max_depth: int = 1 mappings: str = "FAMILIES" exhaustive_cap: int = 8 apportionment: str = "NONE" max_background: int = 0 def __post_init__(self) -> None: for name in _INT_BOUNDS: value = getattr(self, name) if isinstance(value, np.integer): value = value.item() object.__setattr__(self, name, value) if not isinstance(value, int) or isinstance(value, bool): raise TypeError(f"{name} must be an integer; got {value!r}") if self.max_constituents < 1: raise ValueError( f"max_constituents must be >= 1; got {self.max_constituents}" ) if self.max_update_grain < 1: raise ValueError( f"max_update_grain must be >= 1; got {self.max_update_grain}" ) if self.max_depth < 0: raise ValueError(f"max_depth must be >= 0; got {self.max_depth}") if self.mappings not in _MAPPING_POLICIES: raise ValueError( f"unknown mappings policy {self.mappings!r}; " f"expected one of {_MAPPING_POLICIES}" ) if self.apportionment not in _APPORTIONMENT_POLICIES: raise ValueError( f"unknown apportionment policy {self.apportionment!r}; " f"expected one of {_APPORTIONMENT_POLICIES}" ) if self.apportionment == "ENUMERATE" and self.max_background == 0: raise ValueError('apportionment="ENUMERATE" requires max_background >= 1') @property def max_micro_grain(self) -> int: """Largest micro grain a derived unit can reach (grains compose down the hierarchy).""" return self.max_update_grain**self.max_depth
[docs] def estimate(self, substrate, *, limit: int = 1_000_000) -> SearchEstimate: """Pre-flight estimate of the sweep these bounds define over ``substrate``, by pure counting; see :func:`pyphi.macro.estimate.estimate_search`. Only the substrate's size is read — no TPM is constructed and no φₛ is computed.""" from pyphi.macro.estimate import estimate_search return estimate_search(substrate, bounds=self, limit=limit)
_DEFAULT_BOUNDS = SearchBounds() def _canonical_table(table: tuple[int, ...]) -> tuple[int, ...]: """The representative of ``{table, complement}``. A mapping and its complement define the same partition of the constituents' sequence-states into two classes; the macro unit's two state labels are conventional and the analysis is invariant under relabeling. The representative maps the all-OFF sequence to macro state 0. """ if table[0] == 1: return tuple(1 - entry for entry in table) return table
[docs] def candidate_mappings( num_constituents: int, update_grain: int, bounds: SearchBounds ) -> tuple[tuple[int, ...], ...]: """Deduplicated candidate truth tables for a unit shape. FAMILIES: every non-degenerate ``coarse_grain`` on-count set (update grain 1 only, by the family's definition) plus every nonempty ``blackbox`` output subset (any grain). EXHAUSTIVE: every surjective table when the sequence-state count is within ``exhaustive_cap``; ``ValueError`` above it. Tables are canonicalized up to state-label complementation (the all-OFF sequence maps to macro state 0) and deduplicated, preserving first-seen order. """ tables: list[tuple[int, ...]] = [] seen: set[tuple[int, ...]] = set() def add(table: tuple[int, ...]) -> None: table = _canonical_table(table) if table not in seen: seen.add(table) tables.append(table) if bounds.mappings == "FAMILIES": if update_grain == 1: counts = tuple(range(num_constituents + 1)) for size in range(1, len(counts)): for on_counts in itertools.combinations(counts, size): add(coarse_grain(num_constituents, on_counts)) for size in range(1, num_constituents + 1): for outputs in itertools.combinations(range(num_constituents), size): add(blackbox(num_constituents, update_grain, outputs)) else: # EXHAUSTIVE num_states = (2**num_constituents) ** update_grain if num_states > bounds.exhaustive_cap: raise ValueError( f"EXHAUSTIVE mappings for {num_constituents} constituents " f"at update grain {update_grain} require {num_states} " f"sequence-states, above exhaustive_cap={bounds.exhaustive_cap}" ) for index in range(1, 2**num_states - 1): add(tuple((index >> k) & 1 for k in range(num_states))) return tuple(tables)
def _system_of(substrate, units, micro_history) -> MacroSystem | None: """The system of ``units`` over the full universe, or None. Returns None when the system's state is unreachable under its own TPM: such a system specifies no cause and cannot exist (φₛ = 0). """ units = canonical_units(units) needed = max(unit.micro_grain for unit in units) window = micro_history[len(micro_history) - needed :] try: return MacroSystem.from_micro(substrate, units, window) except exceptions.StateUnreachableError: return None def _system_of_cached(substrate, units, micro_history, system_cache): """``_system_of`` memoized on canonical unit order for one run. Sharing constructions between the collect and judge phases avoids rebuilding the same macro TPMs twice. """ key = canonical_units(units) if key not in system_cache: system_cache[key] = _system_of(substrate, units, micro_history) return system_cache[key] def _phi(substrate, units, micro_history, memo, system_cache): """Memoized ``(system, φₛ)`` of the system of ``units``.""" system = _system_of_cached(substrate, units, micro_history, system_cache) if system is None: return None, None if system not in memo: memo[system] = float(system.sia().phi) return system, memo[system] def _evaluate_one(item) -> float: """Worker entry: φₛ of one ``(system, system_state)`` pair. ``system_state`` may be ``None``; when given, it is the precomputed intrinsic-information state specification, forwarded to ``sia`` so it is not recomputed. The inner ``sia`` runs sequentially: the dispatcher enters ``config.override(parallel=False)`` around the ``map_reduce`` call (see :func:`_evaluate_systems`), so process workers inherit it via the config snapshot and thread workers see the parent's single override. The worker body opens no override of its own. """ system, system_state = item kwargs = {} if system_state is None else {"system_state": system_state} return float(system.sia(**kwargs).phi) def _evaluate_systems(systems, memo, parallel_kwargs=None, system_states=None) -> None: """Evaluate ``systems`` and merge φₛ into ``memo`` in order. Systems already in the memo, duplicates within the batch, and ``None`` (unreachable) entries are skipped. The surviving systems are evaluated in dispatch order -- in parallel when the macro option is enabled, otherwise in-process under the ambient config -- and inserted into the memo in that same order, so a parallel run's memo (and every result derived from it) is identical to a sequential one's. ``system_states`` optionally maps systems to precomputed intrinsic-information state specifications, forwarded to each ``sia`` call. """ from pyphi import conf as _conf from pyphi.conf import config as _config from pyphi.parallel import map_reduce pending: list[MacroSystem] = [] seen: set[MacroSystem] = set() for system in systems: if system is None or system in memo or system in seen: continue seen.add(system) pending.append(system) if not pending: return states = system_states or {} pkwargs = _conf.parallel_kwargs( _config.infrastructure.parallel_macro_system_evaluation, **(parallel_kwargs or {}), ) if pkwargs.get("parallel"): pkwargs["ordered"] = True pkwargs["total"] = len(pending) pkwargs.setdefault("desc", "Evaluating macro systems") # Force the inner ``sia`` calls sequential so search-level # parallelism stays one pool deep (nested pools merely # oversubscribe). The override is entered once here, after the # dispatch decision: process workers inherit it through the # config snapshot captured at dispatch, and thread workers read # the parent's live config directly. Opening the override inside # each worker body instead would interleave enter/exit pairs on # the shared global under the thread backend. with _config.override(parallel=False): phis = map_reduce( _evaluate_one, [(system, states.get(system)) for system in pending], **pkwargs, ) else: phis = [] for system in pending: state = states.get(system) kwargs = {} if state is None else {"system_state": state} phis.append(float(system.sia(**kwargs).phi)) for system, phi in zip(pending, phis, strict=True): memo[system] = phi def _resolve_prune(prune: str | None) -> str: """Resolve the ``prune`` mode against the active system measure. ``None`` selects ``"certified"`` exactly when the resolved system measure applies the intrinsic-information requirement (under which φₛ ≤ ii by construction), and ``"off"`` otherwise. Requesting ``"certified"`` without the requirement is an error: ii ≥ φₛ does not hold under other measures, so a certified prune would be unsound. """ from pyphi.conf import ConfigurationError from pyphi.conf import config as _config from pyphi.measures.distribution import resolve_system_measure if prune not in (None, "certified", "off"): raise ValueError(f"prune must be 'certified', 'off', or None; got {prune!r}") if prune == "off": return "off" measure = resolve_system_measure(_config.formalism.iit.system_phi_measure) applies_requirement = bool( getattr(measure, "applies_intrinsic_information_requirement", False) ) if prune == "certified" and not applies_requirement: raise ConfigurationError( "prune='certified' requires a system measure that applies the " "intrinsic-information requirement " "(system_phi_measure='INTRINSIC_INFORMATION'); ii ≥ φₛ does " f"not hold under {_config.formalism.iit.system_phi_measure!r}" ) return "certified" if applies_requirement else "off" def _strictly_below(x: float, y: float) -> bool: """True when ``x < y`` beyond ``config.numerics.precision``.""" from pyphi import numerics as _numerics return x < y and not _numerics.eq(x, y) def _ii_ceiling(system): """``(ceiling, system_state)``: the certified φₛ upper bound. The ceiling is the minimum over directions of the specified state's intrinsic specification. It bounds ii(s), and through Eq. 23 also φₛ. The returned state specification is the same object ``sia`` computes before its partition sweep, so callers can pass it back to ``sia`` to avoid recomputation. A missing direction contributes 0.0 (no specified cause or effect certifies φₛ = 0). """ from pyphi.conf import config as _config from pyphi.formalism.iit4 import system_intrinsic_specification from pyphi.measures.distribution import resolve_mechanism_measure state = system_intrinsic_specification( system, specification_measure=resolve_mechanism_measure( _config.formalism.iit.specification_measure ), ) cause = 0.0 if state.cause is None else float(state.cause.intrinsic_specification) effect = 0.0 if state.effect is None else float(state.effect.intrinsic_specification) return min(cause, effect), state def _ceiling_one(system): """Worker entry: the ceiling of one system. The inner computation is sequential via the dispatcher's override (mirrors :func:`_evaluate_one`).""" return _ii_ceiling(system) def _compute_ceilings(systems, ceilings, parallel_kwargs=None) -> None: """Merge ``(ceiling, system_state)`` for ``systems`` into ``ceilings`` in dispatch order, skipping entries already present, duplicates, and ``None`` systems (mirrors :func:`_evaluate_systems`).""" from pyphi import conf as _conf from pyphi.conf import config as _config from pyphi.parallel import map_reduce pending = [] seen = set() for system in systems: if system is None or system in ceilings or system in seen: continue seen.add(system) pending.append(system) if not pending: return pkwargs = _conf.parallel_kwargs( _config.infrastructure.parallel_macro_system_evaluation, **(parallel_kwargs or {}), ) if pkwargs.get("parallel"): pkwargs["ordered"] = True pkwargs["total"] = len(pending) pkwargs.setdefault("desc", "Computing ii ceilings") # Single parent-side override; see the note in _evaluate_systems. with _config.override(parallel=False): results = map_reduce(_ceiling_one, pending, **pkwargs) else: results = [_ii_ceiling(system) for system in pending] for system, result in zip(pending, results, strict=True): ceilings[system] = result def _as_constituent(unit: MacroUnit) -> MacroUnit | int: """A pool unit as a constituent: identity micro units become bare indices, so derived units compare equal to hand-built ones.""" if ( len(unit.constituents) == 1 and not isinstance(unit.constituents[0], MacroUnit) and unit.micro_grain == 1 and unit.mapping == (0, 1) and not unit.background_apportionment ): return unit.constituents[0] return unit def _assemble_systems(pool, background_cap: int): """Nonempty unit sets with pairwise-disjoint stakes (Eq. 19). Yields tuples in depth-first inclusion order over ``pool``. """ out: list[tuple[MacroUnit, ...]] = [] def extend(start, partial, claimed, apportioned): for k in range(start, len(pool)): unit = pool[k] stake = set(unit.micro_constituents) | set(unit.background_apportionment) if claimed & stake: continue total = apportioned + len(unit.background_apportionment) if total > background_cap: continue current = (*partial, unit) out.append(current) extend(k + 1, current, claimed | stake, total) extend(0, (), set(), 0) return out def _decompositions(footprint, pool, *, allow_singleton: bool): """Sets of pool units with disjoint footprints whose union is ``footprint``, all sharing one micro grain.""" remaining_all = set(footprint) candidates = [unit for unit in pool if set(unit.micro_constituents) <= remaining_all] out: list[tuple[MacroUnit, ...]] = [] def extend(partial, remaining): if not remaining: if len(partial) == 1 and not allow_singleton: return if len({unit.micro_grain for unit in partial}) == 1: out.append(tuple(partial)) return first = min(remaining) for unit in candidates: fp = set(unit.micro_constituents) if first in fp and fp <= remaining: extend((*partial, unit), remaining - fp) extend((), remaining_all) return out def _apportionments(n, footprint, inherited, bounds: SearchBounds): """Candidate ``W^J`` sets for a footprint. Always contains the union of the constituents' apportionments (Eq. 13). Under ENUMERATE, extends it with subsets of the remaining background up to ``max_background`` total. """ inherited = tuple(sorted(inherited)) if bounds.apportionment == "NONE": return (inherited,) if len(inherited) > bounds.max_background: return () available = sorted(set(range(n)) - set(footprint) - set(inherited)) return tuple( tuple(sorted((*inherited, *extra))) for size in range(bounds.max_background - len(inherited) + 1) for extra in itertools.combinations(available, size) ) def _competitor_members(pool, footprint, W, tau): """The pool units that can belong to a system in ``f(U^J, W^J, τ_J)`` (Eq. 17): units over a strict subset of the footprint, with apportionments inside ``W^J`` and micro grain at most ``τ_J``.""" fp = set(footprint) allowed = set(W) return [ unit for unit in pool if set(unit.micro_constituents) < fp and set(unit.background_apportionment) <= allowed and unit.micro_grain <= tau ] def _f( substrate, V, W, footprint, tau, pool, micro_history, bounds, memo, system_cache, ceilings, gates, mode, ): """``f(U^J, W^J, τ_J)``: competitor entries ``(system, φₛ)`` (Eq. 17). Under the certified prune, a competitor whose intrinsic-information ceiling is strictly below the candidate's φₛ at precision carries ``None`` in place of φₛ: it cannot beat or tie the candidate, so its partition sweep is skipped. """ from pyphi import numerics as _numerics members = _competitor_members(pool, footprint, W, tau) own = canonical_units(V) phi_V = None if mode == "certified": _, phi_V = _phi(substrate, V, micro_history, memo, system_cache) entries = [] for combo in _assemble_systems(members, bounds.max_background): if canonical_units(combo) == own: continue system = _system_of_cached(substrate, combo, micro_history, system_cache) if system is None: continue if ( mode == "certified" and system not in memo and phi_V is not None and _numerics.is_positive(phi_V) ): if system not in ceilings: ceilings[system] = _ii_ceiling(system) ceiling = ceilings[system][0] if _strictly_below(ceiling, phi_V): gates[system] = ceiling entries.append((system, None)) continue _, phi = _phi(substrate, combo, micro_history, memo, system_cache) entries.append((system, phi)) return entries def _update_grains(V, bounds: SearchBounds) -> range: """The update grains a decomposition's variants take. A single-constituent decomposition is pure grain raising, so its variants start at update grain 2 (a grain-1 wrap is the constituent relabeled). """ return range(2 if len(V) == 1 else 1, bounds.max_update_grain + 1) def _variants(V, W, bounds: SearchBounds, update_grain: int) -> list[MacroUnit]: """The mapped unit variants of a valid decomposition at one update grain.""" constituents = tuple(_as_constituent(u) for u in canonical_units(V)) return [ MacroUnit(constituents, update_grain, mapping, W) for mapping in candidate_mappings(len(V), update_grain, bounds) ] def _max_tau(V, bounds: SearchBounds) -> int: """The largest micro grain τ_J among a decomposition's variants.""" return bounds.max_update_grain * V[0].micro_grain def _judge( substrate, V, W, footprint, tau, micro_history, bounds, pool, memo, system_cache, ceilings, gates, mode, ): _, phi = _phi(substrate, V, micro_history, memo, system_cache) entries = _f( substrate, V, W, footprint, tau, pool, micro_history, bounds, memo, system_cache, ceilings, gates, mode, ) competitors = [(s, p) for s, p in entries if p is not None] num_gated = sum(1 for _, p in entries if p is None) return judge_candidate(0.0 if phi is None else phi, competitors, num_gated=num_gated) def _trivial_verdict(phi) -> UnitVerdict: return UnitVerdict( valid=True, reason=Reason.VALID, phi=0.0 if phi is None else float(phi), witness=None, witness_phi=None, num_competitors=0, ) def _is_micro(unit: MacroUnit) -> bool: """Micro for gating purposes: one micro constituent at grain 1. Eqs. 16-17 gate macroing only; micro units are axiomatically valid. """ return len(unit.micro_constituents) == 1 and unit.micro_grain == 1 def _unit_history_requirement(unit: MacroUnit, bounds: SearchBounds) -> int: return max(bounds.max_micro_grain, unit.constituent_micro_grain)
[docs] @dataclass(frozen=True) class DecompositionVerdict: """A judged candidate decomposition ``(V^J, W^J)`` at update grain τ_J. Attributes ---------- constituents : tuple[MacroUnit | int, ...] The direct constituents ``V^J``. background_apportionment : tuple[int, ...] The background apportionment ``W^J``. micro_grain : int τ_J, the candidate's update grain in micro updates. Competitors are built only from units whose micro grain is at most τ_J. verdict : UnitVerdict The outcome of Eqs. 16-17. """ constituents: tuple[MacroUnit | int, ...] background_apportionment: tuple[int, ...] micro_grain: int verdict: UnitVerdict
def _class_combos(candidates, pool_at_class_start, bounds): """Unit-combos a size class needs, in sequential-first-need order. For each candidate ``(footprint, V, W)``: the constituent units ``V``, then each competitor combo at the candidate's largest update grain in ``_assemble_systems`` order. The competitor sets of smaller grains are subsets of that one. This mirrors the order in which the judge phase requests systems lazily, so batch evaluation warms the memo identically to a sequential run. """ for footprint, V, W in candidates: yield V members = _competitor_members( pool_at_class_start, footprint, W, _max_tau(V, bounds) ) own = canonical_units(V) for combo in _assemble_systems(members, bounds.max_background): if canonical_units(combo) == own: continue yield combo def _derive_units( substrate, micro_history, bounds, memo, system_cache, *, within=None, proper=False, parallel_kwargs=None, ceilings=None, gates=None, mode="off", ): """The intrinsic-unit recursion (paper p. 9), bounded by ``bounds``. Level 0 is the micro units. Each level derives candidate decompositions from the previous level's pool, processed in footprint-size classes (smallest first). Because ``f(U^J, W^J, τ_J)`` admits only strict-subset footprints, every candidate in a size class is independent of the others, so the class's φₛ evaluations are batched (and optionally parallelized) before the judgments run sequentially over the warm memo. Under the certified prune the batching runs in stages — candidate systems first (their φₛ values are the gate incumbents), then competitor ceilings, then only the surviving competitors — warming ``memo`` and ``ceilings`` so the judge walk makes identical decisions. Returns ``(pool, verdicts)``. """ if ceilings is None: ceilings = {} if gates is None: gates = {} n = substrate.size indices = tuple(range(n)) if within is None else tuple(sorted(within)) pool: list[MacroUnit] = [micro_unit(i) for i in indices] _evaluate_systems( [_system_of_cached(substrate, (u,), micro_history, system_cache) for u in pool], memo, parallel_kwargs, ) verdicts: list[DecompositionVerdict] = [] for unit in pool: _, phi = _phi(substrate, (unit,), micro_history, memo, system_cache) verdicts.append( DecompositionVerdict( constituents=(unit.constituents[0],), background_apportionment=(), micro_grain=1, verdict=_trivial_verdict(phi), ) ) seen: set = set() min_size = 1 if bounds.max_update_grain > 1 else 2 for _level in range(bounds.max_depth): pool_prev = tuple(pool) emitted_any = False max_size = min(len(indices) - (1 if proper else 0), bounds.max_constituents) for size in range(min_size, max_size + 1): pool_at_class_start = tuple(pool) candidates: list[tuple[tuple[int, ...], tuple, tuple[int, ...]]] = [] for footprint in itertools.combinations(indices, size): for V in _decompositions( footprint, pool_prev, allow_singleton=bounds.max_update_grain > 1 ): inherited = set().union( *(set(u.background_apportionment) for u in V) ) for W in _apportionments(n, footprint, inherited, bounds): key = (canonical_units(V), W) if key in seen: continue seen.add(key) candidates.append((footprint, V, W)) if mode == "certified": from pyphi import numerics as _numerics v_systems = [ _system_of_cached(substrate, V, micro_history, system_cache) for _fp, V, _W in candidates ] _evaluate_systems(v_systems, memo, parallel_kwargs) combo_systems: list = [] combo_gate_phi: list = [] for (footprint, V, W), v_system in zip( candidates, v_systems, strict=True ): phi_V = None if v_system is None else memo.get(v_system) members = _competitor_members( pool_at_class_start, footprint, W, _max_tau(V, bounds) ) own = canonical_units(V) for combo in _assemble_systems(members, bounds.max_background): if canonical_units(combo) == own: continue system = _system_of_cached( substrate, combo, micro_history, system_cache ) if system is None or system in memo: continue combo_systems.append(system) combo_gate_phi.append(phi_V) _compute_ceilings(combo_systems, ceilings, parallel_kwargs) survivors = [] survivor_seen: set = set() for system, phi_V in zip(combo_systems, combo_gate_phi, strict=True): if system in survivor_seen or system in memo: continue if ( phi_V is not None and _numerics.is_positive(phi_V) and _strictly_below(ceilings[system][0], phi_V) ): continue survivor_seen.add(system) survivors.append(system) _evaluate_systems( survivors, memo, parallel_kwargs, system_states={s: ceilings[s][1] for s in survivors}, ) else: _evaluate_systems( [ _system_of_cached(substrate, units, micro_history, system_cache) for units in _class_combos( candidates, pool_at_class_start, bounds ) ], memo, parallel_kwargs, ) new_units: list[MacroUnit] = [] for footprint, V, W in candidates: for update_grain in _update_grains(V, bounds): tau = update_grain * V[0].micro_grain verdict = _judge( substrate, V, W, footprint, tau, micro_history, bounds, pool_at_class_start, memo, system_cache, ceilings, gates, mode, ) verdicts.append( DecompositionVerdict( constituents=tuple( _as_constituent(u) for u in canonical_units(V) ), background_apportionment=W, micro_grain=tau, verdict=verdict, ) ) if verdict.valid: new_units.extend(_variants(V, W, bounds, update_grain)) pool.extend(new_units) emitted_any = emitted_any or bool(new_units) if not emitted_any: break return tuple(pool), tuple(verdicts) def _f_for_unit( substrate, unit, V, micro_history, bounds, memo, system_cache, ceilings, gates, mode, parallel_kwargs=None, ): pool, _ = _derive_units( substrate, micro_history, bounds, memo, system_cache, within=unit.micro_constituents, proper=True, parallel_kwargs=parallel_kwargs, ceilings=ceilings, gates=gates, mode=mode, ) members = _competitor_members( pool, unit.micro_constituents, unit.background_apportionment, unit.micro_grain ) own = canonical_units(V) v_system = _system_of_cached(substrate, V, micro_history, system_cache) combos = [] for combo in _assemble_systems(members, bounds.max_background): if canonical_units(combo) == own: continue combos.append(_system_of_cached(substrate, combo, micro_history, system_cache)) if mode == "certified": from pyphi import numerics as _numerics _evaluate_systems([v_system], memo, parallel_kwargs) phi_V = None if v_system is None else memo.get(v_system) to_ceiling = [s for s in combos if s is not None and s not in memo] _compute_ceilings(to_ceiling, ceilings, parallel_kwargs) if phi_V is not None and _numerics.is_positive(phi_V): survivors = [ s for s in to_ceiling if not _strictly_below(ceilings[s][0], phi_V) ] else: survivors = to_ceiling _evaluate_systems( survivors, memo, parallel_kwargs, system_states={s: ceilings[s][1] for s in survivors}, ) else: _evaluate_systems([v_system, *combos], memo, parallel_kwargs) return _f( substrate, V, unit.background_apportionment, unit.micro_constituents, unit.micro_grain, pool, micro_history, bounds, memo, system_cache, ceilings, gates, mode, ) def _parallel_options(parallel: bool | None, progress: bool | None) -> dict: """The candidate-evaluation overrides a public search function forwards: ``parallel`` and ``progress``, where given.""" from pyphi.conf._helpers import check_parallel_flag from pyphi.conf._helpers import check_progress_flag return { name: value for name, value in ( ("parallel", check_parallel_flag(parallel)), ("progress", check_progress_flag(progress)), ) if value is not None }
[docs] def competing_systems( substrate: Substrate, unit: MacroUnit, micro_history, *, bounds: SearchBounds = _DEFAULT_BOUNDS, parallel: bool | None = None, prune: str | None = None, progress: bool | None = None, ) -> tuple[MacroSystem, ...]: """``f(U^J, W^J, τ_J)`` materialized within the unit's footprint (Eq. 17). τ_J is the unit's micro grain: every unit of a returned system has a micro grain of at most τ_J. ``prune="certified"`` skips partition sweeps whose outcome is certified by the intrinsic-information requirement; ``"off"`` evaluates everything; ``None`` (default) selects ``"certified"`` exactly when the active system measure applies the requirement. The returned systems are identical under every mode. ``parallel`` and ``progress`` govern the evaluation of candidate systems; ``None`` defers to ``config.infrastructure.parallel_macro_system_evaluation``. """ parallel_kwargs = _parallel_options(parallel, progress) _require_macro_formalism() mode = _resolve_prune(prune) history = _normalized_history( substrate, micro_history, _unit_history_requirement(unit, bounds) ) if _is_micro(unit): return () memo: dict[MacroSystem, float] = {} system_cache: dict[tuple, MacroSystem | None] = {} ceilings: dict = {} gates: dict = {} V = canonical_units(_as_unit(c) for c in unit.constituents) return tuple( system for system, _ in _f_for_unit( substrate, unit, V, history, bounds, memo, system_cache, ceilings, gates, mode, parallel_kwargs, ) )
[docs] def is_intrinsic_unit( substrate: Substrate, unit: MacroUnit, micro_history, *, bounds: SearchBounds = _DEFAULT_BOUNDS, parallel: bool | None = None, prune: str | None = None, progress: bool | None = None, ) -> UnitVerdict: """Eqs. 16-17 for one candidate; micro units return VALID trivially. The unit's own mapping is ignored (Eqs. 16-17 do not depend on it); its micro grain τ_J bounds the grains of its competitors. The recursion is run restricted to the unit's footprint to build ``f(U^J, W^J, τ_J)``. ``prune="certified"`` skips competitor partition sweeps whose outcome is certified by the intrinsic-information requirement; ``"off"`` evaluates everything; ``None`` (default) selects ``"certified"`` exactly when the active system measure applies the requirement. The verdict is identical under every mode. ``parallel`` and ``progress`` govern the evaluation of candidate systems; ``None`` defers to ``config.infrastructure.parallel_macro_system_evaluation``. """ parallel_kwargs = _parallel_options(parallel, progress) _require_macro_formalism() mode = _resolve_prune(prune) history = _normalized_history( substrate, micro_history, _unit_history_requirement(unit, bounds) ) memo: dict[MacroSystem, float] = {} system_cache: dict[tuple, MacroSystem | None] = {} ceilings: dict = {} gates: dict = {} if _is_micro(unit): _, phi = _phi(substrate, (unit,), history, memo, system_cache) return _trivial_verdict(phi) V = canonical_units(_as_unit(c) for c in unit.constituents) entries = _f_for_unit( substrate, unit, V, history, bounds, memo, system_cache, ceilings, gates, mode, parallel_kwargs, ) _, phi = _phi(substrate, V, history, memo, system_cache) competitors = [(s, p) for s, p in entries if p is not None] num_gated = sum(1 for _, p in entries if p is None) return judge_candidate(0.0 if phi is None else phi, competitors, num_gated=num_gated)
[docs] @dataclass(frozen=True) class IntrinsicUnitsResult: """The recursion's output: the valid-unit pool and every verdict. Attributes ---------- units : tuple[MacroUnit, ...] All derived intrinsic units, micro units included, in derivation order (footprints smallest-first per level). verdicts : tuple[DecompositionVerdict, ...] One :class:`DecompositionVerdict` per judged ``(V^J, W^J)`` candidate and update grain τ_J, micro units included. """ units: tuple[MacroUnit, ...] verdicts: tuple[DecompositionVerdict, ...]
[docs] def units_by_footprint(self) -> dict[tuple[int, ...], tuple[MacroUnit, ...]]: """The unit pool grouped by micro footprint.""" grouped: dict[tuple[int, ...], list[MacroUnit]] = {} for unit in self.units: grouped.setdefault(unit.micro_constituents, []).append(unit) return {k: tuple(v) for k, v in grouped.items()}
[docs] def intrinsic_units( substrate: Substrate, micro_history, *, bounds: SearchBounds, parallel: bool | None = None, prune: str | None = None, progress: bool | None = None, ) -> IntrinsicUnitsResult: """The recursion's fixed point: the valid-unit pool plus all verdicts. ``prune="certified"`` skips competitor partition sweeps whose outcome is certified by the intrinsic-information requirement; ``"off"`` evaluates everything; ``None`` (default) selects ``"certified"`` exactly when the active system measure applies the requirement. Units and verdicts are identical under every mode. ``parallel`` and ``progress`` govern the evaluation of candidate systems; ``None`` defers to ``config.infrastructure.parallel_macro_system_evaluation``. """ parallel_kwargs = _parallel_options(parallel, progress) _require_macro_formalism() mode = _resolve_prune(prune) history = _normalized_history(substrate, micro_history, bounds.max_micro_grain) memo: dict[MacroSystem, float] = {} system_cache: dict[tuple, MacroSystem | None] = {} ceilings: dict = {} gates: dict = {} units, verdicts = _derive_units( substrate, history, bounds, memo, system_cache, parallel_kwargs=parallel_kwargs, ceilings=ceilings, gates=gates, mode=mode, ) return IntrinsicUnitsResult(units=units, verdicts=verdicts)
[docs] def valid_systems( substrate: Substrate, micro_history, *, bounds: SearchBounds, parallel: bool | None = None, prune: str | None = None, progress: bool | None = None, ) -> tuple[MacroSystem, ...]: """The bounded ``P(u)``: every Eq-19-compatible system of intrinsic units, evaluated over the full universe with everything else as background. Systems whose state is unreachable are dropped. ``prune`` gates the unit derivation's competitor sweeps as in :func:`intrinsic_units`; the returned systems are identical under every mode. ``parallel`` and ``progress`` govern the evaluation of candidate systems; ``None`` defers to ``config.infrastructure.parallel_macro_system_evaluation``. """ parallel_kwargs = _parallel_options(parallel, progress) _require_macro_formalism() mode = _resolve_prune(prune) history = _normalized_history(substrate, micro_history, bounds.max_micro_grain) memo: dict[MacroSystem, float] = {} system_cache: dict[tuple, MacroSystem | None] = {} units, _ = _derive_units( substrate, history, bounds, memo, system_cache, parallel_kwargs=parallel_kwargs, mode=mode, ) systems = [] for combo in _assemble_systems(list(units), bounds.max_background): system = _system_of_cached(substrate, combo, history, system_cache) if system is not None: systems.append(system) return tuple(systems)
[docs] @dataclass(frozen=True) class EvaluationRecord: """One candidate system and what the search established about it. Attributes ---------- system : MacroSystem The candidate system. phi : float or None The exact φₛ, or ``None`` for a gated candidate — one whose partition sweep was skipped because its intrinsic-information ceiling is certifiably below an overlapping accepted complex's φₛ. ii_ceiling : float or None The certified upper bound on φₛ (the minimum-direction intrinsic information), when the certified prune computed one. gated : bool Whether the candidate was gated; ``phi`` is ``None`` exactly when this is True. """ system: MacroSystem phi: float | None ii_ceiling: float | None = None gated: bool = False
[docs] @dataclass(frozen=True, repr=False) class ComplexesResult(Displayable, ToPandasMixin): """The complexes of the bounded candidate space (Eq. 20, applied recursively). Attributes ---------- complexes : tuple[Complex, ...] The complexes identified by the recursive exclusion cascade over the candidates in ``P(u)`` with φₛ > 0, in descending-φₛ order, each carrying its macro unit structure and exclusion records. Mutually disjoint in micro footprint by construction; empty when every candidate is reducible. records : tuple[EvaluationRecord, ...] One entry per candidate the run considered (criteria checks included): evaluated systems first, in evaluation order, with exact φₛ (and their intrinsic-information ceiling when the certified prune computed one), followed by gated candidates carrying ``phi=None`` and their ceiling. A candidate is gated only when its φₛ is certifiably below an overlapping accepted complex's at precision. ties : tuple[tuple[MacroSystem, ...], ...] Cliques of overlapping candidate systems that tied at φₛ and still tied at Φ under Composition escalation, failing the exclusion postulate; none of their members is a complex. """ complexes: tuple[Any, ...] records: tuple[EvaluationRecord, ...] ties: tuple[tuple[MacroSystem, ...], ...] @property def maximal_complex(self): """The φₛ-maximal complex, or a falsy null Complex when none exists.""" if self.complexes: return self.complexes[0] from pyphi.formalism.iit4 import NullSystemIrreducibilityAnalysis from pyphi.models.complex import Complex substrate = self.records[0].system.micro_substrate if self.records else None return Complex( sia=NullSystemIrreducibilityAnalysis(), substrate=substrate, is_maximal=True, excluded=(), units=(), node_indices=(), ) def _to_pandas(self): """One row per complex: its micro footprint, each unit's micro constituents and micro grain, and the complex's own record.""" rows = [] for complex_ in self.complexes: units, grains = _complex_units(complex_) rows.append( { "node_indices": complex_.node_indices, "units": units, "grains": grains, **complex_._pandas_record(), } ) # With no complex, the null complex's record supplies the columns. columns = ( None if rows else [ "node_indices", "units", "grains", *( column for column in self.maximal_complex._pandas_record() if column != "node_indices" ), ] ) return records_to_frame(rows, columns=columns) def _describe(self, verbosity: int) -> Description: # noqa: ARG002 from pyphi.conf.formalism import IITConfig cls = type(self).__name__ n_gated = sum(record.gated for record in self.records) rows = [ Row("Complexes", len(self.complexes)), Row("Candidate systems", len(self.records)), ] if n_gated: rows.append(Row("Gated", n_gated)) rows.append(Row("Tied cliques", len(self.ties))) # As on an Analysis card, the version of IIT is shown only when it is # not the default. It is read from the complexes' analyses, so a # result with no complex has none to show. if self.complexes: formalism = self.complexes[0].sia.config.formalism.iit.version if formalism != IITConfig.version: rows.append(Row("Formalism", formalism)) sections = [Section(rows=tuple(rows))] if self.complexes: sections.append( Section( label="Complexes", body=( capped_table( ("φ_s", "Nodes", "Units", "Grains"), self.complexes, _complex_row, total=len(self.complexes), ), ), ) ) return Description( title=cls, sections=tuple(sections), compact=( f"{cls}({len(self.complexes)} complexes," f" {len(self.records)} candidate systems)" ), )
def _complex_units(complex_) -> tuple[tuple[tuple[int, ...], ...], tuple[int, ...]]: """Each unit's micro constituents and each unit's micro grain.""" units = complex_.units or () return ( tuple(unit.micro_constituents for unit in units), tuple(unit.micro_grain for unit in units), ) def _complex_row(complex_) -> tuple[str, str, str, str]: """One table row of a :class:`ComplexesResult` card: φₛ, the micro footprint, each unit's micro constituents, and each unit's micro grain.""" units, grains = _complex_units(complex_) return ( format_value(complex_.phi), str(complex_.node_indices), " ".join("{" + ",".join(map(str, unit)) + "}" for unit in units), " ".join(map(str, grains)), )
[docs] def complexes( substrate: Substrate, micro_history, *, bounds: SearchBounds = _DEFAULT_BOUNDS, parallel: bool | None = None, prune: str | None = None, progress: bool | None = None, ) -> ComplexesResult: """Identify the complexes of the bounded candidate space -- the one-call driver. Every admissible system of intrinsic units (Eq. 19) is evaluated over the full universe, then condensed by the recursive exclusion cascade: candidates with φₛ = 0 are reducible and dropped, and Eq. 20's comparison is applied to the rest tier by tier, so a candidate excluded by an accepted complex has no standing to exclude other candidates. φₛ ties between overlapping candidates escalate to Composition (Φ); cliques that still tie fail exclusion and are reported in ``ties``. ``prune="certified"`` skips partition sweeps whose outcome is certified by the intrinsic-information requirement; ``"off"`` evaluates everything; ``None`` (default) selects ``"certified"`` exactly when the active system measure applies the requirement. ``parallel`` and ``progress`` govern the evaluation of candidate systems; ``None`` defers to ``config.infrastructure.parallel_macro_system_evaluation``. Notes ----- Under the certified prune the identified complexes, φₛ values, ties, verdicts and exclusion margins are identical to a full evaluation: a gated candidate whose ceiling could exceed a complex's best rival is evaluated to settle the margin. The candidates the prune gated appear in ``records`` with ``gated=True``, and those with a positive ceiling that overlap a complex also appear in its ``excluded`` list, with ``phi=None``. A gated candidate's φₛ is bounded by its intrinsic-information ceiling but never computed, so it may be reducible (φₛ = 0); a full evaluation lists only rivals with φₛ > 0. """ parallel_kwargs = _parallel_options(parallel, progress) _require_macro_formalism() from pyphi.condensation import Candidate from pyphi.condensation import exclusion_cascade from pyphi.condensation import exclusion_records from pyphi.models.complex import Complex mode = _resolve_prune(prune) history = _normalized_history(substrate, micro_history, bounds.max_micro_grain) memo: dict[MacroSystem, float] = {} system_cache: dict[tuple, MacroSystem | None] = {} ceilings: dict = {} gates: dict = {} units, _ = _derive_units( substrate, history, bounds, memo, system_cache, parallel_kwargs=parallel_kwargs, ceilings=ceilings, gates=gates, mode=mode, ) sweep_systems = [ _system_of_cached(substrate, combo, history, system_cache) for combo in _assemble_systems(list(units), bounds.max_background) ] if mode == "certified": from pyphi.condensation import PendingCandidate from pyphi.condensation import gated_exclusion_cascade _compute_ceilings(sweep_systems, ceilings, parallel_kwargs) pending = [ PendingCandidate( footprint=frozenset(_system_micro_indices(system.units)), ceiling=ceilings[system][0], payload=system, ) for system in sweep_systems if system is not None ] candidates: list[Candidate] = [] by_candidate: dict = {} def _evaluate_band(band): _evaluate_systems( [p.payload for p in band], memo, parallel_kwargs, system_states={p.payload: ceilings[p.payload][1] for p in band}, ) batch = [] for p in band: candidate = Candidate( footprint=p.footprint, phi=memo[p.payload], sia_provider=lambda system=p.payload: system.sia(), system_provider=lambda system=p.payload: system, units=p.payload.units, ) candidates.append(candidate) by_candidate[candidate] = p.payload batch.append(candidate) return batch outcome, gated = gated_exclusion_cascade(pending, _evaluate_band) # A candidate the cascade gated may already have been evaluated while # deriving the units; its exact φₛ makes it an ordinary rival. sweep_gated = [] for p in gated: if p.payload in memo: candidate = Candidate( footprint=p.footprint, phi=memo[p.payload], sia_provider=lambda system=p.payload: system.sia(), system_provider=lambda system=p.payload: system, units=p.payload.units, ) candidates.append(candidate) by_candidate[candidate] = p.payload else: sweep_gated.append(p) gates.setdefault(p.payload, p.ceiling) # A complex's exclusion margin is set by its best overlapping rival # at or below its φₛ. Evaluate the gated rivals that could be that # rival, highest ceiling first, until no remaining ceiling exceeds the # best rival found; the rest cannot change the margin. from pyphi import numerics as _numerics for accepted_candidate in outcome.accepted: phi = accepted_candidate.phi def _best_rival(accepted_candidate=accepted_candidate, phi=phi): # numerics: exact — the reported margin's rival, not a selection. return max( ( c.phi for c in candidates if c is not accepted_candidate and c.footprint & accepted_candidate.footprint # numerics: exact — composed with eq into a tolerant ≤ and (c.phi < phi or _numerics.eq(c.phi, phi)) ), default=0.0, ) overlapping = sorted( ( p for p in sweep_gated if p.footprint & accepted_candidate.footprint and _numerics.is_positive(p.ceiling) ), key=lambda p: -p.ceiling, ) for p in overlapping: best = _best_rival() # numerics: exact — composed with eq into a tolerant ≤ if p.ceiling < best or _numerics.eq(p.ceiling, best): break _evaluate_band([p]) sweep_gated.remove(p) # List rivals in the sweep's order, as a full evaluation does. position = {system: i for i, system in enumerate(sweep_systems)} candidates.sort(key=lambda c: position[by_candidate[c]]) else: _evaluate_systems(sweep_systems, memo, parallel_kwargs) evaluated: list[tuple[MacroSystem, float]] = [ (system, memo[system]) for system in sweep_systems if system is not None ] candidates = [ Candidate( footprint=frozenset(_system_micro_indices(system.units)), phi=phi, sia_provider=lambda system=system: system.sia(), system_provider=lambda system=system: system, units=system.units, ) for system, phi in evaluated ] by_candidate = dict(zip(candidates, (s for s, _ in evaluated), strict=True)) outcome = exclusion_cascade(candidates) sweep_gated = [] records_map = exclusion_records(outcome.accepted, candidates) if sweep_gated: from pyphi import numerics as _numerics from pyphi.models.complex import ExcludedCandidate # A ceiling of 0 certifies φₛ = 0: the candidate is reducible and is # not a rival of any complex. for accepted_candidate in outcome.accepted: key = tuple(sorted(accepted_candidate.footprint)) extra = tuple( ExcludedCandidate( tuple(sorted(p.footprint)), None, units=p.payload.units, ii_ceiling=p.ceiling, gated=True, ) for p in sweep_gated if accepted_candidate.footprint & p.footprint and _numerics.is_positive(p.ceiling) ) records_map[key] = records_map[key] + extra winners = tuple( Complex( sia=cand.sia_provider(), substrate=substrate, is_maximal=(i == 0), excluded=records_map[tuple(sorted(cand.footprint))], units=cand.units, node_indices=tuple(sorted(cand.footprint)), ) for i, cand in enumerate(outcome.accepted) ) ties = tuple( tuple(by_candidate[c] for c in clique) for clique in outcome.failed_cliques ) records = tuple( EvaluationRecord( system=system, phi=phi, ii_ceiling=(ceilings[system][0] if system in ceilings else None), ) for system, phi in memo.items() ) + tuple( EvaluationRecord(system=system, phi=None, ii_ceiling=ceiling, gated=True) for system, ceiling in gates.items() if system not in memo ) validate.non_overlapping(winners) return ComplexesResult(complexes=winners, records=records, ties=ties)