#!/usr/bin/env python3 """Create the closed-form Chapter 14 profile and compare NCA calculations.""" from __future__ import annotations import csv import json import math import os import subprocess from pathlib import Path BOOK = Path(__file__).resolve().parents[1] INPUT = BOOK / "documents" / "ch14" / "input" RESULTS = BOOK / "documents" / "ch14" / "results" / "oral_closed_form" DATA = INPUT / "ch14_oral.csv" CONFIG = INPUT / "chapter14.nca" TIMES = [0.25, 0.5, 1, 2, 3, 4, 6, 8, 12, 24, 36, 48] KA, K, DOSE, AMPLITUDE = 1.5, 0.1, 500.0, 100.0 def conc(t: float) -> float: return AMPLITUDE * KA / (KA - K) * (math.exp(-K * t) - math.exp(-KA * t)) def make_data() -> list[tuple[float, float]]: INPUT.mkdir(parents=True, exist_ok=True) points = [(t, conc(t)) for t in TIMES] with DATA.open("w", newline="", encoding="utf-8") as handle: writer = csv.writer(handle) writer.writerow(["ID", "TIME", "DV", "AMT", "EVID", "MDV", "CMT"]) writer.writerow([1, 0, ".", DOSE, 1, 1, 1]) for t, c in points: writer.writerow([1, t, f"{c:.12f}", 0, 0, 0, 2]) return points def seg_auc(t1: float, c1: float, t2: float, c2: float, logarithmic: bool) -> float: dt = t2 - t1 if logarithmic and c1 > 0 and c2 > 0 and c1 != c2: return (c1 - c2) * dt / math.log(c1 / c2) return (c1 + c2) * dt / 2 def auc(points: list[tuple[float, float]], method: str) -> float: tmax = max(points, key=lambda p: p[1])[0] total = 0.0 for (t1, c1), (t2, c2) in zip(points, points[1:]): logarithmic = ( method == "linear-log" and t1 >= tmax - 1e-12 ) or (method == "linear-up-log-down" and c2 < c1) total += seg_auc(t1, c1, t2, c2, logarithmic) return total def find_executable() -> Path: if os.environ.get("NLMX_EXE"): return Path(os.environ["NLMX_EXE"]) candidates = sorted((BOOK.parent / "nlmx" / "target" / "release").glob("nlmx*.exe")) if not candidates: raise FileNotFoundError("Set NLMX_EXE or build target/release/nlmx.exe") return candidates[0] def run() -> None: measured = make_data() curve = [(0.0, 0.0), *measured] exact_auc_inf = AMPLITUDE / K reference = { "model": "C(t)=A*ka/(ka-k)*(exp(-k*t)-exp(-ka*t))", "A": AMPLITUDE, "ka": KA, "lambda_z": K, "half_life": math.log(2) / K, "auc_inf": exact_auc_inf, "cl_over_f": DOSE / exact_auc_inf, "vz_over_f": DOSE / (K * exact_auc_inf), "mrt_inf": 1 / K + 1 / KA, } INPUT.joinpath("closed_form_reference.json").write_text( json.dumps(reference, indent=2) + "\n", encoding="utf-8" ) with INPUT.joinpath("trapezoid_comparison.csv").open("w", newline="", encoding="utf-8") as handle: writer = csv.writer(handle) writer.writerow(["METHOD", "AUCLAST_TO_48", "EXACT_AUC_0_48", "ERROR"]) exact_48 = AMPLITUDE * KA / (KA - K) * ( (1 - math.exp(-K * 48)) / K - (1 - math.exp(-KA * 48)) / KA ) for method in ("linear", "linear-log", "linear-up-log-down"): value = auc(curve, method) writer.writerow([method, f"{value:.12f}", f"{exact_48:.12f}", f"{value-exact_48:.12f}"]) RESULTS.mkdir(parents=True, exist_ok=True) command = [str(find_executable()), "nca", "-c", str(CONFIG), "-o", str(RESULTS), "--overwrite", "--no-color"] subprocess.run(command, cwd=INPUT, check=True) if __name__ == "__main__": run()