From 6e1a84277f1d75520a492d22e7f90c403d834517 Mon Sep 17 00:00:00 2001 From: MikeMike88 <149670168+MikeMike88@users.noreply.github.com> Date: Mon, 9 Nov 2026 01:32:59 +0500 Subject: [PATCH 1/2] Steady flow with valves: finite pivoting solver and an honest converged flag steady_state() mixed m^3/s node rows and Pa edge rows under one absolute tolerance (1e-7 inside, 1e-6 for converged). At physiological scale a node imbalance of 3e-7 m^3/s passed as zero, so on random valve networks 39/2000 solves returned converged=True with wrong flows (worst 23%; a 4-node regression network is off by 87%). A final max(q, 0) clamp hid the negative flows through closed valves. The solver now scales every residual row, solves each open/closed pattern by Newton with the analytic Jacobian (exact in one step for linear edges), pivots with Murty's least-index rule, and sets converged only if the scaled residual is below tol and every one-way edge satisfies complementarity. The implicit Euler Newton step gets the same scaling and warns instead of silently returning a non-converged iterate. Referee: exact enumeration of all valve / collapse regimes. 0/6000 wrong, error <= 8e-15; the headline venous network is unchanged (88.6688 mmHg). docs/steady_complementarity.md proves flow uniqueness for valves (minimum content KKT), reduces linear valves to a P-matrix LCP, records Starling uniqueness as an enumeration-backed conjecture, and documents that the expansion kinetic term makes the lumped model ill-posed above 0.53 L/min for a 3->6 mm vessel (not fixed here). Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + .../check_veins.py | 60 ++++ .../expansion_roots.py | 40 +++ .../probe_active_set.py | 205 +++++++++++ .../probe_collapsible.py | 171 +++++++++ .../report.md | 102 ++++++ auto-research/README.md | 1 + docs/steady_complementarity.md | 193 +++++++++++ tests/test_flow_complementarity.py | 327 ++++++++++++++++++ vh/graph/flow.py | 212 +++++++++--- 10 files changed, 1264 insertions(+), 48 deletions(-) create mode 100644 auto-research/2026-11-08-E-steady-complementarity/check_veins.py create mode 100644 auto-research/2026-11-08-E-steady-complementarity/expansion_roots.py create mode 100644 auto-research/2026-11-08-E-steady-complementarity/probe_active_set.py create mode 100644 auto-research/2026-11-08-E-steady-complementarity/probe_collapsible.py create mode 100644 auto-research/2026-11-08-E-steady-complementarity/report.md create mode 100644 docs/steady_complementarity.md create mode 100644 tests/test_flow_complementarity.py diff --git a/README.md b/README.md index 63525eb..fa4a5fb 100644 --- a/README.md +++ b/README.md @@ -210,6 +210,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. - **OpenCode agent (DeepSeek V4.1 Flash Free)** — conserved-flow graph, vein model, Bernoulli derivation, and flow validation under the above direction. +- **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 [`auto-research.md`](auto-research.md) for how to help. diff --git a/auto-research/2026-11-08-E-steady-complementarity/check_veins.py b/auto-research/2026-11-08-E-steady-complementarity/check_veins.py new file mode 100644 index 0000000..4bbcce2 --- /dev/null +++ b/auto-research/2026-11-08-E-steady-complementarity/check_veins.py @@ -0,0 +1,60 @@ +"""Check the PR's headline venous network against the brute-force exact solution. + +build_vein_network is copied verbatim from scripts/validate_flow.py (branch +auto/E-vein-flow-graph, commit 8152583) to avoid importing matplotlib. +""" + +import numpy as np + +from vh.graph.flow import MMHG, FlowNetwork, FlowNodeSpec, VesselSpec, build_flow_graph +from probe_active_set import brute_force, kkt_violation + +VEIN_POSITIONS = { + "ra": (0.55, 1.05), "ivc": (0.50, 0.95), "iliac": (0.44, 0.88), + "femoral": (0.38, 0.75), "popliteal": (0.42, 0.48), "calf": (0.36, 0.30), + "ankle": (0.32, 0.06), "foot": (0.24, 0.02), "saphenous": (0.72, 0.42), +} + + +def build_vein_network(tilt_deg=90.0, q_cap_l_min=0.5, p_ra_mmhg=5.0): + s = np.sin(np.deg2rad(tilt_deg)) + z = {name: h * s for name, (_, h) in VEIN_POSITIONS.items()} + nodes = [ + FlowNodeSpec("ra", "reservoir", pressure_pa=p_ra_mmhg * MMHG, z_m=z["ra"]), + FlowNodeSpec("ivc", "junction", z_m=z["ivc"]), + FlowNodeSpec("iliac", "junction", z_m=z["iliac"]), + FlowNodeSpec("femoral", "junction", z_m=z["femoral"]), + FlowNodeSpec("popliteal", "junction", z_m=z["popliteal"]), + FlowNodeSpec("calf", "compartment", compliance_m3_pa=2.0e-8, z_m=z["calf"]), + FlowNodeSpec("ankle", "compartment", compliance_m3_pa=5.0e-9, z_m=z["ankle"]), + FlowNodeSpec("foot", "compartment", compliance_m3_pa=5.0e-9, z_m=z["foot"], + source_m3_s=q_cap_l_min / 60000.0), + FlowNodeSpec("saphenous", "junction", z_m=z["saphenous"]), + ] + vessels = [ + VesselSpec("foot_ankle", "foot", "ankle", length_m=0.08, radius_m=0.0025, valve=True), + VesselSpec("ankle_calf", "ankle", "calf", length_m=0.24, radius_m=0.0030, valve=True), + VesselSpec("calf_popliteal", "calf", "popliteal", length_m=0.15, radius_m=0.0040, valve=True), + VesselSpec("popliteal_femoral", "popliteal", "femoral", length_m=0.15, radius_m=0.0045, valve=True), + VesselSpec("femoral_iliac", "femoral", "iliac", length_m=0.15, radius_m=0.0050, valve=True), + VesselSpec("iliac_ivc", "iliac", "ivc", length_m=0.10, radius_m=0.0060, valve=True), + VesselSpec("ivc_ra", "ivc", "ra", length_m=0.15, radius_m=0.0080, valve=True), + VesselSpec("ankle_saphenous", "ankle", "saphenous", length_m=0.20, radius_m=0.0020, valve=True), + VesselSpec("saphenous_femoral", "saphenous", "femoral", length_m=0.60, radius_m=0.0020, valve=True), + ] + return build_flow_graph(nodes, vessels) + + +for tilt in (0, 30, 60, 90): + g, _ = build_vein_network(tilt) + net = FlowNetwork.from_graph(g) + sol = net.steady_state() + p = np.array([sol.pressure[i] for i in net.node_ids]) + q = np.array([sol.flow[i] for i in net.edge_ids]) + truth = brute_force(net) + pt, qt = truth[0] + foot = net.node_index["foot"] + print(f"tilt {tilt:2d}: method={sol.method} converged={sol.converged} n_true={len(truth)} " + f"foot solver={p[foot] / MMHG:.4f} true={pt[foot] / MMHG:.4f} mmHg " + f"max|dq|/max|q|={np.max(np.abs(q - qt)) / np.max(np.abs(qt)):.1e} " + f"kkt={ {k: f'{v:.1e}' for k, v in kkt_violation(net, p, q).items()} }") diff --git a/auto-research/2026-11-08-E-steady-complementarity/expansion_roots.py b/auto-research/2026-11-08-E-steady-complementarity/expansion_roots.py new file mode 100644 index 0000000..1c4a22f --- /dev/null +++ b/auto-research/2026-11-08-E-steady-complementarity/expansion_roots.py @@ -0,0 +1,40 @@ +"""Single expanding tube between two reservoirs: all steady states of R q + c q|q| = dp (c < 0).""" + +import numpy as np + +from vh.graph.flow import RHO_BLOOD, FlowNetwork, FlowNodeSpec, VesselSpec, poiseuille_resistance + +r1, r2, length = 0.003, 0.006, 0.1 +A1, A2 = np.pi * r1 ** 2, np.pi * r2 ** 2 +R = poiseuille_resistance(length, r1) +c = 0.5 * RHO_BLOOD * (1 / A2 ** 2 - 1 / A1 ** 2) +a = abs(c) +print(f"R={R:.4e} c={c:.4e} q_crit={R / (2 * a):.4e} m3/s ({R / (2 * a) * 6e4:.3f} L/min) " + f"dp_max={R ** 2 / (4 * a):.3f} Pa") + + +def exact_roots(dp): + roots = [] + disc = R ** 2 - 4 * a * dp + if disc >= 0: # q > 0: a q^2 - R q + dp = 0 + roots += [(R - np.sqrt(disc)) / (2 * a), (R + np.sqrt(disc)) / (2 * a)] + s = (-R + np.sqrt(R ** 2 + 4 * a * dp)) / (2 * a) # q = -s < 0: a s^2 + R s - dp = 0 ... see below + # for q < 0: R q + c q|q| = R q - c q^2 = R q + a q^2 = dp + disc2 = R ** 2 + 4 * a * dp + for q in ((-R + np.sqrt(disc2)) / (2 * a), (-R - np.sqrt(disc2)) / (2 * a)): + if q < 0: + roots.append(q) + return sorted(roots) + + +for dp in (10.0, 30.0, 48.0, 49.0, 100.0, 1000.0): + nodes = [FlowNodeSpec("up", "reservoir", pressure_pa=dp), FlowNodeSpec("down", "reservoir", pressure_pa=0.0)] + vessels = [VesselSpec("e", "up", "down", length_m=length, radius_m=r1, + area_src_m2=A1, area_dst_m2=A2, gravity_head_pa=0.0)] + net = FlowNetwork.from_specs(nodes, vessels) + sol = net.steady_state() + roots = exact_roots(dp) + resid = [R * q + c * q * abs(q) - dp for q in roots] + print(f"dp={dp:7.1f} Pa: exact roots {[f'{q:.4e}' for q in roots]} (residuals {[f'{x:.1e}' for x in resid]})" + f" | solver q={sol.flow['e']:.4e} converged={sol.converged} method={sol.method}" + f" | Poiseuille dp/R={dp / R:.4e}") diff --git a/auto-research/2026-11-08-E-steady-complementarity/probe_active_set.py b/auto-research/2026-11-08-E-steady-complementarity/probe_active_set.py new file mode 100644 index 0000000..0faa25f --- /dev/null +++ b/auto-research/2026-11-08-E-steady-complementarity/probe_active_set.py @@ -0,0 +1,205 @@ +"""Probe: does FlowNetwork.steady_state() report converged=True on wrong answers? + +Random linear resistor networks with ideal one-way valves. Every junction is +connected to a reservoir through a spanning tree of plain (two-way) resistors, +so for every open/closed pattern the linear system is nonsingular and the true +solution is unique (strictly convex content, see notes). + +For each network we + * run the solver under test; + * check the KKT / complementarity conditions independently; + * find the true solution by brute force over all 2^k valve patterns. +""" + +from __future__ import annotations + +import itertools +import json +import sys + +import numpy as np + +from vh.graph.flow import FlowNetwork, FlowNodeSpec, VesselSpec + +TOL_Q = 1e-9 # relative flow tolerance +TOL_P = 1e-6 # Pa + + +def random_network(rng, n_res, n_junc, n_tree_extra, n_valves): + """Return (nodes, vessels, meta) for a random network.""" + ids = [f"r{i}" for i in range(n_res)] + [f"j{i}" for i in range(n_junc)] + nodes = [] + for i in range(n_res): + nodes.append(FlowNodeSpec(ids[i], "reservoir", pressure_pa=float(rng.uniform(0, 2000)))) + for i in range(n_junc): + src = float(rng.choice([0.0, 0.0, rng.uniform(-1, 1) * 1e-6])) + nodes.append(FlowNodeSpec(ids[n_res + i], "junction", source_m3_s=src)) + vessels = [] + k = 0 + + def add(a, b, valve): + nonlocal k + vessels.append(VesselSpec(f"e{k}", a, b, length_m=0.1, radius_m=0.003, + resistance_pa_s_m3=float(10 ** rng.uniform(7, 9)), + gravity_head_pa=0.0, valve=valve)) + k += 1 + + # spanning tree of two-way resistors: each new node attaches to an earlier one + order = list(range(len(ids))) + for pos in range(1, len(order)): + a = ids[order[pos]] + b = ids[order[int(rng.integers(0, pos))]] + if rng.random() < 0.5: + a, b = b, a + add(a, b, False) + for _ in range(n_tree_extra): + a, b = rng.choice(len(ids), 2, replace=False) + add(ids[a], ids[b], False) + for _ in range(n_valves): + a, b = rng.choice(len(ids), 2, replace=False) + add(ids[a], ids[b], True) + return nodes, vessels + + +def linear_solve(net, open_mask): + """Solve with valves fixed open/closed (closed: q=0). Returns p, q.""" + n, m = net.n, net.m + A = np.zeros((n + m, n + m)) + b = np.zeros(n + m) + for i in range(n): + if net.is_reservoir[i]: + A[i, i] = 1.0 + b[i] = net.p_fixed[i] + else: + A[i, n:] = net.B[i] + b[i] = -net.source[i] + for e in range(m): + row = n + e + if net.valve[e] and not open_mask[e]: + A[row, n + e] = 1.0 + else: + A[row, :n] = net.B[:, e] + A[row, n + e] = net.R[e] + b[row] = -net.h[e] + x = np.linalg.solve(A, b) + return x[:n], x[n:] + + +def kkt_violation(net, p, q): + """Violations of the steady KKT conditions, each normalised to be O(1) when wrong. + + Pressure-like residuals are divided by pscale (largest |p|), flow-like ones by + qscale (largest |q|), so one relative tolerance serves every check. + For a valve the complementarity is q >= 0, R q - drive >= 0, q (R q - drive) = 0, + measured in pressure units as min(R q, R q - drive) (Fischer-Burmeister-like). + """ + qscale = max(1e-30, float(np.max(np.abs(q)))) + pscale = max(1e-30, float(np.max(np.abs(p)))) + drive = p[net.src] - p[net.dst] - net.h # src minus dst + v = {} + bal = net.B @ q + net.source + junc = ~net.is_reservoir + v["balance"] = float(np.max(np.abs(bal[junc]))) / qscale if np.any(junc) else 0.0 + tw = ~net.valve + v["law_twoway"] = float(np.max(np.abs(drive[tw] - net.R[tw] * q[tw]))) / pscale if np.any(tw) else 0.0 + val = net.valve + if np.any(val): + a = net.R[val] * q[val] # >= 0 + b = net.R[val] * q[val] - drive[val] # >= 0 (blocking pressure of a closed valve) + v["valve_compl"] = float(np.max(np.abs(np.minimum(a, b)))) / pscale + else: + v["valve_compl"] = 0.0 + return v + + +def is_kkt(v, tol=1e-9): + return all(x < tol for x in v.values()) + + +def brute_force(net): + idx = np.nonzero(net.valve)[0] + sols = [] + for bits in itertools.product([False, True], repeat=len(idx)): + mask = np.ones(net.m, dtype=bool) + mask[idx] = bits + try: + p, q = linear_solve(net, mask) + except np.linalg.LinAlgError: + # a junction cut off from every reservoir: its pressure is not determined + # by this pattern (only bounded by the closed valves); skip it here + continue + if is_kkt(kkt_violation(net, p, q)): + # a degenerate valve (q = 0 and drive = 0) is a KKT point both open and + # closed; count distinct solutions, not patterns + if not any(np.allclose(q, q2, rtol=1e-9, atol=1e-9 * np.max(np.abs(q))) + and np.allclose(p, p2, rtol=1e-9, atol=1e-9 * np.max(np.abs(p))) + for p2, q2 in sols): + sols.append((p, q)) + return sols + + +def main(seed=0, trials=2000): + rng = np.random.default_rng(seed) + stats = {"trials": 0, "solver_converged": 0, "solver_wrong_but_converged": 0, + "solver_wrong_not_converged": 0, "unique_true_solution": 0, "examples": []} + for t in range(trials): + n_res = int(rng.integers(1, 4)) + n_junc = int(rng.integers(2, 8)) + n_valves = int(rng.integers(1, 9)) + nodes, vessels = random_network(rng, n_res, n_junc, int(rng.integers(0, 3)), n_valves) + net = FlowNetwork.from_specs(nodes, vessels) + sol = net.steady_state() + p = np.array([sol.pressure[i] for i in net.node_ids]) + q = np.array([sol.flow[i] for i in net.edge_ids]) + v = kkt_violation(net, p, q) + ok = is_kkt(v) + truth = brute_force(net) + stats["trials"] += 1 + stats["unique_true_solution"] += int(len(truth) == 1) + stats.setdefault("n_true_hist", {}) + stats["n_true_hist"][str(len(truth))] = stats["n_true_hist"].get(str(len(truth)), 0) + 1 + if sol.converged and len(truth) == 1: + pt, qt = truth[0] + err = float(np.max(np.abs(q - qt)) / max(1e-30, np.max(np.abs(qt)))) + perr = float(np.max(np.abs(p - pt)) / max(1e-30, np.max(np.abs(pt)))) + stats.setdefault("converged_err_hist", {"<1e-9": 0, "1e-9..1e-6": 0, "1e-6..1e-3": 0, "1e-3..1e-1": 0, ">=1e-1": 0}) + bucket = ("<1e-9" if err < 1e-9 else "1e-9..1e-6" if err < 1e-6 else "1e-6..1e-3" if err < 1e-3 + else "1e-3..1e-1" if err < 1e-1 else ">=1e-1") + stats["converged_err_hist"][bucket] += 1 + if err > stats.get("worst_converged", {}).get("q_rel_err", -1): + stats["worst_converged"] = { + "trial": t, "q_rel_err": err, "p_rel_err": perr, "residual_norm": sol.residual_norm, + "violations": v, "q_solver": q.tolist(), "q_true": qt.tolist(), + "nodes": [n.__dict__ for n in nodes], "vessels": [e.__dict__ for e in vessels]} + if ok and len(truth) == 1: + qt = truth[0][1] + stats.setdefault("max_rel_err_vs_truth_when_ok", 0.0) + stats["max_rel_err_vs_truth_when_ok"] = max( + stats["max_rel_err_vs_truth_when_ok"], + float(np.max(np.abs(q - qt)) / max(1e-30, np.max(np.abs(qt))))) + stats["solver_converged"] += int(sol.converged) + if not ok: + key = "solver_wrong_but_converged" if sol.converged else "solver_wrong_not_converged" + stats[key] += 1 + if len(stats["examples"]) < 5 and sol.converged: + stats["examples"].append({ + "trial": t, "violations": v, "n_true_solutions": len(truth), + "nodes": [n.__dict__ for n in nodes], + "vessels": [e.__dict__ for e in vessels], + }) + return stats + + +if __name__ == "__main__": + seed = int(sys.argv[1]) if len(sys.argv) > 1 else 0 + trials = int(sys.argv[2]) if len(sys.argv) > 2 else 2000 + out = sys.argv[3] if len(sys.argv) > 3 else None + s = main(seed, trials) + summary = {k: v for k, v in s.items() if k not in ("examples", "worst_converged")} + w = s.get("worst_converged", {}) + summary["worst_converged"] = {k: w.get(k) for k in ("trial", "q_rel_err", "p_rel_err", "residual_norm", "violations")} + print(json.dumps(summary, indent=1)) + if out: + with open(out, "w", encoding="utf-8") as f: + json.dump(s, f, indent=1, default=float) + print("examples ->", out) diff --git a/auto-research/2026-11-08-E-steady-complementarity/probe_collapsible.py b/auto-research/2026-11-08-E-steady-complementarity/probe_collapsible.py new file mode 100644 index 0000000..40202d4 --- /dev/null +++ b/auto-research/2026-11-08-E-steady-complementarity/probe_collapsible.py @@ -0,0 +1,171 @@ +"""Collapsible (Starling) edges: is the steady solution unique, and does the solver find it? + +Edge law in vh.graph.flow (one-way, q >= 0): + open: R q = p_src - max(p_dst, p_ext) - h + closed: q = 0 and p_src - max(p_dst, p_ext) - h <= 0 +Each collapsible edge has three linear regimes: + C closed q = 0, drive <= 0 + N open, normal R q = p_src - p_dst - h, p_dst >= p_ext, q >= 0 + W open, waterfall R q = p_src - p_ext - h, p_dst <= p_ext, q >= 0 +Enumerating all 3^k regimes and keeping the self-consistent ones gives every +steady solution exactly (the system is piecewise linear). +""" + +from __future__ import annotations + +import itertools +import json +import sys + +import numpy as np + +from vh.graph.flow import FlowNetwork, FlowNodeSpec, VesselSpec + +TOL = 1e-9 + + +def random_net(rng): + n_res, n_junc = int(rng.integers(1, 4)), int(rng.integers(1, 6)) + ids = [f"r{i}" for i in range(n_res)] + [f"j{i}" for i in range(n_junc)] + nodes = [FlowNodeSpec(ids[i], "reservoir", pressure_pa=float(rng.uniform(0, 2000))) + for i in range(n_res)] + nodes += [FlowNodeSpec(ids[n_res + i], "junction", + source_m3_s=float(rng.choice([0.0, rng.uniform(-1, 1) * 1e-6]))) + for i in range(n_junc)] + vessels = [] + + def add(a, b, kind): + kw = {} + if kind == "valve": + kw["valve"] = True + elif kind == "coll": + kw["collapsible"] = True + kw["external_pressure_pa"] = float(rng.uniform(0, 2000)) + vessels.append(VesselSpec(f"e{len(vessels)}", a, b, length_m=0.1, radius_m=0.003, + resistance_pa_s_m3=float(10 ** rng.uniform(7, 9)), + gravity_head_pa=0.0, **kw)) + + for k in range(1, len(ids)): + a, b = ids[k], ids[int(rng.integers(0, k))] + add(*((a, b) if rng.random() < 0.5 else (b, a)), "two") + for _ in range(int(rng.integers(0, 2))): + a, b = rng.choice(len(ids), 2, replace=False) + add(ids[a], ids[b], "two") + for _ in range(int(rng.integers(0, 3))): + a, b = rng.choice(len(ids), 2, replace=False) + add(ids[a], ids[b], "valve") + for _ in range(int(rng.integers(1, 5))): + a, b = rng.choice(len(ids), 2, replace=False) + add(ids[a], ids[b], "coll") + return nodes, vessels + + +def solve_regime(net, regime): + """regime[e] in {'T' two-way, 'O' open valve, 'C' closed, 'N' normal, 'W' waterfall}.""" + n, m = net.n, net.m + A = np.zeros((n + m, n + m)) + b = np.zeros(n + m) + for i in range(n): + if net.is_reservoir[i]: + A[i, i] = 1.0 + b[i] = net.p_fixed[i] + else: + A[i, n:] = net.B[i] + b[i] = -net.source[i] + for e in range(m): + row = n + e + r = regime[e] + if r == "C": + A[row, n + e] = 1.0 + elif r == "W": # p_src - R q = p_ext + h + A[row, net.src[e]] = 1.0 + A[row, n + e] = -net.R[e] + b[row] = net.external_pressure[e] + net.h[e] + else: # T, O, N: p_src - p_dst - R q = h + A[row, net.src[e]] = 1.0 + A[row, net.dst[e]] = -1.0 + A[row, n + e] = -net.R[e] + b[row] = net.h[e] + x = np.linalg.solve(A, b) + return x[:n], x[n:] + + +def consistent(net, p, q): + """Full steady conditions, checked directly (regime-free).""" + ps = max(1e-30, float(np.max(np.abs(p))), float(np.max(np.abs(net.external_pressure), initial=0))) + # flow scale from the physics, not from the answer: a network can carry no flow + qs = max(float(np.max(np.abs(q))), ps / float(np.median(net.R)), + float(np.max(np.abs(net.source), initial=0.0))) + junc = ~net.is_reservoir + if np.max(np.abs((net.B @ q + net.source)[junc]), initial=0.0) > TOL * qs: + return False + p_eff = p[net.dst].copy() + p_eff[net.collapsible] = np.maximum(p_eff[net.collapsible], net.external_pressure[net.collapsible]) + drive = p[net.src] - p_eff - net.h + one = net.valve | net.collapsible + if np.max(np.abs(drive[~one] - net.R[~one] * q[~one]), initial=0.0) > TOL * ps: + return False + a = net.R[one] * q[one] + w = a - drive[one] + return np.max(np.abs(np.minimum(a, w)), initial=0.0) <= TOL * ps + + +def enumerate_all(net): + choices = [] + for e in range(net.m): + if net.collapsible[e]: + choices.append("CNW") + elif net.valve[e]: + choices.append("CO") + else: + choices.append("T") + sols = [] + for regime in itertools.product(*choices): + try: + p, q = solve_regime(net, regime) + except np.linalg.LinAlgError: + continue + if consistent(net, p, q): + if not any(np.allclose(q, q2, rtol=1e-8, atol=1e-8 * np.max(np.abs(q))) for _, q2 in sols): + sols.append((p, q)) + return sols + + +def main(seed, trials, out): + rng = np.random.default_rng(seed) + stats = {"trials": trials, "hist_n_solutions": {}, "solver_converged": 0, + "solver_matches_unique": 0, "solver_wrong_but_converged": 0, "solver_not_converged": 0} + multi = [] + for t in range(trials): + nodes, vessels = random_net(rng) + net = FlowNetwork.from_specs(nodes, vessels) + sols = enumerate_all(net) + k = str(len(sols)) + stats["hist_n_solutions"][k] = stats["hist_n_solutions"].get(k, 0) + 1 + sol = net.steady_state() + p = np.array([sol.pressure[i] for i in net.node_ids]) + q = np.array([sol.flow[i] for i in net.edge_ids]) + ok = consistent(net, p, q) + stats["solver_converged"] += int(sol.converged) + if not sol.converged: + stats["solver_not_converged"] += 1 + elif not ok: + stats["solver_wrong_but_converged"] += 1 + if len(sols) == 1 and ok and sol.converged: + qscale = max(float(np.max(np.abs(sols[0][1]))), + float(np.max(np.abs(sols[0][0]))) / float(np.median(net.R))) + stats["solver_matches_unique"] += int(np.max(np.abs(q - sols[0][1])) <= 1e-8 * qscale) + if len(sols) != 1 and len(multi) < 5: + multi.append({"trial": t, "n_solutions": len(sols), + "q_solutions": [s[1].tolist() for s in sols], + "p_solutions": [s[0].tolist() for s in sols], + "solver_q": q.tolist(), "solver_converged": sol.converged, + "nodes": [n.__dict__ for n in nodes], + "vessels": [e.__dict__ for e in vessels]}) + print(json.dumps(stats, indent=1)) + with open(out, "w", encoding="utf-8") as f: + json.dump({"stats": stats, "non_unique_examples": multi}, f, indent=1) + + +if __name__ == "__main__": + main(int(sys.argv[1]), int(sys.argv[2]), sys.argv[3]) diff --git a/auto-research/2026-11-08-E-steady-complementarity/report.md b/auto-research/2026-11-08-E-steady-complementarity/report.md new file mode 100644 index 0000000..be6481b --- /dev/null +++ b/auto-research/2026-11-08-E-steady-complementarity/report.md @@ -0,0 +1,102 @@ +# Steady flow with valves: a unique solution, a finite solver, and an honest `converged` + +- **Track**: E (graph formalization), follow-up to `2026-11-08-E-vein-flow-graph` +- **Author**: MikeMike88 with Claude Code (Claude Opus 5.5) +- **Date**: 2026-11-08 +- **Branch / PR**: `auto/E-steady-complementarity` (based on `auto/E-vein-flow-graph`) +- **Code added**: `vh/graph/flow.py` (steady solver, transient Newton tolerance), + `tests/test_flow_complementarity.py`, `docs/steady_complementarity.md`, probe scripts in + this folder + +## Question + +`FlowNetwork.steady_state()` solves networks with one-way valves and collapsible +veins by an active-set loop. Is its answer the right one, and does `converged=True` +mean anything? What does the mathematics guarantee here? + +## Method + +1. **Referee by enumeration.** A valve is either open or closed, and a collapsible + edge is closed, open-normal, or open-waterfall. Every pattern is a linear system, + so solving all `2^k` (or `3^k`) systems and keeping the self-consistent solutions + finds **every** steady state exactly. No iteration and no tolerance tuning are + involved, and nothing from the solver under test is used. +2. **Theory** (`docs/steady_complementarity.md`). + - The steady problem with valves and monotone losses is the KKT system of a + strictly convex *minimum-content* program (Millar 1951). So the flows are + unique, and the junction pressures are its multipliers. + - With linear edges it reduces to a P-matrix LCP, for which Murty's least-index + single-pivot rule is finite. +3. **Solver changes.** + - Residual rows are scaled by a characteristic pressure and flow. + - Each pattern is solved by Newton with the analytic Jacobian; for linear edges + the first step is exact. + - Pivoting follows Murty's least-index rule instead of flipping all violators at + once. + - `converged` now requires a scaled residual below `1e-10` **and** + complementarity on every one-way edge. + - The transient implicit-Euler Newton step uses the same scaling, and it warns + instead of silently returning a non-converged iterate. + +## Validation + +Authority: exact enumeration of all valve/collapse regimes (piecewise-linear +steady states), plus closed-form roots for the single expanding tube. + +| Quantity | Before | After | Authority | +|---|---|---|---| +| random valve networks, `converged=True` but wrong | **39 / 2000** (seed 0) | **0 / 6000** (seeds 0–2) | enumeration of `2^k` patterns | +| worst flow error among "converged" | **23%** | **8e-15** relative | same | +| regression network (4 nodes, 7 edges) | flows off by **87%**, balance off by **22%**, `converged=True` | exact, residual 6e-17 | same | +| random collapsible networks | not separately measured | **6000 / 6000** unique steady states; solver matches to 1e-8 | enumeration of `3^k` regimes | +| headline venous network (all tilts) | foot 88.6688 mmHg | identical (to 2e-16) | enumeration | +| expanding tube, 0 < dp < R²/(4\|c\|) | Poiseuille branch | Poiseuille branch, error < 1e-10 | exact quadratic root | +| `tests/test_flow_complementarity.py` | 4 of 11 tests fail, 66 s | 11 / 11 pass, 3.7 s | — | + +The original 24 flow tests and the graph tests still pass. Full run: +`tests/test_flow.py tests/test_graph.py tests/test_flow_complementarity.py`, with +`-W error::RuntimeWarning`. + +## Limits + +- **Expansions make the lumped model ill-posed.** For `A_dst > A_src` the edge law + `R q + c q|q|` with `c < 0` stops increasing at `q_crit = R/(2|c|)`. For a 10 cm + vessel widening from 3 to 6 mm, `q_crit = 0.53 L/min`. On a single such edge, + `0 < dp < R²/(4|c|) = 48.7 Pa` gives three steady states. A larger `dp` gives + only reverse flow (about 3 L/min backwards at `dp = 1000 Pa`), and both solvers + return it as converged. This is a modelling issue (static-pressure nodes plus + lossless pressure recovery), not a solver bug. It is reported here and **not + fixed**. +- **Starling uniqueness is a conjecture.** It holds in every one of the 6000 + enumerated networks, but Theorem 1 does not cover three-terminal waterfall + edges, and the maximum-principle proof fails for them (section 6 of the doc). +- **Murty finiteness needs a connectivity assumption.** The proof needs the + two-way edges to connect every junction to a reservoir. Otherwise flows are + still unique, but the pivot count is only capped (`50 + 10k`); a run that hits + the cap reports `converged=False`. +- **Collapsible edges stay one-way, as before.** Reverse flow through a + collapsible vessel is forbidden. This is a pre-existing modelling choice; it + is now documented but unchanged. +- **The transient test is a guard, not a regression demonstration.** It also + passes on the old code. + +## Reproduce + +```bash +pip install -e . numpy scipy pytest +pytest -q tests/test_flow_complementarity.py tests/test_flow.py -W error::RuntimeWarning +cd auto-research/2026-11-08-E-steady-complementarity +python probe_active_set.py 0 2000 results_valves_s0.json # enumeration vs solver +python probe_collapsible.py 0 2000 results_collapsible_s0.json +python expansion_roots.py # three roots / no forward root +python check_veins.py # headline network unchanged +``` + +## References + +- W. Millar, *Phil. Mag.* 42 (1951) 1150–1160: content minimum principle for + monotone resistor networks. +- K. G. Murty, *Opsearch* 11 (1974) 123–130: finiteness of the least-index + principal pivoting rule for P-matrix LCPs. +- R. W. Cottle, J.-S. Pang, R. E. Stone, *The Linear Complementarity Problem* + (1992). diff --git a/auto-research/README.md b/auto-research/README.md index 98c7c60..d8a7789 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-08 | E | [Conserved-flow graphs: topology → venous pressure](2026-11-08-E-vein-flow-graph/report.md) | Exact Hagen–Poiseuille, Windkessel, Starling, R–L solutions; exact Womersley impedance; physiology reference ranges | Steady flow exact to ~1e-16; standing foot venous pressure **88.7 mmHg** vs **85–90** (foot inside range, ankle 0.6 mmHg below); lumped R–L within 1% up to α=0.48, with measured breakdown at high α | OpenCode agent (DeepSeek V4.1 Flash Free) | +| 2026-11-08 | E | [Steady flow with valves: unique solution, finite solver, honest `converged`](2026-11-08-E-steady-complementarity/report.md) | Exact enumeration of all valve / collapse regimes; closed-form roots | Previous solver: 39/2000 random networks wrong but `converged=True` (worst 23%); now 0/6000, error ≤ 8e-15. Flow uniqueness proved for valves; Starling uniqueness 6000/6000 (conjecture). Expansion kinetic term makes the model ill-posed above 0.53 L/min (documented, not fixed) | MikeMike88 with Claude Code (Claude Opus 5.5) | diff --git a/docs/steady_complementarity.md b/docs/steady_complementarity.md new file mode 100644 index 0000000..c256bc2 --- /dev/null +++ b/docs/steady_complementarity.md @@ -0,0 +1,193 @@ +# Steady flow with valves and collapse: existence, uniqueness, and a finite solver + +This note gives the mathematics behind `FlowNetwork.steady_state()` for networks +with one-way valves and collapsible (Starling) vessels, and states exactly what is +proved, what is only checked numerically, and where the model itself breaks. +Tests: `tests/test_flow_complementarity.py`. + +## 1. The problem + +A network has reservoirs `S` (fixed pressure `p_r`), junctions/compartments `J` +(unknown pressure, source `s_j`), and edges `E` with incidence `B` +(`B[src,e] = -1`, `B[dst,e] = +1`). Edge `e` carries flow `q_e` and has the law + + p_src - p_dst - h_e = phi_e(q_e), phi_e(q) = R_e q + c_e q|q| + k_e q|q| + +(`R_e > 0` Poiseuille, `c_e` the Bernoulli kinetic term, `k_e >= 0` minor loss, +`h_e` gravity head). At steady state every junction balances, `(B q)_j + s_j = 0`. + +A **valve** edge `v` additionally allows only forward flow. With the blocking +pressure `w_v = phi_v(q_v) - (p_src - p_dst - h_v)` the valve law is the +complementarity condition + + q_v >= 0, w_v >= 0, q_v * w_v = 0. (C) + +An open valve has `w_v = 0`. A closed valve has `q_v = 0` and holds back +`w_v >= 0`. + +## 2. Valves with monotone losses: a unique flow solution + +**Theorem 1.** Let every `phi_e` be continuous and strictly increasing with +`phi_e(0) = 0` and `|phi_e(q)| -> infinity` as `|q| -> infinity`. Assume the +balance equations have a solution with `q_V >= 0` (for example, every junction +reaches a reservoir through two-way edges). Then the steady problem with valves +(C) has a solution, and its **flow vector is unique**. If every junction is +connected to a reservoir by two-way edges, the pressures are unique too. + +*Proof.* Let `Phi_e(q) = int_0^q phi_e` (strictly convex and coercive). Minimise +the content + + F(q) = sum_e [ Phi_e(q_e) + h_e q_e ] + sum_{r in S} p_r (B q)_r + +subject to the linear constraints `(B q)_j + s_j = 0` for `j in J` and `q_v >= 0` +for `v in V`. `F` is strictly convex and coercive on a nonempty polyhedron, so +there is exactly one minimiser `q*`. The constraints are linear, so the KKT +conditions are necessary and sufficient. Write `lambda_j` for the multipliers of +the balance rows and `mu_v >= 0` for the sign constraints. Stationarity in `q_e` +reads + + phi_e(q_e) + h_e + sum_{i} p_i B[i,e] - mu_e = 0 , with p_j := lambda_j on J, + +and `sum_i p_i B[i,e] = p_dst - p_src`. So `phi_e(q_e) = p_src - p_dst - h_e + mu_e`: +for a two-way edge (`mu_e = 0`) this is the edge law, and for a valve `mu_v = w_v`. +`mu_v >= 0`, `q_v >= 0` and `mu_v q_v = 0` are exactly (C). The KKT system is +therefore *identical* to the steady equations, and the multipliers are the junction +pressures. Any steady solution is a KKT point, hence equals the minimiser: the +flows are unique. If two-way edges connect every junction to a reservoir, the +pressures follow uniquely from the flows along those edges. ∎ + +Without the connectivity assumption the pressures can be non-unique. For example, +a junction whose edges are all closed valves may sit at any pressure that keeps +them closed. The flows are still unique. + +## 3. Linear valves: a P-matrix LCP and a finite pivoting rule + +Take linear edges (`phi_e = R_e q`), and let two-way edges connect every junction +to a reservoir. Eliminate the junction pressures through the grounded Laplacian +`L_J = B_{J,T} R_T^{-1} B_{J,T}^T` of the two-way subnetwork `T`; `L_J` is symmetric +positive definite under the connectivity assumption. The blocking pressures +become an affine function of the valve flows, + + w = M q_V + c, M = R_V + B_{J,V}^T L_J^{-1} B_{J,V}, + +with `M` symmetric positive definite (`R_V` is a positive diagonal matrix, the +second term is PSD). So (C) is the linear complementarity problem `LCP(c, M)` +with a P-matrix: it has exactly one solution for every `c`. + +`steady_state()` uses single principal pivots with **Murty's least-index rule**: +1. Solve the equations of the current open/closed pattern. +2. Among the valves whose state contradicts the solution (open with `q < 0`, or + closed with positive driving pressure), flip only the one with the lowest + index. + +For P-matrix LCPs this terminates after finitely many pivots (Murty 1974), and the +final pattern gives the unique solution. + +The previous loop flipped *every* violating valve at once (block pivoting) and +stopped after 20 sweeps. Simultaneous flipping has no general finiteness +guarantee, unlike the single least-index pivot. The new +loop also stops at a cap (`50 + 10 k` pivots), but then it reports +`converged = False` instead of returning the last iterate. + +**What is not covered.** If some valve pattern cuts a junction off from every +reservoir, the elimination above does not exist for that pattern. Then the +finiteness argument does not apply, although Theorem 1 still gives unique flows. + +## 4. The convergence test, and the bug it fixes + +The steady residual mixes units: junction rows are flows (m³/s) and edge rows are +pressures (Pa). At physiological scale they differ by ~9 orders of magnitude +(`q ~ 1e-6 m³/s`, `p ~ 1e3 Pa`). The previous code compared the raw residual +with one absolute number (`1e-7` inside the loop, `1e-6` for `converged`). A +node imbalance of `3e-7 m³/s` passed as "zero", although it was 22% of the +largest flow. `tests/test_flow_complementarity.py::regression_network` is such a +case: 4 nodes and 7 edges, flows wrong by 87%, reported `converged=True`. The +final `max(q, 0)` clamp then hid the negative flows through closed valves. + +Now every row is divided by its own scale: pressures by `P*`, flows by +`Q* = max(|s|, P*/median(R), |q|)`. `converged` requires a scaled residual below +`tol` (default `1e-10`) **and** complementarity on every one-way edge. +`residual_norm` is the scaled (dimensionless) residual. + +Measured against brute-force enumeration of all `2^k` valve patterns, on 6000 +random networks (seeds 0–2, up to 10 nodes and 8 valves): + +| solver | `converged=True` but wrong | worst flow error when "converged" | +|---|---:|---:| +| previous active-set loop (seed 0) | 39 / 2000 | 23% | +| this one (seeds 0–2) | 0 / 6000 | 8e-15 relative | + +The headline venous network of `scripts/validate_flow.py` was **not** affected. +All its valves are open, and the first linear solve is already exact (foot +pressure 88.6688 mmHg standing, identical to 1e-16 with both solvers). + +## 5. The kinetic term breaks monotonicity at an expansion + +For an edge that widens (`A_dst > A_src`), the Bernoulli coefficient +`c = (alpha rho / 2)(1/A_dst² - 1/A_src²)` is negative (pressure recovery). Then +`phi(q) = R q + c q|q|` increases only for `|q| < q_crit = R / (2|c|)` (with no +minor loss), and Theorem 1 no longer applies. On a single such edge between two +reservoirs with `dp = p_src - p_dst > 0`: + +- for `0 < dp < R²/(4|c|)` there are **three** steady states: + `q = (R ∓ sqrt(R² - 4|c| dp)) / (2|c|)` forward, and one reverse root; +- for `dp > R²/(4|c|)` there is **no forward solution at all**, only reverse flow + against the pressure difference. + +With the code's constants (`mu = 3.5e-3 Pa s`, `rho = 1060 kg/m³`), a 10 cm vessel +widening from 3 mm to 6 mm radius has `q_crit = 8.9e-6 m³/s = 0.53 L/min`, which +is inside the physiological range. It also has `R²/(4|c|) = 48.7 Pa` +(0.37 mmHg). At `dp = 1000 Pa` the only steady state of the equations is a +reverse flow of about 3 L/min. Both the old and the new solver return it as +converged, because it does satisfy the equations. Between 49 and 100 Pa both +report `converged=False`. + +This is a property of the lumped model, not of the solver. Static-pressure +continuity at nodes, plus a lossless kinetic term, lets the recovered kinetic +pressure grow like `q²` while the viscous drop grows like `q`. Fixing it is a +modelling decision: total-pressure nodes, a Borda–Carnot loss, or a bounded +recovery. This change does not take that decision. The solver starts Newton +from the Poiseuille solution, so it follows the physical branch while that branch +exists (`test_expanding_tube_follows_the_poiseuille_branch`). + +## 6. Collapsible (Starling) edges: unique in every test, not proved + +In `vh.graph.flow` a collapsible edge is one-way with +`q = max(0, (p_src - max(p_dst, p_ext) - h) / R)`. It is piecewise linear with +three regimes: closed, open-normal, and open-waterfall. Enumerating all `3^k` +regime combinations finds every steady state exactly. On 6000 random networks +(seeds 0–2 of `probe_collapsible.py`, up to 4 collapsible edges plus valves) +every network had **exactly one** steady state, and the solver matched it to +`1e-8` relative. The suite re-checks 100 such networks. + +Theorem 1 does not cover this case: a waterfall edge has three terminals, and its +flow depends on absolute pressure through `p_ext`, not only on `p_src - p_dst`. +The maximum-principle argument also fails. Shifting all pressures by `t > 0` +raises a waterfall's flow, so the junction map is not "diagonally dominant" under +uniform shifts. So uniqueness here is a **conjecture backed by enumeration**, +not a theorem. + +Modelling remark (unchanged here): the code treats collapsible edges as one-way, +so reverse flow through a collapsible vessel is forbidden. In a Starling +resistor the flow can reverse, with the collapse then forming at the other end. +This assumption is not stated elsewhere in the docs. + +## 7. Transients + +`_nonlinear_step` (implicit Euler with kinetic/minor terms) had the same +mixed-unit absolute stopping test (`1e-10`), and it silently returned the last +iterate when Newton did not converge. It now scales the rows the same way, and +it emits a `RuntimeWarning` on non-convergence. The new test +`test_nonlinear_transient_relaxes_to_the_steady_state` guards this. The old code +also passes it, so it is not a regression demonstration. + +## References + +- K. G. Murty, "Note on a Bard-type scheme for solving the complementarity + problem", *Opsearch* 11 (1974) 123–130: finiteness of least-index principal + pivoting for P-matrix LCPs. +- R. W. Cottle, J.-S. Pang, R. E. Stone, *The Linear Complementarity Problem*, + Academic Press 1992: P-matrices and uniqueness of LCP solutions. +- W. Millar, "Some general theorems for non-linear systems possessing resistance", + *Phil. Mag.* 42 (1951) 1150–1160: the content/co-content minimum principle for + networks of monotone resistors. diff --git a/tests/test_flow_complementarity.py b/tests/test_flow_complementarity.py new file mode 100644 index 0000000..ce9f721 --- /dev/null +++ b/tests/test_flow_complementarity.py @@ -0,0 +1,327 @@ +"""Steady flow with one-way valves: the solution must satisfy the complementarity +(KKT) conditions, and it must equal the exact solution found by enumeration. + +Referee: for a linear network the steady problem with ideal valves is the KKT +system of a strictly convex program (minimum content), so it has exactly one +flow solution. It can be found exactly, without any iteration, by trying every +open/closed pattern of the k valves (2^k linear solves) and keeping the pattern +whose solution satisfies + + q_v >= 0, w_v = R_v q_v - (p_src - p_dst - h_v) >= 0, q_v * w_v = 0 + +for every valve v, plus node balance and the two-way edge laws. This uses +nothing from the solver under test except the network arrays. + +All checks are relative: pressure residuals are divided by the largest |p|, +flow residuals by the largest of |q|, |source| and |p|/median(R). An absolute tolerance would be meaningless +here because pressures (~1e3 Pa) and flows (~1e-6 m^3/s) differ by ~9 orders. +""" + +import itertools + +import numpy as np +import pytest + +from vh.graph.flow import FlowNetwork, FlowNodeSpec, VesselSpec + +REL_TOL = 1e-9 + + +def _vessel(i, a, b, r, valve=False): + return VesselSpec(i, a, b, length_m=0.1, radius_m=0.003, resistance_pa_s_m3=r, + gravity_head_pa=0.0, valve=valve) + + +def _arrays(net, sol): + p = np.array([sol.pressure[i] for i in net.node_ids]) + q = np.array([sol.flow[i] for i in net.edge_ids]) + return p, q + + +def kkt_residuals(net, p, q): + """Relative violations of the steady KKT conditions (all ~0 at the solution).""" + pscale = max(1e-30, float(np.max(np.abs(p)))) + # flow scale from the physics as well as the answer: a network may carry no flow + qscale = max(float(np.max(np.abs(q))), pscale / float(np.median(net.R)), + float(np.max(np.abs(net.source), initial=0.0))) + drive = p[net.src] - p[net.dst] - net.h + junction = ~net.is_reservoir + out = {"balance": float(np.max(np.abs((net.B @ q + net.source)[junction]), initial=0.0)) / qscale} + two_way = ~net.valve + out["two_way_law"] = float(np.max(np.abs(drive[two_way] - net.R[two_way] * q[two_way]), + initial=0.0)) / pscale + a = net.R[net.valve] * q[net.valve] # >= 0 (flow only forward) + b = a - drive[net.valve] # >= 0 (blocking pressure) + out["valve_complementarity"] = float(np.max(np.abs(np.minimum(a, b)), initial=0.0)) / pscale + return out + + +def _pattern_solve(net, open_mask): + n, m = net.n, net.m + A = np.zeros((n + m, n + m)) + rhs = np.zeros(n + m) + for i in range(n): + if net.is_reservoir[i]: + A[i, i] = 1.0 + rhs[i] = net.p_fixed[i] + else: + A[i, n:] = net.B[i] + rhs[i] = -net.source[i] + for e in range(m): + row = n + e + if net.valve[e] and not open_mask[e]: + A[row, n + e] = 1.0 + else: + A[row, :n] = net.B[:, e] + A[row, n + e] = net.R[e] + rhs[row] = -net.h[e] + x = np.linalg.solve(A, rhs) + return x[:n], x[n:] + + +def exact_by_enumeration(net): + """All distinct KKT solutions over the 2^k valve patterns (expected: exactly one).""" + valves = np.nonzero(net.valve)[0] + found = [] + for bits in itertools.product([False, True], repeat=len(valves)): + mask = np.ones(net.m, dtype=bool) + mask[valves] = bits + try: + p, q = _pattern_solve(net, mask) + except np.linalg.LinAlgError: + continue + if max(kkt_residuals(net, p, q).values()) < REL_TOL: + if not any(np.allclose(q, q2, rtol=1e-9, atol=1e-9 * np.max(np.abs(q))) for _, q2 in found): + found.append((p, q)) + return found + + +def random_valve_network(rng): + """Random network whose junctions all reach a reservoir through two-way edges, + so every valve pattern gives a nonsingular linear system.""" + n_res, n_junc = int(rng.integers(1, 4)), int(rng.integers(1, 7)) + ids = [f"r{i}" for i in range(n_res)] + [f"j{i}" for i in range(n_junc)] + nodes = [FlowNodeSpec(ids[i], "reservoir", pressure_pa=float(rng.uniform(0, 2000))) + for i in range(n_res)] + nodes += [FlowNodeSpec(ids[n_res + i], "junction", + source_m3_s=float(rng.choice([0.0, rng.uniform(-1, 1) * 1e-6]))) + for i in range(n_junc)] + vessels = [] + + def add(a, b, valve): + vessels.append(_vessel(f"e{len(vessels)}", a, b, float(10 ** rng.uniform(7, 9)), valve)) + + for k in range(1, len(ids)): # spanning tree of two-way edges + a, b = ids[k], ids[int(rng.integers(0, k))] + add(*((a, b) if rng.random() < 0.5 else (b, a)), False) + for _ in range(int(rng.integers(0, 3))): + a, b = rng.choice(len(ids), 2, replace=False) + add(ids[a], ids[b], False) + for _ in range(int(rng.integers(1, 7))): + a, b = rng.choice(len(ids), 2, replace=False) + add(ids[a], ids[b], True) + return nodes, vessels + + +def regression_network(): + """Found by random search: the original active-set loop reported converged=True + here with flows wrong by 87% and node balance violated by 22% of the largest flow, + because its residual mixed m^3/s and Pa under one absolute tolerance.""" + nodes = [ + FlowNodeSpec("r0", "reservoir", pressure_pa=500.0), + FlowNodeSpec("j0", "junction", source_m3_s=8.7e-7), + FlowNodeSpec("j1", "junction"), + FlowNodeSpec("j2", "junction", source_m3_s=4.2e-7), + ] + vessels = [ + _vessel("e0", "r0", "j0", 6.7e8), + _vessel("e1", "j1", "j0", 1.3e8), + _vessel("e2", "j0", "j2", 5.5e8), + _vessel("e3", "r0", "j2", 8.4e8), + _vessel("e4", "j0", "j2", 1.3e8, valve=True), + _vessel("e5", "j0", "j2", 1.7e7, valve=True), + _vessel("e6", "r0", "j1", 1.2e7, valve=True), + ] + return nodes, vessels + + +def _check_against_enumeration(net): + sol = net.steady_state() + p, q = _arrays(net, sol) + truth = exact_by_enumeration(net) + assert len(truth) == 1, "strict convexity: the flow solution is unique" + pt, qt = truth[0] + res = kkt_residuals(net, p, q) + if sol.converged: + assert max(res.values()) < 1e-8, f"converged=True but KKT violated: {res}" + assert sol.converged, f"solver did not converge: {res}" + assert np.max(np.abs(q - qt)) <= 1e-8 * np.max(np.abs(qt)) + assert np.max(np.abs(p - pt)) <= 1e-8 * np.max(np.abs(pt)) + + +def test_regression_network_matches_enumeration(): + net = FlowNetwork.from_specs(*regression_network()) + _check_against_enumeration(net) + + +@pytest.mark.parametrize("seed", range(4)) +def test_random_valve_networks_match_enumeration(seed): + rng = np.random.default_rng(1000 + seed) + for _ in range(50): + net = FlowNetwork.from_specs(*random_valve_network(rng)) + _check_against_enumeration(net) + + +def test_nonlinear_transient_relaxes_to_the_steady_state(): + """Implicit Euler with minor losses must settle on the steady solution. + + After ~100 time constants the transient is gone to far below 1e-12, so the + end state must equal the steady-state solve to the solver tolerance. With an + absolute 1e-10 stopping test on a residual whose node rows are ~1e-6 m^3/s, + each Newton step could stop with a flow error of ~1e-4 relative. + """ + nodes = [FlowNodeSpec("up", "reservoir", pressure_pa=1500.0), + FlowNodeSpec("c", "compartment", compliance_m3_pa=1e-9), + FlowNodeSpec("down", "reservoir", pressure_pa=0.0)] + vessels = [VesselSpec("a", "up", "c", length_m=0.1, radius_m=0.003, resistance_pa_s_m3=2e8, + gravity_head_pa=0.0, minor_loss_coeff=50.0, minor_area_m2=1e-6), + VesselSpec("b", "c", "down", length_m=0.1, radius_m=0.003, resistance_pa_s_m3=1e8, + gravity_head_pa=0.0)] + net = FlowNetwork.from_specs(nodes, vessels) + steady = net.steady_state() + assert steady.converged and steady.method == "nonlinear" + tau = 1e-9 * 1e8 * 2e8 / (1e8 + 2e8) # linearised R_parallel * C + traj = net.simulate(t_end_s=100 * tau, dt_s=tau / 5, initial="zero") + q_end = traj.flow[-1] + q_ss = np.array([steady.flow[e] for e in net.edge_ids]) + assert np.max(np.abs(q_end - q_ss)) <= 1e-9 * np.max(np.abs(q_ss)) + p_c = traj.pressure_at("c")[-1] + assert abs(p_c - steady.pressure["c"]) <= 1e-9 * 1500.0 + + +def test_expanding_tube_follows_the_poiseuille_branch(): + """An expansion makes the edge law R q + c q|q| non-monotone (c < 0). + + Between two reservoirs with 0 < dp < R^2 / (4|c|) the steady equation has + three exact roots (two forward, one reverse); the solver must return the one + that tends to Poiseuille, q = (R - sqrt(R^2 - 4|c| dp)) / (2|c|). Above that + dp no forward root exists at all (see docs/steady_complementarity.md). + """ + from vh.graph.flow import RHO_BLOOD, poiseuille_resistance + r1, r2, length, dp = 0.003, 0.006, 0.1, 30.0 + a1, a2 = np.pi * r1 ** 2, np.pi * r2 ** 2 + R = poiseuille_resistance(length, r1) + c = 0.5 * RHO_BLOOD * (1 / a2 ** 2 - 1 / a1 ** 2) + assert c < 0 and dp < R ** 2 / (4 * abs(c)) + q_exact = (R - np.sqrt(R ** 2 - 4 * abs(c) * dp)) / (2 * abs(c)) + nodes = [FlowNodeSpec("up", "reservoir", pressure_pa=dp), + FlowNodeSpec("down", "reservoir", pressure_pa=0.0)] + vessels = [VesselSpec("e", "up", "down", length_m=length, radius_m=r1, + area_src_m2=a1, area_dst_m2=a2, gravity_head_pa=0.0)] + sol = FlowNetwork.from_specs(nodes, vessels).steady_state() + assert sol.converged + assert abs(sol.flow["e"] - q_exact) <= 1e-10 * q_exact + + +# --------------------------------------------------------------------------- +# collapsible (Starling) edges: three linear regimes per edge +# --------------------------------------------------------------------------- +# A collapsible edge is one-way with q = max(0, (p_src - max(p_dst, p_ext) - h) / R). +# It is piecewise linear with three regimes: +# C closed q = 0 +# N open, normal R q = p_src - p_dst - h +# W open, waterfall R q = p_src - p_ext - h +# Enumerating every regime combination and keeping the self-consistent solutions +# finds every steady state exactly. Uniqueness is NOT implied by the convexity +# argument used for valves (the waterfall flow depends on absolute pressure via +# p_ext), so the enumeration also counts solutions. + +def _steady_conditions_hold(net, p, q, tol=REL_TOL): + """Regime-free check of the full steady conditions, including collapse.""" + pscale = max(1e-30, float(np.max(np.abs(p))), + float(np.max(np.abs(net.external_pressure), initial=0.0))) + qscale = max(float(np.max(np.abs(q))), pscale / float(np.median(net.R)), + float(np.max(np.abs(net.source), initial=0.0))) + junction = ~net.is_reservoir + if np.max(np.abs((net.B @ q + net.source)[junction]), initial=0.0) > tol * qscale: + return False + p_eff = p[net.dst].copy() + coll = net.collapsible + p_eff[coll] = np.maximum(p_eff[coll], net.external_pressure[coll]) + drive = p[net.src] - p_eff - net.h + one_way = net.valve | net.collapsible + if np.max(np.abs(drive[~one_way] - net.R[~one_way] * q[~one_way]), initial=0.0) > tol * pscale: + return False + a = net.R[one_way] * q[one_way] + return np.max(np.abs(np.minimum(a, a - drive[one_way])), initial=0.0) <= tol * pscale + + +def _regime_solve(net, regime): + n, m = net.n, net.m + A = np.zeros((n + m, n + m)) + rhs = np.zeros(n + m) + for i in range(n): + if net.is_reservoir[i]: + A[i, i] = 1.0 + rhs[i] = net.p_fixed[i] + else: + A[i, n:] = net.B[i] + rhs[i] = -net.source[i] + for e, r in enumerate(regime): + row = n + e + if r == "C": + A[row, n + e] = 1.0 + continue + A[row, net.src[e]] = 1.0 + A[row, n + e] = -net.R[e] + if r == "W": + rhs[row] = net.external_pressure[e] + net.h[e] + else: + A[row, net.dst[e]] = -1.0 + rhs[row] = net.h[e] + x = np.linalg.solve(A, rhs) + return x[:n], x[n:] + + +def all_steady_states(net): + choices = ["CNW" if net.collapsible[e] else "CO" if net.valve[e] else "T" + for e in range(net.m)] + found = [] + for regime in itertools.product(*choices): + try: + p, q = _regime_solve(net, regime) + except np.linalg.LinAlgError: + continue + if _steady_conditions_hold(net, p, q): + qs = max(float(np.max(np.abs(q))), float(np.max(np.abs(p))) / float(np.median(net.R))) + if not any(np.max(np.abs(q - q2)) <= 1e-8 * qs for _, q2 in found): + found.append((p, q)) + return found + + +def random_collapsible_network(rng): + nodes, vessels = random_valve_network(rng) + ids = [n.id for n in nodes] + for _ in range(int(rng.integers(1, 4))): + a, b = rng.choice(len(ids), 2, replace=False) + vessels.append(VesselSpec(f"e{len(vessels)}", ids[a], ids[b], length_m=0.1, radius_m=0.003, + resistance_pa_s_m3=float(10 ** rng.uniform(7, 9)), + gravity_head_pa=0.0, collapsible=True, + external_pressure_pa=float(rng.uniform(0, 2000)))) + return nodes, vessels + + +@pytest.mark.parametrize("seed", range(4)) +def test_random_collapsible_networks_match_enumeration(seed): + rng = np.random.default_rng(2000 + seed) + for _ in range(25): + net = FlowNetwork.from_specs(*random_collapsible_network(rng)) + truth = all_steady_states(net) + assert len(truth) == 1, f"{len(truth)} steady states" + sol = net.steady_state() + p, q = _arrays(net, sol) + assert sol.converged + assert _steady_conditions_hold(net, p, q) + pt, qt = truth[0] + qs = max(float(np.max(np.abs(qt))), float(np.max(np.abs(pt))) / float(np.median(net.R))) + assert np.max(np.abs(q - qt)) <= 1e-8 * qs diff --git a/vh/graph/flow.py b/vh/graph/flow.py index 98bbf20..b4f0974 100644 --- a/vh/graph/flow.py +++ b/vh/graph/flow.py @@ -41,12 +41,12 @@ from __future__ import annotations +import warnings from dataclasses import dataclass from typing import Sequence import numpy as np from scipy.linalg import expm -from scipy.optimize import least_squares, root from scipy.special import jv from .algorithms import connected_components @@ -787,72 +787,179 @@ def _residual_steady(self, x: np.ndarray, open_mask: np.ndarray | None = None) - res[n:][closed] = q[closed] return res - def _solve_active(self, open_mask: np.ndarray, x0: np.ndarray) -> np.ndarray: - sol = root(self._residual_steady, x0, args=(open_mask,), method="hybr", tol=1e-10) - x = sol.x - if (not sol.success - or np.max(np.abs(self._residual_steady(x, open_mask))) > 1e-7): - alt = least_squares(self._residual_steady, x0, args=(open_mask,), - xtol=1e-12, ftol=1e-12, gtol=1e-12, max_nfev=20000) - if np.max(np.abs(self._residual_steady(alt.x, open_mask))) < np.max( - np.abs(self._residual_steady(x, open_mask))): - x = alt.x - return x - - def steady_state(self, initial: np.ndarray | None = None) -> FlowSolution: + # -- scaling ------------------------------------------------------------ + def _scales(self, p: np.ndarray | None = None, q: np.ndarray | None = None) -> tuple[float, float]: + """Characteristic pressure (Pa) and flow (m^3/s) of the problem. + + Node rows of the residual are flows (m^3/s) and edge rows are pressures + (Pa); in physiological units they differ by ~9 orders of magnitude, so + every tolerance is applied to residuals divided by these scales. When a + solution (p, q) is given, its own magnitude is included, so the scales + never fall below the size of the answer. + """ + p_s = max(float(np.max(np.abs(self.p_fixed[self.is_reservoir]), initial=0.0)), + float(np.max(np.abs(self.h), initial=0.0)), + float(np.max(np.abs(self.external_pressure), initial=0.0))) + if p is not None: + p_s = max(p_s, float(np.max(np.abs(p), initial=0.0))) + r_s = float(np.median(self.R)) if self.m else 1.0 + q_s = max(float(np.max(np.abs(self.source), initial=0.0)), p_s / r_s) + if q is not None: + q_s = max(q_s, float(np.max(np.abs(q), initial=0.0))) + p_s = max(p_s, q_s * r_s, 1e-300) + return p_s, max(q_s, 1e-300) + + def _scaled_residual(self, x: np.ndarray, open_mask: np.ndarray, + p_s: float, q_s: float) -> np.ndarray: + n = self.n + res = self._residual_steady(x, open_mask) + out = np.empty_like(res) + out[:n] = np.where(self.is_reservoir, res[:n] / p_s, res[:n] / q_s) + closed = (self.valve | self.collapsible) & ~open_mask + out[n:] = np.where(closed, res[n:] / q_s, res[n:] / p_s) + return out + + def _steady_jacobian(self, x: np.ndarray, open_mask: np.ndarray) -> np.ndarray: + """Analytic Jacobian of :meth:`_residual_steady` for a fixed open/closed pattern.""" + n, m = self.n, self.m + p, q = x[:n], x[n:] + J = np.zeros((n + m, n + m)) + for i in range(n): + if self.is_reservoir[i]: + J[i, i] = 1.0 + else: + J[i, n:] = self.B[i] + d_drop = self._edge_drop_derivative(q) + closed = (self.valve | self.collapsible) & ~open_mask + for e in range(m): + row = n + e + if closed[e]: + J[row, n + e] = 1.0 + continue + J[row, self.src[e]] += 1.0 + # a collapsed tube (downstream below external) does not feel p_dst + if not (self.collapsible[e] and p[self.dst[e]] < self.external_pressure[e]): + J[row, self.dst[e]] -= 1.0 + J[row, n + e] = -d_drop[e] + return J + + def _solve_active(self, open_mask: np.ndarray, x0: np.ndarray, + tol: float = 1e-13, max_iter: int = 60) -> tuple[np.ndarray, bool]: + """Solve the equations of one open/closed pattern by damped Newton. + + Works on the scaled residual, so the stopping test means the same thing + for pressures and flows. For a linear network the first full step is + exact. Returns (x, success). + """ + x = np.asarray(x0, dtype=float).copy() + p_s, q_s = self._scales(x[:self.n], x[self.n:]) + row_scale = np.r_[np.where(self.is_reservoir, p_s, q_s), + np.where((self.valve | self.collapsible) & ~open_mask, q_s, p_s)] + col_scale = np.r_[np.full(self.n, p_s), np.full(self.m, q_s)] + r = self._scaled_residual(x, open_mask, p_s, q_s) + norm = float(np.max(np.abs(r), initial=0.0)) + for _ in range(max_iter): + if norm < tol: + return x, True + J = self._steady_jacobian(x, open_mask) * col_scale[None, :] / row_scale[:, None] + try: + dy = np.linalg.solve(J, -r) + except np.linalg.LinAlgError: + dy, *_ = np.linalg.lstsq(J, -r, rcond=None) + dx = dy * col_scale + step = 1.0 + for _ in range(30): + trial = x + step * dx + r_trial = self._scaled_residual(trial, open_mask, p_s, q_s) + n_trial = float(np.max(np.abs(r_trial), initial=0.0)) + if n_trial < norm or n_trial < tol: + break + step *= 0.5 + else: + return x, False + x, r, norm = trial, r_trial, n_trial + return x, norm < tol + + def _one_way_violations(self, x: np.ndarray, open_mask: np.ndarray, + p_s: float, q_s: float, tol: float) -> np.ndarray: + """Indices of one-way edges whose open/closed state contradicts the solution. + + Open edge: must carry q >= 0. Closed edge: its driving pressure + p_src - p_dst(effective) - h must be <= 0 (otherwise it would open). + """ + p, q = x[:self.n], x[self.n:] + one_way = self.valve | self.collapsible + drive = p[self.src] - self._effective_downstream(p) - self.h + bad_open = one_way & open_mask & (q < -tol * q_s) + bad_closed = one_way & ~open_mask & (drive > tol * p_s) + return np.nonzero(bad_open | bad_closed)[0] + + def steady_state(self, initial: np.ndarray | None = None, + tol: float = 1e-10) -> FlowSolution: """Solve the steady state. Linear R networks are solved exactly by a square linear system. - Networks with kinetic terms or minor losses use a nonlinear root - finder. Collapsible veins and valves add a complementarity condition - (flow is one-way, and a closed tube carries no flow); those are solved - by an active-set loop: open edges obey the pressure-flow law, closed - edges carry q = 0, and an edge is opened/closed when the sign of its - driving pressure or flow changes. + Networks with kinetic terms or minor losses use Newton's method on the + scaled residual. Collapsible veins and valves add a complementarity + condition (flow is one-way, and a closed tube carries no flow): + + q_e >= 0, blocking pressure w_e >= 0, q_e * w_e = 0. + + It is solved by single principal pivots with Murty's least-index rule: + solve the equations of the current open/closed pattern, then flip only + the lowest-index edge whose state contradicts the solution. For linear + edges with valves this is a P-matrix linear complementarity problem + (the minimum-content program is strictly convex), for which the rule is + finite and the solution is unique (Murty 1974). + + ``converged`` is True only if the scaled residual is below ``tol`` *and* + every one-way edge satisfies complementarity; ``residual_norm`` is the + largest scaled (dimensionless) residual. Node/edge residuals are in + physical units (m^3/s and Pa; m^3/s for the q=0 row of a closed edge). """ one_way = self.valve | self.collapsible + open_mask = np.ones(self.m, dtype=bool) + pivots_ok = True if not np.any(one_way) and self._is_linear(): p, q = self._linear_steady() - open_mask = np.ones(self.m, dtype=bool) method = "linear" else: if initial is None: p0, q0 = self._linear_steady() - x0 = np.r_[p0, q0] + x = np.r_[p0, q0] else: - x0 = np.asarray(initial, dtype=float) - open_mask = np.ones(self.m, dtype=bool) + x = np.asarray(initial, dtype=float) method = "nonlinear" if not np.any(one_way) else "active-set" - for _ in range(20): - x = self._solve_active(open_mask, x0) - p, q = x[:self.n], x[self.n:] - changed = False - for e in np.nonzero(one_way)[0]: - if open_mask[e] and q[e] < -1e-12: - open_mask[e] = False - changed = True - elif not open_mask[e]: - p_dst = (max(p[self.dst[e]], self.external_pressure[e]) - if self.collapsible[e] else p[self.dst[e]]) - if p[self.src[e]] - p_dst - self.h[e] > 1e-9: - open_mask[e] = True - changed = True - x0 = x - if not changed: + n_one_way = int(np.count_nonzero(one_way)) + max_pivots = 50 + 10 * n_one_way + for _ in range(max_pivots + 1): + x, _ok = self._solve_active(open_mask, x) + p_s, q_s = self._scales(x[:self.n], x[self.n:]) + bad = self._one_way_violations(x, open_mask, p_s, q_s, tol) + if bad.size == 0: break - # A closed one-way edge has q=0 by construction; clamp against tiny - # numerical negatives before reporting. + open_mask[bad[0]] = ~open_mask[bad[0]] # Murty: least index only + else: + pivots_ok = False + p, q = x[:self.n], x[self.n:] + x = np.r_[p, q] + p_s, q_s = self._scales(p, q) + res = self._residual_steady(x, open_mask) + res_scaled = self._scaled_residual(x, open_mask, p_s, q_s) + norm = float(np.max(np.abs(res_scaled), initial=0.0)) + compl_ok = self._one_way_violations(x, open_mask, p_s, q_s, tol).size == 0 + # Closed edges carry q = 0 exactly (a linear row); open one-way edges may + # carry a negative q only within tolerance, which is clamped for reporting. q_out = q.copy() if np.any(one_way): q_out[one_way] = np.maximum(q_out[one_way], 0.0) - res = self._residual_steady(np.r_[p, q], open_mask) return FlowSolution( pressure={nid: float(p[i]) for i, nid in enumerate(self.node_ids)}, flow={eid: float(q_out[i]) for i, eid in enumerate(self.edge_ids)}, node_residual={nid: float(res[i]) for i, nid in enumerate(self.node_ids)}, edge_residual={eid: float(res[self.n + i]) for i, eid in enumerate(self.edge_ids)}, - converged=bool(np.max(np.abs(res)) < 1e-6), - residual_norm=float(np.max(np.abs(res))), + converged=bool(norm < tol and compl_ok and pivots_ok), + residual_norm=norm, method=method, ) @@ -896,13 +1003,17 @@ def _linear_step(self, dt: float, p_old: np.ndarray, q_old: np.ndarray): return x[:n], x[n:] def _nonlinear_step(self, dt: float, p_old: np.ndarray, q_old: np.ndarray, - tol: float = 1e-10, max_iter: int = 30): + tol: float = 1e-12, max_iter: int = 30): if np.any(self.collapsible) or np.any(self.valve): raise NotImplementedError( "transient collapse/valve edges are not implemented; use the " "steady-state solver for Starling-resistor / valve problems" ) n, m = self.n, self.m + # node rows are flows (m^3/s), edge rows pressures (Pa): test them relative + # to their own scales, not against one absolute number + p_s, q_s = self._scales(p_old, q_old) + row_scale = np.r_[np.where(self.is_reservoir, p_s, q_s), np.full(m, p_s)] def residual(x): p, q = x[:n], x[n:] @@ -911,7 +1022,7 @@ def residual(x): self.C * (p - p_old) / dt - self.B @ q - self.source) res[n:] = (self.L * (q - q_old) / dt + self.B.T @ p + self.h + self._edge_drop(q)) - return res + return res / row_scale x = np.r_[p_old, q_old] for _ in range(max_iter): @@ -930,7 +1041,7 @@ def residual(x): J[row, :n] = self.B[:, e] J[row, n + e] = self.L[e] / dt + self._edge_drop_derivative(x[n:])[e] try: - dx = np.linalg.solve(J, -r) + dx = np.linalg.solve(J / row_scale[:, None], -r) # r is row-scaled except np.linalg.LinAlgError: break # mild damping keeps the Newton step physical for large dt @@ -943,6 +1054,11 @@ def residual(x): step *= 0.5 else: x = x + 0.1 * dx + final = float(np.max(np.abs(residual(x)))) + if final >= tol: + warnings.warn(f"implicit Euler Newton step did not converge " + f"(scaled residual {final:.1e} after {max_iter} iterations)", + RuntimeWarning, stacklevel=3) return x[:n], x[n:] def simulate(self, t_end_s: float, dt_s: float, p0=None, q0=None, From 3752d332d23789a841cb858b11ef842c8768bf04 Mon Sep 17 00:00:00 2001 From: ahrazzle <38987266+ahrazzle@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:51:33 -0600 Subject: [PATCH 2/2] Report the PBPK terminal half-life alongside ln2*Vss/CL summary() printed ln2*Vss/CL as t1/2. That is ln2 * mean residence time, which equals the elimination half-life only for a one-compartment model; for reference-male midazolam it is 2.61 h against the model's own terminal half-life of 4.14 h (slowest eigenvalue of the non-sink block of M, terminal mode 71% adipose). - DerivedParams.effective_half_life_h names ln2*Vss/CL correctly; half_life_h remains as a documented alias with the same value. - PBPKModel.terminal_half_life_h() returns ln2 / -max Re(eig) on the non-sink block; summary() now prints both quantities. - New test referees the eigenvalue value against the fitted terminal log-slope of a simulated IV curve (independent of eig). - Regenerated docs/validation_body and web/data/body.json summaries (all five web individuals); JS engine checks still pass. No solver behavior changes: M, CL and Vss are untouched. --- docs/validation_body.json | 4 ++-- docs/validation_body.md | 4 ++-- tests/test_body.py | 17 ++++++++++++++++ vh/body/pbpk.py | 41 +++++++++++++++++++++++++++++++++++++-- web/data/body.json | 2 +- 5 files changed, 61 insertions(+), 7 deletions(-) diff --git a/docs/validation_body.json b/docs/validation_body.json index 4699c67..71f7216 100644 --- a/docs/validation_body.json +++ b/docs/validation_body.json @@ -5,8 +5,8 @@ "clint_scale_middle_out": 1.1273433145411291, "iv_infusion_h": 0.03333333333333333, "reference_individual": { - "bottom_up": "midazolam in ICRP 89 reference male: Vss 64 L (0.88 L/kg), B:P 0.60, fu 0.031, CLint,hep 760 L/h -> CL_plasma 17.1 L/h (hepatic blood 28.2, renal 0.24), t1/2 ~2.6 h | oral: ka 1.65/h, Fa 0.98, Fg 0.49, Fh 0.72", - "middle_out": "midazolam in ICRP 89 reference male: Vss 64 L (0.88 L/kg), B:P 0.60, fu 0.031, CLint,hep 856 L/h -> CL_plasma 18.6 L/h (hepatic blood 30.7, renal 0.24), t1/2 ~2.4 h | oral: ka 1.65/h, Fa 0.98, Fg 0.46, Fh 0.69" + "bottom_up": "midazolam in ICRP 89 reference male: Vss 64 L (0.88 L/kg), B:P 0.60, fu 0.031, CLint,hep 760 L/h -> CL_plasma 17.1 L/h (hepatic blood 28.2, renal 0.24), t1/2,terminal ~4.1 h (effective ln2*Vss/CL ~2.6 h) | oral: ka 1.65/h, Fa 0.98, Fg 0.49, Fh 0.72", + "middle_out": "midazolam in ICRP 89 reference male: Vss 64 L (0.88 L/kg), B:P 0.60, fu 0.031, CLint,hep 856 L/h -> CL_plasma 18.6 L/h (hepatic blood 30.7, renal 0.24), t1/2,terminal ~3.9 h (effective ln2*Vss/CL ~2.4 h) | oral: ka 1.65/h, Fa 0.98, Fg 0.46, Fh 0.69" }, "summary": { "bottom_up": { diff --git a/docs/validation_body.md b/docs/validation_body.md index 69dc82f..33fb1cb 100644 --- a/docs/validation_body.md +++ b/docs/validation_body.md @@ -7,9 +7,9 @@ Generated by `scripts/validate_body.py`. Observed data: plasma concentration–t - **Bottom-up**: no clinical data used. Liver clearance is scaled from in vitro microsomal kinetics (CYP3A4 Vmax 850 pmol/min/mg, Km 4 µM; UGT1A4 276 pmol/min/mg, Km 37.8 µM; 32 mg microsomal protein/g liver). Tissue distribution comes from physicochemistry (Rodgers & Rowland). Gut-wall first pass from the Qgut model. - **Middle-out**: one multiplier on intrinsic clearance (×1.13) fitted to the IV datasets only, then the oral datasets are predicted blind. Under-prediction of clearance by microsomal IVIVE is a well-known systematic effect. -Reference male, bottom-up: midazolam in ICRP 89 reference male: Vss 64 L (0.88 L/kg), B:P 0.60, fu 0.031, CLint,hep 760 L/h -> CL_plasma 17.1 L/h (hepatic blood 28.2, renal 0.24), t1/2 ~2.6 h | oral: ka 1.65/h, Fa 0.98, Fg 0.49, Fh 0.72 +Reference male, bottom-up: midazolam in ICRP 89 reference male: Vss 64 L (0.88 L/kg), B:P 0.60, fu 0.031, CLint,hep 760 L/h -> CL_plasma 17.1 L/h (hepatic blood 28.2, renal 0.24), t1/2,terminal ~4.1 h (effective ln2*Vss/CL ~2.6 h) | oral: ka 1.65/h, Fa 0.98, Fg 0.49, Fh 0.72 -Reference male, middle-out: midazolam in ICRP 89 reference male: Vss 64 L (0.88 L/kg), B:P 0.60, fu 0.031, CLint,hep 856 L/h -> CL_plasma 18.6 L/h (hepatic blood 30.7, renal 0.24), t1/2 ~2.4 h | oral: ka 1.65/h, Fa 0.98, Fg 0.46, Fh 0.69 +Reference male, middle-out: midazolam in ICRP 89 reference male: Vss 64 L (0.88 L/kg), B:P 0.60, fu 0.031, CLint,hep 856 L/h -> CL_plasma 18.6 L/h (hepatic blood 30.7, renal 0.24), t1/2,terminal ~3.9 h (effective ln2*Vss/CL ~2.4 h) | oral: ka 1.65/h, Fa 0.98, Fg 0.46, Fh 0.69 ## Accuracy diff --git a/tests/test_body.py b/tests/test_body.py index 5907507..736c735 100644 --- a/tests/test_body.py +++ b/tests/test_body.py @@ -38,6 +38,23 @@ def test_iv_auc_equals_dose_over_clearance(mdz): assert auc == pytest.approx(dose / cl, rel=0.01) +def test_terminal_half_life_matches_simulated_terminal_slope(mdz): + """terminal_half_life_h() (eigenvalue) vs an independent referee: the + log-linear slope of the simulated IV plasma curve's terminal phase. + ln2*Vss/CL is only the effective (MRT) half-life and must be shorter.""" + sim = mdz.simulate([Dose(0, 5.0, "iv")], t_end_h=120, dt_h=0.25) + t, c = sim["time_h"], sim["plasma"] + late = (t >= 60) & (c > 0) + slope = np.polyfit(t[late], np.log(c[late]), 1)[0] + fitted = np.log(2) / -slope + assert fitted == pytest.approx(mdz.terminal_half_life_h(), rel=0.02) + # midazolam reference male: effective ~2.6 h, terminal ~4.1 h (issue #4) + assert mdz.p.effective_half_life_h == pytest.approx(2.61, rel=0.02) + assert mdz.terminal_half_life_h() == pytest.approx(4.14, rel=0.02) + assert mdz.p.half_life_h == mdz.p.effective_half_life_h # alias unchanged + assert "t1/2,terminal" in mdz.summary() + + def test_steady_state_infusion(mdz): rate = 1.0 # mg/h sim = mdz.simulate([Dose(0, rate * 100, "iv", 100.0)], t_end_h=99, dt_h=1.0) diff --git a/vh/body/pbpk.py b/vh/body/pbpk.py index 596b0ec..3abc1a1 100644 --- a/vh/body/pbpk.py +++ b/vh/body/pbpk.py @@ -68,9 +68,27 @@ def cl_total_plasma_l_h(self): return self.cl_hep_blood_l_h * self.bp + self.cl_renal_l_h @property - def half_life_h(self): + def effective_half_life_h(self): + """ln2 * Vss / CL = ln2 * mean residence time. + + This equals the elimination half-life only for a one-compartment + model. For this multi-compartment model the terminal half-life -- + the one a clinical terminal slope measures -- is longer and is set + by the slowest eigenvalue of the system matrix; see + PBPKModel.terminal_half_life_h(). + """ return np.log(2) * self.vss_l / self.cl_total_plasma_l_h + @property + def half_life_h(self): + """Backward-compatible alias for effective_half_life_h (ln2*Vss/CL). + + Not the model's terminal half-life; prefer effective_half_life_h + for this quantity and PBPKModel.terminal_half_life_h() for the + terminal slope. + """ + return self.effective_half_life_h + class PBPKModel: """Builds the linear system dx/dt = M x + u(t) for one compound in one individual.""" @@ -248,12 +266,31 @@ def apply_boluses(tt, x): def mass_balance(self, x) -> float: return float(np.sum(x)) + # Absorbing accumulator states: drug only flows in, so they carry the + # matrix's zero eigenvalues and must be excluded from decay analysis. + SINKS = ("elim_hepatic", "elim_renal", "elim_gut_wall", "feces") + + def terminal_half_life_h(self) -> float: + """Half-life of the model's slowest decay mode, ln2 / -max Re(eig). + + Computed from the eigenvalues of M restricted to the non-sink + states. This is the half-life of the terminal log-linear phase of + the plasma curve -- the quantity clinical terminal half-lives + measure. Returns inf if the non-sink system has no decaying mode + (e.g. all clearances zero). + """ + keep = [i for i, n in enumerate(self.names) if n not in self.SINKS] + lam = np.linalg.eigvals(self.M[np.ix_(keep, keep)]) + slowest = float(np.max(lam.real)) + return float(np.log(2) / -slowest) if slowest < 0 else float("inf") + def summary(self) -> str: p = self.p return (f"{self.compound.name} in {self.ind.label}: Vss {p.vss_l:.0f} L ({p.vss_l / self.ind.body_mass:.2f} L/kg), " f"B:P {p.bp:.2f}, fu {p.fu:.3f}, CLint,hep {p.clint_hep_l_h:.0f} L/h -> CL_plasma " f"{p.cl_total_plasma_l_h:.1f} L/h (hepatic blood {p.cl_hep_blood_l_h:.1f}, renal {p.cl_renal_l_h:.2f}), " - f"t1/2 ~{p.half_life_h:.1f} h | oral: ka {p.ka_h:.2f}/h, Fa {p.fa:.2f}, Fg {p.fg:.2f}, " + f"t1/2,terminal ~{self.terminal_half_life_h():.1f} h (effective ln2*Vss/CL ~{p.effective_half_life_h:.1f} h) | " + f"oral: ka {p.ka_h:.2f}/h, Fa {p.fa:.2f}, Fg {p.fg:.2f}, " f"Fh {1 - p.cl_hep_blood_l_h / self.ind.liver_flow_total:.2f}") diff --git a/web/data/body.json b/web/data/body.json index e0d5cd6..d2c9d1e 100644 --- a/web/data/body.json +++ b/web/data/body.json @@ -1 +1 @@ -{"compound":{"name":"midazolam","mw":325.78,"logp":2.897,"fu":0.031,"target":{"name":"GABA-A receptor (benzodiazepine site, GABRG2)","tissue":"brain","kd_nm":1.8,"koff_per_h":60.0,"source":"Buhr 1997 (Kd 1.8 nM), via Open Systems Pharmacology Midazolam-Model (github.com/Open-Systems-Pharmacology/Midazolam-Model)"},"sources":{"mw":"Open Systems Pharmacology Midazolam-Model (github.com/Open-Systems-Pharmacology/Midazolam-Model)","logp":"lipophilicity 2.897 (fitted value in Open Systems Pharmacology Midazolam-Model (github.com/Open-Systems-Pharmacology/Midazolam-Model))","pka":"basic pKa 6.2 (Open Systems Pharmacology Midazolam-Model (github.com/Open-Systems-Pharmacology/Midazolam-Model); acidic pKa 10.95 ignored at physiological pH)","fu":"0.031, Gertz 2010, via Open Systems Pharmacology Midazolam-Model (github.com/Open-Systems-Pharmacology/Midazolam-Model)","bp":"predicted from red-cell partitioning (Rodgers & Rowland); literature ~0.6","peff":"ASSUMED 4e-4 cm/s (BCS class I high permeability; not measured)","gut_metabolism":"Qgut model (Yang 2007) with intestinal CYP3A4 70.5 nmol vs hepatic 137 pmol/mg"}},"constants":{"n_transit":7,"si_transit_h":3.32,"gastric_half_life_h":0.25,"tissues":["lung","heart","brain","muscle","adipose","skin","bone","kidney","liver","gut","spleen","pancreas","rest"],"portal":["gut","spleen","pancreas"]},"clint_scale":1.1273433145411291,"individuals":{"ref_male":{"label":"Reference man (ICRP 89)","sex":"male","age":30.0,"body_mass":73.0,"height":176.0,"volumes":{"lung":0.5,"heart":0.33,"brain":1.45,"muscle":29.0,"adipose":18.2,"skin":3.3,"bone":10.5,"kidney":0.31,"liver":1.8,"gut":1.17,"spleen":0.15,"pancreas":0.14,"rest":1.46},"v_arterial":1.325,"v_venous":3.9749999999999996,"flows":{"lung":390.0,"heart":15.6,"brain":46.8,"muscle":66.3,"adipose":19.5,"skin":19.5,"bone":19.5,"kidney":74.1,"liver":25.35,"gut":58.5,"spleen":11.7,"pancreas":3.9,"rest":29.25},"cardiac_output":390.0,"liver_flow_total":99.45000000000002,"gfr":7.862359666296279,"kp":{"lung":0.7575776381893871,"heart":0.5543702858165431,"brain":0.9729669343541709,"muscle":0.35832561487381903,"adipose":1.9550643053194905,"skin":1.5263040291073704,"bone":0.47147408134646995,"kidney":0.5935042666201106,"liver":0.6456631725164685,"gut":1.101135989748967,"spleen":0.4511271832304625,"pancreas":1.069900452891875,"rest":0.35832561487381903},"bp":0.5969537621514333,"fu":0.031,"clint_hep":856.3686334962259,"cl_renal":0.24373314965518464,"ka":1.645714285714286,"fa":0.982374560767999,"fg":0.45678960782801,"q_gut":6.219895287958116,"clint_gut":7.396647604804071,"vss":64.47240202577142,"summary":"midazolam in Reference man (ICRP 89): Vss 64 L (0.88 L/kg), B:P 0.60, fu 0.031, CLint,hep 856 L/h -> CL_plasma 18.6 L/h (hepatic blood 30.7, renal 0.24), t1/2 ~2.4 h | oral: ka 1.65/h, Fa 0.98, Fg 0.46, Fh 0.69"},"ref_female":{"label":"Reference woman (ICRP 89)","sex":"female","age":30.0,"body_mass":60.0,"height":163.0,"volumes":{"lung":0.42,"heart":0.25,"brain":1.3,"muscle":17.5,"adipose":22.5,"skin":2.3,"bone":7.8,"kidney":0.275,"liver":1.4,"gut":1.06,"spleen":0.13,"pancreas":0.12,"rest":1.2},"v_arterial":0.975,"v_venous":2.925,"flows":{"lung":354.0,"heart":17.7,"brain":42.48,"muscle":42.48,"adipose":30.09,"skin":17.7,"bone":17.7,"kidney":60.18,"liver":23.01,"gut":60.18,"spleen":10.62,"pancreas":3.54,"rest":28.32},"cardiac_output":354.0,"liver_flow_total":97.35000000000001,"gfr":6.288050333680336,"kp":{"lung":0.7575776381893871,"heart":0.5543702858165431,"brain":0.9729669343541709,"muscle":0.35832561487381903,"adipose":1.9550643053194905,"skin":1.5263040291073704,"bone":0.47147408134646995,"kidney":0.5935042666201106,"liver":0.6456631725164685,"gut":1.101135989748967,"spleen":0.4511271832304625,"pancreas":1.069900452891875,"rest":0.35832561487381903},"bp":0.6417366774679406,"fu":0.031,"clint_hep":666.0644927192869,"cl_renal":0.19492956034409042,"ka":1.645714285714286,"fa":0.982374560767999,"fg":0.45678960782801,"q_gut":6.219895287958116,"clint_gut":7.396647604804071,"vss":64.52341905770191,"summary":"midazolam in Reference woman (ICRP 89): Vss 65 L (1.08 L/kg), B:P 0.64, fu 0.031, CLint,hep 666 L/h -> CL_plasma 15.7 L/h (hepatic blood 24.2, renal 0.19), t1/2 ~2.8 h | oral: ka 1.65/h, Fa 0.98, Fg 0.46, Fh 0.75"},"obese_female":{"label":"Obese woman, 136 kg","sex":"female","age":36.0,"body_mass":136.0,"height":163.0,"volumes":{"lung":0.6396058433472983,"heart":0.38071776389720136,"brain":1.9797323722654472,"muscle":26.650243472804096,"adipose":81.90270418629515,"skin":3.502603427854252,"bone":11.878394233592681,"kidney":0.4187895402869215,"liver":2.1320194778243273,"gut":1.6142433189241339,"spleen":0.19797323722654472,"pancreas":0.18274452667065663,"rest":2.72},"v_arterial":1.4679066727827077,"v_venous":4.403720018348123,"flows":{"lung":532.9630381180293,"heart":26.648151905901468,"brain":63.95556457416352,"muscle":63.95556457416352,"adipose":45.30185824003249,"skin":26.648151905901468,"bone":26.648151905901468,"kidney":90.60371648006497,"liver":34.642597477671906,"gut":90.60371648006497,"spleen":15.98889114354088,"pancreas":5.329630381180293,"rest":42.63704304944235},"cardiac_output":532.9630381180293,"liver_flow_total":146.56483548245805,"gfr":9.466944660105536,"kp":{"lung":0.7575776381893871,"heart":0.5543702858165431,"brain":0.9729669343541709,"muscle":0.35832561487381903,"adipose":1.9550643053194905,"skin":1.5263040291073704,"bone":0.47147408134646995,"kidney":0.5935042666201106,"liver":0.6456631725164685,"gut":1.101135989748967,"spleen":0.4511271832304625,"pancreas":1.069900452891875,"rest":0.35832561487381903},"bp":0.6417366774679406,"fu":0.031,"clint_hep":1014.3303371176424,"cl_renal":0.29347528446327165,"ka":1.645714285714286,"fa":0.982374560767999,"fg":0.45678960782801,"q_gut":6.219895287958116,"clint_gut":7.396647604804071,"vss":191.67286960383998,"summary":"midazolam in Obese woman, 136 kg: Vss 192 L (1.41 L/kg), B:P 0.64, fu 0.031, CLint,hep 1014 L/h -> CL_plasma 23.9 L/h (hepatic blood 36.7, renal 0.29), t1/2 ~5.6 h | oral: ka 1.65/h, Fa 0.98, Fg 0.46, Fh 0.75"},"elderly_male":{"label":"Older man, 75 y","sex":"male","age":75.0,"body_mass":78.0,"height":172.0,"volumes":{"lung":0.5081460227790228,"heart":0.335376375034155,"brain":1.473623466059166,"muscle":29.472469321183322,"adipose":22.968845158926545,"skin":3.35376375034155,"bone":10.671066478359478,"kidney":0.3150505341229941,"liver":1.829325682004482,"gut":1.1890616933029132,"spleen":0.1524438068337068,"pancreas":0.1422808863781264,"rest":1.56},"v_arterial":1.3539718622853738,"v_venous":4.061915586856122,"flows":{"lung":398.52756701229873,"heart":15.94110268049195,"brain":47.82330804147585,"muscle":67.7496863920908,"adipose":19.926378350614936,"skin":19.926378350614936,"bone":19.926378350614936,"kidney":75.72023773233676,"liver":25.90429185579942,"gut":59.779135051844804,"spleen":11.955827010368962,"pancreas":3.9852756701229874,"rest":29.889567525922402},"cardiac_output":398.52756701229873,"liver_flow_total":101.62452958813617,"gfr":5.934274535345345,"kp":{"lung":0.7575776381893871,"heart":0.5543702858165431,"brain":0.9729669343541709,"muscle":0.35832561487381903,"adipose":1.9550643053194905,"skin":1.5263040291073704,"bone":0.47147408134646995,"kidney":0.5935042666201106,"liver":0.6456631725164685,"gut":1.101135989748967,"spleen":0.4511271832304625,"pancreas":1.069900452891875,"rest":0.35832561487381903},"bp":0.5969537621514333,"fu":0.031,"clint_hep":870.3206302876279,"cl_renal":0.1839625105957057,"ka":1.645714285714286,"fa":0.982374560767999,"fg":0.45678960782801,"q_gut":6.219895287958116,"clint_gut":7.396647604804071,"vss":74.31142501397069,"summary":"midazolam in Older man, 75 y: Vss 74 L (0.95 L/kg), B:P 0.60, fu 0.031, CLint,hep 870 L/h -> CL_plasma 18.9 L/h (hepatic blood 31.3, renal 0.18), t1/2 ~2.7 h | oral: ka 1.65/h, Fa 0.98, Fg 0.46, Fh 0.69"},"small_female":{"label":"Small woman, 48 kg","sex":"female","age":25.0,"body_mass":48.0,"height":155.0,"volumes":{"lung":0.3516315101729103,"heart":0.20930447034101804,"brain":1.0883832457732938,"muscle":14.651312923871263,"adipose":16.453697277713363,"skin":1.9256011271373659,"bone":6.5302994746397625,"kidney":0.23023491737511986,"liver":1.172105033909701,"gut":0.8874509542459166,"spleen":0.10883832457732938,"pancreas":0.10046614576368866,"rest":0.96},"v_arterial":0.8503968759501455,"v_venous":2.5511906278504366,"flows":{"lung":308.75948111420666,"heart":15.437974055710333,"brain":37.0511377337048,"muscle":37.0511377337048,"adipose":26.244555894707563,"skin":15.437974055710333,"bone":15.437974055710333,"kidney":52.48911178941513,"liver":20.069366272423434,"gut":52.48911178941513,"spleen":9.2627844334262,"pancreas":3.0875948111420666,"rest":24.700758489136533},"cardiac_output":308.75948111420666,"liver_flow_total":84.90885730640683,"gfr":5.484449599568234,"kp":{"lung":0.7575776381893871,"heart":0.5543702858165431,"brain":0.9729669343541709,"muscle":0.35832561487381903,"adipose":1.9550643053194905,"skin":1.5263040291073704,"bone":0.47147408134646995,"kidney":0.5935042666201106,"liver":0.6456631725164685,"gut":1.101135989748967,"spleen":0.4511271832304625,"pancreas":1.069900452891875,"rest":0.35832561487381903},"bp":0.6417366774679406,"fu":0.031,"clint_hep":557.6411034462768,"cl_renal":0.17001793758661524,"ka":1.645714285714286,"fa":0.982374560767999,"fg":0.45678960782801,"q_gut":6.219895287958116,"clint_gut":7.396647604804071,"vss":49.431417313041464,"summary":"midazolam in Small woman, 48 kg: Vss 49 L (1.03 L/kg), B:P 0.64, fu 0.031, CLint,hep 558 L/h -> CL_plasma 13.3 L/h (hepatic blood 20.4, renal 0.17), t1/2 ~2.6 h | oral: ka 1.65/h, Fa 0.98, Fg 0.46, Fh 0.76"}},"observed":[{"study":"Olkkola 1993","route":"IV","dose":"0.05 mg/kg","n":6.0,"reference":"https://www.ncbi.nlm.nih.gov/pubmed/8453848","time":[0.25,0.5,0.75,1.0,1.5,2.0,3.0,4.0,6.0,7.0,8.0],"conc_ng_ml":[63.830960000000005,52.0174429,37.62138,32.44995,24.32209,17.3012409,11.74518,7.2971140000000005,5.0415980000000005,3.176075,2.7865699999999998]},{"study":"Olkkola 1993","route":"PO","dose":"15 mg","n":12.0,"reference":"https://www.ncbi.nlm.nih.gov/pubmed/8453848","time":[0.25,0.5,0.75,1.0,1.5,2.0,3.0,4.0,5.0,6.0,18.0],"conc_ng_ml":[0.3656307,27.4223015,44.24132,47.5319922,48.263248100000006,46.800732599999996,36.197442599999995,21.93784,14.2596,8.775137,0.7312614]},{"study":"Hohmann 2015","route":"IV","dose":"0.001 mg","n":16.0,"reference":"https://www.ncbi.nlm.nih.gov/pubmed/25588320","time":[0.08,0.25,0.5,0.75,1.0,1.5,2.0,2.5,3.0,4.0,6.0,8.0,10.0,24.0],"conc_ng_ml":[0.04187355,0.0192918087,0.01438149,0.0110110705,0.00913471649,0.006811424999999999,0.0050790309999999995,0.0038899720000000002,0.00331537512,0.002222763,0.00111182,0.0008085315,0.0005008498,0.0001050899]},{"study":"Backman 1998","route":"PO","dose":"15 mg","n":9.0,"reference":"https://www.ncbi.nlm.nih.gov/pubmed/9591931","time":[0.0,0.5,1.0,1.5,2.0,3.0,4.0,5.0,6.0,8.0,10.0],"conc_ng_ml":[0.9999998999999999,25.1012184,47.368422200000005,53.84615,54.25101,45.748990000000006,27.12551,18.62348,14.574899299999998,8.906882,6.477733000000001]},{"study":"Kharasch 2011","route":"IV","dose":"1 mg","n":12.0,"reference":"https://www.ncbi.nlm.nih.gov/pubmed/21562488","time":[0.0,0.08,0.17,0.33,0.5,0.75,1.0,1.17,1.25,1.5,1.75,2.0,2.5,3.0,4.0,5.0,6.0,7.0,8.0,9.0],"conc_ng_ml":[61.62133,26.187430000000003,20.44153,14.41864,11.382420000000002,9.399508,7.849926,7.337121000000001,6.630036,5.537023,4.892001,4.273728,3.733594,3.225206,2.406679,1.9214038800000002,1.450004,1.355281,1.10664892,0.9036291]},{"study":"Bornemann 1986","route":"PO","dose":"15 mg","n":18.0,"reference":"https://www.ncbi.nlm.nih.gov/pubmed/2936766","time":[1.5,1.75,2.0,2.25,2.5,3.0,4.0,5.0,6.0,7.0,8.0,9.0,11.0],"conc_ng_ml":[17.00745,26.76059,32.6278321,35.018,35.013059999999996,36.00895,28.89098,24.88269,13.61774,10.251069999999999,6.510167,5.0061205399999995,2.9183181499999997]}],"validation":{"bottom_up":{"IV":{"auc":{"n":28,"gmfe":1.518893682891501,"median_ratio":1.321038552549811,"within_1.5x":0.7142857142857143,"within_2x":0.8214285714285714},"cmax":{"n":28,"gmfe":5.156211298659882,"median_ratio":5.659803257745395,"within_1.5x":0.0,"within_2x":0.10714285714285714}},"PO":{"auc":{"n":54,"gmfe":1.5699854518897394,"median_ratio":1.4724283673043645,"within_1.5x":0.5,"within_2x":0.8148148148148148},"cmax":{"n":54,"gmfe":1.4328163322330683,"median_ratio":1.2937365886370924,"within_1.5x":0.6111111111111112,"within_2x":0.9259259259259259}}},"middle_out":{"IV":{"auc":{"n":28,"gmfe":1.4477889484871933,"median_ratio":1.2155210238574692,"within_1.5x":0.6785714285714286,"within_2x":0.8571428571428571},"cmax":{"n":28,"gmfe":5.15405579301904,"median_ratio":5.657535339316617,"within_1.5x":0.0,"within_2x":0.10714285714285714}},"PO":{"auc":{"n":54,"gmfe":1.3701603697230302,"median_ratio":1.2513841800841723,"within_1.5x":0.7407407407407407,"within_2x":0.9444444444444444},"cmax":{"n":54,"gmfe":1.3771601026404747,"median_ratio":1.140371152659931,"within_1.5x":0.7592592592592593,"within_2x":0.9259259259259259}}}},"reference_profile":{"individual":"ref_male","doses":[[0,2.0,"iv",0.03333333333333333],[6.0,7.5,"oral"]],"time_h":[0.0,0.25,0.5,0.75,1.0,1.25,1.5,1.75,2.0,2.25,2.5,2.75,3.0,3.25,3.5,3.75,4.0,4.25,4.5,4.75,5.0,5.25,5.5,5.75,6.0,6.25,6.5,6.75,7.0,7.25,7.5,7.75,8.0,8.25,8.5,8.75,9.0,9.25,9.5,9.75,10.0,10.25,10.5,10.75,11.0,11.25,11.5,11.75,12.0],"plasma":[0.0,0.04398228672245524,0.030634738011313046,0.02503261942514714,0.021033457321315823,0.017934382711093863,0.015479109739836962,0.013507580060252534,0.011907612041704258,0.010597094854413121,0.009514275205552125,0.008611853956855054,0.00785315991509914,0.007209532409330211,0.006658450561589207,0.006182151508466416,0.0057665858726283865,0.005400615801131332,0.0050753929778177154,0.004783873092949295,0.00452043528070939,0.004280583060406682,0.004060708939394567,0.003857908927449345,0.0036698362736314197,0.015402475142615887,0.028083003224098988,0.03432745339049136,0.03610644762444905,0.035248992432192296,0.03299215068694864,0.030115488560676633,0.027087048489110137,0.024171530848232488,0.021504110144737184,0.019139661443257946,0.017085403899187637,0.015322335939201114,0.0138189661684551,0.012539727525759894,0.011449785684190465,0.010517489821743166,0.009715360636651005,0.009020232374022418,0.008412952679375014,0.007877889405975518,0.007402387623660002,0.006976251855473653,0.006591287254599978],"brain":[0.0,0.05349405422561717,0.03175575371374051,0.02542610861365141,0.021261784636398648,0.01807260492393636,0.015556566659643027,0.013542016776845587,0.011910947231703108,0.010577736544539673,0.009478356391526442,0.008563951253812532,0.007796738316857348,0.007147237073342795,0.006592308352375344,0.006113716082118316,0.005697045356280461,0.005330874421391611,0.0050061338146331815,0.004715606757972277,0.00445353788826351,0.00421532594553316,0.003997281960976627,0.0037964387585937664,0.0036104007621660856,0.011626801851724168,0.025030726305659317,0.032395334679249925,0.03495720718996239,0.03459841482639072,0.032644484116882144,0.02994255106424403,0.027007318612206697,0.02413472243463817,0.021480558732240702,0.019113104479531875,0.017048052539146753,0.015271524473962298,0.013754918535018494,0.012464120601641133,0.011364870814146215,0.010425591580317502,0.0096186186878519,0.008920491365742498,0.008311736265065962,0.007776417762015626,0.007301614115941302,0.006876905222323258,0.006493912321474759]}} \ No newline at end of file +{"compound":{"name":"midazolam","mw":325.78,"logp":2.897,"fu":0.031,"target":{"name":"GABA-A receptor (benzodiazepine site, GABRG2)","tissue":"brain","kd_nm":1.8,"koff_per_h":60.0,"source":"Buhr 1997 (Kd 1.8 nM), via Open Systems Pharmacology Midazolam-Model (github.com/Open-Systems-Pharmacology/Midazolam-Model)"},"sources":{"mw":"Open Systems Pharmacology Midazolam-Model (github.com/Open-Systems-Pharmacology/Midazolam-Model)","logp":"lipophilicity 2.897 (fitted value in Open Systems Pharmacology Midazolam-Model (github.com/Open-Systems-Pharmacology/Midazolam-Model))","pka":"basic pKa 6.2 (Open Systems Pharmacology Midazolam-Model (github.com/Open-Systems-Pharmacology/Midazolam-Model); acidic pKa 10.95 ignored at physiological pH)","fu":"0.031, Gertz 2010, via Open Systems Pharmacology Midazolam-Model (github.com/Open-Systems-Pharmacology/Midazolam-Model)","bp":"predicted from red-cell partitioning (Rodgers & Rowland); literature ~0.6","peff":"ASSUMED 4e-4 cm/s (BCS class I high permeability; not measured)","gut_metabolism":"Qgut model (Yang 2007) with intestinal CYP3A4 70.5 nmol vs hepatic 137 pmol/mg"}},"constants":{"n_transit":7,"si_transit_h":3.32,"gastric_half_life_h":0.25,"tissues":["lung","heart","brain","muscle","adipose","skin","bone","kidney","liver","gut","spleen","pancreas","rest"],"portal":["gut","spleen","pancreas"]},"clint_scale":1.1273433145411291,"individuals":{"ref_male":{"label":"Reference man (ICRP 89)","sex":"male","age":30.0,"body_mass":73.0,"height":176.0,"volumes":{"lung":0.5,"heart":0.33,"brain":1.45,"muscle":29.0,"adipose":18.2,"skin":3.3,"bone":10.5,"kidney":0.31,"liver":1.8,"gut":1.17,"spleen":0.15,"pancreas":0.14,"rest":1.46},"v_arterial":1.325,"v_venous":3.9749999999999996,"flows":{"lung":390.0,"heart":15.6,"brain":46.8,"muscle":66.3,"adipose":19.5,"skin":19.5,"bone":19.5,"kidney":74.1,"liver":25.35,"gut":58.5,"spleen":11.7,"pancreas":3.9,"rest":29.25},"cardiac_output":390.0,"liver_flow_total":99.45000000000002,"gfr":7.862359666296279,"kp":{"lung":0.7575776381893871,"heart":0.5543702858165431,"brain":0.9729669343541709,"muscle":0.35832561487381903,"adipose":1.9550643053194905,"skin":1.5263040291073704,"bone":0.47147408134646995,"kidney":0.5935042666201106,"liver":0.6456631725164685,"gut":1.101135989748967,"spleen":0.4511271832304625,"pancreas":1.069900452891875,"rest":0.35832561487381903},"bp":0.5969537621514333,"fu":0.031,"clint_hep":856.3686334962259,"cl_renal":0.24373314965518464,"ka":1.645714285714286,"fa":0.982374560767999,"fg":0.45678960782801,"q_gut":6.219895287958116,"clint_gut":7.396647604804071,"vss":64.47240202577142,"summary":"midazolam in Reference man (ICRP 89): Vss 64 L (0.88 L/kg), B:P 0.60, fu 0.031, CLint,hep 856 L/h -> CL_plasma 18.6 L/h (hepatic blood 30.7, renal 0.24), t1/2,terminal ~3.9 h (effective ln2*Vss/CL ~2.4 h) | oral: ka 1.65/h, Fa 0.98, Fg 0.46, Fh 0.69"},"ref_female":{"label":"Reference woman (ICRP 89)","sex":"female","age":30.0,"body_mass":60.0,"height":163.0,"volumes":{"lung":0.42,"heart":0.25,"brain":1.3,"muscle":17.5,"adipose":22.5,"skin":2.3,"bone":7.8,"kidney":0.275,"liver":1.4,"gut":1.06,"spleen":0.13,"pancreas":0.12,"rest":1.2},"v_arterial":0.975,"v_venous":2.925,"flows":{"lung":354.0,"heart":17.7,"brain":42.48,"muscle":42.48,"adipose":30.09,"skin":17.7,"bone":17.7,"kidney":60.18,"liver":23.01,"gut":60.18,"spleen":10.62,"pancreas":3.54,"rest":28.32},"cardiac_output":354.0,"liver_flow_total":97.35000000000001,"gfr":6.288050333680336,"kp":{"lung":0.7575776381893871,"heart":0.5543702858165431,"brain":0.9729669343541709,"muscle":0.35832561487381903,"adipose":1.9550643053194905,"skin":1.5263040291073704,"bone":0.47147408134646995,"kidney":0.5935042666201106,"liver":0.6456631725164685,"gut":1.101135989748967,"spleen":0.4511271832304625,"pancreas":1.069900452891875,"rest":0.35832561487381903},"bp":0.6417366774679406,"fu":0.031,"clint_hep":666.0644927192869,"cl_renal":0.19492956034409042,"ka":1.645714285714286,"fa":0.982374560767999,"fg":0.45678960782801,"q_gut":6.219895287958116,"clint_gut":7.396647604804071,"vss":64.52341905770191,"summary":"midazolam in Reference woman (ICRP 89): Vss 65 L (1.08 L/kg), B:P 0.64, fu 0.031, CLint,hep 666 L/h -> CL_plasma 15.7 L/h (hepatic blood 24.2, renal 0.19), t1/2,terminal ~4.1 h (effective ln2*Vss/CL ~2.8 h) | oral: ka 1.65/h, Fa 0.98, Fg 0.46, Fh 0.75"},"obese_female":{"label":"Obese woman, 136 kg","sex":"female","age":36.0,"body_mass":136.0,"height":163.0,"volumes":{"lung":0.6396058433472983,"heart":0.38071776389720136,"brain":1.9797323722654472,"muscle":26.650243472804096,"adipose":81.90270418629515,"skin":3.502603427854252,"bone":11.878394233592681,"kidney":0.4187895402869215,"liver":2.1320194778243273,"gut":1.6142433189241339,"spleen":0.19797323722654472,"pancreas":0.18274452667065663,"rest":2.72},"v_arterial":1.4679066727827077,"v_venous":4.403720018348123,"flows":{"lung":532.9630381180293,"heart":26.648151905901468,"brain":63.95556457416352,"muscle":63.95556457416352,"adipose":45.30185824003249,"skin":26.648151905901468,"bone":26.648151905901468,"kidney":90.60371648006497,"liver":34.642597477671906,"gut":90.60371648006497,"spleen":15.98889114354088,"pancreas":5.329630381180293,"rest":42.63704304944235},"cardiac_output":532.9630381180293,"liver_flow_total":146.56483548245805,"gfr":9.466944660105536,"kp":{"lung":0.7575776381893871,"heart":0.5543702858165431,"brain":0.9729669343541709,"muscle":0.35832561487381903,"adipose":1.9550643053194905,"skin":1.5263040291073704,"bone":0.47147408134646995,"kidney":0.5935042666201106,"liver":0.6456631725164685,"gut":1.101135989748967,"spleen":0.4511271832304625,"pancreas":1.069900452891875,"rest":0.35832561487381903},"bp":0.6417366774679406,"fu":0.031,"clint_hep":1014.3303371176424,"cl_renal":0.29347528446327165,"ka":1.645714285714286,"fa":0.982374560767999,"fg":0.45678960782801,"q_gut":6.219895287958116,"clint_gut":7.396647604804071,"vss":191.67286960383998,"summary":"midazolam in Obese woman, 136 kg: Vss 192 L (1.41 L/kg), B:P 0.64, fu 0.031, CLint,hep 1014 L/h -> CL_plasma 23.9 L/h (hepatic blood 36.7, renal 0.29), t1/2,terminal ~9.0 h (effective ln2*Vss/CL ~5.6 h) | oral: ka 1.65/h, Fa 0.98, Fg 0.46, Fh 0.75"},"elderly_male":{"label":"Older man, 75 y","sex":"male","age":75.0,"body_mass":78.0,"height":172.0,"volumes":{"lung":0.5081460227790228,"heart":0.335376375034155,"brain":1.473623466059166,"muscle":29.472469321183322,"adipose":22.968845158926545,"skin":3.35376375034155,"bone":10.671066478359478,"kidney":0.3150505341229941,"liver":1.829325682004482,"gut":1.1890616933029132,"spleen":0.1524438068337068,"pancreas":0.1422808863781264,"rest":1.56},"v_arterial":1.3539718622853738,"v_venous":4.061915586856122,"flows":{"lung":398.52756701229873,"heart":15.94110268049195,"brain":47.82330804147585,"muscle":67.7496863920908,"adipose":19.926378350614936,"skin":19.926378350614936,"bone":19.926378350614936,"kidney":75.72023773233676,"liver":25.90429185579942,"gut":59.779135051844804,"spleen":11.955827010368962,"pancreas":3.9852756701229874,"rest":29.889567525922402},"cardiac_output":398.52756701229873,"liver_flow_total":101.62452958813617,"gfr":5.934274535345345,"kp":{"lung":0.7575776381893871,"heart":0.5543702858165431,"brain":0.9729669343541709,"muscle":0.35832561487381903,"adipose":1.9550643053194905,"skin":1.5263040291073704,"bone":0.47147408134646995,"kidney":0.5935042666201106,"liver":0.6456631725164685,"gut":1.101135989748967,"spleen":0.4511271832304625,"pancreas":1.069900452891875,"rest":0.35832561487381903},"bp":0.5969537621514333,"fu":0.031,"clint_hep":870.3206302876279,"cl_renal":0.1839625105957057,"ka":1.645714285714286,"fa":0.982374560767999,"fg":0.45678960782801,"q_gut":6.219895287958116,"clint_gut":7.396647604804071,"vss":74.31142501397069,"summary":"midazolam in Older man, 75 y: Vss 74 L (0.95 L/kg), B:P 0.60, fu 0.031, CLint,hep 870 L/h -> CL_plasma 18.9 L/h (hepatic blood 31.3, renal 0.18), t1/2,terminal ~4.8 h (effective ln2*Vss/CL ~2.7 h) | oral: ka 1.65/h, Fa 0.98, Fg 0.46, Fh 0.69"},"small_female":{"label":"Small woman, 48 kg","sex":"female","age":25.0,"body_mass":48.0,"height":155.0,"volumes":{"lung":0.3516315101729103,"heart":0.20930447034101804,"brain":1.0883832457732938,"muscle":14.651312923871263,"adipose":16.453697277713363,"skin":1.9256011271373659,"bone":6.5302994746397625,"kidney":0.23023491737511986,"liver":1.172105033909701,"gut":0.8874509542459166,"spleen":0.10883832457732938,"pancreas":0.10046614576368866,"rest":0.96},"v_arterial":0.8503968759501455,"v_venous":2.5511906278504366,"flows":{"lung":308.75948111420666,"heart":15.437974055710333,"brain":37.0511377337048,"muscle":37.0511377337048,"adipose":26.244555894707563,"skin":15.437974055710333,"bone":15.437974055710333,"kidney":52.48911178941513,"liver":20.069366272423434,"gut":52.48911178941513,"spleen":9.2627844334262,"pancreas":3.0875948111420666,"rest":24.700758489136533},"cardiac_output":308.75948111420666,"liver_flow_total":84.90885730640683,"gfr":5.484449599568234,"kp":{"lung":0.7575776381893871,"heart":0.5543702858165431,"brain":0.9729669343541709,"muscle":0.35832561487381903,"adipose":1.9550643053194905,"skin":1.5263040291073704,"bone":0.47147408134646995,"kidney":0.5935042666201106,"liver":0.6456631725164685,"gut":1.101135989748967,"spleen":0.4511271832304625,"pancreas":1.069900452891875,"rest":0.35832561487381903},"bp":0.6417366774679406,"fu":0.031,"clint_hep":557.6411034462768,"cl_renal":0.17001793758661524,"ka":1.645714285714286,"fa":0.982374560767999,"fg":0.45678960782801,"q_gut":6.219895287958116,"clint_gut":7.396647604804071,"vss":49.431417313041464,"summary":"midazolam in Small woman, 48 kg: Vss 49 L (1.03 L/kg), B:P 0.64, fu 0.031, CLint,hep 558 L/h -> CL_plasma 13.3 L/h (hepatic blood 20.4, renal 0.17), t1/2,terminal ~3.6 h (effective ln2*Vss/CL ~2.6 h) | oral: ka 1.65/h, Fa 0.98, Fg 0.46, Fh 0.76"}},"observed":[{"study":"Olkkola 1993","route":"IV","dose":"0.05 mg/kg","n":6.0,"reference":"https://www.ncbi.nlm.nih.gov/pubmed/8453848","time":[0.25,0.5,0.75,1.0,1.5,2.0,3.0,4.0,6.0,7.0,8.0],"conc_ng_ml":[63.830960000000005,52.0174429,37.62138,32.44995,24.32209,17.3012409,11.74518,7.2971140000000005,5.0415980000000005,3.176075,2.7865699999999998]},{"study":"Olkkola 1993","route":"PO","dose":"15 mg","n":12.0,"reference":"https://www.ncbi.nlm.nih.gov/pubmed/8453848","time":[0.25,0.5,0.75,1.0,1.5,2.0,3.0,4.0,5.0,6.0,18.0],"conc_ng_ml":[0.3656307,27.4223015,44.24132,47.5319922,48.263248100000006,46.800732599999996,36.197442599999995,21.93784,14.2596,8.775137,0.7312614]},{"study":"Hohmann 2015","route":"IV","dose":"0.001 mg","n":16.0,"reference":"https://www.ncbi.nlm.nih.gov/pubmed/25588320","time":[0.08,0.25,0.5,0.75,1.0,1.5,2.0,2.5,3.0,4.0,6.0,8.0,10.0,24.0],"conc_ng_ml":[0.04187355,0.0192918087,0.01438149,0.0110110705,0.00913471649,0.006811424999999999,0.0050790309999999995,0.0038899720000000002,0.00331537512,0.002222763,0.00111182,0.0008085315,0.0005008498,0.0001050899]},{"study":"Backman 1998","route":"PO","dose":"15 mg","n":9.0,"reference":"https://www.ncbi.nlm.nih.gov/pubmed/9591931","time":[0.0,0.5,1.0,1.5,2.0,3.0,4.0,5.0,6.0,8.0,10.0],"conc_ng_ml":[0.9999998999999999,25.1012184,47.368422200000005,53.84615,54.25101,45.748990000000006,27.12551,18.62348,14.574899299999998,8.906882,6.477733000000001]},{"study":"Kharasch 2011","route":"IV","dose":"1 mg","n":12.0,"reference":"https://www.ncbi.nlm.nih.gov/pubmed/21562488","time":[0.0,0.08,0.17,0.33,0.5,0.75,1.0,1.17,1.25,1.5,1.75,2.0,2.5,3.0,4.0,5.0,6.0,7.0,8.0,9.0],"conc_ng_ml":[61.62133,26.187430000000003,20.44153,14.41864,11.382420000000002,9.399508,7.849926,7.337121000000001,6.630036,5.537023,4.892001,4.273728,3.733594,3.225206,2.406679,1.9214038800000002,1.450004,1.355281,1.10664892,0.9036291]},{"study":"Bornemann 1986","route":"PO","dose":"15 mg","n":18.0,"reference":"https://www.ncbi.nlm.nih.gov/pubmed/2936766","time":[1.5,1.75,2.0,2.25,2.5,3.0,4.0,5.0,6.0,7.0,8.0,9.0,11.0],"conc_ng_ml":[17.00745,26.76059,32.6278321,35.018,35.013059999999996,36.00895,28.89098,24.88269,13.61774,10.251069999999999,6.510167,5.0061205399999995,2.9183181499999997]}],"validation":{"bottom_up":{"IV":{"auc":{"n":28,"gmfe":1.518893682891501,"median_ratio":1.321038552549811,"within_1.5x":0.7142857142857143,"within_2x":0.8214285714285714},"cmax":{"n":28,"gmfe":5.156211298659882,"median_ratio":5.659803257745395,"within_1.5x":0.0,"within_2x":0.10714285714285714}},"PO":{"auc":{"n":54,"gmfe":1.5699854518897394,"median_ratio":1.4724283673043645,"within_1.5x":0.5,"within_2x":0.8148148148148148},"cmax":{"n":54,"gmfe":1.4328163322330683,"median_ratio":1.2937365886370924,"within_1.5x":0.6111111111111112,"within_2x":0.9259259259259259}}},"middle_out":{"IV":{"auc":{"n":28,"gmfe":1.4477889484871933,"median_ratio":1.2155210238574692,"within_1.5x":0.6785714285714286,"within_2x":0.8571428571428571},"cmax":{"n":28,"gmfe":5.15405579301904,"median_ratio":5.657535339316617,"within_1.5x":0.0,"within_2x":0.10714285714285714}},"PO":{"auc":{"n":54,"gmfe":1.3701603697230302,"median_ratio":1.2513841800841723,"within_1.5x":0.7407407407407407,"within_2x":0.9444444444444444},"cmax":{"n":54,"gmfe":1.3771601026404747,"median_ratio":1.140371152659931,"within_1.5x":0.7592592592592593,"within_2x":0.9259259259259259}}}},"reference_profile":{"individual":"ref_male","doses":[[0,2.0,"iv",0.03333333333333333],[6.0,7.5,"oral"]],"time_h":[0.0,0.25,0.5,0.75,1.0,1.25,1.5,1.75,2.0,2.25,2.5,2.75,3.0,3.25,3.5,3.75,4.0,4.25,4.5,4.75,5.0,5.25,5.5,5.75,6.0,6.25,6.5,6.75,7.0,7.25,7.5,7.75,8.0,8.25,8.5,8.75,9.0,9.25,9.5,9.75,10.0,10.25,10.5,10.75,11.0,11.25,11.5,11.75,12.0],"plasma":[0.0,0.04398228672245526,0.030634738011313063,0.02503261942514715,0.02103345732131582,0.017934382711093863,0.015479109739836953,0.013507580060252523,0.011907612041704247,0.01059709485441311,0.009514275205552113,0.00861185395685504,0.007853159915099129,0.007209532409330198,0.006658450561589194,0.006182151508466402,0.005766585872628372,0.0054006158011313185,0.005075392977817702,0.004783873092949284,0.004520435280709378,0.004280583060406672,0.004060708939394556,0.0038579089274493328,0.0036698362736314093,0.015402475142615873,0.028083003224098967,0.03432745339049133,0.03610644762444901,0.03524899243219225,0.032992150686948586,0.030115488560676588,0.02708704848911008,0.02417153084823244,0.021504110144737132,0.019139661443257898,0.017085403899187588,0.015322335939201065,0.013818966168455056,0.012539727525759848,0.01144978568419042,0.010517489821743121,0.009715360636650962,0.009020232374022377,0.008412952679374976,0.007877889405975478,0.007402387623659964,0.006976251855473617,0.006591287254599942],"brain":[0.0,0.05349405422561721,0.03175575371374051,0.0254261086136514,0.021261784636398634,0.018072604923936347,0.015556566659643011,0.013542016776845568,0.011910947231703089,0.010577736544539655,0.009478356391526426,0.008563951253812513,0.007796738316857331,0.007147237073342778,0.0065923083523753276,0.0061137160821183026,0.005697045356280445,0.0053308744213915946,0.005006133814633167,0.004715606757972262,0.004453537888263497,0.004215325945533146,0.003997281960976614,0.0037964387585937526,0.0036104007621660726,0.01162680185172415,0.02503072630565929,0.032395334679249876,0.03495720718996234,0.03459841482639066,0.03264448411688209,0.029942551064243966,0.02700731861220663,0.024134722434638104,0.021480558732240643,0.019113104479531816,0.017048052539146694,0.01527152447396224,0.013754918535018444,0.012464120601641083,0.011364870814146161,0.010425591580317453,0.00961861868785185,0.00892049136574245,0.008311736265065917,0.007776417762015582,0.007301614115941259,0.006876905222323216,0.006493912321474723]}} \ No newline at end of file