Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
30 changes: 20 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,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; **conserved-flow graphs** with R/C/L edge laws, gravity, Bernoulli, Starling collapse and valves; 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; steady flow exact against Hagen–Poiseuille/Windkessel/Starling, and the standing foot venous pressure predicted at **88.7 mmHg** vs the physiological **85–90 mmHg** range ([`docs/graph_formalization.md`](docs/graph_formalization.md), [`docs/bernoulli_veins.md`](docs/bernoulli_veins.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; **conserved-flow graphs** with R/C/L edge laws, gravity, Bernoulli, Starling collapse and valves; 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; steady flow exact against Hagen–Poiseuille/Windkessel/Starling, and the standing foot venous pressure predicted at **88.7 mmHg** vs the physiological **85–90 mmHg** range; SBML trajectories and steady states match libRoadRunner to ~1e-9 ([`docs/graph_formalization.md`](docs/graph_formalization.md), [`docs/bernoulli_veins.md`](docs/bernoulli_veins.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).
Expand All @@ -75,16 +75,23 @@ 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:

<p align="center">
<img src="docs/img/pbpk_graph.png" width="760" alt="The whole-body model as a flow graph of organs">
</p>
```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:

Expand All @@ -99,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)
Expand Down Expand Up @@ -184,12 +191,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, flow.py (conserved-flow solver), physiology_graph.py, render.py
vh/graph core.py (typed property graph), algorithms.py, flow.py (conserved-flow solver), 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
Expand All @@ -210,6 +218,8 @@ 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.
- **OpenCode agent (DeepSeek V4.1 Flash Free)** — conserved-flow graph, vein model, Bernoulli derivation, and flow validation under the above direction.
- **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.
- **MikeMike88 with Claude Code (Claude Opus 5.5)** — steady-state complementarity: uniqueness proof, finite pivoting solver, scaled convergence test, enumeration referee.

New contributors (human or agent): add yourself here in your pull request. See
Expand Down
146 changes: 146 additions & 0 deletions auto-research/2026-11-05-E-clearance-reference/report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
# 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

**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
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.
Loading
Loading