"""Generate the book's dark-card explanatory figures for Chapters 6--10. The diagrams are plain SVG: searchable, scalable, reviewable in source control, and independent of a plotting package. They intentionally share one visual grammar so concepts can be compared across chapters. """ from pathlib import Path from xml.sax.saxutils import escape import sys sys.path.insert(0, str(Path(__file__).resolve().parent)) import figlib from figlib import * # light palette (BG, INK, MUTED, CYAN, ...) ROOT = Path(__file__).resolve().parents[1] OUT = ROOT / "figures" W, H = 1200, 650 def text(x, y, value, size=24, weight=400, color=INK, anchor="start", mono=False): family = "ui-monospace,Consolas,monospace" if mono else "Inter,Segoe UI,Arial,sans-serif" return (f'{escape(value)}') def lines(x, y, values, size=20, color=MUTED, gap=29, mono=False, anchor="start"): if isinstance(values, str): values = (values,) return "".join(text(x, y + i * gap, v, size, 400, color, anchor, mono) for i, v in enumerate(values)) def card(x, y, w, h, title, body=(), accent=CYAN, badge=None): s = [f'', f'', text(x+52, y+48, title, 25, 700)] if badge: bw = max(92, len(badge) * 11 + 28) s += [f'', text(x+w-bw/2-22, y+44, badge, 15, 700, "#071426", "middle")] s.append(lines(x+52, y+82, body, 18, MUTED, 27)) return "".join(s) def arrow(x1, y1, x2, y2, color=BLUE): return (f'') def save(name, title, subtitle, body, height=H): OUT.mkdir(parents=True, exist_ok=True) svg = f''' {escape(title)}{escape(subtitle)} {text(52, 55, title, 32, 750)}{text(52, 88, subtitle, 18, 400, MUTED)}{body} ''' (OUT / name).write_text(svg, encoding="utf-8", newline="\n") # Chapter 6: dataset meaning and covariate preparation. figlib.configure(OUT) card, arrow, save = figlib.card, figlib.arrow, figlib.save # shared light card grammar save("fig-06-04-row-classification.svg", "How one row acquires pharmacometric meaning", "Column mapping and record flags are interpreted together; no single field is sufficient.", card(55, 130, 250, 155, "Physical row", ("CSV or whitespace fields", "original row number"), CYAN) + arrow(305, 208, 385, 208) + card(390, 130, 350, 155, "$INPUT mapping", ("aliases • DROP • numeric parsing", "ID and TIME become named items"), BLUE) + arrow(740, 208, 820, 208) + card(825, 130, 320, 155, "Record class", ("observation • dose • reset", "EVID + MDV + AMT + CMT"), ORANGE) + card(95, 355, 1010, 190, "Why this classification matters", ("Subject timelines, likelihood rows, BLQ actions, covariate snapshots and event execution all use it.", "QC the interpreted row—not only the text file—before comparing results across software."), GREEN, "REVIEW GATE")) save("fig-06-05-covariate-pipeline.svg", "Covariate preparation is an ordered pipeline", "Moving a step changes the analysis population or the values supplied to the model.", card(45, 130, 205, 145, "1 Detect", ("numeric / categorical", "subject variability"), CYAN) + arrow(250, 203, 285, 203) + card(290, 130, 205, 145, "2 Complete", ("error / drop / impute", "carry-forward rules"), BLUE) + arrow(495, 203, 530, 203) + card(535, 130, 205, 145, "3 Transform", ("mutate expressions", "ordered evaluation"), ORANGE) + arrow(740, 203, 775, 203) + card(780, 130, 205, 145, "4 Centre", ("median / reference", "units retained"), GREEN) + arrow(985, 203, 1020, 203) + card(1025, 130, 130, 145, "5 Use", ("model", "plots"), YELLOW) + card(120, 360, 960, 160, "Audit record", ("Retain the original data hash, effective rules, exclusions, derived-column definitions and final summaries.", "Cross-software accuracy requires the same rows and covariate values, not merely similar option names."), BLUE)) # Chapter 7: extension ownership and rerun provenance. save("fig-07-04-extension-registry.svg", "Command extensions live below the shared settings contract", "The common layer owns execution and output behavior; each command validates its own scientific namespace.", card(55, 125, 1090, 125, "Shared settings", ("input • output • overwrite • threads • seed • logging • plot defaults"), BLUE, "ALL COMMANDS") + arrow(600, 250, 600, 305) + card(55, 315, 330, 185, "[vpc]", ("bins • replicates • censoring", "strata • prediction intervals"), CYAN) + card(435, 315, 330, 185, "[power]", ("scenarios • targets • engines", "sample sizes • uncertainty"), ORANGE) + card(815, 315, 330, 185, "[custom]", ("data steps • plots • tables", "facets • themes • formats"), GREEN) + text(600, 565, "Unknown keys must fail near their owner; silent acceptance is not reproducibility.", 21, 600, YELLOW, "middle")) save("fig-07-05-provenance-bundle.svg", "A rerunnable settings bundle answers five questions", "The configuration is necessary, but it is not the whole provenance record.", card(55, 125, 520, 105, "1 What ran?", ("executable version + complete command"), CYAN) + card(625, 125, 520, 105, "2 Which inputs?", ("paths, roles and SHA-256 hashes"), BLUE) + card(55, 265, 520, 105, "3 Which effective values?", ("defaults + TOML + CLI after precedence"), ORANGE) + card(625, 265, 520, 105, "4 Which environment?", ("threads, platform and relevant engine details"), GREEN) + card(220, 405, 760, 115, "5 What was emitted?", ("output inventory + checksums + logs + review decision"), YELLOW, "CLOSE THE LOOP") + text(600, 585, "Archive the bundle together; separating it destroys the chain of evidence.", 21, 600, MUTED, "middle")) # Chapter 8: engine selection and likelihood construction. save("fig-08-05-advan-engine-map.svg", "Model structure selects a propagation engine", "Parser support does not imply that every ADVAN/TRANS combination follows the same numerical path.", card(45, 125, 335, 170, "Analytic compartments", ("closed-form amount updates", "fast and exact for supported forms", "dose/event logic still applies"), CYAN) + card(433, 125, 335, 170, "Linear systems", ("matrix exponential propagation", "ADVAN5 / ADVAN7 topology", "conditioning must be checked"), BLUE) + card(820, 125, 335, 170, "$DES systems", ("adaptive ODE integration", "tolerances control local error", "stiffness can dominate runtime"), ORANGE) + arrow(210, 295, 420, 390) + arrow(600, 295, 600, 390) + arrow(987, 295, 780, 390) + card(190, 395, 820, 125, "Shared record executor", ("ordered subject timeline • bolus/infusion • lag • bioavailability • ADDL/SS/reset • observation"), GREEN, "COMMON SEMANTICS") + text(600, 585, "Validate the chosen path, event semantics and tolerances separately.", 22, 600, YELLOW, "middle")) save("fig-08-06-likelihood-path.svg", "From a record to an objective contribution", "Predictions, residual variance and F_FLAG form distinct review checkpoints.", card(45, 130, 220, 150, "State", ("amounts + ETA", "record covariates"), CYAN) + arrow(265, 205, 315, 205) + card(320, 130, 220, 150, "$ERROR", ("F → Y at EPS=0", "EPS finite differences"), BLUE) + arrow(540, 205, 590, 205) + card(595, 130, 220, 150, "Variance", ("V = hᵀΣh", "must be finite > 0"), ORANGE) + arrow(815, 205, 865, 205) + card(870, 130, 285, 150, "Contribution", ("Gaussian • -2 log L", "or direct objective"), GREEN) + card(95, 365, 1010, 150, "Accuracy checkpoint", ("Compare F, Y, h, V and the per-record objective before comparing a total OFV.", "A matching total can conceal compensating record-level differences."), YELLOW, "F_FLAG 0 / 1 / 2")) # Chapter 9: determinism scope and output identity. save("fig-09-04-reproducibility-envelope.svg", "Reproducibility has nested levels", "State the strongest level actually tested; do not use deterministic as an unqualified adjective.", card(70, 125, 1060, 105, "Level 1 — same scientific values within tolerance", ("appropriate across some platforms or algorithm revisions"), CYAN) + card(115, 255, 970, 105, "Level 2 — identical scientific file bytes", ("same stable data outputs across thread counts"), BLUE) + card(160, 385, 880, 105, "Level 3 — identical complete directory", ("rare: logs, timings, paths and metadata usually differ"), ORANGE) + text(600, 560, "Choose the comparison set first; then choose values, hashes, or both.", 22, 650, YELLOW, "middle")) save("fig-09-05-output-identity.svg", "Separate scientific identity from expected metadata variation", "The Chapter 9 experiment compared stable data files across 1, 2 and 4 threads.", card(55, 130, 500, 315, "Compare as scientific outputs", ("analytic_sim.csv", "analytic_subjects.csv", "row order", "values and SHA-256", "method settings other than threads"), GREEN, "IDENTICAL") + card(645, 130, 500, 315, "Expect to vary", ("random log filename", "elapsed time", "thread-count message", "command line", "settings-used thread value"), ORANGE, "METADATA") + text(600, 520, "A whole-directory hash would reject a scientifically reproducible run.", 22, 650, YELLOW, "middle") + text(600, 558, "A value-only comparison could miss reordered or reformatted evidence.", 19, 400, MUTED, "middle")) # Chapter 10: output lifecycle, report anatomy, formats and review. save("fig-10-01-output-bundle-map.svg", "One run produces a layered evidence bundle", "Human review, machine reuse and provenance are complementary—not interchangeable.", card(45, 125, 260, 300, "Human review", ("report.html", "summary.txt", "plots/*.png", "plots/svg/*.svg", "drafts and listings"), CYAN) + card(330, 125, 260, 300, "Machine reuse", ("*.csv tables", "*.json structures", "stable column names", "explicit missing values", "schema-aware readers"), BLUE) + card(615, 125, 260, 300, "Provenance", ("input_manifest.json", "settings_used.*", "command line", "engine version", "logs"), ORANGE) + card(900, 125, 255, 300, "Integrity", ("checksums.sha256", "file inventory", "review sign-off", "archive metadata", "transfer verification"), GREEN) + text(600, 505, "A polished report without machine files cannot be reanalysed.", 21, 650, YELLOW, "middle") + text(600, 542, "A folder of tables without provenance cannot be defended.", 21, 650, YELLOW, "middle")) save("fig-10-02-html-anatomy.svg", "An nlmx HTML report is a self-contained review surface", "CSS, SVG figures and the optional collapsible-section script travel inside one file.", card(55, 120, 1090, 88, "Header", ("analysis title • command line • version and run context"), CYAN) + card(55, 230, 520, 115, "Summary cards", ("key counts, estimates, warnings and fit metrics"), BLUE) + card(625, 230, 520, 115, "Narrative sections", ("methods, diagnostics, limitations and review cues"), ORANGE) + card(55, 370, 520, 115, "Inline SVG", ("theme-aware vectors with legends and tooltips"), GREEN) + card(625, 370, 520, 115, "Collapsible tables", ("visible without JavaScript; controls enhance navigation"), YELLOW) + text(600, 560, "Print CSS expands content and removes interactive buttons.", 22, 650, MUTED, "middle")) save("fig-10-03-theme-tokens.svg", "The same semantic graphic adapts to light and dark display", "Color tokens change surfaces and ink while preserving the meaning of data series.", '<rect x="55" y="125" width="520" height="350" rx="18" fill="#ffffff" stroke="#cbd5e1" stroke-width="2"/>' + text(90, 170, "LIGHT", 18, 750, "#334155") + '<line x1="105" y1="405" x2="530" y2="405" stroke="#111827" stroke-width="3"/><line x1="105" y1="210" x2="105" y2="405" stroke="#111827" stroke-width="3"/>' + '<path d="M120 360 C220 330 270 245 350 270 S455 185 520 215" fill="none" stroke="#2a78d6" stroke-width="8"/>' + '<path d="M120 325 C230 280 310 345 390 250 S470 290 520 235" fill="none" stroke="#eb6834" stroke-width="8"/>' + '<rect x="625" y="125" width="520" height="350" rx="18" fill="#182235" stroke="#3b4a63" stroke-width="2"/>' + text(660, 170, "DARK", 18, 750, "#f8fafc") + '<line x1="675" y1="405" x2="1100" y2="405" stroke="#e5e7eb" stroke-width="3"/><line x1="675" y1="210" x2="675" y2="405" stroke="#e5e7eb" stroke-width="3"/>' + '<path d="M690 360 C790 330 840 245 920 270 S1025 185 1090 215" fill="none" stroke="#69aef5" stroke-width="8"/>' + '<path d="M690 325 C800 280 880 345 960 250 S1040 290 1090 235" fill="none" stroke="#ff8a65" stroke-width="8"/>' + text(600, 550, "Never encode a decision by color alone: retain labels, line styles and legends.", 21, 650, YELLOW, "middle")) save("fig-10-04-figure-pipeline.svg", "One chart specification feeds web and publication outputs", "The data and geometry stay aligned while sizing and color tokens adapt to the destination.", card(55, 145, 280, 180, "Chart specification", ("data • scales • geometry", "labels • legend • caption"), CYAN) + arrow(335, 235, 455, 175) + arrow(335, 235, 455, 355) + card(460, 105, 310, 145, "Web theme", ("responsive SVG", "CSS light/dark tokens", "hover titles"), BLUE) + card(460, 305, 310, 145, "Print theme", ("explicit dimensions in points", "base font + publication colors"), ORANGE) + arrow(770, 178, 865, 178) + arrow(770, 378, 865, 378) + card(870, 105, 275, 145, "report.html", ("inline SVG", "self-contained review"), GREEN) + card(870, 305, 275, 145, "plots/", ("PNG at selected dpi", "optional physical SVG"), YELLOW) + text(600, 540, "Compare the underlying values; presentation paths may legitimately differ.", 21, 650, MUTED, "middle")) save("fig-10-05-svg-versus-png.svg", "SVG and PNG preserve different properties", "Choose the master format according to the next operation, then retain both when the workflow benefits.", card(55, 130, 505, 315, "SVG — vector master", ("resolution independent", "searchable labels", "editable structure", "small for line art", "best for revision and archive"), CYAN, "POINT DIMENSIONS") + card(640, 130, 505, 315, "PNG — raster delivery", ("fixed pixel grid", "embedded pHYs resolution", "widely accepted by office tools", "simple preview", "regenerate after resizing"), ORANGE, "DPI METADATA") + text(600, 515, "7 × 5 in at 300 dpi = 2100 × 1500 pixels.", 25, 750, YELLOW, "middle") + text(600, 557, "Changing dpi changes pixels, not the intended physical size.", 19, 400, MUTED, "middle")) save("fig-10-06-table-encoding.svg", "A table value has a format-specific representation", "Downstream readers must distinguish empty, null, delimiter and list conventions.", card(45, 125, 350, 330, "CSV", ('comma → "dose, mg"', 'quote → "a""b"', "newline forces quoting", "non-finite number → empty", "numeric vector → 1;2;3"), CYAN) + card(425, 125, 350, 330, "JSON", ("typed numbers and booleans", "structured arrays/objects", "non-finite float → null", "pretty printed + final newline", "schema can evolve"), BLUE) + card(805, 125, 350, 330, "Markdown / HTML", ("human-facing layout", "pipes/newlines escaped", "bold, indent, footnotes", "responsive HTML tables", "not the machine truth"), ORANGE) + text(600, 535, "Test the reader with commas, quotes, missingness and non-finite values.", 21, 650, YELLOW, "middle")) save("fig-10-07-checksum-coverage.svg", "Checksums close the output-writing transaction", "The checksum manifest covers files recorded through the OutputSet before finish().", card(55, 130, 300, 300, "Write outputs", ("text via write()", "binary via write_bytes()", "JSON via write_json()", "nested directories created"), CYAN) + arrow(355, 280, 450, 280) + card(455, 130, 300, 300, "Track paths", ("ordered written list", "hash bytes on disk", "store relative names", "one SHA-256 per line"), BLUE) + arrow(755, 280, 850, 280) + card(855, 130, 290, 300, "finish()", ("write checksums.sha256", "report file count", "checksum file excludes itself", "verify after transfer"), GREEN, "FINAL STEP") + text(600, 510, "A file added later is outside this manifest unless it is hashed separately.", 22, 650, YELLOW, "middle") + text(600, 550, "Verify both unexpected additions and missing expected files.", 19, 400, MUTED, "middle")) save("fig-10-08-review-bundle.svg", "Publication and regulatory QC is a gated workflow", "Each gate answers a different question; passing a visual inspection is only one of them.", card(55, 125, 1090, 92, "1 Completeness", ("expected files exist • command-specific optionality explained"), CYAN) + card(55, 235, 1090, 92, "2 Integrity", ("SHA-256 verification • transfer/archive inventory • no untracked post-run edits"), BLUE) + card(55, 345, 1090, 92, "3 Scientific review", ("methods, warnings, tables and figures agree with source values"), ORANGE) + card(55, 455, 1090, 92, "4 Presentation and sign-off", ("final dimensions, readable labels, accessible colors, reviewer and disposition recorded"), GREEN, "RELEASE") + text(600, 605, "Keep the review decision beside the immutable evidence bundle.", 21, 650, YELLOW, "middle"), 635) print("wrote 16 SVG figures for Chapters 6--10")