From 46c374445edbe92d8e7dc23df6d55280585d9773 Mon Sep 17 00:00:00 2001 From: Raz Arif Date: Thu, 5 Nov 2026 14:15:03 +0000 Subject: [PATCH 01/12] Add explicit scalar model contracts for graph edges --- README.md | 9 +- .../2026-11-05-E-model-contracts/report.md | 114 +++++++++ .../2026-11-05-E-model-contracts/results.json | 40 ++++ auto-research/README.md | 2 +- docs/model_contracts.md | 73 ++++++ scripts/validate_model_contracts.py | 57 +++++ tests/test_model_contracts.py | 223 ++++++++++++++++++ vh/graph/__init__.py | 5 + vh/graph/contracts.py | 212 +++++++++++++++++ 9 files changed, 731 insertions(+), 4 deletions(-) create mode 100644 auto-research/2026-11-05-E-model-contracts/report.md create mode 100644 auto-research/2026-11-05-E-model-contracts/results.json create mode 100644 docs/model_contracts.md create mode 100644 scripts/validate_model_contracts.py create mode 100644 tests/test_model_contracts.py create mode 100644 vh/graph/contracts.py diff --git a/README.md b/README.md index 22e9cae..b413323 100644 --- a/README.md +++ b/README.md @@ -75,9 +75,11 @@ the structural/relational class of problems — and `vh.graph` proves it. The ho boundary (in [`docs/graph_formalization.md`](docs/graph_formalization.md)): a graph solves *where / what-connects / how-much-flows / is-it-consistent*; it does **not** solve *how-strong / how-fast / how-it-folds* — that stays physics. The real win is a -**typed graph that is also executable**: every edge carries the validated model -behind it, so the graph wires the scales together and lets any part be verified -alone. +**typed graph with explicit model references**: an edge can name a computational +model, and the optional [`ModelRegistry`](docs/model_contracts.md) executes a +registered callable after checking its scalar inputs and outputs. Engine +adapters are not registered automatically; model validation remains separate +from checking interface compatibility. The body is already a graph at every scale — organs joined by blood flow, atoms joined by bonds. Formalized from the real, validated engines: @@ -171,6 +173,7 @@ research tracks, and how to publish work under [`auto-research/`](auto-research/ - **Rohan Arun** ([@rohanarun](https://github.com/rohanarun)) — creator and maintainer; direction and design. - **Claude** (Anthropic) — implemented and validated the engines under the above direction, in pair with the maintainer. +- **OpenAI Codex** — graph interface contracts and validation, under the direction of [@ahrazzle](https://github.com/ahrazzle). New contributors (human or agent): add yourself here in your pull request. See [`auto-research.md`](auto-research.md) for how to help. diff --git a/auto-research/2026-11-05-E-model-contracts/report.md b/auto-research/2026-11-05-E-model-contracts/report.md new file mode 100644 index 0000000..54d2c17 --- /dev/null +++ b/auto-research/2026-11-05-E-model-contracts/report.md @@ -0,0 +1,114 @@ +# Explicit model contracts for graph edges + +- **Track**: E — incremental graph interface work; not the complete SBML milestone +- **Author**: OpenAI Codex, under the direction of [@ahrazzle](https://github.com/ahrazzle) +- **Date**: 2026-11-05 +- **Branch / PR**: `auto/E-model-contracts` +- **Code added**: `vh/graph/contracts.py`, `scripts/validate_model_contracts.py`, + `tests/test_model_contracts.py`; API guide: `docs/model_contracts.md` + +## Question + +`Edge.model` names a computational model, but the existing graph had no execution +registry for that key. Can an explicit dispatcher detect incompatible quantity +semantics, units, reference bases and contexts before a model consumes them? + +## Method + +Added a standard-library-only `ModelRegistry` and immutable `Quantity`, `PortSpec` +and `ModelSpec` declarations. Callers register trusted Python callables explicitly. +All input names, semantic quantity names, units, bases and complete context +mappings must match the registered ports. Scalars must be finite and within any +declared inclusive bounds. Missing or incompatible inputs fail before the +callable runs; incompatible outputs are not returned. Duplicate model keys fail. +Graph deserialization continues to load only a string key and never imports code. + +Model domain and validation statements are required documentation, not proof. +Inputs and models require source identifiers; outputs preserve all their input +and model identifiers as audit lineage. Copies of mappings prevent accidental +mutation after declaration. There is no automatic unit conversion, dynamic import, +graph scheduler or pre-registered adapter to an existing engine. + +The illustrative conversion is deliberately synthetic: +`CLplasma = CLblood * Cblood/Cplasma`. All fixture values are artificial rational +numbers specified in the validation script; no experimental observations, +patient files or fitted parameters are involved. It is an interface example, not +a new physiological model. Existing engines and their calculations are unchanged. + +## Validation — the part that matters + +**Independent authority:** the exact mass-balance definition +`CLplasma = elimination_rate / plasma_concentration`. The dispatcher receives +blood-referenced clearance and a concentration ratio; the comparison instead uses +elimination rate divided directly by plasma concentration, evaluated as exact +rational arithmetic before float conversion. No fitted parameters are used. + +| Quantity | This work | Authority | Absolute error | +|---|---:|---:|---:| +| Synthetic case 1, plasma clearance | 6 L/h | 6 L/h | 0 L/h | +| Synthetic case 2, plasma clearance | 10 L/h | 10 L/h | 0 L/h | +| Synthetic case 3, plasma clearance | 28 L/h | 28 L/h | 0 L/h | +| Synthetic case 4, plasma clearance | 18 L/h | 18 L/h | 0 L/h | + +Maximum observed absolute error is **0 L/h across these four fixtures**, with a +test tolerance of `1e-12 L/h`. An experimental error bar or confidence interval +does not apply to these exact synthetic cases. This is not a claim of zero error +for arbitrary floating-point inputs. Full fixture values and results are in +[`results.json`](results.json). + +Focused verification: **60 tests passed** (`tests/test_model_contracts.py` and +`tests/test_graph.py`, comprising 50 contract cases and 10 existing graph cases). +Regression cases reject blood/plasma reference confusion, incorrect units, +semantic-quantity confusion, changed/missing/extra context, missing/extra input +ports, unregistered model keys, unsupported numeric ranges, missing provenance, +out-of-domain inputs and invalid outputs. Input failures verify that the callable +was not invoked. Tests also check inclusive bounds, immutable metadata, explicit +dispatch after graph round-trip and preservation of provenance lineage. + +Full engine and browser suites are outside this focused validation run; their +status must be checked before merging alongside other changes. + +## Limits + +Matching metadata does not establish biological validity, causal direction, +identifiability, source reliability or model calibration. Relevant conditions +must be supplied by the caller; an omitted biological variable cannot be inferred. +`domain` and `validation` descriptions cannot be automatically certified. Numerical +bounds and exact contexts provide a limited, reviewable validity check only. +Provenance strings are identifiers, not verified evidence supporting an output. + +Only individual scalar model calls are supported. There is no tensor interface, +unit algebra, uncertain-value propagation, automatic conversion, cycle solver, +whole-graph scheduling or SBML importer. Existing engine edges still require +explicit adapters. Structural endpoint rules remain in `Schema`. Callables should +be pure; a rejected output cannot reverse callback side effects, and this is not +a sandbox for untrusted Python. This completes a small part of track E, not its +stated BioModels/SBML/conservation milestone. + +## Reproduce + +From the repository root with its development dependencies installed: + +```bash +PYTHONPATH=. python scripts/validate_model_contracts.py +PYTHONPATH=. python -m pytest -q tests/test_model_contracts.py tests/test_graph.py +git diff --check +``` + +The recorded run used `/tmp/vh-dev/bin/python` (Python 3.12.14) with `PYTHONPATH=.`; +no paid computation or external dataset access is required. Full regression +commands before merge remain `pytest -q`, `python scripts/export_web.py` and +`node web/test_engines.mjs`, as specified by the repository CI. + +## References + +- Existing graph contract: [`vh/graph/core.py`](../../vh/graph/core.py), + `Edge.model`, graph serialization and `Schema` (upstream baseline + `3d75e8e25d6f3fec08e1ccecd424532bccaa1b82`). +- Repository contribution and validation requirements: + [`auto-research.md`](../../auto-research.md) and + [`docs/accuracy_ladder.md`](../../docs/accuracy_ladder.md). +- Validation authority: definition of clearance, elimination rate divided by + the concentration in its stated reference compartment; synthetic fixtures and + exact rational reference calculations in + [`scripts/validate_model_contracts.py`](../../scripts/validate_model_contracts.py). diff --git a/auto-research/2026-11-05-E-model-contracts/results.json b/auto-research/2026-11-05-E-model-contracts/results.json new file mode 100644 index 0000000..83ca2ac --- /dev/null +++ b/auto-research/2026-11-05-E-model-contracts/results.json @@ -0,0 +1,40 @@ +{ + "fixture_type": "synthetic; no experimental uncertainty or parameter fitting", + "authority": "exact elimination rate / plasma concentration; rational input fixtures", + "tolerance_l_h": 1e-12, + "max_absolute_error_l_h": 0.0, + "cases": [ + { + "rate_mg_h": "3", + "blood_concentration_mg_l": "3/10", + "plasma_concentration_mg_l": "1/2", + "computed_clearance_l_h": 6.0, + "analytic_clearance_l_h": 6.0, + "absolute_error_l_h": 0.0 + }, + { + "rate_mg_h": "5", + "blood_concentration_mg_l": "1/4", + "plasma_concentration_mg_l": "1/2", + "computed_clearance_l_h": 10.0, + "analytic_clearance_l_h": 10.0, + "absolute_error_l_h": 0.0 + }, + { + "rate_mg_h": "7", + "blood_concentration_mg_l": "1/2", + "plasma_concentration_mg_l": "1/4", + "computed_clearance_l_h": 28.0, + "analytic_clearance_l_h": 28.0, + "absolute_error_l_h": 0.0 + }, + { + "rate_mg_h": "9", + "blood_concentration_mg_l": "3/4", + "plasma_concentration_mg_l": "1/2", + "computed_clearance_l_h": 18.0, + "analytic_clearance_l_h": 18.0, + "absolute_error_l_h": 0.0 + } + ] +} diff --git a/auto-research/README.md b/auto-research/README.md index baac25d..e8f809e 100644 --- a/auto-research/README.md +++ b/auto-research/README.md @@ -23,4 +23,4 @@ auto-research/ | Date | Track | Contribution | Validated against | Result | Author | |---|---|---|---|---|---| -| _(none yet — be the first; see the tracks in `../auto-research.md`)_ | | | | | | +| 2026-11-05 | E (partial) | [Explicit model contracts](2026-11-05-E-model-contracts/report.md) | Exact scalar mass balance; interface rejection cases | 0 L/h max error on 4 synthetic cases; 60 focused tests pass | OpenAI Codex / @ahrazzle | diff --git a/docs/model_contracts.md b/docs/model_contracts.md new file mode 100644 index 0000000..b9c03d7 --- /dev/null +++ b/docs/model_contracts.md @@ -0,0 +1,73 @@ +# Executing an edge with explicit model contracts + +`Edge.model` is a declarative key. A `ModelRegistry` now lets a caller explicitly +register a callable for that key and execute one edge after checking its inputs. +Loading a graph does not register, import or run any code. Existing physiology +and molecular graph builders do not automatically register their engine models. + +Each `Quantity` must carry a finite real value, semantic quantity name, unit, +reference basis, nonempty context and provenance. Each `PortSpec` requires exact +matches for those semantic fields, including the complete context mapping. For +example, a blood clearance cannot enter a plasma-clearance port even though both +use L/h. A different compound, species, specimen or assay also fails when encoded +in context. Missing observations remain absent; zero is a measured or modeled +number, not a substitute for an unknown value. + +Every input port must be supplied, and extra ports are rejected. Inclusive +minimum/maximum bounds provide simple numerical domain checks. No callable runs +until all inputs pass. Returned quantities must satisfy the output contracts; +outputs inherit source identifiers from the model and all inputs as an audit +trail. That lineage does not assert that a cited source supports the result. + +```python +from vh.graph import Edge, ModelRegistry, ModelSpec, PortSpec, Quantity + +context = {"system": "synthetic", "compound": "test-solute"} +blood = PortSpec("clearance", "L/h", "blood", context, minimum=0) +ratio = PortSpec("concentration_ratio", "1", "blood/plasma", context, + minimum=0.1, maximum=2) +plasma = PortSpec("clearance", "L/h", "plasma", context, minimum=0) + +def quantity(value, spec): + return Quantity(value, spec.quantity, spec.unit, spec.basis, spec.context, + ("artificial example; not a measurement",)) + +registry = ModelRegistry() +registry.register(ModelSpec( + key="synthetic.clearance_to_plasma", + inputs={"blood": blood, "ratio": ratio}, + outputs={"plasma": plasma}, + compute=lambda x: {"plasma": quantity(x["blood"].value * x["ratio"].value, plasma)}, + domain="Artificial example; ratio in [0.1, 2]. No physiological claim.", + validation="Exact mass balance; scripts/validate_model_contracts.py", + provenance=("CLplasma = CLblood * Cblood/Cplasma by definition",), +)) +edge = Edge("blood", "plasma", "converts", model="synthetic.clearance_to_plasma") +result = registry.execute(edge, {"blood": quantity(10, blood), "ratio": quantity(0.6, ratio)}) +assert result["plasma"].value == 6 # L/h, plasma reference +``` + +The conversion is explicit: the registry does not infer units, search for a +conversion path, or silently change reference bases. Four synthetic mass-balance +cases are checked against the exact identity `CLplasma = elimination_rate / Cp`. +They validate dispatch and arithmetic only. Run: + +```bash +PYTHONPATH=. python scripts/validate_model_contracts.py +PYTHONPATH=. python -m pytest -q tests/test_model_contracts.py +``` + +`domain` and `validation` on `ModelSpec` are required documentation. Their truth +cannot be checked from strings; reviewers must assess the sources, context keys +and numerical bounds. A caller who omits a relevant biological condition can +still build an invalid scientific model. Exact string equality is intentionally +conservative: even equivalent unit spellings need a deliberate conversion or +normalization outside the registry. + +This API does not infer causation from graph reachability, execute a whole graph, +solve cycles, propagate uncertainty, certify provenance, or validate clinical +predictions. Edge endpoint types and other structural invariants remain the job +of `Schema`; the registry dispatches the explicitly named model only. Callbacks +should be pure functions: rejecting an invalid output cannot undo callback side +effects. The registry is not a sandbox for untrusted Python. Contract and callable +definitions remain outside serialized graph data. diff --git a/scripts/validate_model_contracts.py b/scripts/validate_model_contracts.py new file mode 100644 index 0000000..42149ea --- /dev/null +++ b/scripts/validate_model_contracts.py @@ -0,0 +1,57 @@ +"""Synthetic model-dispatch benchmark; no clinical or fitted quantities. + +Run with PYTHONPATH=. python scripts/validate_model_contracts.py. +""" + +import json +from fractions import Fraction + +from vh.graph import Edge, ModelRegistry, ModelSpec, PortSpec, Quantity + + +def validate(): + context = {"system": "synthetic", "compound": "test-solute"} + source = ("artificial mass-balance fixture; no experimental measurement",) + blood = PortSpec("clearance", "L/h", "blood", context, minimum=0) + plasma = PortSpec("clearance", "L/h", "plasma", context, minimum=0) + ratio = PortSpec("concentration_ratio", "1", "blood/plasma", context, minimum=0.1, maximum=2) + + def q(value, spec): + return Quantity(value, spec.quantity, spec.unit, spec.basis, spec.context, source) + + registry = ModelRegistry() + registry.register(ModelSpec( + "synthetic.clearance_to_plasma", {"blood": blood, "ratio": ratio}, {"plasma": plasma}, + lambda values: {"plasma": q(values["blood"].value * values["ratio"].value, plasma)}, + domain="Artificial scalar mass balance; ratio in [0.1, 2]. No physiological claim.", + validation="Check against exact elimination rate divided by plasma concentration.", + provenance=("definition of clearance and concentration ratio",), + )) + edge = Edge("blood", "plasma", "converts", model="synthetic.clearance_to_plasma") + fixtures = [ + (Fraction(3), Fraction(3, 10), Fraction(1, 2)), + (Fraction(5), Fraction(1, 4), Fraction(1, 2)), + (Fraction(7), Fraction(1, 2), Fraction(1, 4)), + (Fraction(9), Fraction(3, 4), Fraction(1, 2)), + ] + rows = [] + for rate, blood_c, plasma_c in fixtures: + actual = registry.execute(edge, { + "blood": q(float(rate / blood_c), blood), + "ratio": q(float(blood_c / plasma_c), ratio), + })["plasma"].value + expected = float(rate / plasma_c) # independent exact mass-balance authority + rows.append({"rate_mg_h": str(rate), "blood_concentration_mg_l": str(blood_c), + "plasma_concentration_mg_l": str(plasma_c), + "computed_clearance_l_h": actual, "analytic_clearance_l_h": expected, + "absolute_error_l_h": abs(actual - expected)}) + maximum_error = max(row["absolute_error_l_h"] for row in rows) + if maximum_error > 1e-12: + raise AssertionError(f"mass-balance error {maximum_error} L/h exceeds tolerance") + return {"fixture_type": "synthetic; no experimental uncertainty or parameter fitting", + "authority": "exact elimination rate / plasma concentration; rational input fixtures", + "tolerance_l_h": 1e-12, "max_absolute_error_l_h": maximum_error, "cases": rows} + + +if __name__ == "__main__": + print(json.dumps(validate(), indent=2)) diff --git a/tests/test_model_contracts.py b/tests/test_model_contracts.py new file mode 100644 index 0000000..2d83c7f --- /dev/null +++ b/tests/test_model_contracts.py @@ -0,0 +1,223 @@ +"""Interface failures must stop execution; exact mass balance checks conversion. + +All numbers and contexts below are artificial test fixtures, not patient or +clinical observations. They validate dispatch and arithmetic, not physiology. +""" + +from dataclasses import replace +from fractions import Fraction + +import pytest + +from vh.graph import ContractError, Edge, Graph, ModelRegistry, ModelSpec, PortSpec, Quantity + + +CONTEXT = {"system": "synthetic", "compound": "test-solute"} +SOURCE = ("synthetic fixture; no experimental measurement",) +BLOOD = PortSpec("clearance", "L/h", "blood", CONTEXT, minimum=0) +PLASMA = PortSpec("clearance", "L/h", "plasma", CONTEXT, minimum=0) +RATIO = PortSpec("concentration_ratio", "1", "blood/plasma", CONTEXT, minimum=0.1, maximum=2) +EDGE = Edge("blood", "plasma", "converts", model="synthetic.clearance_to_plasma") + + +def quantity(value, spec=BLOOD, provenance=SOURCE): + return Quantity(value, spec.quantity, spec.unit, spec.basis, spec.context, provenance) + + +def conversion_registry(compute=None): + calls = [] + + def convert(inputs): + calls.append(inputs) + return {"plasma": quantity(inputs["blood"].value * inputs["ratio"].value, PLASMA)} + + registry = ModelRegistry() + registry.register(ModelSpec( + key=EDGE.model, + inputs={"blood": BLOOD, "ratio": RATIO}, + outputs={"plasma": PLASMA}, + compute=compute or convert, + domain="Artificial scalar mass balance; ratio in [0.1, 2]. No physiological claim.", + validation="Independent elimination-rate / plasma-concentration identity in test_model_contracts.py", + provenance=("synthetic conversion definition: CLplasma = CLblood * Cblood/Cplasma",), + )) + return registry, calls + + +def inputs(): + return {"blood": quantity(10), "ratio": quantity(0.6, RATIO)} + + +@pytest.mark.parametrize("rate,blood_c,plasma_c", [ + (Fraction(3), Fraction(3, 10), Fraction(1, 2)), + (Fraction(5), Fraction(1, 4), Fraction(1, 2)), + (Fraction(7), Fraction(1, 2), Fraction(1, 4)), + (Fraction(9), Fraction(3, 4), Fraction(1, 2)), +]) +def test_conversion_against_independent_rate_over_concentration(rate, blood_c, plasma_c): + # Independent authority: rate [mg/h] / Cp [mg/L] defines clearance [L/h]. + # Dispatch instead receives blood-referenced clearance and a concentration + # ratio. Exact rational fixtures were specified without fitting parameters. + registry, calls = conversion_registry() + result = registry.execute(EDGE, { + "blood": quantity(float(rate / blood_c)), + "ratio": quantity(float(blood_c / plasma_c), RATIO), + })["plasma"] + assert result.value == pytest.approx(float(rate / plasma_c), abs=1e-12, rel=0) + assert result.basis == "plasma" and result.unit == "L/h" + assert len(calls) == 1 + + +@pytest.mark.parametrize("field,value", [ + ("unit", "mL/min"), + ("basis", "plasma"), + ("quantity", "flow"), + ("context", {"system": "synthetic", "compound": "another-solute"}), + ("context", {"system": "synthetic"}), + ("context", {**CONTEXT, "species": "human"}), +]) +def test_semantic_mismatch_never_calls_model(field, value): + registry, calls = conversion_registry() + bad = inputs() + bad["blood"] = replace(bad["blood"], **{field: value}) + with pytest.raises(ContractError, match=f"{field} mismatch"): + registry.execute(EDGE, bad) + assert calls == [] + + +@pytest.mark.parametrize("bad", [ + {}, + {"blood": quantity(10)}, + {**inputs(), "unrequested": quantity(1)}, + {**inputs(), 12: quantity(1)}, + {**inputs(), "ratio": 0.6}, + None, +]) +def test_missing_extra_or_untyped_inputs_never_call_model(bad): + registry, calls = conversion_registry() + with pytest.raises(ContractError): + registry.execute(EDGE, bad) + assert calls == [] + + +@pytest.mark.parametrize("key", [None, "missing", "os.system('never execute strings')"]) +def test_only_explicitly_registered_models_execute(key): + registry, calls = conversion_registry() + with pytest.raises(ContractError, match="explicitly registered"): + registry.execute(replace(EDGE, model=key), inputs()) + assert calls == [] + + +@pytest.mark.parametrize("value", [0.09, 2.01]) +def test_outside_declared_domain_never_calls_model(value): + registry, calls = conversion_registry() + bad = {**inputs(), "ratio": quantity(value, RATIO)} + with pytest.raises(ContractError, match="minimum|maximum"): + registry.execute(EDGE, bad) + assert calls == [] + + +@pytest.mark.parametrize("value", [0.1, 2]) +def test_domain_bounds_are_inclusive(value): + registry, calls = conversion_registry() + result = registry.execute(EDGE, {**inputs(), "ratio": quantity(value, RATIO)}) + assert result["plasma"].value == 10 * value + assert len(calls) == 1 + + +@pytest.mark.parametrize("output", [ + {}, + {"plasma": quantity(6)}, # wrong reference basis despite a plausible number + {"plasma": quantity(-1, PLASMA)}, + {"plasma": 6}, + {"plasma": quantity(6, PLASMA), "extra": quantity(1)}, + None, +]) +def test_invalid_outputs_are_not_returned(output): + registry, _ = conversion_registry(lambda _: output) + with pytest.raises(ContractError): + registry.execute(EDGE, inputs()) + + +def test_nonfinite_computed_output_is_rejected(): + registry, _ = conversion_registry(lambda _: {"plasma": quantity(float("inf"), PLASMA)}) + with pytest.raises(ContractError, match="finite"): + registry.execute(EDGE, inputs()) + + +@pytest.mark.parametrize("value", [float("nan"), float("inf"), -float("inf"), True, "10", None, 1j]) +def test_quantity_does_not_convert_missing_or_invalid_measurements_to_numbers(value): + with pytest.raises(ContractError, match="finite real"): + quantity(value) + + +@pytest.mark.parametrize("field,value", [ + ("quantity", ""), ("unit", " "), ("basis", None), ("context", {}), + ("context", {"species": ""}), ("provenance", ()), ("provenance", "not-a-sequence"), +]) +def test_missing_metadata_is_rejected(field, value): + with pytest.raises(ContractError): + replace(quantity(1), **{field: value}) + + +def test_output_keeps_model_and_all_input_provenance_without_duplicates(): + registry, _ = conversion_registry() + result = registry.execute(EDGE, { + "blood": quantity(10, provenance=("synthetic clearance record A",)), + "ratio": quantity(0.6, RATIO, ("synthetic ratio record B",)), + })["plasma"] + assert "synthetic clearance record A" in result.provenance + assert "synthetic ratio record B" in result.provenance + assert "model:synthetic.clearance_to_plasma" in result.provenance + assert len(result.provenance) == len(set(result.provenance)) + + +def test_specs_and_inputs_snapshot_metadata_and_do_not_allow_callback_mutation(): + context = dict(CONTEXT) + spec = replace(BLOOD, context=context) + value = quantity(1, spec) + context["compound"] = "changed-after-construction" + assert spec.context["compound"] == value.context["compound"] == "test-solute" + with pytest.raises(TypeError): + spec.context["compound"] = "mutated" + + def mutate(inputs): + inputs["blood"] = quantity(999) + + registry, _ = conversion_registry(mutate) + with pytest.raises(TypeError): + registry.execute(EDGE, inputs()) + + +def test_duplicate_registration_is_not_silent_replacement(): + model = ModelSpec("test", {"x": BLOOD}, {"y": BLOOD}, lambda x: {"y": x["x"]}, + "synthetic identity", "identity law", SOURCE) + registry = ModelRegistry() + registry.register(model) + with pytest.raises(ContractError, match="already registered"): + registry.register(model) + + +def test_loading_graph_preserves_key_without_executing_or_serializing_callable(): + registry, calls = conversion_registry() + graph = Graph() + graph.add_node("blood", "reference") + graph.add_node("plasma", "reference") + graph.add_edge("blood", "plasma", "converts", model=EDGE.model) + loaded = Graph.from_dict(graph.to_dict()) + assert calls == [] + assert registry.execute(loaded.edges[0], inputs())["plasma"].value == 6 + + +def test_invalid_numeric_bounds_are_rejected(): + with pytest.raises(ContractError, match="minimum must not exceed"): + replace(RATIO, minimum=3) + with pytest.raises(ContractError, match="finite"): + replace(RATIO, maximum=float("inf")) + + +def test_finite_integer_outside_float_range_raises_contract_error(): + with pytest.raises(ContractError, match="outside the supported finite scalar range"): + quantity(10 ** 1000) + with pytest.raises(ContractError, match="outside the supported finite scalar range"): + replace(RATIO, maximum=10 ** 1000) diff --git a/vh/graph/__init__.py b/vh/graph/__init__.py index dacefed..4a7d03e 100644 --- a/vh/graph/__init__.py +++ b/vh/graph/__init__.py @@ -13,7 +13,12 @@ - partial verification: pull out a subgraph and check it on its own; - a place to wire the physics engines (vh.quantum, vh.molecular, vh.body) together and route information between scales. + +ModelRegistry executes an explicitly registered Edge.model with scalar interface +contracts. See docs/model_contracts.md; existing engine adapters are not registered +automatically, and graph reachability is not a claim of biological causation. """ from .core import Edge, Graph, Node, Schema # noqa: F401 +from .contracts import ContractError, ModelRegistry, ModelSpec, PortSpec, Quantity # noqa: F401 from . import algorithms # noqa: F401 diff --git a/vh/graph/contracts.py b/vh/graph/contracts.py new file mode 100644 index 0000000..b4d797f --- /dev/null +++ b/vh/graph/contracts.py @@ -0,0 +1,212 @@ +"""Explicit scalar contracts for executing a named model behind a graph edge. + +This checks declared interfaces, not the truth of a model or its provenance. +Units, reference bases and contexts must match exactly; conversions are models +registered by the caller, never guessed from strings. No engines are registered +automatically and graph deserialization never imports or executes code. +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +from dataclasses import dataclass, replace +from math import isfinite +from numbers import Real +from types import MappingProxyType + +from .core import Edge + + +class ContractError(ValueError): + """An interface is incomplete, incompatible or outside its declared limits.""" + + +def _text(value: str, label: str) -> str: + if not isinstance(value, str) or not value.strip(): + raise ContractError(f"{label} must be a nonempty string") + return value + + +def _finite(value: Real, label: str) -> None: + if isinstance(value, bool) or not isinstance(value, Real): + raise ContractError(f"{label} must be a finite real scalar (not a boolean)") + try: + finite = isfinite(value) + except (OverflowError, ValueError) as exc: + raise ContractError(f"{label} is outside the supported finite scalar range") from exc + if not finite: + raise ContractError(f"{label} must be a finite real scalar (not a boolean)") + + +def _context(context: Mapping[str, str]) -> Mapping[str, str]: + if not isinstance(context, Mapping) or not context: + raise ContractError("context must be a nonempty mapping of named conditions") + snapshot = dict(context) + for key, value in snapshot.items(): + _text(key, "context key") + _text(value, f"context[{key!r}]") + return MappingProxyType(snapshot) + + +def _provenance(provenance: tuple[str, ...]) -> tuple[str, ...]: + if isinstance(provenance, str): + raise ContractError("provenance must be a sequence of source strings") + try: + sources = tuple(provenance) + except TypeError as exc: + raise ContractError("provenance must be a sequence of source strings") from exc + if not sources: + raise ContractError("provenance must include at least one source") + for source in sources: + _text(source, "provenance source") + return sources + + +@dataclass(frozen=True) +class Quantity: + """A finite scalar with explicit semantics and source identifiers. + + ``quantity`` identifies what was measured (e.g. concentration or clearance), + ``basis`` its reference (e.g. plasma), and ``context`` all conditions the + caller considers relevant (species, compound, compartment, assay, etc.). + A missing measurement is absent, not a Quantity with value zero or NaN. + """ + + value: float + quantity: str + unit: str + basis: str + context: Mapping[str, str] + provenance: tuple[str, ...] + + def __post_init__(self): + _finite(self.value, "value") + for name in ("quantity", "unit", "basis"): + _text(getattr(self, name), name) + object.__setattr__(self, "context", _context(self.context)) + object.__setattr__(self, "provenance", _provenance(self.provenance)) + + +@dataclass(frozen=True) +class PortSpec: + """Required semantics and optional inclusive numerical domain for one port. + + Context is an exact match, including keys. A new species, specimen or assay + therefore needs a deliberate new contract, even if the units are identical. + Bounds are in this port's unit and basis. This is not dimensional analysis. + """ + + quantity: str + unit: str + basis: str + context: Mapping[str, str] + minimum: float | None = None + maximum: float | None = None + + def __post_init__(self): + for name in ("quantity", "unit", "basis"): + _text(getattr(self, name), name) + object.__setattr__(self, "context", _context(self.context)) + for name in ("minimum", "maximum"): + value = getattr(self, name) + if value is not None: + _finite(value, name) + if self.minimum is not None and self.maximum is not None and self.minimum > self.maximum: + raise ContractError("minimum must not exceed maximum") + + def check(self, value: Quantity, label: str) -> None: + if not isinstance(value, Quantity): + raise ContractError(f"{label} must be a Quantity") + _finite(value.value, f"{label}.value") + for name in ("quantity", "unit", "basis", "context"): + if getattr(value, name) != getattr(self, name): + raise ContractError(f"{label}: {name} mismatch") + if self.minimum is not None and value.value < self.minimum: + raise ContractError(f"{label}: value below minimum {self.minimum}") + if self.maximum is not None and value.value > self.maximum: + raise ContractError(f"{label}: value above maximum {self.maximum}") + + +def _ports(ports: Mapping[str, PortSpec], label: str) -> Mapping[str, PortSpec]: + if not isinstance(ports, Mapping): + raise ContractError(f"{label} must be a mapping of names to PortSpec") + snapshot = dict(ports) + for name, spec in snapshot.items(): + _text(name, f"{label} port name") + if not isinstance(spec, PortSpec): + raise ContractError(f"{label}[{name!r}] must be a PortSpec") + return MappingProxyType(snapshot) + + +@dataclass(frozen=True) +class ModelSpec: + """A callable and its declared interface; domain/validation are documentation. + + Scientific adequacy of the stated domain, bounds and validation must be + reviewed separately. Merely providing these strings is not certification. + """ + + key: str + inputs: Mapping[str, PortSpec] + outputs: Mapping[str, PortSpec] + compute: Callable[[Mapping[str, Quantity]], Mapping[str, Quantity]] + domain: str + validation: str + provenance: tuple[str, ...] + + def __post_init__(self): + for name in ("key", "domain", "validation"): + _text(getattr(self, name), name) + object.__setattr__(self, "inputs", _ports(self.inputs, "inputs")) + object.__setattr__(self, "outputs", _ports(self.outputs, "outputs")) + if not self.outputs: + raise ContractError("a model must declare at least one output") + if not callable(self.compute): + raise ContractError("compute must be callable") + object.__setattr__(self, "provenance", _provenance(self.provenance)) + + +def _check_ports(values: Mapping[str, Quantity], specs: Mapping[str, PortSpec], label: str) -> dict[str, Quantity]: + if not isinstance(values, Mapping): + raise ContractError(f"{label} must be a mapping of named quantities") + snapshot = dict(values) + if set(snapshot) != set(specs): + missing = sorted(set(specs) - set(snapshot)) + extra = sorted(repr(k) for k in set(snapshot) - set(specs)) + raise ContractError(f"{label} ports mismatch: missing={missing}, extra={extra}") + for name, spec in specs.items(): + spec.check(snapshot[name], f"{label}[{name!r}]") + return snapshot + + +class ModelRegistry: + """Explicit, opt-in dispatch for Edge.model; no graph-wide scheduling. + + Only named inputs are passed to a callable. All inputs are checked first; + outputs are checked before being returned. A failed output check cannot + undo callback side effects, so callbacks should be pure functions. This is + not a security sandbox for untrusted Python. + """ + + def __init__(self): + self._models: dict[str, ModelSpec] = {} + + def register(self, spec: ModelSpec) -> None: + if not isinstance(spec, ModelSpec): + raise ContractError("register expects a ModelSpec") + if spec.key in self._models: + raise ContractError(f"model {spec.key!r} is already registered") + self._models[spec.key] = spec + + def execute(self, edge: Edge, inputs: Mapping[str, Quantity]) -> dict[str, Quantity]: + if not isinstance(edge, Edge) or not isinstance(edge.model, str) or edge.model not in self._models: + raise ContractError("edge must name an explicitly registered model") + model = self._models[edge.model] + checked = _check_ports(inputs, model.inputs, "inputs") + outputs = _check_ports(model.compute(MappingProxyType(checked)), model.outputs, "outputs") + # Preserve an audit trail of all inputs and the registered model; these + # are source identifiers, not an assertion that any source proves output. + lineage = (*model.provenance, *(source for value in checked.values() for source in value.provenance), + f"model:{model.key}") + return {name: replace(value, provenance=tuple(dict.fromkeys((*value.provenance, *lineage)))) + for name, value in outputs.items()} From d45ca7f50188dc3580dbec11bd0e14367e107fd6 Mon Sep 17 00:00:00 2001 From: Raz Arif Date: Thu, 5 Nov 2026 14:17:16 +0000 Subject: [PATCH 02/12] Fix graph clearance reference basis and validate independent mass balance --- README.md | 15 +- .../report.md | 140 ++++++++++++++++++ auto-research/README.md | 1 + docs/graph_formalization.md | 44 +++++- docs/img/pbpk_elimination_subgraph.mmd | 28 ++++ docs/img/pbpk_elimination_subgraph.svg | 1 - docs/img/pbpk_graph.mmd | 60 ++++++++ docs/img/pbpk_graph.png | Bin 105856 -> 0 bytes docs/img/pbpk_graph.svg | 1 - docs/pbpk_graph.json | 10 +- docs/validation_graph.json | 19 ++- scripts/validate_graph.py | 49 ++++-- tests/test_graph_clearance.py | 90 +++++++++++ vh/graph/physiology_graph.py | 39 ++++- vh/graph/render.py | 3 +- 15 files changed, 462 insertions(+), 38 deletions(-) create mode 100644 auto-research/2026-11-05-E-clearance-reference/report.md create mode 100644 docs/img/pbpk_elimination_subgraph.mmd delete mode 100644 docs/img/pbpk_elimination_subgraph.svg create mode 100644 docs/img/pbpk_graph.mmd delete mode 100644 docs/img/pbpk_graph.png delete mode 100644 docs/img/pbpk_graph.svg create mode 100644 tests/test_graph_clearance.py diff --git a/README.md b/README.md index b413323..ad8be49 100644 --- a/README.md +++ b/README.md @@ -84,9 +84,14 @@ from checking interface compatibility. The body is already a graph at every scale — organs joined by blood flow, atoms joined by bonds. Formalized from the real, validated engines: -

- The whole-body model as a flow graph of organs -

+```mermaid +flowchart LR + liver -->|"CL 16.86 L/h, plasma: effective hepatic"| eliminated + kidney -->|"CL 0.24 L/h, plasma: nominal filtration"| eliminated +``` + +This view shows the clearance reporting parameters; the [complete whole-body +Mermaid source](docs/img/pbpk_graph.mmd) also includes blood flow and absorption. Graph algorithms (all written from scratch) then give exact answers: @@ -101,7 +106,7 @@ Graph algorithms (all written from scratch) then give exact answers: | What does an oral drug hit first? | path enumeration | `gut → liver` before systemic — **first-pass metabolism from topology** | | Does anything recirculate? | strongly-connected components | one loop spanning 15 compartments (systemic circulation) | | Where are the hubs? | betweenness centrality | arterial, venous, lung | -| **Verify a part in isolation** | subgraph extraction | elimination subgraph clearance = full model **exactly (28.488 L/h)** | +| **Inspect a part in isolation** | subgraph extraction | plasma-referenced clearance reporting sum **17.104 L/h**; exact IV dose/AUC **17.103 L/h** ([distinction](docs/graph_formalization.md#clearance-reporting-and-independent-verification)) | | **The graph verifying the engine** | BFS on the bond graph | reproduces the force field's **1687 exclusion pairs exactly** (symmetric difference 0) | That last row is the sharpest: a pure topological fact (atoms within bond-distance ≤ 3) @@ -173,7 +178,7 @@ research tracks, and how to publish work under [`auto-research/`](auto-research/ - **Rohan Arun** ([@rohanarun](https://github.com/rohanarun)) — creator and maintainer; direction and design. - **Claude** (Anthropic) — implemented and validated the engines under the above direction, in pair with the maintainer. -- **OpenAI Codex** — graph interface contracts and validation, under the direction of [@ahrazzle](https://github.com/ahrazzle). +- **OpenAI Codex** — graph interface contracts, clearance reference validation and reporting, under the direction of [@ahrazzle](https://github.com/ahrazzle). New contributors (human or agent): add yourself here in your pull request. See [`auto-research.md`](auto-research.md) for how to help. diff --git a/auto-research/2026-11-05-E-clearance-reference/report.md b/auto-research/2026-11-05-E-clearance-reference/report.md new file mode 100644 index 0000000..7e5f598 --- /dev/null +++ b/auto-research/2026-11-05-E-clearance-reference/report.md @@ -0,0 +1,140 @@ +# Explicit clearance references and independent elimination checks + +- **Track**: E — graph invariants (partial progress; no SBML importer) +- **Author**: OpenAI Codex, under the direction of [@ahrazzle](https://github.com/ahrazzle) +- **Date**: 2026-11-05 +- **Branch / PR**: `auto/E-clearance-reference` +- **Code added/changed**: `vh/graph/physiology_graph.py`, `vh/graph/render.py`, + `scripts/validate_graph.py`, `tests/test_graph_clearance.py` + +## Question + +Can graph validation catch an actual inconsistency in the existing PBPK +formalization? The hepatic `clears` edge used blood clearance while the renal +edge used plasma clearance, and the validation script added them and compared +the same copied operands, incorrectly calling this independent verification of +the full model. + +## Method + +Preserve the PBPK ODE, parameters and existing hepatic well-stirred model. +Convert exported hepatic clearance to plasma reference using +`CL_plasma = bp * CL_blood`, which follows from conservation of elimination +rate and `C_blood = bp * C_plasma`. Both clearance edges now explicitly carry +units, reference basis, quantity kind and their source property. A new graph +invariant rejects incompatible references/units and negative or nonfinite +clearances, including missing values. Old serialized graphs require explicit +conversion; they are not silently treated as plasma-based. + +The reporting sum remains the body's existing `cl_total_plasma_l_h` quantity. +The renal edge is explicitly **nominal renal filtration**, whereas the hepatic +edge is **effective well-stirred hepatic clearance**. These cannot be used as +the ODE's local tissue elimination coefficients merely because their units +match. The script now calls equality with the body property an export check. + +Separately, obtain infinite-time IV plasma AUC by integrating the linear ODE: +`M_active * integral(x dt) = -x0`, for a 1 mg bolus and zero final circulating +drug. Compare dose/AUC with an independently derived steady-state organ balance. +For an organ supplied with plasma-equivalent flow `q = Q_blood * bp` and +intrinsic plasma-referenced loss `c`, that balance gives `CL = q*c/(q+c)`. +Use `c = fu*CLint` for the liver and `c = fu*GFR` for the shipped compound's +renal filtration. Inputs retain their existing provenance in `vh/body`; +no new physiological parameters or clinical datasets were introduced or fit. + +The tests also use invented `fu=0.2` and `CLint=40 L/h`, blood:plasma ratios +0.5, 1 and 2, and both reference physiologies. Exact rational arithmetic solves +hepatic influx minus efflux at input plasma concentration 2 mg/L. This catches +the original bug without reading a derived clearance property as the oracle. + +## Validation — the part that matters + +**Authority:** exact mass balance, evaluated with rational arithmetic for the +synthetic hepatic cases and an analytic well-stirred solution for systemic +clearance. These are mathematical implementation checks, not clinical validation. + +| Quantity | This work | Authority | Error | +|---|---|---|---| +| Hepatic elimination rate, six synthetic cases | exported plasma CL × 2 mg/L | exact rational organ influx minus efflux | maximum observed absolute error 0.0 mg/h; test tolerance 1e-12 mg/h | +| Reference male midazolam systemic clearance | dose/AUC = 17.103069745580346 L/h | analytic organ balance = 17.103069745580346 L/h | observed absolute error 0.0 L/h; test tolerance 1e-10 L/h | +| Three synthetic systemic clearances | exact integral of the ODE | rational hepatic + finite-flow renal clearance | all absolute errors below 1e-10 L/h | + +There is no sampling error bar: these are deterministic calculations. The +tolerances bound accepted floating-point discrepancy, not biological uncertainty. +Zero observed discrepancy at printed precision does not imply exact arithmetic +throughout the numerical solver. No parameters were fitted. + +The corrected **reporting sum** is 17.104405368562304 L/h, replacing a +mixed-reference sum of 28.48825272206046 L/h. Its difference from exact dose/AUC +is **0.001335622981958 L/h**: nominal renal filtration omits finite-flow extraction. +That distinction is reported explicitly rather than treating a shared plasma +reference as proof of identical model semantics. + +Focused validation: **34 passed** with +`tests/test_graph.py tests/test_graph_clearance.py` (24 new cases). The full graph +validation script passed, including blood-flow conservation and the existing +1,687-pair molecular exclusion comparison. Full repository and browser-engine +checks are to be recorded by the integrating contributor before publication. + +## Limits + +- No change to the PBPK engine or evidence of a biological prediction improving. +- Clearance reporting is not automatic model execution. A schema can reject + contradictory declared metadata; it cannot prove the original measurement's + reference basis was truthful. +- The exact systemic expression applies to this linear perfusion-limited model, + with the current renal/hepatic routes and a systemic IV bolus. It is not a + general clearance formula for nonlinear transport or other model structures. +- The full Track E milestone (SBML import and conservation invariants) remains + open. This contribution supplies one invariant that catches a real error. +- Updated Mermaid sources are checked in. SVG/PNG rendering was attempted with + Mermaid CLI 12.2.0 and local Chromium, but the environment denied the renderer + with `net::ERR_BLOCKED_BY_ADMINISTRATOR`. Stale affected images were removed; + docs use a small correct inline Mermaid view and link the full source. Browser + policy was not changed. + +## Reproduce + +```bash +# In an environment with the repository's dev dependencies installed: +PYTHONPATH=. OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 \ + python -m pytest -q tests/test_graph.py tests/test_graph_clearance.py +PYTHONHASHSEED=0 PYTHONPATH=. OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 \ + python scripts/validate_graph.py + +# Optional rasterization, where the local browser policy permits it: +mmdc -i docs/img/pbpk_graph.mmd -o docs/img/pbpk_graph.svg -b transparent +mmdc -i docs/img/pbpk_elimination_subgraph.mmd \ + -o docs/img/pbpk_elimination_subgraph.svg -b transparent +``` + +The commands above used `/tmp/vh-dev/bin/python` for the isolated dev environment. +`docs/validation_graph.json` records the default-model measurements. The six-case +rate check can be reproduced with the following independent calculation: + +```python +from fractions import Fraction as F +from vh.body import MIDAZOLAM, PBPKModel, reference_individual +from vh.graph.physiology_graph import build_pbpk_graph + +errors = [] +for sex in ("male", "female"): + for bp in (0.5, 1.0, 2.0): + ind = reference_individual(sex) + model = PBPKModel(MIDAZOLAM, ind, bp=bp, fu=0.2, clint_hepatic_l_h=40.0) + graph, _ = build_pbpk_graph(model) + q, ratio = F(str(ind.liver_flow_total)), F(str(bp)) + cin = 2 * ratio + cout = q * cin / (q + F(40) * F("0.2") / ratio) + exported_rate = graph.edges_of_type("clears")[0].attrs["cl"] * 2 + errors.append(abs(exported_rate - float(q * (cin - cout)))) +print(max(errors)) # observed: 0.0 mg/h +``` + +## References + +- Existing model definitions and parameter provenance: `vh/body/pbpk.py`, + `vh/body/compound.py`, `vh/body/physiology.py`, `vh/body/partition.py`. +- The upstream baseline inspected was + `3d75e8e25d6f3fec08e1ccecd424532bccaa1b82`. +- The independent authority is the stated conservation equation and exact + linear-system integral; no new empirical reference or fitting dataset is claimed. diff --git a/auto-research/README.md b/auto-research/README.md index e8f809e..31f10a3 100644 --- a/auto-research/README.md +++ b/auto-research/README.md @@ -24,3 +24,4 @@ auto-research/ | Date | Track | Contribution | Validated against | Result | Author | |---|---|---|---|---|---| | 2026-11-05 | E (partial) | [Explicit model contracts](2026-11-05-E-model-contracts/report.md) | Exact scalar mass balance; interface rejection cases | 0 L/h max error on 4 synthetic cases; 60 focused tests pass | OpenAI Codex / @ahrazzle | +| 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 | diff --git a/docs/graph_formalization.md b/docs/graph_formalization.md index 123b45d..995fefa 100644 --- a/docs/graph_formalization.md +++ b/docs/graph_formalization.md @@ -40,23 +40,51 @@ Built from scratch in `vh.graph.algorithms` and demonstrated in | What route does an oral drug take first? | path enumeration | `gut lumen → gut → liver` — **first-pass metabolism falls out of the topology** | | Does anything recirculate? | strongly-connected components | one loop spanning 15 compartments — the systemic circulation | | Where are the hubs / bottlenecks? | betweenness centrality | arterial, venous, lung (all of cardiac output passes through) | -| Which organ dominates elimination? | edge analysis | liver 99% vs kidney 1% of blood clearance | +| Which reported clearance parameter is larger? | edge analysis | liver 99% vs kidney 1% of the plasma-referenced reporting sum; see the distinction below | These are not approximations — they are the exact answers the graph structure determines. -## Partial verification — "render part of it to verify it partially" +## Clearance reporting and independent verification Because the formalization is compositional, any subgraph can be pulled out and checked on its own: - **render** any subgraph to a diagram (`vh.graph.render`, via Mermaid) and - inspect it (`docs/img/pbpk_graph.svg`, and the elimination subgraph); -- **verify** it numerically: the elimination subgraph's total clearance equals - the full model's clearance exactly (28.488 L/h), so that part is correct in - isolation. + inspect the [whole-body source](img/pbpk_graph.mmd) or + [elimination subgraph source](img/pbpk_elimination_subgraph.mmd); +- **check the export**: elimination edges carry explicit `units="L/h"` and + `reference_basis="plasma"`. Since `C_blood = bp * C_plasma`, conserving + elimination rate requires `CL_plasma = bp * CL_blood`. The schema rejects + missing/mixed reference bases, incorrect units, and nonfinite or negative + clearances. The exported sum is **17.104405 L/h** for reference male midazolam, + matching the body's *reported parameter sum*. This replaces a previous + **28.488253 L/h** sum that mixed hepatic blood and renal plasma references. +- **verify independently**: the script integrates the linear ODE analytically, + `integral(x dt) = -M_active^-1 x(0)`, for a 1 mg IV bolus. Dose divided by + venous plasma AUC is **17.103070 L/h**, agreeing with the exact well-stirred + organ mass balance to less than **1e-10 L/h**. Tests separately check exported + hepatic rates against exact rational mass balance at blood:plasma ratios of + 0.5, 1 and 2, so a ratio of 1 cannot hide the reference error. + +These checks answer different questions. Renal `cl` is a **nominal filtration +parameter** (`fu * GFR`), whereas hepatic `cl` is a **well-stirred effective +clearance**. Each edge records its `clearance_kind` and source. The finite renal +blood flow makes exact systemic clearance slightly smaller than the reporting +sum: **0.001336 L/h** in this example. With `q = renal blood flow * bp`, the +effective renal clearance is `q * cl_renal / (q + cl_renal)`. The shared plasma +basis makes export aggregation well defined, but does not make these parameters +identical to the ODE's local tissue elimination coefficients or independently +validate the biology. This change leaves the PBPK ODE and its inputs unchanged. + +```mermaid +flowchart LR + liver -->|"CL 16.86 L/h, plasma: effective hepatic"| eliminated + kidney -->|"CL 0.24 L/h, plasma: nominal filtration"| eliminated +``` -![whole-body graph](img/pbpk_graph.svg) +The full diagrams remain reproducible from the linked Mermaid sources. Old +raster/vector images with mixed reference values have been removed. ## The graph verifying the physics engine @@ -102,5 +130,5 @@ physics a formal, inspectable, verifiable skeleton to hang on. ```bash python scripts/validate_graph.py # runs every algorithm above, renders the diagrams -pytest -q tests/test_graph.py # 10 tests incl. the two verifications +pytest -q tests/test_graph.py tests/test_graph_clearance.py ``` diff --git a/docs/img/pbpk_elimination_subgraph.mmd b/docs/img/pbpk_elimination_subgraph.mmd new file mode 100644 index 0000000..1d67173 --- /dev/null +++ b/docs/img/pbpk_elimination_subgraph.mmd @@ -0,0 +1,28 @@ +%% Elimination subgraph (plasma-referenced reporting parameters) +flowchart LR + venous(["venous blood"]) + spleen["spleen"] + eliminated[("eliminated")] + arterial(["arterial blood"]) + kidney["kidney"] + gut["gut"] + liver["liver"] + pancreas["pancreas"] + arterial -->|"74.1 L/h"| kidney + kidney -->|"74.1 L/h"| venous + arterial -->|"25.4 L/h"| liver + arterial -->|"58.5 L/h"| gut + gut -->|"58.5 L/h"| liver + arterial -->|"11.7 L/h"| spleen + spleen -->|"11.7 L/h"| liver + arterial -->|"3.9 L/h"| pancreas + pancreas -->|"3.9 L/h"| liver + liver -->|"99.5 L/h"| venous + liver -->|"CL 16.86 L/h (plasma)"| eliminated + kidney -->|"CL 0.24 L/h (plasma)"| eliminated + classDef c_blood fill:#C2373A,stroke:#222,color:#ffffff; + class venous,arterial c_blood; + classDef c_compartment fill:#2B44C4,stroke:#222,color:#ffffff; + class spleen,kidney,gut,liver,pancreas c_compartment; + classDef c_sink fill:#586379,stroke:#222,color:#ffffff; + class eliminated c_sink; \ No newline at end of file diff --git a/docs/img/pbpk_elimination_subgraph.svg b/docs/img/pbpk_elimination_subgraph.svg deleted file mode 100644 index 946c01e..0000000 --- a/docs/img/pbpk_elimination_subgraph.svg +++ /dev/null @@ -1 +0,0 @@ -

74.1 L/h

74.1 L/h

25.4 L/h

58.5 L/h

58.5 L/h

11.7 L/h

11.7 L/h

3.9 L/h

3.9 L/h

99.5 L/h

CL 28.24 L/h

CL 0.24 L/h

liver

pancreas

spleen

venous blood

kidney

arterial blood

eliminated

gut

\ No newline at end of file diff --git a/docs/img/pbpk_graph.mmd b/docs/img/pbpk_graph.mmd new file mode 100644 index 0000000..31e5873 --- /dev/null +++ b/docs/img/pbpk_graph.mmd @@ -0,0 +1,60 @@ +%% Midazolam whole-body graph +flowchart LR + arterial(["arterial blood"]) + venous(["venous blood"]) + eliminated[("eliminated")] + gut_lumen(["gut lumen (oral dose)"]) + lung["lung"] + heart["heart"] + brain["brain"] + muscle["muscle"] + adipose["adipose"] + skin["skin"] + bone["bone"] + kidney["kidney"] + liver["liver"] + gut["gut"] + spleen["spleen"] + pancreas["pancreas"] + rest["rest"] + target{"GABA-A receptor (benzodiazepine site, GABRG2)"} + venous -->|"390.0 L/h"| lung + lung -->|"390.0 L/h"| arterial + arterial -->|"15.6 L/h"| heart + heart -->|"15.6 L/h"| venous + arterial -->|"46.8 L/h"| brain + brain -->|"46.8 L/h"| venous + arterial -->|"66.3 L/h"| muscle + muscle -->|"66.3 L/h"| venous + arterial -->|"19.5 L/h"| adipose + adipose -->|"19.5 L/h"| venous + arterial -->|"19.5 L/h"| skin + skin -->|"19.5 L/h"| venous + arterial -->|"19.5 L/h"| bone + bone -->|"19.5 L/h"| venous + arterial -->|"74.1 L/h"| kidney + kidney -->|"74.1 L/h"| venous + arterial -->|"25.4 L/h"| liver + arterial -->|"58.5 L/h"| gut + gut -->|"58.5 L/h"| liver + arterial -->|"11.7 L/h"| spleen + spleen -->|"11.7 L/h"| liver + arterial -->|"3.9 L/h"| pancreas + pancreas -->|"3.9 L/h"| liver + arterial -->|"29.2 L/h"| rest + rest -->|"29.2 L/h"| venous + liver -->|"99.5 L/h"| venous + liver -->|"CL 16.86 L/h (plasma)"| eliminated + kidney -->|"CL 0.24 L/h (plasma)"| eliminated + gut_lumen -->|"Fa·Fg=0.48"| gut + brain -->|"Kd 1.8 nM"| target + classDef c_blood fill:#C2373A,stroke:#222,color:#ffffff; + class arterial,venous c_blood; + classDef c_compartment fill:#2B44C4,stroke:#222,color:#ffffff; + class lung,heart,brain,muscle,adipose,skin,bone,kidney,liver,gut,spleen,pancreas,rest c_compartment; + classDef c_sink fill:#586379,stroke:#222,color:#ffffff; + class eliminated c_sink; + classDef c_lumen fill:#B26A12,stroke:#222,color:#ffffff; + class gut_lumen c_lumen; + classDef c_target fill:#1A8A54,stroke:#222,color:#ffffff; + class target c_target; \ No newline at end of file diff --git a/docs/img/pbpk_graph.png b/docs/img/pbpk_graph.png deleted file mode 100644 index 179810e93904673f880d938e6ab710478de78ba3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 105856 zcmZ6y1yqz>_dbj?NX$^uF@S`0cMhqPAfU8>q_i@CG{Vp+A|X;z(ujz3gVG?~-6-M{JZwzxOUt$_ z4GIbbMFlRagGk*`LpBRNJCb$GYx?Hd@2^F5nReWEMvXJS zgJGEgs%7D*0nhzo6tOeD#mFh|b|u{GMyTL1Nb+|j94;SLJI?$l`L$H%)wi2!kidi; zK>zno|HJ?H?{Jy_``zyU{kzWpo}cqW?@&-1O?fg=Q&Yo7gl^Ukxx?`HjTT-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.5 L/h

11.7 L/h

11.7 L/h

3.9 L/h

3.9 L/h

29.2 L/h

29.2 L/h

99.5 L/h

CL 28.24 L/h

CL 0.24 L/h

Fa·Fg=0.48

Kd 1.8 nM

arterial blood

venous blood

eliminated

gut lumen (oral dose)

lung

heart

brain

muscle

adipose

skin

bone

kidney

liver

gut

spleen

pancreas

rest

GABA-A receptor (benzodiazepine site, GABRG2)

\ No newline at end of file diff --git a/docs/pbpk_graph.json b/docs/pbpk_graph.json index fb37bae..baaf73e 100644 --- a/docs/pbpk_graph.json +++ b/docs/pbpk_graph.json @@ -457,7 +457,11 @@ "type": "clears", "directed": true, "attrs": { - "cl": 28.244519572405274, + "cl": 16.86067221890712, + "units": "L/h", + "reference_basis": "plasma", + "clearance_kind": "well_stirred_hepatic", + "source": "PBPKModel.p.cl_hep_blood_l_h * PBPKModel.p.bp", "organ": "liver" }, "model": "pbpk.hepatic" @@ -469,6 +473,10 @@ "directed": true, "attrs": { "cl": 0.24373314965518464, + "units": "L/h", + "reference_basis": "plasma", + "clearance_kind": "nominal_renal_filtration", + "source": "PBPKModel.p.cl_renal_l_h", "organ": "kidney" }, "model": "pbpk.renal" diff --git a/docs/validation_graph.json b/docs/validation_graph.json index 77343e3..39056fa 100644 --- a/docs/validation_graph.json +++ b/docs/validation_graph.json @@ -16,12 +16,21 @@ "venous", "lung" ], - "hepatic_fraction": 0.9914444331832803 + "hepatic_reported_parameter_fraction": 0.985750270506149, + "clearance_units": "L/h", + "clearance_reference_basis": "plasma" }, - "partial_verification": { - "subgraph_cl": 28.48825272206046, - "full_cl": 28.48825272206046, - "match": true + "clearance_reporting": { + "units": "L/h", + "reference_basis": "plasma", + "subgraph_parameter_sum": 17.104405368562304, + "model_reported_parameter_sum": 17.104405368562304, + "export_matches": true, + "iv_dose_over_venous_plasma_auc": 17.103069745580346, + "analytic_well_stirred_clearance": 17.103069745580346, + "analytic_absolute_error": 0.0, + "reported_sum_minus_dose_over_auc": 0.0013356229819585508, + "limitation": "Reported renal filtration parameter omits finite-flow extraction; export agreement is not independent model validation." }, "molecular": { "n_atoms": 304, diff --git a/scripts/validate_graph.py b/scripts/validate_graph.py index eab0351..1ed2837 100644 --- a/scripts/validate_graph.py +++ b/scripts/validate_graph.py @@ -5,7 +5,7 @@ checked by a graph algorithm; 2. structural pharmacology falls out of topology (IV reach, oral first pass, recirculation, hubs); - 3. partial verification: a subgraph's elimination matches the full model; + 3. clearance reference consistency, with a separate exact IV dose/AUC check; 4. a pure graph BFS on the bond graph reproduces the force-field exclusion list exactly -- the graph verifying the physics engine; 5. renders the body graph and a subgraph to diagrams. @@ -37,6 +37,8 @@ def whole_body(): print(g.summary()) problems = g.validate(schema) print("schema + invariants:", "all pass" if not problems else problems) + if problems: + raise ValueError("invalid PBPK graph: " + "; ".join(problems)) bal = A.flow_balance(g, "flow", ("flow",)) print(f"[1 blood conservation] worst residual {bal['max_abs_residual']:.2e} L/h " @@ -55,7 +57,8 @@ def whole_body(): # elimination split from the clearance edges cl = {e.attrs['organ']: e.attrs['cl'] for e in g.edges_of_type('clears')} print(f"[2 elimination] hepatic {cl['liver']:.2f} L/h vs renal {cl['kidney']:.2f} L/h " - f"-> liver handles {100*cl['liver']/sum(cl.values()):.0f}% (blood clearance)") + f"-> hepatic share {100*cl['liver']/sum(cl.values()):.0f}% " + "(reported plasma-referenced parameters)") report["whole_body"] = { "summary": g.summary(), "schema_ok": not problems, @@ -64,22 +67,48 @@ def whole_body(): "oral_first_pass_path": oral[0] if oral else None, "recirculation_loop_size": max(len(c) for c in loops), "hubs": [h[0] for h in hubs], - "hepatic_fraction": cl["liver"] / sum(cl.values()), + "hepatic_reported_parameter_fraction": cl["liver"] / sum(cl.values()), + "clearance_units": "L/h", "clearance_reference_basis": "plasma", } g.save_json(DOCS / "pbpk_graph.json") render(g, str(IMG / "pbpk_graph.svg"), direction="LR", title="Midazolam whole-body graph") - # 3. partial verification: the elimination subgraph alone reproduces total clearance + # 3. Export consistency is not an independent check of the ODE. The renal + # reporting parameter is nominal filtration clearance, before finite flow. sub = g.subgraph(["arterial", "liver", "kidney", "venous", "gut", "spleen", "pancreas", "eliminated"], name="elimination-subgraph") sub_cl = sum(e.attrs["cl"] for e in sub.edges_of_type("clears")) - full_cl = m.p.cl_hep_blood_l_h + m.p.cl_renal_l_h - print(f"[3 partial verification] elimination subgraph total CL {sub_cl:.3f} L/h " - f"= full model {full_cl:.3f} L/h (match: {abs(sub_cl-full_cl) < 1e-9})") + reported_cl = m.p.cl_total_plasma_l_h + # Independent analytic integrated mass balance: M_active * integral(x dt) + # = -x(0) for a 1 mg IV bolus, with all circulating drug gone at infinity. + active = [i for i, n in enumerate(m.names) if n in m.V] + initial = np.zeros(len(active)) + initial[active.index(m.ix["venous"])] = 1.0 + integrated = -np.linalg.solve(m.M[np.ix_(active, active)], initial) + auc = integrated[active.index(m.ix["venous"])] / m.V["venous"] / m.p.bp + dose_over_auc = 1.0 / auc + # Exact well-stirred organ balance, evaluated from inputs, not edge values. + q_h, q_r = m.ind.liver_flow_total * m.p.bp, m.ind.flows["kidney"] * m.p.bp + intrinsic_h = m.p.fu * m.p.clint_hep_l_h + filtration = m.compound.renal_filtration * m.p.fu * m.ind.gfr + analytic_cl = q_h * intrinsic_h / (q_h + intrinsic_h) + q_r * filtration / (q_r + filtration) + print(f"[3 clearance reporting] subgraph {sub_cl:.6f} L/h = reported parameter " + f"sum {reported_cl:.6f} L/h (plasma); exact IV dose/AUC {dose_over_auc:.6f} L/h") + print(f"[3 independent balance] dose/AUC vs analytic organ balance: " + f"{abs(dose_over_auc - analytic_cl):.2e} L/h error") render(sub, str(IMG / "pbpk_elimination_subgraph.svg"), direction="LR", - title="Elimination subgraph (verified in isolation)") - report["partial_verification"] = {"subgraph_cl": sub_cl, "full_cl": full_cl, - "match": abs(sub_cl - full_cl) < 1e-9} + title="Elimination subgraph (plasma-referenced reporting parameters)") + report["clearance_reporting"] = { + "units": "L/h", "reference_basis": "plasma", + "subgraph_parameter_sum": sub_cl, "model_reported_parameter_sum": reported_cl, + "export_matches": abs(sub_cl - reported_cl) < 1e-9, + "iv_dose_over_venous_plasma_auc": dose_over_auc, + "analytic_well_stirred_clearance": analytic_cl, + "analytic_absolute_error": abs(dose_over_auc - analytic_cl), + "reported_sum_minus_dose_over_auc": sub_cl - dose_over_auc, + "limitation": "Reported renal filtration parameter omits finite-flow extraction; " + "export agreement is not independent model validation.", + } def molecular(): diff --git a/tests/test_graph_clearance.py b/tests/test_graph_clearance.py new file mode 100644 index 0000000..472cd65 --- /dev/null +++ b/tests/test_graph_clearance.py @@ -0,0 +1,90 @@ +"""Clearance export checked against exact organ mass balance, not copied CLs.""" + +from fractions import Fraction + +import numpy as np +import pytest + +from vh.body import MIDAZOLAM, PBPKModel, reference_individual +from vh.graph import Graph +from vh.graph.physiology_graph import build_pbpk_graph +from vh.graph.render import to_mermaid + + +@pytest.mark.parametrize("bp", [0.5, 1.0, 2.0]) +@pytest.mark.parametrize("sex", ["male", "female"]) +def test_export_obeys_hepatic_mass_balance_for_nonunity_blood_plasma_ratio(bp, sex): + # Invented fu and CLint test the algebra; they are not fitted biological data. + ind = reference_individual(sex) + model = PBPKModel(MIDAZOLAM, ind, bp=bp, fu=0.2, clint_hepatic_l_h=40.0) + graph, schema = build_pbpk_graph(model) + edges = {e.attrs["organ"]: e for e in graph.edges_of_type("clears")} + + # Exact rational steady-state organ balance at input plasma concentration + # 2 mg/L: Q*(C_b,in-C_b,out) = CLint*fu/bp*C_b,out. + # This oracle uses original inputs, never DerivedParams clearance properties. + q = Fraction(str(ind.liver_flow_total)) + ratio = Fraction(str(bp)) + intrinsic = Fraction(40) * Fraction("0.2") / ratio + blood_in = ratio * 2 + blood_out = q * blood_in / (q + intrinsic) + hepatic_rate_mg_h = q * (blood_in - blood_out) + renal_rate_mg_h = Fraction(str(ind.gfr)) * Fraction("0.2") * 2 + assert edges["liver"].attrs["cl"] * 2 == pytest.approx(float(hepatic_rate_mg_h), rel=0, abs=1e-12) + assert edges["kidney"].attrs["cl"] * 2 == pytest.approx(float(renal_rate_mg_h), rel=0, abs=1e-12) + assert all(e.attrs["units"] == "L/h" and e.attrs["reference_basis"] == "plasma" + for e in edges.values()) + assert graph.validate(schema) == [] + # Serialization and partial graphs must retain the explicit reference basis. + restored = Graph.from_dict(graph.to_dict()).subgraph(["liver", "kidney", "eliminated"]) + assert [e.attrs for e in restored.edges] == [e.attrs for e in edges.values()] + assert "(plasma)" in to_mermaid(restored) + + +@pytest.mark.parametrize("attr,value", [ + ("units", "mL/min"), ("reference_basis", "blood"), + ("cl", -1.0), ("cl", float("inf")), ("cl", float("nan")), + ("cl", True), ("cl", "1"), ("cl", 1 + 1j), ("cl", None), ("cl", 10**1000), +]) +def test_clearance_invariant_rejects_unsafe_aggregation(attr, value): + graph, schema = build_pbpk_graph(PBPKModel(MIDAZOLAM)) + graph.edges_of_type("clears")[0].attrs[attr] = value + assert any("[clearance-reference]" in error for error in graph.validate(schema)) + + +@pytest.mark.parametrize("attr", ["cl", "units", "reference_basis", "clearance_kind", "source"]) +def test_clearance_schema_requires_semantics(attr): + graph, schema = build_pbpk_graph(PBPKModel(MIDAZOLAM)) + del graph.edges_of_type("clears")[0].attrs[attr] + assert any(f"missing attribute '{attr}'" in error for error in graph.validate(schema)) + + +@pytest.mark.parametrize("bp", [0.5, 1.0, 2.0]) +def test_reporting_sum_is_not_misidentified_as_exact_systemic_clearance(bp): + ind = reference_individual("male") + model = PBPKModel(MIDAZOLAM, ind, bp=bp, fu=0.2, clint_hepatic_l_h=40.0) + graph, _ = build_pbpk_graph(model) + reporting_sum = sum(e.attrs["cl"] for e in graph.edges_of_type("clears")) + assert reporting_sum == pytest.approx(model.p.cl_total_plasma_l_h, rel=0, abs=1e-12) + + # Integral of the linear ODE: M * integral(x dt) = -x0 (1 mg IV bolus). + active = [i for i, name in enumerate(model.names) if name in model.V] + x0 = np.zeros(len(active)) + venous = active.index(model.ix["venous"]) + x0[venous] = 1.0 + integrated = -np.linalg.solve(model.M[np.ix_(active, active)], x0) + dose_over_auc = model.V["venous"] * bp / integrated[venous] + + # Independent exact rational organ balances. The renal filtration parameter + # must be flow-limited before adding it to effective hepatic clearance. + ratio = Fraction(str(bp)) + q_h = Fraction(str(ind.liver_flow_total)) * ratio + q_r = Fraction(str(ind.flows["kidney"])) * ratio + intrinsic_h = Fraction(40) * Fraction("0.2") + filtration = Fraction(str(ind.gfr)) * Fraction("0.2") + effective_h = q_h * intrinsic_h / (q_h + intrinsic_h) + effective_r = q_r * filtration / (q_r + filtration) + assert dose_over_auc == pytest.approx(float(effective_h + effective_r), rel=0, abs=1e-10) + # Preserve the distinction in exported quantities, without changing the ODE. + assert reporting_sum - dose_over_auc == pytest.approx(float(filtration - effective_r), rel=0, abs=1e-10) + assert graph.edges_of_type("clears")[1].attrs["clearance_kind"] == "nominal_renal_filtration" diff --git a/vh/graph/physiology_graph.py b/vh/graph/physiology_graph.py index 8c1a003..7a2a2fa 100644 --- a/vh/graph/physiology_graph.py +++ b/vh/graph/physiology_graph.py @@ -28,8 +28,9 @@ # --------------------------------------------------------------------------- def build_pbpk_graph(model, drug_name: str | None = None) -> tuple[Graph, Schema]: """The PBPK model as a graph. Blood-flow edges carry L/h; partition edges carry - the Rodgers-Rowland Kp; clearance edges carry L/h; the oral route carries the - absorption path. Numbers come straight from the validated model.""" + the Rodgers-Rowland Kp; clearance edges carry explicitly plasma-referenced + L/h. These are reporting parameters, not the tissue elimination coefficients + used by the ODE. The oral route carries the absorption path.""" from vh.body.physiology import PORTAL, TISSUES ind, p = model.ind, model.p @@ -64,9 +65,17 @@ def build_pbpk_graph(model, drug_name: str | None = None) -> tuple[Graph, Schema # the partition coefficient (how strongly the drug concentrates in each tissue, # from Rodgers-Rowland) is already on each compartment node as `kp`. - # elimination edges (the only edges to the sink) - g.add_edge("liver", "eliminated", "clears", cl=float(p.cl_hep_blood_l_h), organ="liver", model="pbpk.hepatic") - g.add_edge("kidney", "eliminated", "clears", cl=float(p.cl_renal_l_h), organ="kidney", model="pbpk.renal") + # Reporting clearances: CL_blood * C_blood = CL_plasma * C_plasma, + # hence CL_plasma = CL_blood * bp. Never sum blood- and plasma-based CL. + # The kidney value is nominal filtration clearance, not the finite-flow + # effective clearance; their sum reproduces p.cl_total_plasma_l_h only. + g.add_edge("liver", "eliminated", "clears", cl=float(p.cl_hep_blood_l_h * p.bp), + units="L/h", reference_basis="plasma", clearance_kind="well_stirred_hepatic", + source="PBPKModel.p.cl_hep_blood_l_h * PBPKModel.p.bp", + organ="liver", model="pbpk.hepatic") + g.add_edge("kidney", "eliminated", "clears", cl=float(p.cl_renal_l_h), + units="L/h", reference_basis="plasma", clearance_kind="nominal_renal_filtration", + source="PBPKModel.p.cl_renal_l_h", organ="kidney", model="pbpk.renal") # oral absorption route g.add_edge("gut_lumen", "gut", "absorbs", fa=float(p.fa), fg=float(p.fg), ka=float(p.ka_h), model="pbpk.absorption") @@ -86,12 +95,30 @@ def _pbpk_schema(cardiac_output: float) -> Schema: "lumen": set(), "target": {"kd_nm"}}, edge_rules=[ EdgeRule("flow", {"blood", "compartment"}, {"blood", "compartment"}, {"flow"}), - EdgeRule("clears", {"compartment"}, {"sink"}, {"cl"}), + EdgeRule("clears", {"compartment"}, {"sink"}, + {"cl", "units", "reference_basis", "clearance_kind", "source"}), EdgeRule("absorbs", {"lumen"}, {"compartment"}, {"fa"}), EdgeRule("binds", {"compartment"}, {"target"}, {"kd_nm"}), ], ) + @schema.invariant("clearance-reference") + def _clearance_reference(g: Graph) -> list[str]: + out = [] + for e in g.edges_of_type("clears"): + if e.attrs.get("units") != "L/h" or e.attrs.get("reference_basis") != "plasma": + out.append(f"edge {e.key}: clearance must use L/h referenced to plasma") + cl = e.attrs.get("cl") + try: + valid = (not isinstance(cl, (bool, np.bool_)) + and isinstance(cl, (int, float, np.number)) and np.isrealobj(cl) + and np.isfinite(float(cl)) and cl >= 0) + except (OverflowError, TypeError, ValueError): + valid = False + if not valid: + out.append(f"edge {e.key}: clearance must be a finite nonnegative number") + return out + @schema.invariant("blood-conservation") def _conserve(g: Graph) -> list[str]: # every compartment and the blood pools must balance blood flow in = out diff --git a/vh/graph/render.py b/vh/graph/render.py index 1413b9b..e8006e6 100644 --- a/vh/graph/render.py +++ b/vh/graph/render.py @@ -25,7 +25,8 @@ } _EDGE_LABEL = { "flow": lambda e: f"{e.attrs.get('flow', 0):.1f} L/h", - "clears": lambda e: f"CL {e.attrs.get('cl', 0):.2f} L/h", + "clears": lambda e: (f"CL {e.attrs.get('cl', 0):.2f} {e.attrs.get('units', '?')} " + f"({e.attrs.get('reference_basis', 'unspecified')})"), "absorbs": lambda e: f"Fa·Fg={e.attrs.get('fa',0)*e.attrs.get('fg',1):.2f}", "binds": lambda e: f"Kd {e.attrs.get('kd_nm','?')} nM", "bond": lambda e: "", From 13cbe265a7f98962199190cc43d19cabe3e66d36 Mon Sep 17 00:00:00 2001 From: Raz Arif Date: Thu, 5 Nov 2026 14:28:51 +0000 Subject: [PATCH 03/12] Record Foundation-0 fork integration and combined verification --- README.md | 5 + .../report.md | 6 ++ .../2026-11-05-E-model-contracts/report.md | 6 ++ docs/project-asma-integration.md | 101 ++++++++++++++++++ 4 files changed, 118 insertions(+) create mode 100644 docs/project-asma-integration.md diff --git a/README.md b/README.md index ad8be49..d2ed0dd 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,10 @@ # Virtual Human +**Foundation-0 development fork:** reusable graph work supporting +[Project Asma](https://github.com/Foundation-0/project-asma). See the +[integration and validation record](docs/project-asma-integration.md). +The original project is [Rohan Arun's Virtual Human](https://github.com/rohanarun/virtual-human). + > *Solving problems in the human body by formalizing the real world into code for agents.* A multi-scale simulation of the human body for testing medicines and proteins, diff --git a/auto-research/2026-11-05-E-clearance-reference/report.md b/auto-research/2026-11-05-E-clearance-reference/report.md index 7e5f598..6640532 100644 --- a/auto-research/2026-11-05-E-clearance-reference/report.md +++ b/auto-research/2026-11-05-E-clearance-reference/report.md @@ -77,6 +77,12 @@ checks are to be recorded by the integrating contributor before publication. ## Limits +**Subsequent combined verification, 2026-11-05:** 111 Python tests passed and +JavaScript engine checks passed with checked-in and regenerated references. +See the [integration record](../../docs/project-asma-integration.md) for the +revision, environment, commands and limits; numerical agreement does not establish +biological applicability. + - No change to the PBPK engine or evidence of a biological prediction improving. - Clearance reporting is not automatic model execution. A schema can reject contradictory declared metadata; it cannot prove the original measurement's diff --git a/auto-research/2026-11-05-E-model-contracts/report.md b/auto-research/2026-11-05-E-model-contracts/report.md index 54d2c17..d3406bf 100644 --- a/auto-research/2026-11-05-E-model-contracts/report.md +++ b/auto-research/2026-11-05-E-model-contracts/report.md @@ -68,6 +68,12 @@ dispatch after graph round-trip and preservation of provenance lineage. Full engine and browser suites are outside this focused validation run; their status must be checked before merging alongside other changes. +**Subsequent combined run, 2026-11-05:** 111 Python tests passed and JavaScript +engine checks passed with both checked-in and regenerated reference fixtures. +See the [integration record](../../docs/project-asma-integration.md) for code +revision, exact commands, runtime and limits. This does not broaden the biological +scope of the synthetic validation above. + ## Limits Matching metadata does not establish biological validity, causal direction, diff --git a/docs/project-asma-integration.md b/docs/project-asma-integration.md new file mode 100644 index 0000000..71cbcb8 --- /dev/null +++ b/docs/project-asma-integration.md @@ -0,0 +1,101 @@ +# Foundation-0 development fork and Project Asma + +This is a development fork of [Rohan Arun's Virtual Human](https://github.com/rohanarun/virtual-human), +created by the Project Asma owner on 2026-11-05. Upstream remains the original +project. Its MIT license, creator credit and contribution requirements are +preserved. The upstream README credits Claude for the original implementation +under the maintainer's direction. The graph contributions below were prepared +with OpenAI Codex under [@ahrazzle](https://github.com/ahrazzle)'s direction. + +## Shared purpose and repository boundary + +[Project Asma](https://github.com/Foundation-0/project-asma) uses a pinned, +unchanged copy of `vh/graph/core.py` for an offline public-evidence prototype. +It supplies a concrete test case: do not silently substitute antibody binding, +protein function, HLA annotation, receptor recognition and tissue injury for one +another. The Asma repository owns the literature curation and domain-specific +rules. This fork owns reusable graph interfaces and numerical-model checks. + +Asma does not currently adopt the molecular, PBPK or quantum engines, nor does it +use the new scalar model registry to invent numerical values for unknown biology. +Its qualitative assertions stay qualitative. Recognition and injury are separate +questions: direct recognition of a CDR2L ligand and indirect injury can coexist. +Neither is established by a graph or a successful software test. + +No patient records, personal correspondence, private clinical analysis or sensitive +derived hypotheses belong in this public fork. Only public-source requirements, +original software, permitted upstream inputs and clearly artificial fixtures are +used for this contribution. + +## Contributions and acceptance + +The initial integration combines two separately reviewable commits and reports: + +| Contribution | Validation authority and outcome | +| --- | --- | +| [Explicit model contracts](../auto-research/2026-11-05-E-model-contracts/report.md) | Exact scalar mass balance: maximum error 0 L/h over four synthetic cases, tolerance 1e-12 L/h; 50 new contract cases. | +| [Clearance reference correction](../auto-research/2026-11-05-E-clearance-reference/report.md) | Exact organ mass balance and integrated linear ODE; 24 new cases. Plasma reporting sum 17.104405 L/h remains distinct from IV dose/AUC 17.103070 L/h. | + +Neither completes the full Track E SBML milestone. Existing PBPK differential +equations are unchanged. Domain/validation strings in a model contract are +declarations; the runtime verifies supplied interface semantics and bounds, not +biological truth. The clearance check catches a real reference-basis error in +graph reporting and avoids overstating copied export arithmetic as independent +physiological validation. + +## Combined verification, 2026-11-05 + +On code revision `d45ca7f50188dc3580dbec11bd0e14367e107fd6` (the two implementation +commits applied to upstream `3d75e8e25d6f3fec08e1ccecd424532bccaa1b82`): + +- **111 Python tests passed**, no skips, in 76.12 s. +- JavaScript engine checks passed using the checked-in reference fixtures. +- `scripts/export_web.py` completed, then JavaScript checks passed again against + regenerated references. Worst plasma-profile relative error was 4.8e-13 over + 48 points. Molecular energy/force comparisons and 500-step stability checks + also passed. This is numerical verification against the supplied fixtures, + not validation of anti-Yo mechanisms or individual outcomes. +- Regenerated molecular web fixtures were not retained: the contribution does + not change those engines or their inputs. Checked-in fixture checks had already + passed independently. No unrelated model or clinical dataset files changed. +- Focused tests and the analytical comparisons were independently rerun by an + internal reviewing agent. This is not external scientific review. + +Runtime: Linux x86_64; Python 3.12.14; Node 24.19.0. Installed numerical/test +versions: NumPy 2.5.4, SciPy 1.18.1, JAX/JAXlib 0.12.0.1, OpenMM 8.6.1, +PDBFixer 1.12.0, PySCF 2.15.0, geomeTRIC 1.1.1, pytest 9.2.0, +Matplotlib 3.11.2. This records the observed environment, not a new repository +dependency lock or a claim of portability to every allowed package version. + +```bash +python -m venv /tmp/vh-dev +/tmp/vh-dev/bin/python -m pip install -e '.[dev]' +PYTHONPATH=. OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 \ + /tmp/vh-dev/bin/python -m pytest -q +node web/test_engines.mjs +PYTHONPATH=. OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 \ + /tmp/vh-dev/bin/python scripts/export_web.py +node web/test_engines.mjs +``` + +The clearance report records a diagram-rendering limitation: browser policy +blocked Mermaid's local renderer. Correct Mermaid source and inline diagrams +replace the affected stale images; no browser policy was changed. + +## How the repositories progress together + +1. Record a concrete Asma failure case or missing interface, without importing + private data. Decide whether it is a general library concern or a domain rule. +2. Put general fixes here with an independent validation authority and a report + following `auto-research.md`; put evidence semantics and scientific critique + in Asma. Preserve unresolved and negative findings. +3. Review each change in a PR. Asma updates its vendored source only deliberately, + preserving hashes and the upstream MIT notice, then reruns its offline checks. +4. Submit reusable changes to the original repository when contributor access is + available. The owner is arranging that access. Fork PRs do not imply upstream + acceptance, and fork-specific coordination docs need not accompany upstream + feature PRs. + +No automatic merge, deployment, background research run or patient simulation is +introduced by this workflow. Further simulation work needs a defined biological +question, applicable inputs and validation that can resolve that question. From 9f4ef7e4dbe89bcd6d948a68991226e877410b9a Mon Sep 17 00:00:00 2001 From: Raz Arif Date: Thu, 5 Nov 2026 14:30:51 +0000 Subject: [PATCH 04/12] Link independently reviewable Asma and graph contributions --- docs/project-asma-integration.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/project-asma-integration.md b/docs/project-asma-integration.md index 71cbcb8..9d38cf8 100644 --- a/docs/project-asma-integration.md +++ b/docs/project-asma-integration.md @@ -29,6 +29,12 @@ used for this contribution. ## Contributions and acceptance +Reviewable changes: [fork PR #1](https://github.com/Foundation-0/virtual-human/pull/1) +and [Project Asma PR #45](https://github.com/Foundation-0/project-asma/pull/45). +Both were opened as drafts. They are independently reviewable: Asma uses the +unchanged baseline graph core, so its prototype does not require merging this +fork PR first. Upstream submission is still pending contributor access. + The initial integration combines two separately reviewable commits and reports: | Contribution | Validation authority and outcome | From 9d36aa7b814dafebc0df7bd339dc09234b44a99e Mon Sep 17 00:00:00 2001 From: Raz Arif Date: Thu, 5 Nov 2026 14:42:43 +0000 Subject: [PATCH 05/12] Record companion Asma merge and validation outcome --- docs/project-asma-integration.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/project-asma-integration.md b/docs/project-asma-integration.md index 9d38cf8..281d282 100644 --- a/docs/project-asma-integration.md +++ b/docs/project-asma-integration.md @@ -102,6 +102,15 @@ replace the affected stale images; no browser policy was changed. acceptance, and fork-specific coordination docs need not accompany upstream feature PRs. +**2026-11-05 14:41 UTC update:** the team merged +[Asma PR #45](https://github.com/Foundation-0/project-asma/pull/45) as +`3afeb2b9b14b9bc7fc126e3503554d7673b43673` after its +[full CI](https://github.com/Foundation-0/project-asma/actions/runs/42046224134) +passed: 227 Python tests, pinned container builds, offline checks and 40 execution +controls. This fork's reusable changes remain independently reviewable in PR #1. +The Asma merge adopts only the bounded graph use described here, not the simulation +stack or a clinically validated model. This contributing session did not merge it. + No automatic merge, deployment, background research run or patient simulation is introduced by this workflow. Further simulation work needs a defined biological question, applicable inputs and validation that can resolve that question. From 3523b288661e41c6ebf10ac427b75fd88f329e31 Mon Sep 17 00:00:00 2001 From: ahrazzle <38987266+ahrazzle@users.noreply.github.com> Date: Thu, 5 Nov 2026 09:46:18 -0600 Subject: [PATCH 06/12] Add conserved reaction networks and explicit intervention experiments (#3) * Add conserved mass-action networks and explicit intervention protocols * Record Asma intervention bridge verification and merged baseline * Link review PRs and pin clean Asma bridge source revision --------- Co-authored-by: Raz Arif --- README.md | 2 +- .../bridge-results.json | 71 ++++ .../report.md | 137 +++++++ .../results.json | 100 ++++++ auto-research/README.md | 1 + docs/project-asma-integration.md | 69 ++++ docs/reaction_experiments.md | 135 +++++++ scripts/validate_asma_interventions.py | 113 ++++++ scripts/validate_reaction_experiments.py | 145 ++++++++ tests/test_reaction_experiments.py | 266 ++++++++++++++ vh/graph/__init__.py | 4 + vh/graph/reactions.py | 338 ++++++++++++++++++ 12 files changed, 1380 insertions(+), 1 deletion(-) create mode 100644 auto-research/2026-11-05-E-reaction-experiments/bridge-results.json create mode 100644 auto-research/2026-11-05-E-reaction-experiments/report.md create mode 100644 auto-research/2026-11-05-E-reaction-experiments/results.json create mode 100644 docs/reaction_experiments.md create mode 100644 scripts/validate_asma_interventions.py create mode 100644 scripts/validate_reaction_experiments.py create mode 100644 tests/test_reaction_experiments.py create mode 100644 vh/graph/reactions.py diff --git a/README.md b/README.md index d2ed0dd..836b655 100644 --- a/README.md +++ b/README.md @@ -183,7 +183,7 @@ research tracks, and how to publish work under [`auto-research/`](auto-research/ - **Rohan Arun** ([@rohanarun](https://github.com/rohanarun)) — creator and maintainer; direction and design. - **Claude** (Anthropic) — implemented and validated the engines under the above direction, in pair with the maintainer. -- **OpenAI Codex** — graph interface contracts, clearance reference validation and reporting, under the direction of [@ahrazzle](https://github.com/ahrazzle). +- **OpenAI Codex** — graph interface contracts, clearance reference validation, and conserved reaction/intervention experiments, under the direction of [@ahrazzle](https://github.com/ahrazzle). New contributors (human or agent): add yourself here in your pull request. See [`auto-research.md`](auto-research.md) for how to help. diff --git a/auto-research/2026-11-05-E-reaction-experiments/bridge-results.json b/auto-research/2026-11-05-E-reaction-experiments/bridge-results.json new file mode 100644 index 0000000..361c711 --- /dev/null +++ b/auto-research/2026-11-05-E-reaction-experiments/bridge-results.json @@ -0,0 +1,71 @@ +{ + "status": "pass", + "scope": "synthetic_operator_consistency_only_not_biological_validation", + "as_of": "2026-11-05", + "authority": "Project Asma exact rational operators and explicit linear-flow solution", + "asma_checkout": { + "commit": "03d6cad7eaa97cf6e332515f6e5e0a9172b5addc", + "dirty": false + }, + "virtual_human_checkout": { + "commit": "cf5510837c89ca636646f215ec62c66e40f5110a", + "dirty": true + }, + "source_sha256": { + "asma_exact_module": "0b3492e8b9fcc9dd2b7100d81552e212bc0f9c1aeed420b40bb76a9c93cb7a1b", + "vh_reactions_module": "a222b1ffa3c9cbdafb1e627004e522da2550d092551a7d0fd88df7b4ead91474", + "comparison_script": "bf31e50ddbe4c3ba2c83943220f505ef5d765484eff92137adf496d2f66a0534" + }, + "tolerance_absolute_mol_per_L": 1e-10, + "maximum_absolute_error_mol_per_L": 4.8530623963927155e-14, + "fixtures": [ + { + "fixture": "selective", + "a": "1/10", + "b": "1", + "q": "1/10", + "maximum_absolute_error_mol_per_L": 1.3447576385772209e-14, + "comparison_errors_mol_per_L": { + "proportional_surgery_first": 4.881511861398735e-15, + "proportional_chemo_first": 4.853756285783106e-15, + "fixed_surgery_first": 4.881511861398735e-15, + "fixed_chemo_first": 1.3447576385772209e-14 + }, + "exact_fixed_after_to_before_resistant_ratio": "100/19" + }, + { + "fixture": "nonselective", + "a": "1/2", + "b": "1/2", + "q": "1/10", + "maximum_absolute_error_mol_per_L": 3.469446951953614e-17, + "comparison_errors_mol_per_L": { + "proportional_surgery_first": 3.469446951953614e-17, + "proportional_chemo_first": 1.3877787807814457e-17, + "fixed_surgery_first": 3.469446951953614e-17, + "fixed_chemo_first": 8.673617379884035e-18 + }, + "exact_fixed_after_to_before_resistant_ratio": "2" + }, + { + "fixture": "capped", + "a": "1/10", + "b": "1/2", + "q": "1/2", + "maximum_absolute_error_mol_per_L": 4.8530623963927155e-14, + "comparison_errors_mol_per_L": { + "proportional_surgery_first": 2.4265311981963578e-14, + "proportional_chemo_first": 2.4265311981963578e-14, + "fixed_surgery_first": 2.4265311981963578e-14, + "fixed_chemo_first": 4.8530623963927155e-14 + }, + "exact_fixed_after_to_before_resistant_ratio": "2" + } + ], + "limitations": [ + "invented quantities and rates", + "no physiological conversion", + "fixed-residual map explicitly applied outside the VH protocol runner", + "no full Gu model, patient model, survival inference or clinical recommendation" + ] +} diff --git a/auto-research/2026-11-05-E-reaction-experiments/report.md b/auto-research/2026-11-05-E-reaction-experiments/report.md new file mode 100644 index 0000000..0560fa7 --- /dev/null +++ b/auto-research/2026-11-05-E-reaction-experiments/report.md @@ -0,0 +1,137 @@ +# Conserved reaction networks and explicit ordered interventions + +- **Track**: E (incremental; full SBML milestone remains open) +- **Author**: OpenAI Codex (Astra), under @ahrazzle's direction +- **Date**: 2026-11-05 +- **Branch / PR**: `auto/E-reaction-experiments`, [Foundation-0/virtual-human PR #3](https://github.com/Foundation-0/virtual-human/pull/3) +- **Code added**: `vh/graph/reactions.py`, `scripts/validate_reaction_experiments.py`, + `tests/test_reaction_experiments.py`; [usage guide](../../docs/reaction_experiments.md) + +## Question + +Can the graph layer support small, explicit numerical experiments that distinguish +reaction conservation from external interventions and test whether an apparent +order effect follows from stated assumptions? This is useful before connecting +literature hypotheses to numerical models: the equations, interventions and +mathematical null cases must be inspectable first. + +## Method + +Added deterministic elementary mass-action dynamics in one fixed well-mixed +compartment, exact integer stoichiometry and rational left-nullspace conservation +checks, and a bipartite graph export preserving catalysts and coefficients. Rates +carry canonical concentration/time units and provenance. Each species and the +network carry provenance; context names the modeled system/compartment. All +states and rates in this contribution are explicitly artificial, with no fitting. + +A from-scratch classical RK4 solver integrates `dC/dt = S v(C)` and optional +analytic forward sensitivities with respect to local dimensionless multipliers +on effective reaction rates. The product-rule Jacobian is valid at zero +concentration. Ordered phases expose retain/add operations and rate multipliers, +record both sides of every state jump, and reset unspecified rate multipliers to +base values in each phase. Negative or nonfinite states fail without clipping. +The numerical implementation reuses NumPy arithmetic, not SciPy's ODE solver. + +The main implementation is general library functionality. Project Asma context, +companion work and optional cross-repository reproduction stay in the fork's +[coordination document](../../docs/project-asma-integration.md). + +## Validation — independent mathematical and engine authorities + +Authorities were not tuned to implementation outputs: + +1. For `A -> B`, `A(t)=A0 exp(-kt)`, `B(t)=A0+B0-A(t)` and multiplier derivative + `dA/dm=-kt A(t)`. Reversible conversion is separately tested against its exact + equilibrium-plus-exponential solution. +2. For `2A -> D`, `A(t)=A0/(1+2kA0t)`, `D(t)=D0+(A0-A(t))/2`, and + `dA/dm=-A0(2kA0t)/(1+2kA0t)^2`. `A+2D` is exactly conserved structurally. +3. For `A+B <-> C`, a separate, hand-written three-equation system is integrated + by SciPy DOP853 (`rtol=2e-13`, `atol=2e-14`). This referee does not reuse our + stoichiometric matrix, flux or Jacobian. Rate sensitivities are independently + checked by central differences of that solver. +4. Scalar retention and homogeneous linear flow commute exactly by linear + algebra. Selective retention and nonlinear dimerization provide boundary + counterexamples; their outcomes are also checked against exact solutions. + +The [machine-readable results](results.json) were generated with Python 3.12.14, +NumPy 2.5.4 and SciPy 1.18.1. Maximum absolute discrepancies over the stated +sampling grids are below; they are numerical errors, **not** statistical or +biological uncertainty estimates. Rate/state parameters and grids are in the +reproduction script, with no external dataset or parameter search. + +| Quantity | Authority | Maximum absolute error (mol/L) | Acceptance bound (mol/L) | +|---|---|---:|---:| +| Linear trajectory, 21 samples to 5 s, step <=0.01 s | Exact exponential | 1.479e-11 | 2e-10 | +| Linear multiplier sensitivity | Exact derivative | 6.065e-11 | 2e-10 | +| Dimerization trajectory, 17 samples to 4 s, step <=0.005 s | Exact rational solution | 1.160e-11 | 2e-10 | +| Dimerization multiplier sensitivity | Exact derivative | 4.777e-11 | 2e-10 | +| Dimer conserved pool drift | Exact initial monomer pool | 2.887e-15 | 1e-14 | +| Nonlinear binding, 26 samples to 5 s, step <=0.005 s | Independent DOP853 equations | 8.520e-12 | 2e-10 | +| Binding multiplier sensitivities | DOP853 central difference, epsilon=1e-4 | 8.755e-10 | 2e-9 | +| Scalar-retention linear order difference | Exact zero commutator | 1.221e-15 | 1e-14 | + +The binding finite-difference discrepancy falls from 8.697e-8 to 8.755e-10 mol/L +when epsilon falls from 1e-3 to 1e-4, consistent with central-difference truncation +error. Linear step-halving errors at 0.2, 0.1 and 0.05 s are 2.484e-6, 1.465e-7 +and 8.890e-9 mol/L, consistent with fourth-order convergence. These are measured +checks on these cases, not universal solver guarantees. + +An intentionally incorrect dimer pool `A+D` returns exact reaction residual -1; +`A+2D` returns exact zero. This catches a **synthetic** modeling mistake, not a +claimed new real-world biological inconsistency. A retained fraction 0.4 before +versus after nonlinear dimerization gives final A concentrations 0.327868852460 +versus 0.173913043489 mol/L, an expected 0.153955808971 mol/L difference under +those artificial equations. The same operation on the linear conversion gives +zero within 1.221e-15 mol/L. A separate remove/add event changes the conserved +pool from 2 to 1.3 mol/L; the subsequent final sum is 1.3000000000000003 mol/L. + +No parameter was fitted. The full Python suite passed: **153 tests, no skips, +62.85 seconds**, including 42 new focused cases; checked-in and +regenerated JavaScript engine fixtures both passed. Regenerated molecular +fixtures were restored because the molecular engines and inputs are unchanged. +Test coverage includes source/sink and inert networks, +zero concentrations/rates, exact conservation, graph catalyst topology, state +mapping order, invalid stoichiometry/units/provenance, failed integration, +observation grids, resource bounds and explicit intervention semantics. + +## Limits + +This is a deterministic single-compartment elementary-rate-law engine. It does +not support SBML, changing volumes, inter-compartment transport, stiff adaptive +integration, empirical kinetic laws, events triggered by state, uncertainty +propagation or parameter fitting. A fixed step must be convergence-checked for +each new model. Exact nullspace calculations can be costly for large networks. + +Sensitivity is local to a single trajectory with initial conditions held fixed; +it does not propagate through protocol interventions. The zero-rate multiplier +derivative is zero, not an estimate of the effect of adding a new process. Source +strings and contexts are required declarations, not evidence certification. + +No anti-Yo recognition, ovarian cancer response, patient outcome or clinical +benefit is modeled or validated here. No private data was used. Mathematical +commutativity under a specific linear model does not establish real treatment +order equivalence. The full Track E BioModels import/invariant milestone remains +open, and none of the upstream molecular/PBPK/quantum engines are changed. + +## Reproduce + +```bash +PYTHONPATH=. OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 \ + python scripts/validate_reaction_experiments.py \ + --output auto-research/2026-11-05-E-reaction-experiments/results.json +PYTHONPATH=. OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 \ + python -m pytest -q +node web/test_engines.mjs +``` + +## References + +- Exact solutions above follow by separation of variables and differentiation; + the linear intervention null follows from scalar-matrix commutation. +- Hairer, Nørsett and Wanner, *Solving Ordinary Differential Equations I: + Nonstiff Problems*, 2nd edition (1993), classical Runge–Kutta methods. + +- Virtanen et al., SciPy 1.0 (2020), *Nature Methods* 17:261–272. + +- SciPy `solve_ivp` DOP853 documentation: + diff --git a/auto-research/2026-11-05-E-reaction-experiments/results.json b/auto-research/2026-11-05-E-reaction-experiments/results.json new file mode 100644 index 0000000..7770d32 --- /dev/null +++ b/auto-research/2026-11-05-E-reaction-experiments/results.json @@ -0,0 +1,100 @@ +{ + "schema_version": 1, + "scope": "Synthetic mathematical verification only; no biological parameter fit or validation", + "provenance": [ + "Artificial mathematical fixture, all rates/states selected for numerical verification" + ], + "environment": { + "python": "3.12.14", + "numpy": "2.5.4", + "scipy": "1.18.1" + }, + "units": { + "concentration": "mol/L", + "time": "s", + "sensitivity_parameter": "dimensionless local effective-rate multiplier" + }, + "metrics": { + "linear_trajectory_max_abs_error_mol_per_L": 1.4789502955636635e-11, + "linear_sensitivity_max_abs_error_mol_per_L": 6.064693192087134e-11, + "dimer_trajectory_max_abs_error_mol_per_L": 1.1604717187196911e-11, + "dimer_sensitivity_max_abs_error_mol_per_L": 4.7774117994947574e-11, + "dimer_conserved_monomers_max_drift_mol_per_L": 2.886579864025407e-15, + "nonlinear_binding_vs_DOP853_max_abs_error_mol_per_L": 8.519518424066064e-12 + }, + "acceptance_thresholds": { + "linear_trajectory_max_abs_error_mol_per_L": 2e-10, + "linear_sensitivity_max_abs_error_mol_per_L": 2e-10, + "dimer_trajectory_max_abs_error_mol_per_L": 2e-10, + "dimer_sensitivity_max_abs_error_mol_per_L": 2e-10, + "dimer_conserved_monomers_max_drift_mol_per_L": 1e-14, + "nonlinear_binding_vs_DOP853_max_abs_error_mol_per_L": 2e-10 + }, + "binding_sensitivity_vs_independent_central_difference": [ + { + "relative_difference_step": 0.001, + "max_abs_error_mol_per_L": 8.696595277246644e-08 + }, + { + "relative_difference_step": 0.0001, + "max_abs_error_mol_per_L": 8.754846847480735e-10 + } + ], + "rk4_step_halving": [ + { + "max_step_s": 0.2, + "abs_error_mol_per_L": 2.484443473338427e-06 + }, + { + "max_step_s": 0.1, + "abs_error_mol_per_L": 1.464574964082921e-07 + }, + { + "max_step_s": 0.05, + "abs_error_mol_per_L": 8.890145675177763e-09 + } + ], + "exact_dimer_pool_residuals": { + "correct_A_plus_2D": { + "dimerize": "0" + }, + "incorrect_A_plus_D": { + "dimerize": "-1" + } + }, + "linear_scalar_retention_order": { + "retention_then_flow_mol_per_L": { + "A": 0.09796514260652593, + "B": 0.7020348573934749 + }, + "flow_then_retention_mol_per_L": { + "A": 0.09796514260652595, + "B": 0.7020348573934737 + }, + "max_abs_difference_mol_per_L": 1.2212453270876722e-15 + }, + "nonlinear_scalar_retention_order": { + "retention_then_flow_mol_per_L": { + "A": 0.32786885245993896, + "D": 0.23606557377003065 + }, + "flow_then_retention_mol_per_L": { + "A": 0.17391304348903505, + "D": 0.3130434782554825 + }, + "max_abs_difference_mol_per_L": 0.1539558089709039 + }, + "external_exchange": { + "before_total_mol_per_L": 2.0, + "after_total_mol_per_L": 1.3, + "final_total_mol_per_L": 1.3000000000000003, + "expected_after_total_mol_per_L": 1.3 + }, + "limits": [ + "No SBML importer or Track E completion", + "No clinical predictions or parameter estimation", + "Finite-step explicit RK4; reject negative states; choose converged step for each model", + "Sensitivity holds initial state fixed and does not propagate through protocol jumps", + "Conservation laws are structural; elemental composition is not inferred" + ] +} diff --git a/auto-research/README.md b/auto-research/README.md index 31f10a3..203c0b7 100644 --- a/auto-research/README.md +++ b/auto-research/README.md @@ -25,3 +25,4 @@ auto-research/ |---|---|---|---|---|---| | 2026-11-05 | E (partial) | [Explicit model contracts](2026-11-05-E-model-contracts/report.md) | Exact scalar mass balance; interface rejection cases | 0 L/h max error on 4 synthetic cases; 60 focused tests pass | OpenAI Codex / @ahrazzle | | 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 | diff --git a/docs/project-asma-integration.md b/docs/project-asma-integration.md index 281d282..a39b392 100644 --- a/docs/project-asma-integration.md +++ b/docs/project-asma-integration.md @@ -114,3 +114,72 @@ stack or a clinically validated model. This contributing session did not merge i No automatic merge, deployment, background research run or patient simulation is introduced by this workflow. Further simulation work needs a defined biological question, applicable inputs and validation that can resolve that question. + +## 2026-11-05 update: executable synthetic intervention checks + +Fork [PR #1](https://github.com/Foundation-0/virtual-human/pull/1) was merged by +the team at 14:53:50 UTC as +`3236b915e659ab96ba862dce3c07930846b561d8`. The contribution below branches from +that merged main. This contributing session did not merge it, and no original +upstream posting or permission retry was needed. + +The next reusable increment, [fork PR #3](https://github.com/Foundation-0/virtual-human/pull/3), adds +[reaction networks and ordered interventions](reaction_experiments.md): elementary +mass-action dynamics in one fixed compartment, exact rational conserved-pool +checks, graph export, analytic local rate-multiplier sensitivities, and explicit +per-phase state/rate interventions. Its +[report](../auto-research/2026-11-05-E-reaction-experiments/report.md) distinguishes +exact structural statements from integration errors and externally changed pools. +Maximum trajectory discrepancy in the report is 1.479e-11 mol/L against exact +kinetics; nonlinear binding agrees with an independently written DOP853 system +to 8.520e-12 mol/L. All states, rates and interventions are artificial. + +The immediate Asma research need is to test treatment-sequence **assumptions** +raised by the public Rosen/Gu work, implemented in +[Asma PR #47](https://github.com/Foundation-0/project-asma/pull/47). Its initial +implementation commit is `aca2556dfdde3ceca8c0c2da1bfab0105eb21e7d`; +The bridge was rerun against clean Asma revision +`03d6cad7eaa97cf6e332515f6e5e0a9172b5addc`; the exact module is unchanged. +`tools/analyze_treatment_sequence.py` has SHA-256 +`0b3492e8b9fcc9dd2b7100d81552e212bc0f9c1aeed420b40bb76a9c93cb7a1b`. Scalar proportional removal commutes with +homogeneous linear dynamics. A fixed absolute residual operation is a different, +state-dependent map. The VH engine exposes those choices rather than assigning +clinical meaning to them. Selective removal and nonlinear kinetics are explicit +counterexamples to extrapolating the scalar/linear null case. + +An optional fork-specific bridge check is provided by +[`scripts/validate_asma_interventions.py`](../scripts/validate_asma_interventions.py). +It uses a **trusted local** Asma checkout containing +`tools/analyze_treatment_sequence.py`; it does not download code or add Asma as a +runtime/test-suite dependency. The three artificial fixtures compare twelve +named intervention-order outcomes with exact rational operators from the Asma +experiment. Maximum absolute discrepancy is 4.8531e-14 mol/L, below the declared +1e-10 mol/L tolerance. A fixed-residual operation remains explicit caller logic, +converted to named retention fractions before passing it to the VH protocol. + +```bash +# Use a trusted checkout of the companion Asma research branch/PR. +PYTHONPATH=. python scripts/validate_asma_interventions.py \ + --asma-root /path/to/project-asma +``` + +The [recorded bridge output](../auto-research/2026-11-05-E-reaction-experiments/bridge-results.json) +contains checkout commits, dirty flags and SHA-256 hashes of the actual three +executed source files. Dirty flags deliberately distinguish worktree code from a +clean committed revision. Values are reused as artificial mol/L concentrations +in VH and arbitrary burden units in Asma to compare the same mathematics; this +is **not a physiological unit conversion**. The bridge does not reproduce the +full published Gu model or analyze a clinical dataset. + +This enables explicit hypothesis-testing software experiments, not simulated +human disease. No patient data, anti-Yo mechanism claim, treatment recommendation +or validation of individual outcomes enters either the bridge or the library. +The Track E BioModels SBML milestone remains open. Fork-specific coordination +and the optional bridge are separate from the reusable library commit for future +upstream review. + +Verification for this increment: **153 Python tests passed with no skips** in +62.85 seconds, including 42 new focused cases. JavaScript engine checks passed +against both checked-in and regenerated fixtures, with worst plasma-profile +relative error 4.8e-13 over 48 points. Regenerated molecular fixtures were not +retained. This is numerical software verification, not biological validation. diff --git a/docs/reaction_experiments.md b/docs/reaction_experiments.md new file mode 100644 index 0000000..3041c72 --- /dev/null +++ b/docs/reaction_experiments.md @@ -0,0 +1,135 @@ +# Explicit reaction and intervention experiments + +`vh.graph.reactions` supplies a small numerical testing engine for elementary +mass-action networks in **one fixed, well-mixed compartment**. Its purpose is to +make assumed dynamics, conserved pools and ordered interventions executable and +checkable. Model equations and parameter provenance must be supplied by the +caller. A graph cannot choose those assumptions or establish biological truth. + +The engine computes concentrations in **mol/L** and time in **seconds**, with no +implicit conversions. All examples below are artificial mathematical fixtures; +the magnitudes do not represent biological measurements. Initial values and the +choice of observation times must be covered by the caller's recorded experiment +provenance. Required source strings are audit metadata, not verified evidence. + +```python +from vh.graph.reactions import ( + Species, Reaction, ReactionNetwork, Phase, run_protocol, +) + +source = ("Artificial demonstration: initial A=2, B=0 mol/L; k=0.7 /s",) +network = ReactionNetwork( + [Species("A", source), Species("B", source)], + [Reaction("convert", {"A": 1}, {"B": 1}, 0.7, "1/s", source)], + context={"system": "synthetic", "compartment": "fixed-volume"}, + provenance=source, +) +trajectory = network.simulate( + {"A": 2, "B": 0}, [0, 1, 2, 3], max_step_s=0.01, + sensitivity_reactions=["convert"], +) +assert network.pool_residuals({"A": 1, "B": 1}) == {"convert": 0} +print(trajectory.final) + +protocol = run_protocol(network, {"A": 2, "B": 0}, [ + Phase("paused", 2, source, rate_scales={"convert": 0}), + Phase("exchange_then_evolve", 1, source, + retain={"A": 0.5}, add={"B": 0.3}), +], max_step_s=0.01) +assert protocol[1].before == {"A": 2, "B": 0} +assert protocol[1].after == {"A": 1, "B": 0.3} +``` + +## Equations and structural checks + +For stoichiometric matrix `S = products - reactants`, the engine evaluates +`dC/dt = S v(C)` with `v_j = k_j product_i C_i**reactant_ij`. Stoichiometric +coefficients are positive integers, including the elementary reaction order. +A source has an empty reactant mapping and a sink has an empty product mapping. +Reversible reactions are two separately named one-way reactions. This is a +deterministic concentration rate law, without stochastic combinatorial factors. + +Canonical rate units are `mol/L/s` (order zero), `1/s` (order one), and +`(mol/L)^-1/s` (order two); `rate_unit(order)` supplies the exact string for any +nonnegative integer order. A non-elementary empirical rate law must not be +encoded by pretending its stoichiometry defines the kinetic orders. No Hill, +Michaelis–Menten, activity, diffusion or transport law is inferred. + +`conservation_basis()` computes the exact rational left nullspace of `S` by row +reduction. Its basis may contain signed combinations and is not automatically a +set of physical moieties. `pool_residuals(weights)` independently checks a named +integer/rational pool per reaction. In `2A -> D`, `A + 2D` has residual zero, +whereas `A + D` has residual -1. Those are exact structural statements, distinct +from numerical drift along an integrated trajectory. Elemental composition, +charge and mass are not known unless separately supplied and checked as pools. +The basis does not prove that the asserted reactions occur in a real system. + +`to_graph()` produces a **declarative bipartite graph** with species and reaction +nodes and reactant/product edges. Coefficients, rates, context and provenance +survive export; catalysts occur on both sides. Prefixes disambiguate a species +and a reaction with the same identifier. The exported graph does not register +executable callbacks and is not an SBML representation or round-trip importer. + +## Numerical execution and sensitivity + +The solver is from-scratch classical fixed-step RK4. Each requested observation +interval is split into equal steps no larger than `max_step_s`. It neither clips +negative concentrations nor returns a partial trajectory as success: negative or +nonfinite intermediate/final states raise `ValueError`. `max_steps` defaults to +one million for each `simulate` call, bounding accidental requests for enormous +work. This is not an adaptive error estimate; rerun at smaller steps and verify +convergence for the model and outputs being tested. Stiff networks need another +solver. Large networks can also make exact rational elimination expensive. + +Forward sensitivity for reaction j is `dC/dm_j` at `m_j=1`, where `m_j` multiplies +that reaction's **effective rate after `rate_scales`**. It is not an absolute-rate +derivative. The augmented equation is `dZ/dt = J(C) Z + S[:,j] v_j`, with zero +initial sensitivity and the analytic product-rule Jacobian. This avoids dividing +by concentration at zero. Sensitivities have concentration units because the +multiplier is dimensionless. A zero effective rate gives zero multiplier +sensitivity; it does not imply that adding a previously absent reaction is +irrelevant. Initial conditions are held fixed. No parameter fitting, uncertainty +propagation, global sensitivity or identifiability certification is performed. + +## Ordered interventions + +Each phase first applies `C_after = retain * C_before + add`, then evolves for its +specified duration. Omitted retain/add entries are one/zero. A phase may have zero +duration to record an instantaneous event. `rate_scales` are relative to network +base rates in **each phase**; omitted entries reset to one, never inherit a prior +phase's setting. Phase names must be unique. Every returned `PhaseResult` records +`before`, `after`, `start_s`, the phase definition/provenance and a trajectory with +local time. Additions are mol/L, with the same fixed compartment volume throughout. + +External events can deliberately change a conserved pool. Check its dynamics +against the **post-event** pool value and account for the jump separately. In the +example, `A+B` changes from 2 to 1.3 mol/L at the exchange and remains 1.3 during +the following dynamics. A protocol does not expose sensitivities: derivatives +through interventions or across phases have not been implemented. + +Equal scalar retention commutes with any homogeneous linear flow: +`exp(Mt) (q I) C = (q I) exp(Mt) C`. The exact null case is useful for checking a +claimed intervention-order effect. It does not extend to selective retention, +nonlinear reactions, differing schedules or nonlinear/state-dependent growth. Tests include both +selective linear and scalar nonlinear counterexamples. These are mathematical +boundaries, not comparative treatment recommendations. + +Keep a network definition fixed after construction; its public definitions and +cached matrices are not a supported mutation interface. Make a new network for +changed equations, or use explicit rate scales for parameter interventions. + +## Validation and current boundary + +Run the report and tests with: + +```bash +PYTHONPATH=. python scripts/validate_reaction_experiments.py +PYTHONPATH=. python -m pytest -q tests/test_reaction_experiments.py +``` + +The [report](../auto-research/2026-11-05-E-reaction-experiments/report.md) records +closed-form linear and dimerization comparisons, independently written nonlinear +binding equations integrated by SciPy DOP853, central-difference sensitivity +checks, step convergence and intervention null/counterexamples. No model was fit. +This is an incremental Track E contribution: there is no BioModels SBML import, +real biological inconsistency claim, patient simulation or validated clinical use. diff --git a/scripts/validate_asma_interventions.py b/scripts/validate_asma_interventions.py new file mode 100644 index 0000000..06e2994 --- /dev/null +++ b/scripts/validate_asma_interventions.py @@ -0,0 +1,113 @@ +"""Optional cross-repository check of wholly synthetic intervention operators. + +Run with a trusted Project Asma checkout; this imports its local Python module. +The same invented numbers are used as mol/L in Virtual Human and arbitrary +burden units in Asma. This is a numerical comparison, not a physiological unit +conversion, clinical model, reproduction of Gu et al., or dataset analysis. +Asma is not a package/runtime dependency and no files are downloaded. +""" +from __future__ import annotations + +import argparse +from fractions import Fraction as F +from hashlib import sha256 +import importlib.util +import json +from math import log +from pathlib import Path +import subprocess + +from vh.graph.reactions import Phase, Reaction, ReactionNetwork, Species, run_protocol + +SOURCE = ("Original artificial mathematical fixture; no empirical calibration",) + + +def revision(root): + """Report revision and dirty state so a hash does not imply a clean checkout.""" + def git(*args): + return subprocess.check_output(["git", "-C", str(root), *args], text=True).strip() + try: + return {"commit": git("rev-parse", "HEAD"), + "dirty": bool(git("status", "--porcelain"))} + except (OSError, subprocess.CalledProcessError): + return {"commit": None, "dirty": None} + + +def validate(asma_root): + exact_path = asma_root / "tools/analyze_treatment_sequence.py" + spec = importlib.util.spec_from_file_location("asma_exact_sequence", exact_path) + if spec is None or spec.loader is None: + raise ValueError("cannot load the trusted Asma exact-arithmetic module") + exact = importlib.util.module_from_spec(spec) + spec.loader.exec_module(exact) + vh_root = Path(__file__).resolve().parents[1] + rows = [] + # Main contrast, no selective enrichment, and a target above available burden. + for label, a, b, q in (("selective", F(1, 10), F(1), F(1, 10)), + ("nonselective", F(1, 2), F(1, 2), F(1, 10)), + ("capped", F(1, 10), F(1, 2), F(1, 2))): + initial_exact = (F(9, 10), F(1, 10)) + initial = dict(zip(("S", "R"), map(float, initial_exact))) + model = ReactionNetwork( + [Species(name, SOURCE) for name in initial], + [Reaction("loss_S", {"S": 1}, {}, -log(float(a)), "1/s", SOURCE), + Reaction("loss_R", {"R": 1}, {}, -log(float(b)), "1/s", SOURCE)], + context={"system": "synthetic", "compartment": "constant-volume"}, + provenance=SOURCE, + ) + expected = exact.compare(initial_exact, a, b, q) + evolve = Phase("evolve", 1, SOURCE) + + def run(state, phases): + return run_protocol(model, state, phases, max_step_s=0.001)[-1].trajectory.final + + retain = {name: float(q) for name in initial} + first = run(initial, [Phase("retain-then-evolve", 1, SOURCE, retain=retain)]) + prop_last = run(initial, [evolve, Phase("retain", 0, SOURCE, retain=retain)]) + pre_last = run(initial, [evolve]) + # State-dependent removal is explicit caller logic, not a hidden VH rule. + target = float(q * sum(initial_exact)) + fraction = min(1.0, target / sum(pre_last.values())) + fixed_last = run(pre_last, [Phase("fixed-residual", 0, SOURCE, + retain={name: fraction for name in initial})]) + comparisons = (("proportional_surgery_first", first), + ("proportional_chemo_first", prop_last), + ("fixed_surgery_first", first), + ("fixed_chemo_first", fixed_last)) + errors = {name: max(abs(observed[key] - float(F(expected[name][field]))) + for key, field in (("S", "sensitive"), ("R", "resistant"))) + for name, observed in comparisons} + rows.append({"fixture": label, "a": str(a), "b": str(b), "q": str(q), + "maximum_absolute_error_mol_per_L": max(errors.values()), + "comparison_errors_mol_per_L": errors, + "exact_fixed_after_to_before_resistant_ratio": + expected["fixed_after_to_before_resistant_ratio"]}) + maximum = max(row["maximum_absolute_error_mol_per_L"] for row in rows) + tolerance = 1e-10 + result = { + "status": "pass" if maximum <= tolerance else "fail", + "scope": "synthetic_operator_consistency_only_not_biological_validation", + "as_of": "2026-11-05", + "authority": "Project Asma exact rational operators and explicit linear-flow solution", + "asma_checkout": revision(asma_root), "virtual_human_checkout": revision(vh_root), + "source_sha256": {"asma_exact_module": sha256(exact_path.read_bytes()).hexdigest(), + "vh_reactions_module": sha256((vh_root / "vh/graph/reactions.py").read_bytes()).hexdigest(), + "comparison_script": sha256(Path(__file__).read_bytes()).hexdigest()}, + "tolerance_absolute_mol_per_L": tolerance, + "maximum_absolute_error_mol_per_L": maximum, + "fixtures": rows, + "limitations": ["invented quantities and rates", "no physiological conversion", + "fixed-residual map explicitly applied outside the VH protocol runner", + "no full Gu model, patient model, survival inference or clinical recommendation"], + } + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--asma-root", required=True, type=Path, + help="trusted local Project Asma checkout containing the exact operator module") + args = parser.parse_args() + result = validate(args.asma_root.resolve()) + print(json.dumps(result, indent=2)) + raise SystemExit(0 if result["status"] == "pass" else 1) diff --git a/scripts/validate_reaction_experiments.py b/scripts/validate_reaction_experiments.py new file mode 100644 index 0000000..31a08a6 --- /dev/null +++ b/scripts/validate_reaction_experiments.py @@ -0,0 +1,145 @@ +"""Reproduce synthetic reaction/intervention validation; no fitted parameters. + +Run with PYTHONPATH=. python scripts/validate_reaction_experiments.py [--output PATH] +Exact solutions and independent hand-written DOP853 equations are the referees. +""" +import argparse +import json +import platform +from math import exp +from pathlib import Path + +import numpy as np +import scipy +from scipy.integrate import solve_ivp + +from vh.graph.reactions import Phase, Reaction, ReactionNetwork, Species, rate_unit, run_protocol + +SOURCE = ("Artificial mathematical fixture, all rates/states selected for numerical verification",) + + +def make_network(ids, reactions): + return ReactionNetwork([Species(s, SOURCE) for s in ids], + [Reaction(name, left, right, rate, rate_unit(sum(left.values())), SOURCE) + for name, left, right, rate in reactions], + context={"system": "synthetic", "compartment": "fixed well-mixed volume"}, provenance=SOURCE) + + +def run(): + linear = make_network(["A", "B"], [("forward", {"A": 1}, {"B": 1}, 0.7)]) + times = np.linspace(0, 5, 21) + trace = linear.simulate({"A": 2, "B": 0}, times, max_step_s=0.01, + sensitivity_reactions=["forward"]) + a = 2*np.exp(-0.7*times) + da = -0.7*times*a + linear_error = float(np.max(np.abs(trace.concentrations-np.column_stack((a, 2-a))))) + linear_sensitivity_error = float(np.max(np.abs(trace.sensitivities[:, :, 0]-np.column_stack((da, -da))))) + dimer = make_network(["A", "D"], [("dimerize", {"A": 2}, {"D": 1}, 0.3)]) + dtimes = np.linspace(0, 4, 17) + dtrace = dimer.simulate({"A": 2, "D": 0}, dtimes, max_step_s=0.005, + sensitivity_reactions=["dimerize"]) + dexact = 2/(1+1.2*dtimes) + ds_exact = -2*1.2*dtimes/(1+1.2*dtimes)**2 + dimer_error = float(np.max(np.abs(dtrace.concentrations[:, 0]-dexact))) + dimer_sensitivity_error = float(np.max(np.abs(dtrace.sensitivities[:, 0, 0]-ds_exact))) + pool_drift = float(np.max(np.abs(dtrace.concentrations @ [1, 2]-2))) + binding = make_network(["A", "B", "C"], [ + ("on", {"A": 1, "B": 1}, {"C": 1}, 1.1), + ("off", {"C": 1}, {"A": 1, "B": 1}, 0.2)]) + btimes = np.linspace(0, 5, 26) + btrace = binding.simulate({"A": 1.2, "B": 0.8, "C": 0}, btimes, max_step_s=0.005, + sensitivity_reactions=["on", "off"]) + + def referee(on=1.1, off=0.2): + def rhs(t, state): + v = on*state[0]*state[1]-off*state[2] + return [-v, -v, v] + solution = solve_ivp(rhs, [0, 5], [1.2, 0.8, 0], method="DOP853", + t_eval=btimes, rtol=2e-13, atol=2e-14) + if not solution.success: + raise RuntimeError(solution.message) + return solution.y.T + + binding_error = float(np.max(np.abs(btrace.concentrations-referee()))) + sensitivity_errors = [] + for epsilon in (1e-3, 1e-4): + errors = [] + for j in range(2): + plus, minus = [1.1, 0.2], [1.1, 0.2] + plus[j] *= 1+epsilon + minus[j] *= 1-epsilon + reference = (referee(*plus)-referee(*minus))/(2*epsilon) + errors.append(float(np.max(np.abs(btrace.sensitivities[:, :, j]-reference)))) + sensitivity_errors.append({"relative_difference_step": epsilon, "max_abs_error_mol_per_L": max(errors)}) + + convergence = [] + for step in (0.2, 0.1, 0.05): + result = linear.simulate({"A": 2, "B": 0}, [0, 2], max_step_s=step) + convergence.append({"max_step_s": step, "abs_error_mol_per_L": abs(result.final["A"]-2*exp(-1.4))}) + + def order_test(model, initial): + retention = {s: 0.4 for s in model.ids} + before = run_protocol(model, initial, [Phase("retention_then_flow", 3, SOURCE, retain=retention)], max_step_s=0.01) + after = run_protocol(model, initial, [Phase("flow", 3, SOURCE), + Phase("retention", 0, SOURCE, retain=retention)], max_step_s=0.01) + left, right = before[-1].trajectory.final, after[-1].trajectory.final + return {"retention_then_flow_mol_per_L": left, "flow_then_retention_mol_per_L": right, + "max_abs_difference_mol_per_L": max(abs(left[s]-right[s]) for s in model.ids)} + + linear_order = order_test(linear, {"A": 2, "B": 0}) + nonlinear_order = order_test(dimer, {"A": 2, "D": 0}) + jump = run_protocol(linear, {"A": 2, "B": 0}, [ + Phase("paused", 2, SOURCE, rate_scales={"forward": 0}), + Phase("external_exchange", 1, SOURCE, retain={"A": 0.5}, add={"B": 0.3})], max_step_s=0.01) + metrics = { + "linear_trajectory_max_abs_error_mol_per_L": linear_error, + "linear_sensitivity_max_abs_error_mol_per_L": linear_sensitivity_error, + "dimer_trajectory_max_abs_error_mol_per_L": dimer_error, + "dimer_sensitivity_max_abs_error_mol_per_L": dimer_sensitivity_error, + "dimer_conserved_monomers_max_drift_mol_per_L": pool_drift, + "nonlinear_binding_vs_DOP853_max_abs_error_mol_per_L": binding_error, + } + thresholds = {name: 2e-10 for name in metrics} + thresholds["dimer_conserved_monomers_max_drift_mol_per_L"] = 1e-14 + for name, value in metrics.items(): + if value > thresholds[name]: + raise AssertionError(f"{name}: {value} exceeds {thresholds[name]}") + if sensitivity_errors[-1]["max_abs_error_mol_per_L"] > 2e-9: + raise AssertionError("binding sensitivity mismatch") + if linear_order["max_abs_difference_mol_per_L"] > 1e-14: + raise AssertionError("linear scalar-retention commutativity failed") + if nonlinear_order["max_abs_difference_mol_per_L"] < 0.1: + raise AssertionError("nonlinear counterexample failed") + return { + "schema_version": 1, + "scope": "Synthetic mathematical verification only; no biological parameter fit or validation", + "provenance": SOURCE, + "environment": {"python": platform.python_version(), "numpy": np.__version__, "scipy": scipy.__version__}, + "units": {"concentration": "mol/L", "time": "s", "sensitivity_parameter": "dimensionless local effective-rate multiplier"}, + "metrics": metrics, "acceptance_thresholds": thresholds, + "binding_sensitivity_vs_independent_central_difference": sensitivity_errors, + "rk4_step_halving": convergence, + "exact_dimer_pool_residuals": {"correct_A_plus_2D": {k: str(v) for k, v in dimer.pool_residuals({"A": 1, "D": 2}).items()}, + "incorrect_A_plus_D": {k: str(v) for k, v in dimer.pool_residuals({"A": 1, "D": 1}).items()}}, + "linear_scalar_retention_order": linear_order, + "nonlinear_scalar_retention_order": nonlinear_order, + "external_exchange": {"before_total_mol_per_L": sum(jump[1].before.values()), + "after_total_mol_per_L": sum(jump[1].after.values()), + "final_total_mol_per_L": sum(jump[1].trajectory.final.values()), + "expected_after_total_mol_per_L": 1.3}, + "limits": ["No SBML importer or Track E completion", "No clinical predictions or parameter estimation", + "Finite-step explicit RK4; reject negative states; choose converged step for each model", + "Sensitivity holds initial state fixed and does not propagate through protocol jumps", + "Conservation laws are structural; elemental composition is not inferred"], + } + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + text = json.dumps(run(), indent=2, allow_nan=False)+"\n" + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(text) + print(text, end="") diff --git a/tests/test_reaction_experiments.py b/tests/test_reaction_experiments.py new file mode 100644 index 0000000..01a3821 --- /dev/null +++ b/tests/test_reaction_experiments.py @@ -0,0 +1,266 @@ +"""Independent exact kinetics, mathematical boundaries and malformed inputs.""" +from fractions import Fraction +from math import exp + +import numpy as np +import pytest +from scipy.integrate import solve_ivp + +from vh.graph.core import Graph +from vh.graph.reactions import Phase, Reaction, ReactionNetwork, Species, rate_unit, run_protocol + +SOURCE = ("Artificial mathematical fixture; not a biological measurement",) + + +def reaction(name, left, right, rate): + return Reaction(name, left, right, rate, rate_unit(sum(left.values())), SOURCE) + + +def network(ids, reactions): + return ReactionNetwork([Species(s, SOURCE) for s in ids], reactions, + context={"system": "synthetic", "compartment": "constant-volume"}, + provenance=SOURCE) + + +def conversion(k=0.7): + return network(["A", "B"], [reaction("forward", {"A": 1}, {"B": 1}, k)]) + + +def dimer(): + return network(["A", "D"], [reaction("dimerize", {"A": 2}, {"D": 1}, 0.3)]) + + +def test_irreversible_exact_trajectory_and_rate_scale_sensitivity(): + times = np.linspace(0, 5, 21) + trace = conversion().simulate({"B": 0, "A": 2}, times, max_step_s=0.01, + sensitivity_reactions=["forward"]) + a = 2 * np.exp(-0.7*times) + expected = np.column_stack((a, 2-a)) + da = -0.7*times*a + np.testing.assert_allclose(trace.concentrations, expected, atol=2e-11, rtol=0) + np.testing.assert_allclose(trace.sensitivities[:, :, 0], np.column_stack((da, -da)), atol=1e-10, rtol=0) + assert trace.species == ("A", "B") # Mapping order never chooses state order. + + +def test_reversible_equilibrium_and_transient_against_exact_solution(): + model = network(["A", "B"], [reaction("f", {"A": 1}, {"B": 1}, 0.7), + reaction("r", {"B": 1}, {"A": 1}, 0.3)]) + times = np.linspace(0, 10, 21) + trace = model.simulate({"A": 2, "B": 1}, times, max_step_s=0.01) + a = 0.9+1.1*np.exp(-times) + np.testing.assert_allclose(trace.concentrations[:, 0], a, atol=4e-11, rtol=0) + steady = model.simulate({"A": 0.9, "B": 2.1}, [0, 10], max_step_s=0.05) + np.testing.assert_allclose(steady.final["A"], 0.9, atol=1e-14) + + +def test_nonlinear_dimer_exact_kinetics_sensitivity_and_monomer_conservation(): + times = np.linspace(0, 4, 17) + trace = dimer().simulate({"A": 2, "D": 0}, times, max_step_s=0.005, + sensitivity_reactions=["dimerize"]) + a = 2/(1+1.2*times) + da = -2*1.2*times/(1+1.2*times)**2 + np.testing.assert_allclose(trace.concentrations[:, 0], a, atol=4e-11, rtol=0) + np.testing.assert_allclose(trace.sensitivities[:, 0, 0], da, atol=2e-10, rtol=0) + np.testing.assert_allclose(trace.concentrations @ [1, 2], 2, atol=1e-14, rtol=0) + assert dimer().pool_residuals({"A": 1, "D": 2}) == {"dimerize": 0} + assert dimer().pool_residuals({"A": 1, "D": 1}) == {"dimerize": -1} + assert dimer().conservation_basis() == ({"A": Fraction(1, 2), "D": Fraction(1)},) + + +def test_binding_nonlinear_trajectory_and_sensitivities_vs_independent_referee(): + model = network(["A", "B", "C"], [reaction("on", {"A": 1, "B": 1}, {"C": 1}, 1.1), + reaction("off", {"C": 1}, {"A": 1, "B": 1}, 0.2)]) + times = np.linspace(0, 5, 26) + trace = model.simulate({"A": 1.2, "B": 0.8, "C": 0}, times, max_step_s=0.005, + sensitivity_reactions=["on", "off"]) + + # Referee equations deliberately do not reuse model stoichiometry or flux code. + def referee(on=1.1, off=0.2): + def rhs(t, x): + binding = on*x[0]*x[1]-off*x[2] + return [-binding, -binding, binding] + result = solve_ivp(rhs, [0, 5], [1.2, 0.8, 0], t_eval=times, + method="DOP853", rtol=2e-13, atol=2e-14) + assert result.success + return result.y.T + + np.testing.assert_allclose(trace.concentrations, referee(), atol=5e-11, rtol=0) + epsilon = 1e-4 + for j in range(2): + plus, minus = [1.1, 0.2], [1.1, 0.2] + plus[j] *= 1+epsilon + minus[j] *= 1-epsilon + derivative = (referee(*plus)-referee(*minus))/(2*epsilon) + np.testing.assert_allclose(trace.sensitivities[:, :, j], derivative, atol=2e-9, rtol=0) + for pool in model.conservation_basis(): + assert set(model.pool_residuals(pool).values()) == {0} + + +def test_rk4_convergence_has_fourth_order_behavior(): + exact = 2*exp(-0.7*2) + errors = [abs(conversion().simulate({"A": 2, "B": 0}, [0, 2], max_step_s=h).final["A"]-exact) + for h in (0.2, 0.1, 0.05)] + assert 14 < errors[0]/errors[1] < 18 + assert 14 < errors[1]/errors[2] < 18 + + +def test_zero_rate_zero_concentration_and_zero_order_source(): + inert = conversion(0).simulate({"A": 2, "B": 0}, [0, 1], max_step_s=0.1, + sensitivity_reactions=["forward"]) + assert inert.final == {"A": 2, "B": 0} + assert not inert.sensitivities.any() + model = network(["A"], [reaction("source", {}, {"A": 1}, 0.4)]) + trace = model.simulate({"A": 0}, [0, 3], max_step_s=0.01, sensitivity_reactions=["source"]) + np.testing.assert_allclose(trace.final["A"], 1.2, atol=1e-14) + np.testing.assert_allclose(trace.sensitivities[-1, 0, 0], 1.2, atol=1e-14) + assert model.conservation_basis() == () + + +def test_no_reactions_and_full_rank_stoichiometry(): + model = network(["A", "B"], []) + assert len(model.conservation_basis()) == 2 + assert model.simulate({"A": 1, "B": 2}, [0, 1], max_step_s=1).final == {"A": 1, "B": 2} + open_model = network(["A", "B"], [reaction("a", {"A": 1}, {}, 1), reaction("b", {"B": 1}, {}, 1)]) + assert open_model.conservation_basis() == () + + +def test_graph_export_preserves_catalyst_and_stoichiometry_with_colliding_ids(): + model = network(["r", "B", "E"], [reaction("r", {"r": 2, "E": 1}, {"B": 1, "E": 1}, 0.1)]) + graph = Graph.from_dict(model.to_graph().to_dict()) + assert len(graph.nodes) == 4 + assert len(graph.edges) == 4 + assert graph.out_edges("species:r")[0].attrs["stoichiometry"] == 2 + assert graph.node("species:r").attrs["network_provenance"] == list(SOURCE) + assert graph.node("reaction:r").attrs["context"] == dict(model.context) + assert {e.type for e in graph.in_edges("species:E")+graph.out_edges("species:E")} == {"reactant", "product"} + assert model.pool_residuals({"E": 1}) == {"r": 0} + + +def test_protocol_records_external_balance_and_resets_rate_scales(): + model = conversion() + phases = [Phase("paused", 2, SOURCE, rate_scales={"forward": 0}), + Phase("remove-add", 1, SOURCE, retain={"A": 0.5}, add={"B": 0.3})] + result = run_protocol(model, {"A": 2, "B": 0}, phases, max_step_s=0.01) + assert result[0].trajectory.final == {"A": 2, "B": 0} + assert result[1].before == {"A": 2, "B": 0} + assert result[1].after == {"A": 1, "B": 0.3} + assert result[1].start_s == 2 + assert sum(result[1].trajectory.final.values()) == pytest.approx(1.3, abs=1e-14, rel=0) + assert result[1].trajectory.final["A"] == pytest.approx(exp(-0.7), abs=1e-10, rel=0) + + +def test_scalar_retention_commutes_with_linear_flow_but_not_nonlinear_flow(): + def ordered(model, initial): + retained = {s: 0.4 for s in model.ids} + before = run_protocol(model, initial, [Phase("retain", 3, SOURCE, retain=retained)], max_step_s=0.01) + after = run_protocol(model, initial, [Phase("evolve", 3, SOURCE), + Phase("retain", 0, SOURCE, retain=retained)], max_step_s=0.01) + return before[-1].trajectory.final, after[-1].trajectory.final + left, right = ordered(conversion(), {"A": 2, "B": 0}) + np.testing.assert_allclose(list(left.values()), list(right.values()), atol=1e-14, rtol=0) + left, right = ordered(dimer(), {"A": 2, "D": 0}) + assert left["A"] == pytest.approx(0.8/(1+0.6*0.8*3), abs=1e-9, rel=0) + assert right["A"] == pytest.approx(0.4*2/(1+0.6*2*3), abs=1e-9, rel=0) + assert abs(left["A"]-right["A"]) > 0.1 + + +def test_selective_retention_need_not_commute_even_in_linear_network(): + model = conversion() + before = run_protocol(model, {"A": 2, "B": 0}, [Phase("retain", 1, SOURCE, retain={"A": 0.5})], max_step_s=0.01) + after = run_protocol(model, {"A": 2, "B": 0}, [Phase("evolve", 1, SOURCE), + Phase("retain", 0, SOURCE, retain={"A": 0.5})], max_step_s=0.01) + assert before[-1].trajectory.final["B"] == pytest.approx(1-exp(-0.7), abs=1e-10, rel=0) + assert after[-1].trajectory.final["B"] == pytest.approx(2*(1-exp(-0.7)), abs=1e-10, rel=0) + + +@pytest.mark.parametrize("initial", [{"A": 1}, {"A": 1, "B": 0, "C": 2}, {"A": -1, "B": 0}, + {"A": float("nan"), "B": 0}, {"A": True, "B": 0}]) +def test_bad_initial_state_rejected(initial): + with pytest.raises(ValueError): + conversion().simulate(initial, [0, 1], max_step_s=0.01) + + +@pytest.mark.parametrize("times", [[], [1], [0, 0], [0, -1], [0, float("inf")], [0, True]]) +def test_bad_times_rejected(times): + with pytest.raises(ValueError): + conversion().simulate({"A": 1, "B": 0}, times, max_step_s=0.01) + + +@pytest.mark.parametrize("kwargs", [{"max_step_s": 0}, {"max_step_s": -1}, {"max_step_s": 1e-320}, + {"max_step_s": 0.01, "max_steps": 2}, {"max_step_s": 0.01, "max_steps": True}, + {"max_step_s": 0.01, "rate_scales": {"wrong": 1}}, + {"max_step_s": 0.01, "rate_scales": {"forward": -1}}, + {"max_step_s": 0.01, "sensitivity_reactions": ["wrong"]}, + {"max_step_s": 0.01, "sensitivity_reactions": ["forward", "forward"]}]) +def test_bad_solver_configuration_rejected(kwargs): + with pytest.raises(ValueError): + conversion().simulate({"A": 1, "B": 0}, [0, 1], **kwargs) + + +def test_unstable_step_rejected_without_clipping(): + with pytest.raises(ValueError, match="negative integration"): + conversion(10).simulate({"A": 1, "B": 0}, [0, 1], max_step_s=1) + + +def test_nonfinite_effective_rate_rejected_even_without_time_evolution(): + with pytest.raises(ValueError, match="effective rate"): + conversion(1e300).simulate({"A": 1, "B": 0}, [0], max_step_s=1, rate_scales={"forward": 1e300}) + + +@pytest.mark.parametrize("left", [{"A": 0}, {"A": -1}, {"A": 0.5}, {"A": True}]) +def test_invalid_stoichiometry_rejected(left): + with pytest.raises(ValueError): + Reaction("r", left, {"B": 1}, 1, "1/s", SOURCE) + + +def test_invalid_network_and_rate_semantics_rejected(): + with pytest.raises(ValueError, match="unit"): + Reaction("r", {"A": 2}, {}, 1, "1/s", SOURCE) + with pytest.raises(ValueError, match="unique"): + network(["A", "A"], []) + r = reaction("r", {"A": 1}, {}, 1) + with pytest.raises(ValueError, match="unique"): + network(["A"], [r, r]) + with pytest.raises(ValueError, match="unknown"): + network(["B"], [r]) + with pytest.raises(ValueError): + Species("A", ()) + with pytest.raises(ValueError): + Species("A", "not a tuple") + with pytest.raises(ValueError): + conversion().pool_residuals({"A": 0.5}) + with pytest.raises(ValueError): + conversion().pool_residuals({"wrong": 1}) + + +def test_phase_validation_and_defensive_copies(): + retain = {"A": 0.5} + phase = Phase("phase", 0, SOURCE, retain=retain) + retain["A"] = 0 + assert phase.retain["A"] == 0.5 + with pytest.raises(TypeError): + phase.retain["A"] = 0 + for kwargs in ({"retain": {"A": 1.1}}, {"add": {"A": -1}}, {"rate_scales": {"r": float("nan")}}): + with pytest.raises(ValueError): + Phase("bad", 1, SOURCE, **kwargs) + for phases in ([], [phase, phase], [Phase("wrong", 0, SOURCE, retain={"C": 1})], + [Phase("wrong", 0, SOURCE, rate_scales={"C": 1})]): + with pytest.raises(ValueError): + run_protocol(conversion(), {"A": 1, "B": 0}, phases, max_step_s=0.1) + + +def test_tiny_time_interval_does_not_underflow_step_count(): + result = conversion().simulate({"A": 1, "B": 0}, [0, 1e-300], max_step_s=1e100) + assert result.final["A"] == 1 + assert result.final["B"] == pytest.approx(0.7e-300, rel=1e-14, abs=0) + + +def test_protocol_time_overflow_rejected_before_running(): + with pytest.raises(ValueError, match="cumulative protocol time"): + run_protocol(conversion(), {"A": 1, "B": 0}, [ + Phase("one", 1e308, SOURCE), Phase("two", 1e308, SOURCE)], max_step_s=1e308) + + +def test_empty_generator_provenance_rejected(): + with pytest.raises(ValueError, match="provenance"): + Species("A", (item for item in [])) diff --git a/vh/graph/__init__.py b/vh/graph/__init__.py index 4a7d03e..b7df993 100644 --- a/vh/graph/__init__.py +++ b/vh/graph/__init__.py @@ -17,6 +17,10 @@ ModelRegistry executes an explicitly registered Edge.model with scalar interface contracts. See docs/model_contracts.md; existing engine adapters are not registered automatically, and graph reachability is not a claim of biological causation. + +For explicit elementary reaction networks and ordered interventions, import +vh.graph.reactions (NumPy required); see docs/reaction_experiments.md. This module +is intentionally not imported here, keeping the basic graph API dependency-free. """ from .core import Edge, Graph, Node, Schema # noqa: F401 diff --git a/vh/graph/reactions.py b/vh/graph/reactions.py new file mode 100644 index 0000000..f915481 --- /dev/null +++ b/vh/graph/reactions.py @@ -0,0 +1,338 @@ +"""Elementary mass-action networks in one fixed, well-mixed compartment. + +Concentrations are mol/L, time is seconds. This is a numerical research primitive, +not a biological model. See docs/reaction_experiments.md for assumptions/limits. +""" +from __future__ import annotations + +from dataclasses import dataclass, field +from fractions import Fraction +from math import ceil, isfinite +from numbers import Real +from types import MappingProxyType +from typing import Mapping + +import numpy as np + +from .core import Graph + + +def _label(value, name): + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{name} must be a nonempty string") + return value + + +def _number(value, name, minimum=0.0): + if isinstance(value, bool) or not isinstance(value, Real) or not isfinite(value) or value < minimum: + raise ValueError(f"{name} must be finite and >= {minimum}") + return float(value) + + +def _sources(values): + if isinstance(values, str): + raise ValueError("provenance must contain source identifiers") + sources = tuple(_label(v, "provenance") for v in values) + if not sources: + raise ValueError("provenance must contain source identifiers") + return sources + + +def rate_unit(order: int) -> str: + """Canonical unit of an elementary rate constant of integer reaction order.""" + if isinstance(order, bool) or not isinstance(order, int) or order < 0: + raise ValueError("order must be a nonnegative integer") + return {0: "mol/L/s", 1: "1/s"}.get(order, f"(mol/L)^{1-order}/s") + + +@dataclass(frozen=True) +class Species: + id: str + provenance: tuple[str, ...] + + def __post_init__(self): + _label(self.id, "species id") + object.__setattr__(self, "provenance", _sources(self.provenance)) + + +@dataclass(frozen=True) +class Reaction: + id: str + reactants: Mapping[str, int] + products: Mapping[str, int] + rate: float + unit: str + provenance: tuple[str, ...] + + def __post_init__(self): + _label(self.id, "reaction id") + for name in ("reactants", "products"): + side = dict(getattr(self, name)) + for species, coefficient in side.items(): + _label(species, "species id") + if isinstance(coefficient, bool) or not isinstance(coefficient, int) or coefficient <= 0: + raise ValueError("stoichiometric coefficients must be positive integers") + object.__setattr__(self, name, MappingProxyType(side)) + if not self.reactants and not self.products: + raise ValueError("a reaction must involve a species") + object.__setattr__(self, "rate", _number(self.rate, "rate")) + if self.unit != rate_unit(sum(self.reactants.values())): + raise ValueError("rate unit does not match elementary reaction order") + object.__setattr__(self, "provenance", _sources(self.provenance)) + + +def _nullspace(rows, columns): + """Exact rational nullspace by row reduction; rows are S transpose.""" + a = [[Fraction(x) for x in row] for row in rows] + pivots = [] + row = 0 + for col in range(columns): + pivot = next((i for i in range(row, len(a)) if a[i][col]), None) + if pivot is None: + continue + a[row], a[pivot] = a[pivot], a[row] + divisor = a[row][col] + a[row] = [x / divisor for x in a[row]] + for i in range(len(a)): + if i != row and a[i][col]: + multiplier = a[i][col] + a[i] = [x - multiplier * y for x, y in zip(a[i], a[row])] + pivots.append(col) + row += 1 + basis = [] + for free in sorted(set(range(columns)) - set(pivots)): + vector = [Fraction(0) for _ in range(columns)] + vector[free] = Fraction(1) + for i, pivot in enumerate(pivots): + vector[pivot] = -a[i][free] + basis.append(vector) + return basis + + +@dataclass +class Trajectory: + times_s: np.ndarray + species: tuple[str, ...] + concentrations: np.ndarray + sensitivity_reactions: tuple[str, ...] + sensitivities: np.ndarray + + @property + def final(self): + return dict(zip(self.species, self.concentrations[-1].tolist())) + + +class ReactionNetwork: + def __init__(self, species, reactions, *, context, provenance): + self.species = tuple(species) + self.reactions = tuple(reactions) + if not self.species or not all(isinstance(s, Species) for s in self.species): + raise ValueError("provide at least one Species") + if not all(isinstance(r, Reaction) for r in self.reactions): + raise ValueError("reactions must be Reaction objects") + self.ids = tuple(s.id for s in self.species) + self.reaction_ids = tuple(r.id for r in self.reactions) + if len(set(self.ids)) != len(self.ids) or len(set(self.reaction_ids)) != len(self.reaction_ids): + raise ValueError("species and reaction ids must be unique within their types") + self.context = MappingProxyType(dict(context)) + if not self.context: + raise ValueError("context must describe the modeled compartment/system") + for key, value in self.context.items(): + _label(key, "context key") + _label(value, "context value") + self.provenance = _sources(provenance) + for r in self.reactions: + if (set(r.reactants) | set(r.products)) - set(self.ids): + raise ValueError(f"reaction {r.id!r} references unknown species") + self._orders = np.array([[r.reactants.get(s, 0) for s in self.ids] + for r in self.reactions], dtype=int).reshape(len(self.reactions), len(self.ids)) + self._stoich_exact = tuple(tuple(r.products.get(s, 0) - r.reactants.get(s, 0) + for r in self.reactions) for s in self.ids) + self._stoich = np.array(self._stoich_exact, dtype=float) + + def conservation_basis(self): + """Basis of w.T S = 0, exactly. Signed combinations are not chemical mass.""" + rows = list(zip(*self._stoich_exact)) + return tuple({s: w for s, w in zip(self.ids, vector) if w} + for vector in _nullspace(rows, len(self.ids))) + + def pool_residuals(self, weights): + """Exact per-reaction residual of a declared pool (zero means conserved). + + Weights must be int/Fraction, avoiding float-to-rational ambiguity. + """ + if not weights or set(weights) - set(self.ids): + raise ValueError("pool must name known species") + if any(isinstance(w, bool) or not isinstance(w, (int, Fraction)) for w in weights.values()): + raise ValueError("pool weights must be integers or Fractions") + return {r: sum((Fraction(weights.get(s, 0)) * self._stoich_exact[i][j] + for i, s in enumerate(self.ids)), Fraction(0)) + for j, r in enumerate(self.reaction_ids)} + + def to_graph(self): + """Bipartite topology preserves multi-reactant stoichiometry and catalysts.""" + graph = Graph("reaction network") + for s in self.species: + graph.add_node(f"species:{s.id}", "chemical_species", "molecule", species_id=s.id, + context=dict(self.context), provenance=list(s.provenance), + network_provenance=list(self.provenance)) + for r in self.reactions: + rid = f"reaction:{r.id}" + graph.add_node(rid, "elementary_reaction", "molecule", reaction_id=r.id, + rate=r.rate, unit=r.unit, provenance=list(r.provenance), + context=dict(self.context), network_provenance=list(self.provenance)) + for s, n in r.reactants.items(): + graph.add_edge(f"species:{s}", rid, "reactant", stoichiometry=n) + for s, n in r.products.items(): + graph.add_edge(rid, f"species:{s}", "product", stoichiometry=n) + return graph + + def _state(self, initial): + if set(initial) != set(self.ids): + raise ValueError("initial concentrations must name every species exactly") + return np.array([_number(initial[s], f"initial {s}") for s in self.ids]) + + def _rates(self, scales): + if set(scales) - set(self.reaction_ids): + raise ValueError("rate scales name an unknown reaction") + return np.array([_number(r.rate * _number(scales.get(r.id, 1), f"rate scale {r.id}"), + f"effective rate {r.id}") for r in self.reactions]) + + def simulate(self, initial, times_s, *, max_step_s, rate_scales=None, sensitivity_reactions=(), + max_steps=1_000_000): + """RK4 trajectory and analytic local multiplicative-rate sensitivities. + + Sensitivity j is dC/dm_j at m_j=1, multiplying that reaction's *effective* + rate (after rate_scales). Initial concentrations are held fixed. + No clipping, adaptive error estimator, stiffness handling or interpolation. + """ + step = _number(max_step_s, "max_step_s") + if not step: + raise ValueError("max_step_s must be positive") + times = np.array([_number(t, "time") for t in times_s]) + if not len(times) or times[0] != 0 or np.any(np.diff(times) <= 0): + raise ValueError("times must start at zero and increase strictly") + if isinstance(max_steps, bool) or not isinstance(max_steps, int) or max_steps < 1: + raise ValueError("max_steps must be a positive integer") + step_counts = [] + for delta in np.diff(times): + ratio = float(delta) / step + if not isfinite(ratio) or ratio > max_steps: + raise ValueError("integration exceeds max_steps budget") + step_counts.append(max(1, ceil(ratio))) + if sum(step_counts) > max_steps: + raise ValueError("integration exceeds max_steps budget") + selected = tuple(sensitivity_reactions) + if len(set(selected)) != len(selected) or set(selected) - set(self.reaction_ids): + raise ValueError("sensitivity reactions must be unique known ids") + indices = [self.reaction_ids.index(r) for r in selected] + rates = self._rates({} if rate_scales is None else rate_scales) + n, p = len(self.ids), len(selected) + z = np.concatenate((self._state(initial), np.zeros(n*p))) + + def derivative(state): + x = state[:n] + if not np.all(np.isfinite(state)) or np.any(x < 0): + raise ValueError("nonfinite or negative integration state; reduce max_step_s or use another solver") + with np.errstate(over="raise", invalid="raise"): + flux = rates * np.prod(x ** self._orders, axis=1) + dx = self._stoich @ flux + if not p: + return dx + # Product rule without dividing by x: valid at zero concentration. + dv = np.zeros((len(self.reactions), n)) + for j, powers in enumerate(self._orders): + for i, power in enumerate(powers): + if power: + reduced = powers.copy() + reduced[i] -= 1 + dv[j, i] = rates[j] * power * np.prod(x ** reduced) + jacobian = self._stoich @ dv + source = self._stoich[:, indices] * flux[indices] + ds = jacobian @ state[n:].reshape(n, p) + source + return np.concatenate((dx, ds.ravel())) + + values = [z[:n].copy()] + sensitivities = [z[n:].reshape(n, p).copy()] + for start, stop, count in zip(times[:-1], times[1:], step_counts): + h = (stop-start)/count + for _ in range(count): + try: + k1 = derivative(z) + k2 = derivative(z+h*k1/2) + k3 = derivative(z+h*k2/2) + k4 = derivative(z+h*k3) + z = z + h*(k1+2*k2+2*k3+k4)/6 + except FloatingPointError as exc: + raise ValueError("integration overflow; reduce step or rescale model") from exc + if not np.all(np.isfinite(z)) or np.any(z[:n] < 0): + raise ValueError("nonfinite or negative integration result; reduce max_step_s or use another solver") + values.append(z[:n].copy()) + sensitivities.append(z[n:].reshape(n, p).copy()) + return Trajectory(times, self.ids, np.array(values), selected, np.array(sensitivities)) + + +@dataclass(frozen=True) +class Phase: + """At phase start retain fractions, then add mol/L; evolve for duration_s. + + Omitted retention/addition entries mean one/zero. Rate scales are relative to + base network rates independently in every phase, never inherited. + """ + name: str + duration_s: float + provenance: tuple[str, ...] + retain: Mapping[str, float] = field(default_factory=dict) + add: Mapping[str, float] = field(default_factory=dict) + rate_scales: Mapping[str, float] = field(default_factory=dict) + + def __post_init__(self): + _label(self.name, "phase name") + object.__setattr__(self, "duration_s", _number(self.duration_s, "duration_s")) + object.__setattr__(self, "provenance", _sources(self.provenance)) + for name in ("retain", "add", "rate_scales"): + values = {key: _number(value, name) for key, value in getattr(self, name).items()} + if name == "retain" and any(v > 1 for v in values.values()): + raise ValueError("retained fractions cannot exceed one") + object.__setattr__(self, name, MappingProxyType(values)) + + +@dataclass +class PhaseResult: + phase: Phase + start_s: float + before: dict[str, float] + after: dict[str, float] + trajectory: Trajectory + + +def run_protocol(network, initial, phases, *, max_step_s): + """Execute explicit ordered phases; preserve both sides of every state jump. + + Each trajectory uses local phase time, with start_s giving absolute offset. + Conservation applies during dynamics, not across external retain/add events. + """ + network._state(initial) + phases = tuple(phases) + if not phases or not all(isinstance(p, Phase) for p in phases): + raise ValueError("provide at least one Phase") + if len({p.name for p in phases}) != len(phases): + raise ValueError("phase names must be unique") + # Validate all operations before running any dynamics. + end_s = 0.0 + for phase in phases: + end_s = _number(end_s + phase.duration_s, "cumulative protocol time") + if (set(phase.retain) | set(phase.add)) - set(network.ids): + raise ValueError("phase state intervention names unknown species") + network._rates(phase.rate_scales) + results = [] + state, start = dict(initial), 0.0 + for phase in phases: + before = dict(state) + state = {s: state[s]*phase.retain.get(s, 1) + phase.add.get(s, 0) for s in network.ids} + times = [0, phase.duration_s] if phase.duration_s else [0] + trajectory = network.simulate(state, times, max_step_s=max_step_s, rate_scales=phase.rate_scales) + results.append(PhaseResult(phase, start, before, dict(state), trajectory)) + state = trajectory.final + start += phase.duration_s + return tuple(results) From 88bc75a1ca8b41bfcf7020d8f7d3d4a0a68966ec Mon Sep 17 00:00:00 2001 From: Zero <343039971+zero-aska@users.noreply.github.com> Date: Thu, 5 Nov 2026 10:02:00 -0600 Subject: [PATCH 07/12] Keep subgraph node order independent of hash seed (#2) Graph.subgraph iterated a set of node ids, so the order of nodes in a subgraph, and in its JSON and Mermaid output, changed with PYTHONHASHSEED. Regenerating docs/img/pbpk_elimination_subgraph.mmd reordered its node lines on every run, with no change in content. Subgraphs now keep the parent graph's insertion order and raise KeyError naming any unknown ids. A new test renders the PBPK elimination subgraph under four hash seeds and requires identical output; the test fails on the previous implementation. The regenerated Mermaid source is committed; the graph JSON and validation outputs are unchanged. Claude-Session: https://claude.ai/code/session_01CoFhtFtE7wJgvHKAzNB3xD Co-authored-by: Claude --- docs/img/pbpk_elimination_subgraph.mmd | 10 ++++---- tests/test_graph.py | 33 ++++++++++++++++++++++++++ vh/graph/core.py | 14 +++++++---- 3 files changed, 48 insertions(+), 9 deletions(-) diff --git a/docs/img/pbpk_elimination_subgraph.mmd b/docs/img/pbpk_elimination_subgraph.mmd index 1d67173..18fece9 100644 --- a/docs/img/pbpk_elimination_subgraph.mmd +++ b/docs/img/pbpk_elimination_subgraph.mmd @@ -1,12 +1,12 @@ %% Elimination subgraph (plasma-referenced reporting parameters) flowchart LR + arterial(["arterial blood"]) venous(["venous blood"]) - spleen["spleen"] eliminated[("eliminated")] - arterial(["arterial blood"]) kidney["kidney"] - gut["gut"] liver["liver"] + gut["gut"] + spleen["spleen"] pancreas["pancreas"] arterial -->|"74.1 L/h"| kidney kidney -->|"74.1 L/h"| venous @@ -21,8 +21,8 @@ flowchart LR liver -->|"CL 16.86 L/h (plasma)"| eliminated kidney -->|"CL 0.24 L/h (plasma)"| eliminated classDef c_blood fill:#C2373A,stroke:#222,color:#ffffff; - class venous,arterial c_blood; + class arterial,venous c_blood; classDef c_compartment fill:#2B44C4,stroke:#222,color:#ffffff; - class spleen,kidney,gut,liver,pancreas c_compartment; + class kidney,liver,gut,spleen,pancreas c_compartment; classDef c_sink fill:#586379,stroke:#222,color:#ffffff; class eliminated c_sink; \ No newline at end of file diff --git a/tests/test_graph.py b/tests/test_graph.py index 62cb133..cae44de 100644 --- a/tests/test_graph.py +++ b/tests/test_graph.py @@ -70,6 +70,39 @@ def test_connected_components_and_subgraph(): assert set(sub.nodes) == {"a", "b"} and len(sub.edges) == 1 +def test_subgraph_order_is_reproducible_across_hash_seeds(): + # String-set iteration order changes with PYTHONHASHSEED; a subgraph must + # follow the parent graph's order so its JSON and Mermaid are byte-stable. + import os + import subprocess + import sys + + g = Graph("ordered") + for n in "fedcba": + g.add_node(n, "x") + g.add_edge("f", "a", "e") + assert list(g.subgraph(["a", "c", "f"]).nodes) == ["f", "c", "a"] + assert list(g.subgraph(reversed(["a", "c", "f"])).nodes) == ["f", "c", "a"] + with pytest.raises(KeyError, match="unknown nodes"): + g.subgraph(["a", "missing"]) + + code = ("from vh.body import PBPKModel, MIDAZOLAM\n" + "from vh.graph.physiology_graph import build_pbpk_graph\n" + "from vh.graph.render import to_mermaid\n" + "g, _ = build_pbpk_graph(PBPKModel(MIDAZOLAM))\n" + "ids = ['arterial', 'liver', 'kidney', 'venous', 'gut', 'spleen', 'pancreas', 'eliminated']\n" + "print(to_mermaid(g.subgraph(set(ids))))\n") + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + outputs = set() + for seed in ("0", "1", "2", "3"): + env = {**os.environ, "PYTHONHASHSEED": seed, + "PYTHONPATH": os.pathsep.join(filter(None, [root, os.environ.get("PYTHONPATH")]))} + run = subprocess.run([sys.executable, "-c", code], env=env, cwd=root, + capture_output=True, text=True, check=True, timeout=120) + outputs.add(run.stdout) + assert len(outputs) == 1 + + def test_schema_validation_catches_bad_edges(): schema = Schema(node_types={"blood": set(), "organ": {"volume"}}, edge_rules=[EdgeRule("flow", {"blood", "organ"}, {"blood", "organ"}, {"flow"})]) diff --git a/vh/graph/core.py b/vh/graph/core.py index 4f93e31..2088b9d 100644 --- a/vh/graph/core.py +++ b/vh/graph/core.py @@ -120,12 +120,18 @@ def degree(self, nid: str) -> int: # --- subgraphs ----------------------------------------------------------- def subgraph(self, node_ids: Iterable[str], name: str | None = None) -> "Graph": - """Induced subgraph on the given nodes (all edges with both ends inside).""" + """Induced subgraph on the given nodes (all edges with both ends inside). + + Nodes keep this graph's insertion order, not the order (or set-iteration + order) of `node_ids`, so serialization and rendering are reproducible.""" keep = set(node_ids) + unknown = keep - self.nodes.keys() + if unknown: + raise KeyError(f"subgraph references unknown nodes {sorted(unknown)!r}") g = Graph(name or f"{self.name}:sub") - for nid in keep: - n = self.nodes[nid] - g.add_node(n.id, n.type, n.scale, n.label, **dict(n.attrs)) + for n in self.nodes.values(): + if n.id in keep: + g.add_node(n.id, n.type, n.scale, n.label, **dict(n.attrs)) for e in self.edges: if e.src in keep and e.dst in keep: g.add_edge(e.src, e.dst, e.type, e.directed, e.model, **dict(e.attrs)) From 5b8c9e5cd5ec1d3fab595d6398f90c2bc4c889bd Mon Sep 17 00:00:00 2001 From: Orda Date: Thu, 5 Nov 2026 10:10:55 -0600 Subject: [PATCH 08/12] Add ovarian HGSOC treatment-sequence parameter ledger (#5) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add cited ovarian HGSOC parameter ledger with Crossref checks Introduce a machine-readable treatment-sequence parameter ledger under data/clinical/, extending the project-asma PR #47 registry citation shape with quantitative rows (KNOWN, CONJECTURE, MISSING). Include schema validation, offline pytest coverage, CI hook, and a pinned script with an optional Crossref DOI title/author verification step. Co-authored-by: Orda * Re-verify ledger rows against open full text only Restrict KNOWN to TCGA values read from PMC3163504; downgrade trial and meta-analysis figures to CONJECTURE (abstract only) or MISSING when full text is paywalled or the abstract lacks the quantity. Correct CA-125 and HRD rows and document verification locators. Co-authored-by: Orda * Fix pytest import path and pin TCGA KNOWN ledger values Set pytest pythonpath to the repo root so CI can import scripts without PYTHONPATH. Correct P005 PMC section locators and add regression tests for verified KNOWN numeric values P002–P005. Co-authored-by: Orda --------- Co-authored-by: Cursor Agent --- .github/workflows/ci.yml | 4 +- .../README-ovarian-parameter-ledger.md | 56 +++ .../ovarian_hgsoc_parameter_ledger.json | 419 ++++++++++++++++++ ...ovarian_hgsoc_parameter_ledger.schema.json | 117 +++++ pyproject.toml | 4 + scripts/validate_ovarian_parameter_ledger.py | 230 ++++++++++ tests/test_ovarian_parameter_ledger.py | 79 ++++ 7 files changed, 908 insertions(+), 1 deletion(-) create mode 100644 data/clinical/README-ovarian-parameter-ledger.md create mode 100644 data/clinical/ovarian_hgsoc_parameter_ledger.json create mode 100644 data/clinical/ovarian_hgsoc_parameter_ledger.schema.json create mode 100644 scripts/validate_ovarian_parameter_ledger.py create mode 100644 tests/test_ovarian_parameter_ledger.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 568da03..f972b0b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,8 +18,10 @@ jobs: run: | python -m pip install --upgrade pip pip install -e ".[dev]" + - name: Parameter ledger schema (offline) + run: PYTHONPATH=. python scripts/validate_ovarian_parameter_ledger.py - name: Python tests (quantum vs experiment, engine vs OpenMM referee, body vs clinical) - run: pytest -q + run: pytest -q -m "not network" - uses: actions/setup-node@v4 with: node-version: "22" diff --git a/data/clinical/README-ovarian-parameter-ledger.md b/data/clinical/README-ovarian-parameter-ledger.md new file mode 100644 index 0000000..70bc361 --- /dev/null +++ b/data/clinical/README-ovarian-parameter-ledger.md @@ -0,0 +1,56 @@ +Research model inputs drawn from published population studies; not medical advice, dosing guidance or treatment recommendations. + +# Ovarian HGSOC parameter ledger + +Machine-readable population parameters for **high-grade serous ovarian cancer (HGSOC)** and **first-line / maintenance treatment-sequence** research models. The ledger is intended as a shared input layer for: + +- [Foundation-0/project-asma PR #47](https://github.com/Foundation-0/project-asma/pull/47) (surgical-removal assumption audits), and +- [Foundation-0/virtual-human PR #3](https://github.com/Foundation-0/virtual-human/pull/3) reaction / intervention graph experiments referenced in [`docs/project-asma-integration.md`](../docs/project-asma-integration.md). + +## Files + +| File | Role | +| --- | --- | +| [`ovarian_hgsoc_parameter_ledger.json`](ovarian_hgsoc_parameter_ledger.json) | Parameter rows | +| [`ovarian_hgsoc_parameter_ledger.schema.json`](ovarian_hgsoc_parameter_ledger.schema.json) | JSON Schema for row shape | +| [`../scripts/validate_ovarian_parameter_ledger.py`](../scripts/validate_ovarian_parameter_ledger.py) | Pinned validator | + +## Row labels + +Each row carries **`label`**: + +- **KNOWN** — numeric or categorical value read from **open full text** of the cited primary source (locator includes `verified from full text, ...`). +- **CONJECTURE** — value taken from abstract or secondary summary when full text is not openly accessible; **`derivation`** must include `value from abstract only` or an explicit derivation chain. +- **CONJECTURE** — value inferred or relayed from a secondary summary; see **`derivation`**. +- **MISSING** — quantity required for modeling but no adequate primary-source estimate; **`value`** is null (no guess). + +Every row includes **`population`**, **`units`**, **`range`** (point, CI95, IQR, etc.), **`citation`** (DOI, first author surname, year, title), **`locator`**, and **`limits`**. + +## What this extends + +The citation/locator/label pattern follows the public registry style introduced in **project-asma PR #47** (`registries/rosen-treatment-sequence-sources.json`). Virtual-human adds quantitative fields and stores the ledger under **`data/clinical/`** next to other provenance-annotated inputs (for example [`midazolam_osp_observed.json`](midazolam_osp_observed.json)). + +Schema remains compatible with that registry vocabulary; downstream tools may ignore unknown quantitative keys. + +## Validation + +**Offline (CI):** + +```bash +PYTHONPATH=. python scripts/validate_ovarian_parameter_ledger.py +PYTHONPATH=. pytest -q tests/test_ovarian_parameter_ledger.py -m "not network" +``` + +**Crossref DOI check (network; run before merging ledger changes):** + +```bash +PYTHONPATH=. python scripts/validate_ovarian_parameter_ledger.py --check-dois +``` + +The DOI step resolves each unique DOI via `https://api.crossref.org/works/` and requires **title** and **first-author surname** agreement with the ledger, not merely HTTP 200. + +## Scope limits + +- Public, published sources only; no private patient data or clinical guidance. +- Associations from observational studies and meta-analyses are not causal treatment effects. +- PK rows remain **MISSING** until a registered virtual-human model contract consumes carboplatin/paclitaxel parameters in the sequence layer. diff --git a/data/clinical/ovarian_hgsoc_parameter_ledger.json b/data/clinical/ovarian_hgsoc_parameter_ledger.json new file mode 100644 index 0000000..82b8684 --- /dev/null +++ b/data/clinical/ovarian_hgsoc_parameter_ledger.json @@ -0,0 +1,419 @@ +{ + "schema_version": 1, + "ledger_id": "ovarian-hgsoc-treatment-sequence", + "checked_on": "2026-11-05", + "scope": "Published population and trial parameters for high-grade serous ovarian cancer (HGSOC) and first-line or maintenance treatment-sequence modeling. Public primary literature only; supports Foundation-0/project-asma PR #47 assumption audits and virtual-human graph reaction experiments. Not fitted to private data.", + "extends": { + "description": "Row identifiers, citation blocks (doi, title, locator) and label vocabulary {KNOWN, CONJECTURE, MISSING} follow the public registry pattern in Foundation-0/project-asma PR #47 (registries/*-sources.json). Quantitative value/range/units/population fields are virtual-human extensions stored under data/clinical/ alongside other provenance-annotated inputs.", + "references": [ + { + "repository": "Foundation-0/project-asma", + "pull_request": 47, + "artifact": "registries/rosen-treatment-sequence-sources.json" + }, + { + "repository": "Foundation-0/virtual-human", + "pull_request": 3, + "artifact": "docs/project-asma-integration.md" + } + ] + }, + "entries": [ + { + "id": "P001", + "quantity": "Prognostic CA-125 half-life threshold during induction chemotherapy (progression risk dichotomy)", + "value": 20, + "range": { "kind": "point", "low": null, "high": null, "level": null }, + "units": "days", + "population": "Epithelial ovarian cancer; n=85; Rotterdam Cancer Institute induction chemotherapy cohort (1988 publication)", + "citation": { + "doi": "10.1016/0090-8258(88)90244-2", + "first_author_surname": "van der Burg", + "year": 1988, + "title": "Ovarian cancer: The prognostic value of the serum half-life of CA125 during induction chemotherapy" + }, + "locator": "PubMed abstract (PMID 3164697); full article not openly accessible", + "label": "CONJECTURE", + "derivation": "value from abstract only; reports half-life ≥20 days versus <20 days prognostic groups (3.2-fold progression rate; median time to progression 11 vs 43 months). Mean half-life in days not stated in abstract.", + "limits": "Mixed histologies; 1988 assay era. Not a continuous kinetic rate constant for modern sequence models." + }, + { + "id": "P002", + "quantity": "Germline BRCA1 mutation prevalence in TCGA high-grade serous ovarian carcinoma exome cohort", + "value": 0.09, + "range": { "kind": "point", "low": null, "high": null, "level": null }, + "units": "fraction of cases", + "population": "TCGA HGS-OvCa; n=316 with whole-exome sequence (of 489 HGS-OvCa total)", + "citation": { + "doi": "10.1038/nature10166", + "first_author_surname": "Network", + "year": 2011, + "title": "Integrated genomic analyses of ovarian carcinoma" + }, + "locator": "verified from full text, PMC3163504, Results (BRCA1/BRCA2 germline mutation frequencies in 316 exome samples)", + "label": "KNOWN", + "derivation": null, + "limits": "Germline component only in this row; same paragraph reports somatic BRCA1/2 mutations in an additional 3% of cases (combined interpretation)." + }, + { + "id": "P003", + "quantity": "Germline BRCA2 mutation prevalence in TCGA high-grade serous ovarian carcinoma exome cohort", + "value": 0.08, + "range": { "kind": "point", "low": null, "high": null, "level": null }, + "units": "fraction of cases", + "population": "TCGA HGS-OvCa; n=316 with whole-exome sequence", + "citation": { + "doi": "10.1038/nature10166", + "first_author_surname": "Network", + "year": 2011, + "title": "Integrated genomic analyses of ovarian carcinoma" + }, + "locator": "verified from full text, PMC3163504, Results (BRCA1/BRCA2 germline mutation frequencies in 316 exome samples)", + "label": "KNOWN", + "derivation": null, + "limits": "Germline component only; see P002 limits for somatic add-on sentence in the same Results passage." + }, + { + "id": "P004", + "quantity": "Germline BRCA1 or BRCA2 mutation attribution in high-grade serous ovarian carcinoma (TCGA)", + "value": 0.13, + "range": { "kind": "point", "low": null, "high": null, "level": null }, + "units": "fraction of HGS-OvCa cases", + "population": "TCGA HGS-OvCa cohort (489 clinically annotated tumors described in the paper)", + "citation": { + "doi": "10.1038/nature10166", + "first_author_surname": "Network", + "year": 2011, + "title": "Integrated genomic analyses of ovarian carcinoma" + }, + "locator": "verified from full text, PMC3163504, Background/Introduction (HGS-OvCa germline BRCA1/2 attribution)", + "label": "KNOWN", + "derivation": null, + "limits": "Population fraction language in primary text ('approximately 13% ... attributable to germline mutations')." + }, + { + "id": "P005", + "quantity": "Homologous recombination (HR) pathway defect prevalence in TCGA high-grade serous ovarian carcinoma", + "value": 0.5, + "range": { "kind": "point", "low": null, "high": null, "level": null }, + "units": "fraction of HGS-OvCa tumors (approximate)", + "population": "TCGA HGS-OvCa; n=489; pathway and mutation analyses in integrated genomic study", + "citation": { + "doi": "10.1038/nature10166", + "first_author_surname": "Network", + "year": 2011, + "title": "Integrated genomic analyses of ovarian carcinoma" + }, + "locator": "verified from full text, PMC3163504, Abstract ('homologous recombination is defective in about half of tumors') and Results ('HR defects may be present in approximately half of HGS-OvCa')", + "label": "KNOWN", + "derivation": null, + "limits": "Primary source gives approximate 'half' wording rather than a single tabulated HRD assay prevalence; distinct from modern Myriad/LOH assay definitions used in later trials." + }, + { + "id": "P006", + "quantity": "Myriad/LOH-based HRD assay prevalence in untreated HGSOC (trial assay definition)", + "value": null, + "range": null, + "units": null, + "population": "Untreated HGSOC with contemporary HRD test as used in PARP maintenance trials", + "citation": { + "doi": "10.1038/nature10166", + "first_author_surname": "Network", + "year": 2011, + "title": "Integrated genomic analyses of ovarian carcinoma" + }, + "locator": "TCGA 2011 reports HR pathway defects (~50%, see P005) but not trial-compatible HRD assay prevalence", + "label": "MISSING", + "derivation": null, + "limits": "Use P005 for TCGA HR-pathway 'half' statement only; do not map directly to PAOLA-1 HRD positivity without assay translation." + }, + { + "id": "P007", + "quantity": "Overall survival hazard ratio for no gross residual disease versus any visible residual (advanced ovarian cancer meta-analysis)", + "value": null, + "range": null, + "units": null, + "population": "Advanced-stage epithelial ovarian cancer; Chang et al. 2013 meta-analysis (PubMed PMID 23747291)", + "citation": { + "doi": "10.1016/j.ygyno.2013.05.040", + "first_author_surname": "Chang", + "year": 2013, + "title": "Survival impact of complete cytoreduction to no gross residual disease for advanced-stage ovarian cancer: A meta-analysis" + }, + "locator": "Publisher full text not openly accessible; PubMed abstract reports weighted median survival regression, not a pooled OS hazard ratio", + "label": "MISSING", + "derivation": null, + "limits": "Prior ledger HR 0.52 removed; do not use without primary-table verification." + }, + { + "id": "P008", + "quantity": "Progression-free survival hazard ratio for no gross residual disease versus any visible residual (same meta-analysis)", + "value": null, + "range": null, + "units": null, + "population": "Advanced-stage epithelial ovarian cancer; Chang et al. 2013 meta-analysis", + "citation": { + "doi": "10.1016/j.ygyno.2013.05.040", + "first_author_surname": "Chang", + "year": 2013, + "title": "Survival impact of complete cytoreduction to no gross residual disease for advanced-stage ovarian cancer: A meta-analysis" + }, + "locator": "Publisher full text not openly accessible; abstract does not report pooled PFS hazard ratio", + "label": "MISSING", + "derivation": null, + "limits": "See P007." + }, + { + "id": "P009", + "quantity": "Progression-free survival hazard ratio for PARP inhibitor (olaparib) maintenance versus placebo after first-line platinum response (SOLO1)", + "value": 0.3, + "range": { "kind": "CI95", "low": 0.23, "high": 0.41, "level": 0.95 }, + "units": "hazard ratio (dimensionless)", + "population": "Newly diagnosed advanced ovarian cancer with BRCA1/2 mutation and platinum response; n=391 randomized (260 olaparib, 131 placebo); PubMed PMID 30345884", + "citation": { + "doi": "10.1056/NEJMoa1810858", + "first_author_surname": "Moore", + "year": 2018, + "title": "Maintenance Olaparib in Patients with Newly Diagnosed Advanced Ovarian Cancer" + }, + "locator": "PubMed abstract Results; NEJM full text not openly accessible to this build", + "label": "CONJECTURE", + "derivation": "value from abstract only", + "limits": "Investigator-assessed PFS; maintenance after response, not surgery–chemotherapy sequencing." + }, + { + "id": "P010", + "quantity": "Investigator-assessed PFS hazard ratio for olaparib plus bevacizumab versus placebo plus bevacizumab (PAOLA-1, ITT)", + "value": 0.59, + "range": { "kind": "CI95", "low": 0.49, "high": 0.72, "level": 0.95 }, + "units": "hazard ratio (dimensionless)", + "population": "Newly diagnosed advanced high-grade ovarian cancer post platinum–taxane plus bevacizumab; n=806 randomized; PubMed PMID 31851799", + "citation": { + "doi": "10.1056/NEJMoa1911361", + "first_author_surname": "Ray-Coquard", + "year": 2019, + "title": "Olaparib plus Bevacizumab as First-Line Maintenance in Ovarian Cancer" + }, + "locator": "PubMed abstract Results; NEJM full text not openly accessible to this build", + "label": "CONJECTURE", + "derivation": "value from abstract only", + "limits": "Both arms include bevacizumab maintenance." + }, + { + "id": "P011", + "quantity": "PFS hazard ratio for olaparib plus bevacizumab versus placebo plus bevacizumab in HRD-positive tumors (PAOLA-1)", + "value": 0.33, + "range": { "kind": "CI95", "low": 0.25, "high": 0.45, "level": 0.95 }, + "units": "hazard ratio (dimensionless)", + "population": "PAOLA-1 HRD-positive subgroup; PubMed PMID 31851799", + "citation": { + "doi": "10.1056/NEJMoa1911361", + "first_author_surname": "Ray-Coquard", + "year": 2019, + "title": "Olaparib plus Bevacizumab as First-Line Maintenance in Ovarian Cancer" + }, + "locator": "PubMed abstract Results (HRD-positive subgroup); NEJM full text not openly accessible to this build", + "label": "CONJECTURE", + "derivation": "value from abstract only", + "limits": "Trial-specific HRD definition." + }, + { + "id": "P012", + "quantity": "Clinical objective response rate after carboplatin plus paclitaxel in optimally resected stage III ovarian cancer (GOG-111 comparison)", + "value": null, + "range": null, + "units": null, + "population": "Optimally resected stage III ovarian cancer; GOG-111 class trial (PubMed PMID 12860964); n=792 enrolled", + "citation": { + "doi": "10.1200/JCO.2003.02.153", + "first_author_surname": "Ozols", + "year": 2003, + "title": "Phase III Trial of Carboplatin and Paclitaxel Compared With Cisplatin and Paclitaxel in Patients With Optimally Resected Stage III Ovarian Cancer: A Gynecologic Oncology Group Study" + }, + "locator": "PubMed abstract reports PFS/OS medians and relative risks only; objective response rate not stated in abstract; JCO full text not openly accessible", + "label": "MISSING", + "derivation": null, + "limits": "Prior value 0.77 withdrawn pending primary-table verification." + }, + { + "id": "P013", + "quantity": "Platinum-free interval threshold defining platinum-sensitive recurrent disease (6 months)", + "value": null, + "range": null, + "units": null, + "population": "Recurrent epithelial ovarian cancer", + "citation": { + "doi": "10.1200/JCO.2001.19.4.1001", + "first_author_surname": "Markman", + "year": 2001, + "title": "Phase III Trial of Standard-Dose Intravenous Cisplatin Plus Paclitaxel Versus Moderately High-Dose Carboplatin Followed by Intravenous Paclitaxel and Intraperitoneal Cisplatin in Small-Volume Stage III Ovarian Carcinoma: An Intergroup Study of the Gynecologic Oncology Group, Southwestern Oncology Group, and Eastern Cooperative Oncology Group" + }, + "locator": "PubMed abstract (PMID 11181662) does not define a 6-month platinum-free interval; full text not openly accessible", + "label": "MISSING", + "derivation": null, + "limits": "Operational 6-month platinum-sensitive definition widely used but not verified from an open primary source in this ledger revision." + }, + { + "id": "P014", + "quantity": "Distribution parameters (mean and standard deviation) of platinum-free interval after first-line therapy in HGSOC", + "value": null, + "range": null, + "units": null, + "population": "HGSOC completing first-line platinum-based therapy", + "citation": { + "doi": "10.1016/j.ygyno.2019.07.008", + "first_author_surname": "Dockery", + "year": 2019, + "title": "Extending the platinum-free interval: The impact of omitting 2nd line platinum chemotherapy in intermediate platinum-sensitive ovarian cancer" + }, + "locator": "No parametric PFI distribution identified in open full text during review", + "label": "MISSING", + "derivation": null, + "limits": "Observational series use categorical bins." + }, + { + "id": "P015", + "quantity": "Untreated high-grade serous ovarian cancer volumetric doubling time", + "value": null, + "range": null, + "units": null, + "population": "Newly diagnosed HGSOC before systemic therapy", + "citation": { + "doi": "10.1073/pnas.2026663118", + "first_author_surname": "Gu", + "year": 2021, + "title": "Computational modeling of ovarian cancer dynamics suggests optimal strategies for therapy and screening" + }, + "locator": "No single untreated HGSOC doubling time tabulated for ledger extraction", + "label": "MISSING", + "derivation": null, + "limits": "Gu et al. simulation parameters not copied into this ledger." + }, + { + "id": "P016", + "quantity": "Proportional intraoperative tumor retention fraction used in sequencing models (empirical estimate)", + "value": null, + "range": null, + "units": null, + "population": "Ovarian cancer patients with quantitative debulking fractions", + "citation": { + "doi": "10.1016/j.jtbi.2006.02.001", + "first_author_surname": "Kohandel", + "year": 2006, + "title": "Mathematical modeling of ovarian cancer treatments: Sequencing of surgery and chemotherapy" + }, + "locator": "Model uses fixed-fraction surgery operator; no patient-derived numeric fraction", + "label": "MISSING", + "derivation": null, + "limits": "See P021 for qualitative prior art." + }, + { + "id": "P017", + "quantity": "12-month clinical recurrence rate after completion of first-line platinum–taxane chemotherapy in advanced HGSOC", + "value": null, + "range": null, + "units": null, + "population": "Advanced HGSOC after first-line platinum doublet", + "citation": { + "doi": "10.1056/nejmoa1103799", + "first_author_surname": "Perren", + "year": 2011, + "title": "A Phase 3 Trial of Bevacizumab in Ovarian Cancer" + }, + "locator": "ICON7 primary publication does not tabulate standalone 12-month recurrence proportion in open full text reviewed here", + "label": "MISSING", + "derivation": null, + "limits": "Use trial PFS landmarks where explicitly reported (see CONJECTURE maintenance rows)." + }, + { + "id": "P018", + "quantity": "Median progression-free survival in SOLO1 placebo maintenance arm (from end of chemotherapy)", + "value": null, + "range": null, + "units": null, + "population": "SOLO1 placebo arm; BRCA-mutated advanced ovarian cancer; PubMed PMID 30345884", + "citation": { + "doi": "10.1056/NEJMoa1810858", + "first_author_surname": "Moore", + "year": 2018, + "title": "Maintenance Olaparib in Patients with Newly Diagnosed Advanced Ovarian Cancer" + }, + "locator": "PubMed abstract reports 3-year landmark (27% placebo) but not placebo median 13.8 months; NEJM full text not openly accessible", + "label": "MISSING", + "derivation": null, + "limits": "Prior median 13.8 months withdrawn pending open full-text table verification." + }, + { + "id": "P019", + "quantity": "Population carboplatin clearance for whole-body PBPK coupling in ovarian treatment-sequence models", + "value": null, + "range": null, + "units": null, + "population": "Virtual-human ovarian treatment-sequence graph experiments", + "citation": { + "doi": "10.1073/pnas.2026663118", + "first_author_surname": "Gu", + "year": 2021, + "title": "Computational modeling of ovarian cancer dynamics suggests optimal strategies for therapy and screening" + }, + "locator": "Not applicable: sequence experiments use dimensionless burden units", + "label": "MISSING", + "derivation": null, + "limits": "Add when a model contract consumes PK parameters." + }, + { + "id": "P020", + "quantity": "Population paclitaxel central volume and clearance for sequence models", + "value": null, + "range": null, + "units": null, + "population": "Virtual-human ovarian treatment-sequence graph experiments", + "citation": { + "doi": "10.1073/pnas.2026663118", + "first_author_surname": "Gu", + "year": 2021, + "title": "Computational modeling of ovarian cancer dynamics suggests optimal strategies for therapy and screening" + }, + "locator": "Not applicable: scalar chemotherapy operators in sequence experiments", + "label": "MISSING", + "derivation": null, + "limits": "Add when a model contract consumes PK parameters." + }, + { + "id": "P021", + "quantity": "Fixed-fraction surgical debulking as explicit sequencing prior art (qualitative)", + "value": 1, + "range": { "kind": "categorical", "categories": ["fixed-fraction_surgery_operator_present"] }, + "units": "categorical indicator", + "population": "Mathematical modeling literature (ovarian sequencing)", + "citation": { + "doi": "10.1016/j.jtbi.2006.02.001", + "first_author_surname": "Kohandel", + "year": 2006, + "title": "Mathematical modeling of ovarian cancer treatments: Sequencing of surgery and chemotherapy" + }, + "locator": "PubMed abstract (PMID 16580022); publisher full text not openly accessible", + "label": "CONJECTURE", + "derivation": "value from abstract only ('Surgery is assumed to eliminate a fixed fraction of tumor cells instantaneously')", + "limits": "Qualitative operator flag; numeric fraction remains MISSING (P016)." + }, + { + "id": "P022", + "quantity": "Median investigator-assessed PFS with bevacizumab-only maintenance in PAOLA-1 control arm", + "value": 16.6, + "range": { "kind": "point", "low": null, "high": null, "level": null }, + "units": "months from randomization", + "population": "PAOLA-1 placebo plus bevacizumab arm; n=269; PubMed PMID 31851799", + "citation": { + "doi": "10.1056/NEJMoa1911361", + "first_author_surname": "Ray-Coquard", + "year": 2019, + "title": "Olaparib plus Bevacizumab as First-Line Maintenance in Ovarian Cancer" + }, + "locator": "PubMed abstract Results; NEJM full text not openly accessible to this build", + "label": "CONJECTURE", + "derivation": "value from abstract only", + "limits": "Includes bevacizumab maintenance." + } + ] +} diff --git a/data/clinical/ovarian_hgsoc_parameter_ledger.schema.json b/data/clinical/ovarian_hgsoc_parameter_ledger.schema.json new file mode 100644 index 0000000..af667a8 --- /dev/null +++ b/data/clinical/ovarian_hgsoc_parameter_ledger.schema.json @@ -0,0 +1,117 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://foundation-0.dev/virtual-human/ovarian_hgsoc_parameter_ledger.schema.json", + "title": "Ovarian HGSOC treatment-sequence parameter ledger", + "description": "Machine-readable population parameters for research models. Extends the registry row shape used in Foundation-0/project-asma (sources registries, PR #47) with quantitative fields required by virtual-human treatment-sequence work.", + "type": "object", + "required": [ + "schema_version", + "ledger_id", + "checked_on", + "scope", + "extends", + "entries" + ], + "properties": { + "schema_version": { "type": "integer", "const": 1 }, + "ledger_id": { "type": "string" }, + "checked_on": { "type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" }, + "scope": { "type": "string" }, + "extends": { + "type": "object", + "required": ["description", "references"], + "properties": { + "description": { "type": "string" }, + "references": { + "type": "array", + "items": { + "type": "object", + "required": ["repository", "pull_request", "artifact"], + "properties": { + "repository": { "type": "string" }, + "pull_request": { "type": "integer" }, + "artifact": { "type": "string" } + } + } + } + } + }, + "entries": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/entry" } + } + }, + "$defs": { + "entry": { + "type": "object", + "required": [ + "id", + "quantity", + "value", + "range", + "units", + "population", + "citation", + "locator", + "label", + "limits" + ], + "properties": { + "id": { "type": "string", "pattern": "^[A-Z][0-9]{3}$" }, + "quantity": { "type": "string", "minLength": 1 }, + "value": { + "oneOf": [ + { "type": "null" }, + { "type": "number" }, + { "type": "string", "minLength": 1 } + ] + }, + "range": { + "oneOf": [ + { "type": "null" }, + { + "type": "object", + "required": ["kind"], + "properties": { + "kind": { + "type": "string", + "enum": ["point", "CI95", "IQR", "min_max", "categorical"] + }, + "low": { "type": ["number", "null"] }, + "high": { "type": ["number", "null"] }, + "level": { "type": ["number", "null"] }, + "categories": { + "type": "array", + "items": { "type": "string" } + } + } + } + ] + }, + "units": { "type": ["string", "null"] }, + "population": { "type": "string", "minLength": 1 }, + "citation": { + "type": "object", + "required": ["doi", "first_author_surname", "year", "title"], + "properties": { + "doi": { "type": "string", "minLength": 1 }, + "first_author_surname": { "type": "string", "minLength": 1 }, + "year": { "type": "integer" }, + "title": { "type": "string", "minLength": 1 } + } + }, + "locator": { "type": "string", "minLength": 1 }, + "label": { "type": "string", "enum": ["KNOWN", "CONJECTURE", "MISSING"] }, + "derivation": { "type": ["string", "null"] }, + "limits": { "type": "string", "minLength": 1 } + }, + "allOf": [ + { + "if": { "properties": { "label": { "const": "MISSING" } } }, + "then": { "properties": { "value": { "type": "null" } } } + } + ] + } + } +} diff --git a/pyproject.toml b/pyproject.toml index cd26967..d1655ab 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,3 +35,7 @@ include = ["vh*"] [tool.pytest.ini_options] testpaths = ["tests"] +pythonpath = ["."] +markers = [ + "network: tests that call external network services (Crossref)", +] diff --git a/scripts/validate_ovarian_parameter_ledger.py b/scripts/validate_ovarian_parameter_ledger.py new file mode 100644 index 0000000..94769c2 --- /dev/null +++ b/scripts/validate_ovarian_parameter_ledger.py @@ -0,0 +1,230 @@ +"""Validate the ovarian HGSOC parameter ledger (schema + optional Crossref DOI checks). + +Offline schema validation (default): + PYTHONPATH=. python scripts/validate_ovarian_parameter_ledger.py + +Network DOI verification (separate step; not run in default CI): + PYTHONPATH=. python scripts/validate_ovarian_parameter_ledger.py --check-dois +""" + +from __future__ import annotations + +import argparse +import json +import re +import sys +import urllib.error +import urllib.parse +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +LEDGER_PATH = ROOT / "data" / "clinical" / "ovarian_hgsoc_parameter_ledger.json" +SCHEMA_PATH = ROOT / "data" / "clinical" / "ovarian_hgsoc_parameter_ledger.schema.json" +USER_AGENT = "VirtualHumanLedger/1.0 (mailto:agent@cursor.com)" +LABELS = frozenset({"KNOWN", "CONJECTURE", "MISSING"}) + + +def _normalize_title(title: str) -> str: + return re.sub(r"[^a-z0-9]+", "", title.casefold()) + + +def _crossref_first_author_surname(author: dict) -> str: + if author.get("family"): + return str(author["family"]) + name = str(author.get("name", "")).strip() + if not name: + return "" + return name.split()[-1] + + +def _titles_match(ledger_title: str, crossref_title: str) -> bool: + a = _normalize_title(ledger_title) + b = _normalize_title(crossref_title) + if not a or not b: + return False + return a == b or a in b or b in a + + +def _surnames_match(ledger_surname: str, crossref_surname: str) -> bool: + return ledger_surname.casefold() == crossref_surname.casefold() + + +def load_ledger() -> dict: + with LEDGER_PATH.open(encoding="utf-8") as handle: + return json.load(handle) + + +def validate_schema(ledger: dict) -> list[str]: + errors: list[str] = [] + required_top = ("schema_version", "ledger_id", "checked_on", "scope", "extends", "entries") + for key in required_top: + if key not in ledger: + errors.append(f"missing top-level field {key!r}") + + entries = ledger.get("entries") + if not isinstance(entries, list) or not entries: + errors.append("entries must be a non-empty list") + return errors + + seen_ids: set[str] = set() + for index, entry in enumerate(entries): + prefix = f"entries[{index}]" + if not isinstance(entry, dict): + errors.append(f"{prefix} must be an object") + continue + for field in ( + "id", + "quantity", + "value", + "range", + "units", + "population", + "citation", + "locator", + "label", + "limits", + ): + if field not in entry: + errors.append(f"{prefix} missing field {field!r}") + + entry_id = entry.get("id") + if isinstance(entry_id, str): + if entry_id in seen_ids: + errors.append(f"duplicate id {entry_id!r}") + seen_ids.add(entry_id) + + label = entry.get("label") + if label not in LABELS: + errors.append(f"{prefix} label {label!r} not in {sorted(LABELS)}") + + if label == "MISSING" and entry.get("value") is not None: + errors.append(f"{prefix} MISSING row must have null value") + + citation = entry.get("citation") + if isinstance(citation, dict): + for field in ("doi", "first_author_surname", "year", "title"): + if field not in citation or not citation[field]: + errors.append(f"{prefix}.citation missing {field!r}") + else: + errors.append(f"{prefix}.citation must be an object") + + rng = entry.get("range") + if rng is not None: + if not isinstance(rng, dict) or "kind" not in rng: + errors.append(f"{prefix}.range must be null or an object with kind") + + if label == "CONJECTURE" and not entry.get("derivation"): + errors.append(f"{prefix} CONJECTURE requires non-empty derivation") + + return errors + + +def fetch_crossref_work(doi: str) -> dict: + encoded = urllib.parse.quote(doi, safe="") + url = f"https://api.crossref.org/works/{encoded}" + request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) + with urllib.request.urlopen(request, timeout=30) as response: + payload = json.load(response) + return payload["message"] + + +def check_dois(ledger: dict) -> dict: + entries = ledger["entries"] + unique_dois: dict[str, list[str]] = {} + for entry in entries: + doi = entry["citation"]["doi"] + unique_dois.setdefault(doi, []).append(entry["id"]) + + results = [] + failures = 0 + for doi, entry_ids in sorted(unique_dois.items()): + row = {"doi": doi, "entry_ids": entry_ids, "status": "ok"} + try: + work = fetch_crossref_work(doi) + except urllib.error.HTTPError as exc: + failures += 1 + row["status"] = "http_error" + row["detail"] = str(exc) + results.append(row) + continue + except urllib.error.URLError as exc: + failures += 1 + row["status"] = "network_error" + row["detail"] = str(exc) + results.append(row) + continue + + authors = work.get("author") or [{}] + crossref_surname = _crossref_first_author_surname(authors[0]) + crossref_title = (work.get("title") or [""])[0] + ledger_entry = next(e for e in entries if e["citation"]["doi"] == doi) + ledger_surname = ledger_entry["citation"]["first_author_surname"] + ledger_title = ledger_entry["citation"]["title"] + + surname_ok = _surnames_match(ledger_surname, crossref_surname) + title_ok = _titles_match(ledger_title, crossref_title) + row["crossref_first_author_surname"] = crossref_surname + row["crossref_title"] = crossref_title + row["surname_match"] = surname_ok + row["title_match"] = title_ok + if not (surname_ok and title_ok): + failures += 1 + row["status"] = "mismatch" + results.append(row) + + return { + "ledger_path": str(LEDGER_PATH.relative_to(ROOT)), + "unique_dois_checked": len(unique_dois), + "failures": failures, + "results": results, + } + + +def label_counts(ledger: dict) -> dict[str, int]: + counts = {label: 0 for label in sorted(LABELS)} + for entry in ledger["entries"]: + counts[entry["label"]] += 1 + return counts + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--check-dois", + action="store_true", + help="Contact Crossref and verify DOI title and first-author surname (network step).", + ) + args = parser.parse_args(argv) + + if not LEDGER_PATH.is_file(): + print(f"ledger not found: {LEDGER_PATH}", file=sys.stderr) + return 2 + + ledger = load_ledger() + schema_errors = validate_schema(ledger) + if schema_errors: + print("Schema validation failed:") + for err in schema_errors: + print(f" - {err}") + return 1 + + summary = { + "status": "pass", + "schema_path": str(SCHEMA_PATH.relative_to(ROOT)), + "label_counts": label_counts(ledger), + "entry_count": len(ledger["entries"]), + } + print(json.dumps(summary, indent=2)) + + if args.check_dois: + print("\n--- Crossref DOI verification (network) ---") + doi_report = check_dois(ledger) + print(json.dumps(doi_report, indent=2)) + if doi_report["failures"]: + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_ovarian_parameter_ledger.py b/tests/test_ovarian_parameter_ledger.py new file mode 100644 index 0000000..dca4e5b --- /dev/null +++ b/tests/test_ovarian_parameter_ledger.py @@ -0,0 +1,79 @@ +"""Offline tests for the ovarian HGSOC parameter ledger.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from scripts.validate_ovarian_parameter_ledger import ( + LEDGER_PATH, + check_dois, + label_counts, + load_ledger, + validate_schema, +) + +ROOT = Path(__file__).resolve().parents[1] + + +def test_ledger_file_exists(): + assert LEDGER_PATH.is_file() + + +def test_schema_validation_passes(): + ledger = load_ledger() + errors = validate_schema(ledger) + assert errors == [] + + +def test_required_candidate_quantities_represented(): + ledger = load_ledger() + text = json.dumps(ledger).casefold() + needles = [ + "ca-125", + "doubling time", + "platinum-free interval", + "response rate", + "residual", + "brca", + "hrd", + "recurrence", + "parp", + "olaparib", + "carboplatin", + "paclitaxel", + ] + missing = [n for n in needles if n not in text] + assert not missing, f"missing topic needles: {missing}" + + +def test_missing_rows_have_null_value(): + ledger = load_ledger() + for entry in ledger["entries"]: + if entry["label"] == "MISSING": + assert entry["value"] is None + + +def test_label_counts_stable(): + counts = label_counts(load_ledger()) + assert counts["KNOWN"] == 4 + assert counts["CONJECTURE"] == 6 + assert counts["MISSING"] == 12 + assert sum(counts.values()) == len(load_ledger()["entries"]) + + +def test_known_row_values_pinned_to_verified_numbers(): + by_id = {entry["id"]: entry for entry in load_ledger()["entries"]} + assert by_id["P002"]["value"] == 0.09 + assert by_id["P003"]["value"] == 0.08 + assert by_id["P004"]["value"] == 0.13 + assert by_id["P005"]["value"] == 0.5 + + +@pytest.mark.network +def test_crossref_doi_check_live(): + report = check_dois(load_ledger()) + assert report["failures"] == 0 + assert report["unique_dois_checked"] >= 10 From 73c50a5201a4da9cde5a3e75c837096a21e75feb Mon Sep 17 00:00:00 2001 From: ahrazzle <38987266+ahrazzle@users.noreply.github.com> Date: Thu, 5 Nov 2026 15:44:06 -0600 Subject: [PATCH 09/12] docs: establish Virtual Human and Asma research foundation (#6) --- README.md | 3 + docs/research-foundation.md | 198 +++++++++++++++++++++++++++++ docs/research-question-template.md | 54 ++++++++ 3 files changed, 255 insertions(+) create mode 100644 docs/research-foundation.md create mode 100644 docs/research-question-template.md diff --git a/README.md b/README.md index 836b655..806872a 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,9 @@ **Foundation-0 development fork:** reusable graph work supporting [Project Asma](https://github.com/Foundation-0/project-asma). See the [integration and validation record](docs/project-asma-integration.md). +Start with the [plain-language research foundation](docs/research-foundation.md) +for the evidence-map, simulation and validation boundaries, then use the +[bounded research-question template](docs/research-question-template.md). The original project is [Rohan Arun's Virtual Human](https://github.com/rohanarun/virtual-human). > *Solving problems in the human body by formalizing the real world into code for agents.* diff --git a/docs/research-foundation.md b/docs/research-foundation.md new file mode 100644 index 0000000..4a516e2 --- /dev/null +++ b/docs/research-foundation.md @@ -0,0 +1,198 @@ +# Virtual Human and Asma: a research foundation + +Virtual Human is a **workbench for building and checking pieces of a computerized +human**. Its useful starting point is a careful evidence map and small, inspectable +experiments. It is not a complete virtual person or a treatment-decision tool. + +This guide compiles the project's plain-language explanation into a shared +starting point for contributors. It connects existing work rather than adopting a +new disease model. Use it with the [architecture](architecture.md), +[Asma integration record](project-asma-integration.md), and +[research-question template](research-question-template.md). + +## 1. Four maps, four different questions + +A body spans many scales: molecules interact, cells respond, drugs move through +organs, and immune activity has consequences across tissues. Different tools are +needed at each scale. Connecting them requires explicit assumptions, compatible +inputs and validation of the connection itself. + +| Analogy | What is implemented | What it can answer | What it does not establish | +| --- | --- | --- | --- | +| Street map | [Typed graph and schema](../vh/graph/core.py); Asma adds its own evidence rules | What connects to what? Does a recorded assertion match the requested context? | A route through a graph is not proof of causation, recognition or injury. | +| Traffic simulation | [Reaction networks and interventions](reaction_experiments.md) | Given explicit rates and operations, how do quantities change, and which assumptions change the result? | Artificial rates do not become measured biology because the solver runs. | +| Plumbing map | [Whole-body PBPK](../vh/body/pbpk.py) | Under the compartment model, where does a drug go and how does concentration change? | Drug exposure alone does not establish disease response or an individual's outcome. | +| Microscope | [Molecular](../vh/molecular/) and [quantum](../vh/quantum/) tools | Forces, interactions and small-system calculations under the chosen physical model | Agreement on small systems does not validate a complete disease mechanism. | + +A street map can show two places are connected without predicting traffic. In the +same way, graph structure needs separately justified equations and parameters +before it can become a dynamic model. The optional [model registry](model_contracts.md) +checks scalar quantity names, units, reference bases, contexts and bounds before +calling an explicitly registered model. It does not supply missing observations +or certify the model's biological truth. + +The existing [occupancy bridge](../vh/bridge/occupancy.py) uses unbound target-site +concentration and a binding constant to calculate occupancy. Its documentation +states that binding constants currently come from experiment; obtaining them from +atomistic binding-free-energy calculations remains development work. Occupancy +is itself distinct from cellular response and tissue injury. + +## 2. Asma's evidence map today + +Asma's public research includes ovarian cancer and anti-Yo-related biology. +Three questions that sound like one story must remain separate: + +1. Is a particular protein present? +2. Can the immune system recognize it in the relevant context? +3. Does that recognition lead to injury in neural tissue? + +Evidence for the first question does not automatically answer the second or +third. Antibody binding, protein function, HLA annotation, receptor recognition +and tissue injury are distinct claims. Direct recognition and indirect injury +can also coexist; they should not be forced into mutually exclusive explanations. + +Asma currently uses a small, unchanged, hash-pinned copy of Virtual Human's graph +container and schema, with Asma-owned matching rules. It keeps entity identity, +relationship, source, assay and other recorded contexts attached to assertions. +The query must be satisfied by one complete matching record; fragments from +different studies must not be joined into an observation that nobody made. + +For example, separate catalog records containing CDR2L, HLA-II and a glioblastoma +model do not establish that complete conjunction in one record. A finite negative +screen also cannot establish universal absence of recognition. Missing support +remains unresolved; contradictory matching assertions remain conflicting. + +The recorded [evidence-graph result][evidence-result] contains 24 curated +assertions and 22 manually specified requests. These are not 24 independent +observations or patients. Matching the expected answers is a hand-curated software +benchmark, not an independent scientific accuracy estimate. Human curation can +still omit important context or misread a source. +Omitting a query field does not generalize the evidence: the full matched context +is returned, and callers must request every distinction relevant to their claim. + +**Verification boundary:** the evidence map is machine-checked, not formally +proved. Schema checks and regression tests establish bounded software behavior. +A future proof or exhaustive check would need a specified property and model, +such as prohibiting cross-observation joins. It would still not prove that the +underlying biology or the chosen rules describe nature correctly. Exact rational +conservation checks in the reaction engine are a different, narrower mathematical +guarantee, not a formal proof of Asma's evidence system. + +## 3. A toy experiment: ask which assumption changes the answer + +Consider whether the order of surgery and chemotherapy changes a model outcome. +Start with deliberately imaginary burden units, not patients, cells or doses: + +- Initial burden: 100. +- Operation A retains half; operation B also retains half. +- A then B: 100 -> 50 -> 25. +- B then A: 100 -> 50 -> 25. + +In this toy world, order makes no difference. The conclusion is about the stated +operations, not a recommendation about clinical treatment order. If a richer model +predicts a difference, ask **which added assumption caused it?** + +An exact replay needs only Python's standard library: + +```python +from fractions import Fraction + +initial = Fraction(100) +retain_a = retain_b = Fraction(1, 2) +a_then_b = retain_b * (retain_a * initial) +b_then_a = retain_a * (retain_b * initial) +assert a_then_b == b_then_a == 25 +``` + +Possible changes include a fixed absolute residual instead of a fixed percentage, +state-dependent dynamics, conversion between populations, different gaps or +schedules, or inaccessible disease. Selective effects alone are not sufficient +in every model: two fixed diagonal removal operations still commute. Scalar +proportional retention commutes with any fixed homogeneous linear flow. These +null cases should be retained alongside counterexamples. + +Asma's [treatment-sequence assumption audit][sequence-result] compares proportional +retention with a capped fixed-residual rule, using artificial sensitive/resistant +burdens and exact rational arithmetic. It preserves negative results and explains +why fitting one sequence can leave the other sequence unresolved. It does not +reproduce the full published Gu/Rosen model or estimate clinical efficacy. + +Virtual Human's [optional local bridge](../scripts/validate_asma_interventions.py) +compares corresponding artificial outcomes against the Asma implementation. +Agreement checks the same toy mathematics. Reusing numbers as artificial mol/L +here and arbitrary burden units there is not a physiological unit conversion. +The bridge requires a trusted local Asma checkout and does not download code. +See its [recorded result](../auto-research/2026-11-05-E-reaction-experiments/bridge-results.json) +and the [integration record](project-asma-integration.md) for exact revision/hash +provenance. It does not establish which sequence is better for a real patient. + +## 4. What is available, what remains proposed + +Snapshot checked on **2026-11-05**, against Virtual Human main +`5b8c9e5cd5ec1d3fab595d6398f90c2bc4c889bd` and Asma main +`aa944ef8ee56bcf61153c10497c89f066fc240ad`. This is a dated inventory, not an +automatically updated status dashboard. + +- **Present on main:** graph/schema, explicit scalar model contracts, elementary + mass-action reaction experiments, organ/molecular/quantum tools and the + occupancy bridge. Reaction/intervention work was merged in + [PR #3](https://github.com/Foundation-0/virtual-human/pull/3). +- **Used by Asma:** its pinned graph core and the bounded synthetic comparison + described above. The organ, molecular and quantum engines are **not integrated + into Asma**. Its qualitative claims remain qualitative. +- **Recorded inputs, not a disease simulator:** the + [ovarian HGSOC ledger](../data/clinical/README-ovarian-parameter-ledger.md), + merged in [PR #5](https://github.com/Foundation-0/virtual-human/pull/5), labels + source-backed values, conjectures and missing quantities. Population prevalence, + trial hazard ratios and rate constants are not interchangeable. Missing growth, + removal and drug-PK parameters remain gaps, not values to guess. +- **Open proposal at this snapshot:** + [SBML-import PR #4](https://github.com/Foundation-0/virtual-human/pull/4). + It is not on the inspected main branch. Do not assume its importer or validation + results are available in a main checkout. This foundation does not duplicate or + modify that work. +- **Future research:** bounded disease mechanisms, validated connections between + scales, applicable parameters, uncertainty analysis and independent outcome + validation. The [roadmap](roadmap.md) is an ambition and acceptance-test list, + not proof that these capabilities already exist. + +## 5. How to start from this foundation + +For one specific research question, use the [question template](research-question-template.md): + +1. State the endpoint, population/system and context. Keep recognition, injury, + exposure and treatment response distinct. +2. Map the public evidence and its source/locator/access limits. Preserve + conflicting and missing evidence rather than converting it to numbers. +3. Write competing assumptions and the simplest null case before adding + complexity. Keep synthetic fixtures visibly artificial. +4. Identify the measurements and units the model actually requires. Explain + every proposed transformation from a published quantity to a parameter. +5. Compare implementation with an independent engine or analytic result. For a + scientific prediction, separately specify independent observations that could + disprove it, held apart from any fitting data. +6. Record what failed and what remains unresolved. Revise or stop when the + assumptions are not distinguishable at available precision. A prettier graph + or passing test cannot fill missing biological evidence. +7. Review reusable library changes here and domain evidence/rules in Asma. Keep + vendored updates deliberate, preserve attribution and rerun the relevant + checks. See [contribution guidance](../auto-research.md). + +Drug-distribution or molecular tools may eventually help with carefully bounded +questions. That requires the missing biological links, applicable inputs and +validation, rather than plugging ovarian or anti-Yo labels into a generic model. +Independent scientific review remains separate from software review. + +## Scope and public-data boundary + +This foundation covers public evidence and synthetic examples only. It contains +no patient records, personal correspondence, private clinical analysis or +patient-specific simulation. No new data acquisition, clinical experiment, +treatment recommendation or deployment is authorized by this document. + +The practical aim is to draw a careful map, experiment with assumptions, and ask +what evidence would change the answer. The research-question template is a +proposed starting workflow, not a claim that a new experiment has been completed. + +[evidence-result]: https://github.com/Foundation-0/project-asma/blob/aa944ef8ee56bcf61153c10497c89f066fc240ad/docs/evidence-graph-result-2026-11-05.md +[sequence-result]: https://github.com/Foundation-0/project-asma/blob/aa944ef8ee56bcf61153c10497c89f066fc240ad/docs/research/rosen-treatment-sequence-assumptions.md diff --git a/docs/research-question-template.md b/docs/research-question-template.md new file mode 100644 index 0000000..be1ecac --- /dev/null +++ b/docs/research-question-template.md @@ -0,0 +1,54 @@ +# Bounded research question template + +Copy and fill this template for a proposed experiment. Empty fields are open +questions, not permission to infer inputs. Read the +[research foundation](research-foundation.md) first. This template introduces no +new model, acquisition permission or clinical claim. + +## Question and boundary + +- Question, endpoint and observation time: +- System/population and relevant context: +- Claim type (presence, recognition, injury, exposure, response, or another explicit type): +- What this experiment cannot conclude: +- Owner/reviewer and status (proposed, running, completed, unresolved): + +## Evidence and missing measurements + +- Source identifiers, exact locators and access depth: +- Complete assertion/context supporting each premise: +- Negative or conflicting findings: +- Missing inputs and how their absence limits the result: +- Quantity, units, reference basis and applicability of each numerical input: +- Derivation of any parameter from a reported quantity, with a separate justification: +- Rights/permission boundary for any future acquisition or execution: + +## Competing models + +- Simplest null case and exact expected result: +- Alternative assumptions and explicit equations/operations: +- Which assumption changes between models: +- Artificial fixtures, clearly labeled and separate from observations: +- Measurements that could distinguish the models: +- Identifiability limits, confounders and omitted mechanisms: + +## Verification and scientific validation + +- Software property, schema or invariant to check: +- Independent analytic result or implementation referee: +- Numerical tolerance and convergence check, if relevant: +- Independent biological observations needed to test a prediction: +- Training/fitting data and held-out data separation, if applicable: +- Failure criteria and stop rule when data cannot distinguish alternatives: +- Reviewer qualifications and limits of review: + +## Reproducibility and outcome + +- Repository revision, source hashes and runtime/dependency versions: +- Commands and expected outputs: +- Passed, failed, skipped and not-run checks: +- Retained negative results and unresolved alternatives: +- Conclusion limited to the tested assumptions: +- What evidence would change the conclusion: +- Reusable Virtual Human change versus Asma-specific evidence/rule: +- Next action and any separate authorization it requires: From 2f23ae5e3f521b32611941e1b5314a17a5d72f6e Mon Sep 17 00:00:00 2001 From: Zero <343039971+zero-aska@users.noreply.github.com> Date: Thu, 5 Nov 2026 15:44:11 -0600 Subject: [PATCH 10/12] Import SBML reaction networks as verified graphs (Track E) (#4) * Import SBML reaction networks as verified graphs Add a from-scratch reader for SBML Level 2/3 core (vh/graph/sbml.py): compartments, species, global and local parameters, function definitions, initial assignments, assignment rules and reactions with MathML kinetic laws. Unsupported constructs (events, rate and algebraic rules, delays, fast reactions, stoichiometryMath, conversion factors, variable compartments, required packages) are refused by name. Documents with a DOCTYPE are refused and MathML compiles to closures over a fixed operator table. Models simulate, solve for steady states on the conservation-reduced system and report reduced eigenvalues. vh/graph/stoichiometry.py does exact rational algebra: canonical conservation laws (RREF of the left nullspace) and positive-mass stoichiometric consistency (Gevorgyan et al. 2008) with exactly checked certificates. SBML graphs carry species, reaction, compartment and moiety nodes; the schema recomputes N from edges and checks stoichiometry, location, exact complete conservation and consistency. Validation (scripts/validate_sbml.py, auto-research report): three CC0 BioModels vendored with SHA-256 provenance agree with libRoadRunner, an independent SBML engine used only as a test referee, to <=6.9e-10 on trajectories, <=1.7e-12 on steady states and <=1.3e-9 on reduced eigenvalues; periods match to ~1e-11. Across BIOMD0000000001-060, 49 models are read and 11 refused by name; trajectories of all 49 agree with the referee (median 1.7e-9). The consistency invariant flags 8 models with exact certificates, including a stoichiometry used as a unit conversion in Chassagnole 2002, as its own notes describe. libroadrunner joins the dev extras as a test-only referee. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CoFhtFtE7wJgvHKAzNB3xD * Refuse DTDs in any encoding, not only ASCII-compatible bytes The DOCTYPE/entity refusal scanned raw bytes for " Claude-Session: https://claude.ai/code/session_01CoFhtFtE7wJgvHKAzNB3xD --------- Co-authored-by: Claude --- README.md | 8 +- .../2026-11-05-E-sbml-import/report.md | 212 +++ .../2026-11-05-E-sbml-import/results.json | 1110 +++++++++++++ auto-research/README.md | 1 + data/sbml/BIOMD0000000009.xml | 1429 +++++++++++++++++ data/sbml/BIOMD0000000010.xml | 733 +++++++++ data/sbml/BIOMD0000000012.xml | 1052 ++++++++++++ data/sbml/sources.json | 50 + docs/graph_formalization.md | 55 +- docs/img/kholodenko_mapk_sbml.mmd | 62 + docs/roadmap.md | 3 + pyproject.toml | 4 +- scripts/validate_sbml.py | 251 +++ tests/test_sbml.py | 430 +++++ vh/graph/render.py | 8 + vh/graph/sbml.py | 1066 ++++++++++++ vh/graph/stoichiometry.py | 259 +++ 17 files changed, 6728 insertions(+), 5 deletions(-) create mode 100644 auto-research/2026-11-05-E-sbml-import/report.md create mode 100644 auto-research/2026-11-05-E-sbml-import/results.json create mode 100644 data/sbml/BIOMD0000000009.xml create mode 100644 data/sbml/BIOMD0000000010.xml create mode 100644 data/sbml/BIOMD0000000012.xml create mode 100644 data/sbml/sources.json create mode 100644 docs/img/kholodenko_mapk_sbml.mmd create mode 100644 scripts/validate_sbml.py create mode 100644 tests/test_sbml.py create mode 100644 vh/graph/sbml.py create mode 100644 vh/graph/stoichiometry.py diff --git a/README.md b/README.md index 806872a..6e41556 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ faster than real time. | `vh.molecular` | From-scratch JAX engine: AMBER ff14SB force field, GB-OBC2 implicit water, autodiff forces, Langevin (BAOAB) and Verlet dynamics, L-BFGS minimization | Matches OpenMM (used only as a referee) term by term to ~1e-14 relative on real proteins; trajectories identical step by step; energy conserved ([`docs/validation_molecular.md`](docs/validation_molecular.md)) | | `vh.body` | From-scratch whole-body PBPK: 13 organs + blood, Rodgers & Rowland tissue partitioning, liver (well-stirred, IVIVE), kidney (filtration), oral absorption (stomach + 7-segment intestine) with gut-wall first-pass, virtual populations; solved exactly with matrix exponentials | Bottom-up midazolam predictions vs 100 clinical datasets (IV and oral) digitized by the Open Systems Pharmacology project | | `vh.bridge` | Unbound drug at the target organ → receptor occupancy over time; Kd ↔ binding free energy | Analytic round-trip; kinetic occupancy | -| `vh.graph` | **Formalizes the body as a typed graph** across scales (organs↔blood flow, atoms↔bonds); graph algorithms for reachability, pathways, cycles, flow balance, bottlenecks; renders and verifies subgraphs | Blood conservation (Kirchhoff) to 1e-16 on the real PBPK model; a pure graph BFS reproduces the force field's exclusion list exactly ([`docs/graph_formalization.md`](docs/graph_formalization.md)) | +| `vh.graph` | **Formalizes the body as a typed graph** across scales (organs↔blood flow, species↔reactions, atoms↔bonds); graph algorithms for reachability, pathways, cycles, flow balance, bottlenecks; renders and verifies subgraphs; imports SBML reaction networks with exact conservation and consistency invariants | Blood conservation (Kirchhoff) to 1e-16 on the real PBPK model; a pure graph BFS reproduces the force field's exclusion list exactly; SBML trajectories and steady states match libRoadRunner to ~1e-9 ([`docs/graph_formalization.md`](docs/graph_formalization.md)) | | `web/` | Real-time demo: atom-level protein dynamics and a virtual patient, live in the browser | JS engine checked against the Python engine to ≤1e-12 | The explicit-solvent engine (`vh.molecular.periodic`, `.constraints`, `.explicit_md`) adds rung 3 of the accuracy ladder: every water molecule, exact long-range electrostatics (Ewald / smooth PME), rigid-water SHAKE/RATTLE and a Monte-Carlo barostat — validated term-by-term against OpenMM Ewald (energy to 1e-13, PME to 1e-11, constraints to 1e-16). @@ -161,12 +161,13 @@ vh/molecular energy.py (force field), integrate.py, minimize.py, prep.py, io.p periodic.py (Ewald/PME explicit solvent), constraints.py (SHAKE/RATTLE), explicit_md.py vh/body physiology.py, partition.py, compound.py, pbpk.py vh/bridge molecular → body coupling (Kd ↔ ΔG, receptor occupancy) -vh/graph core.py (typed property graph), algorithms.py, physiology_graph.py, render.py +vh/graph core.py (typed property graph), algorithms.py, physiology_graph.py, render.py, + contracts.py (model interfaces), sbml.py (SBML import), stoichiometry.py (exact algebra) tests/ pytest suite scripts/ validation report + figure generators docs/ accuracy_ladder, graph_formalization, feasibility, validation reports, architecture, roadmap web/ real-time browser engine + demo -data/ structures, tissue composition, clinical observations +data/ structures, tissue composition, clinical observations, SBML models (CC0) ``` ## Not a medical device @@ -187,6 +188,7 @@ research tracks, and how to publish work under [`auto-research/`](auto-research/ - **Rohan Arun** ([@rohanarun](https://github.com/rohanarun)) — creator and maintainer; direction and design. - **Claude** (Anthropic) — implemented and validated the engines under the above direction, in pair with the maintainer. - **OpenAI Codex** — graph interface contracts, clearance reference validation, and conserved reaction/intervention experiments, under the direction of [@ahrazzle](https://github.com/ahrazzle). +- **Claude** (Anthropic), Foundation-0 fork — SBML import with exact conservation and positive-mass consistency invariants. New contributors (human or agent): add yourself here in your pull request. See [`auto-research.md`](auto-research.md) for how to help. diff --git a/auto-research/2026-11-05-E-sbml-import/report.md b/auto-research/2026-11-05-E-sbml-import/report.md new file mode 100644 index 0000000..4c4f010 --- /dev/null +++ b/auto-research/2026-11-05-E-sbml-import/report.md @@ -0,0 +1,212 @@ +# SBML reaction networks as verified graphs + +- **Track**: E — grow the graph formalization (SBML import; conservation and consistency invariants) +- **Author**: Claude (Anthropic), under the direction of the Foundation-0 owner +- **Date**: 2026-11-05 +- **Branch / PR**: `auto/E-sbml-import` +- **Code added**: `vh/graph/sbml.py`, `vh/graph/stoichiometry.py`, `vh/graph/render.py` (styles), + `scripts/validate_sbml.py`, `tests/test_sbml.py`, `data/sbml/` (three CC0 BioModels with provenance) + +## Question + +Track E's milestone: *a BioModels SBML model imports to a graph whose +steady-state / conservation invariants are verified, and at least one new +invariant catches a real inconsistency.* Can a from-scratch reader turn +curated reaction networks into executable models and typed graphs whose +structural claims are proven exactly rather than asserted, and whose dynamics +agree with an independent SBML engine? + +## Method + +**Reader.** `read_sbml` parses SBML Level 2 (v1–5) and Level 3 (v1–2) core with +the standard-library XML parser. It refuses documents containing a DOCTYPE or +entity declarations. MathML is compiled to closures over a fixed operator table; +nothing is passed to `eval`. Supported constructs: +- compartments of constant size, species, and global and local parameters; +- function definitions, inlined at compile time; +- initial assignments, and assignment rules in dependency order (loops are + rejected); +- reactions with exact rational stoichiometry, modifiers and kinetic laws. + +Every other construct raises `UnsupportedSBML` and names it: events, rate and +algebraic rules, constraints, delays, fast reactions, stoichiometryMath, +conversion factors, non-constant compartments and required packages. + +The reader implements the SBML semantics the kinetics depend on: +- a species symbol means concentration unless `hasOnlySubstanceUnits`; +- kinetic laws are in substance per time; +- boundary species are not changed by reactions. + +It also rejects documents that violate them, such as a constant, non-boundary +species consumed by a reaction. Units are not checked. + +**Dynamics.** `d amount / dt = N v(x)` is integrated with SciPy (LSODA) on the +concentration-scaled state. Steady states come from a hybrid Newton solve on the +conservation-reduced system. Stability uses the Jacobian restricted to the +stoichiometric class: central differences reduced through the exact link matrix. + +**Exact stoichiometry** (`vh.graph.stoichiometry`). All coefficients are +`Fraction`s. +- **Conservation laws** are the RREF of the left nullspace of `N`, scaled to + coprime integers. That basis is canonical for the space, so two + implementations can be compared row by row. +- **Positive-mass (stoichiometric) consistency** follows Gevorgyan, Poolman & + Fell (2008): every reacting species must admit a strictly positive mass that + every internal reaction conserves. A floating-point LP classifies the + species, and the classification is then proved with exact certificates: + - for a conserved species, a mass vector `m ≥ 0` with `mᵀN = 0` and `mᵢ > 0`; + - for an unconserved species, a reaction combination `v` with `N v ≥ 0` and + `(N v)ᵢ > 0`, which shows by Farkas' lemma that no positive mass exists. + + Rounding is removed exactly. Rows the LP leaves numerically at zero are + constrained to be exactly zero in their exact nullspace, and the LP is solved + again. A result is labelled `certified` only if every certificate checks + exactly. +- **Internal reactions.** Boundary and constant species keep their rows, + because holding a species fixed does not change its mass. A reaction counts as + internal only if each side has a species that is not held fixed. Reactions + that touch only fixed pools on one side, such as `A → EmptySet`, are + exchanges. + +**Graph.** `SBMLModel.to_graph()` builds a typed graph: +- nodes for `compartment`, `species`, `reaction` and `moiety`; +- `reactant`/`product` edges carrying exact stoichiometry strings, plus + `modifier`, `located_in` and `member` edges. + +`sbml_schema()` recomputes `N` from the edges alone and checks four invariants: +stoichiometry, located, conservation (exact, complete, with matching totals) +and stoichiometric consistency. + +**Inputs and provenance.** Three curated BioModels whose notes state CC0 are +vendored unmodified. `data/sbml/sources.json` records each one's URL, SHA-256, +size and PubMed IDs: +- BIOMD0000000009, Huang & Ferrell 1996 +- BIOMD0000000010, Kholodenko 2000 +- BIOMD0000000012, Elowitz & Leibler 2000 + +Survey models (BIOMD0000000001–060) are identified by SHA-256 in +`results.json` and are not vendored. + +## Validation — the part that matters + +The authorities are of two kinds. +- **Exact rational algebra** for the structural claims, together with + closed-form solutions for synthetic networks. +- **libRoadRunner 2.11.0** (libSBML + CVODE, C++) as an independent SBML + implementation for the dynamics. It was not used to produce any value here. + +Tolerances were `rtol = 1e-12` and `atol = 1e-16` in both engines for the +vendored models. The survey used `rtol = 1e-10` and `atol = 1e-14`. + +| Quantity | This work | Authority | Error | +|---|---|---|---| +| Conservation laws, Kholodenko 2000 | 3 laws: MKKK, MKK and MAPK totals = 100, 300, 300 | exact `l·N = 0`; rank(N) + laws = 8; libRoadRunner moiety space | residual **0** (exact); same row space | +| Conservation laws, Huang & Ferrell 1996 | 7 laws (E1, E2, KKK, KK, K, KPase, KKPase totals) | same | residual **0**; same row space | +| Conservation laws, repressilator | none | rank(N) = 6 | exact | +| Trajectories, 3 models, 101 points | — | libRoadRunner | ≤ **6.9e-10** × species range | +| Drift of conserved totals along trajectories | — | exact invariance | ≤ **1.1e-13** relative | +| Steady state, Huang & Ferrell 1996 (stable) | max Re λ = −0.0716 | libRoadRunner steady state and reduced eigenvalues | state **1.7e-12**; eigenvalues **8.2e-10** | +| Fixed point, Kholodenko 2000 (unstable) | max Re λ = +0.00158 | same | state **1.5e-15**; eigenvalues **1.3e-9** | +| Fixed point, repressilator (unstable) | max Re λ = +0.0144 | same | state **1.2e-16**; eigenvalues **4.5e-10** | +| Limit-cycle period, Kholodenko 2000 (MKKK) | 1299.7705 time units | libRoadRunner trajectory | **8.9e-12** relative | +| Limit-cycle period, repressilator (PX) | 125.35416 time units | same | **1.8e-12** relative | +| First-order decay, `V = 2.5`, both species conventions | — | `A₀ e^{−kt}` | ≤ 1e-8 relative | +| Reversible `A ⇌ B`: relaxation, steady state, eigenvalue | — | closed form | 1e-8 / 1e-12 / 1e-6 | +| Survey trajectories, 49 models, `[0, 100]`, `rtol` 1e-10 | — | libRoadRunner | median **1.7e-9**; 47 of 49 ≤ 1e-6; worst 1.1e-5, which falls to **2.9e-7** at `rtol` 1e-12 | + +No parameter was fitted. + +**Survey of BIOMD0000000001–060.** +- **Read:** 49 of 60. +- **Refused by name (11):** rate rules (5), events (3), delays (2) and + stoichiometryMath (1). +- **Referee check:** every model that was read was also simulated by + libRoadRunner over the same window. The two Borghans 1997 calcium + oscillators (BIOMD0000000044/045) agree least closely: 1.1e-5 and 1.3e-6 at + `rtol` 1e-10. The script reruns them automatically at `rtol` 1e-12, where + the gap falls to 2.9e-7 and 3.3e-8. In an exploratory check (not recorded in + `results.json`), our own LSODA and Radau runs differed from each other by a + similar amount. The shrinking gap points to integration error on sharp + calcium spikes, not a semantic difference. + +**The new invariant catches real inconsistencies.** Positive-mass consistency +fails, with exact certificates, for 8 of the 49 models that were read: +BIOMD0000000008, 015, 018, 035, 049, 050, 051 and 052. The model-level check +and the graph invariant agree on all 49. Three cases were inspected: + +- **Chassagnole 2002, *E. coli* carbon metabolism (051).** The + phosphotransferase reaction is written + `cglcex + 65 cpep → 65 cg6p + 65 cpyr`. The model's own notes say the + biomass-to-volume ratio "is taken into account by appropriately adjusting + the stoichiometries", because both compartments have size 1. One glucose + therefore formally yields 65 glucose-6-phosphate: a unit conversion hidden + in stoichiometry. That is harmless for this model in isolation, but it would + silently corrupt any mass balance or model composition built on it. + Neutralising the factor does not make the model consistent. A second + certificate runs through `vPGDH`, written + `6-phosphogluconate → ribulose 5-phosphate` with no CO₂. +- **Vilar 2002 oscillator (035).** Transcription and translation are template + reactions (`DA → DA + MA`, `MA → A + MA`), and `C → R` degrades the bound + activator inside the complex. These are deliberate abstractions with + precursors and degradation products omitted. +- **Gardner 1998 cell cycle (008).** `Z → C` and `Z → Y` degrade one partner + inside a complex. This is also a deliberate abstraction. + +A positive-mass failure is therefore a proven property of the network as +written, not proof of a modelling error. The invariant makes the abstraction +visible and machine-checkable. Judging whether it is acceptable needs the +model's context. + +An earlier version of the check dropped boundary species before testing mass +balance. That made binding to a clamped ligand look like creation from nothing: +Schoeberl 2002 (019) was flagged because EGF is a boundary species. The final +rule, described under Method, removes that artifact without hiding real +template synthesis. + +## Limits + +- **Construct coverage.** 11 of the 60 surveyed models use constructs outside + the subset: events, rate rules, delays and stoichiometryMath. They are + refused, not approximated. +- **Units are not checked.** Numbers are used as written, as an SBML simulator + would use them. A dimensionally inconsistent kinetic law is not detected. +- **Consistency is structural.** It ignores kinetic laws and modifiers, and it + cannot tell an intended abstraction from an error. +- **Steady states depend on the starting point.** The solve finds the fixed + point of the given stoichiometric class nearest the guess. Multistability is + not enumerated. +- **Speed.** Kinetics run as Python closures. That is adequate here (the + largest surveyed model, about 100 species, simulates in seconds), but it is + neither JAX-differentiable nor fast. Making it so is a natural next step. +- **What agreement with libRoadRunner shows.** It establishes that both engines + implement the same SBML semantics on these models. It does not validate the + biology of any model. +- **No link to the rest of the stack.** Nothing here touches `vh.bridge`, + occupancy, or patient data. + +## Reproduce + +```bash +pip install -e '.[dev]' # includes libroadrunner (referee only) +PYTHONPATH=. pytest -q tests/test_sbml.py +mkdir -p /tmp/biomodels && for i in $(seq -w 1 60); do id=BIOMD00000000$i; \ + curl -sSL -o /tmp/biomodels/$id.xml "https://www.ebi.ac.uk/biomodels/model/download/$id?filename=${id}_url.xml"; done +PYTHONPATH=. python scripts/validate_sbml.py --survey /tmp/biomodels # writes results.json here +``` + +The survey files' SHA-256 values are recorded in `results.json`. A later +BioModels release may serve different bytes; compare against those hashes. + +## References + +- Hucka M. et al. The Systems Biology Markup Language (SBML): language specification for Level 3 Version 2 Core (2019); Level 2 Version 4 (2008). +- Gevorgyan A., Poolman M. G., Fell D. A. Detection of stoichiometric inconsistencies in biomolecular models. *Bioinformatics* 24:2245–2251 (2008). +- Welsh C. et al. libRoadRunner 2.0: a high performance SBML simulation and analysis library. *Bioinformatics* 39:btac770 (2023). +- Le Novère N. et al. BioModels Database. *Nucleic Acids Res.* 34:D689 (2006); models used under CC0 as stated in each file. +- Models, with the PubMed IDs annotated in each SBML file: + - Kholodenko B. N. *Eur. J. Biochem.* 267:1583 (2000), PMID 10712587. + - Huang C.-Y. F., Ferrell J. E. *PNAS* 93:10078 (1996), PMID 8816754. + - Elowitz M. B., Leibler S. *Nature* 403:335 (2000), PMID 10659856. + - Vilar J. M. G. et al. *PNAS* 99:5988 (2002), PMID 11972055. + - Gardner T. S. et al. *PNAS* 95:14190 (1998), PMID 9826676. + - Chassagnole C. et al. *Biotechnol. Bioeng.* 79:53 (2002). BIOMD0000000051 annotates PMID 17590932; it was not checked against this citation. diff --git a/auto-research/2026-11-05-E-sbml-import/results.json b/auto-research/2026-11-05-E-sbml-import/results.json new file mode 100644 index 0000000..3bc65a9 --- /dev/null +++ b/auto-research/2026-11-05-E-sbml-import/results.json @@ -0,0 +1,1110 @@ +{ + "authority": "exact rational algebra; libRoadRunner as independent SBML referee", + "models": [ + { + "id": "BIOMD0000000009", + "name": "Huang1996 - Ultrasensitivity in MAPK cascade", + "sha256": "1f95d793517d47dbf98321a89cdb14fcff9f461427b4ea062d398734c962ab98", + "sbml": "L2V4", + "species": 26, + "dynamic_species": 22, + "reactions": 20, + "assignment_rules": 4, + "conservation_laws": [ + "E1 + E1_KKK", + "E2 + E2_P_KKK", + "KKK + P_KKK + E1_KKK + E2_P_KKK + P_KKK_KK + P_KKK_P_KK", + "KK + P_KK + PP_KK + P_KKK_KK + P_KKK_P_KK + PP_KK_K + PP_KK_P_K + KKPase_PP_KK + KKPase_P_KK", + "K + P_K + PP_K + PP_KK_K + PP_KK_P_K + KPase_PP_K + KPase_P_K", + "KPase + KPase_PP_K + KPase_P_K", + "KKPase + KKPase_PP_KK + KKPase_P_KK" + ], + "conserved_totals_initial_amount": [ + 1.2e-16, + 1.1999999999999998e-15, + 1.2e-14, + 4.8e-12, + 4.8e-12, + 4.8e-13, + 1.1999999999999998e-15 + ], + "conserved_totals_initial_concentration": [ + 3e-05, + 0.0003, + 0.003, + 1.2, + 1.2, + 0.12, + 0.0003 + ], + "exact_residual_l_dot_N": "0", + "rank_plus_laws_equals_dynamic_species": true, + "positive_mass_consistent": true, + "consistency_certified": true, + "graph_invariant_problems": [], + "referee": { + "engine": "libRoadRunner 2.11.0", + "trajectory_max_error_rel_to_species_max": 5.617227786242932e-10, + "conservation_space_equal": true + }, + "max_relative_drift_of_conserved_totals": 1.1107161545511846e-13, + "steady_state": { + "solver_success": true, + "max_abs_rate_of_change": 4.8467614016778965e-15, + "max_diff_vs_referee_rel_to_max": 1.7004532594088963e-12, + "eigenvalue_max_diff_vs_referee_rel": 8.216172658283124e-10, + "max_real_eigenvalue": -0.07161415016477386, + "stable": true + } + }, + { + "id": "BIOMD0000000010", + "name": "Kholodenko2000 - Ultrasensitivity and negative feedback bring oscillations in MAPK cascade", + "sha256": "906964e07ffd570ad94a03c1222e230b54b913cd536b008392bfb6155930a966", + "sbml": "L2V4", + "species": 8, + "dynamic_species": 8, + "reactions": 10, + "assignment_rules": 0, + "conservation_laws": [ + "MKKK + MKKK_P", + "MKK + MKK_P + MKK_PP", + "MAPK + MAPK_P + MAPK_PP" + ], + "conserved_totals_initial_amount": [ + 100.0, + 300.0, + 300.0 + ], + "conserved_totals_initial_concentration": [ + 100.0, + 300.0, + 300.0 + ], + "exact_residual_l_dot_N": "0", + "rank_plus_laws_equals_dynamic_species": true, + "positive_mass_consistent": true, + "consistency_certified": true, + "graph_invariant_problems": [], + "referee": { + "engine": "libRoadRunner 2.11.0", + "trajectory_max_error_rel_to_species_max": 6.83867922800367e-10, + "conservation_space_equal": true + }, + "max_relative_drift_of_conserved_totals": 4.547473508864641e-15, + "steady_state": { + "solver_success": true, + "max_abs_rate_of_change": 5.551115123125783e-17, + "max_diff_vs_referee_rel_to_max": 1.4870278679293009e-15, + "eigenvalue_max_diff_vs_referee_rel": 1.3041323793590769e-09, + "max_real_eigenvalue": 0.0015808867973344746, + "stable": false + }, + "oscillation": { + "species": "MKKK", + "period": 1299.7705094979783, + "referee_period": 1299.7705095095023, + "relative_difference": 8.866165148521614e-12, + "cycles_averaged": 2, + "model_time_units": "as written in the model" + } + }, + { + "id": "BIOMD0000000012", + "name": "Elowitz2000 - Repressilator", + "sha256": "d535c84bc5fe68b01728cac5c53f8fed971176e3f0f2367a9ba1e9c043b11a2d", + "sbml": "L2V3", + "species": 6, + "dynamic_species": 6, + "reactions": 12, + "assignment_rules": 9, + "conservation_laws": [], + "conserved_totals_initial_amount": [], + "conserved_totals_initial_concentration": [], + "exact_residual_l_dot_N": "0", + "rank_plus_laws_equals_dynamic_species": true, + "positive_mass_consistent": true, + "consistency_certified": true, + "graph_invariant_problems": [], + "referee": { + "engine": "libRoadRunner 2.11.0", + "trajectory_max_error_rel_to_species_max": 6.908546759502274e-10, + "conservation_space_equal": true + }, + "max_relative_drift_of_conserved_totals": 0.0, + "steady_state": { + "solver_success": true, + "max_abs_rate_of_change": 3.552713678800501e-15, + "max_diff_vs_referee_rel_to_max": 1.1801944309700211e-16, + "eigenvalue_max_diff_vs_referee_rel": 4.497717690631207e-10, + "max_real_eigenvalue": 0.0144474668713797, + "stable": false + }, + "oscillation": { + "species": "PX", + "period": 125.35415830519999, + "referee_period": 125.35415830543108, + "relative_difference": 1.8435520807816913e-12, + "cycles_averaged": 7, + "model_time_units": "as written in the model" + } + } + ], + "survey": { + "files": 60, + "read": 49, + "refused_by_construct": { + "model element ": 3, + "": 5, + "csymbol function": 2, + "stoichiometryMath": 1 + }, + "referee": { + "horizon": 100.0, + "rtol": 1e-10, + "atol": 1e-14, + "compared": 49, + "max_error_rel_to_species_range": 1.0786057563640103e-05, + "median_error": 1.7192407749872498e-09, + "within_1e-6": 47, + "rerun_at_tight_tolerance": { + "BIOMD0000000044": [ + 1.0786057563640103e-05, + 2.864557502320601e-07 + ], + "BIOMD0000000045": [ + 1.3126266067169491e-06, + 3.348195409229243e-08 + ] + }, + "tight_tolerance": { + "rtol": 1e-12, + "atol": 1e-16 + } + }, + "errors": [], + "inconsistent": [ + "BIOMD0000000008", + "BIOMD0000000015", + "BIOMD0000000018", + "BIOMD0000000035", + "BIOMD0000000049", + "BIOMD0000000050", + "BIOMD0000000051", + "BIOMD0000000052" + ], + "all_classifications_certified": true, + "graph_invariant_agrees_everywhere": true, + "models": [ + { + "id": "BIOMD0000000001", + "sha256": "407fccc883f80e6d120e34d8b0810a206a5cc6535a26d4574611504e683beb08", + "status": "refused", + "reason": "model element " + }, + { + "id": "BIOMD0000000002", + "sha256": "7f7ee585a886f9cd88199887a9e674e070ce368b2884ceeee65dd437f3edca7f", + "status": "read", + "name": "Edelstein1996 - EPSP ACh species", + "species": 13, + "reactions": 17, + "conservation_laws": 2, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 4.7031616501968764e-07 + }, + { + "id": "BIOMD0000000003", + "sha256": "a633872e4c602922e85ac487ef52ac8bd8ead762ec7c0f86f9e93032a84c90f5", + "status": "read", + "name": "Goldbeter1991 - Min Mit Oscil", + "species": 3, + "reactions": 7, + "conservation_laws": 0, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 1.962975820480737e-07 + }, + { + "id": "BIOMD0000000004", + "sha256": "504dc54b5697b4183bd0046fb11f0991702961e3dee0baf15ac1ecaad5009eb6", + "status": "read", + "name": "Goldbeter1991 - Min Mit Oscil, Expl Inact", + "species": 5, + "reactions": 7, + "conservation_laws": 2, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 1.5033265555272367e-07 + }, + { + "id": "BIOMD0000000005", + "sha256": "5a4f44b5a0bc8f32d3206f460f748236539de593be0fb016da2ed7cddd098e36", + "status": "read", + "name": "Tyson1991 - Cell Cycle 6 var", + "species": 9, + "reactions": 9, + "conservation_laws": 1, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 1.1896814023712015e-07 + }, + { + "id": "BIOMD0000000006", + "sha256": "c3cd0b2dfc738565fe72be3208eec28023e623297e198015df1df77a7e430820", + "status": "refused", + "reason": "" + }, + { + "id": "BIOMD0000000007", + "sha256": "9503b8fb38f0e285897a4d1155634e6893ae5b4ca843a3997098db8ee1614bda", + "status": "refused", + "reason": "model element " + }, + { + "id": "BIOMD0000000008", + "sha256": "6c49ab1dd2efddc682cc97563de927e000fbae1e471563bb2c62c37640d990f1", + "status": "read", + "name": "Gardner1998 - Cell Cycle Goldbeter", + "species": 5, + "reactions": 13, + "conservation_laws": 0, + "positive_mass_consistent": false, + "certified": true, + "graph_invariant_agrees": true, + "unconserved": [ + "C", + "Y", + "Z" + ], + "leak_certificate": { + "reaction9": "3", + "reaction10": "-2", + "reaction11": "-2" + }, + "referee_trajectory_max_error": 4.1259901787439805e-09 + }, + { + "id": "BIOMD0000000009", + "sha256": "1f95d793517d47dbf98321a89cdb14fcff9f461427b4ea062d398734c962ab98", + "status": "read", + "name": "Huang1996 - Ultrasensitivity in MAPK cascade", + "species": 26, + "reactions": 20, + "conservation_laws": 7, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 1.0719422732093982e-09 + }, + { + "id": "BIOMD0000000010", + "sha256": "906964e07ffd570ad94a03c1222e230b54b913cd536b008392bfb6155930a966", + "status": "read", + "name": "Kholodenko2000 - Ultrasensitivity and negative feedback bring oscillations in MAPK cascade", + "species": 8, + "reactions": 10, + "conservation_laws": 3, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 1.4013873632606925e-09 + }, + { + "id": "BIOMD0000000011", + "sha256": "7d13449074b774b4ea328d939ce433efa1444b5224f8117066ab914cd0ff748d", + "status": "read", + "name": "Levchenko2000_MAPK_noScaffold", + "species": 22, + "reactions": 30, + "conservation_laws": 7, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 8.515842167035795e-10 + }, + { + "id": "BIOMD0000000012", + "sha256": "d535c84bc5fe68b01728cac5c53f8fed971176e3f0f2367a9ba1e9c043b11a2d", + "status": "read", + "name": "Elowitz2000 - Repressilator", + "species": 6, + "reactions": 12, + "conservation_laws": 0, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 1.7192407749872498e-09 + }, + { + "id": "BIOMD0000000013", + "sha256": "e4a9445a74eef88a9783c178f873eebccba72464e8da1fee5cc84e5b4b9192bc", + "status": "read", + "name": "Poolman2004_CalvinCycle", + "species": 27, + "reactions": 21, + "conservation_laws": 2, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 4.829230195370593e-13 + }, + { + "id": "BIOMD0000000014", + "sha256": "7646eb90f0dc8dd072a37612aa7c60fb516a8d4b7e2ab81ba5b5c8a315d23025", + "status": "read", + "name": "Levchenko2000_MAPK_Scaffold", + "species": 86, + "reactions": 300, + "conservation_laws": 8, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 1.878996358536559e-09 + }, + { + "id": "BIOMD0000000015", + "sha256": "74c5cc7d4ad82d45a8c4299b04ee8822c51aeaf19cb4ba4dfda09f55a323bb54", + "status": "read", + "name": "Curto1998 - purine metabolism", + "species": 18, + "reactions": 37, + "conservation_laws": 0, + "positive_mass_consistent": false, + "certified": true, + "graph_invariant_agrees": true, + "unconserved": [ + "PRPP", + "IMP", + "SAMP", + "ATP", + "SAM", + "Ade", + "XMP", + "GTP", + "dATP", + "dGTP", + "RNA", + "DNA", + "HX", + "Xa", + "Gua", + "UA" + ], + "leak_certificate": { + "ampd": "-12", + "aprt": "-2", + "asuc": "1", + "dada": "-2", + "den": "15", + "dnaa": "-1", + "gdrnr": "1", + "gnuc": "-8", + "gprt": "-14", + "gua": "5", + "hxd": "-3", + "impd": "1", + "polyam": "-1", + "rnaa": "-9", + "rnag": "8", + "xd": "1" + }, + "referee_trajectory_max_error": 2.86241885614117e-10 + }, + { + "id": "BIOMD0000000016", + "sha256": "35ad538383991b45273e2a767c0325d996d188dba10ce959de9635564813f703", + "status": "read", + "name": "Goldbeter1995_CircClock", + "species": 7, + "reactions": 10, + "conservation_laws": 0, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 8.88362367422757e-09 + }, + { + "id": "BIOMD0000000017", + "sha256": "b75db9f5e0b418d7eb015e44565c992ebcda10f56f8934747a2677e222b16148", + "status": "read", + "name": "Hoefnagel2002_PyruvateBranches", + "species": 19, + "reactions": 14, + "conservation_laws": 3, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 7.577820458206507e-11 + }, + { + "id": "BIOMD0000000018", + "sha256": "79abf91af1c46fa23f4e1ca2cfedc8f879dcbf41bbd8fbc7a41046f6aa3c2a12", + "status": "read", + "name": "Morrison1989 - Folate Cycle", + "species": 33, + "reactions": 47, + "conservation_laws": 0, + "positive_mass_consistent": false, + "certified": true, + "graph_invariant_agrees": true, + "unconserved": [ + "DHFRf", + "HCHO", + "FGAR", + "AICAR", + "dUMP", + "GAR", + "serine", + "formate", + "ATP", + "NADP", + "NADPH", + "homocysteine" + ], + "leak_certificate": { + "SHMT": "-1", + "SHMTr": "1", + "CH2FH4toHCHO": "1", + "MTHFR": "-1", + "MTR": "-1", + "HCOOHtoCHOFH4": "-1", + "GARFT": "-1", + "ATIC7": "-1", + "MTHFD": "-1", + "TYMS": "-1", + "DHFReductase": "-1", + "FFH2syn": "-2", + "ATIC12": "-2", + "AICARsyn": "-2", + "MTX2off": "1", + "MTX2deg": "-1" + }, + "referee_trajectory_max_error": 6.740855293246711e-10 + }, + { + "id": "BIOMD0000000019", + "sha256": "541c2a16196dfcd0649df14cff51fb80fc4157bad041c562b17679552baeff48", + "status": "read", + "name": "Schoeberl2002 - EGF MAPK", + "species": 100, + "reactions": 125, + "conservation_laws": 12, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 4.2250256132454956e-09 + }, + { + "id": "BIOMD0000000020", + "sha256": "5fbf09694a5fc3ec4ccec2bb8ba89909faeabb9ea709f44a555c994954f444cf", + "status": "refused", + "reason": "" + }, + { + "id": "BIOMD0000000021", + "sha256": "02376379c0270208b2fd72529a50ccefcdd68c8b23a40585bfdcdd0926a4c8da", + "status": "read", + "name": "Leloup1999_CircClock", + "species": 10, + "reactions": 24, + "conservation_laws": 0, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 5.464687585573705e-08 + }, + { + "id": "BIOMD0000000022", + "sha256": "0b569c675eaed0226dc4c1dcd7f7e2e210a7cbd1b5562da97e55f47c255cdf04", + "status": "read", + "name": "Ueda2001_CircClock", + "species": 13, + "reactions": 32, + "conservation_laws": 0, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 1.1625583922709105e-08 + }, + { + "id": "BIOMD0000000023", + "sha256": "dccd31fe46f4fb06484a9e3b95718aad788692e9abad1dc68fd368d7c8247066", + "status": "read", + "name": "Rohwer2001_Sucrose", + "species": 13, + "reactions": 11, + "conservation_laws": 0, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 3.7213379600053997e-09 + }, + { + "id": "BIOMD0000000024", + "sha256": "748514f402eea94c49346701a30f2b429c9c7d5de922cd450e5a155d5f69dbe1", + "status": "refused", + "reason": "csymbol function http://www.sbml.org/sbml/symbols/delay" + }, + { + "id": "BIOMD0000000025", + "sha256": "5e86b47a659f8e3b4183dd03bf18e68da3419a340f87da966108518be062c0fa", + "status": "refused", + "reason": "csymbol function http://www.sbml.org/sbml/symbols/delay" + }, + { + "id": "BIOMD0000000026", + "sha256": "d293eb11fdd65b3150999c68edaf690a9449ea9e070a8f61878b3a4648eff7c5", + "status": "read", + "name": "Markevich2004_MAPK_orderedElementary", + "species": 11, + "reactions": 10, + "conservation_laws": 3, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 3.6056230459042765e-10 + }, + { + "id": "BIOMD0000000027", + "sha256": "56d8acc83add5a262b6785b18f2e905e606b9072625e25ba1520306bc4d586bb", + "status": "read", + "name": "Markevich2004 - MAPK double phosphorylation, ordered Michaelis-Menton", + "species": 5, + "reactions": 4, + "conservation_laws": 1, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 2.1135597305880588e-10 + }, + { + "id": "BIOMD0000000028", + "sha256": "2ecdc543c6ecb323ae31d13f8fec1846905cc5b9567827f1da8b0efef30ee107", + "status": "read", + "name": "Markevich2004_MAPK_phosphoRandomElementary", + "species": 16, + "reactions": 17, + "conservation_laws": 3, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 5.629178830445155e-10 + }, + { + "id": "BIOMD0000000029", + "sha256": "c1eb117678b7d423b8e1d2fd7f493c865fb66559980256f3544938f5a431b530", + "status": "read", + "name": "Markevich2004_MAPK_phosphoRandomMM", + "species": 6, + "reactions": 7, + "conservation_laws": 1, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 5.105826749333507e-10 + }, + { + "id": "BIOMD0000000030", + "sha256": "decd8cbc5b3981608b1bca8f5df1d6f5af95d9acb2e52c7b8c0d0346851f7bfb", + "status": "read", + "name": "Markevich2004_MAPK_AllRandomElementary", + "species": 18, + "reactions": 20, + "conservation_laws": 3, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 4.65955886828595e-10 + }, + { + "id": "BIOMD0000000031", + "sha256": "56ddd4cc0a0cf51c55a27fa386e0ee670c798ea69151ad39fadf363d0c0297a1", + "status": "read", + "name": "Markevich2004_MAPK_orderedMM2kinases", + "species": 6, + "reactions": 4, + "conservation_laws": 1, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 7.35699221928327e-10 + }, + { + "id": "BIOMD0000000032", + "sha256": "45cec22aefca6b49e78fd3ad5105748559df3e1dcc3bf5ffd787fda8bc6e60df", + "status": "read", + "name": "Kofahl2004_PheromonePathway", + "species": 37, + "reactions": 47, + "conservation_laws": 11, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 7.272437013147094e-10 + }, + { + "id": "BIOMD0000000033", + "sha256": "a0337a2687498ce30dfabd47cc15c5c634fc6d0ad1a7829fb569a36fdef9456d", + "status": "read", + "name": "Brown2004 - NGF and EGF signaling", + "species": 32, + "reactions": 26, + "conservation_laws": 15, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 4.061791087745291e-10 + }, + { + "id": "BIOMD0000000034", + "sha256": "05d93958690ebe26ab031bfdd3a288d091b33ad50b347076a98635b28d7357fe", + "status": "refused", + "reason": "" + }, + { + "id": "BIOMD0000000035", + "sha256": "3303169fdd9a672fa25c26586822c9a1b91ac461744d1926d317f493e6981237", + "status": "read", + "name": "Vilar2002_Oscillator", + "species": 10, + "reactions": 16, + "conservation_laws": 2, + "positive_mass_consistent": false, + "certified": true, + "graph_invariant_agrees": true, + "unconserved": [ + "A", + "C", + "MA", + "MR", + "R" + ], + "leak_certificate": { + "Reaction1": "1", + "Reaction7": "1", + "Reaction10": "2", + "Reaction13": "1", + "Reaction16": "2" + }, + "referee_trajectory_max_error": 1.578098475130181e-08 + }, + { + "id": "BIOMD0000000036", + "sha256": "c95e89456a74ebf7bbef76e648ac4e83f59a913b894b01a69387458ae77802f4", + "status": "read", + "name": "Tyson1999_CircClock", + "species": 3, + "reactions": 5, + "conservation_laws": 0, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 1.6564204500450833e-08 + }, + { + "id": "BIOMD0000000037", + "sha256": "2a8f7a68ac7efd45e09f42a1a5f5e30c9a47b9c039fb79ecf86ef7e3def17c07", + "status": "read", + "name": "Marwan2003 - Genetics, regulatory hierarchy between genes", + "species": 12, + "reactions": 12, + "conservation_laws": 3, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 3.028687969882321e-09 + }, + { + "id": "BIOMD0000000038", + "sha256": "33708cec1fad44db6958c3ac6255397ad79b45564a296d29732fd934608d787b", + "status": "read", + "name": "Rohwer2000_Phosphotransferase_System", + "species": 17, + "reactions": 10, + "conservation_laws": 4, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 4.5330480698328444e-15 + }, + { + "id": "BIOMD0000000039", + "sha256": "6b221222be03747b11454cc4f2a6218697d9c6367d3578a170c7cc5c34ad3b12", + "status": "read", + "name": "Marhl2000_CaOscillations", + "species": 5, + "reactions": 7, + "conservation_laws": 2, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 4.222560473459409e-07 + }, + { + "id": "BIOMD0000000040", + "sha256": "0bf2abb25229f3fe7979315139396f9c0bcdb06370ae9c835f7d3fc0e0c79c6a", + "status": "refused", + "reason": "stoichiometryMath" + }, + { + "id": "BIOMD0000000041", + "sha256": "f6bcb0469ae530aacb147c7d35205766d57a8d4a612fab9b148ba90659078ceb", + "status": "read", + "name": "Kongas2007 - Creatine Kinase in energy metabolic signaling in muscle", + "species": 10, + "reactions": 9, + "conservation_laws": 3, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 1.5172626674860024e-10 + }, + { + "id": "BIOMD0000000042", + "sha256": "3c7946ce1e76401eca4d1b878d435083bf12cf6b16eee6b10316f2aa935109f9", + "status": "read", + "name": "Nielsen1998_Glycolysis", + "species": 15, + "reactions": 25, + "conservation_laws": 0, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 2.1915107454441513e-08 + }, + { + "id": "BIOMD0000000043", + "sha256": "63881219e93fc8552192bb3ed0c55bf1ee3f6756cbdaf84e188d94422b31d9b8", + "status": "read", + "name": "Borghans1997 - Calcium Oscillation - Model 1", + "species": 5, + "reactions": 7, + "conservation_laws": 2, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 6.108555195363742e-07 + }, + { + "id": "BIOMD0000000044", + "sha256": "d441dc324396b20899427988aa72d3637a9c1edaa954bac7399e5e3113b6ce24", + "status": "read", + "name": "Borghans1997 - Calcium Oscillation - Model 2", + "species": 4, + "reactions": 8, + "conservation_laws": 1, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 1.0786057563640103e-05, + "referee_trajectory_max_error_tight_tolerance": 2.864557502320601e-07 + }, + { + "id": "BIOMD0000000045", + "sha256": "a4ede2fcb4cf09bd48ad53745515e9bc4cee570efbb11abf5a9063ffa3ef786d", + "status": "read", + "name": "Borghans1997 - Calcium Oscillation - Model 3", + "species": 4, + "reactions": 8, + "conservation_laws": 1, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 1.3126266067169491e-06, + "referee_trajectory_max_error_tight_tolerance": 3.348195409229243e-08 + }, + { + "id": "BIOMD0000000046", + "sha256": "dc1d91abdde172fb3ddfd74cc421f8e35df660d3fffe6a329a73edb15015c03b", + "status": "read", + "name": "Olsen2003_peroxidase", + "species": 16, + "reactions": 15, + "conservation_laws": 2, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 2.4014558026888917e-08 + }, + { + "id": "BIOMD0000000047", + "sha256": "0982b27ae47c7df89c3186029464fee8b660e73035cc70eb6369649b1bcbe676", + "status": "refused", + "reason": "" + }, + { + "id": "BIOMD0000000048", + "sha256": "3f958d9b64a07f8ff0b8b56431c10b005bf1cbc1de936527399951a0eea63c08", + "status": "read", + "name": "Kholodenko1999 - EGFR signaling", + "species": 23, + "reactions": 25, + "conservation_laws": 6, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 5.910940654481731e-10 + }, + { + "id": "BIOMD0000000049", + "sha256": "746aaefe22c346f7853387e7768b1ea1dca2077c00e5aece7f7f3a9b5551e92e", + "status": "read", + "name": "Sasagawa2005_MAPK", + "species": 99, + "reactions": 150, + "conservation_laws": 18, + "positive_mass_consistent": false, + "certified": true, + "graph_invariant_agrees": true, + "unconserved": [ + "EGFR", + "L_EGFR", + "L_EGFR_dimer", + "L_dpEGFR", + "proteosome", + "EGF" + ], + "leak_certificate": { + "re2": "-1", + "re8": "-1", + "J5": "-2", + "J9": "1", + "J11": "-1", + "J19": "1", + "J20": "1", + "J24": "-1", + "J25": "-1", + "J27": "1", + "J33": "-4", + "J35": "-3", + "J37": "-3", + "J38": "-4", + "J40": "1", + "J43": "-1", + "J45": "-4", + "J119": "-4", + "J118": "-1", + "J124": "-1", + "J164": "-4" + }, + "referee_trajectory_max_error": 9.831557283058588e-10 + }, + { + "id": "BIOMD0000000050", + "sha256": "4846396a6621661b5faa775f7f7b48aefe36c3396bb2da41aeb96f3319d084ad", + "status": "read", + "name": "Martins2003_AmadoriDegradation", + "species": 14, + "reactions": 16, + "conservation_laws": 2, + "positive_mass_consistent": false, + "certified": true, + "graph_invariant_agrees": true, + "unconserved": [ + "Cn", + "_3DG", + "FA", + "_1DG", + "AA", + "Man", + "Glu", + "MG", + "Fru" + ], + "leak_certificate": { + "v2": "1/8", + "v3": "-1/8", + "v5": "1/2", + "v6": "-7/8", + "v8": "3/4", + "v9": "-7/8", + "v12": "-1/8", + "v13": "-1/4", + "v15": "1", + "v16": "1/8" + }, + "referee_trajectory_max_error": 8.112872312822886e-10 + }, + { + "id": "BIOMD0000000051", + "sha256": "167e78583aa85b49c0e283543f5c80e826a16d23cc06bb34e60c6dfbeb67f3fc", + "status": "read", + "name": "Chassagnole2002_Carbon_Metabolism", + "species": 18, + "reactions": 48, + "conservation_laws": 0, + "positive_mass_consistent": false, + "certified": true, + "graph_invariant_agrees": true, + "unconserved": [ + "cpep", + "cglcex", + "cg6p", + "cpyr", + "cf6p", + "cg1p", + "cpg", + "cfdp", + "csed7p", + "cgap", + "ce4p", + "cxyl5p", + "crib5p", + "cdhap", + "cpgp", + "cpg3", + "cpg2", + "cribu5p" + ], + "leak_certificate": { + "vPTS": "-1", + "vPGI": "399", + "vPGM": "1", + "vG6PDH": "-466", + "vPFK": "83", + "vTA": "-157", + "vTKA": "-156", + "vTKB": "-158", + "vALDO": "82", + "vGAPDH": "5", + "vTIS": "81", + "vPGK": "4", + "vrpGluMu": "3", + "vENO": "2", + "vPK": "66", + "vPGDH": "-467", + "vR5PI": "-155", + "vRu5P": "-313" + }, + "referee_trajectory_max_error": 1.2624584773255264e-08 + }, + { + "id": "BIOMD0000000052", + "sha256": "6abff8a7b414eaaa62165f20e48f2244dd597d16699a1209ae171ae9d12cb89f", + "status": "read", + "name": "Brands2002 - Monosaccharide-casein systems", + "species": 11, + "reactions": 11, + "conservation_laws": 3, + "positive_mass_consistent": false, + "certified": true, + "graph_invariant_agrees": true, + "unconserved": [ + "Glu", + "Fru", + "Formic_acid", + "Triose", + "Acetic_acid", + "Cn", + "C5" + ], + "leak_certificate": { + "_J3": "1/9", + "_J5": "5/9", + "_J6": "1", + "_J7": "-2/9", + "_J8": "-8/9", + "_J9": "2/3", + "_J10": "-2/3" + }, + "referee_trajectory_max_error": 8.70301582569469e-10 + }, + { + "id": "BIOMD0000000053", + "sha256": "8c0cf08f4398ccb1989cc1b8cf9eaff86325f06a32b453551612af59676216e5", + "status": "read", + "name": "Ferreira2003_CML_generation2", + "species": 6, + "reactions": 12, + "conservation_laws": 0, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 2.3879181016267972e-08 + }, + { + "id": "BIOMD0000000054", + "sha256": "22b92a2a8c71b2577515d1add05e2e6c7ad68c0ead197bbb08a8e2c09ad6c67e", + "status": "read", + "name": "Ataullahkhanov1996_Adenylate", + "species": 3, + "reactions": 5, + "conservation_laws": 0, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 1.4326567113495416e-09 + }, + { + "id": "BIOMD0000000055", + "sha256": "0ec0148324f94a17028bdf31b03a57b53343f5e290da377af1ca10a610aa542f", + "status": "read", + "name": "Locke2005 - Circadian Clock", + "species": 13, + "reactions": 32, + "conservation_laws": 0, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 6.472601473664629e-09 + }, + { + "id": "BIOMD0000000056", + "sha256": "fc955bffc47e55f1f6376b002d5d5ca10ce40e63bbb2959910665b647f937bd1", + "status": "refused", + "reason": "model element " + }, + { + "id": "BIOMD0000000057", + "sha256": "b5c3c40cca539b7c93943b065e6878a77315c945b69be60e8f70f343cefb5b5d", + "status": "read", + "name": "Sneyd2002_IP3_Receptor", + "species": 6, + "reactions": 5, + "conservation_laws": 1, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 8.52987199620894e-11 + }, + { + "id": "BIOMD0000000058", + "sha256": "51e36d55367f126099cbf4d9fcb34ec7c0bdb670ae9bb7da1e8586e763c068a0", + "status": "read", + "name": "Bindschadler2001_coupled_Ca_oscillators", + "species": 4, + "reactions": 11, + "conservation_laws": 0, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 3.0804830676931965e-08 + }, + { + "id": "BIOMD0000000059", + "sha256": "62b74f8818f8bd3596fbb1c4b4f3ff09427f27fc0557c0495c6666fbbe425580", + "status": "refused", + "reason": "" + }, + { + "id": "BIOMD0000000060", + "sha256": "0d4d9a4a48c8f493afe72d6e9fbffd7afbc1e6218cdfb89a2dea47a53588a9b1", + "status": "read", + "name": "Keizer1996_Ryanodine_receptor_adaptation", + "species": 4, + "reactions": 3, + "conservation_laws": 1, + "positive_mass_consistent": true, + "certified": true, + "graph_invariant_agrees": true, + "referee_trajectory_max_error": 3.3428152758005716e-10 + } + ] + } +} diff --git a/auto-research/README.md b/auto-research/README.md index 203c0b7..41d7577 100644 --- a/auto-research/README.md +++ b/auto-research/README.md @@ -26,3 +26,4 @@ auto-research/ | 2026-11-05 | E (partial) | [Explicit model contracts](2026-11-05-E-model-contracts/report.md) | Exact scalar mass balance; interface rejection cases | 0 L/h max error on 4 synthetic cases; 60 focused tests pass | OpenAI Codex / @ahrazzle | | 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) | diff --git a/data/sbml/BIOMD0000000009.xml b/data/sbml/BIOMD0000000009.xml new file mode 100644 index 0000000..0c30b98 --- /dev/null +++ b/data/sbml/BIOMD0000000009.xml @@ -0,0 +1,1429 @@ + + + + + +
Huang1996 - Ultrasensitivity in MAPK cascade
+

The temporal sequence of kinase activation, from MAPKKK (activated RAF) to the final effector MAPK (activated ERK), is described here. It is observed from the model that there is an increase in sensitivity along the levels of the cascade, where the activity of MAPK reaches its maximal before MAPKKK.

+
+
+

The species K_PP_norm, KKK_P_norm and KK_PP_norm are the relative concentrations of the active MAPK, MAPKK and MAPKKK, that is the double, or single resp. phophorylated forms divided by the total concentrations of each kinase. For MAPK additionally the also active MAPK divided by the maximal concentration of active MAPK is given by rel_K_PP_max. The parameter K_PP_norm_max, the maximal ratio of active MapK, has to be calculated for each change of parameters.

+
+

This model is hosted on BioModels Database + and identified by: BIOMD0000000009 + .

+

To cite BioModels Database, please use: BioModels Database: An enhanced, curated and annotated resource for published quantitative kinetic models + .

+
+

To the extent possible under law, all copyright and related or neighbouring rights to this encoded model have been dedicated to the public domain worldwide. Please refer to CC0 Public Domain Dedication + for more information.

+
+ + + + + + + + + + + Machne + Rainer + + raim@tbi.univie.ac.at + + University of Vienna + + + + + + 2005-02-10T23:39:30Z + + + 2015-06-02T12:02:44Z + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+ the maximal value of K_PP_norm at a stimulation conc. of 10.

+ +
+
+
+ + + + + + + + PP_K + KPase_PP_K + + + + PP_K + P_K + K + PP_KK_K + PP_KK_P_K + KPase_PP_K + KPase_P_K + + + + + + + + + K_PP_norm + K_PP_norm_max + + + + + + + + + + PP_KK + PP_KK_K + PP_KK_P_K + KKPase_PP_KK + + + + PP_KK + P_KK + KK + PP_KK_K + PP_KK_P_K + P_KKK_KK + P_KKK_P_KK + KKPase_PP_KK + KKPase_P_KK + + + + + + + + + + + P_KKK + P_KKK_KK + P_KKK_P_KK + + + + KKK + P_KKK + P_KKK_KK + P_KKK_P_KK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + + + + + a1 + E1 + KKK + + + + d1 + E1_KKK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + k2 + E1_KKK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + + + + + a2 + E2 + P_KKK + + + + d2 + E2_P_KKK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + k2 + E2_P_KKK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + + + + + a3 + KK + P_KKK + + + + d3 + P_KKK_KK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + k3 + P_KKK_KK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + + + + + a4 + P_KK + KKPase + + + + d4 + KKPase_P_KK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + k4 + KKPase_P_KK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + + + + + a5 + P_KK + P_KKK + + + + d5 + P_KKK_P_KK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + k5 + P_KKK_P_KK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + + + + + a6 + PP_KK + KKPase + + + + d6 + KKPase_PP_KK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + k6 + KKPase_PP_KK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + + + + + a7 + K + PP_KK + + + + d7 + PP_KK_K + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + k7 + PP_KK_K + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + + + + + a8 + P_K + KPase + + + + d8 + KPase_P_K + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + k8 + KPase_P_K + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + + + + + a9 + P_K + PP_KK + + + + d9 + PP_KK_P_K + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + k9 + PP_KK_P_K + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + + + + + a10 + PP_K + KPase + + + + d10 + KPase_PP_K + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + compartment + k10 + KPase_PP_K + + + + + + + + + + \ No newline at end of file diff --git a/data/sbml/BIOMD0000000010.xml b/data/sbml/BIOMD0000000010.xml new file mode 100644 index 0000000..b50d6c5 --- /dev/null +++ b/data/sbml/BIOMD0000000010.xml @@ -0,0 +1,733 @@ + + + + + +
Kholodenko2000 - Ultrasensitivity and negative feedback bring oscillations in MAPK cascade
+
+

The combination of ultrasensitivity and negative feedback bring sustained oscillations in the mitogen-activated protein kinase cascades.

+
+
+

This model is described in the article:

+ +
Kholodenko BN
+
Eur. J. Biochem. 2000; 267(6):1583-8
+

Abstract:

+
+

Functional organization of signal transduction into protein phosphorylation cascades, such as the mitogen-activated protein kinase (MAPK) cascades, greatly enhances the sensitivity of cellular targets to external stimuli. The sensitivity increases multiplicatively with the number of cascade levels, so that a tiny change in a stimulus results in a large change in the response, the phenomenon referred to as ultrasensitivity. In a variety of cell types, the MAPK cascades are imbedded in long feedback loops, positive or negative, depending on whether the terminal kinase stimulates or inhibits the activation of the initial level. Here we demonstrate that a negative feedback loop combined with intrinsic ultrasensitivity of the MAPK cascade can bring about sustained oscillations in MAPK phosphorylation. Based on recent kinetic data on the MAPK cascades, we predict that the period of oscillations can range from minutes to hours. The phosphorylation level can vary between the base level and almost 100% of the total protein. The oscillations of the phosphorylation cascades and slow protein diffusion in the cytoplasm can lead to intracellular waves of phospho-proteins.

+
+
+
+

This model is hosted on BioModels Database + and identified by: BIOMD0000000010 + .

+

To cite BioModels Database, please use: BioModels Database: An enhanced, curated and annotated resource for published quantitative kinetic models + .

+
+
+

To the extent possible under law, all copyright and related or neighbouring rights to this encoded model have been dedicated to the public domain worldwide. Please refer to CC0 Public Domain Dedication + for more information.

+
+ +
+ + + + + + + + Sauro + Herbert + + Herbert_Sauro@kgi.edu + + Keck Graduate Institute + + + + + + 2005-02-12T00:18:12Z + + + 2015-06-02T12:04:33Z + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + uVol + V1 + MKKK + + + + + + 1 + + + + + MAPK_PP + Ki + + n + + + + + K1 + MKKK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + uVol + V2 + MKKK_P + + + + KK2 + MKKK_P + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + uVol + k3 + MKKK_P + MKK + + + + KK3 + MKK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + uVol + k4 + MKKK_P + MKK_P + + + + KK4 + MKK_P + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + uVol + V5 + MKK_PP + + + + KK5 + MKK_PP + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + uVol + V6 + MKK_P + + + + KK6 + MKK_P + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + uVol + k7 + MKK_PP + MAPK + + + + KK7 + MAPK + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + uVol + k8 + MKK_PP + MAPK_P + + + + KK8 + MAPK_P + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + uVol + V9 + MAPK_PP + + + + KK9 + MAPK_PP + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + uVol + V10 + MAPK_P + + + + KK10 + MAPK_P + + + + + + + + + + +
+
\ No newline at end of file diff --git a/data/sbml/BIOMD0000000012.xml b/data/sbml/BIOMD0000000012.xml new file mode 100644 index 0000000..fe19368 --- /dev/null +++ b/data/sbml/BIOMD0000000012.xml @@ -0,0 +1,1052 @@ + + + + + +
Elowitz2000 - Repressilator
+
+

This model describes the deterministic version of the repressilator system.

+

The authors of this model (see reference) use three transcriptional repressor systems that are not part of any natural biological clock to build an oscillating network that they called the repressilator. The model system was induced in Escherichia coli.

+

In this system, LacI (variable X is the mRNA, variable PX is the protein) inhibits the tetracycline-resistance transposon tetR (Y, PY describe mRNA and protein). Protein tetR inhibits the gene Cl from phage Lambda (Z, PZ: mRNA, protein),and protein Cl inhibits lacI expression. With the appropriate parameter values this system oscillates.

+
+
+

This model is described in the article:

+ +
Elowitz MB, Leibler S.
+
Nature. 2000 Jan; 403(6767):335-338
+

Abstract:

+
+

Networks of interacting biomolecules carry out many essential functions in living cells, but the 'design principles' underlying the functioning of such intracellular networks remain poorly understood, despite intensive efforts including quantitative analysis of relatively simple systems. Here we present a complementary approach to this problem: the design and construction of a synthetic network to implement a particular function. We used three transcriptional repressor systems that are not part of any natural biological clock to build an oscillating network, termed the repressilator, in Escherichia coli. The network periodically induces the synthesis of green fluorescent protein as a readout of its state in individual cells. The resulting oscillations, with typical periods of hours, are slower than the cell-division cycle, so the state of the oscillator has to be transmitted from generation to generation. This artificial clock displays noisy behaviour, possibly because of stochastic fluctuations of its components. Such 'rational network design may lead both to the engineering of new cellular behaviours and to an improved understanding of naturally occurring networks.

+
+
+
+

The model is based upon the equations in Box 1 of the paper; however, these equations as printed are dimensionless, and the correct dimensions have been returned to the equations, and the parameters set to reproduce Figure 1C (left).

+
+
+

The original model was generated by B.E. Shapiro using Cellerator version 1.0 update 2.1127 using Mathematica 4.2 for Mac OS X (June 4, 2002), November 27, 2002 12:15:32, using (PowerMac,PowerPC, Mac OS X,MacOSX,Darwin).

+

Nicolas Le Novere provided a corrected version generated by SBMLeditor on Sun Aug 20 00:44:05 BST 2006. This removed the EmptySet species. Ran fine on COPASI 4.0 build 18.

+

Bruce Shapiro revised the model with SBMLeditor on 23 October 2006 20:39 PST. This defines default units and correct reactions. The original Cellerator reactions while being mathematically correct did not accurately reflect the intent of the authors. The original notes were mostly removed because they were mostly incorrect in the revised version. Tested with MathSBML 2.6.0.

+

Nicolas Le Novere changed the volume to 1 cubic micrometre, to allow for stochastic simulation.

+

Changed by Lukas Endler to use the average livetime of mRNA instead of its halflife and a corrected value of alpha and alpha0.

+

Moreover, the equations used in this model were clarified, cf. below.

+

The equations given in box 1 + of the original publication are rescaled in three respects (lowercase letters denote the rescaled, uppercase letters the unscaled number of molecules per cell):

+
    +
  • the time is rescaled to the average mRNA lifetime, t_ave: τ = t/t_ave
  • +
  • the mRNA concentration is rescaled to the translation efficiency eff: m = M/eff
  • +
  • the protein concentration is rescaled to Km: p = P/Km
  • +
+

+ α + in the equations should be in units of rescaled proteins per promotor and cell, and β + is the ratio of the protein to the mRNA decay rates or the ratio of the mRNA to the protein halflife.

+

In this version of the model α + and β + are calculated correspondingly to the article, while p + and m + where just replaced by P/Km + resp. M/eff + and all equations multiplied by 1/t_ave + . Also, to make the equations easier to read, commonly used variables derived from the parameters given in the article by simple rules were introduced.

+

The parameters given in the article were:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
promotor strength (repressed) ( tps_repr + ): 5*10 -4transcripts/(promotor*s)
promotor strength (full) ( tps_active + ): 0.5transcripts/(promotor*s)
mRNA half life, τ 1/2,mRNA + : 2min
protein half life, τ 1/2,prot + : 10min
K M + : 40monomers/cell
Hill coefficient n:2 +
+

From these the following constants can be derived:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
average mRNA lifetime ( t_ave + ): + τ 1/2,mRNA + /ln(2) + = 2.89 min
mRNA decay rate ( kd_mRNA + ): + ln(2)/ τ 1/2,mRNA + = 0.347 min -1
protein decay rate ( kd_prot + ): + ln(2)/ τ 1/2,prot +
transcription rate ( a_tr + ): + tps_active*60 + = 29.97 transcripts/min
transcription rate (repressed) ( a0_tr + ): + tps_repr*60 + = 0.03 transcripts/min
translation rate ( k_tl + ): + eff*kd_mRNA + = 6.93 proteins/(mRNA*min)
α : + a_tr*eff*τ 1/2,prot + /(ln(2)*K M + ) + = 216.4 proteins/(promotor*cell*Km)
α 0 + : + a0_tr*eff*τ 1/2,prot + /(ln(2)*K M + ) + = 0.2164 proteins/(promotor*cell*Km)
β : + k_dp/k_dm + = 0.2
+
+

Annotation by the Kinetic Simulation Algorithm Ontology (KiSAO):

+

To reproduce the simulations run published by the authors, the model has to be simulated with any of two different approaches. First, one could use a deterministic method ( KISAO_0000035 + ) with continuous variables ( KISAO_0000018 + ). One sample algorithm to use is the CVODE solver ( KISAO_0000019 + ). Second, one could simulate the system using Gillespie's direct method ( KISAO_0000029 + ), which is a stochastic method ( KISAO_0000036 + ) supporting adaptive timesteps ( KISAO_0000041 + ) and using discrete variables ( KISAO_0000016 + ).

+
+
+

This model is hosted on BioModels Database + and identified by: BIOMD0000000012 + .

+

To cite BioModels Database, please use: BioModels Database: An enhanced, curated and annotated resource for published quantitative kinetic models + .

+
+
+

To the extent possible under law, all copyright and related or neighbouring rights to this encoded model have been dedicated to the public domain worldwide. Please refer to CC0 Public Domain Dedication + for more information.

+
+ +
+ + + + + + + + Le Novère + Nicolas + + lenov@ebi.ac.uk + + EMBL-EBI + + + + + + + + Shapiro + Bruce + + bshapiro@caltech.edu + + Jet Propulsion Laboratory + + + + + Juty + Nick + + juty@ebi.ac.uk + + EMBL-EBI + + + + + Endler + Lukas + + lukas@ebi.ac.uk + + EMBL-EBI + + + + + Chelliah + Vijayalakshmi + + viji@ebi.ac.uk + + EMBL-EBI + + + + + + 2009-01-20T14:03:56Z + + + 2013-07-10T10:59:30Z + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+ lacI inhibitor

+
+ + + + + + + + + + + + +
+ + +

+ Tet repressor protein

+
+ + + + + + + + + + + + +
+ + +

+ lambda repressor

+
+ + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +

+ ratio of protein to mRNA decay rates

+
+
+ + +

+ Leakiness in protein copies per promoter and cell

+
+
+ + +

+ Protein copies per promoter and cell

+
+
+ + +

+ Average number of proteins per transcript

+
+
+ + +

+ Hill coefficient

+
+
+ + +

+ Number of repressor molecules per cell giving half maximal repression, in monomers per cell

+
+
+ + + + + +

+ mRNA decay rate constant

+
+
+ + +

+ Protein decay rate costant

+
+
+ + +

+ Translation rate constant

+
+
+ + +

+ Transcription rate from free promotor minus a0_tr

+
+
+ + +

+ Transcrition from free promotor in transcripts per second and promotor

+
+
+ + +

+ Transcrition from fully repressed promotor in transcripts per second and promotor

+
+
+ + +

+ Transcription rate from fully repressed promotor

+
+
+
+ + + + + + tau_mRNA + + + 2 + + + + + + + + + tau_mRNA + tau_prot + + + + + + + + eff + t_ave + + + + + + + + + + ps_a + ps_0 + + 60 + + + + + + + + ps_0 + 60 + + + + + + + + + + 2 + + tau_prot + + + + + + + + + + 2 + + tau_mRNA + + + + + + + + + + a_tr + eff + tau_prot + + + + + + 2 + + KM + + + + + + + + + + + a0_tr + eff + tau_prot + + + + + + 2 + + KM + + + + + + + + + + + + + + + + + + + + + + + + + + + kd_mRNA + X + + + + + + + + + + + + + + + + + + + + + + + + + kd_mRNA + Y + + + + + + + + + + + + + + + + + + + + + + + + + kd_mRNA + Z + + + + + + + + + + + + + + + + + + + + + + + + + + + + k_tl + X + + + + + + + + + + + + + + + + + + + + + + + + + + + + k_tl + Y + + + + + + + + + + + + + + + + + + + + + + + + + + + + k_tl + Z + + + + + + + + + + + + + + + + + + + + + + + + + kd_prot + PX + + + + + + + + + + + + + + + + + + + + + + + + + kd_prot + PY + + + + + + + + + + + + + + + + + + + + + + + + + kd_prot + PZ + + + + + + + + + + + + + + + + + + + + + + + + + + + + a0_tr + + + + + a_tr + + + KM + n + + + + + + + KM + n + + + + PZ + n + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + a0_tr + + + + + a_tr + + + KM + n + + + + + + + KM + n + + + + PX + n + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + a0_tr + + + + + a_tr + + + KM + n + + + + + + + KM + n + + + + PY + n + + + + + + + + +
+
\ No newline at end of file diff --git a/data/sbml/sources.json b/data/sbml/sources.json new file mode 100644 index 0000000..34e3fd7 --- /dev/null +++ b/data/sbml/sources.json @@ -0,0 +1,50 @@ +{ + "description": "Curated BioModels used as the SBML import regression set. Files are unmodified downloads.", + "retrieved": "2026-11-05", + "download_url_pattern": "https://www.ebi.ac.uk/biomodels/model/download/{id}?filename={id}_url.xml", + "models": [ + { + "id": "BIOMD0000000009", + "file": "BIOMD0000000009.xml", + "name": "Huang1996 - Ultrasensitivity in MAPK cascade", + "sbml": "L2V4", + "bytes": 54521, + "sha256": "1f95d793517d47dbf98321a89cdb14fcff9f461427b4ea062d398734c962ab98", + "url": "https://www.ebi.ac.uk/biomodels/model/download/BIOMD0000000009?filename=BIOMD0000000009_url.xml", + "license": "CC0 1.0 (stated in the model's notes)", + "pubmed": [ + "20587024", + "8816754" + ] + }, + { + "id": "BIOMD0000000010", + "file": "BIOMD0000000010.xml", + "name": "Kholodenko2000 - Ultrasensitivity and negative feedback bring oscillations in MAPK cascade", + "sbml": "L2V4", + "bytes": 29295, + "sha256": "906964e07ffd570ad94a03c1222e230b54b913cd536b008392bfb6155930a966", + "url": "https://www.ebi.ac.uk/biomodels/model/download/BIOMD0000000010?filename=BIOMD0000000010_url.xml", + "license": "CC0 1.0 (stated in the model's notes)", + "pubmed": [ + "10712587", + "20587024" + ] + }, + { + "id": "BIOMD0000000012", + "file": "BIOMD0000000012.xml", + "name": "Elowitz2000 - Repressilator", + "sbml": "L2V3", + "bytes": 43901, + "sha256": "d535c84bc5fe68b01728cac5c53f8fed971176e3f0f2367a9ba1e9c043b11a2d", + "url": "https://www.ebi.ac.uk/biomodels/model/download/BIOMD0000000012?filename=BIOMD0000000012_url.xml", + "license": "CC0 1.0 (stated in the model's notes)", + "pubmed": [ + "10659856", + "20587024" + ] + } + ], + "note": "Only models whose own notes state the CC0 1.0 public-domain dedication are vendored. Survey-only models are identified in the auto-research report by id and SHA-256, not copied here." +} diff --git a/docs/graph_formalization.md b/docs/graph_formalization.md index 995fefa..efac275 100644 --- a/docs/graph_formalization.md +++ b/docs/graph_formalization.md @@ -86,6 +86,58 @@ flowchart LR The full diagrams remain reproducible from the linked Mermaid sources. Old raster/vector images with mixed reference values have been removed. +## Reaction networks from SBML + +`vh.graph.sbml` reads a declared subset of SBML (Levels 2 and 3 core) from +scratch: compartments, species, parameters, function definitions, initial +assignments, assignment rules and reactions with MathML kinetic laws. Anything +outside the subset — events, rate or algebraic rules, delays, fast reactions, +stoichiometryMath, conversion factors, required packages — is refused by name, +never silently dropped. A model becomes + +- an **executable network**: reaction rates, `d amount / dt = N v`, + trajectories, steady states and the Jacobian restricted to the stoichiometric + class; and +- a **typed graph**: `species`, `reaction`, `compartment` and `moiety` nodes; + `reactant`/`product` edges carrying exact stoichiometry, `modifier` edges, and + `member` edges from each species to the conserved moieties it belongs to. + +The graph schema adds four invariants, each recomputed from the graph's own +edges rather than trusted from the importer: + +- **stoichiometry** — every coefficient is a positive exact rational; +- **located** — every species is in exactly one compartment; +- **conservation** — each moiety is an exact left-null vector of `N` + (`l . N = 0` in rational arithmetic), the moieties are independent and span + the whole left nullspace, and each total equals the weighted initial amounts; +- **stoichiometric consistency** — every reacting species admits a strictly + positive mass conserved by all internal reactions (Gevorgyan et al. 2008). + Each answer carries an exact certificate: a mass vector, or a reaction + combination that provably creates the unconserved species from nothing. + +Validated on three CC0 BioModels in [`data/sbml/`](../data/sbml/sources.json) +against exact algebra and libRoadRunner as an independent referee (details in +the [auto-research report](../auto-research/2026-11-05-E-sbml-import/report.md)): + +| Model | Exact conservation laws | Referee agreement | +|---|---|---| +| Kholodenko 2000 MAPK oscillator (BIOMD0000000010) | 3 kinase totals (100, 300, 300) | trajectories 7e-10; unstable fixed point and eigenvalues match; period 1299.77 to 9e-12 | +| Huang & Ferrell 1996 MAPK cascade (BIOMD0000000009) | 7 enzyme/kinase/phosphatase totals | trajectories 6e-10; stable steady state 2e-12; eigenvalues 8e-10 | +| Elowitz & Leibler 2000 repressilator (BIOMD0000000012) | none (open system) | trajectories 7e-10; unstable fixed point; period 125.354 to 2e-12 | + +```mermaid +flowchart LR + MKKK -->|J0| MKKK_P -->|J1| MKKK + MKK -->|J2| MKK_P -->|J3| MKK_PP -->|J4| MKK_P -->|J5| MKK + MAPK -->|J6| MAPK_P -->|J7| MAPK_PP -->|J8| MAPK_P -->|J9| MAPK + MKKK_P -.->|activates J2, J3| MKK + MKK_PP -.->|activates J6, J7| MAPK + MAPK_PP -.->|inhibits J0| MKKK +``` + +The full imported graph, including reaction nodes and moieties, is in +[`img/kholodenko_mapk_sbml.mmd`](img/kholodenko_mapk_sbml.mmd). + ## The graph verifying the physics engine The sharpest demonstration that the formalization is faithful: a **pure graph @@ -130,5 +182,6 @@ physics a formal, inspectable, verifiable skeleton to hang on. ```bash python scripts/validate_graph.py # runs every algorithm above, renders the diagrams -pytest -q tests/test_graph.py tests/test_graph_clearance.py +python scripts/validate_sbml.py # SBML import against exact algebra and libRoadRunner +pytest -q tests/test_graph.py tests/test_graph_clearance.py tests/test_sbml.py ``` diff --git a/docs/img/kholodenko_mapk_sbml.mmd b/docs/img/kholodenko_mapk_sbml.mmd new file mode 100644 index 0000000..550465d --- /dev/null +++ b/docs/img/kholodenko_mapk_sbml.mmd @@ -0,0 +1,62 @@ +%% Kholodenko 2000 MAPK cascade imported from SBML (BIOMD0000000010) +flowchart LR + MKKK["Mos"] + MKKK_P["Mos-P"] + MKK["Mek1"] + MKK_P["Mek1-P"] + MKK_PP["Mek1-PP"] + MAPK["Erk2"] + MAPK_P["Erk2-P"] + MAPK_PP["Erk2-PP"] + J0["MAPKKK activation"] + J1["MAPKKK inactivation"] + J2["phosphorylation of MAPKK"] + J3["phosphorylation of MAPKK-P"] + J4["dephosphorylation of MAPKK-PP"] + J5["dephosphorylation of MAPKK-P"] + J6["phosphorylation of MAPK"] + J7["phosphorylation of MAPK-P"] + J8["dephosphorylation of MAPK-PP"] + J9["dephosphorylation of MAPK-P"] + moiety_1["MKKK + MKKK_P"] + moiety_2["MKK + MKK_P + MKK_PP"] + moiety_3["MAPK + MAPK_P + MAPK_PP"] + MKKK --> J0 + J0 --> MKKK_P + MAPK_PP -->|"modifies"| J0 + MKKK_P --> J1 + J1 --> MKKK + MKK --> J2 + J2 --> MKK_P + MKKK_P -->|"modifies"| J2 + MKK_P --> J3 + J3 --> MKK_PP + MKKK_P -->|"modifies"| J3 + MKK_PP --> J4 + J4 --> MKK_P + MKK_P --> J5 + J5 --> MKK + MAPK --> J6 + J6 --> MAPK_P + MKK_PP -->|"modifies"| J6 + MAPK_P --> J7 + J7 --> MAPK_PP + MKK_PP -->|"modifies"| J7 + MAPK_PP --> J8 + J8 --> MAPK_P + MAPK_P --> J9 + J9 --> MAPK + MKKK --> moiety_1 + MKKK_P --> moiety_1 + MKK --> moiety_2 + MKK_P --> moiety_2 + MKK_PP --> moiety_2 + MAPK --> moiety_3 + MAPK_P --> moiety_3 + MAPK_PP --> moiety_3 + classDef c_species fill:#2B44C4,stroke:#222,color:#ffffff; + class MKKK,MKKK_P,MKK,MKK_P,MKK_PP,MAPK,MAPK_P,MAPK_PP c_species; + classDef c_reaction fill:#586379,stroke:#222,color:#ffffff; + class J0,J1,J2,J3,J4,J5,J6,J7,J8,J9 c_reaction; + classDef c_moiety fill:#1A8A54,stroke:#222,color:#ffffff; + class moiety_1,moiety_2,moiety_3 c_moiety; diff --git a/docs/roadmap.md b/docs/roadmap.md index 71a02d8..6b78fe3 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -75,6 +75,9 @@ A cell is ~10¹⁴ atoms, so pure CCSD(T) will never reach it. The path up: from the molecular layer → action-potential prolongation → torsade risk category. *Done when* the 28 CiPA reference drugs are classified into their published risk categories. 10. **Cells and pathways.** SBML import (BioModels) so target occupancy drives signaling and cellular response. + *Started 2026-11-05:* a from-scratch SBML core reader with exact conservation and positive-mass + invariants, validated against libRoadRunner ([report](../auto-research/2026-11-05-E-sbml-import/report.md)). + Still open: events, rate rules, delays, units checking, and wiring `vh.bridge` occupancy into a pathway. 11. **Uncertainty end to end.** Propagate parameter uncertainty across scales; Bayesian calibration; because every layer is differentiable (JAX), gradients of a clinical endpoint with respect to molecular parameters. diff --git a/pyproject.toml b/pyproject.toml index d1655ab..94092e3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,7 +28,9 @@ dependencies = [ prep = ["openmm>=8.1", "pdbfixer>=1.9"] # the quantum accuracy ceiling (rungs 4-5): ab initio electronic structure + geometry optimization quantum = ["pyscf>=2.5", "geometric>=1.0"] -dev = ["pytest>=8", "matplotlib>=3.8", "openmm>=8.1", "pdbfixer>=1.9", "pyscf>=2.5", "geometric>=1.0"] +# libroadrunner is the independent SBML referee for vh.graph.sbml (tests only) +dev = ["pytest>=8", "matplotlib>=3.8", "openmm>=8.1", "pdbfixer>=1.9", "pyscf>=2.5", "geometric>=1.0", + "libroadrunner>=2.7"] [tool.setuptools.packages.find] include = ["vh*"] diff --git a/scripts/validate_sbml.py b/scripts/validate_sbml.py new file mode 100644 index 0000000..033bd48 --- /dev/null +++ b/scripts/validate_sbml.py @@ -0,0 +1,251 @@ +"""SBML import validation: exact structure, an independent referee, and a survey. + +For each vendored BioModels file (data/sbml, CC0) this records the exact +conservation laws and their initial totals, positive-mass consistency with +exact certificates, and agreement with libRoadRunner (libSBML + CVODE) on +trajectories, the conservation space, steady states, reduced Jacobian +eigenvalues and, for oscillators, the limit-cycle period. + +With ``--survey DIR`` it also reads every BIOMD*.xml in DIR and records which +are refused (and why) and which fail positive-mass consistency, with the exact +certificate. Survey files are identified by SHA-256; they are not vendored. + + PYTHONPATH=. python scripts/validate_sbml.py [--survey DIR] +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +import numpy as np + +from vh.graph import Graph +from vh.graph import stoichiometry as S +from vh.graph.render import to_mermaid +from vh.graph.sbml import SBMLError, UnsupportedSBML, read_sbml + +ROOT = Path(__file__).resolve().parents[1] +DATA = ROOT / "data" / "sbml" +OUT = ROOT / "auto-research" / "2026-11-05-E-sbml-import" +IMG = ROOT / "docs" / "img" + +CASES = { # trajectory horizon, presimulation before the steady-state solve, oscillator? + "BIOMD0000000009": (200.0, 2000.0, False), + "BIOMD0000000010": (4000.0, 4000.0, True), + "BIOMD0000000012": (1000.0, 1000.0, True), +} + + +def _period(t, x): + """Mean interval between upward mean-crossings over the second half.""" + half = len(t) // 2 + tt, xx = t[half:], x[half:] - x[half:].mean() + up = np.nonzero((xx[:-1] < 0) & (xx[1:] >= 0))[0] + cross = tt[up] - xx[up] * (tt[up + 1] - tt[up]) / (xx[up + 1] - xx[up]) + gaps = np.diff(cross) + return float(gaps.mean()), float(gaps.std()), int(len(gaps)) + + +def _referee(path): + import roadrunner + + rr = roadrunner.RoadRunner(str(path)) + rr.integrator.relative_tolerance = 1e-12 + rr.integrator.absolute_tolerance = 1e-16 + rr.integrator.maximum_num_steps = 100000 + return rr, roadrunner.__version__ + + +def validate_model(mid: str) -> dict: + from scipy.optimize import linear_sum_assignment + + path = DATA / f"{mid}.xml" + m = read_sbml(path) + horizon, settle, oscillator = CASES[mid] + ids = m.dynamic_species + n = m.stoichiometry_matrix() + laws = m.conservation_laws() + x0 = dict(zip(ids, m.initial_amounts())) + cons = m.stoichiometric_consistency() + g, schema = m.to_graph() + row = { + "id": mid, "name": m.name, "sha256": m.source["sha256"], "sbml": f"L{m.level}V{m.version}", + "species": len(m.species), "dynamic_species": len(ids), "reactions": len(m.reactions), + "assignment_rules": len(m.rules), + "conservation_laws": [" + ".join(s if c == 1 else f"{c}*{s}" for s, c in law.items()) for law in laws], + "conserved_totals_initial_amount": [float(sum(c * x0[s] for s, c in law.items())) for law in laws], + "conserved_totals_initial_concentration": [ + float(sum(c * x0[s] for s, c in law.items()) / m.compartments[m.species[next(iter(law))].compartment].size) + if len({m.species[s].compartment for s in law}) == 1 else None for law in laws], + "exact_residual_l_dot_N": str(S.conservation_residual(S.conservation_laws(n), n)), + "rank_plus_laws_equals_dynamic_species": S.rank(n) + len(laws) == len(ids), + "positive_mass_consistent": cons["consistent"], "consistency_certified": cons["certified"], + "graph_invariant_problems": g.validate(schema), + } + + rr, version = _referee(path) + t = np.linspace(0, horizon, 101) + ref = np.array(rr.simulate(0, horizon, 101, selections=["time"] + ids)) + ours = m.simulate(ref[:, 0]) + traj = ours["amount"] + row["referee"] = {"engine": f"libRoadRunner {version}", + "trajectory_max_error_rel_to_species_max": float( + np.max(np.abs(traj - ref[:, 1:]) / np.abs(ref[:, 1:]).max(axis=0)))} + totals = np.array([[sum(c * traj[k, ids.index(s)] for s, c in law.items()) for law in laws] + for k in range(len(t))]) if laws else np.zeros((len(t), 0)) + row["max_relative_drift_of_conserved_totals"] = float( + np.max(np.abs(totals - totals[0]) / np.abs(totals[0]))) if laws else 0.0 + + rr2, _ = _referee(path) + rr2.conservedMoietyAnalysis = True + cm = rr2.getConservationMatrix() + arr = np.array(cm) + refm = arr[:, [list(cm.colnames).index(s) for s in ids]] if arr.size else np.zeros((0, len(ids))) + refm = refm[np.abs(refm).sum(axis=1) > 0] + oursm = np.array([[law.get(s, 0) for s in ids] for law in laws], float).reshape(-1, len(ids)) + rk = np.linalg.matrix_rank + row["referee"]["conservation_space_equal"] = bool( + rk(oursm) == rk(refm) == (rk(np.vstack([oursm, refm])) if len(oursm) else 0)) + + tail = m.simulate(np.linspace(0, settle, 401))["amount"][200:] + ss = m.steady_state(tail.mean(axis=0)) + rr2.simulate(0, settle, 3) + rr2.steadyState() + rss = np.array([rr2[s] for s in ids]) + ev = m.reduced_eigenvalues(ss["amount"]) + rev = np.array(rr2.getReducedEigenValues()) + cost = np.abs(ev[:, None] - rev[None, :]) + r_i, c_i = linear_sum_assignment(cost) + row["steady_state"] = { + "solver_success": ss["success"], "max_abs_rate_of_change": ss["max_abs_derivative"], + "max_diff_vs_referee_rel_to_max": float(np.max(np.abs(ss["amount"] - rss)) / np.max(np.abs(rss))), + "eigenvalue_max_diff_vs_referee_rel": float(np.max(cost[r_i, c_i]) / np.max(np.abs(rev))), + "max_real_eigenvalue": float(ev.real.max()), "stable": bool(ev.real.max() < 0), + } + if oscillator: + t_long = np.linspace(0, 1.5 * horizon if mid == "BIOMD0000000010" else 2 * horizon, 60001) + k = 0 + ours_p = _period(t_long, m.simulate(t_long)["amount"][:, k]) + rr3, _ = _referee(path) + ref_p = _period(t_long, np.array(rr3.simulate(0, t_long[-1], len(t_long), selections=["time", ids[k]]))[:, 1]) + row["oscillation"] = {"species": ids[k], "period": ours_p[0], "referee_period": ref_p[0], + "relative_difference": abs(ours_p[0] - ref_p[0]) / ref_p[0], + "cycles_averaged": ours_p[2], "model_time_units": "as written in the model"} + return row + + +SURVEY_HORIZON = 100.0 # model time units; the same window for every surveyed model + + +SURVEY_TOL = (1e-10, 1e-14) # (rtol, atol) in both engines +TIGHT_TOL = (1e-12, 1e-16) # re-run for any model above 1e-6, to separate integration error from semantics + + +def _survey_referee(path, m, tol=SURVEY_TOL): + """Worst |ours - libRoadRunner| / species range over [0, SURVEY_HORIZON], 51 points.""" + import roadrunner + + ids = m.dynamic_species + if not ids: + return None + roadrunner.Logger.setLevel(roadrunner.Logger.LOG_ERROR) + rr = roadrunner.RoadRunner(str(path)) + rr.integrator.relative_tolerance, rr.integrator.absolute_tolerance = tol + rr.integrator.maximum_num_steps = 500000 + ref = np.array(rr.simulate(0, SURVEY_HORIZON, 51, selections=["time"] + ids)) + ours = m.simulate(ref[:, 0], rtol=tol[0], atol=tol[1])["amount"] + scale = np.maximum(np.abs(ref[:, 1:]).max(axis=0), 1e-300) + return float(np.max(np.abs(ours - ref[:, 1:]) / scale)) + + +def survey(directory: Path) -> dict: + rows, refused = [], {} + for path in sorted(directory.glob("BIOMD*.xml")): + data = path.read_bytes() + entry = {"id": path.stem, "sha256": hashlib.sha256(data).hexdigest()} + try: + m = read_sbml(data) + except UnsupportedSBML as exc: + entry["status"] = "refused" + entry["reason"] = str(exc) + refused[str(exc).split(" '")[0].split(" http")[0]] = refused.get(str(exc).split(" '")[0].split(" http")[0], 0) + 1 + rows.append(entry) + continue + except SBMLError as exc: + entry["status"] = "error" + entry["reason"] = str(exc) + rows.append(entry) + continue + c = m.stoichiometric_consistency() + g, schema = m.to_graph() + graph_flag = any("[stoichiometric-consistency]" in p for p in g.validate(schema)) + entry.update({"status": "read", "name": m.name, "species": len(m.species), "reactions": len(m.reactions), + "conservation_laws": len(m.conservation_laws()), "positive_mass_consistent": c["consistent"], + "certified": c["certified"], "graph_invariant_agrees": graph_flag == (not c["consistent"])}) + if not c["consistent"]: + entry["unconserved"] = c["unconserved"] + entry["leak_certificate"] = c["leak_combination"] + entry["referee_trajectory_max_error"] = _survey_referee(path, m) + if entry["referee_trajectory_max_error"] is not None and entry["referee_trajectory_max_error"] > 1e-6: + entry["referee_trajectory_max_error_tight_tolerance"] = _survey_referee(path, m, TIGHT_TOL) + rows.append(entry) + read = [r for r in rows if r["status"] == "read"] + errs = [r["referee_trajectory_max_error"] for r in read if r["referee_trajectory_max_error"] is not None] + return {"files": len(rows), "read": len(read), "refused_by_construct": refused, + "referee": {"horizon": SURVEY_HORIZON, "rtol": SURVEY_TOL[0], "atol": SURVEY_TOL[1], + "compared": len(errs), "max_error_rel_to_species_range": max(errs), + "median_error": float(np.median(errs)), "within_1e-6": sum(e <= 1e-6 for e in errs), + "rerun_at_tight_tolerance": {r["id"]: [r["referee_trajectory_max_error"], + r["referee_trajectory_max_error_tight_tolerance"]] + for r in read if "referee_trajectory_max_error_tight_tolerance" in r}, + "tight_tolerance": {"rtol": TIGHT_TOL[0], "atol": TIGHT_TOL[1]}}, + "errors": [r for r in rows if r["status"] == "error"], + "inconsistent": [r["id"] for r in read if not r["positive_mass_consistent"]], + "all_classifications_certified": all(r["certified"] for r in read), + "graph_invariant_agrees_everywhere": all(r["graph_invariant_agrees"] for r in read), + "models": rows} + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--survey", type=Path, help="directory of BIOMD*.xml files to survey") + args = ap.parse_args(argv) + results = {"authority": "exact rational algebra; libRoadRunner as independent SBML referee", + "models": [validate_model(mid) for mid in CASES]} + if args.survey: + results["survey"] = survey(args.survey) + OUT.mkdir(parents=True, exist_ok=True) + (OUT / "results.json").write_text(json.dumps(results, indent=1) + "\n") + + g, _ = read_sbml(DATA / "BIOMD0000000010.xml").to_graph() + view = Graph(g.name) # built in document order, so the output is reproducible + for node in g.nodes.values(): + if node.type in ("species", "reaction", "moiety"): + view.add_node(node.id, node.type, node.scale, node.label, **node.attrs) + for e in g.edges: + if e.type in ("reactant", "product", "modifier", "member"): + view.add_edge(e.src, e.dst, e.type, e.directed, e.model, **e.attrs) + (IMG / "kholodenko_mapk_sbml.mmd").write_text( + to_mermaid(view, "LR", title="Kholodenko 2000 MAPK cascade imported from SBML (BIOMD0000000010)") + "\n") + + for row in results["models"]: + print(f"{row['id']} {row['name']}: {len(row['conservation_laws'])} exact laws, " + f"consistent={row['positive_mass_consistent']} (certified {row['consistency_certified']}); " + f"trajectory err {row['referee']['trajectory_max_error_rel_to_species_max']:.1e}; " + f"steady state diff {row['steady_state']['max_diff_vs_referee_rel_to_max']:.1e}, " + f"eig diff {row['steady_state']['eigenvalue_max_diff_vs_referee_rel']:.1e}, " + f"stable={row['steady_state']['stable']}") + if args.survey: + sv = results["survey"] + print(f"survey: {sv['read']}/{sv['files']} read; refused {sv['refused_by_construct']}; " + f"inconsistent {sv['inconsistent']}; certified {sv['all_classifications_certified']}; " + f"referee {sv['referee']['within_1e-6']}/{sv['referee']['compared']} within 1e-6, " + f"worst {sv['referee']['max_error_rel_to_species_range']:.1e}") + print(f"wrote {OUT.relative_to(ROOT)}/results.json and docs/img/kholodenko_mapk_sbml.mmd") + + +if __name__ == "__main__": + main() diff --git a/tests/test_sbml.py b/tests/test_sbml.py new file mode 100644 index 0000000..3546379 --- /dev/null +++ b/tests/test_sbml.py @@ -0,0 +1,430 @@ +"""SBML import: analytic kinetics, exact stoichiometry, refusals, and a referee. + +Synthetic networks below are artificial fixtures with closed-form solutions. +The vendored BioModels (data/sbml, CC0) are checked against exact algebra and, +when installed, against libRoadRunner -- an independent SBML implementation +(libSBML + CVODE) used here only as a referee. +""" + +import hashlib +import json +import math +from fractions import Fraction +from pathlib import Path + +import numpy as np +import pytest + +from vh.graph import Graph +from vh.graph import stoichiometry as S +from vh.graph.sbml import SBMLError, UnsupportedSBML, read_sbml + +ROOT = Path(__file__).resolve().parents[1] +DATA = ROOT / "data" / "sbml" +M = 'xmlns="http://www.w3.org/1998/Math/MathML"' + + +def l3(body: str, version: int = 2, extra: str = "") -> bytes: + return (f'\n{body}' + ).encode() + + +def l2(body: str) -> bytes: + return ('\n{body}').encode() + + +def species(sid, comp="c", conc=None, amount=None, hosu="false", boundary="false", constant="false"): + init = f'initialConcentration="{conc}"' if conc is not None else f'initialAmount="{amount}"' + return (f'') + + +def reaction(rid, reactants, products, math, local="", reversible="false", modifiers=()): + def refs(tag, items): + if not items: + return "" + inner = "".join(f'' for s, c in items) + return f"<{tag}>{inner}" + mods = ("" + "".join(f'' for m in modifiers) + + "") if modifiers else "" + lp = f"{local}" if local else "" + return (f'{refs("listOfReactants", reactants)}' + f'{refs("listOfProducts", products)}{mods}{math}{lp}') + + +def apply(op, *args): + return f"<{op}/>{''.join(args)}" + + +def ci(x): + return f"{x}" + + +def cn(x): + return f"{x}" + + +COMP = '' + + +# --------------------------------------------------------------------------- +# kinetics against closed-form solutions +# --------------------------------------------------------------------------- +@pytest.mark.parametrize("hosu", ["false", "true"]) +def test_first_order_decay_respects_concentration_versus_amount(hosu): + # V = 2.5, A0 = 10 (amount). Kinetic laws are substance/time: with + # hasOnlySubstanceUnits=false the symbol A is a concentration, so the law + # k*c*A and the amount-based law k*A describe the same amount decay. + size, k = 2.5, 0.3 + law = apply("times", ci("k"), ci("c"), ci("A")) if hosu == "false" else apply("times", ci("k"), ci("A")) + doc = l3(COMP.format(size=size) + + "" + species("A", amount=10, hosu=hosu) + species("B", amount=0, hosu=hosu) + + "" + + reaction("decay", [("A", 1)], [("B", 1)], law, f'') + + "") + m = read_sbml(doc) + t = np.linspace(0, 20, 41) + out = m.simulate(t) + exact = 10 * np.exp(-k * t) + np.testing.assert_allclose(out["amount"][:, 0], exact, rtol=1e-8, atol=1e-10) + np.testing.assert_allclose(out["amount"].sum(axis=1), 10, rtol=1e-12) + expected_value = exact / size if hosu == "false" else exact + np.testing.assert_allclose(out["value"][:, 0], expected_value, rtol=1e-8, atol=1e-10) + assert m.conservation_laws() == [{"A": 1, "B": 1}] + + +def test_reversible_mass_action_relaxation_steady_state_and_eigenvalue(): + kf, kr, a0 = 2.0, 0.5, 3.0 + law = apply("minus", apply("times", ci("kf"), ci("A")), apply("times", ci("kr"), ci("B"))) + doc = l3(COMP.format(size=1) + '' + '' + + species("A", conc=a0) + species("B", conc=0) + "" + + reaction("r", [("A", 1)], [("B", 1)], law, reversible="true") + "") + m = read_sbml(doc) + a_eq = a0 * kr / (kf + kr) + t = np.linspace(0, 5, 26) + out = m.simulate(t) + np.testing.assert_allclose(out["amount"][:, 0], a_eq + (a0 - a_eq) * np.exp(-(kf + kr) * t), rtol=1e-8) + ss = m.steady_state() + assert ss["success"] + np.testing.assert_allclose(ss["amount"], [a_eq, a0 - a_eq], rtol=1e-12) + np.testing.assert_allclose(m.reduced_eigenvalues(ss["amount"]), [-(kf + kr)], rtol=1e-6) + + +def test_functions_piecewise_time_rules_initial_assignment_and_local_shadowing(): + body = ( + f'' + f'{ci("x")}{ci("K")}{apply("divide", ci("x"), apply("plus", ci("K"), ci("x")))}' + '' + + COMP.format(size=2) + + '' + '' + + "" + species("A", conc=1) + species("B", conc=0) + "" + + f'' + f'{apply("times", cn(3), ci("base"))}' + + f'' + f'{cn(2)}{apply("lt", "t", cn(5))}' + f'{cn(0)}' + + "" + + reaction("r", [("A", 1)], [("B", 1)], + apply("times", ci("c"), ci("k"), ci("g"), f"{ci('sat')}{ci('A')}{cn(0.5)}"), + '') + + "") + m = read_sbml(l3(body)) + x0 = m.initial_amounts() + np.testing.assert_allclose(x0, [3 * 1.5 * 2, 0]) # initial assignment is a concentration + a = 4.5 + expected = 2 * 0.25 * 2 * a / (0.5 + a) # local k shadows the global k = 100 + assert m.rates(x0, t=1.0)[0] == pytest.approx(expected, rel=1e-15) + assert m.rates(x0, t=6.0)[0] == 0.0 # piecewise on csymbol time + + +# --------------------------------------------------------------------------- +# refusals: unsupported constructs are named, never silently dropped +# --------------------------------------------------------------------------- +BASE = COMP.format(size=1) + "" + species("A", conc=1) + species("B", conc=0) + "" +DECAY = reaction("r", [("A", 1)], [("B", 1)], apply("times", cn(0.1), ci("A"))) + + +@pytest.mark.parametrize("doc,message", [ + (l3(BASE + "" + DECAY + ""), "listOfEvents"), + (l3(BASE + f'{cn(1)}'), "rateRule"), + (l3(BASE + f'{ci("A")}'), "algebraicRule"), + (l3(BASE + "" + reaction("r", [("A", 1)], [("B", 1)], + "d" + + ci("A") + cn(1) + "") + ""), "delay"), + (l3(BASE + "" + DECAY.replace('reversible="false"', 'reversible="false" fast="true"') + + "", version=1), "fast reaction"), + (l2('' + '' + '' + f'{cn(2)}' + f'{ci("A")}'), "stoichiometryMath"), + (l3(BASE, extra=' xmlns:fbc="http://www.sbml.org/sbml/level3/version1/fbc/version2" fbc:required="true"'), + "required SBML package"), + (l3(BASE.replace('" + reaction("r", [("A", 1)], [("B", 1)], apply("factorial", ci("A"))) + + ""), "factorial"), + (l3(BASE + "" + reaction("r", [("A", 1)], [("B", 1)], ci("r")) + ""), + "reaction id"), + (l3(BASE.replace('constant="true"/>', 'constant="false"/>')), + "non-constant compartment"), + (l3(BASE + ""), "listOfConstraints"), +]) +def test_unsupported_constructs_are_refused_by_name(doc, message): + with pytest.raises(UnsupportedSBML, match=message): + read_sbml(doc) + + +@pytest.mark.parametrize("prefix", [ + b']>', + b'', +]) +def test_doctype_and_entity_declarations_are_refused(prefix): + with pytest.raises(SBMLError, match="DOCTYPE"): + read_sbml(prefix + l3(BASE).split(b"\n", 1)[1]) + + +UTF16_ENTITY = ('\n]>\n' + '' + '') + + +@pytest.mark.parametrize("encoding", ["utf-16", "utf-16-le", "utf-16-be"]) +def test_entity_refusal_does_not_depend_on_the_byte_encoding(encoding): + # Regression: an ASCII byte scan missed these, and the entity was expanded. + with pytest.raises(SBMLError, match="DOCTYPE"): + read_sbml(UTF16_ENTITY.encode(encoding)) + + +def test_utf16_documents_without_a_doctype_still_load(): + doc = l3(BASE + "" + DECAY + "").decode() + m = read_sbml(doc.replace('encoding="UTF-8"', 'encoding="UTF-16"').encode("utf-16")) + assert m.dynamic_species == ["A", "B"] + + +@pytest.mark.parametrize("data", [b"", b"".encode("utf-32")]) +def test_unreadable_xml_is_an_sbml_error(data): + with pytest.raises(SBMLError): + read_sbml(data) + + +@pytest.mark.parametrize("doc,message", [ + (l3(COMP.format(size=1) + "" + species("A", conc=1, constant="true") + species("B", conc=0) + + "" + DECAY + ""), "constant"), + (l3(BASE + '' + f'{ci("q")}' + f'{ci("p")}'), "algebraic loop"), + (l3(BASE + "" + reaction("r", [("A", 1)], [("B", 1)], ci("nope")) + ""), + "unknown symbols"), + (l3(COMP.format(size=1) + ''), "no initial value"), + (l3(COMP.format(size=1) + ''), + "needs attribute"), + (l3(BASE + "" + reaction("r", [("A", 0)], [("B", 1)], ci("A")) + ""), + "positive"), +]) +def test_semantic_errors_are_reported(doc, message): + with pytest.raises(SBMLError, match=message): + read_sbml(doc) + + +# --------------------------------------------------------------------------- +# exact stoichiometric algebra +# --------------------------------------------------------------------------- +def test_exact_rref_nullspace_and_conservation_laws(): + # A + E <-> AE -> B + E : conserved E + AE and A + AE + B. + n = [[-1, 1, 0], [-1, 1, 1], [1, -1, -1], [0, 0, 1]] # rows A, E, AE, B + laws = S.conservation_laws(n) + assert laws == [[1, 0, 1, 1], [0, 1, 1, 0]] + assert S.conservation_residual(laws, n) == 0 + assert S.rank(n) + len(laws) == 4 + for v in S.nullspace(n): + assert all(sum(Fraction(row[j]) * v[j] for j in range(3)) == 0 for row in n) + assert S.integer_row([Fraction(-1, 2), Fraction(1, 3)]) == [3, -2] + with pytest.raises(TypeError): + S.as_fraction(0.1) + + +def _check_certificates(n, res): + """Independent exact check of the returned certificates.""" + internal = res["internal_reactions"] + sub = [[Fraction(row[j]) for j in internal] for row in n] + mass = res["mass"] + assert all(m >= 0 for m in mass) and all(mass[i] > 0 for i in res["conserved"]) + assert all(sum(mass[i] * sub[i][k] for i in range(len(n))) == 0 for k in range(len(internal))) + if res["unconserved"]: + v = res["leak_combination"] + produced = [sum(sub[i][k] * v[k] for k in range(len(internal))) for i in range(len(n))] + assert all(p >= 0 for p in produced) and all(produced[i] > 0 for i in res["unconserved"]) + + +@pytest.mark.parametrize("n,internal,unconserved", [ + ([[-1, 0], [-1, 0], [1, -1], [0, 1]], None, []), # A + B -> C -> D + # A -> A + B: the net column hides the catalytic A, so the caller (as + # SBMLModel does from reactant/product lists) marks the reaction internal. + ([[0], [1]], [True], [1]), + ([[0], [1]], None, []), # same column read as pure synthesis + ([[-1], [-1], [1]], None, []), # A + B -> C + ([[-1, 0], [0, 1]], None, []), # A -> (out), (in) -> B: exchanges only + ([[-1, 1], [1, -2]], None, [0, 1]), # A -> B, 2B -> A: mass cannot balance + ([[-2, 1], [1, 0], [0, -1]], None, []), # 2A -> B, C -> A (fractional masses) +]) +def test_stoichiometric_consistency_with_exact_certificates(n, internal, unconserved): + res = S.stoichiometric_consistency(n, internal) + assert res["unconserved"] == unconserved + assert res["consistent"] == (not unconserved) + assert res["certified"] + _check_certificates(n, res) + + +# --------------------------------------------------------------------------- +# vendored BioModels: provenance, exact structure and graph invariants +# --------------------------------------------------------------------------- +SOURCES = json.loads((DATA / "sources.json").read_text()) +EXPECTED_LAWS = { + # Kinase totals of the three-tier cascade (Kholodenko 2000). + "BIOMD0000000010": [{"MKKK": 1, "MKKK_P": 1}, {"MKK": 1, "MKK_P": 1, "MKK_PP": 1}, + {"MAPK": 1, "MAPK_P": 1, "MAPK_PP": 1}], + # Two enzymes, three kinases and two phosphatases, each free plus bound (Huang & Ferrell 1996). + "BIOMD0000000009": [ + {"E1": 1, "E1_KKK": 1}, {"E2": 1, "E2_P_KKK": 1}, + {"KKK": 1, "P_KKK": 1, "E1_KKK": 1, "E2_P_KKK": 1, "P_KKK_KK": 1, "P_KKK_P_KK": 1}, + {"KK": 1, "P_KK": 1, "PP_KK": 1, "P_KKK_KK": 1, "P_KKK_P_KK": 1, "PP_KK_K": 1, "PP_KK_P_K": 1, + "KKPase_PP_KK": 1, "KKPase_P_KK": 1}, + {"K": 1, "P_K": 1, "PP_K": 1, "PP_KK_K": 1, "PP_KK_P_K": 1, "KPase_PP_K": 1, "KPase_P_K": 1}, + {"KPase": 1, "KPase_PP_K": 1, "KPase_P_K": 1}, {"KKPase": 1, "KKPase_PP_KK": 1, "KKPase_P_KK": 1}], + # Synthesis and degradation of every species: nothing is conserved (Elowitz & Leibler 2000). + "BIOMD0000000012": [], +} + + +def load(mid): + return read_sbml(DATA / f"{mid}.xml") + + +def test_vendored_models_match_recorded_provenance(): + assert {m["id"] for m in SOURCES["models"]} == set(EXPECTED_LAWS) + for entry in SOURCES["models"]: + data = (DATA / entry["file"]).read_bytes() + assert hashlib.sha256(data).hexdigest() == entry["sha256"] and len(data) == entry["bytes"] + assert entry["license"].startswith("CC0") and b"CC0" in data + + +@pytest.mark.parametrize("mid", sorted(EXPECTED_LAWS)) +def test_biomodels_exact_conservation_consistency_and_graph(mid): + m = load(mid) + assert m.conservation_laws() == EXPECTED_LAWS[mid] + n = m.stoichiometry_matrix() + laws = S.conservation_laws(n) + assert S.conservation_residual(laws, n) == 0 and S.rank(n) + len(laws) == len(m.dynamic_species) + res = m.stoichiometric_consistency() + assert res["consistent"] and res["certified"] + g, schema = m.to_graph() + assert g.validate(schema) == [] + restored = Graph.from_dict(json.loads(json.dumps(g.to_dict()))) + assert restored.validate(schema) == [] + + +def test_kholodenko_totals_are_conserved_along_the_trajectory(): + m = load("BIOMD0000000010") + out = m.simulate(np.linspace(0, 3000, 61)) + idx = {s: i for i, s in enumerate(out["species"])} + for law, total in zip(EXPECTED_LAWS["BIOMD0000000010"], (100, 300, 300)): + series = sum(c * out["amount"][:, idx[s]] for s, c in law.items()) + np.testing.assert_allclose(series, total, rtol=1e-9) + + +def test_graph_invariants_catch_tampered_structure(): + g, schema = load("BIOMD0000000009").to_graph() + member = next(e for e in g.edges_of_type("member") if e.src == "E1_KKK") + member.attrs["coefficient"] = "2" + assert any("[conservation] moiety_1: not conserved" in p for p in g.validate(schema)) + + g, schema = load("BIOMD0000000009").to_graph() + g = g.subgraph([n for n in g.nodes if n != "moiety_7"]) + assert any("6 moieties recorded" in p for p in g.validate(schema)) + + g, schema = load("BIOMD0000000010").to_graph() + next(iter(g.edges_of_type("product"))).attrs["stoichiometry"] = "0" + assert any("[stoichiometry]" in p for p in g.validate(schema)) + + # A product edge that creates MAPK from a conversion of MKKK breaks both + # the recorded moieties and positive-mass consistency. + g, schema = load("BIOMD0000000010").to_graph() + g.add_edge("J0", "MAPK", "product", stoichiometry="1") + problems = g.validate(schema) + assert any("[conservation]" in p for p in problems) + assert any("[stoichiometric-consistency]" in p and "exact certificate" in p for p in problems) + + +# --------------------------------------------------------------------------- +# independent referee: libRoadRunner +# --------------------------------------------------------------------------- +TIMES = {"BIOMD0000000010": 4000.0, "BIOMD0000000009": 200.0, "BIOMD0000000012": 1000.0} +# Presimulation before a steady-state solve: long enough to settle (stable +# model) or to sample a whole orbit (oscillators). Huang-Ferrell amounts are +# ~1e-13, so the referee's absolute steady-state threshold needs a start near +# the fixed point. +SETTLE = {"BIOMD0000000010": 4000.0, "BIOMD0000000009": 2000.0, "BIOMD0000000012": 1000.0} + + +def _referee(mid): + roadrunner = pytest.importorskip("roadrunner") + rr = roadrunner.RoadRunner(str(DATA / f"{mid}.xml")) + rr.integrator.relative_tolerance = 1e-12 + rr.integrator.absolute_tolerance = 1e-16 + rr.integrator.maximum_num_steps = 100000 + return rr + + +@pytest.mark.parametrize("mid", sorted(TIMES)) +def test_trajectories_match_libroadrunner(mid): + rr = _referee(mid) + m = load(mid) + ids = m.dynamic_species + ref = np.array(rr.simulate(0, TIMES[mid], 101, selections=["time"] + ids)) + ours = m.simulate(ref[:, 0]) + scale = np.abs(ref[:, 1:]).max(axis=0) + assert np.max(np.abs(ours["amount"] - ref[:, 1:]) / scale) < 1e-8 + + +@pytest.mark.parametrize("mid", sorted(TIMES)) +def test_conservation_space_matches_libroadrunner(mid): + rr = _referee(mid) + rr.conservedMoietyAnalysis = True + m = load(mid) + ids = m.dynamic_species + cm = rr.getConservationMatrix() + ref = np.array(cm)[:, [list(cm.colnames).index(s) for s in ids]] if np.array(cm).size else np.zeros((0, len(ids))) + ref = ref[np.abs(ref).sum(axis=1) > 0] # rows on rule-set species vanish here + ours = np.array([[law.get(s, 0) for s in ids] for law in m.conservation_laws()], float).reshape(-1, len(ids)) + rank = np.linalg.matrix_rank + assert rank(ours) == rank(ref) == (rank(np.vstack([ours, ref])) if len(ours) else 0) + + +@pytest.mark.parametrize("mid,stable", [("BIOMD0000000009", True), ("BIOMD0000000010", False), + ("BIOMD0000000012", False)]) +def test_steady_state_and_stability_match_libroadrunner(mid, stable): + from scipy.optimize import linear_sum_assignment + + rr = _referee(mid) + rr.conservedMoietyAnalysis = True + m = load(mid) + ids = m.dynamic_species + tail = m.simulate(np.linspace(0, SETTLE[mid], 401))["amount"][200:] + ss = m.steady_state(tail.mean(axis=0)) # an orbit's mean starts Newton near the fixed point + assert ss["success"] and ss["max_abs_derivative"] < 1e-9 + rr.simulate(0, SETTLE[mid], 3) + rr.steadyState() + ref = np.array([rr[s] for s in ids]) + assert np.max(np.abs(ss["amount"] - ref)) / np.max(np.abs(ref)) < 1e-7 + ours_ev = m.reduced_eigenvalues(ss["amount"]) + ref_ev = np.array(rr.getReducedEigenValues()) + cost = np.abs(ours_ev[:, None] - ref_ev[None, :]) + rows, cols = linear_sum_assignment(cost) + assert len(ours_ev) == len(ref_ev) + assert np.max(cost[rows, cols]) / np.max(np.abs(ref_ev)) < 1e-6 + assert (ours_ev.real.max() < 0) == stable diff --git a/vh/graph/render.py b/vh/graph/render.py index e8006e6..29adffe 100644 --- a/vh/graph/render.py +++ b/vh/graph/render.py @@ -22,6 +22,9 @@ "lumen": ("#B26A12", "#ffffff"), "target": ("#1A8A54", "#ffffff"), "atom": ("#2B44C4", "#ffffff"), + "species": ("#2B44C4", "#ffffff"), + "reaction": ("#586379", "#ffffff"), + "moiety": ("#1A8A54", "#ffffff"), } _EDGE_LABEL = { "flow": lambda e: f"{e.attrs.get('flow', 0):.1f} L/h", @@ -30,6 +33,11 @@ "absorbs": lambda e: f"Fa·Fg={e.attrs.get('fa',0)*e.attrs.get('fg',1):.2f}", "binds": lambda e: f"Kd {e.attrs.get('kd_nm','?')} nM", "bond": lambda e: "", + # SBML reaction networks: show a coefficient only when it is not 1 + "reactant": lambda e: "" if str(e.attrs.get("stoichiometry", "1")) == "1" else str(e.attrs["stoichiometry"]), + "product": lambda e: "" if str(e.attrs.get("stoichiometry", "1")) == "1" else str(e.attrs["stoichiometry"]), + "modifier": lambda e: "modifies", + "member": lambda e: "" if str(e.attrs.get("coefficient", "1")) == "1" else str(e.attrs["coefficient"]), } diff --git a/vh/graph/sbml.py b/vh/graph/sbml.py new file mode 100644 index 0000000..1807b06 --- /dev/null +++ b/vh/graph/sbml.py @@ -0,0 +1,1066 @@ +"""Read a declared subset of SBML into an executable reaction network and a typed graph. + +Written from scratch on the standard-library XML parser; libSBML/libRoadRunner +are used only as independent referees in the tests. Supported: SBML Level 2 +(versions 1-5) and Level 3 (versions 1-2) core models built from + + compartments (constant size), species, global and local parameters, + function definitions, initial assignments, assignment rules, and reactions + with reactants, products, modifiers and a MathML kinetic law. + +Anything outside that subset -- events, rate and algebraic rules, constraints, +delays, fast reactions, stoichiometryMath, conversion factors, variable +compartments, required packages, or a MathML element not listed in +``_OPERATORS`` -- raises ``UnsupportedSBML`` naming the construct. Nothing is +silently dropped except notes, annotations, units and SBO terms. Units are not +checked: the numbers are used as written, as an SBML simulator would. + +SBML semantics implemented here: a species symbol in math means its +concentration (amount / compartment size) unless ``hasOnlySubstanceUnits``; a +kinetic law is in substance per time, so ``d amount_i / dt = sum_j N_ij v_j``; +boundary-condition species are not changed by reactions. + +Documents containing a DOCTYPE are refused (no entity expansion); MathML is +compiled to closures over a fixed operator table, never to ``eval``. +""" + +from __future__ import annotations + +import hashlib +import math +import xml.etree.ElementTree as ET +from dataclasses import dataclass, field +from fractions import Fraction +from pathlib import Path + +import numpy as np + +from . import stoichiometry as S +from .core import EdgeRule, Graph, Schema + +MATHML = "http://www.w3.org/1998/Math/MathML" +_TIME = "http://www.sbml.org/sbml/symbols/time" +_AVOGADRO = "http://www.sbml.org/sbml/symbols/avogadro" +_DELAY = "http://www.sbml.org/sbml/symbols/delay" + + +class SBMLError(ValueError): + """The document is malformed or violates SBML semantics this reader relies on.""" + + +class UnsupportedSBML(SBMLError): + """The document is valid SBML but uses a construct outside the supported subset.""" + + +# --------------------------------------------------------------------------- +# MathML -> expression tree +# --------------------------------------------------------------------------- +# A node is a tuple: ("num", float) | ("sym", id) | ("time",) | ("op", name, args) +# | ("piecewise", ((value, cond), ...), otherwise_or_None) | ("call", fname, args) + +def _local(tag: str) -> str: + return tag.rsplit("}", 1)[-1] + + +def _ieee_div(a, b): + if b == 0: + if a == 0 or math.isnan(a): + return math.nan + return math.copysign(math.inf, a) * math.copysign(1.0, b) + return a / b + + +def _ieee_pow(a, b): + try: + r = a ** b + except ZeroDivisionError: + return math.inf + except OverflowError: + return math.inf + return math.nan if isinstance(r, complex) else r + + +def _ieee(fn): + """Domain errors become NaN and overflow becomes inf, as in IEEE arithmetic, + so a kinetic law evaluated off its domain does not abort an integration.""" + def wrapped(args): + try: + return fn(args) + except (ValueError, ZeroDivisionError): + return math.nan + except OverflowError: + return math.inf + return wrapped + + +def _log(args): + return math.log10(args[0]) if len(args) == 1 else math.log(args[1], args[0]) + + +def _chain(cmp): + return lambda args: all(cmp(a, b) for a, b in zip(args, args[1:])) + + +_OPERATORS = { + "plus": lambda a: sum(a) if a else 0.0, + "minus": lambda a: -a[0] if len(a) == 1 else a[0] - a[1], + "times": lambda a: math.prod(a) if a else 1.0, + "divide": lambda a: _ieee_div(a[0], a[1]), + "power": lambda a: _ieee_pow(a[0], a[1]), + "root": _ieee(lambda a: _ieee_pow(a[1], 1.0 / a[0]) if len(a) == 2 else math.sqrt(a[0])), + "exp": _ieee(lambda a: math.exp(a[0])), + "ln": _ieee(lambda a: math.log(a[0])), + "log": _ieee(_log), + "abs": lambda a: abs(a[0]), + "floor": lambda a: float(math.floor(a[0])), + "ceiling": lambda a: float(math.ceil(a[0])), + "sin": lambda a: math.sin(a[0]), "cos": lambda a: math.cos(a[0]), + "tan": lambda a: math.tan(a[0]), "arcsin": _ieee(lambda a: math.asin(a[0])), + "arccos": _ieee(lambda a: math.acos(a[0])), "arctan": lambda a: math.atan(a[0]), + "sinh": _ieee(lambda a: math.sinh(a[0])), "cosh": _ieee(lambda a: math.cosh(a[0])), + "tanh": lambda a: math.tanh(a[0]), + "eq": _chain(lambda x, y: x == y), "neq": lambda a: a[0] != a[1], + "gt": _chain(lambda x, y: x > y), "lt": _chain(lambda x, y: x < y), + "geq": _chain(lambda x, y: x >= y), "leq": _chain(lambda x, y: x <= y), + "and": lambda a: all(a), "or": lambda a: any(a), "xor": lambda a: sum(map(bool, a)) % 2 == 1, + "not": lambda a: not a[0], +} +_ARITY = {"minus": (1, 2), "divide": (2, 2), "power": (2, 2), "neq": (2, 2), "not": (1, 1)} +_UNARY = {"exp", "ln", "abs", "floor", "ceiling", "sin", "cos", "tan", "arcsin", "arccos", + "arctan", "sinh", "cosh", "tanh"} +_CONSTANTS = {"pi": math.pi, "exponentiale": math.e, "true": 1.0, "false": 0.0, + "infinity": math.inf, "notanumber": math.nan} +_INFIX = {"plus": "+", "minus": "-", "times": "*", "divide": "/", "power": "^"} + + +def _cn(el) -> tuple: + kind = el.attrib.get("type", "real") + parts = [p.strip() for p in "".join(el.itertext()).split()] if kind not in ("e-notation", "rational") else None + if kind in ("e-notation", "rational"): + seps = [c for c in el if _local(c.tag) == "sep"] + if len(seps) != 1: + raise SBMLError(f" needs exactly one ") + a = (el.text or "").strip() + b = (seps[0].tail or "").strip() + return ("num", float(a) * 10.0 ** float(b) if kind == "e-notation" else float(Fraction(a) / Fraction(b))) + if kind not in ("real", "integer", "double"): + raise UnsupportedSBML(f"") + if len(parts) != 1: + raise SBMLError(" must contain one number") + return ("num", float(parts[0])) + + +def parse_mathml(el) -> tuple: + """Expression tree of one MathML element (```` or a child).""" + tag = _local(el.tag) + if tag in ("math", "semantics"): + kids = [c for c in el if _local(c.tag) not in ("annotation", "annotation-xml")] + if len(kids) != 1: + raise SBMLError(f"<{tag}> must contain exactly one expression") + return parse_mathml(kids[0]) + if tag == "cn": + return _cn(el) + if tag == "ci": + return ("sym", "".join(el.itertext()).strip()) + if tag == "csymbol": + url = el.attrib.get("definitionURL", "").strip() + if url == _TIME: + return ("time",) + if url == _AVOGADRO: + return ("num", 6.02214076e23) + raise UnsupportedSBML(f"csymbol {url or '(no definitionURL)'}") + if tag in _CONSTANTS: + return ("num", _CONSTANTS[tag]) + if tag == "piecewise": + pieces, otherwise = [], None + for c in el: + kids = list(c) + if _local(c.tag) == "piece" and len(kids) == 2: + pieces.append((parse_mathml(kids[0]), parse_mathml(kids[1]))) + elif _local(c.tag) == "otherwise" and len(kids) == 1: + otherwise = parse_mathml(kids[0]) + else: + raise SBMLError("malformed ") + return ("piecewise", tuple(pieces), otherwise) + if tag == "apply": + kids = list(el) + if not kids: + raise SBMLError("empty ") + head, rest = kids[0], kids[1:] + h = _local(head.tag) + if h == "ci": + return ("call", "".join(head.itertext()).strip(), tuple(parse_mathml(k) for k in rest)) + if h == "csymbol": + raise UnsupportedSBML(f"csymbol function {head.attrib.get('definitionURL', '')}") + if h not in _OPERATORS: + raise UnsupportedSBML(f"MathML operator <{h}>") + args = [] + for k in rest: + q = _local(k.tag) + if q in ("degree", "logbase"): + inner = list(k) + if len(inner) != 1: + raise SBMLError(f"<{q}> must contain one expression") + args.insert(0, parse_mathml(inner[0])) + else: + args.append(parse_mathml(k)) + lo, hi = _ARITY.get(h, (1, 1) if h in _UNARY else (0, None)) + if h in ("root", "log"): + lo, hi = 1, 2 + if len(args) < lo or (hi is not None and len(args) > hi): + raise SBMLError(f"<{h}> applied to {len(args)} arguments") + return ("op", h, tuple(args)) + raise UnsupportedSBML(f"MathML element <{tag}>") + + +def symbols(node) -> set[str]: + kind = node[0] + if kind == "sym": + return {node[1]} + if kind == "op" or kind == "call": + out = set() + for a in node[2]: + out |= symbols(a) + return out + if kind == "piecewise": + out = set() + for v, c in node[1]: + out |= symbols(v) | symbols(c) + if node[2] is not None: + out |= symbols(node[2]) + return out + return set() + + +def infix(node) -> str: + """Human-readable form for graph attributes and reports (not re-parsed).""" + kind = node[0] + if kind == "num": + return repr(node[1]) if not float(node[1]).is_integer() else str(int(node[1])) + if kind == "sym": + return node[1] + if kind == "time": + return "time" + if kind == "call": + return f"{node[1]}({', '.join(infix(a) for a in node[2])})" + if kind == "piecewise": + body = ", ".join(f"{infix(v)} if {infix(c)}" for v, c in node[1]) + return f"piecewise({body}{', otherwise ' + infix(node[2]) if node[2] else ''})" + name, args = node[1], node[2] + if name in _INFIX and len(args) >= 2: + return "(" + f" {_INFIX[name]} ".join(infix(a) for a in args) + ")" + if name == "minus" and len(args) == 1: + return f"-{infix(args[0])}" + return f"{name}({', '.join(infix(a) for a in args)})" + + +def _substitute(node, mapping): + kind = node[0] + if kind == "sym": + return mapping.get(node[1], node) + if kind in ("op", "call"): + return (kind, node[1], tuple(_substitute(a, mapping) for a in node[2])) + if kind == "piecewise": + return ("piecewise", tuple((_substitute(v, mapping), _substitute(c, mapping)) for v, c in node[1]), + None if node[2] is None else _substitute(node[2], mapping)) + return node + + +def _inline(node, functions, depth=0): + """Replace calls to SBML function definitions by their bodies.""" + if depth > 64: + raise SBMLError("function definitions nest too deeply (recursive?)") + kind = node[0] + if kind == "call": + if node[1] not in functions: + raise SBMLError(f"call to undefined function {node[1]!r}") + params, body = functions[node[1]] + args = [_inline(a, functions, depth) for a in node[2]] + if len(args) != len(params): + raise SBMLError(f"function {node[1]!r} takes {len(params)} arguments, got {len(args)}") + return _inline(_substitute(body, dict(zip(params, args))), functions, depth + 1) + if kind == "op": + return ("op", node[1], tuple(_inline(a, functions, depth) for a in node[2])) + if kind == "piecewise": + return ("piecewise", tuple((_inline(v, functions, depth), _inline(c, functions, depth)) + for v, c in node[1]), + None if node[2] is None else _inline(node[2], functions, depth)) + return node + + +def compile_expr(node, index: dict[str, int], constants: dict[str, float] | None = None): + """Closure ``f(env, t) -> float``; ``index`` maps symbols to ``env`` slots and + ``constants`` binds local parameters (which shadow global symbols).""" + constants = constants or {} + kind = node[0] + if kind == "num": + v = float(node[1]) + return lambda env, t: v + if kind == "time": + return lambda env, t: t + if kind == "sym": + name = node[1] + if name in constants: + v = float(constants[name]) + return lambda env, t: v + if name not in index: + raise SBMLError(f"math references unknown or unsupported symbol {name!r}") + i = index[name] + return lambda env, t: env[i] + if kind == "piecewise": + pieces = [(compile_expr(v, index, constants), compile_expr(c, index, constants)) for v, c in node[1]] + other = compile_expr(node[2], index, constants) if node[2] is not None else (lambda env, t: math.nan) + + def piecewise(env, t): + for value, cond in pieces: + if cond(env, t): + return value(env, t) + return other(env, t) + return piecewise + if kind == "call": + raise SBMLError("function calls must be inlined before compilation") + fn = _OPERATORS[node[1]] + args = [compile_expr(a, index, constants) for a in node[2]] + if len(args) == 1: + a0 = args[0] + return lambda env, t: fn([a0(env, t)]) + if len(args) == 2: + a0, a1 = args + return lambda env, t: fn([a0(env, t), a1(env, t)]) + return lambda env, t: fn([a(env, t) for a in args]) + + +# --------------------------------------------------------------------------- +# model components +# --------------------------------------------------------------------------- +@dataclass(frozen=True) +class Compartment: + id: str + size: float | None + name: str = "" + + +@dataclass(frozen=True) +class Species: + id: str + compartment: str + initial: tuple[str, float] | None # ("amount" | "concentration", value) as written + has_only_substance_units: bool + boundary_condition: bool + constant: bool + name: str = "" + + +@dataclass(frozen=True) +class Reaction: + id: str + reactants: tuple[tuple[str, Fraction], ...] + products: tuple[tuple[str, Fraction], ...] + modifiers: tuple[str, ...] + rate: tuple | None # inlined expression tree, or None (no kinetic law) + local_parameters: dict = field(default_factory=dict) + reversible: bool = True + name: str = "" + + +def _bool(el, attr, default, level): + v = el.attrib.get(attr) + if v is None: + if level >= 3 and default is None: + raise SBMLError(f"<{_local(el.tag)} id={el.attrib.get('id')!r}> needs attribute {attr!r} in Level 3") + return bool(default) + if v not in ("true", "false", "1", "0"): + raise SBMLError(f"attribute {attr}={v!r} is not a boolean") + return v in ("true", "1") + + +def _float(el, attr): + v = el.attrib.get(attr) + if v is None: + return None + x = float(v) + if not math.isfinite(x): + raise SBMLError(f"attribute {attr}={v!r} is not finite") + return x + + +def _stoichiometry(ref, level) -> Fraction: + for c in ref: + if _local(c.tag) == "stoichiometryMath": + raise UnsupportedSBML("stoichiometryMath") + raw = ref.attrib.get("stoichiometry") + if raw is None: + if level >= 3: + raise UnsupportedSBML(f"Level 3 speciesReference to {ref.attrib.get('species')!r} without stoichiometry") + raw = "1" + try: + value = Fraction(raw.strip()) + except ValueError as exc: + raise SBMLError(f"stoichiometry {raw!r} is not a finite decimal") from exc + if value <= 0: + raise SBMLError(f"stoichiometry {raw!r} must be positive") + return value + + +_IGNORED = {"notes", "annotation", "listOfUnitDefinitions", "listOfCompartmentTypes", "listOfSpeciesTypes"} +_HANDLED = {"listOfFunctionDefinitions", "listOfCompartments", "listOfSpecies", "listOfParameters", + "listOfInitialAssignments", "listOfRules", "listOfReactions"} + + +class SBMLModel: + """An SBML reaction network: structure (exact stoichiometry), executable + kinetics, and conversion to a typed :class:`Graph`.""" + + def __init__(self, *, id, name, level, version, compartments, species, parameters, + functions, initial_assignments, rules, reactions, source=None): + self.id, self.name, self.level, self.version = id, name, level, version + self.compartments: dict[str, Compartment] = compartments + self.species: dict[str, Species] = species + self.parameters: dict[str, tuple[float | None, bool]] = parameters + self.functions = functions + self.initial_assignments: dict[str, tuple] = initial_assignments + self.rules: dict[str, tuple] = rules + self.reactions: dict[str, Reaction] = reactions + self.source = source or {} + self._check_semantics() + self._compile() + + # --- structure ----------------------------------------------------------- + def _check_semantics(self): + ids = list(self.compartments) + list(self.species) + list(self.parameters) + list(self.reactions) + dup = {i for i in ids if ids.count(i) > 1} + if dup: + raise SBMLError(f"duplicate ids {sorted(dup)}") + for s in self.species.values(): + if s.compartment not in self.compartments: + raise SBMLError(f"species {s.id!r} in unknown compartment {s.compartment!r}") + for target in self.rules: + if target in self.compartments: + raise UnsupportedSBML(f"assignment rule for compartment {target!r} (variable volume)") + if target not in self.species and target not in self.parameters: + raise SBMLError(f"assignment rule for unknown or reaction id {target!r}") + if target in self.initial_assignments: + raise SBMLError(f"{target!r} has both an assignment rule and an initial assignment") + if (target in self.parameters and self.parameters[target][1]) or ( + target in self.species and self.species[target].constant): + raise SBMLError(f"constant {target!r} cannot have an assignment rule") + for target in self.initial_assignments: + if target not in self.compartments and target not in self.species and target not in self.parameters: + raise UnsupportedSBML(f"initial assignment to {target!r} (not a compartment, species or parameter)") + for c in self.compartments.values(): + if c.size is None and c.id not in self.initial_assignments: + raise SBMLError(f"compartment {c.id!r} has no size") + for s in self.species.values(): + if s.initial is None and s.id not in self.initial_assignments and s.id not in self.rules: + raise SBMLError(f"species {s.id!r} has no initial value") + for p, (value, _) in self.parameters.items(): + if value is None and p not in self.initial_assignments and p not in self.rules: + raise SBMLError(f"parameter {p!r} has no value") + for r in self.reactions.values(): + for sid, _ in r.reactants + r.products: + if sid not in self.species: + raise SBMLError(f"reaction {r.id!r} references unknown species {sid!r}") + sp = self.species[sid] + if not sp.boundary_condition and (sp.constant or sid in self.rules): + raise SBMLError(f"species {sid!r} is changed by reaction {r.id!r} but is " + f"{'constant' if sp.constant else 'set by an assignment rule'} " + "and not a boundary condition") + for sid in r.modifiers: + if sid not in self.species: + raise SBMLError(f"reaction {r.id!r} modifier {sid!r} is not a species") + + @property + def dynamic_species(self) -> list[str]: + """Species whose amounts are state variables (changed only by reactions).""" + return [s.id for s in self.species.values() + if not s.boundary_condition and not s.constant and s.id not in self.rules] + + @property + def reaction_ids(self) -> list[str]: + return list(self.reactions) + + def stoichiometry_matrix(self, species_ids: list[str] | None = None) -> list[list[Fraction]]: + """Exact net stoichiometry N (rows: species, columns: reactions).""" + species_ids = self.dynamic_species if species_ids is None else species_ids + row = {s: i for i, s in enumerate(species_ids)} + n = [[Fraction(0)] * len(self.reactions) for _ in species_ids] + for j, r in enumerate(self.reactions.values()): + for sid, c in r.reactants: + if sid in row: + n[row[sid]][j] -= c + for sid, c in r.products: + if sid in row: + n[row[sid]][j] += c + return n + + def conservation_laws(self) -> list[dict[str, int]]: + """Exact conserved moieties over dynamic species amounts (see stoichiometry).""" + ids = self.dynamic_species + laws = S.conservation_laws(self.stoichiometry_matrix(ids)) + return [{ids[i]: c for i, c in enumerate(law) if c} for law in laws] + + def reacting_species(self) -> list[str]: + """Every species consumed or produced by some reaction, in document order.""" + used = {sid for r in self.reactions.values() for sid, _ in r.reactants + r.products} + return [s for s in self.species if s in used] + + def stoichiometric_consistency(self) -> dict: + """Positive-mass check over all reacting species. + + Boundary and constant species keep their rows (being held fixed does + not change a species' mass), but a reaction counts as internal only if + each side has at least one species that is not held fixed. Reactions + whose reactants or products are all fixed pools (for example + ``A -> EmptySet``, or synthesis from a clamped precursor) exchange + matter with the environment, like pure synthesis or degradation.""" + ids = self.reacting_species() + free = {s.id for s in self.species.values() if not s.boundary_condition and not s.constant} + internal = [any(sid in free for sid, _ in r.reactants) and any(sid in free for sid, _ in r.products) + for r in self.reactions.values()] + res = S.stoichiometric_consistency(self.stoichiometry_matrix(ids), internal) + return {**res, + "conserved": [ids[i] for i in res["conserved"]], + "unconserved": [ids[i] for i in res["unconserved"]], + "internal_reactions": [self.reaction_ids[j] for j in res["internal_reactions"]], + "mass": None if res["mass"] is None else {ids[i]: str(m) for i, m in enumerate(res["mass"])}, + "leak_combination": None if res["leak_combination"] is None else { + self.reaction_ids[j]: str(v) for j, v in zip(res["internal_reactions"], res["leak_combination"]) + if v}} + + # --- kinetics ------------------------------------------------------------ + def _compile(self): + self._symbols = list(self.compartments) + list(self.species) + list(self.parameters) + self._index = {s: i for i, s in enumerate(self._symbols)} + allowed = set(self._index) + + def check_refs(expr, where, local=()): + unknown = symbols(expr) - allowed - set(local) + if unknown & set(self.reactions): + raise UnsupportedSBML(f"{where} uses a reaction id as a rate symbol") + if unknown: + raise SBMLError(f"{where} references unknown symbols {sorted(unknown)}") + + for target, expr in {**self.rules, **self.initial_assignments}.items(): + check_refs(expr, f"rule/assignment for {target!r}") + self._rule_order = _topological(self.rules, set(self.rules)) + self._rule_fns = [(self._index[t], compile_expr(self.rules[t], self._index)) for t in self._rule_order] + self._rate_fns = [] + for r in self.reactions.values(): + if r.rate is None: + self._rate_fns.append(None) + continue + check_refs(r.rate, f"kinetic law of {r.id!r}", r.local_parameters) + self._rate_fns.append(compile_expr(r.rate, self._index, r.local_parameters)) + self._missing_laws = [r for r, fn in zip(self.reactions, self._rate_fns) if fn is None] + dyn = self.dynamic_species + self._dyn_env = np.array([self._index[s] for s in dyn], dtype=int) + self._dyn_size_ix = np.array([self._index[self.species[s].compartment] for s in dyn], dtype=int) + self._dyn_conc = np.array([not self.species[s].has_only_substance_units for s in dyn], dtype=bool) + n = self.stoichiometry_matrix(dyn) + self._n = np.array([[float(x) for x in row] for row in n]).reshape(len(dyn), len(self.reactions)) + self._env0 = self._initial_env() + + def _initial_env(self) -> np.ndarray: + """Symbol values at t = 0: attributes, then initial assignments and rules in + dependency order. Species values are concentrations unless + hasOnlySubstanceUnits.""" + env = np.full(len(self._symbols), np.nan) + defs: dict[str, tuple] = {} + for c in self.compartments.values(): + if c.size is not None: + env[self._index[c.id]] = c.size + for p, (value, _) in self.parameters.items(): + if value is not None: + env[self._index[p]] = value + raw_species = {} + for s in self.species.values(): + if s.id in self.initial_assignments or s.id in self.rules: + continue + raw_species[s.id] = s + defs[s.id] = ("sym", s.compartment) # dependency marker only + defs.update(self.initial_assignments) + defs.update(self.rules) + order = _topological(defs, set(defs)) + for target in order: + i = self._index[target] + if target in raw_species: + s = raw_species[target] + kind, value = s.initial + size = env[self._index[s.compartment]] + as_amount = value if kind == "amount" else value * size + env[i] = as_amount if s.has_only_substance_units else _ieee_div(as_amount, size) + else: + env[i] = compile_expr(_inline(defs[target], self.functions), self._index)(env, 0.0) + if np.isnan(env).any(): + missing = [s for s, v in zip(self._symbols, env) if np.isnan(v)] + raise SBMLError(f"no initial value for {missing}") + return env + + def sizes(self) -> np.ndarray: + """Compartment size of each dynamic species (state scaling).""" + return self._env0[self._dyn_size_ix].copy() + + def initial_amounts(self) -> np.ndarray: + """Initial amount of each dynamic species, in model substance units.""" + v = self._env0[self._dyn_env] + return np.where(self._dyn_conc, v * self.sizes(), v) + + def _env(self, amounts, t) -> np.ndarray: + env = self._env0.copy() + sizes = env[self._dyn_size_ix] + env[self._dyn_env] = np.where(self._dyn_conc, amounts / sizes, amounts) + for i, fn in self._rule_fns: + env[i] = fn(env, t) + return env + + def rates(self, amounts, t: float = 0.0) -> np.ndarray: + """Reaction rates (substance / time) at the given dynamic species amounts.""" + if self._missing_laws: + raise SBMLError(f"reactions without kinetic laws cannot be simulated: {self._missing_laws}") + env = self._env(np.asarray(amounts, dtype=float), t) + return np.array([fn(env, t) for fn in self._rate_fns], dtype=float) + + def amount_derivative(self, amounts, t: float = 0.0) -> np.ndarray: + return self._n @ self.rates(amounts, t) if len(self.reactions) else np.zeros(len(amounts)) + + def simulate(self, times, rtol=1e-10, atol=1e-12, method="LSODA", amounts0=None) -> dict: + """Integrate from t = times[0]. The integrated state is amount / size + (concentration-scaled) so tolerances are comparable across compartments.""" + from scipy.integrate import solve_ivp + + times = np.asarray(times, dtype=float) + sizes = self.sizes() + y0 = (self.initial_amounts() if amounts0 is None else np.asarray(amounts0, float)) / sizes + sol = solve_ivp(lambda t, y: self.amount_derivative(y * sizes, t) / sizes, + (times[0], times[-1]), y0, t_eval=times, method=method, rtol=rtol, atol=atol) + if not sol.success: + raise RuntimeError(f"integration failed: {sol.message}") + amounts = (sol.y.T * sizes) + conc = np.where(self._dyn_conc, amounts / sizes, amounts) + return {"time": sol.t, "species": self.dynamic_species, "amount": amounts, + "value": conc, "nfev": int(sol.nfev)} + + def _reduction(self): + """Exact conservation laws in RREF on amounts: x_P = T - M x_Q.""" + ids = self.dynamic_species + laws = S.conservation_laws(self.stoichiometry_matrix(ids)) + if not laws: + return [], [], list(range(len(ids))), np.zeros((0, len(ids))) + r, pivots = S.rref(laws) + free = [c for c in range(len(ids)) if c not in pivots] + return r, pivots, free, np.array([[float(x) for x in row] for row in r]) + + def jacobian(self, amounts, t: float = 0.0, rel_step=1e-7) -> np.ndarray: + """d(amount derivative)/d(amount) by central differences.""" + x = np.asarray(amounts, dtype=float) + scale = np.maximum(np.abs(x), self.sizes() * 1e-9) + j = np.empty((len(x), len(x))) + for k in range(len(x)): + h = rel_step * scale[k] + xp, xm = x.copy(), x.copy() + xp[k] += h + xm[k] -= h + j[:, k] = (self.amount_derivative(xp, t) - self.amount_derivative(xm, t)) / (2 * h) + return j + + def steady_state(self, amounts_guess=None, tol=1e-13) -> dict: + """Newton/hybrid solve of N v(x) = 0 on the conservation-reduced system. + + The conserved totals are fixed at those of ``amounts_guess`` (default: + the initial amounts), so the answer is the steady state of that + stoichiometric class, nearest the guess when several exist. + """ + from scipy.optimize import root + + x0 = self.initial_amounts() if amounts_guess is None else np.asarray(amounts_guess, float) + sizes = self.sizes() + _, pivots, free, lr = self._reduction() + totals = lr @ x0 if len(pivots) else np.zeros(0) + + def residual(y): + x = y * sizes + f = self.amount_derivative(x) / sizes + return np.concatenate([f[free], (lr @ x - totals) / np.maximum(np.abs(totals), 1e-300)]) + + sol = root(residual, x0 / sizes, method="hybr", tol=tol) + x = sol.x * sizes + f = self.amount_derivative(x) + return {"amount": x, "species": self.dynamic_species, "success": bool(sol.success), + "max_abs_derivative": float(np.max(np.abs(f / sizes))) if len(f) else 0.0, + "conservation_residual": float(np.max(np.abs(lr @ x - totals))) if len(pivots) else 0.0} + + def reduced_eigenvalues(self, amounts) -> np.ndarray: + """Eigenvalues of the Jacobian restricted to the stoichiometric class + (the conservation laws' zero modes removed via the link matrix).""" + j = self.jacobian(amounts) + _, pivots, free, lr = self._reduction() + link = np.zeros((len(amounts), len(free))) + for col, q in enumerate(free): + link[q, col] = 1.0 + for row, p in enumerate(pivots): + link[p, :] = -lr[row, free] + return np.linalg.eigvals(j[np.ix_(free, range(len(amounts)))] @ link) + + # --- graph --------------------------------------------------------------- + def to_graph(self) -> tuple[Graph, Schema]: + """Typed graph: compartments, species, reactions and exact conserved + moieties, with the schema and invariants in :func:`sbml_schema`.""" + g = Graph(self.id or "sbml") + env0 = self._env0 + for c in self.compartments.values(): + g.add_node(c.id, "compartment", "cell", c.name or c.id, size=float(env0[self._index[c.id]])) + x0 = dict(zip(self.dynamic_species, self.initial_amounts())) + for s in self.species.values(): + v = env0[self._index[s.id]] + amount = v if s.has_only_substance_units else v * env0[self._index[s.compartment]] + g.add_node(s.id, "species", "molecule", s.name or s.id, + compartment=s.compartment, initial_amount=float(x0.get(s.id, amount)), + boundary_condition=s.boundary_condition, constant=s.constant, + has_only_substance_units=s.has_only_substance_units, + assignment_rule=infix(self.rules[s.id]) if s.id in self.rules else None) + g.add_edge(s.id, s.compartment, "located_in") + for r in self.reactions.values(): + g.add_node(r.id, "reaction", "cell", r.name or r.id, reversible=r.reversible, + kinetic_law=None if r.rate is None else infix(r.rate), + local_parameters={k: float(v) for k, v in r.local_parameters.items()}) + key = f"sbml:{self.id}/{r.id}" + for sid, c in r.reactants: + g.add_edge(sid, r.id, "reactant", model=key, stoichiometry=str(c)) + for sid, c in r.products: + g.add_edge(r.id, sid, "product", model=key, stoichiometry=str(c)) + for sid in r.modifiers: + g.add_edge(sid, r.id, "modifier", model=key) + for k, law in enumerate(self.conservation_laws()): + total = sum(c * x0[s] for s, c in law.items()) + mid = f"moiety_{k + 1}" + g.add_node(mid, "moiety", "molecule", " + ".join( + (f"{c}*{s}" if c != 1 else s) for s, c in law.items()), total=float(total)) + for s, c in law.items(): + g.add_edge(s, mid, "member", coefficient=str(c)) + return g, sbml_schema() + + +def _topological(defs: dict[str, tuple], targets: set[str]) -> list[str]: + """Order definitions so each follows the targets it references.""" + deps = {t: symbols(e) & targets - {t} for t, e in defs.items()} + for t, e in defs.items(): + if t in symbols(e) and e[0] != "sym": + raise SBMLError(f"{t!r} is defined in terms of itself") + order, done, active = [], set(), set() + + def visit(t): + if t in done: + return + if t in active: + raise SBMLError(f"algebraic loop through {t!r}") + active.add(t) + for d in sorted(deps[t]): + visit(d) + active.discard(t) + done.add(t) + order.append(t) + + for t in defs: + visit(t) + return order + + +# --------------------------------------------------------------------------- +# reading +# --------------------------------------------------------------------------- +def _refuse_dtd(data: bytes) -> None: + """Refuse any DOCTYPE or entity declaration before the real parse. + + Expat decodes the document in whatever encoding it declares (UTF-8, + UTF-16 with or without a byte-order mark, Latin-1, ...), so the check + sees the declarations themselves. A scan of the raw bytes would not: in + UTF-16, `` SBMLModel: + """Read an SBML document from a path or bytes. A path's SHA-256 is recorded.""" + if isinstance(source, (bytes, bytearray)): + data, origin = bytes(source), None + else: + origin = Path(source) + data = origin.read_bytes() + _refuse_dtd(data) + root = ET.fromstring(data) + if _local(root.tag) != "sbml": + raise SBMLError("root element is not ") + ns = root.tag[1:].split("}")[0] if root.tag.startswith("{") else "" + level, version = int(root.attrib.get("level", 0)), int(root.attrib.get("version", 0)) + if (level, version) not in {(2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2)}: + raise UnsupportedSBML(f"SBML Level {level} Version {version}") + for attr, value in root.attrib.items(): + if _local(attr) == "required" and value == "true": + raise UnsupportedSBML(f"required SBML package ({attr})") + + def q(tag): + return f"{{{ns}}}{tag}" if ns else tag + + model = root.find(q("model")) + if model is None: + raise SBMLError("no ") + if level >= 3 and "conversionFactor" in model.attrib: + raise UnsupportedSBML("model conversionFactor") + for child in model: + name = _local(child.tag) + if name in _IGNORED or (name in _HANDLED and child.tag == q(name)): + continue + if len(child) == 0 and name.startswith("listOf"): + continue + raise UnsupportedSBML(f"model element <{name}>") + + def items(list_tag, item_tag): + lst = model.find(q(list_tag)) + if lst is None: + return [] + out = [] + for el in lst: + if _local(el.tag) in ("notes", "annotation"): + continue + if el.tag != q(item_tag): + raise UnsupportedSBML(f"<{_local(el.tag)}> in <{list_tag}>") + out.append(el) + return out + + def math_of(el, where): + m = el.find(f"{{{MATHML}}}math") + if m is None: + raise SBMLError(f"{where} has no MathML") + return parse_mathml(m) + + functions = {} + for fd in items("listOfFunctionDefinitions", "functionDefinition"): + m = fd.find(f"{{{MATHML}}}math") + if m is None: + raise SBMLError(f"function {fd.attrib.get('id')!r} has no MathML") + lam_el = [c for c in m if _local(c.tag) not in ("annotation", "annotation-xml")] + if len(lam_el) != 1 or _local(lam_el[0].tag) != "lambda": + raise SBMLError(f"function {fd.attrib.get('id')!r} is not a lambda") + kids = list(lam_el[0]) + params = [] + for k in kids[:-1]: + if _local(k.tag) != "bvar" or len(k) != 1: + raise SBMLError(f"function {fd.attrib.get('id')!r}: malformed ") + params.append("".join(k[0].itertext()).strip()) + functions[fd.attrib["id"]] = (tuple(params), parse_mathml(kids[-1])) + + compartments = {} + for c in items("listOfCompartments", "compartment"): + if not _bool(c, "constant", True if level < 3 else None, level): + raise UnsupportedSBML(f"non-constant compartment {c.attrib['id']!r}") + size = _float(c, "size") + compartments[c.attrib["id"]] = Compartment(c.attrib["id"], size, c.attrib.get("name", "")) + + species = {} + for s in items("listOfSpecies", "species"): + if "conversionFactor" in s.attrib: + raise UnsupportedSBML(f"species conversionFactor on {s.attrib['id']!r}") + amount, conc = _float(s, "initialAmount"), _float(s, "initialConcentration") + if amount is not None and conc is not None: + raise SBMLError(f"species {s.attrib['id']!r} has both initialAmount and initialConcentration") + initial = ("amount", amount) if amount is not None else ("concentration", conc) if conc is not None else None + species[s.attrib["id"]] = Species( + s.attrib["id"], s.attrib.get("compartment", ""), initial, + _bool(s, "hasOnlySubstanceUnits", False if level < 3 else None, level), + _bool(s, "boundaryCondition", False if level < 3 else None, level), + _bool(s, "constant", False if level < 3 else None, level), + s.attrib.get("name", "")) + + parameters = {} + for p in items("listOfParameters", "parameter"): + parameters[p.attrib["id"]] = (_float(p, "value"), _bool(p, "constant", True if level < 3 else None, level)) + + initial_assignments = {} + for ia in items("listOfInitialAssignments", "initialAssignment"): + initial_assignments[ia.attrib["symbol"]] = _inline(math_of(ia, "initialAssignment"), functions) + + rules = {} + lst = model.find(q("listOfRules")) + for rule in (lst if lst is not None else []): + kind = _local(rule.tag) + if kind in ("notes", "annotation"): + continue + if kind != "assignmentRule": + raise UnsupportedSBML(f"<{kind}>") + var = rule.attrib["variable"] + if var in rules: + raise SBMLError(f"two assignment rules for {var!r}") + rules[var] = _inline(math_of(rule, f"rule for {var!r}"), functions) + + reactions = {} + for r in items("listOfReactions", "reaction"): + rid = r.attrib["id"] + if _bool(r, "fast", False if (level < 3 or version >= 2) else None, level): + raise UnsupportedSBML(f"fast reaction {rid!r}") + def refs(tag, item): + lst = r.find(q(tag)) + out = [] + for el in (lst if lst is not None else []): + if _local(el.tag) in ("notes", "annotation"): + continue + if el.tag != q(item): + raise UnsupportedSBML(f"<{_local(el.tag)}> in <{tag}>") + out.append(el) + return out + + reactants = tuple((x.attrib["species"], _stoichiometry(x, level)) + for x in refs("listOfReactants", "speciesReference")) + products = tuple((x.attrib["species"], _stoichiometry(x, level)) + for x in refs("listOfProducts", "speciesReference")) + modifiers = tuple(x.attrib["species"] for x in refs("listOfModifiers", "modifierSpeciesReference")) + kl = r.find(q("kineticLaw")) + rate, local = None, {} + if kl is not None: + for tag, item in (("listOfParameters", "parameter"), ("listOfLocalParameters", "localParameter")): + lst = kl.find(q(tag)) + for p in (lst if lst is not None else []): + if _local(p.tag) in ("notes", "annotation"): + continue + if p.tag != q(item): + raise UnsupportedSBML(f"<{_local(p.tag)}> in kinetic law of {rid!r}") + v = _float(p, "value") + if v is None: + raise SBMLError(f"local parameter {p.attrib['id']!r} of {rid!r} has no value") + local[p.attrib["id"]] = v + rate = _inline(math_of(kl, f"kinetic law of {rid!r}"), functions) + reactions[rid] = Reaction(rid, reactants, products, modifiers, rate, local, + _bool(r, "reversible", True if level < 3 else None, level), + r.attrib.get("name", "")) + + src = {"sha256": hashlib.sha256(data).hexdigest()} + if origin is not None: + src["path"] = str(origin) + return SBMLModel(id=model.attrib.get("id", ""), name=model.attrib.get("name", ""), + level=level, version=version, compartments=compartments, species=species, + parameters=parameters, functions=functions, + initial_assignments=initial_assignments, rules=rules, + reactions=reactions, source=src) + + +# --------------------------------------------------------------------------- +# schema and invariants for an SBML-derived graph +# --------------------------------------------------------------------------- +def _graph_stoichiometry(g: Graph, dynamic_only: bool = True): + """N recomputed from graph edges alone (independent of SBMLModel): rows are + the dynamic species, or with ``dynamic_only=False`` every reacting species.""" + if dynamic_only: + dyn = [n.id for n in g.nodes_of_type("species") + if not n.attrs.get("boundary_condition") and not n.attrs.get("constant") + and n.attrs.get("assignment_rule") is None] + else: + used = {e.src for e in g.edges_of_type("reactant")} | {e.dst for e in g.edges_of_type("product")} + dyn = [n.id for n in g.nodes_of_type("species") if n.id in used] + rx = [n.id for n in g.nodes_of_type("reaction")] + row, col = {s: i for i, s in enumerate(dyn)}, {r: j for j, r in enumerate(rx)} + n = [[Fraction(0)] * len(rx) for _ in dyn] + for e in g.edges_of_type("reactant"): + if e.src in row: + n[row[e.src]][col[e.dst]] -= Fraction(e.attrs["stoichiometry"]) + for e in g.edges_of_type("product"): + if e.dst in row: + n[row[e.dst]][col[e.src]] += Fraction(e.attrs["stoichiometry"]) + return dyn, rx, n + + +def sbml_schema() -> Schema: + schema = Schema( + node_types={"compartment": {"size"}, "species": {"compartment", "initial_amount", "boundary_condition"}, + "reaction": {"reversible"}, "moiety": {"total"}}, + edge_rules=[ + EdgeRule("reactant", {"species"}, {"reaction"}, {"stoichiometry"}), + EdgeRule("product", {"reaction"}, {"species"}, {"stoichiometry"}), + EdgeRule("modifier", {"species"}, {"reaction"}), + EdgeRule("located_in", {"species"}, {"compartment"}), + EdgeRule("member", {"species"}, {"moiety"}, {"coefficient"}), + ]) + + @schema.invariant("stoichiometry") + def _stoich(g: Graph) -> list[str]: + out = [] + for e in g.edges_of_type("reactant", "product"): + try: + c = Fraction(str(e.attrs.get("stoichiometry"))) + ok = c > 0 + except (TypeError, ValueError, ZeroDivisionError): + ok = False + if not ok: + out.append(f"edge {e.key}: stoichiometry must be a positive exact rational") + return out + + @schema.invariant("located") + def _located(g: Graph) -> list[str]: + return [f"species {n.id}: needs exactly one compartment" + for n in g.nodes_of_type("species") if len(g.out_edges(n.id, ("located_in",))) != 1] + + @schema.invariant("conservation") + def _conservation(g: Graph) -> list[str]: + """Each moiety node must be an exact left-null vector of N, the moieties + must be independent and span the whole left nullspace, and each total + must equal the initial amounts it weights.""" + try: + dyn, _, n = _graph_stoichiometry(g) + except (KeyError, ValueError, ZeroDivisionError) as exc: + return [f"cannot rebuild stoichiometry: {exc}"] + out, laws = [], [] + idx = {s: i for i, s in enumerate(dyn)} + for m in g.nodes_of_type("moiety"): + law = [Fraction(0)] * len(dyn) + for e in g.in_edges(m.id, ("member",)): + if e.src not in idx: + out.append(f"{m.id}: member {e.src} is not a dynamic species") + continue + law[idx[e.src]] = Fraction(e.attrs["coefficient"]) + if S.conservation_residual([law], n) != 0: + out.append(f"{m.id}: not conserved by every reaction (l.N != 0)") + total = sum(float(c) * g.nodes[s].attrs["initial_amount"] for s, c in zip(dyn, law) if c) + if not math.isclose(total, m.attrs["total"], rel_tol=1e-12, abs_tol=1e-300): + out.append(f"{m.id}: total {m.attrs['total']} != weighted initial amounts {total}") + laws.append(law) + expected = len(dyn) - S.rank(n) if n and n[0] else len(dyn) + if laws and S.rank(laws) != len(laws): + out.append("moieties are linearly dependent") + if len(laws) != expected: + out.append(f"{len(laws)} moieties recorded, but the stoichiometry has {expected} " + "independent conservation laws") + return out + + @schema.invariant("stoichiometric-consistency") + def _consistency(g: Graph) -> list[str]: + """Every dynamic species must admit a positive mass conserved by all + internal reactions (Gevorgyan et al. 2008).""" + dyn, rx, n = _graph_stoichiometry(g, dynamic_only=False) + fixed = {v.id for v in g.nodes_of_type("species") + if v.attrs.get("boundary_condition") or v.attrs.get("constant")} + internal = [any(e.src not in fixed for e in g.in_edges(r, ("reactant",))) + and any(e.dst not in fixed for e in g.out_edges(r, ("product",))) for r in rx] + res = S.stoichiometric_consistency(n, internal) + out = [] + if res["unconserved"]: + names = [dyn[i] for i in res["unconserved"]] + leak = res["leak_combination"] + how = ("exact certificate: net production by " + ", ".join( + f"{v}*{rx[j]}" for j, v in zip(res["internal_reactions"], leak) if v) + if leak else "LP only; no exact certificate") + out.append(f"species {names} cannot carry a positive conserved mass ({how})") + elif not res["certified"]: + out.append("consistency found by LP but no exact mass vector could be certified") + return out + + return schema diff --git a/vh/graph/stoichiometry.py b/vh/graph/stoichiometry.py new file mode 100644 index 0000000..1847175 --- /dev/null +++ b/vh/graph/stoichiometry.py @@ -0,0 +1,259 @@ +"""Exact stoichiometric analysis: conservation laws and stoichiometric consistency. + +Stoichiometric coefficients are exact rationals (``fractions.Fraction``), so the +linear algebra here has no rounding: a conservation law ``l`` is accepted only if +``l . N`` is exactly zero, and the number of laws is exactly ``n - rank(N)``. + +Stoichiometric consistency (Gevorgyan, Poolman & Fell, Bioinformatics 24:2245, +2008) asks whether every species can be given a strictly positive mass such that +every internal reaction conserves mass. It is a linear program; the LP is solved +in floating point (SciPy/HiGHS), then each answer is turned into an exact +rational certificate and checked exactly: + + - a conserved species gets a nonnegative mass vector ``m`` with + ``m^T N_internal = 0`` exactly and ``m_i > 0``; + - an unconserved species gets a reaction combination ``v`` with + ``N_internal v >= 0`` exactly and ``(N_internal v)_i > 0``. For any + nonnegative ``m`` with ``m^T N_internal = 0``, ``0 = m^T N v >= m_i (N v)_i``, + so ``m_i = 0``: no positive mass exists (Farkas' lemma). + +If rounding prevents an exact certificate, the result says so instead of +reporting the floating-point answer as proven. +""" + +from __future__ import annotations + +from fractions import Fraction +from math import gcd, lcm +from numbers import Rational + +Matrix = list[list[Fraction]] + + +def as_fraction(value) -> Fraction: + """Exact rational from an int, Fraction or decimal string; floats are rejected + because their binary value is rarely the coefficient the author meant.""" + if isinstance(value, bool): + raise TypeError("a boolean is not a stoichiometric coefficient") + if isinstance(value, (Rational, str)): + return Fraction(value) + raise TypeError(f"exact rational required, got {type(value).__name__}") + + +def _matrix(rows) -> Matrix: + out = [[as_fraction(x) for x in row] for row in rows] + if out and any(len(r) != len(out[0]) for r in out): + raise ValueError("matrix rows must have equal length") + return out + + +def transpose(rows: Matrix, ncols: int | None = None) -> Matrix: + if not rows: + return [[] for _ in range(ncols or 0)] + return [list(col) for col in zip(*rows)] + + +def rref(rows) -> tuple[Matrix, list[int]]: + """Reduced row echelon form over the rationals, and its pivot columns.""" + a = [list(r) for r in _matrix(rows)] + if not a: + return [], [] + nrows, ncols = len(a), len(a[0]) + pivots: list[int] = [] + r = 0 + for c in range(ncols): + p = next((i for i in range(r, nrows) if a[i][c] != 0), None) + if p is None: + continue + a[r], a[p] = a[p], a[r] + inv = 1 / a[r][c] + a[r] = [x * inv for x in a[r]] + for i in range(nrows): + if i != r and a[i][c] != 0: + f = a[i][c] + a[i] = [x - f * y for x, y in zip(a[i], a[r])] + pivots.append(c) + r += 1 + if r == nrows: + break + return a[:r], pivots + + +def rank(rows) -> int: + return len(rref(rows)[1]) + + +def nullspace(rows, ncols: int | None = None) -> Matrix: + """Basis of {v : A v = 0} (one vector per free column of the RREF).""" + a = _matrix(rows) + n = len(a[0]) if a else (ncols or 0) + r, pivots = rref(a) + free = [c for c in range(n) if c not in pivots] + basis = [] + for f in free: + v = [Fraction(0)] * n + v[f] = Fraction(1) + for row, p in zip(r, pivots): + v[p] = -row[f] + basis.append(v) + return basis + + +def integer_row(row) -> list[int]: + """Scale a rational row to coprime integers with a positive first nonzero.""" + row = [as_fraction(x) for x in row] + den = lcm(*(x.denominator for x in row)) if row else 1 + ints = [int(x * den) for x in row] + g = gcd(*ints) if any(ints) else 1 + ints = [x // g for x in ints] + first = next((x for x in ints if x), 0) + return [-x for x in ints] if first < 0 else ints + + +def conservation_laws(stoichiometry) -> list[list[int]]: + """Canonical integer basis of the left nullspace of N (species x reactions). + + Each row ``l`` satisfies ``l . N = 0`` exactly, so ``sum_i l_i x_i`` is + constant along every trajectory of ``dx/dt = N v(x)``. The basis is the RREF + of the left nullspace (unique for the space), scaled to coprime integers, so + two implementations can be compared row for row. + """ + n = _matrix(stoichiometry) + nspecies = len(n) + nreactions = len(n[0]) if n else 0 + if nreactions == 0: + return [integer_row([int(i == j) for j in range(nspecies)]) for i in range(nspecies)] + left = nullspace(transpose(n), nspecies) + if not left: + return [] + canonical, _ = rref(left) + return [integer_row(r) for r in canonical] + + +def conservation_residual(laws, stoichiometry) -> Fraction: + """max |l . N_j| over laws and reactions, computed exactly (0 means proven).""" + n = _matrix(stoichiometry) + worst = Fraction(0) + for law in laws: + law = [as_fraction(x) for x in law] + for j in range(len(n[0]) if n else 0): + worst = max(worst, abs(sum(law[i] * n[i][j] for i in range(len(n))))) + return worst + + +def _matmul(a: Matrix, b: Matrix) -> Matrix: + return [[sum(x * y for x, y in zip(row, col)) for col in zip(*b)] for row in a] if b and b[0] else [[] for _ in a] + + +def _certify(b: Matrix, positive: list[int], max_rounds: int = 64): + """Exact y with w = B y >= 0 and w_i > 0 for every i in ``positive``. + + Solves an LP in floating point (maximise the number of positive entries + requested), rationalises the answer and checks it exactly. Entries that + the LP leaves numerically at zero are then constrained to be exactly zero + by restricting y to the exact nullspace of those rows, and the LP is + solved again; each round fixes at least one more row, so the loop ends. + Returns (y, w) as Fractions, or None when no exact certificate is found. + """ + from scipy.optimize import linprog + + nrows = len(b) + ncols = len(b[0]) if b else 0 + zero: set[int] = set() + for _ in range(max_rounds): + if zero: + k = nullspace([b[i] for i in sorted(zero)], ncols) + if not k: + return None + basis = transpose(k) # ncols x dim + else: + basis = [[Fraction(int(i == j)) for j in range(ncols)] for i in range(ncols)] + m = _matmul(b, basis) # nrows x dim + dim = len(basis[0]) if basis else 0 + free_rows = [i for i in range(nrows) if i not in zero] + want = [i for i in positive if i not in zero] + if len(want) < len(positive): + return None + mf = [[float(x) for x in m[i]] for i in range(nrows)] + # variables [y (dim, free), z (len(want), in [0,1])]: M y >= 0 on free rows; z_k <= (M y)_want_k + a_ub = [[-x for x in mf[i]] + [0.0] * len(want) for i in free_rows] + a_ub += [[-x for x in mf[i]] + [1.0 if c == k else 0.0 for c in range(len(want))] + for k, i in enumerate(want)] + lp = linprog(c=[0.0] * dim + [-1.0] * len(want), A_ub=a_ub or None, + b_ub=[0.0] * len(a_ub) or None, + bounds=[(None, None)] * dim + [(0, 1)] * len(want), method="highs") + if lp.status != 0: + return None + y = lp.x[:dim] + wf = [sum(mf[i][c] * y[c] for c in range(dim)) for i in range(nrows)] + scale = max((abs(x) for x in wf), default=0.0) or 1.0 + yq = [Fraction(float(v) / scale).limit_denominator(10**9) for v in y] + w = [sum(m[i][c] * yq[c] for c in range(dim)) for i in range(nrows)] + if all(x >= 0 for x in w) and all(w[i] > 0 for i in positive): + return [sum(basis[j][c] * yq[c] for c in range(dim)) for j in range(ncols)], w + tiny = {i for i in free_rows if i not in positive and abs(wf[i]) / scale < 1e-9} + if not tiny - zero: + return None + zero |= tiny + return None + + +def stoichiometric_consistency(stoichiometry, internal: list[bool] | None = None) -> dict: + """Which species can carry a strictly positive conserved mass? + + Rows of ``stoichiometry`` should be every species that takes part in a + reaction, including boundary or constant species: holding a species fixed + changes its dynamics, not its mass. ``internal[j]`` marks reactions that + should conserve mass; by default a reaction is internal when it has both a + consumed and a produced species (pure synthesis/degradation/exchange + reactions are open by construction). + + Returns ``consistent`` (every species conservable), the conserved and + unconserved species indices, the exact certificates described in the + module docstring, and ``certified`` (True only if every classification has + an exactly verified certificate). + """ + from scipy.optimize import linprog + + n = _matrix(stoichiometry) + ns = len(n) + nr = len(n[0]) if n else 0 + if internal is None: + internal = [any(n[i][j] < 0 for i in range(ns)) and any(n[i][j] > 0 for i in range(ns)) + for j in range(nr)] + cols = [j for j in range(nr) if internal[j]] + sub = [[n[i][j] for j in cols] for i in range(ns)] + result = {"internal_reactions": cols, "n_species": ns} + if ns == 0 or not cols: + return {**result, "consistent": True, "conserved": list(range(ns)), "unconserved": [], + "mass": [Fraction(1)] * ns, "leak_combination": [], "certified": True} + + # Classification LP: maximise the number of species with positive mass. + # variables [m (ns, >= 0), z (ns, in [0, 1])]; m^T N_int = 0; z <= m. + a_eq = [[float(sub[i][k]) for i in range(ns)] + [0.0] * ns for k in range(len(cols))] + a_ub = [[-1.0 if c == i else 0.0 for c in range(ns)] + [1.0 if c == i else 0.0 for c in range(ns)] + for i in range(ns)] + lp = linprog(c=[0.0] * ns + [-1.0] * ns, A_ub=a_ub, b_ub=[0.0] * ns, A_eq=a_eq, + b_eq=[0.0] * len(cols), bounds=[(0, None)] * ns + [(0, 1)] * ns, method="highs") + if lp.status != 0: + raise RuntimeError(f"consistency LP failed: {lp.message}") + conserved = [i for i in range(ns) if lp.x[ns + i] > 0.5] + unconserved = [i for i in range(ns) if i not in conserved] + + # Mass certificate: m = B c in the exact left nullspace of N_int, m >= 0, m_conserved > 0. + mass = None + left = nullspace(transpose(sub), ns) + if left and conserved: + cert = _certify(transpose(left), conserved) + if cert is not None: + mass = cert[1] + elif not conserved: + mass = [Fraction(0)] * ns + # Leak certificate: v with N_int v >= 0 and (N_int v)_unconserved > 0. + leak: list[Fraction] | None = [] + if unconserved: + cert = _certify(sub, unconserved) + leak = None if cert is None else cert[0] + return {**result, "consistent": not unconserved, "conserved": conserved, + "unconserved": unconserved, "mass": mass, "leak_combination": leak, + "certified": mass is not None and leak is not None} From ff2f5e5544a06ad798c48075e5ab03a46ba9280d Mon Sep 17 00:00:00 2001 From: ahrazzle <38987266+ahrazzle@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:49:50 -0600 Subject: [PATCH 11/12] Add explicit evidence bindings for nominal scalar experiments --- README.md | 2 +- .../2026-11-06-E-evidence-bindings/report.md | 88 +++++++++++ .../results.json | 113 ++++++++++++++ auto-research/README.md | 2 + docs/evidence_bindings.md | 56 +++++++ docs/model_contracts.md | 7 + scripts/validate_evidence_bindings.py | 73 +++++++++ tests/test_evidence_bindings.py | 145 ++++++++++++++++++ vh/graph/evidence.py | 110 +++++++++++++ 9 files changed, 595 insertions(+), 1 deletion(-) create mode 100644 auto-research/2026-11-06-E-evidence-bindings/report.md create mode 100644 auto-research/2026-11-06-E-evidence-bindings/results.json create mode 100644 docs/evidence_bindings.md create mode 100644 scripts/validate_evidence_bindings.py create mode 100644 tests/test_evidence_bindings.py create mode 100644 vh/graph/evidence.py diff --git a/README.md b/README.md index 6e41556..6f522e6 100644 --- a/README.md +++ b/README.md @@ -187,7 +187,7 @@ research tracks, and how to publish work under [`auto-research/`](auto-research/ - **Rohan Arun** ([@rohanarun](https://github.com/rohanarun)) — creator and maintainer; direction and design. - **Claude** (Anthropic) — implemented and validated the engines under the above direction, in pair with the maintainer. -- **OpenAI Codex** — graph interface contracts, clearance reference validation, and conserved reaction/intervention experiments, under the direction of [@ahrazzle](https://github.com/ahrazzle). +- **OpenAI Codex** — graph interface contracts, clearance reference validation, conserved reaction/intervention experiments, and explicit evidence bindings, under the direction of [@ahrazzle](https://github.com/ahrazzle). - **Claude** (Anthropic), Foundation-0 fork — SBML import with exact conservation and positive-mass consistency invariants. New contributors (human or agent): add yourself here in your pull request. See diff --git a/auto-research/2026-11-06-E-evidence-bindings/report.md b/auto-research/2026-11-06-E-evidence-bindings/report.md new file mode 100644 index 0000000..ea41e04 --- /dev/null +++ b/auto-research/2026-11-06-E-evidence-bindings/report.md @@ -0,0 +1,88 @@ +# Explicit evidence bindings for nominal scalar experiments + +- **Track:** E, reusable graph/model interfaces +- **Author:** gpt-forge (OpenAI Codex, Astra), under @ahrazzle's direction +- **Date:** 2026-11-06 +- **Branch:** `research/evidence-bindings-20261106` +- **Code:** `vh/graph/evidence.py`, `scripts/validate_evidence_bindings.py`, `tests/test_evidence_bindings.py` + +## Question + +Can a scalar experiment retain the evidence's complete context, source locator, +limits, and uncertainty while refusing unsupported inputs before model execution? +Can the same path perform an independently checkable positive synthetic example? + +## Method + +An opt-in immutable evidence record binds a fully specified Quantity to a +PortSpec. Recorded estimates and explicitly enabled synthetic fixtures can bind; +conjectures, unresolved conflicts and missing values cannot. Every supplied +quantity/unit/basis/context must match exactly. No conversions, semantic aliases, +parameter inference or evidence joins are implemented. The model registry checks +its own contract again before dispatch. Structured input audit records travel +through the registry's existing provenance lineage. + +Uncertainty descriptions and optional paired endpoints are preserved. They are +not sampled or propagated. Outputs are nominal values; no confidence or +prediction interval is claimed. Synthetic fixtures remain artificial. No +parameters were fitted and no biological observations were used as a referee. + +## Validation + +The independent mathematical authority is the exact rational identity relating +elimination rate, plasma concentration and clearance. Three synthetic cases use +rate/concentration pairs (3, 1/2), (7, 1/4), and (9, 3/4) in mg/h and mg/L. +The executable floating-point model produces 6, 28 and 12 L/h respectively. + +| Check | Result | Authority | Error / tolerance | +| --- | --- | --- | --- | +| Three nominal clearances | 6, 28, 12 L/h | Exact rational rate / concentration | Maximum 0 L/h; tolerance 1e-12 L/h | +| Missing kinetic inputs | Four refused | Checked-in ledger P015, P016, P019, P020 | All four lack estimates; software consistency check only | +| Interface tests | 32 new passing cases | Explicit boundary examples and exact arithmetic | No statistical accuracy claim | + +The arithmetic error has no statistical error bar: these are fixed synthetic +fixtures, not sampled observations. Source uncertainty remains attached to the +inputs. Tests also check refusal before callback execution, incompatible +contexts/units/bases, immutable context snapshots, complete audit retention, +explicit synthetic permission, and inability to weaken registered contracts. + +The CLI output in `results.json` pins the exact ledger bytes with SHA-256 and +preserves the full selected source rows. Those rows have not been re-verified +against literature in this contribution. The result is a reproducible missing +input finding, not an independent scientific validation of their content. + +## Limits + +A caller can mislabel an input or omit a relevant context field. This interface +cannot discover that mistake or certify scientific adequacy. It is opt-in and +does not prevent use of the underlying registry. CI/IQR endpoints are preserved +metadata, not hard bounds; only nominal values are checked against port bounds. +No output uncertainty or probability distribution is produced. Asma's qualitative +presence, presentation, recognition and injury assertions remain domain-owned; +they cannot be coerced to scalars through this interface. + +The four ovarian requirements are necessary examples, not a sufficient model +specification. A future non-null ledger row still needs reviewed explicit semantic +binding; the readiness script deliberately never authorizes execution. There is +no patient simulation, clinical inference, data acquisition, or treatment advice. +Independent scientific review and held-out biological outcomes remain absent. + +## Reproduce + +```bash +PYTHONPATH=. python3 scripts/validate_evidence_bindings.py +python3 -m pytest -q tests/test_evidence_bindings.py tests/test_model_contracts.py tests/test_reaction_experiments.py tests/test_ovarian_parameter_ledger.py -m 'not network' +node web/test_engines.mjs +``` + +Observed environment: Python 3.14.6, pytest 9.1.1, NumPy 2.5.4, SciPy 1.18.1. +Focused pre-serialization check: 129 passed, 1 network test deselected; final evidence-only suite: 32 passed. JavaScript engine checks +passed against checked-in fixtures, including worst plasma-profile relative error +4.8e-13. Final full local suite: 217 passed, 15 skipped, 1 network test deselected. Skips reflect unavailable OpenMM, PySCF and libRoadRunner; those independent-engine checks were not run. No dependency installation was performed. + +## References + +- Existing `vh/graph/contracts.py` interfaces and exact clearance identity tests. +- `data/clinical/ovarian_hgsoc_parameter_ledger.json`, unchanged source ledger. +- `docs/research-foundation.md` and `docs/research-question-template.md` for the + separation of evidence assertions, modeling assumptions and scientific validation. diff --git a/auto-research/2026-11-06-E-evidence-bindings/results.json b/auto-research/2026-11-06-E-evidence-bindings/results.json new file mode 100644 index 0000000..466a73d --- /dev/null +++ b/auto-research/2026-11-06-E-evidence-bindings/results.json @@ -0,0 +1,113 @@ +{ + "ledger_sha256": "37695eac4ed4c854b86c7e37a7e7324a462f69bf33c2c90fa2000db4955c0478", + "ovarian_readiness": { + "interpretation": "Readiness for these four necessary inputs only, not a complete model specification. KNOWN describes source access, not applicability; prevalence and hazard ratios are not kinetic rates.", + "ready": false, + "requirements": [ + { + "ledger_record": { + "citation": { + "doi": "10.1073/pnas.2026663118", + "first_author_surname": "Gu", + "title": "Computational modeling of ovarian cancer dynamics suggests optimal strategies for therapy and screening", + "year": 2021 + }, + "derivation": null, + "id": "P015", + "label": "MISSING", + "limits": "Gu et al. simulation parameters not copied into this ledger.", + "locator": "No single untreated HGSOC doubling time tabulated for ledger extraction", + "population": "Newly diagnosed HGSOC before systemic therapy", + "quantity": "Untreated high-grade serous ovarian cancer volumetric doubling time", + "range": null, + "units": null, + "value": null + }, + "ready": false, + "reason": "missing estimate", + "record_id": "P015", + "required_role": "tumor_growth" + }, + { + "ledger_record": { + "citation": { + "doi": "10.1016/j.jtbi.2006.02.001", + "first_author_surname": "Kohandel", + "title": "Mathematical modeling of ovarian cancer treatments: Sequencing of surgery and chemotherapy", + "year": 2006 + }, + "derivation": null, + "id": "P016", + "label": "MISSING", + "limits": "See P021 for qualitative prior art.", + "locator": "Model uses fixed-fraction surgery operator; no patient-derived numeric fraction", + "population": "Ovarian cancer patients with quantitative debulking fractions", + "quantity": "Proportional intraoperative tumor retention fraction used in sequencing models (empirical estimate)", + "range": null, + "units": null, + "value": null + }, + "ready": false, + "reason": "missing estimate", + "record_id": "P016", + "required_role": "surgical_retention" + }, + { + "ledger_record": { + "citation": { + "doi": "10.1073/pnas.2026663118", + "first_author_surname": "Gu", + "title": "Computational modeling of ovarian cancer dynamics suggests optimal strategies for therapy and screening", + "year": 2021 + }, + "derivation": null, + "id": "P019", + "label": "MISSING", + "limits": "Add when a model contract consumes PK parameters.", + "locator": "Not applicable: sequence experiments use dimensionless burden units", + "population": "Virtual-human ovarian treatment-sequence graph experiments", + "quantity": "Population carboplatin clearance for whole-body PBPK coupling in ovarian treatment-sequence models", + "range": null, + "units": null, + "value": null + }, + "ready": false, + "reason": "missing estimate", + "record_id": "P019", + "required_role": "carboplatin_clearance" + }, + { + "ledger_record": { + "citation": { + "doi": "10.1073/pnas.2026663118", + "first_author_surname": "Gu", + "title": "Computational modeling of ovarian cancer dynamics suggests optimal strategies for therapy and screening", + "year": 2021 + }, + "derivation": null, + "id": "P020", + "label": "MISSING", + "limits": "Add when a model contract consumes PK parameters.", + "locator": "Not applicable: scalar chemotherapy operators in sequence experiments", + "population": "Virtual-human ovarian treatment-sequence graph experiments", + "quantity": "Population paclitaxel central volume and clearance for sequence models", + "range": null, + "units": null, + "value": null + }, + "ready": false, + "reason": "missing estimate", + "record_id": "P020", + "required_role": "paclitaxel_volume_and_clearance" + } + ] + }, + "schema_version": 1, + "synthetic_validation": { + "cases": 3, + "interpretation": "Nominal synthetic arithmetic only; no output uncertainty or biological validation", + "maximum_absolute_error_L_per_h": 0.0, + "passed": true, + "tolerance_L_per_h": 1e-12 + } +} diff --git a/auto-research/README.md b/auto-research/README.md index 41d7577..6725884 100644 --- a/auto-research/README.md +++ b/auto-research/README.md @@ -27,3 +27,5 @@ 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: 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. diff --git a/docs/evidence_bindings.md b/docs/evidence_bindings.md new file mode 100644 index 0000000..708eca8 --- /dev/null +++ b/docs/evidence_bindings.md @@ -0,0 +1,56 @@ +# Evidence at an executable scalar boundary + +`vh.graph.evidence` adds an optional checked path from an explicitly quantified +record to `ModelRegistry`. It does not read papers, infer model parameters, or +certify an observation's truth or applicability. The original scalar registry +remains available; this is an opt-in interface, not a security enforcement layer. + +`EvidenceInput` holds a record ID, status, an optional `Quantity`, source, exact +locator, limits, and `Uncertainty`. The quantity retains its complete context, +quantity name, unit, reference basis, and prior provenance. These fields must be +chosen and reviewed by the caller. A `recorded` status means a recorded estimate, +not a validated model, causal effect, or clinical finding. + +- `recorded` estimates may bind when every `PortSpec` field and bound matches. +- `synthetic` estimates additionally require `allow_synthetic=True`. +- `conjecture`, `missing`, and `conflicting` records cannot bind. Missing and + conflicting records carry no selected point estimate. The caller must resolve + evidence outside this interface; changing a label alone is not validation. +- Qualitative assertions have no scalar representation here. Protein presence, + antigen presentation, receptor recognition, and neural injury cannot substitute + for one another. Asma owns those assertion distinctions and evidence rules. + +`execute_evidence(registry, edge, evidence, specs)` first binds every input and +then delegates to the registry, which independently rechecks the registered model +contract. Supplying weaker binding specifications cannot override that contract. +A rejected input never invokes the registered callback. As with the registry, +callbacks should be pure: output validation cannot undo callback side effects. + +The complete input audit is serialized under an `evidence:` provenance entry and +therefore accompanies every returned output through the registry's existing +lineage union. Returned values are nominal scenario outputs. The recorded input +uncertainty is not output uncertainty. A source CI, IQR, or unquantified range is +neither a probability distribution nor an asserted hard domain; there is no +sampling, independence assumption, interval propagation, or automatic conversion. + +## Reproduce a positive example and the current missing-input result + +```bash +PYTHONPATH=. python3 scripts/validate_evidence_bindings.py +python3 -m pytest -q tests/test_evidence_bindings.py +``` + +The script executes three explicitly artificial clearance scenarios, independently +checked against exact rational rate/concentration identities, and prints a +deterministic JSON report. It also records the exact ovarian ledger hash and the +complete rows for four necessary inputs: growth, surgical retention, carboplatin +clearance, and paclitaxel volume/clearance. All four are currently missing. This +list is not a complete disease-model specification. The readiness checker never +activates a model: a future numeric ledger entry still needs an explicit reviewed +semantic binding. Existing prevalence values and trial hazard ratios do not +supply those parameters. + +No source data were acquired or re-curated. The ledger's `KNOWN` label describes +its source-access convention and must not be translated into model validity. +The [research report](../auto-research/2026-11-06-E-evidence-bindings/report.md) +records the bounded software result and remaining validation work. diff --git a/docs/model_contracts.md b/docs/model_contracts.md index b9c03d7..6d282f2 100644 --- a/docs/model_contracts.md +++ b/docs/model_contracts.md @@ -71,3 +71,10 @@ of `Schema`; the registry dispatches the explicitly named model only. Callbacks should be pure functions: rejecting an invalid output cannot undo callback side effects. The registry is not a sandbox for untrusted Python. Contract and callable definitions remain outside serialized graph data. + +## Optional evidence bindings + +For recorded source locators, uncertainty metadata, missing/conflicting input refusal, +and explicitly enabled synthetic scenarios, see [evidence bindings](evidence_bindings.md). +This opt-in layer preserves input audit records; it does not certify scientific +applicability or infer output uncertainty. diff --git a/scripts/validate_evidence_bindings.py b/scripts/validate_evidence_bindings.py new file mode 100644 index 0000000..66f5040 --- /dev/null +++ b/scripts/validate_evidence_bindings.py @@ -0,0 +1,73 @@ +"""Offline nominal synthetic mass balance and ovarian kinetic-input readiness. + +No ledger value is converted, imported into a model, or scientifically validated. +""" +from __future__ import annotations +import hashlib +import json +from pathlib import Path +from fractions import Fraction + +from vh.graph import Edge, ModelRegistry, ModelSpec, PortSpec, Quantity +from vh.graph.evidence import EvidenceInput, Uncertainty, execute_evidence + +ROOT = Path(__file__).resolve().parents[1] + + +def synthetic_check(): + context = {"system": "artificial mass-balance fixture"} + specs = {"rate": PortSpec("elimination_rate", "mg/h", "eliminated", context, minimum=0), + "concentration": PortSpec("concentration", "mg/L", "plasma", context, minimum=0.01)} + output = PortSpec("clearance", "L/h", "plasma", context, minimum=0) + def quantity(value, spec): + return Quantity(value, spec.quantity, spec.unit, spec.basis, spec.context, ("artificial fixture",)) + registry = ModelRegistry() + registry.register(ModelSpec("synthetic.clearance", specs, {"clearance": output}, + lambda values: {"clearance": quantity(values["rate"].value / values["concentration"].value, output)}, + "Artificial scalar mass balance only", "Exact rational rate/concentration identity", + ("synthetic definition",))) + errors = [] + for rate, concentration in ((3, Fraction(1, 2)), (7, Fraction(1, 4)), (9, Fraction(3, 4))): + records = {name: EvidenceInput(name, "synthetic", quantity(float(value), specs[name]), + "synthetic fixture", "validate_evidence_bindings.py:synthetic_check", "Not a biological measurement", + Uncertainty("not_quantified", "Fixed artificial input; no sampling interpretation")) + for name, value in (("rate", rate), ("concentration", concentration))} + result = execute_evidence(registry, Edge("a", "b", "converts", model="synthetic.clearance"), + records, specs, allow_synthetic=True)["clearance"] + errors.append(abs(result.value - float(Fraction(rate) / concentration))) + return {"cases": len(errors), "maximum_absolute_error_L_per_h": max(errors), + "tolerance_L_per_h": 1e-12, "passed": max(errors) <= 1e-12, + "interpretation": "Nominal synthetic arithmetic only; no output uncertainty or biological validation"} + + +def readiness(ledger): + entries = ledger["entries"] + by_id = {row["id"]: row for row in entries} + if len(by_id) != len(entries): + raise ValueError("duplicate ledger IDs") + required = {"P015": "tumor_growth", "P016": "surgical_retention", "P019": "carboplatin_clearance", + "P020": "paclitaxel_volume_and_clearance"} + rows = [] + for identifier, role in required.items(): + row = by_id.get(identifier) + rows.append({"record_id": identifier, "required_role": role, "ready": False, + "reason": "record absent" if row is None else ( + "missing estimate" if row["label"] == "MISSING" or row["value"] is None else + "explicit reviewed quantity/unit/basis/context binding required"), + "ledger_record": row}) + return {"ready": False, "requirements": rows, + "interpretation": "Readiness for these four necessary inputs only, not a complete model specification. " + "KNOWN describes source access, not applicability; prevalence and hazard ratios are not kinetic rates."} + + +def main(): + path = ROOT / "data/clinical/ovarian_hgsoc_parameter_ledger.json" + content = path.read_bytes() + result = {"schema_version": 1, "ledger_sha256": hashlib.sha256(content).hexdigest(), + "synthetic_validation": synthetic_check(), "ovarian_readiness": readiness(json.loads(content))} + print(json.dumps(result, indent=2, sort_keys=True, allow_nan=False)) + return 0 if result["synthetic_validation"]["passed"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_evidence_bindings.py b/tests/test_evidence_bindings.py new file mode 100644 index 0000000..f8bec55 --- /dev/null +++ b/tests/test_evidence_bindings.py @@ -0,0 +1,145 @@ +"""Boundary checks and exact synthetic arithmetic; no biological validation.""" +from dataclasses import replace +from fractions import Fraction +import json +import runpy +from pathlib import Path + +import pytest + +from vh.graph import ContractError, Edge, ModelRegistry, ModelSpec, PortSpec, Quantity +from vh.graph.evidence import EvidenceInput, Uncertainty, execute_evidence + +SPEC = PortSpec("concentration", "mol/L", "free", {"system": "synthetic"}, minimum=0) +EDGE = Edge("a", "b", "converts", model="identity") + + +def record(status="recorded"): + return EvidenceInput("fixture-1", status, + Quantity(2.0, SPEC.quantity, SPEC.unit, SPEC.basis, SPEC.context, ("fixture",)), + "artificial source", "table 1, row 1", "No biological validity", + Uncertainty("CI95", "Artificial confidence interval, not a distribution", 1.0, 3.0)) + + +def registry(): + calls = [] + def compute(values): + calls.append(values) + return {"out": values["in"]} + result = ModelRegistry() + result.register(ModelSpec("identity", {"in": SPEC}, {"out": SPEC}, compute, + "synthetic", "identity", ("synthetic identity",))) + return result, calls + + +def test_complete_audit_survives_execution_and_original_context_mutation(): + source_context = {"system": "synthetic"} + evidence = replace(record(), estimate=replace(record().estimate, context=source_context)) + source_context["system"] = "changed" + models, calls = registry() + result = execute_evidence(models, EDGE, {"in": evidence}, {"in": SPEC})["out"] + audit = json.loads(next(s[len("evidence:"):] for s in result.provenance if s.startswith("evidence:"))) + assert audit == evidence.audit() + assert audit["uncertainty"]["kind"] == "CI95" + assert audit["estimate"]["context"] == {"system": "synthetic"} + assert result.value == 2.0 + assert len(calls) == 1 + + +@pytest.mark.parametrize("status", ["conjecture", "synthetic", "missing", "conflicting"]) +def test_unsupported_status_never_calls_model(status): + item = record() if status not in ("missing", "conflicting") else replace(record(), status=status, estimate=None) + item = replace(item, status=status) + models, calls = registry() + with pytest.raises(ContractError, match="cannot bind"): + execute_evidence(models, EDGE, {"in": item}, {"in": SPEC}) + assert calls == [] + + +def test_synthetic_permission_is_explicit_and_does_not_allow_conjecture(): + assert record("synthetic").bind(SPEC, allow_synthetic=True).value == 2 + with pytest.raises(ContractError): + record("conjecture").bind(SPEC, allow_synthetic=True) + with pytest.raises(ContractError): + record("synthetic").bind(SPEC, allow_synthetic="yes") + + +@pytest.mark.parametrize("field,value", [("quantity", "hazard_ratio"), ("unit", "mg/L"), + ("basis", "total"), ("context", {"system": "human"}), ("value", -1)]) +def test_wrong_semantics_never_calls_model(field, value): + evidence = replace(record(), estimate=replace(record().estimate, **{field: value})) + models, calls = registry() + with pytest.raises(ContractError): + execute_evidence(models, EDGE, {"in": evidence}, {"in": SPEC}) + assert calls == [] + + +def test_registered_specs_cannot_be_overridden_by_binding_specs(): + other = replace(SPEC, basis="total") + evidence = replace(record(), estimate=replace(record().estimate, basis="total")) + models, calls = registry() + with pytest.raises(ContractError, match="basis mismatch"): + execute_evidence(models, EDGE, {"in": evidence}, {"in": other}) + assert calls == [] + + +@pytest.mark.parametrize("change", [{"status": "unknown"}, {"estimate": None}, {"source": ""}, + {"locator": ""}, {"limits": ""}, {"uncertainty": None}, {"estimate": 2}, + {"status": "missing"}, {"status": "conflicting"}]) +def test_malformed_evidence_rejected(change): + with pytest.raises(ContractError): + replace(record(), **change) + + +@pytest.mark.parametrize("low,high", [(1, None), (None, 2), (3, 1), (True, 2), (1, float("inf")), + (float("nan"), 3)]) +def test_malformed_uncertainty_rejected(low, high): + with pytest.raises(ContractError): + Uncertainty("CI95", "reported interval", low, high) + + +def test_uncertainty_is_retained_not_used_as_input_bounds(): + # A CI is not a hard range: execution checks the nominal value only. + assert replace(record(), uncertainty=Uncertainty("CI95", "source CI", -1, 3)).bind(SPEC).value == 2 + + +def test_missing_extra_and_untyped_ports_rejected_before_dispatch(): + models, calls = registry() + for data in ({}, {"in": record(), "extra": record()}, {"in": 2}): + with pytest.raises(ContractError): + execute_evidence(models, EDGE, data, {"in": SPEC}) + assert calls == [] + + +def test_synthetic_end_to_end_against_exact_rational_identity(): + script = runpy.run_path(str(Path(__file__).parents[1] / "scripts/validate_evidence_bindings.py")) + result = script["synthetic_check"]() + assert result["cases"] == 3 + assert result["maximum_absolute_error_L_per_h"] == 0 + assert result["passed"] + + +def test_actual_ledger_cannot_supply_kinetic_inputs(): + root = Path(__file__).parents[1] + script = runpy.run_path(str(root / "scripts/validate_evidence_bindings.py")) + ledger = json.loads((root / "data/clinical/ovarian_hgsoc_parameter_ledger.json").read_text()) + result = script["readiness"](ledger) + assert not result["ready"] + assert len(result["requirements"]) == 4 + assert all(r["reason"] == "missing estimate" for r in result["requirements"]) + # A newly filled row still needs explicit semantic binding; merely changing + # its label/value cannot authorize a simulation. + row = next(r for r in ledger["entries"] if r["id"] == "P015") + row.update(label="KNOWN", value=10) + updated = script["readiness"](ledger) + assert updated["requirements"][0]["reason"] == "explicit reviewed quantity/unit/basis/context binding required" + assert not updated["ready"] + + +def test_finite_real_scalars_have_serializable_audits(): + item = replace(record(), estimate=replace(record().estimate, value=Fraction(1, 2)), + uncertainty=Uncertainty("bounds", "artificial", Fraction(1, 4), Fraction(3, 4))) + bound = item.bind(SPEC) + assert bound.value == Fraction(1, 2) + assert item.audit()["estimate"]["value"] == 0.5 + assert item.audit()["uncertainty"]["low"] == 0.25 diff --git a/vh/graph/evidence.py b/vh/graph/evidence.py new file mode 100644 index 0000000..6cb04f2 --- /dev/null +++ b/vh/graph/evidence.py @@ -0,0 +1,110 @@ +"""Opt-in evidence bindings for scalar models, without scientific certification. + +A recorded estimate is not a validated model parameter. Callers must supply the +complete applicable semantics; no source parsing or conversions happen here. +Uncertainty metadata accompanies nominal execution, never becomes a distribution +or an output confidence interval. Missing/conflicting assertions cannot execute. +""" +from __future__ import annotations + +from dataclasses import dataclass +import json +from types import MappingProxyType +from collections.abc import Mapping + +from .contracts import ContractError, ModelRegistry, PortSpec, Quantity, _text, _finite +from .core import Edge + + +@dataclass(frozen=True) +class Uncertainty: + """Source-reported interval or explicit lack of quantification. + + CI, IQR and bounds retain their meaning; none implies a sampling distribution. + Endpoints share the estimate's units and basis. No interval propagation occurs. + """ + kind: str + description: str + low: float | None = None + high: float | None = None + + def __post_init__(self): + _text(self.kind, "uncertainty kind") + _text(self.description, "uncertainty description") + if (self.low is None) != (self.high is None): + raise ContractError("uncertainty requires both endpoints or neither") + if self.low is not None: + _finite(self.low, "uncertainty low") + _finite(self.high, "uncertainty high") + if self.low > self.high: + raise ContractError("uncertainty endpoints are reversed") + + +@dataclass(frozen=True) +class EvidenceInput: + record_id: str + status: str + estimate: Quantity | None + source: str + locator: str + limits: str + uncertainty: Uncertainty + + def __post_init__(self): + for name in ("record_id", "source", "locator", "limits"): + _text(getattr(self, name), name) + if self.status not in ("recorded", "synthetic", "conjecture", "missing", "conflicting"): + raise ContractError("unknown evidence status") + if self.estimate is not None and not isinstance(self.estimate, Quantity): + raise ContractError("estimate must be a Quantity or absent") + if self.status in ("recorded", "synthetic", "conjecture") and self.estimate is None: + raise ContractError("numeric evidence status requires an estimate") + if self.status in ("missing", "conflicting") and self.estimate is not None: + raise ContractError("missing/conflicting evidence must not select an estimate") + if not isinstance(self.uncertainty, Uncertainty): + raise ContractError("uncertainty must be explicit") + + def audit(self) -> dict: + q = self.estimate + return {"record_id": self.record_id, "status": self.status, "source": self.source, + "locator": self.locator, "limits": self.limits, + "uncertainty": {"kind": self.uncertainty.kind, "description": self.uncertainty.description, + "low": None if self.uncertainty.low is None else float(self.uncertainty.low), + "high": None if self.uncertainty.high is None else float(self.uncertainty.high)}, + "estimate": None if q is None else {"value": float(q.value), "quantity": q.quantity, + "unit": q.unit, "basis": q.basis, "context": dict(q.context), + "provenance": list(q.provenance)}} + + def bind(self, spec: PortSpec, *, allow_synthetic: bool = False) -> Quantity: + if not isinstance(allow_synthetic, bool): + raise ContractError("allow_synthetic must be boolean") + if self.status != "recorded" and not (self.status == "synthetic" and allow_synthetic): + raise ContractError(f"{self.record_id}: evidence status {self.status!r} cannot bind") + if not isinstance(spec, PortSpec): + raise ContractError("binding requires a PortSpec") + spec.check(self.estimate, self.record_id) + q = self.estimate + # Structured audit survives ModelRegistry's existing provenance union. + audit = "evidence:" + json.dumps(self.audit(), sort_keys=True, separators=(",", ":"), allow_nan=False) + return Quantity(q.value, q.quantity, q.unit, q.basis, q.context, (*q.provenance, audit)) + + +def execute_evidence(registry: ModelRegistry, edge: Edge, + evidence: Mapping[str, EvidenceInput], specs: Mapping[str, PortSpec], *, + allow_synthetic: bool = False) -> dict[str, Quantity]: + """Validate every binding before dispatch; preserve full evidence in lineage. + + Specs are explicit binding requirements, independently rechecked against the + registered model by ModelRegistry. This is opt-in and not a security boundary. + Returned values are nominal scenario outputs, with no inferred uncertainty. + """ + if not isinstance(evidence, Mapping) or not isinstance(specs, Mapping): + raise ContractError("evidence and specs must be mappings") + 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") + bound = {name: record.bind(ports[name], allow_synthetic=allow_synthetic) + for name, record in records.items()} + return registry.execute(edge, MappingProxyType(bound)) From a76be7540fc8afba4599b516ce18020d45d00c16 Mon Sep 17 00:00:00 2001 From: ahrazzle <38987266+ahrazzle@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:51:23 -0600 Subject: [PATCH 12/12] Preserve exact scalar values in evidence audit lineage --- .../2026-11-06-E-evidence-bindings/report.md | 12 ++++++++--- docs/evidence_bindings.md | 5 +++++ tests/test_evidence_bindings.py | 18 +++++++++++++++-- vh/graph/evidence.py | 20 ++++++++++++++++--- 4 files changed, 47 insertions(+), 8 deletions(-) diff --git a/auto-research/2026-11-06-E-evidence-bindings/report.md b/auto-research/2026-11-06-E-evidence-bindings/report.md index ea41e04..c583ef0 100644 --- a/auto-research/2026-11-06-E-evidence-bindings/report.md +++ b/auto-research/2026-11-06-E-evidence-bindings/report.md @@ -38,7 +38,7 @@ The executable floating-point model produces 6, 28 and 12 L/h respectively. | --- | --- | --- | --- | | Three nominal clearances | 6, 28, 12 L/h | Exact rational rate / concentration | Maximum 0 L/h; tolerance 1e-12 L/h | | Missing kinetic inputs | Four refused | Checked-in ledger P015, P016, P019, P020 | All four lack estimates; software consistency check only | -| Interface tests | 32 new passing cases | Explicit boundary examples and exact arithmetic | No statistical accuracy claim | +| Interface tests | 33 new passing cases | Explicit boundary examples and exact arithmetic | No statistical accuracy claim | The arithmetic error has no statistical error bar: these are fixed synthetic fixtures, not sampled observations. Source uncertainty remains attached to the @@ -76,9 +76,9 @@ node web/test_engines.mjs ``` Observed environment: Python 3.14.6, pytest 9.1.1, NumPy 2.5.4, SciPy 1.18.1. -Focused pre-serialization check: 129 passed, 1 network test deselected; final evidence-only suite: 32 passed. JavaScript engine checks +Focused pre-serialization check: 129 passed, 1 network test deselected; evidence-only suite before independent-review correction: 32 passed. JavaScript engine checks passed against checked-in fixtures, including worst plasma-profile relative error -4.8e-13. Final full local suite: 217 passed, 15 skipped, 1 network test deselected. Skips reflect unavailable OpenMM, PySCF and libRoadRunner; those independent-engine checks were not run. No dependency installation was performed. +4.8e-13. Final full local suite: 218 passed, 15 skipped, 1 network test deselected. Skips reflect unavailable OpenMM, PySCF and libRoadRunner; those independent-engine checks were not run. No dependency installation was performed. ## References @@ -86,3 +86,9 @@ passed against checked-in fixtures, including worst plasma-profile relative erro - `data/clinical/ovarian_hgsoc_parameter_ledger.json`, unchanged source ledger. - `docs/research-foundation.md` and `docs/research-question-template.md` for the separation of evidence assertions, modeling assumptions and scientific validation. + +Independent software review found an audit precision defect for large integers. +The correction preserves JSON integers and tagged exact rationals and rejects +other non-lossless representations before dispatch. A large-integer regression +verifies the executed value and recorded endpoints agree exactly. Final suite +after this correction: 218 passed, 15 skipped, 1 network test deselected. diff --git a/docs/evidence_bindings.md b/docs/evidence_bindings.md index 708eca8..0d93b10 100644 --- a/docs/evidence_bindings.md +++ b/docs/evidence_bindings.md @@ -26,6 +26,11 @@ contract. Supplying weaker binding specifications cannot override that contract. A rejected input never invokes the registered callback. As with the registry, callbacks should be pure: output validation cannot undo callback side effects. +Integer audit values retain exact JSON integers; rational values retain tagged +numerator/denominator pairs. Other real scalar values must convert losslessly to +a JSON float or binding fails before execution. Consumers must preserve these +representations when decoding the audit. + The complete input audit is serialized under an `evidence:` provenance entry and therefore accompanies every returned output through the registry's existing lineage union. Returned values are nominal scenario outputs. The recorded input diff --git a/tests/test_evidence_bindings.py b/tests/test_evidence_bindings.py index f8bec55..d60f63c 100644 --- a/tests/test_evidence_bindings.py +++ b/tests/test_evidence_bindings.py @@ -141,5 +141,19 @@ def test_finite_real_scalars_have_serializable_audits(): uncertainty=Uncertainty("bounds", "artificial", Fraction(1, 4), Fraction(3, 4))) bound = item.bind(SPEC) assert bound.value == Fraction(1, 2) - assert item.audit()["estimate"]["value"] == 0.5 - assert item.audit()["uncertainty"]["low"] == 0.25 + assert item.audit()["estimate"]["value"] == {"representation": "rational", "numerator": 1, "denominator": 2} + assert item.audit()["uncertainty"]["low"] == {"representation": "rational", "numerator": 1, "denominator": 4} + + +def test_audit_retains_large_integer_estimate_and_bounds_exactly(): + value = 2**53 + 1 + item = replace(record(), estimate=replace(record().estimate, value=value), + uncertainty=Uncertainty("bounds", "artificial exact integers", value, value + 2)) + models, calls = registry() + result = execute_evidence(models, EDGE, {"in": item}, {"in": SPEC})["out"] + audit = json.loads(next(s[len("evidence:"):] for s in result.provenance if s.startswith("evidence:"))) + assert audit["estimate"]["value"] == value == result.value + assert audit["uncertainty"]["low"] == value + assert audit["uncertainty"]["high"] == value + 2 + assert isinstance(audit["estimate"]["value"], int) + assert len(calls) == 1 diff --git a/vh/graph/evidence.py b/vh/graph/evidence.py index 6cb04f2..510eaa3 100644 --- a/vh/graph/evidence.py +++ b/vh/graph/evidence.py @@ -11,11 +11,25 @@ import json from types import MappingProxyType from collections.abc import Mapping +from numbers import Integral, Rational from .contracts import ContractError, ModelRegistry, PortSpec, Quantity, _text, _finite from .core import Edge +def _audit_scalar(value): + """Lossless JSON representation of an accepted scalar, or refuse binding.""" + if isinstance(value, Integral): + return int(value) + if isinstance(value, Rational): + return {"representation": "rational", "numerator": int(value.numerator), + "denominator": int(value.denominator)} + converted = float(value) + if value != converted: + raise ContractError("scalar cannot be serialized losslessly for evidence audit") + return converted + + @dataclass(frozen=True) class Uncertainty: """Source-reported interval or explicit lack of quantification. @@ -69,9 +83,9 @@ def audit(self) -> dict: return {"record_id": self.record_id, "status": self.status, "source": self.source, "locator": self.locator, "limits": self.limits, "uncertainty": {"kind": self.uncertainty.kind, "description": self.uncertainty.description, - "low": None if self.uncertainty.low is None else float(self.uncertainty.low), - "high": None if self.uncertainty.high is None else float(self.uncertainty.high)}, - "estimate": None if q is None else {"value": float(q.value), "quantity": q.quantity, + "low": None if self.uncertainty.low is None else _audit_scalar(self.uncertainty.low), + "high": None if self.uncertainty.high is None else _audit_scalar(self.uncertainty.high)}, + "estimate": None if q is None else {"value": _audit_scalar(q.value), "quantity": q.quantity, "unit": q.unit, "basis": q.basis, "context": dict(q.context), "provenance": list(q.provenance)}}

This model is described in the article:

+
+
Huang CY, Ferrell JE Jr
+
Proc. Natl. Acad. Sci. U.S.A. 1996:93(19):10078-83
+

Abstract:

+

The mitogen-activated protein kinase (MAPK) cascade is a highly conserved series of three protein kinases implicated in diverse biological processes. Here we demonstrate that the cascade arrangement has unexpected consequences for the dynamics of MAPK signaling. We solved the rate equations for the cascade numerically and found that MAPK is predicted to behave like a highly cooperative enzyme, even though it was not assumed that any of the enzymes in the cascade were regulated cooperatively. Measurements of MAPK activation in Xenopus oocyte extracts confirmed this prediction. The stimulus/response curve of the MAPK was found to be as steep as that of a cooperative enzyme with a Hill coefficient of 4-5, well in excess of that of the classical allosteric protein hemoglobin. The shape of the MAPK stimulus/ response curve may make the cascade particularly appropriate for mediating processes like mitogenesis, cell fate induction, and oocyte maturation, where a cell switches from one discrete state to another.

+
+