"""PF-002 recoil identifiability study, version 1.

Virtual lab - simulated experiment. No physical measurement. Section numbers
refer to PF002_IDENTIFIABILITY_V1.md. The generator is the only code that sees
truth labels. Estimators, decisions and the exit guard read readings, the
detector's reads, labels, sample indices and declared design constants.

Primary execution stays refused until the twin authorises a mode.
"""

import json
import math
from pathlib import Path
import random
import sys
import unicodedata

import pf002_identifiability_bounds_v1 as bounds
import pf002_identifiability_inputs_v1 as inputs
import pf002_identifiability_oracle_v1 as oracle
import pf002_reference_gain_v1 as rg

ROOT = Path(__file__).resolve().parent
PROTOCOL_FILE = "pf002-identifiability-v1-protocol.json"
ENVIRONMENT = "Virtual lab - simulated experiment"
STRUCTURE_DIGEST = ("sha256:8d01ee904e799382e6c0178bcce71e67"
                    "e3c8ae142e06aa2bf60f554761f6f2cb")
MAX_INPUT_BYTES = 1048576
MAX_RECORD_DEPTH = 16
CELLS = 64
MODES = ("exploratory", "confirmatory")
HARD_SEED = 1000000
FROZEN_SCENARIOS = ("S01-constant", "S03-rate-retained", "S05-label-retained",
                    "S09-common-force", "S11-label-within-window")


class OperationalFailure(Exception):
    """A required reading, guard or denominator does not exist."""


def _number(value, low, high, name):
    return rg._number(value, low, high, name)


def _fixed(value, expected, name):
    """Exact value and exact type. True never passes for 1."""
    if type(value) is not type(expected) or value != expected:
        raise ValueError(f"{name} differs from its frozen value")


def _cohort_bounds(value, cap, name):
    """Pair of integers with a fixed count, before any range is built."""
    if not isinstance(value, list) or len(value) != 2:
        raise ValueError(f"{name} is not a pair")
    rg._integer(value[0], 1, HARD_SEED, name)
    rg._integer(value[1], value[0], HARD_SEED, name)
    if not 1 <= value[1]-value[0]+1 <= cap:
        raise ValueError(f"{name} count outside its fixed limit")
    return value[0], value[1]


def _check_cohorts(p):
    seeds = p["seeds"]
    _fixed(seeds["absolute_confirmatory_cap"], 32, "confirmatory cap")
    spans = [_cohort_bounds(seeds["fixture_and_witness"], 16, "fixture seeds"),
             _cohort_bounds(seeds["exploratory"], 8, "exploratory seeds"),
             _cohort_bounds(seeds["confirmatory"], 32, "confirmatory seeds")]
    for i, (low, high) in enumerate(spans):
        for other_low, other_high in spans[i+1:]:
            if low <= other_high and other_low <= high:
                raise ValueError("seed cohorts overlap")


def _check_timing(p):
    timing = p["timing"]
    _fixed(timing["samples_total"], 1000, "samples_total")
    _fixed(timing["sample_step_seconds"], 0.1, "sample step")
    _fixed(timing["late_window_samples"], [91, 100], "late window")
    _fixed(timing["early_window_samples"], [41, 50], "early window")


def _check_limits(p):
    limits = p["limits"]
    for name, low, high in (("maximum_runtime_seconds_including_cleanup", 1, 900),
                            ("maximum_fixture_seconds", 1, 1200),
                            ("maximum_retained_bytes", 1, 2097152),
                            ("maximum_parser_nodes", 1, 200000),
                            ("maximum_json_depth", 1, 16),
                            ("maximum_stdout_bytes", 1, 65536),
                            ("maximum_stderr_bytes", 1, 65536)):
        rg._integer(limits[name], low, high, name)
    _fixed(limits["maximum_study_processes"], 1, "study processes")
    _fixed(limits["maximum_fixture_workers"], 1, "fixture workers")
    _fixed(limits["network_calls"], 0, "network calls")
    _fixed(limits["new_dependencies"], 0, "new dependencies")
    lean = p["lean_record"]
    rg._integer(lean["maximum_bytes_per_configuration"], 1, 16384, "configuration bytes")
    rg._integer(lean["maximum_nodes_per_configuration"], 1, 1800, "configuration nodes")


def _check_rows(p):
    _fixed(p["scenarios"], list(FROZEN_SCENARIOS), "scenarios")
    _fixed(p["configuration_count"], 26, "configuration count")
    _fixed(p["configuration_cap"], 48, "configuration cap")
    _fixed(p["witnesses_per_configuration"], 6, "witnesses")
    rows = p["extra_rows"]
    if not isinstance(rows, list) or len(rows) != 6:
        raise ValueError("extra rows differ from the frozen list")
    names = []
    for row in rows:
        if not isinstance(row, dict):
            raise ValueError("extra row is not an object")
        if row["architecture"] not in ("X1", "T1", "M1"):
            raise ValueError("extra row architecture")
        if row["scenario"] not in FROZEN_SCENARIOS:
            raise ValueError("extra row scenario")
        names.append(row["name"])
        if "chi" in row:
            _number(row["chi"], 0, 1, "chi")
        if "R_x" in row:
            _number(row["R_x"], 0.5, 1, "R_x")
        if "eps_cap" in row:
            _number(row["eps_cap"], 0, 0.1, "eps_cap")
        if "delta_metres" in row:
            _number(row["delta_metres"], 1e-3, 10, "delta")
    _fixed(sorted(names), ["T1-over", "T1-over", "X1-N", "X1-R", "X1-cap", "X1-cap"],
           "extra row names")


def check_values(p):
    """Every value this code reads from the twin, before any allocation."""
    if p["study"] != "pf002-identifiability-v1":
        raise ValueError("wrong study")
    if p["environment"] != ENVIRONMENT:
        raise ValueError("wrong environment")
    if type(p["execution_authorised"]) is not bool:
        raise ValueError("execution_authorised is not a boolean")
    if not isinstance(p["authorised_modes"], list) or len(p["authorised_modes"]) > 2:
        raise ValueError("authorised_modes is not a short list")
    if any(m not in MODES for m in p["authorised_modes"]):
        raise ValueError("unknown authorised mode")
    if not p["execution_authorised"] and p["authorised_modes"]:
        raise ValueError("a mode is named while execution is not authorised")
    rg._integer(p["protocol_revision"], 1, 1000, "protocol_revision")
    _fixed(p["required_margin_newtons"], 1e-12, "required margin")
    _fixed(p["structural_allowance_per_phase_newtons"], 2e-12, "allowance")
    terms = p["added_terms"]
    for name, low, high in (
            ("R_x_minimum", 0.5, 1.0), ("p_b", 0, 0.1), ("phi_s", 0, 0.1),
            ("th_x_radians", 0, 0.1), ("dl_b_metres", 0, 0.1),
            ("c_b_per_metre", 0, 100), ("zeta_b", 0, 1), ("nu_b_newtons", 0, 1e-11),
            ("g_xb", 0, 0.1), ("J_b_newton_seconds", 0, 1e-10), ("q_cap_newtons", 0, 1e-11),
            ("r_c", 0, 0.1), ("th_c_radians", 0, 0.1), ("u_l_metres", 0, 0.1),
            ("dx_metres", 0, 0.1)):
        _number(terms[name]["value"], low, high, name)
    rg._integer(terms["n_sw_bins"]["value"], 1, 90, "n_sw_bins")
    if p["architectures"]["X1"]["exit_pattern_dwells_1_to_8"] != list(bounds.EXIT):
        raise ValueError("exit pattern differs from the frozen pattern")
    _fixed(p["architectures"]["T1"]["span_metres"], 0.2, "span")
    _fixed(p["architectures"]["T1"]["primary_delta_metres"], 0.1, "delta")
    _fixed(p["architectures"]["M1"]["lam"], 1, "lam")
    knowledge = p["bounds"]["response_knowledge"]
    _number(knowledge["x_tau"], 1e-6, 0.2, "x_tau")
    _number(knowledge["maximum_relative_gap"], 1e-6, 1, "gap limit")
    _number(knowledge["dimensionless_floor"], 1e-12, 1, "gap floor")
    _number(p["paired_audit"]["reading_tolerance_newtons"], 0, 1e-15, "pair tolerance")
    _number(p["hypothesis_thresholds"]["closed_form_tolerance_fraction_H9"], 0, 1,
            "H9 tolerance")
    _number(p["lag_decision"]["guard_minimum_late_fraction"], 0.01, 1, "lag guard")
    _fixed(p["detection_controls"]["required_when_injected_at_least_threshold_times"], 2,
           "detection factor")
    _check_timing(p)
    _check_cohorts(p)
    _check_rows(p)
    _check_limits(p)


def parse_protocol(data):
    """Strict bytes to twin. Any ambiguity is a refusal."""
    if not isinstance(data, bytes) or len(data) > MAX_INPUT_BYTES:
        raise ValueError("protocol input refused")
    rg._prescan(data)
    protocol = json.loads(
        data.decode("utf-8"), object_pairs_hook=rg._unique,
        parse_constant=rg._reject_constant, parse_float=rg._finite_float,
        parse_int=rg._bounded_integer)
    if not isinstance(protocol, dict):
        raise ValueError("protocol is not an object")
    for value in rg._walk(protocol):
        if isinstance(value, str) and not unicodedata.is_normalized("NFC", value):
            raise ValueError("protocol string is not NFC")
    if rg._depth(protocol) > MAX_RECORD_DEPTH:
        raise ValueError("protocol nesting too deep")
    if rg.structure_digest(protocol) != STRUCTURE_DIGEST:
        raise ValueError("protocol structure differs from the reviewed twin")
    try:
        check_values(protocol)
    except KeyError as error:
        raise ValueError(f"protocol key missing: {error}") from error
    except TypeError as error:
        raise ValueError(f"protocol value has the wrong type: {error}") from error
    return protocol


def load_protocol(path=ROOT/PROTOCOL_FILE):
    return parse_protocol(Path(path).read_bytes())


PROTOCOL = load_protocol()
prior = rg.prior
BASE = rg.BASE
PRIMARY, REFERENCE = rg.PRIMARY, rg.REFERENCE
STEP = PROTOCOL["timing"]["sample_step_seconds"]
BINS = PROTOCOL["timing"]["samples_total"]
LATE = tuple(PROTOCOL["timing"]["late_window_samples"])
EARLY = tuple(PROTOCOL["timing"]["early_window_samples"])
WINDOWS = {"late": LATE, "early": EARLY}
M = PROTOCOL["structural_allowance_per_phase_newtons"]
REQUIRED = PROTOCOL["required_margin_newtons"]
TERMS = {name: (spec["value"] if isinstance(spec, dict) and "value" in spec else None)
         for name, spec in PROTOCOL["added_terms"].items()}
KNOW = PROTOCOL["bounds"]["response_knowledge"]
X_TAU = KNOW["x_tau"]
T1_SPEC = PROTOCOL["architectures"]["T1"]
SPAN = T1_SPEC["span_metres"]
DELTA = T1_SPEC["primary_delta_metres"]
LAM = PROTOCOL["architectures"]["M1"]["lam"]
EXIT = tuple(PROTOCOL["architectures"]["X1"]["exit_pattern_dwells_1_to_8"])
EXTRA = PROTOCOL["extra_rows"]
SCENARIOS = tuple(PROTOCOL["scenarios"])
ARCHS = ("B1", "X1", "M1", "T1")
CHANNELS = {"B1": ("p", "r"), "X1": ("p", "r"), "M1": ("p", "r", "q", "u"),
            "T1": ("p1", "r1", "p2", "r2")}
LAGS = {"impostor-source-fixed-lag-10s": 10.0, "impostor-source-fixed-lag-0p1s": 0.1}
C_LIGHT = 299792458.0
READING_TOLERANCE = PROTOCOL["paired_audit"]["reading_tolerance_newtons"]
LEVERS_OVER = 2.0  # delta = D in T1-over


def configurations():
    """26 declared keys, in a fixed order."""
    keys = [(arch, scenario, "primary") for arch in ARCHS for scenario in SCENARIOS]
    keys += [(row["architecture"], row["scenario"], row["name"]) for row in EXTRA]
    return keys


def balance(channel):
    return REFERENCE if channel[0] in "ru" else PRIMARY


def source_power():
    """Escaping power at the frozen source, quarter cycle, nominal feed."""
    return rg.prior._unit(prior.QUARTER)[0]*prior.SOURCE["optical_feed_watts"]


def order_for(bit):
    return tuple(rg.order_for(bit))


def dwell_weights(arch, sigma):
    """Sign of each dwell in the route's statistic. Design only."""
    if arch == "X1":
        return tuple(s*e for s, e in zip(sigma, EXIT))
    return tuple(sigma)


def exit_factors(row, g_plus, g_minus):
    """gam_i of section 5, per dwell."""
    if row == "X1-cap":
        return [g_plus if e > 0 else TERMS["eps_cap"]*(e < 0) for e in EXIT]
    return [g_plus if e > 0 else -g_minus for e in EXIT]


TERMS["eps_cap"] = next(r["eps_cap"] for r in EXTRA if r["name"] == "X1-cap")
TERMS["chi"] = next(r["chi"] for r in EXTRA if r["name"] == "X1-N")


def delta_for(row):
    return SPAN if row == "T1-over" else DELTA


def lever_for(row):
    """Design lever of the in-class impostor, from zhat_a = 0, section 5."""
    return delta_for(row)


def shares(z):
    """Load shares of a force at lever z on supports at -D/2, +D/2."""
    return 0.5-z/SPAN, 0.5+z/SPAN


def _stream(*parts):
    return random.Random(rg.stream("pf002-identifiability-v1", *parts))


def _r_x(row):
    return next((r["R_x"] for r in EXTRA if r["name"] == row and "R_x" in r),
                TERMS["R_x_minimum"])


def draw(config, seed, control, orientation, cohort, **override):
    """Every generator draw. Paired across controls, so a matched world shares it."""
    arch, scenario, row = config
    settings = prior.scenario_settings(scenario)

    def rng(purpose):
        return _stream(cohort, arch, scenario, row, seed, orientation, purpose)

    sigma = order_for(rng("order").choice((-1, 1)))
    box = rng("constants")
    dg, dw, dl = (BASE["calibration_knowledge"], BASE["weight_knowledge"],
                  BASE["leakage_knowledge"])
    gains = {}
    for name in CHANNELS[arch]:
        gains[name] = balance(name).calibration_fraction+box.uniform(-dg, dg)
    r_low = _r_x(row)
    r_actual = box.uniform(r_low, 1.0)
    g_plus = r_actual**3
    g_minus = max(r_low**3, min(1.0, g_plus*(1+box.uniform(-1, 1)*TERMS["p_b"])))
    draws = {
        "config": config, "settings": settings, "order": sigma, "seed": seed,
        "control": control, "orientation": orientation, "cohort": cohort,
        "gains": gains, "w": prior.WEIGHT+box.uniform(-dw, dw),
        "w_c": prior.WEIGHT+box.uniform(-dw, dw),
        "leak": max(0.0, prior.LEAK+box.uniform(-dl, dl)),
        "leak_c": max(0.0, prior.LEAK+box.uniform(-dl, dl)),
        "a_c": box.uniform(1-TERMS["r_c"], 1.0),
        "vibration": box.uniform(*prior.BAND),
        "g_plus": g_plus, "g_minus": g_minus,
        "z_a": box.uniform(-TERMS["u_l_metres"], TERMS["u_l_metres"]),
        "z_c": box.choice((-SPAN/2, SPAN/2)),
    }
    nuisance = rng("nuisance")
    offset = (prior.adversarial_offset(rg.A1) if "label_within_window"
              in settings["classes"] else nuisance.randrange(10))
    draws["offset"] = offset
    weights = dwell_weights(arch, sigma)
    wander = {}
    for name in CHANNELS[arch]:
        s = settings["s_r"] if name[0] in "ru" else settings["s_p"]
        if row == "X1-N":
            label = rg.wander_path(settings, s, sigma, seed, nuisance, offset)
            part = rg.wander_path(settings, TERMS["chi"]*s, weights, seed, nuisance,
                                  offset)
            wander[name] = [x*(1-TERMS["chi"])+y for x, y in zip(label, part)]
        else:
            # Full class: odd seeds lock wander to the statistic's own weights.
            lock = weights if seed % 2 else sigma
            wander[name] = rg.wander_path(settings, s, lock, seed, nuisance, offset)
    draws["wander"] = wander
    draws["blind"] = rg._label(sigma, settings["blind"], seed, nuisance)
    draws["common"] = rg._label(sigma, settings["common"], seed, nuisance)
    added = rng("added")
    size = added_force_half(row)
    draws["added"] = [
        (w*added.choice((-1, 1)) if seed % 2 else added.uniform(-1, 1))*size
        for w in weights] if arch == "X1" else [0.0]*8
    draws["exit_gain"] = {name: added.uniform(-TERMS["g_xb"], TERMS["g_xb"])
                          for name in CHANNELS[arch]}
    draws["impulse"] = [added.choice((-1, 1))*TERMS["J_b_newton_seconds"]/STEP
                        for _ in bounds.SWAP_SEGMENTS]
    draws["dead"] = [[added.uniform(-1, 1) for _ in range(TERMS["n_sw_bins"])]
                     for _ in bounds.SWAP_SEGMENTS]
    draws["catcher_added"] = [
        s*added.uniform(-1, 1)*(catcher_force_half()) for s in sigma]
    optical = rng("optical")
    mapping = optical.choice((-1, 1))
    positive = prior.QUARTER if prior.recoil(prior.QUARTER, 1) > 0 else -prior.QUARTER
    jitter, variation = BASE["phase_jitter_radians"], BASE["feed_variation_fraction"]
    phases, feeds = [], []
    for s in sigma:
        base = 0.0 if control == "phase-null" else s*mapping*positive
        phases.append(optical.choice(prior.lattice(base, jitter, prior.PHASE_POINTS)))
        feeds.append(optical.choice(prior.lattice(1.0, variation, prior.FEED_POINTS)))
    draws.update(phases=phases, feeds=feeds, mapping=mapping)
    draws["psi"], draws["xi"] = rg._walk_paths(rng("phase_feed"), offset)
    reads = rng("detector")
    half = detector_half()/2
    draws["detector_error"] = [reads.uniform(-half, half) for _ in sigma]
    draws["noise_seed"] = rng("noise").randrange(2**32)
    draws.update(override)
    return draws


def detector_half():
    """Frozen raw contrast half-width. A read's error, no averaging credit."""
    data = rg.optical()
    return (data["optical_maximum_newtons"]-data["optical_minimum_newtons"])/2


def added_force_half(row):
    """Per-phase exit-locked force, section 8.5: half of each contrast form."""
    power = source_power()
    feed = BASE["feed_variation_fraction"]
    stray = 2*TERMS["phi_s"]*power/C_LIGHT
    axial = TERMS["th_x_radians"]*2*feed*power/C_LIGHT
    moment = TERMS["c_b_per_metre"]*TERMS["dl_b_metres"]*2*feed*power/C_LIGHT
    capture = TERMS["q_cap_newtons"] if row == "X1-cap" else 0.0
    return (stray+axial+moment+TERMS["nu_b_newtons"]+capture)/2


def catcher_force_half():
    power = source_power()
    feed = BASE["feed_variation_fraction"]
    return (2*TERMS["r_c"]*power/C_LIGHT
            + TERMS["th_c_radians"]*2*feed*power/C_LIGHT)/2


def _nominal_force():
    return prior.nominal_contrast()/2


def impostor_size(config):
    """Per-phase impostor of a world, in the source frame."""
    arch = config[0]
    if arch == "M1":
        return force_domain()["A_min"]/2
    return _nominal_force()


def force_domain():
    """Raw limits of section 4.5, from the declared box and window only."""
    lower, upper = window_limits()
    low = transfer_limits()[0]
    return {"A_min": lower/low, "A_max": upper/low}


def source_terms(draws):
    """Per-bin source-frame and laboratory inputs. Generator side, section 4.3."""
    control, config = draws["control"], draws["config"]
    arch, _, row = config
    sigma, locks = draws["order"], [prior.phase_lock(p) for p in draws["phases"]]
    size = draws.get("impostor_half", impostor_size(config))
    gam = exit_factors(row, draws["g_plus"], draws["g_minus"]) if arch == "X1" else [1.0]*8
    if control == "exit-stuck":
        gam = [draws["g_plus"]]*8
    elif control == "exit-part-way":
        gam = [g*0.5 if e < 0 else g for g, e in zip(gam, EXIT)]
    lag = LAGS.get(control)
    lag_scale = rg._lag_scale(locks, lag) if lag else 1.0
    lag_weight = -math.expm1(-STEP/lag) if lag else 0.0
    lag_state = 0.0
    out = {"recoil": [], "gam": [], "beta": 1.0, "light": 1.0, "iota": [], "lab": [],
           "mimic": [],
           "common": [], "coupling": [], "heat": [], "nu": [], "catcher": [],
           "catcher_lab": []}
    zero_recoil = {"force-decoupled", "impostor-lab-fixed-in-window",
                   "impostor-source-fixed-instant", "impostor-source-fixed-lag-10s",
                   "impostor-source-fixed-lag-0p1s", "reference-path-label-mimic",
                   "impostor-out-of-window", "mixed-impostor-in-class",
                   "reference-mimic-on-sigma-e", "near-aperture-1mm",
                   "near-exit-following-0p5", "near-exit-following-0p9",
                   "witness-impostor", "witness-null"}
    additive = arch == "M1"
    if control in zero_recoil and not (additive and control in (
            "impostor-source-fixed-instant", "witness-impostor")):
        out["beta"] = 0.0
    if control in ("exit-following-impostor", "aperture-local-impostor",
                   "substitutive-world"):
        out["beta"] = 0.0
    if control == "near-substitution-0p5":
        out["beta"] = 0.5
    paired = control == "paired-forces"
    if paired:
        # Algebraic construction: no recoil and no momentum reaches either body.
        out["beta"], out["light"] = 0.0, 0.0
    orientation = draws["orientation"]
    for k in range(BINS):
        if k < 200:
            for name in ("recoil", "iota", "lab", "mimic", "heat", "nu",
                         "catcher", "catcher_lab"):
                out[name].append(0.0)
            out["gam"].append(1.0)
            out["common"].append(prior.COMMON)
            out["coupling"].append(prior.COUPLING)
            continue
        i = k//100-2
        phase, feed = draws["phases"][i]+draws["psi"][k], draws["feeds"][i]*(1+draws["xi"][k])
        force = prior.recoil(phase, feed)
        value = gam[i]
        if arch == "X1" and row != "X1-cap" and control not in ("exit-stuck",):
            for s, segment in enumerate(bounds.SWAP_SEGMENTS):
                if segment*100 <= k < segment*100+TERMS["n_sw_bins"]:
                    value = draws["dead"][s][k-segment*100]
        iota = 0.0
        lock = locks[i]
        if control in ("impostor-source-fixed-instant", "witness-impostor"):
            iota = lock*size
        elif control == "impostor-out-of-window":
            iota = lock*rg.PROTOCOL["out_of_window"]["per_dwell_amplitude_newtons"]
        elif lag:
            lag_state += lag_weight*(lock*_nominal_force()-lag_state)
            iota = lag_scale*lag_state
        elif control == "mixed-impostor-in-class":
            z = TERMS["zeta_b"]*rg.optical()["signal_maximum_newtons"]/2
            iota = lock*(size+z*EXIT[i])
        elif control in ("near-exit-following-0p5", "near-exit-following-0p9"):
            ratio = 0.5 if control.endswith("0p5") else 0.9
            iota = lock*size*((1-ratio)+ratio*EXIT[i])
        elif control in ("exit-following-impostor", "aperture-local-impostor",
                         "substitutive-world"):
            iota = value*force
        elif control == "near-substitution-0p5":
            iota = 0.5*force
        elif control == "near-aperture-1mm":
            iota = lock*size
        elif paired:
            iota = force
        lab = lock*_nominal_force() if control == "impostor-lab-fixed-in-window" else 0.0
        factor = 1+draws["common"][i]
        mimic = 0.0
        if control == "reference-path-label-mimic":
            mimic = -orientation*lock*_nominal_force()/draws["w"]*factor
        elif control == "reference-mimic-on-sigma-e":
            mimic = -orientation*lock*EXIT[i]*_nominal_force()/draws["w"]*factor
        nu = draws["added"][i]
        catcher = 0.0
        catcher_lab = draws["catcher_added"][i] if arch == "M1" else 0.0
        if paired:
            catcher = -draws["a_c"]*force
        elif control == "paired-attempt-with-n-l":
            catcher_lab -= draws["a_c"]*force
        if control == "catcher-offset":
            catcher += draws["catcher_added"][i]
        out["recoil"].append(force)
        out["gam"].append(value)
        out["iota"].append(iota)
        out["lab"].append(lab)
        out["mimic"].append(mimic)
        out["common"].append(prior.COMMON*factor)
        out["coupling"].append(prior.COUPLING*(1+draws["blind"][i]))
        out["heat"].append(prior.source_heat(phase, feed))
        out["nu"].append(nu)
        out["catcher"].append(catcher)
        out["catcher_lab"].append(catcher_lab)
    return out


def channel_forces(draws, terms):
    """Laboratory x force on each channel, from the frames of 4.3 and section 5."""
    arch, _, row = draws["config"]
    o = draws["orientation"]
    control = draws["control"]
    leak, coupling = draws["leak"], terms["coupling"]
    out = {name: [] for name in CHANNELS[arch]}
    z_a = draws["z_a"]
    if control in ("aperture-local-impostor",):
        z_f = z_a
    elif control == "near-aperture-1mm":
        z_f = 1e-3
    else:
        z_f = lever_for(row)*(1 if draws["seed"] % 2 else -1)
    if control == "lever-at-design-with-offset-aperture":
        z_f = lever_for(row)
    share_a, share_f = shares(z_a), shares(z_f)
    share_c = shares(draws["z_c"])
    beta = terms["beta"]
    half = {name: [0.0]*BINS for name in out}
    for k in range(BINS):
        recoil = beta*terms["gam"][k]*terms["recoil"][k]
        iota, nu, lab = terms["iota"][k], terms["nu"][k], terms["lab"][k]
        common, m = terms["common"][k], terms["mimic"][k]
        if arch == "T1":
            for index, (p, r) in enumerate((("p1", "r1"), ("p2", "r2"))):
                source = o*(recoil*share_a[index]+iota*share_f[index])+lab*0.5
                half[p][k] = source+common*share_c[index]
                half[r][k] = (leak*source+coupling[k]*common*share_c[index]
                              + m*0.5)
        else:
            source = o*(recoil+iota+nu)+lab
            half["p"][k] = source+common
            half["r"][k] = leak*source+coupling[k]*common+m
            if arch == "M1":
                light = o*(-draws["a_c"]*terms["light"]*terms["gam"][k]*terms["recoil"][k]
                           + terms["catcher"][k])+terms["catcher_lab"][k]
                half["q"][k] = light+common
                half["u"][k] = (draws["leak_c"]*light
                                + prior.COUPLING*common)
    if arch == "X1":
        for s, segment in enumerate(bounds.SWAP_SEGMENTS):
            k = segment*100
            half["p"][k] += o*draws["impulse"][s]
            half["r"][k] += leak*o*draws["impulse"][s]
    return half


def simulate(draws, *, noise_path=None):
    """Sample-wise forward model. Only readings leave to estimators."""
    arch = draws["config"][0]
    terms = source_terms(draws)
    forces = channel_forces(draws, terms)
    rng = random.Random(draws["noise_seed"])
    y, states = {}, {}
    extra = draws.get("gain_step", 0.0)
    for name in CHANNELS[arch]:
        bal = balance(name)
        a = math.exp(-STEP/bal.response_seconds)
        weight = -math.expm1(-STEP/bal.thermal_seconds)
        x = th = 0.0
        gain = 1+draws["gains"][name]
        path = draws["wander"][name]
        reads, track = [], []
        catcher = name[0] in "qu"
        for k in range(BINS):
            time = (k+1)*STEP
            q = terms["heat"][k]
            if catcher:
                q = source_power() if q else 0.0
            th += weight*(q*bal.thermal_newtons_per_watt*(
                prior.HEAT_COUPLING if name[0] in "ru" else 1.0)-th)
            x = a*x+(1-a)*(forces[name][k]+th)
            track.append(x)
            wander = path[k]
            if arch == "X1" and k >= 200:
                wander += draws["exit_gain"][name]*EXIT[k//100-2]+extra*(k >= 400)
            noise = (noise_path(name, k) if noise_path else
                     rng.uniform(-bal.noise_bound_newtons, bal.noise_bound_newtons))
            value = (gain*(1+wander)*x+bal.offset_newtons
                     + bal.drift_newtons_per_second*time
                     + bal.vibration_newtons*math.sin(
                         2*math.pi*draws["vibration"]*time)+noise)
            if not math.isfinite(value):
                raise OperationalFailure("non-finite reading")
            if abs(value) > prior.FAILS["reading_saturation_newtons"]:
                raise OperationalFailure("reading saturated")
            reads.append(value)
        y[name], states[name] = reads, track
    return {"y": y, "states": states, "forces": forces, "terms": terms}


def _mean(values, segment, window):
    samples = bounds.window_bins(segment, window)
    return math.fsum(values[k] for k in samples)/len(samples)


def _pair_contrast(y, primary, reference, w, weights, window):
    n = len(weights)
    return 2/n*math.fsum(
        s*(_mean(y[primary], i+2, window)-w*_mean(y[reference], i+2, window))
        for i, s in enumerate(weights))


def _channel_contrast(values, weights, window):
    n = len(weights)
    return 2/n*math.fsum(s*_mean(values, i+2, window) for i, s in enumerate(weights))


def t1_weights(row):
    """c_1, c_2 of section 5, refused unless delta is positive."""
    delta = delta_for(row)
    if not delta > 0:
        raise bounds.Unproved("delta must be positive before division")
    return SPAN/2/delta, SPAN/2/delta


def moment(c_1_contrast, c_2_contrast):
    """Unscaled Z of section 5, about zhat_a = 0."""
    return SPAN/2*c_2_contrast-SPAN/2*c_1_contrast


def estimate(arch, row, sigma, y, weight, weight_c, window):
    """Statistics from readings and design constants only. No truth reaches here."""
    out = {}
    if arch in ("B1", "M1"):
        out["C"] = _pair_contrast(y, "p", "r", weight, sigma, window)
        out["C_ref"] = _channel_contrast(y["r"], sigma, window)
    if arch == "B1":
        out["Q"] = out["C"]
    elif arch == "X1":
        product = dwell_weights("X1", sigma)
        out["C_s"] = _pair_contrast(y, "p", "r", weight, sigma, window)
        out["Q"] = _pair_contrast(y, "p", "r", weight, product, window)
        out["C_ref_s"] = _channel_contrast(y["r"], sigma, window)
        out["C_ref_x"] = _channel_contrast(y["r"], product, window)
        if row == "X1-cap":
            out["Q"] *= 2
    elif arch == "M1":
        out["C_q"] = _pair_contrast(y, "q", "u", weight_c, sigma, window)
        out["Q"] = out["C"]+LAM*out["C_q"]
    elif arch == "T1":
        c_1, c_2 = t1_weights(row)
        first = _pair_contrast(y, "p1", "r1", weight, sigma, window)
        second = _pair_contrast(y, "p2", "r2", weight, sigma, window)
        out["C"] = first+second
        out["Z"] = moment(first, second)
        out["Q"] = c_2*second-c_1*first
    return out


def detector_sign_reads(draws, terms):
    """Dwell-end detector reads of the outgoing contrast, frozen read model.

    Ohat_i = gam_i*O_i + err_i, from light that left. It carries no balance
    coupling, so a stuck exit shows here whatever the balance does.
    """
    reads = []
    for i in range(len(draws["order"])):
        k = (i+3)*100-1
        reads.append(terms["gam"][k]*prior.recoil(draws["phases"][i], draws["feeds"][i])
                     + draws["detector_error"][i])
    return reads


def exit_guard(sigma, reads, half, lower, upper, *, capture=False):
    """Reads only. Sign, and magnitude within the read half-width, section 5.

    half is the contrast half-width: four reads at half of it, no averaging.
    Capture expects the second state dark, so a stuck element shows there too.
    """
    groups = {1: [], -1: []}
    for s, e, value in zip(sigma, EXIT, reads):
        groups[e].append(s*value)
    plus = math.fsum(groups[1])/2
    minus = math.fsum(groups[-1])/2
    sign = 1 if plus >= 0 else -1
    a = sign*plus
    b = -sign*minus
    first = a-half > 0 and a+half >= lower and a-half <= upper
    if capture:
        second = abs(minus) <= half
    else:
        second = b-half > 0 and b+half >= lower and b-half <= upper
    return {"pass": first and second, "sign": sign, "O_plus": plus, "O_minus": minus}


def predicted_sign(sigma, reads, signs=None):
    """Source-frame sign from the detector's reads, on the statistic's weights."""
    signs = sigma if signs is None else signs
    return 1 if math.fsum(s*v for s, v in zip(signs, reads)) >= 0 else -1


# Bound assembly, section 8.

_tables = {}


def box_tables():
    """Cell tables of 8.0, built once, gap-checked. A failure is unproved."""
    if _tables:
        return _tables
    limit, floor = KNOW["maximum_relative_gap"], KNOW["dimensionless_floor"]
    for name, bal in (("p", PRIMARY), ("r", REFERENCE)):
        forces = {}
        nominal = {}
        a = bounds.decay(bal.response_seconds, STEP)
        for label, window in WINDOWS.items():
            forces[label] = bounds.force_cells(bal.response_seconds, STEP, X_TAU,
                                               CELLS, window)
            nominal[label] = bounds.nominal_force_table(a, window)
            bounds.check_gaps(forces[label], limit, floor)
        heat = bounds.cascade_cells(bal.thermal_seconds, bal.response_seconds, STEP,
                                    X_TAU, CELLS, WINDOWS)
        heat_nominal = bounds.nominal_cascade(bal.thermal_seconds, bal.response_seconds,
                                              STEP, WINDOWS)
        lag = {}
        for tau in LAGS.values():
            cells = bounds.cascade_cells(tau, bal.response_seconds, STEP, X_TAU,
                                         CELLS, WINDOWS)
            lag[tau] = (cells, bounds.nominal_cascade(tau, bal.response_seconds, STEP,
                                                      WINDOWS))
            for label in WINDOWS:
                bounds.check_gaps(cells[label], limit, floor)
        for label in WINDOWS:
            bounds.check_gaps(heat[label], limit, floor)
        _tables[name] = {"force": forces, "nominal": nominal, "heat": heat,
                         "heat_nominal": heat_nominal, "lag": lag}
    return _tables


def _gain_limits():
    return rg._gain_bounds()


def _gamma(name, shat, exit_gain=0.0):
    """Gamma_ch,max of 8.5: the full product of the reading law of 4.3."""
    return (1+_gain_limits()[name][1])*(1+shat+exit_gain)


def _W():
    return prior.WEIGHT+BASE["weight_knowledge"]


def _L_max():
    return prior.LEAK+BASE["leakage_knowledge"]


def _shat(settings):
    factor = prior.amplitude_factor(settings)
    return factor*settings["s_p"], factor*settings["s_r"]


def _full_weights(signs):
    return [2/len(signs)*s for s in signs]


def plain_parts(settings, klass, sigma, signs, window):
    """Reference-gain section 8.1 terms, with the statistic's own dwell signs.

    With signs = sigma this is the reviewed B1 evaluation at nominal constants.
    Envelopes keep the true label order. Only the statistic's weights change.
    """
    gains = _gain_limits()
    W = _W()
    base = klass if klass in rg.SPOOF_CLASSES or klass in ("step", "phase_null") else "none"
    env = rg.class_envelope(rg.B1, settings, base, sigma, "primary")
    s_p, s_r = settings["s_p"], settings["s_r"]
    extra = 0.0
    if klass == "step":
        extra = W*(1+gains["r"][1])*rg.PROTOCOL["anchor_step"]["s_r_fraction"]*abs(
            rg.transient_contrast(env["r"]["centre"], signs, window))
    gain = ((1+gains["p"][1])*rg.sequence_gain(settings, "p", env["p"], signs, window,
                                               s_p, W)
            + W*(1+gains["r"][1])*rg.sequence_gain(settings, "r", env["r"], signs,
                                                   window, s_r, W)
            + rg.slow_term(settings, env, signs, window, s_p, s_r, gains, W))
    quiet = rg.class_envelope(rg.B1, settings, rg.quiet_class(klass), sigma, "primary")
    fixed = extra+rg.nuisance_contrast(quiet, signs, window, klass)
    noise, vib = rg.floor_terms(None, window)
    return {"gain": gain, "fixed": fixed, "noise": noise, "vib": vib, "env": env}


def plain_total(settings, klass, signs_of, window):
    """Worst of both orders, as bound_plain takes it."""
    best = None
    for bit in (1, -1):
        sigma = order_for(bit)
        parts = plain_parts(settings, klass, sigma, signs_of(sigma), window)
        total = parts["gain"]+parts["fixed"]
        if best is None or total > best["gain"]+best["fixed"]:
            best = parts
    return best


def _class_extra(settings, klass, window):
    if klass in ("held", "mimic"):
        return rg.plain_class_term(settings, klass, window, "transducer")
    return 0.0


def retained_b1(config):
    """Nominal B1, for regression only. Decisions use the box of 8.0."""
    settings = prior.scenario_settings(config[1])
    identity = lambda sigma: sigma
    values = {}
    for klass in ("none", "phase_null", "held", "mimic", "lag10", "lag01", "spoof+",
                  "spoof-", "step"):
        parts = plain_total(settings, klass, identity, LATE)
        total = parts["gain"]+parts["fixed"]+parts["noise"]+parts["vib"]
        if klass in rg.LAG_CLASSES:
            total += rg.plain_class_term(settings, klass, LATE, "transducer")
        else:
            total += _class_extra(settings, klass, LATE)
        values[klass] = total
    rho = max(rg.settling_rho(order_for(b), LATE) for b in (1, -1))
    S_max = rg.optical()["signal_maximum_newtons"]
    null = max(values["none"],
               values["phase_null"]+rho*2*rg.phase_null_ranges()["recoil_maximum"])
    values["held"] += rho*S_max
    E_S = max(v for k, v in values.items() if k not in ("none", "phase_null"))
    return {"E_N": null, "E_S": E_S, "half": E_S+2*M}


def contrast_rho(signs_w, amplitudes, settled, window_label):
    """rho of 8.4, per unit contrast, per channel's own sup over the box."""
    tables = box_tables()
    coefficients = bounds.lag_coefficients(signs_w, amplitudes)
    return max(bounds.sup_response(tables[c]["force"][window_label], coefficients,
                                   settled)/2 for c in "pr")


def _amps(signs):
    return [0.0, 0.0]+list(signs)


def box_excess(settings, sigma, signs, window_label):
    """Excess of 8.0 over the nominal value, sign kept inside each cell."""
    tables = box_tables()
    gains = _gain_limits()
    W = _W()
    weights = _full_weights(signs)
    shat = dict(zip("pr", _shat(settings)))
    data = rg.optical()
    q_mid = (data["heat_maximum_watts"]+data["heat_minimum_watts"])/2
    q_rad = (data["heat_maximum_watts"]-data["heat_minimum_watts"])/2
    factor = (1+settings["common"])*(1+settings["blind"])
    total = 0.0
    for name, bal, multiplier, couple, heat_couple in (
            ("p", PRIMARY, 1+gains["p"][1], 1.0, 1.0),
            ("r", REFERENCE, W*(1+gains["r"][1]), prior.COUPLING, prior.HEAT_COUPLING)):
        table = tables[name]
        level = prior.COMMON*couple*factor
        change = bounds.sup_change(table["force"][window_label],
                                   table["nominal"][window_label][0],
                                   bounds.lag_coefficients(weights, [level]*bounds.SEGMENTS))
        coefficient = bal.thermal_newtons_per_watt*heat_couple
        heat_c = bounds.lag_coefficients(weights, [0.0, 0.0]+[q_mid]*8)
        nominal = table["heat_nominal"][window_label]
        heat = (bounds.sup_change(table["heat"][window_label], nominal, heat_c)
                * coefficient*(1+X_TAU)
                + X_TAU*coefficient*abs(math.fsum(
                    c*v for c, v in zip(heat_c, nominal))))
        peak = table["nominal"][window_label][1]
        rise = 0.0
        for row in table["force"][window_label]:
            rise = max(rise, math.fsum(max(0.0, e[2]-p) for e, p in zip(row, peak)))
        spread = bounds.held_map(table["heat"][window_label], weights,
                                 [0.0, 0.0]+[q_rad]*8)*coefficient*(1+X_TAU)
        spread -= math.fsum(abs(w)*q_rad*coefficient*math.fsum(
            nominal[i+2-j] for j in range(2, i+3)) for i, w in enumerate(weights))
        total += multiplier*(change+heat+max(0.0, spread))
        total += multiplier*2*shat[name]*level*rise
    return total


def lag_excess(settings, sigma, signs, window_label):
    """Largest box change of a lag term, over both declared lag values.

    Truth follows the primary response, so only the reference's mismatch with
    it is error, section 8.4. Both channels' changes enter through that path.
    """
    tables = box_tables()
    gains = _gain_limits()
    W, L_max = _W(), _L_max()
    best = 0.0
    nominal = _nominal_force()
    amps = [0.0, 0.0]+[nominal*s for s in sigma]
    multiplier = W*L_max*(1+gains["r"][1])
    for tau in LAGS.values():
        scale = rg._lag_scale(list(sigma), tau)
        coefficients = bounds.lag_coefficients(_full_weights(signs), amps)
        value = 0.0
        for name in "pr":
            cells, centre = tables[name]["lag"][tau]
            value += multiplier*bounds.sup_change(cells[window_label],
                                                  centre[window_label], coefficients)
        best = max(best, scale*value)
    return best


def lag_term(settings, sigma, signs, window, tau):
    """Reference-gain lag form at nominal, on the statistic's signs."""
    gains = _gain_limits()
    W, L_max = _W(), _L_max()
    shat_p, shat_r = _shat(settings)
    wave = rg._lag_waveform(sigma, tau)
    u_p = rg._filtered(wave, math.exp(-STEP/PRIMARY.response_seconds))
    u_r = rg._filtered(wave, math.exp(-STEP/REFERENCE.response_seconds))
    D = rg.transient_contrast(u_r, signs, window)-rg.transient_contrast(u_p, signs, window)
    n = len(signs)

    def U(u):
        return 2/n*math.fsum(
            math.fsum(abs(u[(i+2)*100+q-1]) for q in range(window[0], window[1]+1))
            / (window[1]-window[0]+1) for i in range(n))
    return (W*L_max*(1+gains["r"][1])*abs(D)+(1+gains["p"][1])*shat_p*U(u_p)
            + W*L_max*(1+gains["r"][1])*shat_r*U(u_r),
            abs(rg.transient_contrast(u_p, signs, window)))


def transfer_limits():
    return prior.transfer_box()


def kappa_bound():
    """K of section 6: largest |1 - lam*T_c*a_c/T| times U, over both boxes."""
    low, high = transfer_limits()
    U = window_limits()[1]
    a_low = 1-TERMS["r_c"]
    return max(abs(1-LAM*high/low), abs(1-LAM*low*a_low/high))*U


def window_limits():
    box = transfer_limits()
    data = rg.optical()
    walk = data["walk_newtons"]
    return prior.map_interval([data["optical_minimum_newtons"]-walk,
                               data["optical_maximum_newtons"]+walk], box)


def signal_level():
    return transfer_limits()[0]*rg.optical()["signal_minimum_newtons"]


def _x1_mapped(row, settings, window_label, sigma):
    """Channel mapping of 8.5 for X1's added inputs."""
    tables = box_tables()
    gains = _gain_limits()
    W, L_max = _W(), _L_max()
    shat = dict(zip("pr", _shat(settings)))
    signs = dwell_weights("X1", sigma)
    weights = _full_weights(signs)
    window = WINDOWS[window_label]
    S_max = rg.optical()["signal_maximum_newtons"]
    power = source_power()
    feed = BASE["feed_variation_fraction"]
    deviation = S_max/2 if row == "X1-cap" else S_max
    out = dict.fromkeys(("E_forces", "E_sw", "E_J", "E_Qx"), 0.0)
    force = added_force_half(row)
    heat = ((1-_r_x(row)**3)*power*2*feed+TERMS["p_b"]*power)
    if row == "X1-cap":
        heat = power*(2*feed+TERMS["p_b"])
    for name, bal, multiplier in (
            ("p", PRIMARY, 1.0), ("r", REFERENCE, W)):
        gamma = _gamma(name, shat[name], TERMS["g_xb"])*multiplier
        path = 1.0 if name == "p" else L_max
        table = tables[name]
        out["E_forces"] += gamma*path*bounds.held_map(
            table["force"][window_label], weights, [0.0, 0.0]+[force]*8)
        out["E_sw"] += gamma*path*bounds.bins_map(
            bal.response_seconds, STEP, X_TAU, CELLS, weights, window,
            bounds.swap_bins(deviation, TERMS["n_sw_bins"]))
        out["E_J"] += gamma*path*bounds.bins_map(
            bal.response_seconds, STEP, X_TAU, CELLS, weights, window,
            bounds.swap_bins(TERMS["J_b_newton_seconds"]/STEP, 1))
        coupling = prior.HEAT_COUPLING if name == "r" else 1.0
        out["E_Qx"] += (gamma*bal.thermal_newtons_per_watt*(1+X_TAU)*coupling
                        * bounds.held_map(table["heat"][window_label], weights,
                                          [0.0, 0.0]+[heat]*8))
    return out


def _levels(env, signs, window):
    """Sum of |weight*state| over a statistic's samples, per channel."""
    n, count = len(signs), window[1]-window[0]+1
    return {c: math.fsum(abs(env[c]["centre"][(i+2)*100+q-1])
                         for i in range(n) for q in range(window[0], window[1]+1)
                         )*2/n/count for c in "pr"}


def _world_gain(settings):
    """E_G,Q per unit force amplitude F, section 8.4, at B1's weights."""
    gains = _gain_limits()
    shat_p, shat_r = _shat(settings)
    return ((1+gains["p"][1])*shat_p+_W()*(1+gains["r"][1])*shat_r*_L_max())


def _rho_factor():
    """Rho_Q of 8.4 per unit rho and force: both channels' gains and the leak."""
    gains = _gain_limits()
    return (1+gains["p"][1])+_W()*(1+gains["r"][1])*_L_max()


def evaluate(config, window_label="late"):
    """Half-width, world errors and margins. Validity precedes any margin."""
    arch, scenario, row = config
    settings = prior.scenario_settings(scenario)
    window = WINDOWS[window_label]
    plan = {"config": list(config), "valid": True, "reason": None, "window": window_label}
    try:
        _assemble(plan, arch, row, settings, window, window_label)
    except bounds.Unproved as error:
        plan.update(valid=False, reason=str(error))
    return plan


def _base_terms(arch, row, settings, window, window_label):
    """E_N at this statistic's signs, worst of both orders, plus the box excess."""
    def signs_of(sigma):
        return dwell_weights(arch, sigma)
    quiet = settings
    if row == "X1-N":
        quiet = dict(settings, s_p=0.0, s_r=0.0, classes=settings["classes"]-{
            "label_correlated"})
    nominal = plain_total(quiet, "none", signs_of, window)
    if row == "X1-N":
        full = plain_total(settings, "none", signs_of, window)
        nominal = dict(nominal, gain=nominal["gain"]+TERMS["chi"]*(
            full["gain"]-nominal["gain"]))
    phase_null = plain_total(quiet, "phase_null", signs_of, window)
    rho_null = max(contrast_rho(_full_weights(signs_of(order_for(b))),
                                _amps(signs_of(order_for(b))), 2.0, window_label)
                   for b in (1, -1))
    null_extra = rho_null*2*rg.phase_null_ranges()["recoil_maximum"]
    excess = max(box_excess(settings, order_for(b), signs_of(order_for(b)), window_label)
                 for b in (1, -1))
    return nominal, phase_null, null_extra, excess


def _assemble(plan, arch, row, settings, window, window_label):
    data = rg.optical()
    S_max = data["signal_maximum_newtons"]
    lower, upper = window_limits()
    level = signal_level()
    nominal, phase_null, null_extra, excess = _base_terms(arch, row, settings, window,
                                                          window_label)
    scale_read, scale_gain = 1.0, 1.0
    w_Q = 1.0
    if row == "X1-cap":
        scale_read = scale_gain = 2.0
        w_Q = 2.0
    elif arch == "T1":
        delta = delta_for(row)
        t1_weights(row)
        scale_read, scale_gain = SPAN/delta, SPAN/delta/2
        w_Q = SPAN/delta
    elif arch == "M1":
        scale_read = scale_gain = 1+LAM
        w_Q = 1+LAM

    def combine(parts):
        return (scale_read*(parts["noise"]+parts["vib"]+parts["fixed"])
                + scale_gain*parts["gain"])
    E_N0 = (max(combine(nominal), combine(phase_null)+scale_read*null_extra*_rho_factor())
            + scale_read*excess)
    domain = force_domain()
    A_max, T_low = domain["A_max"], transfer_limits()[0]
    unit = (_world_gain(settings)*(TERMS["chi"] if row == "X1-N" else 1.0)
            * (1.5 if row == "T1-over" else 1.0))
    E_G = unit*S_max
    F_I = A_max
    plan_terms = {"E_N0": E_N0, "excess": scale_read*excess}
    sigma = order_for(1)
    signs = dwell_weights(arch, sigma)
    w_full = _full_weights(signs)
    rho_r = max(contrast_rho(_full_weights(dwell_weights(arch, order_for(b))),
                             _amps(dwell_weights(arch, order_for(b))), 2.0, window_label)
                for b in (1, -1))
    add, route_R, route_I = 0.0, 0.0, 0.0
    g_Q, set_term = 1.0, 0.0
    if arch == "X1":
        g_Q = 1.0 if row == "X1-cap" else _r_x(row)**3
        mapped = _x1_mapped(row, settings, window_label, sigma)
        env = nominal["env"]
        levels = _levels(env, signs, window)
        gains = _gain_limits()
        gx0 = TERMS["g_xb"]*((1+gains["p"][1])*levels["p"]
                             + _W()*(1+gains["r"][1])*levels["r"])
        gxU = TERMS["g_xb"]*S_max*_rho_factor()
        E_z = TERMS["zeta_b"]*upper
        add = (mapped["E_forces"]+mapped["E_sw"]+mapped["E_J"]+mapped["E_Qx"]+gx0)*scale_read
        F_I = A_max+E_z/T_low
        route_R = gxU*scale_read
        route_I = TERMS["g_xb"]*F_I*_rho_factor()*scale_read
        set_term = E_z
        rho_i = max(contrast_rho(_full_weights(dwell_weights(arch, order_for(b))),
                                 _amps(order_for(b)), 0.0, window_label)
                    for b in (1, -1))
        plan_terms.update(mapped, E_gx0=gx0, E_gxU=gxU, E_z=E_z, rho_i=rho_i)
        impostor_rho = rho_i*F_I*scale_read*_rho_factor()
    else:
        impostor_rho = rho_r*F_I*scale_read*_rho_factor()
    if arch == "T1":
        delta = delta_for(row)
        E_lev = upper*TERMS["u_l_metres"]/delta
        c = SPAN/2/delta
        dg = BASE["calibration_knowledge"]
        feed = BASE["feed_variation_fraction"]
        shat_map = dict(zip("pr", _shat(settings)))
        E_mom = (2*feed*source_power()/C_LIGHT*TERMS["dx_metres"]/delta
                 * (_gamma("p", shat_map["p"])+_W()*_L_max()*_gamma("r", shat_map["r"])))
        E_box = c*dg*(1+_W()*_L_max())*upper/transfer_limits()[0]
        add = E_mom
        route_R, route_I = E_box, E_box
        set_term = E_lev
        plan_terms.update(E_lev=E_lev, E_mom=E_mom, E_box=E_box)
    if arch == "M1":
        K = kappa_bound()
        power, feed = source_power(), BASE["feed_variation_fraction"]
        tables = box_tables()
        gains = _gain_limits()
        shat = dict(zip("pr", _shat(settings)))
        force = catcher_force_half()
        E_c = E_Qc = 0.0
        for name, bal, multiplier, path in (
                ("p", PRIMARY, 1.0, 1.0), ("r", REFERENCE, _W(), _L_max())):
            gamma = _gamma(name, shat[name])*multiplier*LAM
            E_c += gamma*path*bounds.held_map(tables[name]["force"][window_label], w_full,
                                              [0.0, 0.0]+[force]*8)
            coupling = prior.HEAT_COUPLING if name == "r" else 1.0
            E_Qc += (gamma*bal.thermal_newtons_per_watt*(1+X_TAU)*coupling*bounds.held_map(
                tables[name]["heat"][window_label], w_full,
                [0.0, 0.0]+[power*2*feed]*8))
        add = E_c+E_Qc
        route_R, set_term = K, K
        plan_terms.update(K=K, E_c=E_c, E_Qc=E_Qc)
    E_N = E_N0+add
    E_signal = scale_read*(rho_r*S_max*_rho_factor()+E_G)
    if arch == "M1":
        # Section 8.4: the balance pair carries recoil plus impostor, the catcher
        # pair recoil alone, and wander can align all four channels.
        force_I = S_max+A_max+LAM*S_max
        E_G_I = unit*force_I
        E_impostor = rho_r*_rho_factor()*force_I+E_G_I
    else:
        E_G_I = scale_read*unit*F_I
        E_impostor = impostor_rho+E_G_I
    plan_terms.update(A_min=domain["A_min"], A_max=A_max, F_I=F_I, E_G_R=scale_read*E_G,
                      E_G_I=E_G_I)
    E_R = E_N+E_signal+route_R
    E_I = E_N+E_impostor+route_I
    if arch == "X1":
        E_I += plan_terms["E_z"]
    E_M, E_L = _other_worlds(arch, row, settings, window, window_label, E_N, scale_read)
    E_S = max(E_R, E_I, E_M, E_L)
    half = E_S+2*M*w_Q
    plan.update(E_N=E_N, E_R=E_R, E_I=E_I, E_M=E_M, E_L=E_L, E_S=E_S, half=half, w_Q=w_Q,
                lower=lower, upper=upper, signal_level=level, g_Q=g_Q, rho=rho_r,
                terms=plan_terms)
    if arch == "X1":
        Ehat_R, Ehat_I = E_R, E_I-plan_terms["E_z"]
        low = _r_x(row)**3 if row != "X1-cap" else 1.0
        plan.update(bounds.x1_margins(low, level, lower, plan_terms["E_z"], Ehat_R,
                                      Ehat_I, half))
        plan.update(predicted=[low*lower, upper], null_set=plan_terms["E_z"],
                    a_goal=None, set_term=plan_terms["E_z"])
    elif arch == "T1":
        Ehat_R, Ehat_I = E_R-set_term, E_I
        plan.update(bounds.t1_margins(lower, set_term, Ehat_R, Ehat_I, half))
        plan.update(a_goal=lower, set_term=set_term)
    elif arch == "M1":
        Ehat_R, Ehat_I = E_R-set_term, E_I
        sets = bounds.m1_margins(lower, set_term, Ehat_R, Ehat_I, half)
        plan.update(sets, a_goal=lower, set_term=set_term)
        plan["a_star"] = bounds.a_star_m1(REQUIRED, set_term, Ehat_R, Ehat_I, half)
        plan["a_star_state"] = bounds.a_star_state(plan["a_star"], T_low, A_max)
    else:
        E_A = max(E_S, E_N+(rho_r*_rho_factor()+unit)*(S_max+A_max))
        half_A = E_A+2*M*w_Q
        star = bounds.a_star_b1(REQUIRED, lower, upper, E_A, half_A)
        plan_terms.update(E_A=E_A, half_A=half_A)
        plan.update(m_R=None, m_I=None, separation="not_estimable",
                    m_null=lower-E_N-half, m_signal=level-E_S-half, a_star=star,
                    a_star_state=bounds.a_star_state(star, T_low, A_max))


def _other_worlds(arch, row, settings, window, window_label, E_N, scale):
    best_L = 0.0
    for bit in (1, -1):
        sigma = order_for(bit)
        signs = dwell_weights(arch, sigma)
        excess = lag_excess(settings, sigma, signs, window_label)
        for tau in LAGS.values():
            term, _ = lag_term(settings, sigma, signs, window, tau)
            best_L = max(best_L, term+excess)
    shat_r = _shat(settings)[1]
    if row == "X1-N":
        shat_r *= TERMS["chi"]
    mimic = ((1+settings["common"])*prior.nominal_contrast()*shat_r
             * (1+_gain_limits()["r"][1]))
    rho_b = max(
        contrast_rho(_full_weights(dwell_weights(arch, order_for(b))),
                     _amps(order_for(b) if arch == "X1" else dwell_weights(arch, order_for(b))),
                     0.0 if arch == "X1" else 2.0, window_label)
        for b in (1, -1))*prior.nominal_contrast()*_rho_factor()
    return E_N+scale*(mimic+rho_b), E_N+scale*best_L


def lag_design(config, late_half):
    """k_Q, dk_Q and B_early of 9.4. A failed guard is unproved, and says so."""
    arch = config[0]
    guard = PROTOCOL["lag_decision"]["guard_minimum_late_fraction"]
    tables = box_tables()["p"]
    k, dk = 0.0, 0.0
    try:
        early = evaluate(config, "early")
        if not early["valid"]:
            raise bounds.Unproved(early["reason"])
        for bit in (1, -1):
            signs = dwell_weights(arch, order_for(bit))
            coefficients = bounds.lag_coefficients(_full_weights(signs), _amps(signs))
            ratio, change = bounds.ratio_change(
                tables["force"]["early"], tables["force"]["late"], coefficients,
                tables["nominal"]["early"][0], tables["nominal"]["late"][0], guard)
            k, dk = max(k, ratio), max(dk, change)
    except bounds.Unproved as error:
        return {"proved": False, "reason": str(error)}
    return {"proved": True, "k": k, "dk": dk, "half_early": early["half"],
            "half_late": late_half}


def lag_statistic(stats, design):
    """Lambda and its half-width, from statistics and design values only."""
    early, late = source_part(stats, "Q", "early"), source_part(stats, "Q", "late")
    return (early-design["k"]*late,
            design["half_early"]+design["k"]*design["half_late"]+abs(late)*design["dk"])


def lag_state(flags, design):
    """flags maps instant, short and long to lists of exceedances, section 9.4."""
    if not design["proved"]:
        return "unproved"
    if any(flags["instant"]) or any(flags["short"]):
        return "lag_separated_defect"
    if flags["long"] and all(flags["long"]):
        return "attribution_separated_conditional"
    return "rank_raised_not_resolved"


def reference_threshold(config, plan):
    """T_ref of 9.5, design time, from the class. Never from data."""
    settings = prior.scenario_settings(config[1])
    gains = _gain_limits()
    G_r = 1+gains["r"][1]
    shat_r = _shat(settings)[1]
    tables = box_tables()["r"]
    data = rg.optical()
    q_rad = (data["heat_maximum_watts"]-data["heat_minimum_watts"])/2
    kernel = rg.prior_bounds.mean_kernel(10, prior.BAND[0], STEP)
    read = 2*(REFERENCE.noise_bound_newtons+REFERENCE.vibration_newtons*kernel)
    best = 0.0
    for bit in (1, -1):
        sigma = order_for(bit)
        signs = dwell_weights("X1", sigma)
        weights = _full_weights(signs)
        env = rg.class_envelope(rg.B1, settings, "none", sigma, "primary")
        level = _levels(env, signs, LATE)["r"]
        level_force = prior.COMMON*prior.COUPLING*(1+settings["common"])
        change = bounds.sup_change(tables["force"]["late"], tables["nominal"]["late"][0],
                                   bounds.lag_coefficients(weights, [level_force]*10))
        heat = (bounds.held_map(tables["heat"]["late"], weights, [0.0, 0.0]+[q_rad]*8)
                * REFERENCE.thermal_newtons_per_watt*(1+X_TAU)*prior.HEAT_COUPLING)
        best = max(best, read+G_r*(shat_r+TERMS["g_xb"])*level+G_r*change+G_r*heat
                   + 2*settings["common"]*prior.COUPLING*prior.COMMON*G_r
                   + _L_max()*G_r*data["signal_maximum_newtons"])
    return best


def detection_design(config, plan):
    """Threshold and required flag of each detection, section 9.5."""
    arch = config[0]
    if not plan["valid"]:
        return None
    factor = PROTOCOL["detection_controls"][
        "required_when_injected_at_least_threshold_times"]
    nominal = prior.nominal_contrast()
    if arch == "X1":
        threshold = reference_threshold(config, plan)
        injected = (1+_gain_limits()["r"][0])*nominal/_W()
        return {"name": "reference_interaction", "threshold": threshold,
                "injected": injected, "required": injected >= factor*threshold,
                "statistic": "reference_contrast",
                "control": "reference-mimic-on-sigma-e"}
    if arch == "M1":
        terms = plan["terms"]
        threshold = terms["E_N0"]/(1+LAM)+terms["E_c"]+terms["E_Qc"]
        injected = (1-TERMS["r_c"])*transfer_limits()[0]*nominal
        return {"name": "catcher_lab", "threshold": threshold, "injected": injected,
                "required": injected >= factor*threshold, "statistic": "catcher_sigma",
                "control": "paired-attempt-with-n-l"}
    return None


# Decisions, section 10.

def decide(arch, plan, q, *, commanded_null=False):
    """Rejection tuple. q is already aligned to the detector's source-frame sign.

    It reads a statistic, its half-width and declared sets only. A commanded
    null changes the prediction, as the operator knows, and never reads truth.
    """
    half = plan["half"]
    if arch == "X1":
        low, high = plan["predicted"]
        reject_recoil = q+half < low
        overlap = q+half >= low and q-half <= high
        reject_impostor = abs(q)-half > plan["null_set"] and overlap
        contradicted = q+half < 0
    elif arch == "B1":
        low, high = plan["lower"], plan["upper"]
        if commanded_null:
            low, high = -plan["lower"], plan["lower"]
        resolved = abs(q) > half
        overlap = q+half >= low and q-half <= high
        return {"resolved": resolved, "overlap": overlap,
                "decision": "resolved_overlap" if resolved and overlap else (
                    "resolved_no_overlap" if resolved else (
                        "unresolved_overlap" if overlap else "unresolved_no_overlap"))}
    else:
        K = plan["set_term"]
        reject_recoil = abs(q)-half > K
        reject_impostor = abs(q)+half < plan["a_goal"]-(K if arch == "M1" else 0.0)
        contradicted = False
    if contradicted:
        decision = "contradicted"
    elif reject_recoil and reject_impostor:
        decision = "both"
    elif reject_recoil:
        decision = "reject_recoil"
    elif reject_impostor:
        decision = "reject_impostor"
    else:
        decision = "unresolved"
    return {"reject_recoil": reject_recoil, "reject_impostor": reject_impostor,
            "decision": decision}


CONTROLS = {
    "common": ("opposite-phase", "force-decoupled", "phase-null",
               "impostor-lab-fixed-in-window", "impostor-source-fixed-instant",
               "impostor-source-fixed-lag-10s", "impostor-source-fixed-lag-0p1s",
               "reference-path-label-mimic", "impostor-out-of-window"),
    "B1": (),
    "X1": ("mixed-impostor-in-class", "reference-mimic-on-sigma-e",
           "near-exit-following-0p5", "near-exit-following-0p9", "exit-stuck",
           "exit-part-way", "exit-following-impostor"),
    "T1": ("near-aperture-1mm", "aperture-local-impostor"),
    "M1": ("near-substitution-0p5", "catcher-offset", "substitutive-world",
           "paired-forces", "paired-attempt-with-n-l"),
}
OUTSIDE = {"B1": ("substitutive-world",), "X1": ("exit-following-impostor",),
           "T1": ("aperture-local-impostor",),
           "M1": ("substitutive-world", "paired-forces")}
EXPECT = {
    "X1": {"opposite-phase": "reject_impostor", "force-decoupled": "reject_recoil",
           "impostor-lab-fixed-in-window": "reject_recoil",
           "impostor-source-fixed-instant": "reject_recoil",
           "mixed-impostor-in-class": "reject_recoil",
           "reference-path-label-mimic": "reject_recoil",
           "reference-mimic-on-sigma-e": "reject_impostor"},
    "T1": {"opposite-phase": "reject_impostor", "force-decoupled": "reject_impostor",
           "impostor-source-fixed-instant": "reject_recoil",
           "impostor-lab-fixed-in-window": "reject_impostor"},
    "M1": {"opposite-phase": "reject_impostor",
           "impostor-source-fixed-instant": "reject_recoil"},
    "B1": {"opposite-phase": "resolved_overlap",
           "force-decoupled": "unresolved_no_overlap",
           "phase-null": "unresolved_overlap",
           "impostor-source-fixed-instant": "resolved_overlap"},
}


def controls_for(arch):
    return CONTROLS["common"]+CONTROLS[arch]


def acquire(config, seed, control, orientation, cohort, *, noise=None, **override):
    """noise, where given, builds a path from the draws: a generator witness."""
    draws = draw(config, seed, control, orientation, cohort, **override)
    run = simulate(draws, noise_path=noise(draws) if noise else None)
    return draws, run


def dual(config, plan, seed, control, cohort, *, noise=None, **override):
    """Both orientations. K(o) = a*statistic, a the detector's source-frame sign."""
    arch, _, row = config
    stats, guards, runs = {}, {}, {}
    for o in (1, -1):
        draws, run = acquire(config, seed, control, o, cohort, noise=noise, **override)
        reads = detector_sign_reads(draws, run["terms"])
        sign = predicted_sign(draws["order"], reads, dwell_weights(arch, draws["order"]))
        stats[o] = {}
        for label, window in WINDOWS.items():
            values = estimate(arch, row, draws["order"], run["y"], draws["w"],
                              draws["w_c"], window)
            stats[o][label] = {name: sign*value for name, value in values.items()}
        guards[o] = {"reads": reads, "order": draws["order"], "sign": sign}
        runs[o] = (draws, run)
    return stats, guards, runs


def guard_status(config, control, guards):
    """X1's guard, on detector reads. A commanded null has no sign to confirm."""
    arch, _, row = config
    if arch != "X1" or control == "phase-null":
        return True
    half = detector_half()
    data = rg.optical()
    low = _r_x(row)**3*data["optical_minimum_newtons"]
    for o in (1, -1):
        result = exit_guard(guards[o]["order"], guards[o]["reads"], half, low,
                            data["optical_maximum_newtons"], capture=row == "X1-cap")
        if not result["pass"]:
            return False
    return True


def source_part(stats, name="Q", window="late"):
    return (stats[1][window][name]-stats[-1][window][name])/2


def lab_part(stats, name="Q", window="late"):
    return (stats[1][window][name]+stats[-1][window][name])/2


def truth(runs, config, guards):
    """T_D: fixed gains, actual forces, fixed w, combined as the decision combines."""
    arch, _, row = config
    total = 0.0
    for o, (draws, run) in runs.items():
        total += o*guards[o]["sign"]*_truth_one(draws, run, arch, row)/2
    return total


def lab_truth(runs, config, guards):
    """T_Sigma of section 10.4, with the same two coefficients."""
    arch, _, row = config
    total = 0.0
    for o, (draws, run) in runs.items():
        total += guards[o]["sign"]*_truth_one(draws, run, arch, row)/2
    return total


def _truth_one(draws, run, arch, row):
    terms = run["terms"]
    sigma = draws["order"]
    signs = dwell_weights(arch, sigma)
    gains = draws["gains"]
    n = len(sigma)
    o = draws["orientation"]
    beta = terms["beta"]
    # Forces through the primary response, so lag and settling stay in truth.
    a = math.exp(-STEP/PRIMARY.response_seconds)
    source = [o*(beta*g*s+i)+(0.0 if arch == "T1" else l) for g, s, i, l in zip(
        terms["gam"], terms["recoil"], terms["iota"], terms["lab"])]
    state = rg._filtered(source, a)
    a_r = math.exp(-STEP/REFERENCE.response_seconds)
    mimic = rg._filtered(terms["mimic"], a_r)
    if arch == "T1":
        T_pair = 0.5*((1+gains["p1"])+(1+gains["p2"]))-draws["w"]*draws["leak"]*0.5*(
            (1+gains["r1"])+(1+gains["r2"]))
        contrast = 2/n*math.fsum(s*_mean(state, i+2, LATE) for i, s in enumerate(signs))
        return T_pair*contrast*_lever_ratio(draws)
    T = (1+gains["p"])-draws["w"]*draws["leak"]*(1+gains["r"])
    contrast = 2/n*math.fsum(s*_mean(state, i+2, LATE) for i, s in enumerate(signs))
    value = T*contrast-draws["w"]*(1+gains["r"])*2/n*math.fsum(
        s*_mean(mimic, i+2, LATE) for i, s in enumerate(signs))
    if row == "X1-cap":
        value *= 2
    if arch == "M1":
        T_c = (1+gains["q"])-draws["w_c"]*draws["leak_c"]*(1+gains["u"])
        light = [o*(-draws["a_c"]*terms["light"]*g*s+c)+n for g, s, c, n in zip(
            terms["gam"], terms["recoil"], terms["catcher"], terms["catcher_lab"])]
        caught = rg._filtered(light, a)
        value += LAM*T_c*2/n*math.fsum(s*_mean(caught, i+2, LATE)
                                       for i, s in enumerate(signs))
    return value


def _lever_ratio(draws):
    """Truth lever for the row's force, from zhat_a = 0. Generator side."""
    control, row = draws["control"], draws["config"][2]
    delta = delta_for(row)
    if control == "aperture-local-impostor":
        return draws["z_a"]/delta
    if control == "near-aperture-1mm":
        return 1e-3/delta
    if control in ("opposite-phase",):
        return draws["z_a"]/delta
    return lever_for(row)*(1 if draws["seed"] % 2 else -1)/delta


def lab_audit(arch, stats, runs, plan, control):
    """Lab-fixed detection through Sigma, section 9.2."""
    if control != "impostor-lab-fixed-in-window":
        return None
    name = "C_s" if arch == "X1" else ("C" if arch in ("B1", "M1", "T1") else "Q")
    return abs(lab_part(stats, name)) > plan["half"]


def run_control(config, plan, seed, control, cohort, *, noise=None, **override):
    arch = config[0]
    stats, guards, runs = dual(config, plan, seed, control, cohort, noise=noise, **override)
    guard_ok = guard_status(config, control, guards)
    q = source_part(stats)
    decision = decide(arch, plan, q, commanded_null=control == "phase-null")
    actual = truth(runs, config, guards)
    error = abs(q-actual)
    sigma_error = abs(lab_part(stats)-lab_truth(runs, config, guards))
    row = {"control": control, "seed": seed, "Q": q, "truth": actual, "error": error,
           "half": plan["half"], "decision": decision["decision"], "guard": guard_ok,
           "covered": error <= plan["half"],
           "dual_covered": sigma_error <= plan["half"]+prior.FLIP*plan["upper"]}
    expected = EXPECT[arch].get(control)
    row["expected"] = expected
    row["matched"] = expected is None or decision["decision"] == expected
    lab = lab_audit(arch, stats, runs, plan, control)
    if lab is not None:
        row["lab_detected"] = lab
    if arch == "X1":
        row["reference_contrast"] = abs(source_part(stats, "C_ref_x"))
    if arch == "M1":
        row["catcher_sigma"] = abs(lab_part(stats, "C_q"))
    return row, stats, runs


def paired_audit(config, plan, seed, control, cohort):
    """Section 2.4: actual tuples against the matched recoil world, never labels."""
    world, world_stats, world_runs = run_control(config, plan, seed, "opposite-phase",
                                                 cohort)
    row, stats, runs = run_control(config, plan, seed, control, cohort)
    worst = 0.0
    for o in (1, -1):
        for name in CHANNELS[config[0]]:
            worst = max(worst, max(abs(a-b) for a, b in zip(
                runs[o][1]["y"][name], world_runs[o][1]["y"][name])))
    same_stats = stats == world_stats
    same_tuple = (row["decision"], row["half"], row["Q"]) == (
        world["decision"], world["half"], world["Q"])
    return {"control": control, "seed": seed, "reading_difference": worst,
            "readings_identical": worst <= READING_TOLERANCE,
            "statistics_identical": same_stats, "tuple_identical": same_tuple,
            "decision": row["decision"], "matched_decision": world["decision"]}


def witness_noise(config, sign):
    """Noise at its bound, added to the source-frame statistic. Generator side."""
    arch = config[0]

    def build(draws):
        lock = dwell_weights(arch, draws["order"])
        aligned = sign*draws["orientation"]*draws["mapping"]

        def noise(name, k):
            if k < 200:
                return 0.0
            bound = balance(name).noise_bound_newtons
            flip = -1 if name[0] in "ru" else 1
            pair = -1 if arch == "T1" and name.endswith("1") else 1
            return aligned*flip*pair*lock[k//100-2]*bound
        return noise
    return build


def run_witnesses(config, plan, seed, cohort):
    """Six fixed witnesses, three worlds at both signs. Lower evidence only."""
    rows = []
    for control, name in (("opposite-phase", "recoil"), ("witness-impostor", "impostor"),
                          ("witness-null", "null")):
        for sign in (1, -1):
            row, _, _ = run_control(config, plan, seed, control, cohort,
                                    noise=witness_noise(config, sign))
            rows.append({"world": name, "sign": sign, "Q": row["Q"], "error": row["error"],
                         "half": row["half"], "covered": row["covered"],
                         "decision": row["decision"]})
    return rows


WITNESS_EXPECT = {
    "X1": {"recoil": "reject_impostor", "impostor": "reject_recoil", "null": "reject_recoil"},
    "T1": {"recoil": "reject_impostor", "impostor": "reject_recoil", "null": "reject_impostor"},
    "M1": {"recoil": "reject_impostor", "impostor": "reject_recoil"},
    "B1": {},
}
CAUSES = {
    1: ("m_R_below", "m_I_below"),
    2: ("decision", "lab_fixed_miss", "detection_miss", "detection_false"),
    3: ("truth", "dual_truth"),
    4: ("witness_decision", "witness_outside_half"),
    5: ("guard", "paired_audit", "witness_outside_half", "injection", "budget",
        "lag_separated"),
}
ROW_LIMIT = 8


def _new_summary(config, plan):
    return {"config": list(config), "plan": public_plan(plan), "rows": 0, "failing": [],
            "condition_causes": {str(c): {name: {"count": 0, "first": None}
                                          for name in names}
                                 for c, names in CAUSES.items()},
            "paired": [], "witnesses": [], "guard_failures": 0, "operational": [],
            "large_stimulus": "diagnostic_outside_declared_domain_no_bound"}


def public_plan(plan):
    out = {}
    for key, value in plan.items():
        if isinstance(value, float):
            out[key] = value
        elif key in ("config", "reason", "window", "valid", "separation", "a_star_state"):
            out[key] = value
    if "terms" in plan:
        out["terms"] = {k: v for k, v in plan["terms"].items()}
    if "predicted" in plan:
        out["predicted"] = plan["predicted"]
    return out


def _cause(summary, condition, name, reference):
    entry = summary["condition_causes"][str(condition)][name]
    entry["count"] += 1
    if entry["first"] is None:
        entry["first"] = reference


def _detect(summary, detection, result, reference):
    """Count one detection row. It never changes a decision or a half-width."""
    if detection is None or detection["statistic"] not in result:
        return
    value = result[detection["statistic"]]
    entry = summary["detection"]
    flagged = value > detection["threshold"]
    if result["control"] == detection["control"]:
        entry["rows"] += 1
        entry["detected"] += flagged
        entry["worst_statistic"] = (value if entry["worst_statistic"] is None
                                    else min(entry["worst_statistic"], value))
        if detection["required"] and not flagged:
            _cause(summary, 2, "detection_miss", reference)
    elif result["control"] in ("opposite-phase", "force-decoupled"):
        entry["false_rows"] += flagged
        if flagged:
            _cause(summary, 2, "detection_false", reference)


def _lag_rows(summary, design, stats, control, reference, flags):
    if not design["proved"]:
        return
    group = {"impostor-source-fixed-instant": "instant",
             "impostor-source-fixed-lag-0p1s": "short",
             "impostor-source-fixed-lag-10s": "long"}.get(control)
    if group is None:
        return
    value, half = lag_statistic(stats, design)
    flags[group].append(abs(value) > half)
    if group != "long" and abs(value) > half:
        _cause(summary, 5, "lag_separated", reference)


def run_configuration(config, seeds, cohort):
    seed_gate(seeds, cohort)
    arch, _, row = config
    plan = evaluate(config)
    summary = _new_summary(config, plan)
    if not plan["valid"]:
        summary["class"] = "inconclusive_invalid_envelope"
        summary["lag_state"] = "unproved"
        return finish_summary(summary)
    design = lag_design(config, plan["half"])
    summary["lag"] = {k: v for k, v in design.items() if k != "half_late"}
    flags = {"instant": [], "short": [], "long": []}
    detection = detection_design(config, plan)
    if detection:
        summary["detection"] = {
            "name": detection["name"], "threshold": detection["threshold"],
            "injected": detection["injected"], "required": detection["required"],
            "rows": 0, "detected": 0, "false_rows": 0, "worst_statistic": None}
    for seed in seeds:
        for control in controls_for(arch):
            if control in OUTSIDE.get(arch, ()):
                continue
            try:
                result, stats, _ = run_control(config, plan, seed, control, cohort)
            except OperationalFailure as error:
                summary["operational"].append(f"{control}: {error}")
                continue
            summary["rows"] += 1
            reference = f"{control}|{seed}"
            _detect(summary, detection, result, reference)
            _lag_rows(summary, design, stats, control, reference, flags)
            if control == "exit-stuck":
                if result["guard"]:
                    _cause(summary, 5, "guard", reference)
            elif control != "exit-part-way" and not result["guard"]:
                summary["guard_failures"] += 1
                _cause(summary, 5, "guard", reference)
            if not result["matched"]:
                _cause(summary, 2, "decision", reference)
                _keep(summary, result)
            if result.get("lab_detected") is False:
                _cause(summary, 2, "lab_fixed_miss", reference)
            if not result["covered"] and control != "impostor-out-of-window":
                _cause(summary, 3, "truth", reference)
                _keep(summary, result)
            if not result["dual_covered"] and control != "impostor-out-of-window":
                _cause(summary, 3, "dual_truth", reference)
        for control in OUTSIDE.get(arch, ()):
            audit = paired_audit(config, plan, seed, control, cohort)
            summary["paired"].append(audit)
            if not (audit["readings_identical"] and audit["statistics_identical"]
                    and audit["tuple_identical"]):
                _cause(summary, 5, "paired_audit", f"{control}|{seed}")
    summary["lag_state"] = lag_state(flags, design)
    injection = oracle_injection(config, seeds[0], cohort)
    summary["injection_worst"] = injection
    if injection > READING_TOLERANCE:
        _cause(summary, 5, "injection", str(seeds[0]))
    rows = run_witnesses(config, plan, seeds[0], cohort)
    summary["witnesses"] = rows
    for item in rows:
        wanted = WITNESS_EXPECT[arch].get(item["world"])
        if wanted and item["decision"] != wanted:
            _cause(summary, 4, "witness_decision", f"{item['world']}|{item['sign']}")
        if not item["covered"]:
            _cause(summary, 4, "witness_outside_half", f"{item['world']}|{item['sign']}")
            _cause(summary, 5, "witness_outside_half", f"{item['world']}|{item['sign']}")
    if plan.get("m_R") is not None:
        if plan["m_R"] < REQUIRED:
            _cause(summary, 1, "m_R_below", "design")
        if plan["m_I"] < REQUIRED:
            _cause(summary, 1, "m_I_below", "design")
    return finish_summary(summary)


def _keep(summary, row):
    if len(summary["failing"]) < ROW_LIMIT:
        summary["failing"].append({k: row[k] for k in (
            "control", "seed", "Q", "truth", "error", "decision")})


def oracle_injection(config, seed, cohort):
    """Separate replay of the channel recursion on the generator's forces."""
    arch = config[0]
    draws, run = acquire(config, seed, "opposite-phase", 1, cohort)
    worst = 0.0
    for name in CHANNELS[arch]:
        heat = _channel_heat(run["terms"], name)
        replay = oracle.replay_state(oracle.constants(name), run["forces"][name], heat)
        worst = max(worst, max(abs(a-b) for a, b in zip(replay, run["states"][name])))
    return worst


def _channel_heat(terms, name):
    if name[0] in "qu":
        return [source_power() if q else 0.0 for q in terms["heat"]]
    return terms["heat"]


def condition_met(summary, condition):
    return all(entry["count"] == 0 for entry in
               summary["condition_causes"][str(condition)].values())


def classify(summary):
    """First match wins, section 10.5. Validity is read before any margin."""
    arch = summary["config"][0]
    if summary.get("class"):
        return summary["class"]
    if summary["operational"]:
        return "operational_failure"
    if arch == "B1":
        return "structurally_degenerate"
    if not condition_met(summary, 5):
        return "inconclusive_invalid_envelope"
    two, three = condition_met(summary, 2), condition_met(summary, 3)
    if not (two and three):
        return "negative"
    if not (condition_met(summary, 1) and condition_met(summary, 4)):
        return "seeded_pass_not_robust"
    return "conditional_model_qualification"


def missing_causes(summary):
    """A class short of the positive one must have a named cause."""
    named = any(entry["count"] for causes in summary["condition_causes"].values()
                for entry in causes.values())
    if summary.get("class") == "conditional_model_qualification" or named:
        return []
    if summary["config"][0] == "B1" or summary["operational"]:
        return []
    return [summary.get("class", "unclassified")] if not summary["plan"].get(
        "reason") else []


def finish_summary(summary):
    summary["class"] = classify(summary)
    summary["missing_causes"] = missing_causes(summary)
    return summary


def table_response(signs, amplitudes, window_label, leak=prior.LEAK, weight=prior.WEIGHT):
    """P(v, f, W) of 4.4 at unit gains, by lag tables and not by stepping."""
    weights = _full_weights(signs)
    coefficients = bounds.lag_coefficients(weights, [0.0, 0.0]+list(amplitudes))
    total = 0.0
    for bal, factor in ((PRIMARY, 1.0), (REFERENCE, -weight*leak)):
        a = bounds.decay(bal.response_seconds, STEP)
        table = bounds.nominal_force_table(a, WINDOWS[window_label])[0]
        total += factor*math.fsum(c*v for c, v in zip(coefficients, table))
    return total


def finite_x1(sigma=None, g=0.97):
    """Finite D rows of X1 by lag tables, for comparison with the oracle."""
    sigma = sigma or order_for(1)
    product = dwell_weights("X1", sigma)
    recoil = [s*g*e/2 for s, e in zip(sigma, EXIT)]
    instant = [s/2 for s in sigma]
    rows = {}
    for label in WINDOWS:
        for name, signs in (("s", sigma), ("x", product)):
            rows[f"D^{name}_{label}"] = {
                "r": table_response(signs, recoil, label),
                "s_i": table_response(signs, instant, label),
                "x": table_response(signs, recoil, label)}
    return rows


def finite_m1(sigma=None, a_c=0.999, leak=prior.LEAK):
    """Catcher rows by the forward map's two orientations, on lag tables."""
    sigma = sigma or order_for(1)
    unit = [s/2 for s in sigma]
    rows = {}
    for label in WINDOWS:
        by = {}
        for o in (1, -1):
            by[o] = {"r": table_response(sigma, [-o*a_c*v for v in unit], label, leak),
                     "n_s": table_response(sigma, [o*v for v in unit], label, leak),
                     "n_l": table_response(sigma, unit, label, leak)}
        rows[f"D^c_{label}"] = {n: (by[1][n]-by[-1][n])/2 for n in by[1]}
        rows[f"Sigma^c_{label}"] = {n: (by[1][n]+by[-1][n])/2 for n in by[1]}
    return rows


def structure_statement():
    """Exact rational tables of section 7, from the oracle. Structure only."""
    x1, t1, m1 = oracle.x1_rows(), oracle.t1_rows(), oracle.m1_rows()
    t1_zero = oracle.t1_rows(d=oracle.F(0))
    base = oracle.base_rows()
    return {
        "scope": "exact_rational_representative_entries_no_physical_singular_value",
        "B1": {"rank": oracle.rank(base), "columns": 5,
               "recoil_instant_identical": oracle.identical_columns(base, 0, 1)},
        "X1": {"rank_first_5": oracle.rank(oracle.columns_of(x1, 0, 1, 2, 3, 4)),
               "rank_first_6": oracle.rank(oracle.columns_of(x1, 0, 1, 2, 3, 4, 5)),
               "rank_all": oracle.rank(x1), "columns": 7,
               "recoil_exit_following_identical": oracle.identical_columns(x1, 0, 6)},
        "T1": {"rank_first_5": oracle.rank(oracle.columns_of(t1, 0, 1, 2, 3, 4)),
               "rank_all": oracle.rank(t1), "columns": 6,
               "rank_first_5_d_zero": oracle.rank(
                   oracle.columns_of(t1_zero, 0, 1, 2, 3, 4)),
               "recoil_aperture_identical": oracle.identical_columns(t1, 0, 5)},
        "M1": {"rank_first_5": oracle.rank(oracle.columns_of(m1, 0, 1, 2, 3, 4)),
               "rank_first_6": oracle.rank(oracle.columns_of(m1, 0, 1, 2, 3, 4, 5)),
               "rank_all": oracle.rank(m1), "columns": 7,
               "dependency_holds": oracle.m1_dependency_holds(m1)}}


def structure_matches(statement):
    """H2 against the declared expectations of the twin."""
    wanted = PROTOCOL["response_tables"]["expected"]
    x1, t1, m1, b1 = (statement[k] for k in ("X1", "T1", "M1", "B1"))
    return (b1["rank"] == wanted["B1"]["rank"] and b1["recoil_instant_identical"]
            and x1["rank_first_5"] == wanted["X1"]["rank_first_5"]
            and x1["rank_first_6"] == wanted["X1"]["rank_first_6"]
            and x1["rank_all"] == wanted["X1"]["rank_all"]
            and x1["recoil_exit_following_identical"]
            and t1["rank_first_5"] == wanted["T1"]["rank_first_5_d_nonzero"]
            and t1["rank_first_5_d_zero"] == wanted["T1"]["rank_first_5_d_zero"]
            and t1["rank_all"] == wanted["T1"]["rank_all_d_nonzero"]
            and t1["recoil_aperture_identical"]
            and m1["rank_first_5"] == wanted["M1"]["rank_first_5"]
            and m1["rank_first_6"] == wanted["M1"]["rank_first_6"]
            and m1["rank_all"] == wanted["M1"]["rank_all"] and m1["dependency_holds"])


def near_limits():
    """H9: response against closed form, at unit transfer, on lag tables."""
    tolerance = PROTOCOL["hypothesis_thresholds"]["closed_form_tolerance_fraction_H9"]
    sigma = order_for(1)
    product = dwell_weights("X1", sigma)
    checks = {}
    for ratio in (0.5, 0.9):
        amps = [s*((1-ratio)+ratio*e)/2 for s, e in zip(sigma, EXIT)]
        transfer = 1-prior.WEIGHT*prior.LEAK
        checks[f"x1_{ratio}"] = (table_response(product, amps, "late"), transfer*ratio)
        checks[f"c_s_{ratio}"] = (table_response(sigma, amps, "late"), transfer*(1-ratio))
    for lever in (0.1, 0.001):
        checks[f"t1_{lever}"] = (oracle.t1_statistic(lever, DELTA), lever/DELTA)
    out = {"worst": 0.0}
    for value, closed in checks.values():
        out["worst"] = max(out["worst"], abs(value-closed)/abs(closed))
    out["within"] = out["worst"] <= tolerance
    return out


def seed_gate(seeds, cohort):
    """Section 10.7. A primary cohort is exactly its declared range, or nothing."""
    if not isinstance(seeds, (list, tuple)) or not seeds or len(seeds) > 64:
        raise OperationalFailure("a cohort is a short non-empty list")
    if any(type(seed) is not int for seed in seeds):
        raise OperationalFailure("a seed is an integer")
    if cohort == "fixture":
        low, high = PROTOCOL["seeds"]["fixture_and_witness"]
        if len(set(seeds)) != len(seeds) or not all(low <= s <= high for s in seeds):
            raise OperationalFailure("fixture cohort outside its range")
        return
    if cohort not in MODES or not mode_authorised(cohort):
        raise OperationalFailure("execution is not authorised by the protocol")
    low, high = PROTOCOL["seeds"][cohort]
    if list(seeds) != list(range(low, high+1)):
        raise OperationalFailure("primary cohort differs from its declared range")


POSITIVE = "conditional_model_qualification"
INVALID = ("operational_failure", "inconclusive_invalid_envelope")


def pair_status(by, seeds):
    """H8 and H1 of 10.6: declared keys, each once, or no statement."""
    expected = {(config, seed, control) for config in map(tuple, configurations())
                for seed in seeds for control in OUTSIDE[config[0]]}
    found = {}
    for config, item in by.items():
        for audit in item.get("paired", []):
            key = (config, audit.get("seed"), audit.get("control"))
            if key in found:
                return "inconclusive"
            found[key] = audit
    if set(found) != expected:
        return "inconclusive"
    if any(item["class"] == "operational_failure" for item in by.values()):
        return "inconclusive"
    if all(a["readings_identical"] and a["statistics_identical"] and a["tuple_identical"]
           for a in found.values()):
        return "supported"
    return "refuted"


def comparison_status(by):
    """H10 of 10.6: both rows valid, each with a finite a_star."""
    m1, b1 = by.get(("M1", "S01-constant", "primary")), by.get(
        ("B1", "S01-constant", "primary"))
    if m1 is None or b1 is None or m1["class"] in INVALID:
        return "inconclusive"
    if b1["class"] != "structurally_degenerate":
        return "inconclusive"
    stars = (m1["plan"].get("a_star"), b1["plan"].get("a_star"))
    if not all(isinstance(v, float) and math.isfinite(v) for v in stars):
        return "inconclusive"
    if (m1["plan"].get("a_star_state") != "in_domain"
            or b1["plan"].get("a_star_state") != "in_domain"):
        return "inconclusive"
    return "supported" if stars[0] < stars[1] else "refuted"


def evaluate_hypotheses(results, seeds):
    """Declared rows and declared seeds only. Nothing reads a present list alone."""
    by = {}
    for item in results:
        key = tuple(item["config"])
        if key in by:
            return {name: "inconclusive" for name in PROTOCOL["hypotheses"]}
        by[key] = item

    def row(arch, scenario, name="primary"):
        return by.get((arch, scenario, name))

    def primary(item):
        if item is None or item["class"] in INVALID:
            return "inconclusive"
        return "supported" if item["class"] == POSITIVE else "not_qualified"
    pairs = pair_status(by, seeds)
    structure = structure_matches(structure_statement())
    return {
        "H1": pairs if pairs != "supported" or structure else "refuted",
        "H2": "supported" if structure else "refuted",
        "H3": primary(row("X1", "S05-label-retained")),
        "H4": primary(row("M1", "S05-label-retained")),
        "H5": primary(row("T1", "S05-label-retained")),
        "H6": primary(row("X1", "S01-constant")),
        "H7": primary(row("X1", "S05-label-retained", "X1-N")),
        "H8": pairs,
        "H9": "supported" if near_limits()["within"] else "refuted",
        "H10": comparison_status(by),
    }


def resource_statement():
    """Section 6: known time plus an unknown overhead, and nothing beyond."""
    return {"elapsed_known_seconds": 200, "t_rot": "unknown",
            "total_resource_claim": "not_claimed",
            "matched_hardware_qualification": "not_claimed"}


def canonical(record):
    return rg.canonical(record)


def count_nodes(value):
    return rg.count_nodes(value)


def enforce_record_budget(record):
    """Byte and node caps, per configuration and whole. A breach is retained."""
    text = canonical(record)
    limits = PROTOCOL["limits"]
    lean = PROTOCOL["lean_record"]
    if len(text) > limits["maximum_retained_bytes"]:
        raise OperationalFailure("record exceeds its byte limit")
    if count_nodes(record) > limits["maximum_parser_nodes"]:
        raise OperationalFailure("record exceeds its node limit")
    for item in record["configurations"]:
        if len(canonical(item)) > lean["maximum_bytes_per_configuration"]:
            raise OperationalFailure("configuration exceeds its byte limit")
        if count_nodes(item) > lean["maximum_nodes_per_configuration"]:
            raise OperationalFailure("configuration exceeds its node limit")
    return len(text)


def mode_authorised(mode):
    """Authorisation is per mode. It is never blanket cohort permission."""
    return (PROTOCOL["execution_authorised"] is True
            and mode in PROTOCOL["authorised_modes"])


def source_digests():
    return inputs.digests(ROOT)


def run_cohort(mode, commit, *, root=ROOT.parent.parent):
    """Refuses while unauthorised. Serial, in one process, inside the boundary."""
    if not mode_authorised(mode):
        raise OperationalFailure("execution is not authorised by the protocol")
    if not (isinstance(commit, str) and len(commit) == 40
            and all(ch in "0123456789abcdef" for ch in commit)):
        raise ValueError("a full source commit is required")
    runtime = rg.check_runtime(rg.PROTOCOL)
    return inputs.bound_run(root, ROOT, commit,
                            lambda opened: _cohort(mode, commit, runtime, opened))


def _cohort(mode, commit, runtime, opened):
    low, high = PROTOCOL["seeds"][mode]
    seeds = list(range(low, high+1))
    record = {
        "study": PROTOCOL["study"], "protocol_revision": PROTOCOL["protocol_revision"],
        "environment": ENVIRONMENT, "kind": "identifiability_cohort", "mode": mode,
        "status": "virtual_lab_simulated_not_physical_evidence",
        "source": {"commit": commit, "mode": mode,
                   "argv": ["pf002_identifiability_v1.py", mode]},
        "runtime": runtime, "implementation": opened,
        "resources": resource_statement(),
        "configurations": [run_configuration(c, seeds, mode) for c in configurations()]}
    record["hypotheses"] = evaluate_hypotheses(record["configurations"], seeds)
    record["structure"] = structure_statement()
    record["near_limits"] = near_limits()
    enforce_record_budget(record)
    return record


def main(arguments=None):
    arguments = sys.argv[1:] if arguments is None else arguments
    if not arguments or not mode_authorised(arguments[0]):
        print("execution is not authorised by the protocol", file=sys.stderr)
        return 3
    if (len(arguments) != 5 or arguments[0] not in MODES
            or arguments[1] != "--commit" or arguments[3] != "--result-fd"):
        print("usage: exploratory|confirmatory --commit COMMIT --result-fd FD",
              file=sys.stderr)
        return 2
    record = run_cohort(arguments[0], arguments[2])
    with open(int(arguments[4]), "wb") as sink:
        sink.write(canonical(record))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
