From be1b28b4b741471dbc2b73d8613c866edfc46e39 Mon Sep 17 00:00:00 2001 From: ahrazzle <38987266+ahrazzle@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:37:50 -0600 Subject: [PATCH 1/3] Add competitive groove occupancy kinetics and evidence corner envelopes --- .../report.md | 39 +++ .../summary.json | 108 ++++++ ...idate_competitive_binding_and_envelopes.py | 309 ++++++++++++++++++ ...est_competitive_occupancy_and_envelopes.py | 206 ++++++++++++ vh/bridge/__init__.py | 3 + vh/bridge/occupancy.py | 147 +++++++++ vh/graph/__init__.py | 7 + vh/graph/evidence.py | 113 ++++++- 8 files changed, 931 insertions(+), 1 deletion(-) create mode 100644 auto-research/2026-11-06-E-competitive-binding-envelopes/report.md create mode 100644 auto-research/2026-11-06-E-competitive-binding-envelopes/summary.json create mode 100644 scripts/validate_competitive_binding_and_envelopes.py create mode 100644 tests/test_competitive_occupancy_and_envelopes.py diff --git a/auto-research/2026-11-06-E-competitive-binding-envelopes/report.md b/auto-research/2026-11-06-E-competitive-binding-envelopes/report.md new file mode 100644 index 0000000..7ec7c7c --- /dev/null +++ b/auto-research/2026-11-06-E-competitive-binding-envelopes/report.md @@ -0,0 +1,39 @@ +# Auto-Research Experiment `2026-11-06-E-competitive-binding-envelopes`: Competitive Two-Ligand Groove Occupancy, Shared-Core Non-Identifiability, and Deterministic Evidence Corner Envelopes + +## Question + +When two ligands compete for a shared receptor or MHC class II groove (for example, paralogous CDR2L and CDR2 peptides sharing an interior 9-mer binding core as established in `project-asma` assay `18456218`), how do we: +1. Compute exact competitive equilibrium and transient Motulsky-Mahan competitive binding kinetics without single-ligand approximations? +2. Characterize the exact concentration locus across which two cross-reactive ligands produce an indistinguishable bulk groove-occupancy readout? +3. Evaluate how source-reported parameter intervals (`Uncertainty.low`, `Uncertainty.high`) propagate across the $2^d$ corners of an evidence-bound model to detect when an output conclusion straddles a decision threshold, without silently treating interval metadata as a probability distribution? + +## Implementation + +1. **`vh/bridge/occupancy.py`**: + - `competitive_equilibrium_occupancy(cu_a_nm, kd_a_nm, cu_b_nm, kd_b_nm)`: exact Gaddum two-ligand competitive binding equilibrium returning `occupancy_a`, `occupancy_b`, `occupancy_total`, and `free_receptor_fraction`. + - `shared_core_identifiability_locus(target_total_occupancy, kd_a_nm, kd_b_nm, cu_a_nm)`: solves the affine equivalence locus $C_A / K_{d,A} + C_B / K_{d,B} = O_{\text{total}} / (1 - O_{\text{total}})$ for the concentration $C_B$ that yields identical total groove occupancy alongside $C_A$. + - `competitive_kinetic_occupancy(...)`: exact piecewise $2 \times 2$ Putzer matrix-exponential propagator for coupled Motulsky-Mahan competitive kinetics, bounded in $(0, 1]$ for all $\Delta t \ge 0$ and smooth across the $\Delta \to 0$ equal-rate limit. +2. **`vh/graph/evidence.py`**: + - `OutputEnvelope` and `execute_evidence_envelope(registry, edge, evidence, specs, *, allow_synthetic=False, thresholds=None)`: fail-closed validation that every bound input carries explicit `[low, high]` endpoints bracketing `estimate.value` (`low <= estimate.value <= high`) and satisfying `PortSpec` bounds before invoking the registered model at the nominal point and all $2^d$ distinct interval corners, classifying any supplied output decision threshold as `"above_across_envelope"`, `"below_across_envelope"`, or `"straddles_threshold"`. + +## Three-Authority Validation (`scripts/validate_competitive_binding_and_envelopes.py`) + +| Validation authority | Scope checked | Quantitative result | +| --- | --- | --- | +| **Authority 1: Exact rational arithmetic (`fractions.Fraction`)** | Three competitive equilibrium cases, five shared-core equivalence pairs at $O_{\text{total}} = 3/4$, and 8-corner ($2^3$) competitive evidence envelope bounds (`3/15` to `24/27` for $O_A$; `5/9` lower bound for $O_{\text{total}}$) | Maximum absolute error **$1.11 \times 10^{-16}$** (1 float ulp; **$0.0$** on rational-denominator cases and locus pairs) | +| **Authority 2: Elementary mass-action network (`vh.graph.reactions.ReactionNetwork`)** | Three-species elementary competitive network (`R`, `RL_A`, `RL_B`) with exact rational left-nullspace conservation basis and RK4 trajectory (`dt = 0.001 h`) | Exact rational conservation basis `R + RL_A + RL_B = 1` (per-reaction residual `0`); max conservation drift **$6.00 \times 10^{-15}$**; trajectory agreement vs. Putzer propagator **$7.83 \times 10^{-12}$** | +| **Authority 3: Adaptive 8th-order Runge-Kutta (`scipy.integrate.solve_ivp` `DOP853`)** | 301-point transient competitive overshoot trajectory ($C_A = 30\text{ nM}, K_{d,A} = 10\text{ nM}, k_{\text{off},A} = 0.2\text{ h}^{-1}$ vs. fast competitor $C_B = 40\text{ nM}, K_{d,B} = 40\text{ nM}, k_{\text{off},B} = 4.0\text{ h}^{-1}$) | Max absolute error **$1.98 \times 10^{-15}$** ($O_A$) and **$2.69 \times 10^{-14}$** ($O_B$); fast competitor $B$ peaks at **$0.4280$** ($t = 0.40\text{ h}$) before decaying to its **$0.2000$** equilibrium (**$+0.2280$** kinetic overshoot) | + +## Reproduce + +```sh +python3 scripts/validate_competitive_binding_and_envelopes.py +python3 scripts/validate_evidence_bindings.py +pytest -q -m "not network" +node web/test_engines.mjs +``` + +## Limits + +- `execute_evidence_envelope` evaluates the $2^d$ corners of source-reported input intervals; it is exact for componentwise monotonic functions on the hyperrectangle (such as Gaddum competitive occupancy with respect to each concentration and dissociation constant), does not bound interior extrema of non-monotonic functions, and does not assign probability mass to the interval. +- `competitive_kinetic_occupancy` assumes excess/buffered free ligand concentrations on each step interval $[t_{i-1}, t_i]$; when receptor concentration is comparable to total ligand concentration (ligand depletion), use `vh.graph.reactions.ReactionNetwork` with explicit free-ligand species instead. diff --git a/auto-research/2026-11-06-E-competitive-binding-envelopes/summary.json b/auto-research/2026-11-06-E-competitive-binding-envelopes/summary.json new file mode 100644 index 0000000..8c83fd9 --- /dev/null +++ b/auto-research/2026-11-06-E-competitive-binding-envelopes/summary.json @@ -0,0 +1,108 @@ +{ + "evidence_corner_envelope_validation": { + "evaluated_corners": 8, + "fail_closed_rejections_verified": 3, + "occ_a_envelope": [ + 0.2, + 0.8888888888888888 + ], + "occ_a_exact_rational_envelope": [ + "3/15", + "24/27" + ], + "occ_a_nominal": 0.6, + "occ_a_threshold_0_50_status": "straddles_threshold", + "occ_total_envelope": [ + 0.5555555555555556, + 0.9333333333333333 + ], + "occ_total_exact_rational_low": "5/9", + "occ_total_threshold_0_40_status": "above_across_envelope" + }, + "experiment": "2026-11-06-E-competitive-binding-envelopes", + "max_equilibrium_abs_error": 1.1102230246251565e-16, + "motulsky_mahan_kinetics_validation": { + "equilibrium_occupancy_b": 0.2, + "grid_points": 301, + "max_abs_error_vs_dop853_occupancy_a": 1.9845236565174673e-15, + "max_abs_error_vs_dop853_occupancy_b": 2.6867397195928788e-14, + "overshoot_amplitude_b": 0.22802786902750533, + "reaction_network_conservation_basis": [ + [ + 1, + 1, + 1 + ] + ], + "reaction_network_max_conservation_drift": 5.995204332975845e-15, + "reaction_network_trajectory_max_abs_error": 7.82610781735471e-12, + "transient_peak_occupancy_b": 0.42802786902750534, + "transient_peak_time_h": 0.4 + }, + "rational_equilibrium_cases": [ + { + "case": "balanced_competition", + "max_abs_error": 0.0, + "occupancy_a_exact": "3/5", + "occupancy_b_exact": "1/5", + "occupancy_total_exact": "4/5" + }, + { + "case": "high_affinity_dominance", + "max_abs_error": 0.0, + "occupancy_a_exact": "5/8", + "occupancy_b_exact": "1/4", + "occupancy_total_exact": "7/8" + }, + { + "case": "low_occupancy_tail", + "max_abs_error": 1.1102230246251565e-16, + "occupancy_a_exact": "1/23", + "occupancy_b_exact": "2/23", + "occupancy_total_exact": "3/23" + } + ], + "shared_core_identifiability_locus": { + "equivalent_pairs": [ + { + "cu_a_nm": 0.0, + "cu_b_nm": 75.0, + "occupancy_a": 0.0, + "occupancy_b": 0.75, + "occupancy_total": 0.75 + }, + { + "cu_a_nm": 5.0, + "cu_b_nm": 62.5, + "occupancy_a": 0.125, + "occupancy_b": 0.625, + "occupancy_total": 0.75 + }, + { + "cu_a_nm": 12.5, + "cu_b_nm": 43.75, + "occupancy_a": 0.3125, + "occupancy_b": 0.4375, + "occupancy_total": 0.75 + }, + { + "cu_a_nm": 20.0, + "cu_b_nm": 25.0, + "occupancy_a": 0.5, + "occupancy_b": 0.25, + "occupancy_total": 0.75 + }, + { + "cu_a_nm": 30.0, + "cu_b_nm": 0.0, + "occupancy_a": 0.75, + "occupancy_b": 0.0, + "occupancy_total": 0.75 + } + ], + "kd_a_nm": 10.0, + "kd_b_nm": 25.0, + "max_abs_error": 0.0, + "target_total_occupancy": 0.75 + } +} diff --git a/scripts/validate_competitive_binding_and_envelopes.py b/scripts/validate_competitive_binding_and_envelopes.py new file mode 100644 index 0000000..1c2504f --- /dev/null +++ b/scripts/validate_competitive_binding_and_envelopes.py @@ -0,0 +1,309 @@ +#!/usr/bin/env python3 +"""Validate competitive two-ligand groove occupancy, Motulsky-Mahan kinetics, +shared-core non-identifiability, and deterministic evidence corner envelopes +against three independent mathematical/numerical authorities: + 1. Exact rational arithmetic (fractions.Fraction) + 2. Elementary mass-action ODE reaction network (vh.graph.reactions.ReactionNetwork) + 3. High-order adaptive Runge-Kutta integration (scipy.integrate.solve_ivp DOP853) +""" +from __future__ import annotations + +from fractions import Fraction +import json +from pathlib import Path +import sys + +import numpy as np +from scipy.integrate import solve_ivp + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from vh.bridge.occupancy import ( # noqa: E402 + competitive_equilibrium_occupancy, + competitive_kinetic_occupancy, + shared_core_identifiability_locus, +) +from vh.graph import ( # noqa: E402 + ContractError, + Edge, + EvidenceInput, + ModelRegistry, + ModelSpec, + PortSpec, + Quantity, + Uncertainty, + execute_evidence_envelope, +) +from vh.graph.reactions import Reaction, ReactionNetwork, Species # noqa: E402 + + +def _fraction_competitive_eq(ca: Fraction, kda: Fraction, cb: Fraction, kdb: Fraction) -> dict[str, Fraction]: + alpha = ca / kda + beta = cb / kdb + denom = Fraction(1) + alpha + beta + return { + "occupancy_a": alpha / denom, + "occupancy_b": beta / denom, + "occupancy_total": (alpha + beta) / denom, + "free_receptor_fraction": Fraction(1) / denom, + } + + +def validate_all() -> dict: + # Authority 1: Exact rational arithmetic for Gaddum equilibrium and shared-core locus + rational_cases = [ + ("balanced_competition", Fraction(30), Fraction(10), Fraction(20), Fraction(20)), + ("high_affinity_dominance", Fraction(15), Fraction(3), Fraction(50), Fraction(25)), + ("low_occupancy_tail", Fraction(1, 2), Fraction(10), Fraction(3, 2), Fraction(15)), + ] + eq_results = [] + max_eq_error = 0.0 + for name, ca, kda, cb, kdb in rational_cases: + exact = _fraction_competitive_eq(ca, kda, cb, kdb) + num = competitive_equilibrium_occupancy(float(ca), float(kda), float(cb), float(kdb)) + err = max(abs(num[k] - float(exact[k])) for k in exact) + max_eq_error = max(max_eq_error, err) + assert err <= 1e-15, f"{name}: equilibrium error {err}" + eq_results.append({ + "case": name, + "occupancy_a_exact": f"{exact['occupancy_a'].numerator}/{exact['occupancy_a'].denominator}", + "occupancy_b_exact": f"{exact['occupancy_b'].numerator}/{exact['occupancy_b'].denominator}", + "occupancy_total_exact": f"{exact['occupancy_total'].numerator}/{exact['occupancy_total'].denominator}", + "max_abs_error": err, + }) + + # Shared-core affine non-identifiability locus: + # For target O_total = 3/4 (normalized total affinity = 3), any cu_a in [0, 3*Kd_A] + # paired with cu_b = shared_core_identifiability_locus(3/4, Kd_A, Kd_B, cu_a) yields O_total = 3/4. + target_occ = 0.75 + kda_locus, kdb_locus = 10.0, 25.0 + locus_pairs = [] + max_locus_error = 0.0 + for cu_a in (0.0, 5.0, 12.5, 20.0, 30.0): + cu_b = shared_core_identifiability_locus(target_occ, kda_locus, kdb_locus, cu_a) + check = competitive_equilibrium_occupancy(cu_a, kda_locus, cu_b, kdb_locus) + err = abs(check["occupancy_total"] - target_occ) + max_locus_error = max(max_locus_error, err) + assert err <= 1e-15 + locus_pairs.append({ + "cu_a_nm": cu_a, + "cu_b_nm": cu_b, + "occupancy_a": check["occupancy_a"], + "occupancy_b": check["occupancy_b"], + "occupancy_total": check["occupancy_total"], + }) + + # Authority 2 & 3: Motulsky-Mahan transient overshoot vs DOP853 and ReactionNetwork + # Ligand A: slow binder, high affinity (Cu_A = 30 nM, Kd_A = 10 nM, koff_A = 0.2 /h => kon_A = 0.02 /(nM*h)) + # Ligand B: fast binder, lower affinity (Cu_B = 40 nM, Kd_B = 40 nM, koff_B = 4.0 /h => kon_B = 0.10 /(nM*h)) + # Equilibrium: O_A_inf = 3/(1+3+1) = 0.60, O_B_inf = 1/(1+3+1) = 0.20, O_tot_inf = 0.80. + # Transiently, fast ligand B overshoots > 0.63 around t ~ 0.45 h before decaying to 0.20! + cu_a, kd_a, koff_a = 30.0, 10.0, 0.2 + cu_b, kd_b, koff_b = 40.0, 40.0, 4.0 + kon_a = koff_a / kd_a + kon_b = koff_b / kd_b + t_grid = np.linspace(0.0, 30.0, 301) + + mm = competitive_kinetic_occupancy(t_grid, cu_a, kd_a, koff_a, cu_b, kd_b, koff_b, oa0=0.0, ob0=0.0) + + def rhs(_t, y): + oa, ob = y + free = 1.0 - oa - ob + return [kon_a * cu_a * free - koff_a * oa, kon_b * cu_b * free - koff_b * ob] + + dop = solve_ivp(rhs, (0.0, 30.0), [0.0, 0.0], t_eval=t_grid, method="DOP853", rtol=1e-13, atol=1e-15, max_step=0.02) + assert dop.success + max_dop_err_a = float(np.max(np.abs(mm["occupancy_a"] - dop.y[0]))) + max_dop_err_b = float(np.max(np.abs(mm["occupancy_b"] - dop.y[1]))) + assert max(max_dop_err_a, max_dop_err_b) <= 1e-13 + + peak_b_idx = int(np.argmax(mm["occupancy_b"])) + peak_b_val = float(mm["occupancy_b"][peak_b_idx]) + peak_b_time = float(t_grid[peak_b_idx]) + eq_check = competitive_equilibrium_occupancy(cu_a, kd_a, cu_b, kd_b) + assert peak_b_val > eq_check["occupancy_b"] + 0.20, "Expected pronounced Motulsky-Mahan kinetic overshoot" + + # Authority 2: Elementary mass-action ReactionNetwork with exact receptor conservation R + RL_A + RL_B = 1 + net = ReactionNetwork( + species=( + Species("R", ("synthetic_groove",)), + Species("RL_A", ("synthetic_groove",)), + Species("RL_B", ("synthetic_groove",)), + ), + reactions=( + Reaction("bind_A", {"R": 1}, {"RL_A": 1}, kon_a * cu_a, "1/s", ("motulsky_mahan",)), + Reaction("unbind_A", {"RL_A": 1}, {"R": 1}, koff_a, "1/s", ("motulsky_mahan",)), + Reaction("bind_B", {"R": 1}, {"RL_B": 1}, kon_b * cu_b, "1/s", ("motulsky_mahan",)), + Reaction("unbind_B", {"RL_B": 1}, {"R": 1}, koff_b, "1/s", ("motulsky_mahan",)), + ), + context={"compartment": "well_mixed_groove_assay"}, + provenance=("motulsky_mahan_1984",), + ) + basis = net.conservation_basis() + assert basis == ({"R": Fraction(1), "RL_A": Fraction(1), "RL_B": Fraction(1)},) + residuals = net.pool_residuals({"R": 1, "RL_A": 1, "RL_B": 1}) + assert all(v == 0 for v in residuals.values()) + traj = net.simulate({"R": 1.0, "RL_A": 0.0, "RL_B": 0.0}, t_grid, max_step_s=0.001) + rn_final = traj.final + rn_eq_err = max(abs(rn_final["RL_A"] - eq_check["occupancy_a"]), abs(rn_final["RL_B"] - eq_check["occupancy_b"])) + assert rn_eq_err <= 1e-3 # At t=30, exp(-lambda_minus * 30) ~ 1.5e-4; let's also check trajectory match vs mm! + rn_traj_err = float(np.max(np.abs(traj.concentrations[:, 1] - mm["occupancy_a"])) + + np.max(np.abs(traj.concentrations[:, 2] - mm["occupancy_b"]))) + assert rn_traj_err <= 1e-10 + rn_conservation_drift = float(np.max(np.abs(np.sum(traj.concentrations, axis=1) - 1.0))) + assert rn_conservation_drift <= 1e-14 + + # Deterministic 2^3 corner-envelope validation and threshold straddling + ctx = {"system": "mhc_ii_competitive_groove"} + in_specs = { + "cu_a": PortSpec("concentration", "nM", "unbound_groove", ctx, minimum=0.0), + "kd_a": PortSpec("dissociation_constant", "nM", "unbound_groove", ctx, minimum=0.1), + "cu_b": PortSpec("concentration", "nM", "unbound_groove", ctx, minimum=0.0), + "kd_b": PortSpec("dissociation_constant", "nM", "unbound_groove", ctx, minimum=0.1), + } + out_specs = { + "occ_a": PortSpec("occupancy_fraction", "1", "bound_receptor", ctx, minimum=0.0, maximum=1.0), + "occ_b": PortSpec("occupancy_fraction", "1", "bound_receptor", ctx, minimum=0.0, maximum=1.0), + "occ_total": PortSpec("occupancy_fraction", "1", "bound_receptor", ctx, minimum=0.0, maximum=1.0), + } + reg = ModelRegistry() + + def comp_model(inputs): + res = competitive_equilibrium_occupancy( + inputs["cu_a"].value, + inputs["kd_a"].value, + inputs["cu_b"].value, + inputs["kd_b"].value, + ) + return { + "occ_a": Quantity(res["occupancy_a"], "occupancy_fraction", "1", "bound_receptor", ctx, ("gaddum_a",)), + "occ_b": Quantity(res["occupancy_b"], "occupancy_fraction", "1", "bound_receptor", ctx, ("gaddum_b",)), + "occ_total": Quantity(res["occupancy_total"], "occupancy_fraction", "1", "bound_receptor", ctx, ("gaddum_tot",)), + } + + reg.register( + ModelSpec( + "competitive_gaddum", + in_specs, + out_specs, + comp_model, + "two-ligand competitive equilibrium groove occupancy", + "validated against exact rational arithmetic", + ("gaddum_1937",), + ) + ) + edge = Edge("ligand_pool", "mhc_ii_groove", "competitive_binding", model="competitive_gaddum") + + ev = { + "cu_a": EvidenceInput( + "EV_CUA", "synthetic", + Quantity(30.0, "concentration", "nM", "unbound_groove", ctx, ("synth",)), + "synthetic_bench", "case:1", "synthetic interval", + Uncertainty("bounds", "2-fold exposure range", 15.0, 60.0), + ), + "kd_a": EvidenceInput( + "EV_KDA", "synthetic", + Quantity(10.0, "dissociation_constant", "nM", "unbound_groove", ctx, ("synth",)), + "synthetic_bench", "case:1", "synthetic interval", + Uncertainty("bounds", "affinity bracket", 5.0, 20.0), + ), + "cu_b": EvidenceInput( + "EV_CUB", "synthetic", + Quantity(20.0, "concentration", "nM", "unbound_groove", ctx, ("synth",)), + "synthetic_bench", "case:1", "synthetic interval", + Uncertainty("bounds", "competitor exposure range", 10.0, 40.0), + ), + "kd_b": EvidenceInput( + "EV_KDB", "synthetic", + Quantity(20.0, "dissociation_constant", "nM", "unbound_groove", ctx, ("synth",)), + "synthetic_bench", "case:1", "fixed comparator Kd", + Uncertainty("bounds", "degenerate point interval", 20.0, 20.0), + ), + } + + env = execute_evidence_envelope( + reg, edge, ev, in_specs, allow_synthetic=True, + thresholds={"occ_a": 0.50, "occ_total": 0.40}, + ) + # 3 non-degenerate intervals x 1 degenerate interval = 2^3 = 8 corners + assert env["occ_a"].corner_count == 8 + # Exact rational bounds for occ_a: + # min occ_a at (cu_a=15, kd_a=20, cu_b=40, kd_b=20): alpha=3/4, beta=2 => (3/4)/(15/4) = 1/5 = 0.20 + # max occ_a at (cu_a=60, kd_a=5, cu_b=10, kd_b=20): alpha=12, beta=1/2 => 12/(27/2) = 8/9 + # nominal occ_a at (30, 10, 20, 20): alpha=3, beta=1 => 3/5 = 0.60 + assert abs(env["occ_a"].nominal.value - 0.60) <= 1e-15 + assert abs(env["occ_a"].envelope_low.value - float(Fraction(3, 15))) <= 1e-15 + assert abs(env["occ_a"].envelope_high.value - float(Fraction(24, 27))) <= 1e-15 + assert env["occ_a"].threshold_status == "straddles_threshold" + # Min occ_total at (cu_a=15, kd_a=20, cu_b=10, kd_b=20): (3/4 + 1/2)/(1 + 3/4 + 1/2) = (5/4)/(9/4) = 5/9 > 0.40 + assert abs(env["occ_total"].envelope_low.value - float(Fraction(5, 9))) <= 1e-15 + assert env["occ_total"].threshold_status == "above_across_envelope" + + # Fail-closed rejection count across adversarial envelope inputs + rejected = 0 + bad_envelopes = [ + # Missing endpoints (None, None) + {**ev, "cu_a": EvidenceInput("EV_NONE", "synthetic", ev["cu_a"].estimate, "s", "l", "lim", Uncertainty("unquantified", "none"))}, + # Estimate outside [low, high] + {**ev, "cu_a": EvidenceInput("EV_OUT", "synthetic", ev["cu_a"].estimate, "s", "l", "lim", Uncertainty("bounds", "bad", 40.0, 60.0))}, + # Low endpoint violates PortSpec minimum=0.1 + {**ev, "kd_a": EvidenceInput("EV_LOW", "synthetic", ev["kd_a"].estimate, "s", "l", "lim", Uncertainty("bounds", "bad", 0.05, 20.0))}, + ] + for bad in bad_envelopes: + try: + execute_evidence_envelope(reg, edge, bad, in_specs, allow_synthetic=True) + except ContractError: + rejected += 1 + assert rejected == len(bad_envelopes) + + return { + "experiment": "2026-11-06-E-competitive-binding-envelopes", + "rational_equilibrium_cases": eq_results, + "max_equilibrium_abs_error": max_eq_error, + "shared_core_identifiability_locus": { + "target_total_occupancy": target_occ, + "kd_a_nm": kda_locus, + "kd_b_nm": kdb_locus, + "max_abs_error": max_locus_error, + "equivalent_pairs": locus_pairs, + }, + "motulsky_mahan_kinetics_validation": { + "grid_points": len(t_grid), + "max_abs_error_vs_dop853_occupancy_a": max_dop_err_a, + "max_abs_error_vs_dop853_occupancy_b": max_dop_err_b, + "transient_peak_occupancy_b": peak_b_val, + "transient_peak_time_h": peak_b_time, + "equilibrium_occupancy_b": eq_check["occupancy_b"], + "overshoot_amplitude_b": peak_b_val - eq_check["occupancy_b"], + "reaction_network_conservation_basis": [[1, 1, 1]], + "reaction_network_trajectory_max_abs_error": rn_traj_err, + "reaction_network_max_conservation_drift": rn_conservation_drift, + }, + "evidence_corner_envelope_validation": { + "evaluated_corners": env["occ_a"].corner_count, + "occ_a_nominal": env["occ_a"].nominal.value, + "occ_a_envelope": [env["occ_a"].envelope_low.value, env["occ_a"].envelope_high.value], + "occ_a_exact_rational_envelope": ["3/15", "24/27"], + "occ_a_threshold_0_50_status": env["occ_a"].threshold_status, + "occ_total_envelope": [env["occ_total"].envelope_low.value, env["occ_total"].envelope_high.value], + "occ_total_exact_rational_low": "5/9", + "occ_total_threshold_0_40_status": env["occ_total"].threshold_status, + "fail_closed_rejections_verified": rejected, + }, + } + + +def main() -> int: + summary = validate_all() + out_dir = ROOT / "auto-research/2026-11-06-E-competitive-binding-envelopes" + out_dir.mkdir(parents=True, exist_ok=True) + out_path = out_dir / "summary.json" + out_path.write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8") + print(f"OK: {out_path.relative_to(ROOT)} verified against Fraction, ReactionNetwork, and DOP853") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_competitive_occupancy_and_envelopes.py b/tests/test_competitive_occupancy_and_envelopes.py new file mode 100644 index 0000000..5513eaa --- /dev/null +++ b/tests/test_competitive_occupancy_and_envelopes.py @@ -0,0 +1,206 @@ +"""Tests for competitive two-ligand groove occupancy, Motulsky-Mahan kinetics, +shared-core non-identifiability, and deterministic evidence corner envelopes. +""" +from __future__ import annotations + +from decimal import Decimal +from fractions import Fraction +import numpy as np +import pytest +from scipy.integrate import solve_ivp + +from vh.bridge import ( + competitive_equilibrium_occupancy, + competitive_kinetic_occupancy, + equilibrium_occupancy, + kinetic_occupancy, + shared_core_identifiability_locus, +) +from vh.graph import ( + ContractError, + Edge, + EvidenceInput, + ModelRegistry, + ModelSpec, + PortSpec, + Quantity, + Uncertainty, + execute_evidence_envelope, +) + + +def test_competitive_equilibrium_matches_exact_rationals_and_single_ligand_limit(): + res = competitive_equilibrium_occupancy(30.0, 10.0, 20.0, 20.0) + assert res["occupancy_a"] == pytest.approx(float(Fraction(3, 5)), abs=1e-15) + assert res["occupancy_b"] == pytest.approx(float(Fraction(1, 5)), abs=1e-15) + assert res["occupancy_total"] == pytest.approx(float(Fraction(4, 5)), abs=1e-15) + assert res["free_receptor_fraction"] == pytest.approx(float(Fraction(1, 5)), abs=1e-15) + + # Zero competitor B reduces identically to single-ligand Hill-Langmuir occupancy + c_grid = np.array([0.0, 2.5, 10.0, 40.0]) + comp0 = competitive_equilibrium_occupancy(c_grid, 10.0, np.zeros_like(c_grid), 25.0) + single = equilibrium_occupancy(c_grid, 10.0) + np.testing.assert_allclose(comp0["occupancy_a"], single, rtol=0, atol=1e-15) + np.testing.assert_allclose(comp0["occupancy_b"], 0.0, rtol=0, atol=1e-15) + + +@pytest.mark.parametrize( + "ca,kda,cb,kdb", + [ + (-1.0, 10.0, 5.0, 10.0), + (1.0, 0.0, 5.0, 10.0), + (1.0, 10.0, -0.1, 10.0), + (1.0, 10.0, 5.0, -2.0), + (float("nan"), 10.0, 5.0, 10.0), + (1.0, float("inf"), 5.0, 10.0), + ], +) +def test_competitive_equilibrium_rejects_invalid_inputs(ca, kda, cb, kdb): + with pytest.raises(ValueError): + competitive_equilibrium_occupancy(ca, kda, cb, kdb) + + +def test_shared_core_identifiability_locus_preserves_total_occupancy(): + target = 0.75 + kda, kdb = 10.0, 25.0 + for cu_a in (0.0, 5.0, 12.5, 20.0, 30.0): + cu_b = shared_core_identifiability_locus(target, kda, kdb, cu_a) + res = competitive_equilibrium_occupancy(cu_a, kda, cu_b, kdb) + assert res["occupancy_total"] == pytest.approx(target, abs=1e-15) + + # Exceeding target_total_occupancy with ligand A alone must fail + with pytest.raises(ValueError, match="exceeds"): + shared_core_identifiability_locus(0.50, 10.0, 25.0, 15.0) + with pytest.raises(ValueError): + shared_core_identifiability_locus(1.0, 10.0, 25.0, 0.0) + + +def test_competitive_kinetics_matches_dop853_and_captures_transient_overshoot(): + t = np.linspace(0.0, 25.0, 251) + cu_a, kd_a, koff_a = 30.0, 10.0, 0.2 + cu_b, kd_b, koff_b = 40.0, 40.0, 4.0 + mm = competitive_kinetic_occupancy(t, cu_a, kd_a, koff_a, cu_b, kd_b, koff_b, oa0=0.0, ob0=0.0) + + kon_a, kon_b = koff_a / kd_a, koff_b / kd_b + sol = solve_ivp( + lambda _t, y: [ + kon_a * cu_a * (1.0 - y[0] - y[1]) - koff_a * y[0], + kon_b * cu_b * (1.0 - y[0] - y[1]) - koff_b * y[1], + ], + (0.0, 25.0), + [0.0, 0.0], + t_eval=t, + method="DOP853", + rtol=1e-13, + atol=1e-15, + max_step=0.02, + ) + assert sol.success + np.testing.assert_allclose(mm["occupancy_a"], sol.y[0], rtol=0, atol=1e-13) + np.testing.assert_allclose(mm["occupancy_b"], sol.y[1], rtol=0, atol=1e-13) + + # Fast competitor B transiently overshoots >2x its equilibrium occupancy (0.20) + eq = competitive_equilibrium_occupancy(cu_a, kd_a, cu_b, kd_b) + assert np.max(mm["occupancy_b"]) > 2.0 * eq["occupancy_b"] + + # Zero competitor B matches single-ligand kinetic_occupancy exactly, including equal-koff degenerate branch + single = kinetic_occupancy(t, np.full_like(t, cu_a), kd_a, koff_a, o0=0.1) + comp_zero = competitive_kinetic_occupancy(t, cu_a, kd_a, koff_a, 0.0, kd_a, koff_a, oa0=0.1, ob0=0.0) + np.testing.assert_allclose(comp_zero["occupancy_a"], single, rtol=0, atol=1e-14) + np.testing.assert_allclose(comp_zero["occupancy_b"], 0.0, rtol=0, atol=1e-15) + + +def test_execute_evidence_envelope_computes_exact_corners_and_threshold_classifications(): + ctx = {"system": "competitive_groove"} + in_specs = { + "cu_a": PortSpec("concentration", "nM", "unbound", ctx, minimum=0.0), + "kd_a": PortSpec("dissociation_constant", "nM", "unbound", ctx, minimum=0.1), + "cu_b": PortSpec("concentration", "nM", "unbound", ctx, minimum=0.0), + "kd_b": PortSpec("dissociation_constant", "nM", "unbound", ctx, minimum=0.1), + } + out_specs = { + "occ_a": PortSpec("occupancy_fraction", "1", "bound", ctx, minimum=0.0, maximum=1.0), + "occ_total": PortSpec("occupancy_fraction", "1", "bound", ctx, minimum=0.0, maximum=1.0), + } + calls = [] + + def model(inputs): + calls.append(dict(inputs)) + res = competitive_equilibrium_occupancy( + inputs["cu_a"].value, inputs["kd_a"].value, inputs["cu_b"].value, inputs["kd_b"].value + ) + return { + "occ_a": Quantity(res["occupancy_a"], "occupancy_fraction", "1", "bound", ctx, ("m",)), + "occ_total": Quantity(res["occupancy_total"], "occupancy_fraction", "1", "bound", ctx, ("m",)), + } + + reg = ModelRegistry() + reg.register(ModelSpec("gaddum", in_specs, out_specs, model, "domain", "val", ("src",)), model) + edge = Edge("pool", "groove", "bind", model="gaddum") + + ev = { + "cu_a": EvidenceInput( + "R_CUA", "recorded", Quantity(30.0, "concentration", "nM", "unbound", ctx, ("p",)), + "S", "L", "lim", Uncertainty("bounds", "range", 15.0, 60.0), + ), + "kd_a": EvidenceInput( + "R_KDA", "recorded", Quantity(10.0, "dissociation_constant", "nM", "unbound", ctx, ("p",)), + "S", "L", "lim", Uncertainty("bounds", "range", 5.0, 20.0), + ), + "cu_b": EvidenceInput( + "R_CUB", "recorded", Quantity(20.0, "concentration", "nM", "unbound", ctx, ("p",)), + "S", "L", "lim", Uncertainty("bounds", "range", 10.0, 40.0), + ), + "kd_b": EvidenceInput( + "R_KDB", "recorded", Quantity(20.0, "dissociation_constant", "nM", "unbound", ctx, ("p",)), + "S", "L", "lim", Uncertainty("bounds", "point", 20.0, 20.0), + ), + } + + env = execute_evidence_envelope( + reg, edge, ev, in_specs, thresholds={"occ_a": 0.50, "occ_total": 0.99} + ) + # 1 nominal call + 8 unique corner calls = 9 model invocations + assert len(calls) == 9 + assert env["occ_a"].corner_count == 8 + assert env["occ_a"].nominal_within_corners is True + assert env["occ_a"].nominal.value == pytest.approx(0.60, abs=1e-15) + assert env["occ_a"].envelope_low.value == pytest.approx(0.20, abs=1e-15) + assert env["occ_a"].envelope_high.value == pytest.approx(float(Fraction(8, 9)), abs=1e-15) + assert env["occ_a"].threshold_status == "straddles_threshold" + assert env["occ_total"].threshold_status == "below_across_envelope" + + +def test_execute_evidence_envelope_fails_closed_before_calling_model(): + ctx = {"system": "in_vitro"} + spec = PortSpec("rate_constant", "1/h", "unbound_plasma", ctx, minimum=0.0, maximum=10.0) + calls = [] + reg = ModelRegistry() + reg.register( + ModelSpec("pass", {"in": spec}, {"out": spec}, lambda x: calls.append(x) or {"out": x["in"]}, "d", "v", ("s",)), + lambda x: calls.append(x) or {"out": x["in"]}, + ) + edge = Edge("a", "b", "r", model="pass") + q = Quantity(2.0, "rate_constant", "1/h", "unbound_plasma", ctx, ("src",)) + + bad_records = [ + # Missing uncertainty endpoints + EvidenceInput("E1", "recorded", q, "S", "L", "lim", Uncertainty("unquantified", "none")), + # Estimate outside [low, high] + EvidenceInput("E2", "recorded", q, "S", "L", "lim", Uncertainty("CI95", "shifted", 2.5, 4.0)), + # Low endpoint below PortSpec.minimum + EvidenceInput("E3", "recorded", q, "S", "L", "lim", Uncertainty("CI95", "negative low", -0.5, 4.0)), + # High endpoint above PortSpec.maximum + EvidenceInput("E4", "recorded", q, "S", "L", "lim", Uncertainty("CI95", "excess high", 1.0, 12.0)), + # Lossy Decimal endpoint + EvidenceInput("E5", "recorded", q, "S", "L", "lim", Uncertainty("CI95", "decimal", Decimal("1.1"), 3.0)), + ] + for bad in bad_records: + with pytest.raises(ContractError): + execute_evidence_envelope(reg, edge, {"in": bad}, {"in": spec}) + assert calls == [] + + # Unknown threshold output port rejected + good = EvidenceInput("E_OK", "recorded", q, "S", "L", "lim", Uncertainty("CI95", "ok", 1.0, 3.0)) + with pytest.raises(ContractError, match="unknown output port"): + execute_evidence_envelope(reg, edge, {"in": good}, {"in": spec}, thresholds={"missing_port": 1.5}) diff --git a/vh/bridge/__init__.py b/vh/bridge/__init__.py index b5f5c11..bdada76 100644 --- a/vh/bridge/__init__.py +++ b/vh/bridge/__init__.py @@ -2,8 +2,11 @@ from .occupancy import ( # noqa: F401 binding_free_energy_from_kd, + competitive_equilibrium_occupancy, + competitive_kinetic_occupancy, equilibrium_occupancy, kd_from_binding_free_energy, kinetic_occupancy, + shared_core_identifiability_locus, target_engagement, ) diff --git a/vh/bridge/occupancy.py b/vh/bridge/occupancy.py index 963bac6..cf4dda2 100644 --- a/vh/bridge/occupancy.py +++ b/vh/bridge/occupancy.py @@ -38,6 +38,153 @@ def equilibrium_occupancy(cu_nm, kd_nm): return cu / (cu + kd_nm) +def competitive_equilibrium_occupancy(cu_a_nm, kd_a_nm: float, cu_b_nm, kd_b_nm: float) -> dict: + """Exact Gaddum competitive equilibrium for two ligands sharing one receptor or groove. + + Given unbound concentrations Cu_A, Cu_B >= 0 and dissociation constants Kd_A, Kd_B > 0: + O_A = (Cu_A / Kd_A) / (1 + Cu_A / Kd_A + Cu_B / Kd_B) + O_B = (Cu_B / Kd_B) / (1 + Cu_A / Kd_A + Cu_B / Kd_B) + O_total = O_A + O_B + """ + if kd_a_nm <= 0 or kd_b_nm <= 0 or not (np.isfinite(kd_a_nm) and np.isfinite(kd_b_nm)): + raise ValueError("dissociation constants kd_a_nm and kd_b_nm must be finite and positive") + ca = np.asarray(cu_a_nm, dtype=float) + cb = np.asarray(cu_b_nm, dtype=float) + if np.any(~np.isfinite(ca)) or np.any(~np.isfinite(cb)) or np.any(ca < 0) or np.any(cb < 0): + raise ValueError("unbound concentrations must be finite and nonnegative") + alpha = ca / float(kd_a_nm) + beta = cb / float(kd_b_nm) + denom = 1.0 + alpha + beta + occ_a = alpha / denom + occ_b = beta / denom + occ_total = (alpha + beta) / denom + if np.ndim(ca) == 0 and np.ndim(cb) == 0: + return { + "occupancy_a": float(occ_a), + "occupancy_b": float(occ_b), + "occupancy_total": float(occ_total), + "free_receptor_fraction": float(1.0 / denom), + } + return { + "occupancy_a": occ_a, + "occupancy_b": occ_b, + "occupancy_total": occ_total, + "free_receptor_fraction": 1.0 / denom, + } + + +def shared_core_identifiability_locus( + target_total_occupancy: float, + kd_a_nm: float, + kd_b_nm: float, + cu_a_nm: float, +) -> float: + """Concentration Cu_B of ligand B yielding target_total_occupancy alongside Cu_A. + + When two cross-reactive ligands (for example paralogous peptides sharing a 9-mer + MHC-II binding core) contribute equally to a bulk occupancy or activation readout + O_total = (Cu_A/Kd_A + Cu_B/Kd_B) / (1 + Cu_A/Kd_A + Cu_B/Kd_B), any pair (Cu_A, Cu_B) + on the affine locus Cu_A/Kd_A + Cu_B/Kd_B = O_total / (1 - O_total) produces the + identical total occupancy. + """ + if not (0.0 <= target_total_occupancy < 1.0 and np.isfinite(target_total_occupancy)): + raise ValueError("target_total_occupancy must be finite and in [0, 1)") + if kd_a_nm <= 0 or kd_b_nm <= 0 or not (np.isfinite(kd_a_nm) and np.isfinite(kd_b_nm)): + raise ValueError("kd_a_nm and kd_b_nm must be finite and positive") + if cu_a_nm < 0 or not np.isfinite(cu_a_nm): + raise ValueError("cu_a_nm must be finite and nonnegative") + total_normalized_affinity = target_total_occupancy / (1.0 - target_total_occupancy) + remaining_affinity = total_normalized_affinity - (cu_a_nm / kd_a_nm) + if remaining_affinity < -1e-15: + raise ValueError("cu_a_nm alone exceeds target_total_occupancy") + return float(max(0.0, remaining_affinity) * kd_b_nm) + + +def competitive_kinetic_occupancy( + t_h, + cu_a_nm, + kd_a_nm: float, + koff_a_per_h: float, + cu_b_nm, + kd_b_nm: float, + koff_b_per_h: float, + oa0: float = 0.0, + ob0: float = 0.0, +) -> dict: + """Exact piecewise 2x2 matrix-exponential (Motulsky-Mahan) solution for competitive kinetics. + + Solves on each interval [t_{i-1}, t_i] with midpoint unbound concentrations: + dO_A/dt = kon_A * Cu_A * (1 - O_A - O_B) - koff_A * O_A + dO_B/dt = kon_B * Cu_B * (1 - O_A - O_B) - koff_B * O_B + where kon_A = koff_A / Kd_A and kon_B = koff_B / Kd_B. + """ + if kd_a_nm <= 0 or kd_b_nm <= 0 or koff_a_per_h <= 0 or koff_b_per_h <= 0: + raise ValueError("Kd and koff parameters must be positive") + if oa0 < 0 or ob0 < 0 or oa0 + ob0 > 1.0 + 1e-12: + raise ValueError("initial occupancies must be nonnegative and sum to at most 1") + t = np.asarray(t_h, dtype=float) + if t.ndim != 1 or len(t) == 0 or np.any(np.diff(t) < 0): + raise ValueError("t_h must be a nonempty 1D nondecreasing array") + ca = np.broadcast_to(np.asarray(cu_a_nm, dtype=float), t.shape) + cb = np.broadcast_to(np.asarray(cu_b_nm, dtype=float), t.shape) + if np.any(ca < 0) or np.any(cb < 0) or np.any(~np.isfinite(ca)) or np.any(~np.isfinite(cb)): + raise ValueError("unbound concentrations must be finite and nonnegative") + + kon_a = float(koff_a_per_h) / float(kd_a_nm) + kon_b = float(koff_b_per_h) / float(kd_b_nm) + k2 = float(koff_a_per_h) + k4 = float(koff_b_per_h) + + oa = np.empty_like(t) + ob = np.empty_like(t) + oa[0] = float(oa0) + ob[0] = float(ob0) + + for i in range(1, len(t)): + dt = float(t[i] - t[i - 1]) + if dt == 0.0: + oa[i] = oa[i - 1] + ob[i] = ob[i - 1] + continue + c_a = 0.5 * float(ca[i] + ca[i - 1]) + c_b = 0.5 * float(cb[i] + cb[i - 1]) + k1 = kon_a * c_a + k3 = kon_b * c_b + m11 = k1 + k2 + m12 = k1 + m21 = k3 + m22 = k3 + k4 + det = k1 * k4 + k2 * k3 + k2 * k4 + oa_inf = (k1 * k4) / det + ob_inf = (k2 * k3) / det + + tau = 0.5 * (m11 + m22) + half_diff = 0.5 * (m11 - m22) + delta = float(np.sqrt(half_diff * half_diff + m12 * m21)) + lam_minus = tau - delta + lam_plus = tau + delta + e_minus = float(np.exp(-lam_minus * dt)) + e_plus = float(np.exp(-lam_plus * dt)) + c0 = 0.5 * (e_minus + e_plus) + if delta * dt >= 1e-8: + s_coeff = (e_minus - e_plus) / (2.0 * delta) + else: + s_coeff = float(np.exp(-tau * dt)) * dt * (1.0 - (delta * dt) ** 2 / 6.0) + + da0 = oa[i - 1] - oa_inf + db0 = ob[i - 1] - ob_inf + # exp(-M dt) = c0 * I - s_coeff * (M - tau * I) + oa[i] = oa_inf + (c0 - s_coeff * half_diff) * da0 - (s_coeff * m12) * db0 + ob[i] = ob_inf - (s_coeff * m21) * da0 + (c0 + s_coeff * half_diff) * db0 + + return { + "time_h": t, + "occupancy_a": oa, + "occupancy_b": ob, + "occupancy_total": oa + ob, + } + + def kinetic_occupancy(t_h, cu_nm, kd_nm, koff_per_h, o0=0.0): """Exact piecewise solution assuming Cu is constant within each interval.""" t = np.asarray(t_h, dtype=float) diff --git a/vh/graph/__init__.py b/vh/graph/__init__.py index b7df993..242bf8b 100644 --- a/vh/graph/__init__.py +++ b/vh/graph/__init__.py @@ -25,4 +25,11 @@ from .core import Edge, Graph, Node, Schema # noqa: F401 from .contracts import ContractError, ModelRegistry, ModelSpec, PortSpec, Quantity # noqa: F401 +from .evidence import ( # noqa: F401 + EvidenceInput, + OutputEnvelope, + Uncertainty, + execute_evidence, + execute_evidence_envelope, +) from . import algorithms # noqa: F401 diff --git a/vh/graph/evidence.py b/vh/graph/evidence.py index 510eaa3..1a2d688 100644 --- a/vh/graph/evidence.py +++ b/vh/graph/evidence.py @@ -8,10 +8,11 @@ from __future__ import annotations from dataclasses import dataclass +from itertools import product import json from types import MappingProxyType from collections.abc import Mapping -from numbers import Integral, Rational +from numbers import Integral, Rational, Real from .contracts import ContractError, ModelRegistry, PortSpec, Quantity, _text, _finite from .core import Edge @@ -122,3 +123,113 @@ def execute_evidence(registry: ModelRegistry, edge: Edge, bound = {name: record.bind(ports[name], allow_synthetic=allow_synthetic) for name, record in records.items()} return registry.execute(edge, MappingProxyType(bound)) + + +@dataclass(frozen=True) +class OutputEnvelope: + """Deterministic corner-envelope summary for an output port. + + Corner bounds summarize evaluation at the 2^d endpoints of source-reported + input intervals; they do not define a probability distribution or confidence + interval, and interior extrema of non-monotonic models are not bounded by + corner evaluation alone. + """ + nominal: Quantity + envelope_low: Quantity + envelope_high: Quantity + corner_count: int + nominal_within_corners: bool + threshold: float | int | Rational | None = None + threshold_status: str | None = None + + +def execute_evidence_envelope( + registry: ModelRegistry, + edge: Edge, + evidence: Mapping[str, EvidenceInput], + specs: Mapping[str, PortSpec], + *, + allow_synthetic: bool = False, + thresholds: Mapping[str, float | int | Rational] | None = None, +) -> dict[str, OutputEnvelope]: + """Evaluate a registered scalar model at nominal evidence and all 2^d interval corners. + + Requires every input to carry explicit uncertainty endpoints [low, high] that + bracket its point estimate (low <= estimate.value <= high) and satisfy its + PortSpec contract before the model is invoked on any point. + """ + if not isinstance(evidence, Mapping) or not isinstance(specs, Mapping): + raise ContractError("evidence and specs must be mappings") + if thresholds is not None and not isinstance(thresholds, Mapping): + raise ContractError("thresholds must be a mapping or None") + records, ports = dict(evidence), dict(specs) + if set(records) != set(ports): + raise ContractError("evidence ports mismatch") + if any(not isinstance(v, EvidenceInput) for v in records.values()): + raise ContractError("all bindings must be EvidenceInput") + + threshold_map = {} if thresholds is None else dict(thresholds) + for out_name, tau in threshold_map.items(): + _text(out_name, "threshold port") + _finite(tau, f"{out_name} threshold") + _audit_scalar(tau) + + ordered_names = sorted(records) + bound_nominal: dict[str, Quantity] = {} + endpoint_choices: list[tuple[Quantity, ...]] = [] + + for name in ordered_names: + rec = records[name] + spec = ports[name] + nom_q = rec.bind(spec, allow_synthetic=allow_synthetic) + unc = rec.uncertainty + if unc.low is None or unc.high is None: + raise ContractError(f"{rec.record_id}: envelope execution requires explicit uncertainty endpoints") + _audit_scalar(unc.low) + _audit_scalar(unc.high) + if not (unc.low <= nom_q.value <= unc.high): + raise ContractError( + f"{rec.record_id}: point estimate {nom_q.value} lies outside uncertainty interval [{unc.low}, {unc.high}]" + ) + low_q = Quantity(unc.low, nom_q.quantity, nom_q.unit, nom_q.basis, nom_q.context, nom_q.provenance) + high_q = Quantity(unc.high, nom_q.quantity, nom_q.unit, nom_q.basis, nom_q.context, nom_q.provenance) + spec.check(low_q, f"{rec.record_id}.low") + spec.check(high_q, f"{rec.record_id}.high") + bound_nominal[name] = nom_q + endpoint_choices.append((low_q,) if unc.low == unc.high else (low_q, high_q)) + + nominal_out = registry.execute(edge, MappingProxyType(bound_nominal)) + unknown_thresholds = set(threshold_map) - set(nominal_out) + if unknown_thresholds: + raise ContractError(f"threshold specified for unknown output port: {sorted(unknown_thresholds)[0]}") + + corner_outputs: list[dict[str, Quantity]] = [] + for combo in product(*endpoint_choices): + corner_in = {name: q for name, q in zip(ordered_names, combo)} + corner_outputs.append(registry.execute(edge, MappingProxyType(corner_in))) + + envelopes: dict[str, OutputEnvelope] = {} + for out_name, nom_q in nominal_out.items(): + series = [c[out_name] for c in corner_outputs] + low_q = min(series, key=lambda q: q.value) + high_q = max(series, key=lambda q: q.value) + within = bool(low_q.value <= nom_q.value <= high_q.value) + tau = threshold_map.get(out_name) + status = None + if tau is not None: + if low_q.value > tau: + status = "above_across_envelope" + elif high_q.value < tau: + status = "below_across_envelope" + else: + status = "straddles_threshold" + envelopes[out_name] = OutputEnvelope( + nominal=nom_q, + envelope_low=low_q, + envelope_high=high_q, + corner_count=len(corner_outputs), + nominal_within_corners=within, + threshold=tau, + threshold_status=status, + ) + return envelopes From 29a8b1a07a742b9260bdc38ecd538b39d87902cd Mon Sep 17 00:00:00 2001 From: ahrazzle <38987266+ahrazzle@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:53:20 -0600 Subject: [PATCH 2/3] Fix competitive-binding envelope tests to the ModelRegistry API First review of this branch: two tests called ModelRegistry.register(spec, fn), but the registry takes the ModelSpec alone (the callable lives in the spec), and one fail-closed case expected a Decimal uncertainty endpoint to reach the envelope when Uncertainty construction already rejects non-Real endpoints. Test-only changes; the occupancy/envelope implementation is unchanged and its validator (Fraction / ReactionNetwork / DOP853) passes as checked in. --- tests/test_competitive_occupancy_and_envelopes.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/test_competitive_occupancy_and_envelopes.py b/tests/test_competitive_occupancy_and_envelopes.py index 5513eaa..4875435 100644 --- a/tests/test_competitive_occupancy_and_envelopes.py +++ b/tests/test_competitive_occupancy_and_envelopes.py @@ -135,7 +135,7 @@ def model(inputs): } reg = ModelRegistry() - reg.register(ModelSpec("gaddum", in_specs, out_specs, model, "domain", "val", ("src",)), model) + reg.register(ModelSpec("gaddum", in_specs, out_specs, model, "domain", "val", ("src",))) edge = Edge("pool", "groove", "bind", model="gaddum") ev = { @@ -178,7 +178,6 @@ def test_execute_evidence_envelope_fails_closed_before_calling_model(): reg = ModelRegistry() reg.register( ModelSpec("pass", {"in": spec}, {"out": spec}, lambda x: calls.append(x) or {"out": x["in"]}, "d", "v", ("s",)), - lambda x: calls.append(x) or {"out": x["in"]}, ) edge = Edge("a", "b", "r", model="pass") q = Quantity(2.0, "rate_constant", "1/h", "unbound_plasma", ctx, ("src",)) @@ -192,9 +191,11 @@ def test_execute_evidence_envelope_fails_closed_before_calling_model(): EvidenceInput("E3", "recorded", q, "S", "L", "lim", Uncertainty("CI95", "negative low", -0.5, 4.0)), # High endpoint above PortSpec.maximum EvidenceInput("E4", "recorded", q, "S", "L", "lim", Uncertainty("CI95", "excess high", 1.0, 12.0)), - # Lossy Decimal endpoint - EvidenceInput("E5", "recorded", q, "S", "L", "lim", Uncertainty("CI95", "decimal", Decimal("1.1"), 3.0)), ] + # A lossy Decimal endpoint never even constructs: Uncertainty itself + # rejects non-Real endpoints, so it cannot reach the model either. + with pytest.raises(ContractError): + Uncertainty("CI95", "decimal", Decimal("1.1"), 3.0) for bad in bad_records: with pytest.raises(ContractError): execute_evidence_envelope(reg, edge, {"in": bad}, {"in": spec}) From 1f120e1e0b20f96e6974d702ace8dadecefa559c Mon Sep 17 00:00:00 2001 From: ahrazzle <38987266+ahrazzle@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:53:36 -0600 Subject: [PATCH 3/3] Index the competitive-binding contribution in auto-research README --- auto-research/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/auto-research/README.md b/auto-research/README.md index 1b1af5b..5f50726 100644 --- a/auto-research/README.md +++ b/auto-research/README.md @@ -27,6 +27,7 @@ auto-research/ | 2026-11-05 | E | [Clearance reference validation](2026-11-05-E-clearance-reference/report.md) | Exact organ mass balance and linear ODE integral | Mixed references caught; reported sum 17.104405 L/h, dose/AUC 17.103070 L/h | OpenAI Codex / @ahrazzle | | 2026-11-05 | E (partial) | [Reaction and intervention experiments](2026-11-05-E-reaction-experiments/report.md) | Exact kinetics/conservation/commutativity; independent DOP853 | Maximum trajectory error 1.479e-11 mol/L; no biological validation | OpenAI Codex / @ahrazzle | | 2026-11-05 | E | [SBML reaction networks as verified graphs](2026-11-05-E-sbml-import/report.md) | Exact rational algebra; libRoadRunner as independent SBML engine | 3 CC0 BioModels: exact conservation laws, trajectories ≤7e-10, steady states ≤2e-12; positive-mass invariant flags 8 of 49 surveyed models with exact certificates | Claude (Anthropic) | +| 2026-11-06 | E | [Competitive groove occupancy and evidence corner envelopes](2026-11-06-E-competitive-binding-envelopes/report.md) | Exact rational arithmetic (Fraction); elementary mass-action ReactionNetwork; DOP853 | Equilibrium/locus exact to 1 ulp; kinetic propagator vs DOP853 ≤2.7e-14; envelopes fail closed before model invocation | @ahrazzle | | 2026-11-08 | E | [Conserved-flow graphs: topology → venous pressure](2026-11-08-E-vein-flow-graph/report.md) | Exact Hagen–Poiseuille, Windkessel, Starling, R–L solutions; exact Womersley impedance; physiology reference ranges | Steady flow exact to ~1e-16; standing foot venous pressure **88.7 mmHg** vs **85–90** (foot inside range, ankle 0.6 mmHg below); lumped R–L within 1% up to α=0.48, with measured breakdown at high α | OpenCode agent (DeepSeek V4.1 Flash Free) | - [2026-11-06: Explicit evidence bindings](2026-11-06-E-evidence-bindings/report.md): nominal scalar execution with preserved context and uncertainty; exact synthetic mass balance and missing kinetic-input report.