"""Run the reproducible model-engine examples for Chapter 8.""" from argparse import ArgumentParser from datetime import datetime, timezone from hashlib import sha256 from pathlib import Path import csv import json import math import subprocess BOOK = Path(__file__).resolve().parents[1] DOC = BOOK / "documents" / "ch08" def write_new(path: Path, text: str): path.parent.mkdir(parents=True, exist_ok=True) if path.exists(): if path.read_text(encoding="utf-8") != text: raise SystemExit(f"Refusing to replace changed fixture: {path}") return path.write_text(text, encoding="utf-8", newline="\n") TIMES = [0.25, 0.5, 1, 2, 4, 8, 12, 24] DOSE, CL, V, KA = 100.0, 5.0, 50.0, 1.2 def oral(t): k = CL / V return DOSE / V * KA / (KA - k) * (math.exp(-k * t) - math.exp(-KA * t)) DATA = "ID,TIME,AMT,RATE,EVID,MDV,DV,CMT\n" + "1,0,100,0,1,1,0,1\n" + "".join( f"1,{t:g},0,0,0,0,{oral(t):.12g},2\n" for t in TIMES ) COMMON = '''$PROBLEM Chapter 8 one-compartment oral reference $INPUT ID TIME AMT RATE EVID MDV DV CMT $DATA engine.csv IGNORE=@ {model} $ERROR IPRED = F Y = IPRED + EPS(1) $THETA 5 ; CL $THETA 50 ; V $THETA 1.2 ; KA $OMEGA 0 FIX $SIGMA 0.01 $ESTIMATION METHOD=1 INTERACTION MAXEVAL=0 ''' ANALYTIC = COMMON.format(model='''$SUBROUTINES ADVAN2 TRANS2 $PK CL = THETA(1) V = THETA(2) KA = THETA(3) S2 = V''') ODE = COMMON.format(model='''$SUBROUTINES ADVAN13 TOL=10 ATOL=12 $MODEL COMP=(DEPOT DEFDOSE) COMP=(CENTRAL DEFOBS) $PK CL = THETA(1) V = THETA(2) KA = THETA(3) S2 = V $DES DADT(1) = -KA*A(1) DADT(2) = KA*A(1) - (CL/V)*A(2)''') BAD = COMMON.format(model='''$SUBROUTINES ADVAN2 TRANS2 $PK " CL = THETA(1) V = THETA(2) KA = THETA(3) S2 = V''') def read_predictions(path: Path): with path.open(newline="", encoding="utf-8-sig") as f: rows = list(csv.DictReader(f)) return [(float(r["TIME"]), float(r["IPRED"])) for r in rows] def main(): ap = ArgumentParser() ap.add_argument("--nlmx", required=True, type=Path) ap.add_argument("--output", type=Path, default=DOC / "results") ns = ap.parse_args() exe, out = ns.nlmx.resolve(), ns.output.resolve() if BOOK.resolve() not in out.parents: raise SystemExit("Output must remain inside nlmx-book") if out.exists() and any(out.iterdir()): raise SystemExit(f"Choose a new output folder; existing results retained: {out}") write_new(DOC / "engine.csv", DATA) write_new(DOC / "analytic.ctl", ANALYTIC) write_new(DOC / "ode.ctl", ODE) write_new(DOC / "unsupported-verbatim.ctl", BAD) logs = out / "logs" logs.mkdir(parents=True) rel = lambda p: Path(p).resolve().relative_to(BOOK.resolve()).as_posix() commands = [] def run(name, args, expected=0, contains=None): cmd = [str(exe), *args, "--no-color"] got = subprocess.run(cmd, cwd=BOOK, capture_output=True, text=True, encoding="utf-8", errors="replace") combined = got.stdout + got.stderr (logs / f"{name}.txt").write_text( "$ nlmx " + " ".join(args) + "\n\n" + combined, encoding="utf-8", newline="\n") commands.append({"name": name, "args": args, "exit_code": got.returncode}) if expected is not None and got.returncode != expected: raise RuntimeError(f"{name}: expected {expected}, got {got.returncode}") if contains and contains not in combined: raise RuntimeError(f"{name}: expected message fragment {contains!r}") print(name, "exit", got.returncode, flush=True) return got version = run("version", ["version"]) version_line = next((x.strip() for x in version.stdout.splitlines() if "nlmx " in x.lower()), "nlmx 4.3.0") common = ["--max-iterations", "0", "--no-cov-step", "--no-plots"] analytic_dir, ode_dir = out / "analytic-run", out / "ode-run" run("analytic-fit", ["fit", "documents/ch08/analytic.ctl", *common, "-o", rel(analytic_dir)]) run("ode-fit", ["fit", "documents/ch08/ode.ctl", *common, "-o", rel(ode_dir)]) bad = run("unsupported-verbatim", ["fit", "documents/ch08/unsupported-verbatim.ctl", *common, "-o", rel(out / "bad-run")], expected=None, contains="verbatim Fortran code is not supported") if bad.returncode == 0: raise RuntimeError("unsupported verbatim Fortran unexpectedly succeeded") ana, ode = read_predictions(analytic_dir / "predictions.csv"), read_predictions(ode_dir / "predictions.csv") if [x[0] for x in ana] != [x[0] for x in ode]: raise RuntimeError("analytic and ODE observation grids differ") rows = [] for (t, a), (_, o) in zip(ana, ode): closed = oral(t) rows.append({"time": t, "closed_form": closed, "analytic_ipred": a, "ode_ipred": o, "analytic_abs_error": abs(a - closed), "ode_abs_error": abs(o - closed), "analytic_ode_abs_difference": abs(a - o)}) max_ana = max(r["analytic_abs_error"] for r in rows) max_ode = max(r["ode_abs_error"] for r in rows) max_between = max(r["analytic_ode_abs_difference"] for r in rows) if max_ana > 1e-8 or max_ode > 2e-7 or max_between > 2e-7: raise RuntimeError(f"accuracy limits exceeded: {max_ana}, {max_ode}, {max_between}") with (out / "analytic_vs_ode.csv").open("w", newline="", encoding="utf-8") as f: w = csv.DictWriter(f, fieldnames=list(rows[0])) w.writeheader(); w.writerows(rows) summary = { "source_tree_version": "4.4.0", "evidence_executable": version_line, "created_utc": datetime.now(timezone.utc).isoformat(), "executable_sha256": sha256(exe.read_bytes()).hexdigest(), "observations_compared": len(rows), "max_abs_error_analytic_vs_closed_form": max_ana, "max_abs_error_ode_vs_closed_form": max_ode, "max_abs_difference_analytic_vs_ode": max_between, "unsupported_verbatim_exit_code": bad.returncode, "commands": commands, } (out / "example_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8", newline="\n") print(json.dumps({k: v for k, v in summary.items() if k != "commands"}, indent=2)) if __name__ == "__main__": main()