"""Generate and run the reproducible dataset examples for Chapter 6. The script writes only below documents/ch06. It refuses a non-empty results folder so the recorded evidence cannot be overwritten accidentally. """ from argparse import ArgumentParser from datetime import datetime, timezone from hashlib import sha256 from pathlib import Path import csv import json import math import random import subprocess BOOK = Path(__file__).resolve().parents[1] DOC = BOOK / "documents" / "ch06" def write_new(path: Path, text: str): path.parent.mkdir(parents=True, exist_ok=True) if path.exists(): old = path.read_text(encoding="utf-8") if old != text: raise SystemExit(f"Refusing to replace changed fixture: {path}") return path.write_text(text, encoding="utf-8", newline="\n") def make_timevary(): rows = ["@ID,TIME,AMT,EVID,MDV,DV,CMT,RATE,ADDL,II,SS,WT,CRCL,OCC"] obs = [0.5, 2, 6, 12, 12.5, 18, 24, 24.5, 30, 36, 36.5, 42] for sid in range(1, 9): wt = 56 + 4 * sid base = 112 - 3 * sid rows.append(f"{sid},0,100,1,1,.,1,0,3,12,0,{wt},{base},1") for t in obs: occ = 1 if t < 24 else 2 crcl = base if t < 18 else base - 18 td = t % 12 if td == 0: td = 12 cl = 3.5 * (crcl / 90) ** 0.5 v = 30.0 dv = 100 / v * math.exp(-cl / v * td) * (1 + 0.015 * (sid - 4.5)) rows.append(f"{sid},{t},0,0,0,{dv:.10g},1,0,0,0,0,{wt},{crcl},{occ}") write_new(DOC / "timevary.csv", "\n".join(rows) + "\n") write_new(DOC / "timevary.ctl", """$PROBLEM Time-varying CRCL with ADDL/II dosing $INPUT ID TIME AMT EVID MDV DV CMT RATE ADDL II SS WT CRCL OCC $DATA timevary.csv IGNORE=@ $SUBROUTINES ADVAN1 TRANS2 $PK CL = THETA(1)*(CRCL/90)**THETA(3)*EXP(ETA(1)) V = THETA(2) S1 = V $ERROR Y = F + EPS(1) $THETA (0,3.5,20) (0,30,200) (0,0.5,2) $OMEGA 0.09 $SIGMA 0.04 $ESTIMATION METHOD=1 INTERACTION MAXEVAL=0 """) def make_blq(): rng = random.Random(6202) header = ["ID", "TIME", "AMT", "EVID", "MDV", "DV", "CMT", "RATE", "ADDL", "II", "SS", "WT", "DVID", "BLQ", "LLOQ"] out = [",".join(header)] times = [0.25, 0.5, 1, 2, 4, 8, 12, 24] for sid in range(1, 25): wt = 48 + (sid * 7) % 45 out.append(f"{sid},0,100,1,1,.,1,0,0,0,0,{wt},1,0,0.7") cl = 3.2 * (wt / 70) ** 0.55 v = 32.0 * (wt / 70) ka = 1.1 k = cl / v for t in times: pred = (100 / v) * ka / (ka - k) * (math.exp(-k*t) - math.exp(-ka*t)) raw = max(0.001, pred * math.exp(rng.gauss(0, 0.18))) blq = int(raw < 0.7) dv = 0.7 if blq else raw out.append(f"{sid},{t},0,0,0,{dv:.10g},2,0,0,0,0,{wt},1,{blq},0.7") write_new(DOC / "blq.csv", "\n".join(out) + "\n") write_new(DOC / "blq.ctl", """$PROBLEM BLQ-heavy one-compartment oral example $INPUT ID TIME AMT EVID MDV DV CMT RATE ADDL II SS WT DVID BLQ LLOQ $DATA blq.csv IGNORE=@ $SUBROUTINES ADVAN2 TRANS2 $PK CL = THETA(1)*(WT/70)**THETA(4)*EXP(ETA(1)) V = THETA(2) KA = THETA(3) S2 = V $ERROR Y = F + EPS(1) $THETA (0,3.2,20) (0,32,200) (0,1.1,10) (0,0.55,2) $OMEGA 0.09 $SIGMA 0.04 $ESTIMATION METHOD=1 INTERACTION MAXEVAL=0 """) def make_mapping(): write_new(DOC / "mapping.csv", """@SUBJECT,NOMINAL_H,DOSE_MG,CONC,EVENT,MISSING,COMP,COMMENT,EXTRA 1,0,100,.,1,1,1,dose,999 1,1,0,2.4,0,0,2,sample,999 1,4,0,1.1,0,0,2,sample,999 """) write_new(DOC / "mapping.ctl", """$PROBLEM Positional INPUT mapping example $INPUT ID=SUBJECT TIME=NOMINAL_H AMT=DOSE_MG DV=CONC EVID=EVENT MDV=MISSING CMT=COMP COMMENT=DROP $DATA mapping.csv IGNORE=@ $SUBROUTINES ADVAN2 TRANS2 $PK CL=THETA(1) V=THETA(2) KA=THETA(3) S2=V $ERROR Y=F+EPS(1) $THETA 3 30 1 $OMEGA 0 FIX $SIGMA 0.04 $ESTIMATION MAXEVAL=0 """) 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 = ns.nlmx.resolve() out = 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}") make_mapping(); make_timevary(); make_blq() logs = out / "logs" logs.mkdir(parents=True) rel = lambda p: Path(p).resolve().relative_to(BOOK.resolve()).as_posix() runs = [] def run(name, args, expected=0): cmd = [str(exe), *args, "--no-color", "--threads", "1"] got = subprocess.run(cmd, cwd=BOOK, capture_output=True, text=True, encoding="utf-8", errors="replace") (logs / f"{name}.txt").write_text("$ nlmx " + " ".join(args) + "\n\n" + got.stdout + got.stderr, encoding="utf-8", newline="\n") runs.append({"name": name, "args": args, "exit_code": got.returncode}) if got.returncode != expected: raise RuntimeError(f"{name}: expected {expected}, got {got.returncode}; see {logs/name}.txt") print(name, "exit", got.returncode, flush=True) return got version = run("version", ["version"]) if "4.3.0" not in version.stdout: raise RuntimeError("Chapter 6 evidence is pinned to nlmx 4.3.0") run("mapping", ["fit", "documents/ch06/mapping.ctl", "--max-iterations", "0", "--no-cov-step", "--keep-predose", "-o", rel(out/"mapping-fit")]) run("timevary-fit", ["fit", "documents/ch06/timevary.ctl", "--max-iterations", "0", "--no-cov-step", "--keep-predose", "-o", rel(out/"timevary-fit")]) run("timevary-inspect", ["inspect", "--model-dir", rel(out/"timevary-fit"), "--run-stem", "timevary", "--covariates", "CL=CRCL"]) run("qc-blq", ["qc-data", "documents/ch06/blq.csv", "--lloq", "0.7", "--blq-flag", "BLQ", "-o", rel(out/"qc-blq")]) run("nca-blq", ["nca", "documents/ch06/blq.csv", "--lloq", "0.7", "--blq-flag", "BLQ", "--blq-rule", "tmax-zero-missing", "--no-plots", "-o", rel(out/"nca-blq")]) run("blq-fit", ["fit", "documents/ch06/blq.ctl", "--max-iterations", "0", "--no-cov-step", "--keep-predose", "-o", rel(out/"blq-fit")]) run("vpc-blq", ["vpc", "documents/ch06/blq.ctl", "--results-dir", rel(out/"blq-fit"), "--vpc-type", "vpc", "--samples", "30", "--lloq", "LLOQ", "--blq-flag", "BLQ", "--bins", "0,0.5,1,2,4,8,12,24", "--no-plots", "-o", rel(out/"vpc-blq")]) run("mutate-filter", ["eda", "documents/ch06/blq.csv", "--mutate", "LNDV = log(DV); WT70 = WT/70; PERIOD = ifelse(TIME <= 4, 1, 2)", "--filter", "EVID == 0 & DVID == 1", "--no-plots", "-o", rel(out/"eda-mutated")]) summary = { "software_version": "4.3.0", "created_utc": datetime.now(timezone.utc).isoformat(), "executable_sha256": sha256(exe.read_bytes()).hexdigest(), "fixtures": { "mapping_rows": 3, "timevary_subjects": 8, "timevary_records": 104, "blq_subjects": 24, "blq_observations": 192, }, "commands": runs, } (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()