"""PF-002 reference-gain architecture study, version 1.

Virtual lab - simulated experiment. Nothing here is a physical measurement or
calibration. Forces are channel-domain nominal newtons. Execution refuses while
the protocol's execution_authorised is false. Section numbers refer to
PF002_REFERENCE_GAIN_V1.md.
"""

import hashlib
import json
import math
from pathlib import Path
import platform
import random
import sys
import time
import unicodedata

import pf002_reference_gain_bounds_v1 as bounds
import pf002_reference_gain_inputs_v1 as inputs
import pf002_stationarity_bounds_v1 as prior_bounds
import pf002_stationarity_v1 as prior

ROOT = Path(__file__).resolve().parent
PROTOCOL_FILE = "pf002-reference-gain-v1-protocol.json"
ENVIRONMENT = "Virtual lab - simulated experiment"
STRUCTURE_DIGEST = ("sha256:8aad212ae78d0f20d3a7b818f13c47fb"
                    "43aef1fa2848a523b5c1f81796a22945")
IMPLEMENTATION = inputs.INPUTS
# Hard limits. A twin cannot raise these through its own validation block.
MAX_INPUT_BYTES = 1048576
MAX_INPUT_DEPTH = 16
MAX_INPUT_NODES = 20000
MAX_INTEGER_DIGITS = 32


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


def _unique(pairs):
    keys = [key for key, _ in pairs]
    if len(keys) != len(set(keys)):
        raise ValueError("duplicate key in protocol")
    return dict(pairs)


def _reject_constant(token):
    raise ValueError(f"non-finite number in protocol: {token}")


def _finite_float(token):
    """JSON can spell infinity as a finite-looking literal, such as 1e999."""
    value = float(token)
    if not math.isfinite(value):
        raise ValueError(f"number overflows to non-finite: {token}")
    return value


def _bounded_integer(token):
    if len(token) > MAX_INTEGER_DIGITS:
        raise ValueError("integer literal too long")
    return int(token)


def _prescan(data):
    """Depth and node limits, before any recursive parser sees the text."""
    depth = nodes = 0
    inside = escaped = False
    for byte in data:
        if inside:
            if escaped:
                escaped = False
            elif byte == 0x5c:
                escaped = True
            elif byte == 0x22:
                inside = False
            continue
        if byte == 0x22:
            inside = True
        elif byte in (0x7b, 0x5b):
            depth += 1
            nodes += 1
            if depth > MAX_INPUT_DEPTH:
                raise ValueError("protocol nesting too deep")
        elif byte in (0x7d, 0x5d):
            depth -= 1
        elif byte == 0x2c:
            nodes += 1
        if nodes > MAX_INPUT_NODES:
            raise ValueError("protocol has too many nodes")


def _walk(root):
    """Every value, iteratively, so no walk depends on the recursion limit."""
    stack = [root]
    while stack:
        value = stack.pop()
        yield value
        if isinstance(value, dict):
            stack.extend(value.keys())
            stack.extend(value.values())
        elif isinstance(value, list):
            stack.extend(value)


def _number(value, low, high, name):
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise ValueError(f"{name} is not a number")
    if not (math.isfinite(value) and low <= value <= high):
        raise ValueError(f"{name} out of range")
    return value


def _integer(value, low, high, name):
    if type(value) is not int or not low <= value <= high:
        raise ValueError(f"{name} is not an integer in range")
    return value


def _interval(value, low, high, name):
    if not isinstance(value, list) or len(value) != 2:
        raise ValueError(f"{name} is not an interval")
    _number(value[0], low, high, name)
    _number(value[1], low, high, name)
    if value[0] > value[1]:
        raise ValueError(f"{name} is reversed")


def _window(value, name):
    if not isinstance(value, list) or len(value) != 2:
        raise ValueError(f"{name} is not a window")
    _integer(value[0], 1, 100, name)
    _integer(value[1], 1, 100, name)
    if value[0] >= value[1]:
        raise ValueError(f"{name} is reversed")


def _fixed(value, expected, name):
    if type(value) is not type(expected) or value != expected:
        raise ValueError(f"{name} is fixed")


def check_values(p):
    """Types, ranges, sequences, windows and counts. Failure refuses execution."""
    if type(p["execution_authorised"]) is not bool:
        raise ValueError("execution_authorised is not a boolean")
    if p["authorised_modes"] != ["confirmatory"]:
        raise ValueError("only the confirmatory mode may be authorised here")
    _integer(p["protocol_revision"], 1, 1000, "protocol_revision")
    _fixed(p["study"], "pf002-reference-gain-v1", "study")
    _fixed(p["environment"], ENVIRONMENT, "environment")
    rules = p["validation"]
    _fixed(rules["maximum_json_depth"], MAX_INPUT_DEPTH, "depth limit")
    _fixed(rules["maximum_input_bytes"], MAX_INPUT_BYTES, "byte limit")
    _fixed(rules["maximum_input_nodes"], MAX_INPUT_NODES, "node limit")
    timing = p["timing"]
    _fixed(timing["samples_total"], bounds.SESSION_BINS, "samples_total")
    _fixed(timing["sample_step_seconds"], 0.1, "sample step")
    _fixed(timing["total_elapsed_seconds"], 100, "elapsed")
    _fixed(timing["lit_seconds_per_label"], 40, "lit time")
    _fixed(timing["detector_exposure_seconds"], 80, "exposure")
    _fixed(timing["segments"]["lit_dwell_i"]["count"], 8, "dwell count")
    seeds = p["seeds"]
    ranges = []
    for name in ("exploratory", "confirmatory", "fixture_and_witness_search"):
        item = seeds[name]
        if not isinstance(item, list) or len(item) != 2:
            raise ValueError("seed range is not a pair")
        _integer(item[0], 1, 2**31, name)
        _integer(item[1], item[0], 2**31, name)
        ranges.append(item)
    if ranges[1][1]-ranges[1][0]+1 > 16 or ranges[0][1]-ranges[0][0]+1 > 16:
        raise ValueError("seed count cap exceeded")
    if ranges[2][1]-ranges[2][0]+1 != 6:
        raise ValueError("fixture seed count is fixed")
    _fixed(seeds["absolute_confirmatory_cap"], 32, "seed cap")
    for i, one in enumerate(ranges):
        for other in ranges[i+1:]:
            if one[0] <= other[1] and other[0] <= one[1]:
                raise ValueError("seed ranges overlap")
    limits = p["limits"]
    for key, value in (
            ("maximum_runtime_seconds_including_cleanup", 3600),
            ("maximum_retained_bytes", 2097152), ("maximum_parser_nodes", 200000),
            ("maximum_stdout_bytes", 65536), ("maximum_stderr_bytes", 65536),
            ("maximum_study_processes", 1), ("network_calls", 0),
            ("new_dependencies", 0)):
        _fixed(limits[key], value, key)
    _fixed(p["lean_record"]["maximum_bytes_per_configuration"], 24576, "lean bytes")
    _fixed(p["lean_record"]["maximum_nodes_per_configuration"], 2800, "lean nodes")
    _fixed(p["required_margin_newtons"], 1e-12, "required margin")
    _fixed(p["structural_allowance_per_phase_newtons"], 2e-12, "allowance")
    _fixed(p["configuration_count"], 48, "configuration count")
    if len(p["architectures"]) != 4 or p["scenarios"]["count"] != 11:
        raise ValueError("configuration count mismatch")
    names = [row["name"] for row in p["extra_rows"]]
    if len(names) != 4 or len(set(names)) != 4:
        raise ValueError("extra rows mismatch")
    late = {"B1-thue-morse-8-idle-anchor": [91, 100],
            "R1-anchored-reference-tone": [81, 100],
            "R2-commutated-blind-witness": [91, 100],
            "R3-label-keyed-dual-null": [91, 100]}
    if set(p["architectures"]) != set(late):
        raise ValueError("architecture set mismatch")
    for name, arch in p["architectures"].items():
        _fixed(arch["order_rule"], "ABBABAAB_or_seeded_complement", "order rule")
        _window(arch["late_window_samples"], name)
        _window(arch["early_window_samples"], name)
        if arch["late_window_samples"] != late[name]:
            raise ValueError("late window is fixed")
        if arch["early_window_samples"][1] >= arch["late_window_samples"][0]:
            raise ValueError("early window overlaps late window")
    r1 = p["architectures"]["R1-anchored-reference-tone"]
    _number(r1["tone_hertz"], 0.1, 1.0, "tone frequency")
    _number(r1["tone_amplitude_newtons"], 1e-10, 1e-8, "tone amplitude")
    r2 = p["architectures"]["R2-commutated-blind-witness"]
    pattern = r2["commutation_pattern_dwells_1_to_8"]
    if (not isinstance(pattern, list) or len(pattern) != 8
            or any(type(c) is not int or c not in (-1, 1) for c in pattern)):
        raise ValueError("commutation pattern is malformed")
    if (sum(pattern) or sum(a*b for a, b in zip(pattern, bounds.SIGMA_ORDER))
            or sum((i+1)*c for i, c in enumerate(pattern))):
        raise ValueError("commutation pattern is not balanced")
    swaps = [i+1 for i in range(1, 8) if pattern[i] != pattern[i-1]]
    if swaps != r2["swap_first_bins_of_dwells"]:
        raise ValueError("swap dwells disagree with the pattern")
    _interval(r2["witness_response"]["response_seconds_interval"], 0.1, 10, "tau_w")
    r3 = p["architectures"]["R3-label-keyed-dual-null"]
    _number(r3["command_clamp_newtons"], 1e-11, 1e-9, "clamp")
    _number(r3["in_domain_clamp_proof_maximum_newtons"], 0, 1e-9, "clamp proof")
    if r3["in_domain_clamp_proof_maximum_newtons"] >= r3["command_clamp_newtons"]:
        raise ValueError("clamp proof must sit below the clamp")
    _interval(r3["Khat_interval"], 0.01, 100, "Khat interval")
    photon = p["actuators"]["photon_primary"]
    _number(photon["k_b"], 1e-6, 0.1, "k_b")
    _interval(photon["K_c0_interval"], 0.01, 100, "K interval")
    _number(photon["L_nl"], 0, 0.2, "L_nl")
    _number(photon["h_b_newtons"], 0, 1e-12, "h_b")
    _number(photon["cross_talk_x_b"], 0, 0.1, "x_b")
    _number(photon["R_box_minimum"], 0.5, 1, "R_box")
    _number(p["actuators"]["electrostatic_row"]["k_e"], 1e-6, 0.1, "k_e")
    witness = p["witness_channel"]
    _interval(witness["signal_leak_interval"], 0, 1, "l_w")
    _interval(witness["common_coupling_interval"], 0.1, 10, "c_w")
    _interval(witness["shared_mimic_path_interval"], 0, 1, "b_w")
    _number(p["narrowed_class_row"]["transducer_fraction_z"], 0, 1, "z")
    _number(p["narrowed_class_row"]["chi"], 0, 1, "chi")
    for key, value in p["hypothesis_thresholds"].items():
        if key != "detection_scenario_H7":
            _number(value, 0, 1, key)
    guards = p["r3_bounds"]["guards"]
    for key in guards:
        _number(guards[key], 1e-6, 1, key)
    expected = {str(k-1): v-1 for k, v in bounds.PREVIOUS.items()}
    if p["r3_bounds"]["previous_same_label_position"] != expected:
        raise ValueError("previous same-label map is fixed")
    stimulus = p["out_of_window"]
    _number(stimulus["per_dwell_amplitude_newtons"], 1e-10, 1e-8, "F_x")
    if stimulus["contrast_newtons"] != 2*stimulus["per_dwell_amplitude_newtons"]:
        raise ValueError("S_x must be twice F_x")
    search = p["joint_witness_search"]
    _fixed(search["maximum_passes"], 2, "search passes")
    _fixed(search["maximum_evaluations_per_configuration"], 72, "search evaluations")
    _fixed(search["maximum_seconds_per_run"], 300, "search seconds")
    if search["start_seeds"] != ranges[2]:
        raise ValueError("search seeds must be the fixture seeds")
    gaps = p["r1_enclosures"]
    _fixed(gaps["xi_cells"], 1024, "xi cells")
    _fixed(gaps["kernel_xi_cells"], 64, "kernel cells")
    _fixed(gaps["kernel_frequency_cells"], 512, "frequency cells")
    _fixed(gaps["maximum_relative_gap"], 0.05, "gap limit")
    _fixed(gaps["dimensionless_floor"], 1e-06, "gap floor")
    budgets = p["budgets"]
    _number(budgets["actuator_optical_energy_cap_joules"], 0, 15, "energy cap")
    for table in ("force_reads", "transducers", "actuators", "commutator_swaps"):
        for value in budgets[table].values():
            _integer(value, 0, 10000, table)
    runtime = p["runtime"]
    for key, value in (("python_implementation", "CPython"),
                       ("python_version", "3.14.6"), ("machine", "arm64"),
                       ("system", "Darwin"), ("pythonhashseed", "0")):
        _fixed(runtime[key], value, key)
    if runtime["interpreter_flags"] != ["-B"]:
        raise ValueError("interpreter flags are fixed")


def validate_protocol(data):
    """Strict parse and value checks. Any failure refuses execution."""
    if not isinstance(data, (bytes, bytearray)) or len(data) > MAX_INPUT_BYTES:
        raise ValueError("protocol exceeds its byte limit")
    _prescan(data)
    protocol = json.loads(
        data.decode("utf-8"), object_pairs_hook=_unique,
        parse_constant=_reject_constant, parse_float=_finite_float,
        parse_int=_bounded_integer)
    if not isinstance(protocol, dict):
        raise ValueError("protocol is not an object")
    for value in _walk(protocol):
        if isinstance(value, float) and not math.isfinite(value):
            raise ValueError("protocol holds a non-finite number")
        if value is None:
            raise ValueError("protocol holds a null")
        if isinstance(value, str) and not unicodedata.is_normalized("NFC", value):
            raise ValueError("protocol text is not NFC")
    if _depth(protocol) > MAX_INPUT_DEPTH:
        raise ValueError("protocol nesting too deep")
    if structure_digest(protocol) != STRUCTURE_DIGEST:
        raise ValueError("protocol has unknown or missing keys")
    try:
        check_values(protocol)
    except (KeyError, TypeError, IndexError, AttributeError) as error:
        raise ValueError(f"protocol value malformed: {error!r}") from error
    return protocol


def _strings(value):
    for item in _walk(value):
        if isinstance(item, str):
            yield item


def _depth(value):
    if isinstance(value, dict):
        return 1+max(map(_depth, value.values()), default=0)
    if isinstance(value, list):
        return 1+max(map(_depth, value), default=0)
    return 0


def structure_digest(protocol):
    text = "\n".join(sorted(prior.key_paths(protocol))).encode("ascii")
    return "sha256:"+hashlib.sha256(text).hexdigest()


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


def check_runtime(protocol, identity=None):
    declared = protocol["runtime"]
    actual = identity or {
        "python_implementation": platform.python_implementation(),
        "python_version": platform.python_version(),
        "machine": platform.machine(), "system": platform.system()}
    for key, value in actual.items():
        if declared[key] != value:
            raise ValueError(f"runtime identity mismatch: {key}")
    return actual


PROTOCOL = load_protocol()
PRIMARY, REFERENCE = prior.PRIMARY, prior.REFERENCE
BASE = prior.BASE
STEP = PROTOCOL["timing"]["sample_step_seconds"]
BINS = bounds.SESSION_BINS
A1 = next(a for a in prior.ARCHITECTURES if a.name == "A1-thue-morse-8")
PHOTON = PROTOCOL["actuators"]["photon_primary"]
ELECTRO = PROTOCOL["actuators"]["electrostatic_row"]
WITNESS = PROTOCOL["witness_channel"]
NARROW = PROTOCOL["narrowed_class_row"]
ARCHS = PROTOCOL["architectures"]
B1, R1, R2, R3 = tuple(ARCHS)
R2_SPEC, R3_SPEC, R1_SPEC = ARCHS[R2], ARCHS[R3], ARCHS[R1]
TONE_OMEGA = 2*math.pi*R1_SPEC["tone_hertz"]
LATE = {B1: (91, 100), R1: (81, 100), R2: (91, 100), R3: (91, 100)}
EARLY = {B1: (41, 50), R1: (31, 50), R2: (41, 50), R3: (41, 50)}
SCENARIOS = tuple(prior.PROTOCOL["scenarios"])
GUARDS = PROTOCOL["r3_bounds"]["guards"]
EXTRA = {row["name"]: row for row in PROTOCOL["extra_rows"]}
C_LIGHT = 299792458.0


def configurations():
    rows = [(arch, scenario, "primary") for arch in ARCHS for scenario in SCENARIOS]
    rows += [(row["architecture"], row["scenario"], name)
             for name, row in EXTRA.items()]
    if len(rows) != PROTOCOL["configuration_count"]:
        raise ValueError("configuration count mismatch")
    return rows


_sweep = {}


def actuator_params(row):
    k_b = _sweep.get("k_b") or (
        ELECTRO["k_e"] if row == "R3-E" else PHOTON["k_b"])
    low, high = PHOTON["K_c0_interval"]
    return {"k_b": k_b, "L_nl": _sweep.get("L_nl") or PHOTON["L_nl"],
            "h_b": _sweep.get("h_b") or PHOTON["h_b_newtons"],
            "x_b": PHOTON["cross_talk_x_b"], "A": R3_SPEC[
                "anchor_step_amplitude_newtons"],
            "clamp": R3_SPEC["command_clamp_newtons"], "Kmin": low, "Kmax": high,
            "guard_k_plus_L": GUARDS["k_b_plus_L_nl_maximum"],
            "guard_abar": GUARDS["abar_maximum"],
            "guard_rho": GUARDS["rho_maximum"],
            "guard_cold": GUARDS["cold_remainder_maximum"]}


def tone_amplitude(row):
    return (EXTRA[row]["tone_amplitude_newtons"] if row == "R1-2nN"
            else R1_SPEC["tone_amplitude_newtons"])


def level_segment(k):
    """Segment of one-based bin k: 0 D0a, 1 D0b, i+1 lit dwell i."""
    return (k-1)//bounds.SEGMENT_BINS


def order_for(bit):
    return tuple(s*bit for s in bounds.SIGMA_ORDER)


def stream(*parts):
    text = "|".join(str(part) for part in parts).encode("ascii")
    return int.from_bytes(hashlib.sha256(text).digest()[:8], "big")


def held_x(k, offset):
    """x at the midpoint of sample k's clipped hold block, section 3.4."""
    block = prior.hold_block(k, offset)
    low = max(0.0, (offset+10*(block-1))*STEP)
    high = min(BINS*STEP, (offset+10*block)*STEP)
    return 2*((low+high)/2)/(BINS*STEP)-1


def _slow(a, b, offset):
    series = []
    for k in range(BINS):
        x = held_x(k, offset)
        series.append(a*x+b*(x*x-1/3))
    return series


def _rate(rng, s, offset):
    slew = s*prior.LEVELS["slew_fraction_of_amplitude_per_second"]
    value, block, series = rng.uniform(-s, s), 0, []
    for k in range(BINS):
        now = prior.hold_block(k, offset)
        while block < now:
            value = max(-s, min(s, value+rng.choice((-slew, 0.0, slew))))
            block += 1
        series.append(value)
    return series


def _label(sigmas, bound, seed, rng):
    if seed % 2 == 0:
        return [rng.uniform(-bound, bound) for _ in sigmas]
    sign = rng.choice((-1, 1))
    return [s*sign*bound for s in sigmas]


def wander_path(settings, s, order, seed, rng, offset):
    """Readout wander for one level, inherited classes, zero label part in D0."""
    path = [0.0]*BINS
    classes = settings["classes"]
    if "slow_drift" in classes:
        extra = _slow(rng.uniform(-s, s), rng.uniform(-s, s), offset)
        path = [x+y for x, y in zip(path, extra)]
    if "bounded_rate" in classes:
        extra = _rate(rng, s, offset)
        path = [x+y for x, y in zip(path, extra)]
    if "label_correlated" in classes:
        values = _label(order, s, seed, rng)
        for k in range(200, BINS):
            path[k] += values[k//100-2]
    if "label_within_window" in classes:
        sign = rng.choice((-1, 1))
        for k in range(200, BINS):
            path[k] += order[k//100-2]*sign*s*(-1)**prior.hold_block(k, offset)
    return path


def _walk_paths(rng, offset):
    """Within-dwell phase and feed walk, stationarity section 2.3, per hold block."""
    span = (prior.WITHIN_POINTS-1)//2
    psi_values = prior.within_lattice(BASE["phase_jitter_radians"])
    xi_values = prior.within_lattice(BASE["feed_variation_fraction"])
    m, q = rng.randint(-span, span), rng.randint(-span, span)
    block, psi, xi = 0, [], []
    for k in range(BINS):
        now = prior.hold_block(k, offset)
        while block < now:
            m = max(-span, min(span, m+rng.choice((-1, 0, 1))))
            q = max(-span, min(span, q+rng.choice((-1, 0, 1))))
            block += 1
        psi.append(psi_values[m+span])
        xi.append(xi_values[q+span])
    return psi, xi


def draw(config, seed, control, orientation, cohort):
    """Every generator draw. Paired across architectures and controls."""
    arch, scenario, row = config
    settings = prior.scenario_settings(scenario)

    def rng(purpose, *extra):
        return random.Random(stream(
            "pf002-reference-gain-v1", cohort, scenario, seed, orientation,
            purpose, *extra))

    bit = rng("order", arch).choice((-1, 1))
    order = order_for(bit)
    constants = rng("constants")
    dg, dw, dl = (BASE["calibration_knowledge"], BASE["weight_knowledge"],
                  BASE["leakage_knowledge"])
    draws = {
        "config": config, "settings": settings, "order": order, "seed": seed,
        "control": control, "orientation": orientation, "cohort": cohort,
        "box_gp": PRIMARY.calibration_fraction+constants.uniform(-dg, dg),
        "box_gr": REFERENCE.calibration_fraction+constants.uniform(-dg, dg),
        "box_gw": constants.uniform(-dg, dg),
        "w": prior.WEIGHT+constants.uniform(-dw, dw),
        "leak": max(0.0, prior.LEAK+constants.uniform(-dl, dl)),
        "vibration": constants.uniform(*prior.BAND),
        "tau_w": constants.uniform(*R2_SPEC["witness_response"][
            "response_seconds_interval"]),
        "c_w": constants.uniform(*WITNESS["common_coupling_interval"]),
        "l_w": constants.uniform(*WITNESS["signal_leak_interval"]),
        "b_w": constants.uniform(*WITNESS["shared_mimic_path_interval"]),
    }
    nuisance = rng("nuisance")
    offset = (prior.adversarial_offset(A1) if "label_within_window"
              in settings["classes"] else nuisance.randrange(10))
    draws["offset"] = offset
    s_p, s_r = settings["s_p"], settings["s_r"]
    e_p = wander_path(settings, s_p, order, seed, nuisance, offset)
    e_r = wander_path(settings, s_r, order, seed, nuisance, offset)
    e_w = wander_path(settings, s_r, order, seed, nuisance, offset)
    chain = [[0.0]*BINS, [0.0]*BINS]
    if row == "R2-N":
        z, chi = NARROW["transducer_fraction_z"], NARROW["chi"]
        e_p = wander_path(settings, z*s_p, order, seed, nuisance, offset)
        e_r = wander_path(settings, z*s_r, order, seed, nuisance, offset)
        for index, s in enumerate((s_p, s_r)):
            lock = nuisance.uniform(-s, s)
            rest = [nuisance.uniform(-chi*s, chi*s) for _ in order]
            for k in range(200, BINS):
                i = k//100-2
                chain[index][k] = order[i]*lock+rest[i]
    elif arch == R2 and seed % 2:
        # Chain form of the full class: wander follows the chain, not transducer.
        chain = [e_p, e_r]
        e_p, e_r = [0.0]*BINS, [0.0]*BINS
    draws.update(e_p=e_p, e_r=e_r, e_w=e_w, chain=chain)
    draws["blind"] = _label(order, settings["blind"], seed, nuisance)
    draws["common"] = _label(order, settings["common"], seed, nuisance)
    act = rng("actuator")
    k_b = actuator_params(row)["k_b"]
    low, high = PHOTON["K_c0_interval"]
    draws["K_p"], draws["K_r"] = act.uniform(low, high), act.uniform(low, high)
    draws["k_p"] = _label(order, k_b, seed, act)
    draws["k_r"] = _label(order, k_b, seed, act)
    draws["h_p"] = _label(order, PHOTON["h_b_newtons"], seed, act)
    draws["h_r"] = _label(order, PHOTON["h_b_newtons"], seed, act)
    draws["h_a"], draws["h_0"] = (
        [act.uniform(-PHOTON["h_b_newtons"], PHOTON["h_b_newtons"])
         for _ in (0, 1)])
    x_b = PHOTON["cross_talk_x_b"]
    draws["x_p"], draws["x_r"] = act.uniform(-x_b, x_b), act.uniform(-x_b, x_b)
    draws["phi_kind"] = act.choice(("linear", "sine"))
    draws["phi_sign"] = act.choice((-1, 1))
    draws["tau"] = _label(order, PHOTON["timing_label_bound_seconds"], seed, act)
    draws["reflectance"] = act.uniform(PHOTON["R_box_minimum"], 1.0)
    estimator = rng("estimator")
    knowledge = prior.PILOT["response_time_estimator_knowledge_fraction"]
    draws["xi_r"] = estimator.uniform(-knowledge, knowledge)
    draws["xi_p"] = estimator.uniform(-knowledge, knowledge)
    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 sigma in order:
        base = 0.0 if control == "phase-null" else sigma*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["spoof_sign"] = optical.choice((-1, 1))
    draws["psi"], draws["xi"] = _walk_paths(rng("phase_feed"), offset)
    draws["noise_seed"] = rng("noise").randrange(2**32)
    return draws


def phi(u, draws):
    """Static Lipschitz map of section 3.2. L_nl is the declared bound."""
    L = PHOTON["L_nl"]
    A = R3_SPEC["anchor_step_amplitude_newtons"]
    if draws["phi_kind"] == "linear":
        return draws["phi_sign"]*L*u
    return draws["phi_sign"]*L*A*math.sin(u/A)


class Controller:
    """Public side of R1, R2, R3. It receives readings, labels and indices only."""

    def __init__(self, arch, order, amplitude, weight, tau_hat):
        self.arch, self.order, self.amplitude = arch, order, amplitude
        self.w, self.tau_hat = weight, tau_hat
        self.segments = {}
        self.u = {"p": {}, "r": {}}
        self.khat = {}
        self.saturated = False

    def _window_mean(self, c, segment, window=(91, 100)):
        values = self.segments[segment][c]
        return math.fsum(values[window[0]-1:window[1]])/(window[1]-window[0]+1)

    def _clamp(self, value):
        clamp = R3_SPEC["command_clamp_newtons"]
        if abs(value) > clamp:
            self.saturated = True
            return math.copysign(clamp, value)
        return value

    def command(self, c, segment):
        """Dwell-held R3 command, from earlier segments only."""
        A = R3_SPEC["anchor_step_amplitude_newtons"]
        if segment == 0:
            return A
        if segment == 1:
            return 0.0
        if c not in self.khat:
            khat = (self._window_mean(c, 1)-self._window_mean(c, 0))/A
            low, high = R3_SPEC["Khat_interval"]
            if not math.isfinite(khat) or not low <= khat <= high:
                raise OperationalFailure("Khat outside its interval")
            self.khat[c] = khat
        previous = None
        if segment in bounds.FIRST_OF_LABEL:
            value = self._window_mean(c, 1)/self.khat[c]
        else:
            previous = bounds.PREVIOUS[segment]
            value = (self.u[c][previous]
                     + self._window_mean(c, previous)/self.khat[c])
        self.u[c][segment] = self._clamp(value)
        return self.u[c][segment]

    def record(self, segment, readings):
        self.segments[segment] = readings


def _forces_for(draws, tables):
    """Non-actuator force, heat and impostor quantities per bin. Generator side."""
    control, orientation = draws["control"], draws["orientation"]
    C, c0 = prior.COMMON, prior.COUPLING
    impostor = prior.nominal_contrast()/2
    locks = [prior.phase_lock(p) for p in draws["phases"]]
    lag = None
    if control == "impostor-source-fixed-lag-10s":
        lag = 10.0
    elif control == "impostor-source-fixed-lag-0p1s":
        lag = 0.1
    scale = _lag_scale(locks, lag) if lag else 1.0
    weight = -math.expm1(-STEP/lag) if lag else 0.0
    lag_state = 0.0
    s, m, common, coupling, heat = [], [], [], [], []
    for k in range(BINS):
        if k < 200:
            s.append(0.0)
            m.append(0.0)
            common.append(C)
            coupling.append(c0)
            heat.append(0.0)
            continue
        i = k//100-2
        phase = draws["phases"][i]+draws["psi"][k]
        feed = draws["feeds"][i]*(1+draws["xi"][k])
        if control in ("opposite-phase", "phase-null"):
            force = orientation*prior.recoil(phase, feed)
        elif control == "impostor-lab-fixed-in-window":
            force = locks[i]*impostor
        elif control == "impostor-source-fixed-instant":
            force = orientation*locks[i]*impostor
        elif lag:
            lag_state += weight*(orientation*locks[i]*impostor-lag_state)
            force = scale*lag_state
        elif control == "impostor-out-of-window":
            force = locks[i]*PROTOCOL["out_of_window"]["per_dwell_amplitude_newtons"]
        else:
            force = 0.0
        s.append(force)
        factor = 1+draws["common"][i]
        common.append(C*factor)
        coupling.append(c0*(1+draws["blind"][i]))
        mimic = 0.0
        if control == "reference-path-label-mimic":
            mimic = -orientation*locks[i]*impostor/draws["w"]*factor
        m.append(mimic)
        heat.append(prior.source_heat(phase, feed))
    return {"s": s, "m": m, "common": common, "coupling": coupling, "heat": heat}


LAG_CLASSES = {"lag10": 10.0, "lag01": 0.1}
SPOOF_CLASSES = {"spoof+": 1, "spoof-": -1}


def _lag_waveform(sigma, lag):
    """Finite waveform of a lagged impostor, for one order, at nominal size."""
    scale = _lag_scale(list(sigma), lag)
    weight = -math.expm1(-STEP/lag)
    nominal = prior.nominal_contrast()/2
    state, out = 0.0, []
    for k in range(BINS):
        if k >= 200:
            state += weight*(sigma[k//100-2]*nominal-state)
        out.append(scale*state)
    return out


def _lag_scale(locks, lag):
    sequence = [0.0]*200+[locks[k//100-2] for k in range(200, BINS)]
    a = math.exp(-STEP/PRIMARY.response_seconds)
    target, lagged, weight, state = [], [], -math.expm1(-STEP/lag), 0.0
    for value in sequence:
        state += weight*(value-state)
        lagged.append(state)

    def contrast(force):
        x, total = 0.0, 0.0
        for k, value in enumerate(force):
            x = a*x+(1-a)*value
            if k >= 200 and (k % 100) >= 90:
                total += locks[k//100-2]*x
        return total
    return contrast(sequence)/contrast(lagged)


def tone_value(k, draws, amplitude):
    i = k//100-2
    tau = draws["tau"][i] if k >= 200 else 0.0
    return amplitude*math.sin(TONE_OMEGA*((k+1)*STEP+tau))


def spoof_force(k, draws):
    if draws["control"] != "tone-spoof-reference":
        return 0.0
    amplitude = actuator_params(draws["config"][2])["k_b"]*R1_SPEC[
        "tone_amplitude_newtons"]
    tone = math.sin(TONE_OMEGA*(k+1)*STEP)
    if 100 <= k < 200:
        return draws["spoof_sign"]*amplitude*(1+tone)
    if k >= 200 and draws["order"][k//100-2] > 0:
        return draws["spoof_sign"]*amplitude*tone
    return 0.0


def anchor_gains(draws):
    """g_c of section 3.3: box gain times the anchor-window mean of wander."""
    result = {}
    for name, path, box in (("p", draws["e_p"], draws["box_gp"]),
                            ("r", draws["e_r"], draws["box_gr"])):
        extra = draws["chain"][0 if name == "p" else 1]
        bar = math.fsum(path[k]+extra[k] for k in range(190, 200))/10
        result[name] = {"box": box, "bar": bar, "g": (1+box)*(1+bar)-1}
    return result


def simulate(draws, *, noise_path=None, controller=None):
    """Bin-by-bin forward model of section 3. Only readings leave to estimators."""
    arch, _, row = draws["config"]
    params = actuator_params(row)
    amplitude = tone_amplitude(row)
    order = draws["order"]
    tau_hat = REFERENCE.response_seconds*(1+draws["xi_r"])
    control = controller or Controller(arch, order, amplitude, draws["w"], tau_hat)
    inputs = _forces_for(draws, None)
    a_p, a_r = (math.exp(-STEP/PRIMARY.response_seconds),
                math.exp(-STEP/REFERENCE.response_seconds))
    a_w = math.exp(-STEP/draws["tau_w"])
    w_tp = -math.expm1(-STEP/PRIMARY.thermal_seconds)
    w_tr = -math.expm1(-STEP/REFERENCE.thermal_seconds)
    x_p = x_r = x_w = th_p = th_r = th_w = 0.0
    rng = random.Random(draws["noise_seed"])
    pattern = R2_SPEC["commutation_pattern_dwells_1_to_8"]
    tcomm = math.exp(-STEP/R2_SPEC["swap_transient_seconds"])
    step_gain = PROTOCOL["anchor_step"]["s_r_fraction"]
    is_step = draws["control"] == "anchor-step-gain"
    y = {"p": [], "r": [], "w": []}
    states = {"p": [], "r": [], "w": []}
    for segment in range(10):
        first, last = bounds.segment_bins(segment)
        u_p = u_r = 0.0
        if arch == R3:
            u_p = control.command("p", segment)
            u_r = control.command("r", segment)
        power = {c: actuator_power(arch, c, segment, row) for c in "pr"}
        i = segment-2
        k_p = draws["k_p"][i] if i >= 0 else 0.0
        k_r = draws["k_r"][i] if i >= 0 else 0.0
        anchor_h = draws["h_a"] if segment == 0 else draws["h_0"]
        h_p = draws["h_p"][i] if i >= 0 else anchor_h
        h_r = draws["h_r"][i] if i >= 0 else anchor_h
        scale = 1-draws["reflectance"]
        readings = {"p": [], "r": [], "w": []}
        for index in range(first-1, last):
            k = index
            time = (k+1)*STEP
            if arch == R1:
                u_r = tone_value(k, draws, amplitude)
            v_p, v_r = draws["K_p"]*u_p, draws["K_r"]*u_r
            full_p = (1+k_p)*(v_p+draws["K_p"]*phi(u_p, draws))
            full_r = (1+k_r)*(v_r+draws["K_r"]*phi(u_r, draws))
            if arch == R3:
                act_p = full_p+h_p+draws["x_p"]*full_r
                act_r = full_r+h_r+draws["x_r"]*full_p
            elif arch == R1:
                act_p = draws["x_p"]*full_r
                act_r = full_r+h_r
            else:
                act_p = act_r = 0.0
            s, common = inputs["s"][k], inputs["common"][k]
            f_p = s+common-act_p
            f_r = (draws["leak"]*s+inputs["coupling"][k]*common+inputs["m"][k]
                   + spoof_force(k, draws)-act_r)
            f_w = (draws["l_w"]*s+draws["c_w"]*common
                   + draws["b_w"]*inputs["m"][k])
            q = inputs["heat"][k]
            th_p += w_tp*((q+scale*power["p"])*PRIMARY.thermal_newtons_per_watt-th_p)
            th_r += w_tr*((q+scale*power["r"])*REFERENCE.thermal_newtons_per_watt-th_r)
            th_w += w_tr*(q*REFERENCE.thermal_newtons_per_watt-th_w)
            x_p = a_p*x_p+(1-a_p)*(f_p+th_p)
            x_r = a_r*x_r+(1-a_r)*(f_r+th_r)
            x_w = a_w*x_w+(1-a_w)*(f_w+th_w)
            chain_p, chain_r = 0, 1
            old_p, old_r = 0, 1
            if arch == R2 and i >= 0 and pattern[i] < 0:
                chain_p, chain_r = 1, 0
            if arch == R2 and i >= 1 and pattern[i-1] < 0:
                old_p, old_r = 1, 0
            e_p = draws["e_p"][k]+draws["chain"][chain_p][k]
            e_r = draws["e_r"][k]+draws["chain"][chain_r][k]
            if is_step and k >= 200:
                e_r = (1+e_r)*(1+step_gain)-1
            gain_p = (1+draws["box_gp"])*(1+e_p)
            gain_r = (1+draws["box_gr"])*(1+e_r)
            sample_p, sample_r = gain_p*x_p, gain_r*x_r
            if arch == R2 and k+1 == first and i >= 1 and pattern[i] != pattern[i-1]:
                sample_p += tcomm*x_p*(1+draws["box_gp"])*(
                    draws["chain"][old_p][k]-draws["chain"][chain_p][k])
                sample_r += tcomm*x_r*(1+draws["box_gr"])*(
                    draws["chain"][old_r][k]-draws["chain"][chain_r][k])
            noise = noise_path(k) if noise_path else (
                rng.uniform(-PRIMARY.noise_bound_newtons, PRIMARY.noise_bound_newtons),
                rng.uniform(-REFERENCE.noise_bound_newtons, REFERENCE.noise_bound_newtons),
                rng.uniform(-REFERENCE.noise_bound_newtons, REFERENCE.noise_bound_newtons))
            y_p = (sample_p+PRIMARY.offset_newtons
                   + PRIMARY.drift_newtons_per_second*time
                   + PRIMARY.vibration_newtons*math.sin(
                       2*math.pi*draws["vibration"]*time)+noise[0])
            y_r = (sample_r+REFERENCE.offset_newtons
                   + REFERENCE.drift_newtons_per_second*time
                   + REFERENCE.vibration_newtons*math.sin(
                       2*math.pi*draws["vibration"]*time)+noise[1])
            y_w = ((1+draws["box_gw"])*(1+draws["e_w"][k])*x_w
                   + REFERENCE.offset_newtons
                   + REFERENCE.drift_newtons_per_second*time
                   + REFERENCE.vibration_newtons*math.sin(
                       2*math.pi*draws["vibration"]*time)+noise[2])
            for value in (y_p, y_r, y_w):
                if not math.isfinite(value):
                    raise OperationalFailure("non-finite reading")
                if abs(value) > prior.FAILS["reading_saturation_newtons"]:
                    raise OperationalFailure("reading saturated")
            readings["p"].append(y_p)
            readings["r"].append(y_r)
            readings["w"].append(y_w)
            states["p"].append(x_p)
            states["r"].append(x_r)
            states["w"].append(x_w)
        control.record(segment, readings)
        for name in y:
            y[name].extend(readings[name])
    return {"y": y, "states": states, "inputs": inputs, "controller": control}


def window_mean(values, segment, window):
    first = segment*100
    return math.fsum(values[first+window[0]-1:first+window[1]])/(window[1]-window[0]+1)


def tone_weights(tau_hat):
    times = [(k+1)*STEP for k in range(180, 200)]
    return prior_bounds.point_weights(tau_hat, times, TONE_OMEGA)


def estimate(arch, order, y, controller, window, *, weight, tau_hat=None,
             row="primary", ratios=None):
    """Public estimate over a window. It sees readings and public values only."""
    n = len(order)
    if arch == R1:
        u = tone_weights(tau_hat)
        amplitude = tone_amplitude(row)
        def project(segment):
            first = segment*100
            values = y["r"][first+80:first+100]
            return -math.fsum(a*b for a, b in zip(u, values))
        low, high = R1_SPEC["projection_ceiling_floor_fraction"]

        def guarded(value):
            if not math.isfinite(value) or not (
                    low*amplitude <= value <= high*amplitude):
                raise OperationalFailure("projection outside its interval")
            return value
        total = 0.0
        if ratios is None:
            y0 = amplitude if row == "R1-abs" else guarded(project(1))
            ratios = []
            for i in range(n):
                ratio = guarded(project(i+2))/y0
                lo, hi = R1_SPEC["gain_ratio_interval"]
                if not math.isfinite(ratio) or not lo <= ratio <= hi:
                    raise OperationalFailure("gain ratio outside its interval")
                ratios.append(ratio)
        for i, sigma in enumerate(order):
            segment = i+2
            ratio = ratios[i]
            total += sigma*(window_mean(y["p"], segment, window)
                            - weight*window_mean(y["r"], segment, window)/ratio)
        return {"contrast": 2/n*total, "ratios": ratios}
    if arch == R3:
        total = 0.0
        for i, sigma in enumerate(order):
            segment = i+2
            f_p = (controller.khat["p"]*controller.u["p"][segment]
                   + window_mean(y["p"], segment, window))
            f_r = (controller.khat["r"]*controller.u["r"][segment]
                   + window_mean(y["r"], segment, window))
            total += sigma*(f_p-weight*f_r)
        return {"contrast": 2/n*total}
    total = 0.0
    for i, sigma in enumerate(order):
        segment = i+2
        total += sigma*(window_mean(y["p"], segment, window)
                        - weight*window_mean(y["r"], segment, window))
    result = {"contrast": 2/n*total}
    if arch == R2:
        c_r = 2/n*math.fsum(sigma*window_mean(y["r"], i+2, window)
                            for i, sigma in enumerate(order))
        c_w = 2/n*math.fsum(sigma*window_mean(y["w"], i+2, window)
                            for i, sigma in enumerate(order))
        base = window_mean(y["w"], 1, (91, 100))
        if base < R2_SPEC["witness_denominator_minimum_fraction_of_c_w_min_C"]*(
                WITNESS["common_coupling_interval"][0]*prior.COMMON):
            raise OperationalFailure("witness denominator")
        kappa = window_mean(y["r"], 1, (91, 100))/base
        low, high = R2_SPEC["kappa_interval"]
        if not low <= kappa <= high:
            raise OperationalFailure("kappa outside its interval")
        result.update(C_RO=c_r-kappa*c_w, kappa=kappa)
    return result


def _filtered(sequence, a):
    state, out = 0.0, []
    for value in sequence:
        state = a*state+(1-a)*value
        out.append(state)
    return out


def _thermal(heat, balance):
    weight = -math.expm1(-STEP/balance.thermal_seconds)
    state, out = 0.0, []
    for q in heat:
        state += weight*(q*balance.thermal_newtons_per_watt-state)
        out.append(state)
    return out


_window_cache = {}


def optical():
    if "window" not in _window_cache:
        _window_cache["window"] = prior.optical_window(A1.additive)
    return _window_cache["window"]


PHASE_NULL_CLASSES = ("phase_null", "phase_null_quiet")
_phase_null_cache = {}


def phase_null_ranges():
    """Heat and recoil on the phase-null lattice with its walk, section 7.1a."""
    if not _phase_null_cache:
        jitter = BASE["phase_jitter_radians"]
        variation = BASE["feed_variation_fraction"]
        heats, recoils = [], []
        for phase in prior.lattice(0.0, jitter, prior.PHASE_POINTS):
            for feed in prior.lattice(1.0, variation, prior.FEED_POINTS):
                for psi in prior.within_lattice(jitter):
                    for xi in prior.within_lattice(variation):
                        heats.append(prior.source_heat(phase+psi, feed*(1+xi)))
                        recoils.append(abs(prior.recoil(phase+psi, feed*(1+xi))))
        _phase_null_cache.update(heat_minimum=min(heats), heat_maximum=max(heats),
                                 recoil_maximum=max(recoils))
    return _phase_null_cache


def quiet_class(klass):
    """The nuisance-only partner of a class. Truth never enters E_T."""
    if klass in SPOOF_CLASSES:
        return klass
    return "phase_null_quiet" if klass == "phase_null" else "none"


def actuator_power(arch, channel, segment, row):
    """Nominal optical power of section 5.1, from the specular force equation."""
    if arch == R3:
        force = (R3_SPEC["anchor_step_amplitude_newtons"] if segment == 0
                 else R3_SPEC["command_clamp_newtons"])
        return force*C_LIGHT/2
    if arch == R1 and channel == "r":
        return tone_amplitude(row)*C_LIGHT/2
    return 0.0


def class_envelope(arch, settings, klass, sigma, row):
    """Per-bin centre and radii of D, for one order, one row class."""
    window = optical()
    f = settings["common"]
    C = prior.COMMON
    c = prior.COUPLING
    b = settings["blind"]
    dL = BASE["leakage_knowledge"]
    L_mid, L_max = prior.LEAK, prior.LEAK+dL
    w_lo = prior.WEIGHT-BASE["weight_knowledge"]
    w_hi = prior.WEIGHT+BASE["weight_knowledge"]
    I_mid, dI = (1/w_lo+1/w_hi)/2, (1/w_lo-1/w_hi)/2
    s_mean = (window["signal_maximum_newtons"]+window["signal_minimum_newtons"])/4
    s_rad = (window["signal_maximum_newtons"]-window["signal_minimum_newtons"])/4
    nominal = prior.nominal_contrast()/2
    q_mid = (window["heat_maximum_watts"]+window["heat_minimum_watts"])/2
    q_rad = (window["heat_maximum_watts"]-window["heat_minimum_watts"])/2
    if klass in PHASE_NULL_CLASSES:
        ranges = phase_null_ranges()
        q_mid = (ranges["heat_maximum"]+ranges["heat_minimum"])/2
        q_rad = (ranges["heat_maximum"]-ranges["heat_minimum"])/2
    centre = {"p": [], "r": []}
    indep = {"p": [], "r": []}
    common = {"p": [], "r": []}
    heat, heat_rad = [], []
    k_s = actuator_params(row)["k_b"]*R1_SPEC["tone_amplitude_newtons"]
    lagged = _lag_waveform(sigma, LAG_CLASSES[klass]) if klass in LAG_CLASSES else None
    for k in range(BINS):
        dark = k < 200
        s_i = 0 if dark else sigma[k//100-2]
        pc, rc, pi, ri = C, c*C, 0.0, 0.0
        if not dark:
            if klass == "held":
                pc += s_i*s_mean
                rc += L_mid*s_i*s_mean
                pi += s_rad
                ri += dL*abs(s_mean)+L_max*s_rad
            elif klass == "mimic":
                rc += s_i*I_mid*nominal
                ri += dI*nominal+f*nominal/w_lo
            elif klass in LAG_CLASSES:
                pc += lagged[k]
                rc += L_mid*lagged[k]
                ri += dL*abs(lagged[k])
            elif klass == "large":
                amp = PROTOCOL["out_of_window"]["per_dwell_amplitude_newtons"]
                pc += s_i*amp
                rc += L_mid*s_i*amp
                ri += dL*amp
            elif klass == "phase_null":
                pi += phase_null_ranges()["recoil_maximum"]
                ri += L_max*phase_null_ranges()["recoil_maximum"]
            ri += b*c*C*(1+f)
        if klass in SPOOF_CLASSES:
            tone = math.sin(TONE_OMEGA*(k+1)*STEP)
            if 100 <= k < 200:
                rc += SPOOF_CLASSES[klass]*k_s*(1+tone)
            elif not dark and s_i > 0:
                rc += SPOOF_CLASSES[klass]*k_s*tone
        centre["p"].append(pc)
        centre["r"].append(rc)
        indep["p"].append(pi)
        indep["r"].append(ri)
        common["p"].append(0.0 if dark else f*C)
        common["r"].append(0.0 if dark else f*c*C)
        heat.append(0.0 if dark else q_mid)
        heat_rad.append(0.0 if dark else q_rad)
    out = {}
    for name, balance in (("p", PRIMARY), ("r", REFERENCE)):
        a = math.exp(-STEP/balance.response_seconds)
        # E_Q: absorbed actuator power, section 8.4, as centre and radius.
        absorbed = [(1-PHOTON["R_box_minimum"])/2*actuator_power(arch, name, k//100, row)
                    for k in range(BINS)]
        th = _thermal([q+x for q, x in zip(heat, absorbed)], balance)
        th_rad = _thermal([q+x for q, x in zip(heat_rad, absorbed)], balance)
        out[name] = {
            "centre": _filtered([u+v for u, v in zip(centre[name], th)], a),
            "indep": _filtered(indep[name], a),
            "heat": _filtered(th_rad, a),
            "common": _filtered(common[name], a), "a": a}
    return out


def _segment_stats(env, window):
    """Dbar, DD and window sets for one channel envelope."""
    bins = {i: [k-1 for k in bounds.window_bins(i, window)] for i in range(10)}
    Dbar, spans = {}, {}
    for i, indices in bins.items():
        radius = [env["indep"][k]+env["common"][k]+env["heat"][k] for k in indices]
        low = [env["centre"][k]-r for k, r in zip(indices, radius)]
        high = [env["centre"][k]+r for k, r in zip(indices, radius)]
        spans[i] = (min(low), max(high))
        Dbar[i] = max(abs(spans[i][0]), abs(spans[i][1]))
    DD = {}
    for i in range(10):
        for j in range(i):
            DD[i, j] = max(abs(spans[i][1]-spans[j][0]),
                           abs(spans[j][1]-spans[i][0]))
    return Dbar, DD, spans


def _gain_bounds():
    dg = BASE["calibration_knowledge"]
    return {"p": (PRIMARY.calibration_fraction-dg, PRIMARY.calibration_fraction+dg),
            "r": (REFERENCE.calibration_fraction-dg, REFERENCE.calibration_fraction+dg)}


def amplitudes(settings, *, anchored):
    factor = prior.amplitude_factor(settings)
    result = {}
    for name, s in (("p", settings["s_p"]), ("r", settings["s_r"])):
        shat = factor*s
        if anchored and settings["classes"] & {"slow_drift", "bounded_rate"} and shat:
            if shat >= 1:
                raise bounds.Unproved("gain amplitude")
            shat = (1+shat)/(1-shat)-1
        result[name] = shat
    return result


def transient_contrast(env_centre, sigma, window):
    n = len(sigma)
    return 2/n*math.fsum(
        sigma[i]*window_mean(env_centre, i+2, window) for i in range(n))


def floor_terms(arch, window, scale=1.0):
    count = window[1]-window[0]+1
    kernel = prior_bounds.mean_kernel(min(count, 10), prior.BAND[0], STEP)
    W = prior.WEIGHT+BASE["weight_knowledge"]
    noise = 2*(PRIMARY.noise_bound_newtons+W*scale*REFERENCE.noise_bound_newtons)
    vib = 2*(PRIMARY.vibration_newtons+W*scale*REFERENCE.vibration_newtons)*kernel
    return noise, vib


def nuisance_contrast(env, sigma, window, klass):
    """E_T: contrast of D at fixed gains, excluding truth, over the weight box."""
    gains = _gain_bounds()
    W = prior.WEIGHT+BASE["weight_knowledge"]
    wlow = prior.WEIGHT-BASE["weight_knowledge"]
    n = len(sigma)
    worst = 0.0
    p = [window_mean(env["p"]["centre"], i+2, window) for i in range(n)]
    r = [window_mean(env["r"]["centre"], i+2, window) for i in range(n)]
    pc = [window_mean(env["p"]["common"], i+2, window) for i in range(n)]
    rc = [window_mean(env["r"]["common"], i+2, window) for i in range(n)]
    pi = [window_mean(env["p"]["indep"], i+2, window) for i in range(n)]
    ri = [window_mean(env["r"]["indep"], i+2, window) for i in range(n)]
    for gp in gains["p"]:
        for gr in gains["r"]:
            for w in (wlow, W):
                centre = 2/n*math.fsum(
                    s*((1+gp)*a-w*(1+gr)*b) for s, a, b in zip(sigma, p, r))
                spread = 2/n*math.fsum(
                    abs((1+gp)*a-w*(1+gr)*b) for a, b in zip(pc, rc))
                worst = max(worst, abs(centre)+spread)
    spread = 2/n*math.fsum((1+gains["p"][1])*a+W*(1+gains["r"][1])*b
                           for a, b in zip(pi, ri))
    return worst+spread+_heat_spread(sigma, window, gains, W)


_heat_cache = {}


def _heat_spread(sigma, window, gains, W):
    """Sum of |contrast response| to dwell-held heat, times its half range."""
    key = (sigma, window)
    if key not in _heat_cache:
        data = optical()
        half = (data["heat_maximum_watts"]-data["heat_minimum_watts"])/2
        total = 0.0
        for balance, gain, weight in ((PRIMARY, gains["p"][1], 1.0),
                                      (REFERENCE, gains["r"][1], W)):
            a = math.exp(-STEP/balance.response_seconds)
            for dwell in range(len(sigma)):
                unit = [1.0 if k//100-2 == dwell else 0.0 for k in range(BINS)]
                state = _filtered(_thermal(unit, balance), a)
                total += weight*(1+gain)*abs(transient_contrast(state, sigma, window))
        _heat_cache[key] = half*total
    return _heat_cache[key]


def settling_rho(sigma, window):
    worst = 0.0
    for balance in (PRIMARY, REFERENCE):
        a = math.exp(-STEP/balance.response_seconds)
        drive = [0.0]*200+[sigma[k//100-2] for k in range(200, BINS)]
        worst = max(worst, abs(1-transient_contrast(_filtered(drive, a), sigma,
                                                    window)/2))
    return worst


def slow_coefficient(centre, sigma, window, offset):
    """|L1| + |L2| of section 8.1, at the generator's own held values."""
    n, count = len(sigma), window[1]-window[0]+1
    l1, l2 = [], []
    for i in range(n):
        first = (i+2)*100
        for q in range(window[0], window[1]+1):
            k = first+q-1
            x = held_x(k, offset)
            value = sigma[i]*2/n/count*centre[k]
            l1.append(value*x)
            l2.append(value*(x*x-1/3))
    return abs(math.fsum(l1))+abs(math.fsum(l2))


def slow_term(settings, env, sigma, window, s_p, s_r, gains, W):
    """E_drift: one shared offset, maximised over the sum of both channels."""
    if "slow_drift" not in settings["classes"]:
        return 0.0
    return max((1+gains["p"][1])*s_p*slow_coefficient(
        env["p"]["centre"], sigma, window, offset)
        + W*(1+gains["r"][1])*s_r*slow_coefficient(
            env["r"]["centre"], sigma, window, offset)
        for offset in range(10))


def sequence_gain(settings, c, env, sigma, window, s, W):
    """Rate and label gain on the state. The slow class has slow_term."""
    classes = settings["classes"]
    centre = env["centre"]
    n = len(sigma)
    total = 0.0
    if not s:
        return 0.0
    count = window[1]-window[0]+1
    sample = []
    for i in range(n):
        first = (i+2)*100
        for q in range(window[0], window[1]+1):
            k = first+q-1
            sample.append((k, sigma[i]*2/n/count*centre[k]))
    if "bounded_rate" in classes:
        slew = s*prior.LEVELS["slew_fraction_of_amplitude_per_second"]
        best = 0.0
        for offset in range(10):
            blocks = {}
            for k, value in sample:
                block = prior.hold_block(k, offset)
                blocks[block] = blocks.get(block, 0.0)+value
            low = min(blocks)
            coefficients = [blocks.get(b, 0.0) for b in range(low, max(blocks)+1)]
            best = max(best, bounds.rate_bound(coefficients, s, slew),
                       bounds.rate_bound([-v for v in coefficients], s, slew))
        total += best
    if classes & {"label_correlated", "label_within_window"}:
        total += s*math.fsum(abs(v) for _, v in sample)
    radius = 2/n*math.fsum(
        window_mean(env["indep"], i+2, window)+window_mean(env["common"], i+2, window)
        + window_mean(env["heat"], i+2, window) for i in range(n))
    return total+prior.amplitude_factor(settings)*s*radius


def plain_class_term(settings, klass, window, form):
    """Stationarity section 6.1 and 6.8 class terms, added to E_N unchanged."""
    gains = _gain_bounds()
    W = prior.WEIGHT+BASE["weight_knowledge"]
    L_max = prior.LEAK+BASE["leakage_knowledge"]
    factor = prior.amplitude_factor(settings)
    s_p, s_r = settings["s_p"], settings["s_r"]
    if form == "chain":
        s_p = s_r = (s_p+s_r)/2
    shat_p, shat_r = factor*s_p, factor*s_r
    if klass == "held":
        return (shat_p+W*shat_r*L_max)*optical()["signal_maximum_newtons"]
    if klass == "mimic":
        return (1+settings["common"])*prior.nominal_contrast()*shat_r
    if klass in LAG_CLASSES:
        best = 0.0
        G_r = 1+gains["r"][1]
        for bit in (1, -1):
            sigma = order_for(bit)
            wave = _lag_waveform(sigma, LAG_CLASSES[klass])
            u_p = _filtered(wave, math.exp(-STEP/PRIMARY.response_seconds))
            u_r = _filtered(wave, math.exp(-STEP/REFERENCE.response_seconds))
            D = transient_contrast(u_r, sigma, window)-transient_contrast(
                u_p, sigma, window)
            n = len(sigma)
            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))
            best = max(best, W*L_max*G_r*abs(D)+shat_p*U(u_p)
                       + W*L_max*shat_r*U(u_r))
        return best
    return 0.0


def bound_plain(arch, settings, klass, row, window, form="transducer"):
    """B1 and R2: section 8.1, on one row class, worst of both orders."""
    gains = _gain_bounds()
    W = prior.WEIGHT+BASE["weight_knowledge"]
    best = 0.0
    for bit in (1, -1):
        sigma = order_for(bit)
        base = klass if klass in SPOOF_CLASSES or klass in (
            "step", "phase_null") else "none"
        env = class_envelope(arch, settings, base, sigma, row)
        s_p, s_r = settings["s_p"], settings["s_r"]
        if form == "chain":
            s_p = s_r = (s_p+s_r)/2
        extra = 0.0
        if klass == "step":
            # A constant reference gain step cancels on a level, not on a contrast.
            extra = W*(1+gains["r"][1])*PROTOCOL["anchor_step"]["s_r_fraction"]*(
                abs(transient_contrast(env["r"]["centre"], sigma, window)))
        terms = ((1+gains["p"][1])*sequence_gain(settings, "p", env["p"], sigma,
                                                 window, s_p, W)
                 + W*(1+gains["r"][1])*sequence_gain(settings, "r", env["r"], sigma,
                                                     window, s_r, W))
        quiet = class_envelope(arch, settings, quiet_class(klass), sigma, row)
        terms += slow_term(settings, env, sigma, window, s_p, s_r, gains, W)
        total = terms+extra+nuisance_contrast(quiet, sigma, window, klass)
        best = max(best, total)
    noise, vib = floor_terms(arch, window)
    return best+noise+vib+plain_class_term(settings, klass, window, form)


def _windows(window):
    return {i: bounds.window_bins(i, window) for i in range(10)}


def _r3_early(env, sigma, window):
    """Early tables and each dwell's early against late force span."""
    early = {}
    for name in ("p", "r"):
        _, _, spans = _segment_stats(env[name], window)
        _, _, late = _segment_stats(env[name], LATE[R3])
        table = bounds.coefficient_tables(env[name]["a"], {
            i: bounds.window_bins(i, window if i >= 2 else LATE[R3])
            for i in range(10)})
        early[name] = {"tables": table, "DD": {
            i: max(abs(spans[i][1]-late[i][0]), abs(late[i][1]-spans[i][0]))
            for i in bounds.LIT}}
    return early


def _r3_channels(settings, klass, sigma, row, window):
    """Class constants of section 8.4 for one order, always on late windows."""
    gains = _gain_bounds()
    W = prior.WEIGHT+BASE["weight_knowledge"]
    env = class_envelope(R3, settings, klass, sigma, row)
    eps = amplitudes(settings, anchored=True)
    if klass == "step":
        eps = dict(eps, r=eps["r"]+PROTOCOL["anchor_step"]["s_r_fraction"])
    rate = settings["classes"] & {"slow_drift", "bounded_rate"}
    steps = prior.window_step(settings)
    params = actuator_params(row)
    channels = {}
    kernel = prior_bounds.mean_kernel(10, prior.BAND[0], STEP)
    for name, balance, dhat in (("p", PRIMARY, steps[0]), ("r", REFERENCE, steps[1])):
        Dbar, DD, spans = _segment_stats(env[name], window)
        addend = {}
        for i in range(10):
            time = (i+1)*100*STEP
            addend[i] = (abs(balance.offset_newtons)
                         + abs(balance.drift_newtons_per_second)*time
                         + balance.vibration_newtons*kernel
                         + balance.noise_bound_newtons)
        change = abs(spans[1][1]-spans[0][0])
        change = max(change, abs(spans[0][1]-spans[1][0]))
        eps_a = 0.0
        if rate:
            eps_a = eps[name]
        channels[name] = {
            "W": W if name == "r" else 1.0, "G1": 1+gains[name][1],
            "g_min": gains[name][0], "eps_b": eps[name], "eps_a": eps_a,
            "Dhat": dhat, "Dbar": Dbar, "DD": _symmetric(DD),
            "addend": addend, "anchor_force_change": change,
            "anchor_addend_change": (
                2*balance.noise_bound_newtons+2*balance.vibration_newtons*kernel
                + 10*abs(balance.drift_newtons_per_second)
                + 2*dhat*(Dbar[0]+params["Kmax"]*params["A"])),
            "tables": bounds.coefficient_tables(env[name]["a"], _windows(window))}
    return channels, env


def _symmetric(table):
    full = dict(table)
    for (i, j), value in table.items():
        full[j, i] = value
    return full


def bound_r3(settings, klass, row, window):
    """Bound[D] of section 8.4, worst of both orders."""
    best, detail = 0.0, None
    params = actuator_params(row)
    noise, vib = floor_terms(R3, window)
    for bit in (1, -1):
        sigma = order_for(bit)
        channels, env = _r3_channels(settings, klass, sigma, row, LATE[R3])
        state = bounds.evaluate_r3(channels, params)
        early = None if window == LATE[R3] else _r3_early(env, sigma, window)
        for c in channels:
            if max(state[c]["Vbar"][i] for i in bounds.LIT)/params["Kmin"] > (
                    R3_SPEC["in_domain_clamp_proof_maximum_newtons"]):
                raise bounds.Unproved("clamp proof")
        terms, total, _ = bounds.r3_terms(channels, state, params, early)
        quiet = class_envelope(R3, settings, quiet_class(klass), sigma, row)
        value = total+nuisance_contrast(quiet, sigma, window, klass)
        if value >= best:
            best = value
            detail = {"terms": terms, "abar": {c: state[c]["abar"] for c in state},
                      "Xbar_r": max(state["r"]["Xbar"].values()),
                      "nuisance": nuisance_contrast(quiet, sigma, window, klass)}
    return best+noise+vib, detail


_projection_cache = {}


def projection_constants():
    """Validated tone projection constants with gap rows, section 8.2a."""
    if "cells" in _projection_cache:
        return _projection_cache["cells"]
    spec = PROTOCOL["r1_enclosures"]
    times = [(k+1)*STEP for k in range(180, 200)]
    knowledge = prior.PILOT["response_time_estimator_knowledge_fraction"]
    cells = prior_bounds.weight_cells(REFERENCE.response_seconds, knowledge,
                                      spec["xi_cells"], times, TONE_OMEGA)
    kernel_cells = prior_bounds.weight_cells(
        REFERENCE.response_seconds, knowledge, spec["kernel_xi_cells"], times,
        TONE_OMEGA)
    a = math.exp(-STEP/REFERENCE.response_seconds)
    tone = _filtered([math.sin(TONE_OMEGA*(k+1)*STEP) for k in range(BINS)], a)
    z = {segment: [tone[segment*100+q] for q in range(80, 100)]
         for segment in range(1, 10)}
    q_bound = q_point = 0.0
    for segment in range(2, 10):
        change = [x-y for x, y in zip(z[segment], z[1])]
        upper, point = prior_bounds.ratio_sup_abs(cells, change, z[1])
        q_bound, q_point = max(q_bound, upper), max(q_point, point)
    gain, gain_point = prior_bounds.noise_gain(cells, z[1])
    low, high, point_low, point_high = prior_bounds.linear_range(cells, z[1])
    kernel, kernel_point = prior_bounds.kernel(
        kernel_cells, times, prior.BAND, spec["kernel_frequency_cells"])
    limit, floor = spec["maximum_relative_gap"], spec["dimensionless_floor"]
    rows = [prior_bounds.gap_check(name, kind, bound, point, floor, limit)
            for name, kind, bound, point in (
                ("S_low", "infimum", low, point_low),
                ("S_high", "supremum", high, point_high),
                ("q", "supremum", q_bound, q_point),
                ("noise_gain", "supremum", gain, gain_point),
                ("K_u", "supremum", kernel, kernel_point))]
    _projection_cache["cells"] = {
        "q": q_bound, "gain": gain, "S_low": low, "S_high": high,
        "kernel": kernel, "carry": a**80,
        "tone_mean": max(abs(math.fsum(z[s]))/20 for s in z),
        "z_peak": max(abs(v) for s in z for v in z[s]), "gaps": rows}
    return _projection_cache["cells"]


def r1_enclosure_table():
    """Validated rows and conservative remainders stay in separate tables."""
    constants = projection_constants()
    return {"validated": constants["gaps"],
            "conservative_remainder": PROTOCOL["r1_enclosures"][
                "conservative_remainders"]}


_tone_cache = {}


def tone_terms(window, amplitude, k_b):
    """Tone level and deviation on one contrast window, from its own samples."""
    key = (window, amplitude, k_b)
    if key not in _tone_cache:
        a = math.exp(-STEP/REFERENCE.response_seconds)
        tone = _filtered([math.sin(TONE_OMEGA*(k+1)*STEP) for k in range(BINS)], a)
        means = [abs(math.fsum(tone[i*100+window[0]-1:i*100+window[1]])
                     / (window[1]-window[0]+1)) for i in bounds.LIT]
        table = _tone_tables(window)
        delta = TONE_OMEGA*PHOTON["timing_label_bound_seconds"]
        Kmax, L = PHOTON["K_c0_interval"][1], PHOTON["L_nl"]
        spread = Kmax*amplitude*(1+L)*(max(means)-min(means))
        deviation = bounds.tone_deviation(table, Kmax, amplitude, k_b, L, delta,
                                          PHOTON["h_b_newtons"])
        _tone_cache[key] = {"mean": max(means), "cold_spread": spread, "deviation": {
            i: value+spread for i, value in deviation.items()}}
    return _tone_cache[key]


_tone_table_cache = {}


def _tone_tables(window):
    if window not in _tone_table_cache:
        a = math.exp(-STEP/REFERENCE.response_seconds)
        _tone_table_cache[window] = bounds.tone_weights(a, TONE_OMEGA, STEP, window)
    return _tone_table_cache[window]


def bound_r1(settings, klass, row, window):
    """Bound[D] of section 8.2, worst of both orders."""
    gains = _gain_bounds()
    W = prior.WEIGHT+BASE["weight_knowledge"]
    constants = projection_constants()
    failed = [r["name"] for r in constants["gaps"] if not r["passed"]]
    if failed:
        raise bounds.Unproved(f"enclosure gap failed: {failed}")
    amplitude = tone_amplitude(row)
    k_b = actuator_params(row)["k_b"]
    Kmin = PHOTON["K_c0_interval"][0]
    eps = amplitudes(settings, anchored=True)
    if klass == "step":
        eps = dict(eps, r=eps["r"]+PROTOCOL["anchor_step"]["s_r_fraction"])
    steps = prior.window_step(settings)
    N, V = REFERENCE.noise_bound_newtons, REFERENCE.vibration_newtons
    gmin = 1+gains["r"][0]-eps["r"]
    if gmin <= 0:
        raise bounds.Unproved("gain lower bound")
    best = 0.0
    for bit in (1, -1):
        sigma = order_for(bit)
        env = class_envelope(R1, settings, klass, sigma, row)
        Dbar_r, _, _ = _segment_stats(env["r"], window)
        Dbar_p, _, _ = _segment_stats(env["p"], window)
        # The projection stays on the late window on both statistics.
        Dbar_late, _, _ = _segment_stats(env["r"], LATE[R1])
        # Section 8.2: X_i holds the tone's window mean, the mean force of an even
        # phi, and memory, none of which is in the force envelope.
        Kmax, L = PHOTON["K_c0_interval"][1], PHOTON["L_nl"]
        tone = tone_terms(window, amplitude, k_b)
        tone_level = (Kmax*(1+k_b)*amplitude*(tone["mean"]*(1+L)+L)
                      + PHOTON["h_b_newtons"]+max(tone["deviation"].values()))
        tone_peak = Kmax*(1+L)*amplitude*constants["z_peak"]
        x_b = PHOTON["cross_talk_x_b"]
        Xbar_r = {i: value+tone_level for i, value in Dbar_r.items()}
        Xbar_p = {i: value+x_b*tone_peak for i, value in Dbar_p.items()}
        # Projection remainder, in units of reading.
        tone_state = amplitude*PHOTON["K_c0_interval"][1]*(1+PHOTON["L_nl"])
        # Every remainder below is relative to sum(u*z), so the floor omits it.
        # A force at the tone frequency passes the tone's own filter.
        lower = gmin*(1-k_b)*Kmin*amplitude
        spoof = (k_b*R1_SPEC["tone_amplitude_newtons"]
                 if klass in SPOOF_CLASSES else 0.0)
        res = {}
        # Largest dwell step left at the window's first sample, section 8.2.
        transient = constants["gain"]*constants["carry"]*2*max(Dbar_late.values())
        for i in range(1, 10):
            mixing = constants["gain"]*steps[1]*(Dbar_late[i]+tone_state)
            res[i] = (constants["gain"]*N+constants["kernel"]/constants["S_low"]*V
                      + mixing
                      + transient+spoof
                      + constants["gain"]*2*PHOTON["h_b_newtons"]*constants["carry"])
        theta = {}
        for i in bounds.LIT:
            theta[i] = bounds.theta_interval(res[i], lower, k_b, constants["q"])
        theta_s = res[1]/(lower-res[1])
        if lower-res[1] <= 0:
            raise bounds.Unproved("anchor denominator")
        if row == "R1-abs":
            low, high = PHOTON["K_c0_interval"]
            g_low, g_high = 1+gains["r"][0], 1+gains["r"][1]
            theta_s = max(abs(1/(high*g_high*constants["S_high"])-1),
                          abs(1/(low*g_low*constants["S_low"])-1))+theta_s
        n = len(sigma)
        contrast = abs(2/n*math.fsum(
            sigma[i]*window_mean(env["r"]["centre"], i+2, window) for i in range(n)))
        contrast += 2/n*math.fsum(window_mean(env["r"]["indep"], i+2, window)
                                  + window_mean(env["r"]["common"], i+2, window)
                                  for i in range(n))
        bracket = {}
        offset_path = {}
        for i in bounds.LIT:
            bracket[i] = (1+theta_s)*(1+theta[i])/(1-eps["r"])-1
            offset_path[i] = (abs(REFERENCE.offset_newtons)
                              + abs(REFERENCE.drift_newtons_per_second)*(i+1)*10)
        terms = bounds.r1_terms({
            "W": W, "G1_p": 1+gains["p"][1], "G1_r": 1+gains["r"][1],
            "eps_p": eps["p"], "Xbar_p": Xbar_p, "Xbar_r": Xbar_r,
            "theta": theta, "theta_s": theta_s, "XC_r": contrast,
            "bracket": bracket, "offset_path": offset_path})
        factor = 1+max(bracket.values())
        noise, vib = floor_terms(R1, (91, 100), factor)
        bracket_max = max(bracket.values())
        tone_sum = 2/n*math.fsum(tone["deviation"].values())
        cold = max(2*W*(1+gains["r"][1])*(k_b*tone_level+PHOTON["h_b_newtons"])
                   + 2*x_b*tone_level,
                   W*(1+gains["r"][1])*(1+bracket_max)*tone_sum+x_b*tone_sum)
        split = 0.0
        if window != LATE[R1]:
            # Section 8.2: a late g_i on an early reading, when gain moves in a dwell.
            split = (2*W*(1+gains["r"][1])*(1+bracket_max)
                     * min(7*steps[1], 2*eps["r"])
                     * (max(Dbar_r.values())+tone_peak))
        mix = bounds.r1_mix(W, 1+gains["r"][1], 1+gains["p"][1],
                            max(bracket.values()), steps, max(Dbar_r.values()),
                            tone_peak, x_b)
        quiet = class_envelope(R1, settings, quiet_class(klass), sigma, row)
        value = (math.fsum(terms.values())+noise+vib+cold+mix+split
                 + nuisance_contrast(quiet, sigma, window, klass))
        best = max(best, value)
    return best


def class_bounds(config, settings, window, plan=None):
    """E_N and every class of section 7.1, on one window. May be unproved."""
    arch, _, row = config
    def one(klass):
        if arch == R3:
            value, detail = bound_r3(settings, klass, row, window)
            if plan is not None:
                plan["terms"][klass] = detail
            return value
        if arch == R1:
            return bound_r1(settings, klass, row, window)
        value = bound_plain(arch, settings, klass, row, window)
        if arch == R2:
            value = max(value, bound_plain(arch, settings, klass, row, window,
                                           form="chain"))
        return value
    rho = max(settling_rho(order_for(b), window) for b in (1, -1))
    null = max(one("none"),
               one("phase_null")+rho*2*phase_null_ranges()["recoil_maximum"])
    return null, {klass: one(klass) for klass in (
        "held", "mimic", "lag10", "lag01", "spoof+", "spoof-", "step")}


def design(config):
    """Half-width, margins and validity. Validity precedes any margin."""
    arch, scenario, row = config
    settings = prior.scenario_settings(scenario)
    if row == "R2-N":
        return _design_narrow(config, settings)
    window = LATE[arch]
    S_max = optical()["signal_maximum_newtons"]
    plan = {"config": config, "valid": True, "reason": None, "terms": {}}
    try:
        rho = max(settling_rho(order_for(b), window) for b in (1, -1))
        null, values = class_bounds(config, settings, window, plan)
        values["held"] += rho*S_max
        plan.update(E_N=null, E_S=max(values.values()), classes=values, rho=rho)
    except bounds.Unproved as error:
        plan.update(valid=False, reason=str(error), E_N=None, E_S=None, classes={})
        return plan
    finish_design(plan)
    plan["half_early"], plan["early_reason"] = early_half(config, settings)
    return plan


def early_half(config, settings):
    """B_early of section 7.5. A refusal leaves the lag state unproved."""
    arch = config[0]
    window = EARLY[arch]
    try:
        _, values = class_bounds(config, settings, window)
        rho = max(settling_rho(order_for(b), window) for b in (1, -1))
    except bounds.Unproved as error:
        return None, str(error)
    values["held"] += rho*optical()["signal_maximum_newtons"]
    if not lag_monotone(arch):
        return None, "early ratio not proved monotone"
    return max(values.values())+2*prior.STRUCTURAL, None


def _design_narrow(config, settings):
    arch, scenario, row = config
    window = LATE[arch]
    quiet = dict(settings, s_p=0.0, s_r=0.0)
    plain = max(bound_plain(arch, quiet, "none", row, window),
                bound_plain(arch, quiet, "phase_null", row, window))
    W = prior.WEIGHT+BASE["weight_knowledge"]
    z, chi = NARROW["transducer_fraction_z"], NARROW["chi"]
    s_p, s_r = settings["s_p"], settings["s_r"]
    x_p, x_r = prior.COMMON, prior.COUPLING*prior.COMMON
    residual = x_p-W*x_r
    label = bounds.r2_narrow_label(s_p, s_r, x_p, x_r, residual, z, chi, W)
    nominal = prior.nominal_contrast()
    mimic = bounds.r2_narrow_mimic(s_p, s_r, nominal, 0.0, z, chi)
    rho = max(settling_rho(order_for(b), window) for b in (1, -1))
    S_max = optical()["signal_maximum_newtons"]
    leak = prior.LEAK+BASE["leakage_knowledge"]
    gain = (S_max*(z*s_p+chi*(s_p+s_r)/2)
            + W*leak*S_max*(z*s_r+chi*(s_p+s_r)/2))
    null = plain+label
    held = null+rho*S_max+gain
    plan = {"config": config, "valid": True, "reason": None, "terms": {},
            "E_N": null, "rho": rho,
            "classes": {"held": held, "mimic": null+mimic},
            "E_S": max(held, null+mimic)}
    finish_design(plan)
    plan["half_early"], plan["early_reason"] = None, "no early class in the narrow row"
    return plan


def finish_design(plan):
    data = optical()
    box = prior.transfer_box()
    walk = data["walk_newtons"]
    low, high = prior.map_interval(
        [data["optical_minimum_newtons"]-walk, data["optical_maximum_newtons"]+walk],
        box)
    half = plan["E_S"]+2*prior.STRUCTURAL
    plan.update(half=half, lower=low, upper=high, box=box, walk=walk,
                m_null=low-plan["E_N"]-half,
                m_signal=box[0]*data["signal_minimum_newtons"]-plan["E_S"]-half)
    return plan


def predicted_interval(draws, plan, detector=None):
    view = {"arch": A1, "order": list(draws["order"]),
            "orientation": draws["orientation"], "phases": draws["phases"],
            "feeds": draws["feeds"]}
    raw = prior.optical_contrast(view, detector=detector)
    return raw, prior.map_interval([raw[0]-plan["walk"], raw[1]+plan["walk"]],
                                   plan["box"])


def truth(draws, run):
    """Audit only. From fixed values, never an estimator quantity."""
    gains = anchor_gains(draws)
    g_p, g_r = gains["p"]["g"], gains["r"]["g"]
    arch = draws["config"][0]
    window = LATE[arch]
    order, n = draws["order"], len(draws["order"])
    actual = (1+g_p)-draws["w"]*draws["leak"]*(1+g_r)
    control = draws["control"]
    inputs = run["inputs"]
    if control == "reference-path-label-mimic":
        a = math.exp(-STEP/REFERENCE.response_seconds)
        state = _filtered(inputs["m"], a)
        return -draws["w"]*(1+g_r)*transient_contrast(state, order, window)
    if control in ("impostor-source-fixed-lag-10s", "impostor-source-fixed-lag-0p1s"):
        a = math.exp(-STEP/PRIMARY.response_seconds)
        return actual*transient_contrast(_filtered(inputs["s"], a), order, window)
    return actual*transient_contrast(inputs["s"], order, window)


def early_ratio(arch, order, tau):
    """Early to late contrast of a label-held unit force, section 7.5."""
    a = math.exp(-STEP/tau)
    drive = [0.0]*200+[order[k//100-2] for k in range(200, BINS)]
    state = _filtered(drive, a)
    return (transient_contrast(state, order, EARLY[arch])
            / transient_contrast(state, order, LATE[arch]))


_lag_proofs = {}


def lag_monotone(arch):
    """The proof of section 7.5, on the whole domain, for both orders."""
    if arch not in _lag_proofs:
        spec = PROTOCOL["lag_decision"]
        knowledge = spec["tauhat_knowledge_fraction"]
        tau = PRIMARY.response_seconds
        low = tau*(1-knowledge)/(1+knowledge)
        high = tau*(1+knowledge)/(1-knowledge)
        _lag_proofs[arch] = all(
            bounds.ratio_direction(order_for(bit), EARLY[arch], LATE[arch], low, high,
                                   spec["monotone_proof"]["cells"], STEP) is not None
            for bit in (1, -1))
    return _lag_proofs[arch]


def lag_radius(arch, order, tau_hat):
    """k at the estimate, and its radius over the inverse true-tau interval."""
    knowledge = PROTOCOL["lag_decision"]["tauhat_knowledge_fraction"]
    k = early_ratio(arch, order, tau_hat)
    return k, max(abs(early_ratio(arch, order, tau_hat/(1+s*knowledge))-k)
                  for s in (-1, 1))


def lag_values(late, early, draws, plan):
    """Lambda_lag and its half-width. Analysis only, never a controller input."""
    half_early = plan.get("half_early")
    if half_early is None:
        return None
    arch = draws["config"][0]
    order = draws["order"]
    k, dk = lag_radius(arch, order, PRIMARY.response_seconds*(1+draws["xi_p"]))
    half = half_early+k*plan["half"]+abs(late)*dk
    return {"statistic": early-k*late, "half": half,
            "exceeds": abs(early-k*late) > half}


def lag_state(rows, plan):
    """First match, section 7.5. It is about lagged impostors, never recoil."""
    if plan.get("half_early") is None:
        return "unproved"
    if any(r["lag"]["exceeds"] for key, r in rows.items() if key[0] in (
            "impostor-source-fixed-instant", "impostor-source-fixed-lag-0p1s")):
        return "instant_or_short_lag_separated"
    lagged = [r["lag"]["exceeds"] for key, r in rows.items()
              if key[0] == "impostor-source-fixed-lag-10s"]
    if lagged and all(lagged):
        return "attribution_separated_conditional"
    return "rank_raised_not_resolved"


def assess(draws, plan, *, detector=None, noise_path=None):
    """One acquisition. Only readings and public values reach the estimator."""
    arch, _, row = draws["config"]
    tau_hat = REFERENCE.response_seconds*(1+draws["xi_r"])
    run = simulate(draws, noise_path=noise_path)
    controller = run["controller"]
    if controller.saturated and draws["control"] != "impostor-out-of-window":
        raise OperationalFailure("command clamp acted in-domain")
    late = estimate(arch, draws["order"], run["y"], controller, LATE[arch],
                    weight=draws["w"], tau_hat=tau_hat, row=row)
    early = estimate(arch, draws["order"], run["y"], controller, EARLY[arch],
                     weight=draws["w"], tau_hat=tau_hat, row=row,
                     ratios=late.get("ratios"))
    raw, predicted = predicted_interval(draws, plan, detector)
    resolved, overlap = prior.judge(late["contrast"], plan["half"], predicted)
    target = truth(draws, run)
    lag = lag_values(late["contrast"], early["contrast"], draws, plan)
    return {"contrast": late["contrast"], "truth": target, "raw": raw, "lag": lag,
            "error": abs(late["contrast"]-target), "predicted": predicted,
            "resolved": resolved, "overlap": overlap,
            "C_RO": late.get("C_RO"), "kappa": late.get("kappa")}


CONTROLS = tuple(PROTOCOL["controls"])
DUAL_CONTROLS = tuple(c for c in CONTROLS if c in prior.DUAL)
ROW_LIMIT = 12


def expectation(control, orientation):
    if control in ("tone-spoof-reference", "anchor-step-gain"):
        return (False, False)
    return prior.single_expectation(control, orientation)


def large_stimulus_bound(config, plan):
    """E_x of section 7.4. Audit only: never an interval and never a decision."""
    arch, scenario, row = config
    settings = prior.scenario_settings(scenario)
    S_x = PROTOCOL["out_of_window"]["contrast_newtons"]
    F_x = PROTOCOL["out_of_window"]["per_dwell_amplitude_newtons"]
    window = LATE[arch]
    L_max = prior.LEAK+BASE["leakage_knowledge"]
    W = prior.WEIGHT+BASE["weight_knowledge"]
    factor = prior.amplitude_factor(settings)
    if arch in (B1, R2):
        return (plan["E_N"]+plan["rho"]*S_x
                + factor*(settings["s_p"]+W*settings["s_r"]*L_max)*S_x)
    if arch == R1:
        return bound_r1(settings, "large", row, window)+plan["rho"]*S_x
    params = actuator_params(row)
    best = 0.0
    noise, vib = floor_terms(R3, window)
    for bit in (1, -1):
        sigma = order_for(bit)
        channels, _ = _r3_channels(settings, "none", sigma, row, window)
        value = bounds.r3_large_stimulus(
            channels, params, {"p": F_x*(1+settings["common"]),
                               "r": L_max*F_x*(1+settings["common"])})
        quiet = class_envelope(R3, settings, "none", sigma, row)
        best = max(best, value+nuisance_contrast(quiet, sigma, window, "none"))
    return best+noise+vib+plan["rho"]*S_x


def detector_design(config, *, witness=True):
    """T_RO and A_unflag of section 7.3. No half-width credit in any row."""
    arch, scenario, row = config
    settings = prior.scenario_settings(scenario)
    gains = _gain_bounds()
    C = prior.COMMON
    c = prior.COUPLING
    low_cw, high_cw = WITNESS["common_coupling_interval"]
    b_w = WITNESS["shared_mimic_path_interval"][1] if witness else 0.0
    eps = amplitudes(settings, anchored=False)
    if row == "R2-N":
        z, chi = NARROW["transducer_fraction_z"], NARROW["chi"]
        eps = {"r": (z+chi)*eps["r"], "p": (z+chi)*eps["p"]}
    eps_w = amplitudes(settings, anchored=False)["r"]
    a_r = math.exp(-STEP/REFERENCE.response_seconds)
    window = LATE[B1]
    windows = {i: bounds.window_bins(i, window) for i in range(10)}
    f = settings["common"]
    q = range(window[0], window[1]+1)
    beta_r = math.fsum(a_r**x for x in q)/len(q)
    tau_w = R2_SPEC["witness_response"]["response_seconds_interval"][1]
    beta_w = math.fsum(math.exp(-x*STEP/tau_w) for x in q)/len(q)
    denominator = 0.5*low_cw*C
    offset = (abs(REFERENCE.offset_newtons)
              + abs(REFERENCE.drift_newtons_per_second)*20
              + REFERENCE.noise_bound_newtons
              + REFERENCE.vibration_newtons)
    dk = 2*offset/denominator+beta_w
    kbar = (1+dk)*(1+gains["r"][1])*c/((1+gains["r"][0])*low_cw)
    G_r_max, G_r_min = 1+gains["r"][1], 1+gains["r"][0]
    data = optical()
    leak = prior.LEAK+BASE["leakage_knowledge"]
    S_max = data["signal_maximum_newtons"]
    noise = 2*REFERENCE.noise_bound_newtons
    vib = 2*REFERENCE.vibration_newtons*prior_bounds.mean_kernel(
        10, prior.BAND[0], STEP)
    b = settings["blind"]
    gain_r = 2*G_r_max*eps["r"]*c*C*(1+f)*(1+b)
    common = 2*f*c*C*G_r_max
    blind = 2*b*c*C*(1+f)*G_r_max
    if witness:
        l_w = WITNESS["signal_leak_interval"][1]
        nbar = (gain_r+2*kbar*G_r_max*eps_w*high_cw*C*(1+f)
                + dk*common+blind
                + kbar*G_r_max*high_cw*2*f*C*4*(beta_w+beta_r)
                + G_r_max*leak*S_max+kbar*G_r_max*l_w*S_max
                + (noise+vib)*(1+kbar))
    else:
        nbar = gain_r+common+blind+G_r_max*leak*S_max+noise+vib
    settings_out = {
        "L_mu": bounds.l_mu(a_r, f, windows),
        "guard_L_mu": PROTOCOL["reference_only_flag"]["L_mu_guard_minimum"],
        "guard_psi": PROTOCOL["hypothesis_thresholds"][
            "minimum_separating_response"],
        "dk": dk, "coupling_ratio_max": c/low_cw, "b_w_max": b_w,
        "G_r_max": G_r_max, "G_r_min": G_r_min, "G_w_max": G_r_max,
        "eps_r": eps["r"], "eps_w": eps_w if witness else 0.0, "kbar": kbar,
        "beta_w": beta_w, "beta_r": beta_r, "f": f, "Nbar": nbar}
    result = bounds.detection_bound(settings_out)
    result["T_RO"] = nbar
    return result


def witness_noise(draws, sign):
    """Noise aligned with the label on every window, at the read bound."""
    order = draws["order"]
    def path(k):
        i = k//100-2
        s = sign*(order[i] if i >= 0 else 1)
        return (s*PRIMARY.noise_bound_newtons, -s*REFERENCE.noise_bound_newtons,
                -s*REFERENCE.noise_bound_newtons)
    return path


def admissible(draws):
    """Separately written validator: every parameter inside its declared class."""
    faults = []
    arch, scenario, row = draws["config"]
    settings = draws["settings"]
    k_b = actuator_params(row)["k_b"]
    low, high = PHOTON["K_c0_interval"]
    for name in ("K_p", "K_r"):
        if not low <= draws[name] <= high:
            faults.append(name)
    for name in ("k_p", "k_r"):
        if max(map(abs, draws[name])) > k_b:
            faults.append(name)
    for name in ("x_p", "x_r"):
        if abs(draws[name]) > PHOTON["cross_talk_x_b"]:
            faults.append(name)
    for name in ("h_p", "h_r"):
        if max(map(abs, draws[name])) > PHOTON["h_b_newtons"]:
            faults.append(name)
    for name, interval in (("c_w", "common_coupling_interval"),
                           ("l_w", "signal_leak_interval"),
                           ("b_w", "shared_mimic_path_interval")):
        a, b = WITNESS[interval]
        if not a <= draws[name] <= b:
            faults.append(name)
    limit_p = prior.amplitude_factor(settings)*settings["s_p"]
    limit_r = prior.amplitude_factor(settings)*settings["s_r"]
    if max(map(abs, draws["e_p"])) > limit_p*(1+1e-12):
        faults.append("e_p")
    if max(map(abs, draws["e_r"])) > limit_r*(1+1e-12):
        faults.append("e_r")
    if draws["reflectance"] < PHOTON["R_box_minimum"]:
        faults.append("reflectance")
    return faults


class InadmissibleWitness(Exception):
    """A candidate left its declared class, so it makes no reading."""


def search_candidate(config, seed, bits):
    """One realisation of the six sign bits of section 13."""
    arch, scenario, row = config
    draws = draw(config, seed, "force-decoupled", 1, "witness-search")
    wander, k, x, phi_bit, K, noise = bits
    bound = actuator_params(row)["k_b"]
    order = draws["order"]
    draws["k_p"] = [s*k*bound for s in order]
    draws["k_r"] = [-s*k*bound for s in order]
    draws["e_p"] = [wander*v for v in draws["e_p"]]
    draws["e_r"] = [wander*v for v in draws["e_r"]]
    x_b = PHOTON["cross_talk_x_b"]
    draws["x_p"], draws["x_r"] = x*x_b, -x*x_b
    draws["phi_sign"] = phi_bit
    low, high = PHOTON["K_c0_interval"]
    draws["K_p"], draws["K_r"] = (high, low) if K > 0 else (low, high)
    return draws, witness_noise(draws, noise)


def joint_witness_search(config, plan, detector=None, clock=None):
    """Bounded coordinate ascent. A lower witness only, never a bound."""
    spec = PROTOCOL["joint_witness_search"]
    low, high = spec["start_seeds"]
    cap = spec["maximum_evaluations_per_configuration"]
    clock = clock if clock is not None else {"used": 0.0}
    started = time.monotonic()
    best = None
    count = 0

    def evaluate(seed, bits):
        nonlocal count
        if count >= cap:
            return None
        if clock["used"]+time.monotonic()-started > spec["maximum_seconds_per_run"]:
            raise OperationalFailure("witness search exceeded its elapsed cap")
        count += 1
        draws, path = search_candidate(config, seed, bits)
        faults = admissible(draws)
        if faults:
            raise InadmissibleWitness(",".join(faults))
        try:
            return assess(draws, plan, detector=detector, noise_path=path)["error"]
        except OperationalFailure:
            return -1.0
    for seed in range(low, high+1):
        rng = random.Random(stream("pf002-reference-gain-v1", "witness-search",
                                   seed, *config))
        bits = [rng.choice((-1, 1)) for _ in spec["bits"]]
        value = evaluate(seed, bits)
        if value is None:
            break
        for _ in range(spec["maximum_passes"]):
            for index in range(len(bits)):
                trial = list(bits)
                trial[index] = -trial[index]
                result = evaluate(seed, trial)
                if result is None:
                    break
                if result > value:
                    value, bits = result, trial
        if best is None or value > best[0]:
            best = (value, seed, list(bits))
    clock["used"] += time.monotonic()-started
    text = json.dumps([best[1], best[2]]).encode("ascii")
    return {"best_error": best[0], "seed": best[1], "bits": best[2],
            "evaluations": count, "digest": "sha256:"+hashlib.sha256(text).hexdigest()}


def run_configuration(config, seeds, cohort, *, witness_seed=None, detector=None,
                      search_clock=None):
    """All rows of one configuration, classified by the section 9 precedence."""
    plan = design(config)
    arch, scenario, row = config
    summary = {"config": list(config), "design": public_plan(plan), "rows": 0,
               "failing": [], "operational": [], "worst_error": None}
    if not plan["valid"]:
        summary["class"] = "inconclusive_invalid_envelope"
        summary["reason"] = plan["reason"]
        return summary
    flag_design = (detector_design(config) if arch == R2 else None)
    condition2 = condition3 = condition5 = True
    worst = 0.0
    digest = hashlib.sha256()
    stimulus = None
    try:
        stimulus = large_stimulus_bound(config, plan)
    except bounds.Unproved as error:
        condition5 = False
        summary["failing"].append(["stimulus", str(error)])
        _cause(summary, 5, "stimulus_unproved", ["design", str(error)[:80]])
    pairs = covered = out_of_window_flags = 0
    worst_dual = 0.0
    all_rows = {}
    for seed in seeds:
        rows = {}
        for control in CONTROLS:
            for orientation in (1, -1):
                if control == "impostor-out-of-window" and orientation == -1:
                    continue
                draws = draw(config, seed, control, orientation, cohort)
                try:
                    result = assess(draws, plan, detector=detector)
                except OperationalFailure as error:
                    _operational(summary, [seed, control, orientation, str(error)])
                    continue
                summary["rows"] += 1
                rows[control, orientation] = result
                all_rows[control, orientation, seed] = result
                digest.update(json.dumps(
                    [seed, control, orientation, result["contrast"]],
                    sort_keys=True).encode("ascii"))
                tuple_ = (result["resolved"], result["overlap"])
                required = expectation(control, orientation)
                if control == "impostor-out-of-window":
                    if stimulus is None or result["error"] > stimulus:
                        condition5 = False
                        _cause(summary, 5, "stimulus_breach" if stimulus is not None
                               else "stimulus_unproved", [seed, control, orientation],
                               None if stimulus is None else result["error"]/stimulus)
                else:
                    worst = max(worst, result["error"])
                    if result["error"] > plan["half"]:
                        condition3 = False
                        _note(summary, [seed, control, orientation, "truth",
                                        result["error"], plan["half"]])
                        _cause(summary, 3, "truth", [seed, control, orientation],
                               result["error"]/plan["half"])
                if tuple_ != required:
                    if control in prior.MIMIC:
                        reference = rows.get(("opposite-phase", orientation))
                        same = reference is not None and tuple_ == (
                            reference["resolved"], reference["overlap"])
                        if not same and control != "impostor-lab-fixed-in-window":
                            condition5 = False
                            _note(summary, [seed, control, orientation, "mimic"])
                            _cause(summary, 5, "mimic_failed",
                                   [seed, control, orientation])
                    else:
                        condition2 = False
                        _note(summary, [seed, control, orientation, "decision"])
                        _cause(summary, 2, "decision", [seed, control, orientation])
                if flag_design and flag_design["status"] == "bounded":
                    flag = abs(result["C_RO"]) > flag_design["T_RO"]
                    is_mimic = control == "reference-path-label-mimic"
                    needs = is_mimic and (
                        prior.nominal_contrast() > flag_design["A_unflag"])
                    if control == "impostor-out-of-window":
                        # Visible, carries no condition: section 7.3, revision 5.
                        out_of_window_flags += int(flag)
                    elif (needs and not flag) or (flag and not is_mimic):
                        condition2 = False
                        _note(summary, [seed, control, orientation, "flag"])
                        _cause(summary, 2, "flag", [seed, control, orientation])
        for control in DUAL_CONTROLS:
            plus, minus = rows.get((control, 1)), rows.get((control, -1))
            if plus is None or minus is None:
                _operational(summary, [seed, control, 0, "missing pair"])
                continue
            pair = dual_pair(plus, minus, plan, control)
            pairs += 1
            covered += pair["covered"]
            worst_dual = max(worst_dual, pair["d_ratio"], pair["sigma_ratio"])
            if not pair["covered"]:
                condition3 = False
                _note(summary, [seed, control, 0, "dual truth"])
                _cause(summary, 3, "dual_truth", [seed, control, 0],
                       max(pair["d_ratio"], pair["sigma_ratio"]))
            if control not in prior.MIMIC and pair["tuple"] != prior.DUAL[control]:
                condition2 = False
                _note(summary, [seed, control, 0, "dual decision"])
                _cause(summary, 2, "dual_decision", [seed, control, 0])
            if control == "impostor-lab-fixed-in-window":
                if pair["tuple"] != prior.DUAL[control]:
                    condition2 = False
                    _note(summary, [seed, control, 0, "lab-fixed miss"])
                    _cause(summary, 2, "lab_fixed_miss", [seed, control, 0])
    summary["dual_truth"] = {"checked": pairs, "covered": covered,
                             "worst_ratio": worst_dual}
    summary["out_of_window_flags"] = out_of_window_flags
    summary["lag_state"] = lag_state(all_rows, plan)
    if summary["lag_state"] == "instant_or_short_lag_separated":
        condition5 = False
        _note(summary, [0, "lag", 0, "instant or short lag separated"])
        _cause(summary, 5, "lag_separated", [0, "lag", 0])
    summary["worst_error"] = worst
    summary["row_digest"] = "sha256:"+digest.hexdigest()
    summary["stimulus_bound"] = stimulus
    summary["detector"] = flag_design
    margins = plan["m_null"] >= PROTOCOL["required_margin_newtons"] and (
        plan["m_signal"] >= PROTOCOL["required_margin_newtons"])
    rejected = _witnesses(config, plan, summary, witness_seed or seeds[0],
                          cohort, detector)
    if rejected is None:
        condition5 = False
        rejected = False
        _cause(summary, 5, "witness_inadmissible", [0, "witness", 0])
        _cause(summary, 4, "witness_inadmissible", [0, "witness", 0])
    try:
        summary["witness_search"] = joint_witness_search(config, plan, detector,
                                                         search_clock)
        if summary["witness_search"]["best_error"] > plan["half"]:
            condition5 = False
            _note(summary, [0, "witness search", 0, "outside half-width"])
            _cause(summary, 5, "search_outside_half",
                   [summary["witness_search"]["seed"], "witness search", 0],
                   summary["witness_search"]["best_error"]/plan["half"])
    except InadmissibleWitness as error:
        condition5 = False
        summary["witness_search"] = {"inadmissible": str(error)}
        _cause(summary, 5, "search_inadmissible", [0, str(error)[:80], 0])
    summary["conditions"] = {"1": margins, "2": condition2, "3": condition3,
                             "4": rejected, "5": condition5}
    if plan["m_null"] < PROTOCOL["required_margin_newtons"]:
        _cause(summary, 1, "m_null_below", ["design"], None)
    if plan["m_signal"] < PROTOCOL["required_margin_newtons"]:
        _cause(summary, 1, "m_signal_below", ["design"], None)
    summary["missing_causes"] = missing_causes(summary)
    summary["class"] = classify(summary)
    summary["evidence_state"] = evidence_state(summary, plan)
    return summary


def dual_pair(plus, minus, plan, control):
    """Stationarity section 6.5 and 9, through its own frame functions."""
    view = {"planned": {"late": {"box": plan["box"]}}, "walk_newtons": plan["walk"]}
    def row(result):
        return {"contrast_newtons": result["contrast"], "half_newtons": plan["half"],
                "optical_raw_newtons": result["raw"]}
    a, b = row(plus), row(minus)
    audit = prior.dual_truth_pair(a, b, plus["truth"], minus["truth"], view)
    return {"tuple": prior.dual(a, b, view, control),
            "covered": audit["d"] <= audit["d_half"] and (
                audit["sigma"] <= audit["sigma_half"]),
            "d_ratio": audit["d"]/audit["d_half"],
            "sigma_ratio": audit["sigma"]/audit["sigma_half"]}


def evidence_state(summary, plan):
    """Section 9.2 states, in order. They concern this criterion and class only."""
    if summary["class"] == "reference_margin_positive_conditional":
        return "certified"
    if summary["class"] in ("operational_failure", "inconclusive_invalid_envelope"):
        return None
    M2 = 2*prior.STRUCTURAL
    required = PROTOCOL["required_margin_newtons"]
    worst = 0.0
    for row in summary.get("witnesses", ()):
        if "error" not in row:
            continue
        worst = max(worst, row["error"])
        h = row["error"]+M2
        low, high = row["predicted"]
        if row["control"] == "force-decoupled":
            distance = max(low-(row["contrast"]+h), (row["contrast"]-h)-high)
        else:
            distance = abs(row["contrast"])-h
        if distance < required:
            row["pointwise_margin"] = distance
            summary["pointwise_failure"] = True
    worst = max(worst, summary.get("witness_search", {}).get("best_error", 0.0))
    summary["m_uniform_up"] = plan["lower"]-2*worst-M2
    if summary.get("pointwise_failure"):
        return "admissible_pointwise_failure"
    if summary["m_uniform_up"] < required:
        return "uniform_criterion_nonqualification"
    return "certification_gap"


def _note(summary, row):
    summary["failing_count"] = summary.get("failing_count", 0)+1
    if len(summary["failing"]) < ROW_LIMIT:
        summary["failing"].append(row)


def _cause(summary, condition, cause, reference, ratio=None):
    """Condition causes, section 14. Fixed names, so this cannot grow with rows."""
    if cause not in PROTOCOL["condition_causes"][str(condition)]:
        raise ValueError(f"undeclared cause: {cause}")
    table = summary.setdefault("condition_causes", {}).setdefault(str(condition), {})
    row = table.setdefault(cause, {"count": 0, "first": reference, "worst": None,
                                   "worst_row": None})
    row["count"] += 1
    if ratio is not None and (row["worst"] is None or ratio > row["worst"]):
        row["worst"], row["worst_row"] = ratio, reference


def missing_causes(summary):
    """A false condition with no recorded cause stays visible in results."""
    causes = summary.get("condition_causes", {})
    return [c for c, value in sorted(summary["conditions"].items())
            if not value and not causes.get(c)]


def _operational(summary, row):
    summary["operational_count"] = summary.get("operational_count", 0)+1
    if len(summary["operational"]) < ROW_LIMIT:
        summary["operational"].append(row)


def _witnesses(config, plan, summary, seed, cohort, detector):
    """Six single-realisation witnesses. They never supply a bound."""
    out = []
    rejected = True
    for control, sign in (("force-decoupled", 1), ("force-decoupled", -1),
                          ("opposite-phase", 1), ("opposite-phase", -1),
                          ("force-decoupled", 2), ("opposite-phase", 2)):
        draws = draw(config, seed, control, 1, "witness:"+cohort)
        faults = admissible(draws)
        row = {"control": control, "sign": sign, "faults": faults}
        if faults:
            summary["witnesses"] = out+[row]
            return None
        path = witness_noise(draws, 1 if sign > 0 else -1)
        try:
            result = assess(draws, plan, detector=detector, noise_path=path)
        except OperationalFailure as error:
            row["operational"] = str(error)
            out.append(row)
            rejected = False
            _cause(summary, 4, "witness_operational", [seed, control, sign])
            continue
        row.update(contrast=result["contrast"], error=result["error"],
                   predicted=result["predicted"], resolved=result["resolved"],
                   overlap=result["overlap"])
        if control == "force-decoupled" and (result["resolved"] or result["overlap"]):
            rejected = False
            _cause(summary, 4, "witness_not_rejected", [seed, control, sign])
        if result["error"] > plan["half"]:
            rejected = False
            _cause(summary, 4, "witness_outside_half", [seed, control, sign],
                   result["error"]/plan["half"])
        out.append(row)
    summary["witnesses"] = out
    return rejected


def classify(summary):
    """First match wins, section 9. Validity is decided before any margin."""
    c = summary["conditions"]
    if summary["operational"]:
        return "operational_failure"
    if not c["5"]:
        return "inconclusive_invalid_envelope"
    if c["2"] and c["3"] and not (c["1"] and c["4"]):
        return "seeded_pass_not_robust"
    if not (c["2"] and c["3"]):
        return "negative"
    return "reference_margin_positive_conditional"


def public_plan(plan):
    keys = ("valid", "reason", "E_N", "E_S", "half", "lower", "upper", "m_null",
            "m_signal", "rho")
    out = {key: plan.get(key) for key in keys}
    out["classes"] = plan.get("classes", {})
    return out


def rank_statement():
    """H8 and H9 by exact arithmetic, with no floating point."""
    from fractions import Fraction as F
    def rank(rows):
        rows = [list(map(F, r)) for r in rows]
        count, column = 0, 0
        while count < len(rows) and column < len(rows[0]):
            pivot = next((r for r in range(count, len(rows)) if rows[r][column]), None)
            if pivot is None:
                column += 1
                continue
            rows[count], rows[pivot] = rows[pivot], rows[count]
            for r in range(len(rows)):
                if r != count and rows[r][column]:
                    factor = rows[r][column]/rows[count][column]
                    rows[r] = [x-factor*y for x, y in zip(rows[r], rows[count])]
            count += 1
            column += 1
        return count
    T, k, L = F(95, 100), F(9, 10), F(5, 100)
    # Columns: recoil, instant, lagged, lab-fixed, reference-only.
    J = [[T, T, T*F(1, 2), 0, F(1)], [0, 0, 0, T, 0],
         [T*k, T*k, T*F(1, 10), 0, F(9, 10)], [0, 0, 0, T*k, 0],
         [L, L, L/2, L, F(21, 20)], [L, L, L/2, L, F(1, 10)]]
    identical = all(row[0] == row[1] for row in J)
    gains = [[1, -1, 0, 0], [0, 1, -1, 0], [0, 0, 1, -1]]
    return {"rank": rank(J), "columns": 5, "recoil_instant_identical": identical,
            "gain_scale_factors": 4, "pairwise_rank": rank(gains)}


INVALID_CLASSES = tuple(PROTOCOL["hypothesis_completeness"]["invalid_classes"])
POSITIVE_CLASS = "reference_margin_positive_conditional"
S09_NAME = "S09-common-force"
S11_NAME = "S11-label-within-window"


def _completeness(results):
    """Declared keys against the record. Duplicates make it ambiguous."""
    keys = [tuple(r["config"]) for r in results]
    declared = set(configurations())
    return {"declared": len(declared), "present": len(set(keys)),
            "duplicates": sorted({k for k in keys if keys.count(k) > 1}),
            "missing": sorted(declared-set(keys)),
            "unknown": sorted(set(keys)-declared)}


def s11_scoped_fact(by):
    """A literal count of S11 rows. It is not H11 and carries no evidence claim."""
    rows = [by[arch, S11_NAME, "primary"] for arch in ARCHS
            if (arch, S11_NAME, "primary") in by]
    valid = [r for r in rows if r["class"] not in INVALID_CLASSES]
    return {"expected": len(ARCHS), "present": len(rows), "valid": len(valid),
            "positive": sum(r["class"] == POSITIVE_CLASS for r in valid)}


def evaluate_hypotheses(results):
    """Section 9 completeness. A missing or invalid row is never support."""
    state = _completeness(results)
    names = [f"H{i}" for i in range(1, 12)]
    if state["duplicates"] or state["unknown"]:
        return dict({name: "inconclusive" for name in names}, completeness=state,
                    s11_no_certified_rows=None)
    by = {tuple(r["config"]): r for r in results}
    thresholds = PROTOCOL["hypothesis_thresholds"]
    b1, r1 = (B1, S05_NAME, "primary"), (R1, S05_NAME, "primary")
    r2, r3 = (R2, S05_NAME, "primary"), (R3, S05_NAME, "primary")
    narrow, absolute = (R2, S05_NAME, "R2-N"), (R1, S05_NAME, "R1-abs")

    def valid(*keys):
        return all(k in by and by[k]["class"] not in INVALID_CLASSES for k in keys)

    def co_primary(key):
        if not valid(key):
            return "inconclusive"
        return "supported" if by[key]["class"] == POSITIVE_CLASS else (
            "certification_not_met")

    def excess(key):
        design_row = by[key]["design"]
        return design_row["E_S"]-design_row["E_N"]

    def ratio(top, bottom, test):
        if not valid(top, bottom) or excess(bottom) <= 0:
            return "inconclusive"
        return "supported" if test(excess(top)/excess(bottom)) else "refuted"

    limit = thresholds["mimic_excess_ratio_maximum_H3"]
    h3_states = [ratio(r, b1, lambda x: x <= limit) for r in (r1, r3)]
    settings = prior.scenario_settings(S05_NAME)
    window = LATE[B1]
    floor = bound_plain(B1, dict(settings, s_p=0.0, s_r=0.0), "none", "primary", window)
    label_b1 = bound_plain(B1, settings, "none", "primary", window)-floor
    label_r2 = max(bound_plain(R2, settings, "none", "primary", window),
                   bound_plain(R2, settings, "none", "primary", window,
                               form="chain"))-floor
    h4 = h5 = h7 = h10 = "inconclusive"
    if valid(b1, r2):
        h4 = "supported" if label_r2 >= thresholds[
            "full_class_label_ratio_minimum_H4"]*label_b1 else "refuted"
    if valid(b1, narrow):
        h5 = "supported" if (by[narrow]["design"]["E_N"]-floor)/label_b1 <= thresholds[
            "label_term_ratio_maximum_H5"] else "refuted"
    s09 = (R2, S09_NAME, "primary")
    if valid(s09):
        witness = detector_design(s09)
        plain = detector_design(s09, witness=False)
        if witness["status"] == plain["status"] == "bounded":
            h7 = "supported" if witness["A_unflag"]/plain["A_unflag"] <= thresholds[
                "detection_ratio_maximum_H7"] else "refuted"
    rank = rank_statement()
    complete = not state["missing"] and all(
        r["class"] not in INVALID_CLASSES for r in results)
    separated = any(r.get("lag_state") == "instant_or_short_lag_separated"
                    for r in results)
    h8 = h9 = "inconclusive"
    if complete:
        h8 = "supported" if rank["pairwise_rank"] == rank["gain_scale_factors"]-1 else (
            "refuted")
    if separated or not rank["recoil_instant_identical"]:
        h9 = "refuted"
    elif complete:
        h9 = "supported"
    if valid(r3):
        try:
            _, detail = bound_r3(settings, "none", "primary", LATE[R3])
            added = {}
            for terms in detail["terms"].values():
                for name, value in terms.items():
                    added[name] = added.get(name, 0.0)+value
            h10 = "supported" if max(added, key=added.get) == "T_k" else "refuted"
        except bounds.Unproved:
            pass
    fact = s11_scoped_fact(by)
    if fact["positive"]:
        h11 = "refuted"
    elif fact["valid"] == fact["expected"]:
        h11 = "supported"
    else:
        h11 = "inconclusive"
    return {
        "H1": co_primary(r3), "H2": co_primary(r1),
        "H3": ("inconclusive" if "inconclusive" in h3_states else
               "supported" if h3_states == ["supported"]*2 else "refuted"),
        "H4": h4, "H5": h5, "H6": ratio(absolute, b1, lambda x: x >= thresholds[
            "absolute_scale_mimic_ratio_minimum_H6"]),
        "H7": h7, "H8": h8, "H9": h9, "H10": h10, "H11": h11,
        "completeness": state, "s11_no_certified_rows": fact}


S05_NAME = "S05-label-retained"


def envelope_sweep():
    """Exploratory, one at a time. It tests dependence and validates nothing."""
    spec = PROTOCOL["exploratory_envelope_sweep"]
    settings = prior.scenario_settings(S05_NAME)
    config = (R3, S05_NAME, "primary")
    rows = []
    for name, key in (("L_nl", "L_nl"), ("k_b", "k_b"), ("h_b", "h_b_newtons")):
        for value in spec[key]:
            if len(rows) >= spec["maximum_evaluations"]:
                raise OperationalFailure("sweep cap exceeded")
            _sweep.clear()
            _sweep[name] = value
            try:
                plan = design(config)
            finally:
                _sweep.clear()
            rows.append({"parameter": name, "value": value, "valid": plan["valid"],
                         "m_null": plan.get("m_null"),
                         "m_signal": plan.get("m_signal")})
    return rows


def enforce_record_budget(record):
    """Byte and node caps of section 14. Exceeding one is a retained failure."""
    text = canonical(record)
    limits = PROTOCOL["limits"]
    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")
    return len(text)


def canonical(record):
    return (json.dumps(record, sort_keys=True, ensure_ascii=True,
                       separators=(",", ":"), allow_nan=False)+"\n").encode("ascii")


def count_nodes(value):
    if isinstance(value, dict):
        return 1+sum(1+count_nodes(v) for v in value.values())
    if isinstance(value, list):
        return 1+sum(count_nodes(v) for v in value)
    return 1


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


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 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 = check_runtime(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 = range(low, high+1)
    clock = {"used": 0.0}
    record = {
        "study": PROTOCOL["study"], "protocol_revision": PROTOCOL["protocol_revision"],
        "environment": ENVIRONMENT, "kind": "reference_gain_cohort", "mode": mode,
        "status": "virtual_lab_simulated_not_physical_evidence",
        "source": {"commit": commit, "mode": mode,
                   "argv": ["pf002_reference_gain_v1.py", mode]},
        "runtime": runtime, "implementation": opened,
        "r1_enclosures": r1_enclosure_table(),
        "configurations": [run_configuration(c, seeds, mode, search_clock=clock)
                           for c in configurations()]}
    record["hypotheses"] = evaluate_hypotheses(record["configurations"])
    record["rank"] = rank_statement()
    if mode == "exploratory":
        record["envelope_sweep"] = envelope_sweep()
    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 ("exploratory", "confirmatory")
            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())
