#!/usr/bin/env python3
"""Deterministic workflow and audit-power scenarios for 'Who Reads the Scan When AI Says It's Normal?'.
Python 3 standard library only; no network. Run from any directory.
Writes inputs.json, mammography_masai.csv, cxr_autonomous.csv,
cxr_audit_power.csv, ctpa_triage_draft.csv, results.json, TABLES.md,
audit_power.svg, and anchoring_breakeven.svg beside this file.
Every model parameter is explicitly labelled OBSERVED (from a cited primary
source) or ASSUMED (policy/stress-test scenario input). Queue waiting time
(exam completion to report start) is kept strictly separate from radiologist
labour.
"""
from __future__ import annotations
import csv
import json
import math
from decimal import ROUND_HALF_UP, Decimal
from pathlib import Path
OUT = Path(__file__).resolve().parent
COHORT = 1000
# ---------------------------------------------------------------------------
# Explicit input register (every input marked OBSERVED or ASSUMED)
# ---------------------------------------------------------------------------
INPUTS = {
"cohort_size": {
"value": COHORT,
"status": "ASSUMED",
"note": "Standardised reporting unit of 1,000 consecutive examinations per workflow.",
},
# Workflow 1: MASAI Mammography (Hernström et al. Lancet Digit Health 2025; Gommers et al. Lancet 2026)
"masai_ai_participants": {
"value": 53043,
"status": "OBSERVED",
"source": "Hernström et al., Lancet Digital Health 2025, Table 2 (MASAI intervention arm denominator; includes 368 unprocessed exams routed to standard care).",
},
"masai_control_participants": {
"value": 52872,
"status": "OBSERVED",
"source": "Hernström et al., Lancet Digital Health 2025, Table 2 (MASAI control arm denominator).",
},
"masai_ai_screen_readings": {
"value": 61248,
"status": "OBSERVED",
"source": "Hernström et al., Lancet Digital Health 2025, Table 2 (total radiologist screen readings, AI arm; MASAI methods explicitly include consensus-meeting readings).",
},
"masai_control_screen_readings": {
"value": 109692,
"status": "OBSERVED",
"source": "Hernström et al., Lancet Digital Health 2025, Table 2 (total radiologist screen readings, control arm; includes consensus-meeting readings).",
},
"masai_ai_consensus_meetings": {
"value": 2023,
"status": "OBSERVED",
"source": "Hernström et al., Lancet Digital Health 2025, Table 2 (consensus meetings, AI arm).",
},
"masai_control_consensus_meetings": {
"value": 1958,
"status": "OBSERVED",
"source": "Hernström et al., Lancet Digital Health 2025, Table 2 (consensus meetings, control arm).",
},
"masai_interval_cancer_ai_per_1000": {
"value": 1.55,
"status": "OBSERVED",
"source": "Gommers et al., The Lancet 2026, 407(10527):505-514 (AI arm interval cancer rate per 1,000; 95% CI 1.23-1.92).",
},
"masai_interval_cancer_control_per_1000": {
"value": 1.76,
"status": "OBSERVED",
"source": "Gommers et al., The Lancet 2026, 407(10527):505-514 (control arm interval cancer rate per 1,000; 95% CI 1.42-2.15; ratio 0.88, 95% CI 0.65-1.18, p=0.41 for difference; non-inferiority met against 20% margin).",
},
"mammography_read_minutes_sweep": {
"value": [0.5, 1.0, 1.5],
"status": "ASSUMED",
"note": "Mean person-minutes per 2D screen reading (1.0 min baseline; 0.5-1.5 min sensitivity).",
},
"mammography_extra_consensus_person_min_sweep": {
"value": [0.0, 2.0, 4.0],
"status": "ASSUMED",
"note": "Incremental person-minutes per consensus meeting beyond readings already embedded in MASAI totals (0.0 avoids double-counting; +2/+4 tests coordination overhead).",
},
# Workflow 2: Autonomous Normal CXR (Plesner et al. Radiology 2023; Vadera UHB NHS poster)
"plesner_eligible_pa_films": {
"value": 1529,
"status": "OBSERVED",
"source": "Plesner et al., Radiology 2023, 307(3):e222268 (1,529 preselected adult PA chest radiographs: 1,100 abnormal [617 critical], 429 normal).",
},
"plesner_ai_high_conf_normal_total": {
"value": 130,
"status": "OBSERVED",
"source": "Plesner et al., Radiology 2023, Table 3: 120 reference-normal + 10 reference-abnormal films cleared from worklist (8.502%).",
},
"plesner_ai_true_normal_clears": {
"value": 120,
"status": "OBSERVED",
"source": "Plesner et al., Radiology 2023, Table 3: correctly cleared normal films (7.848% of 1,529).",
},
"plesner_ai_abnormal_clears_total": {
"value": 10,
"status": "OBSERVED",
"source": "Plesner et al., Radiology 2023, Tables 3-4 and Figures 5-6: 10 reference-abnormal films cleared (9 lowest abnormal grade, 1 critical subtle pneumonia also called normal on original clinical report).",
},
"plesner_ai_critical_miss_in_clears": {
"value": 1,
"status": "OBSERVED",
"source": "Plesner et al., Radiology 2023, Table 3 and Figure 5: 1/130 cleared films (exact 0.7692%; Clopper-Pearson exact binomial 95% CI 0.019%-4.21%) had a critical finding.",
},
"birmingham_uhb_in_scope_films": {
"value": 141597,
"status": "OBSERVED",
"source": "Vadera et al., NHS Fellowship in Clinical AI poster (University Hospitals Birmingham): 141,597 in-scope films, 63,442 NLP-normal reports, 14,820 AI-normal outputs (10.5% of in-scope), 593 AI-normal/NLP-abnormal discordant (4.0% of AI-normal), 14,227 overlap (22.4% of NLP-normal; poster prints marginal ratio 23.4%). Adjudication underway; severity counts omitted.",
},
"birmingham_uhb_ai_normal_outputs": {
"value": 14820,
"status": "OBSERVED",
"source": "Vadera et al., UHB NHS Fellowship poster: count of AI high-confidence normal outputs (not verified correct clears).",
},
"cxr_eligible_fraction_scenarios": {
"value": [1.0, 0.7, 0.5],
"status": "ASSUMED",
"note": "Fraction of all department CXR arrivals meeting adult erect PA label (1.0 = Plesner preselected PA cohort; 0.70 and 0.50 = illustrative hospital-wide mixes).",
},
"cxr_audit_fraction_scenarios": {
"value": [0.0, 0.05, 0.10, 0.25, 1.0],
"status": "ASSUMED",
"note": "Random post-hoc audit share of autonomous clears (1.0 = shadow mode).",
},
"cxr_easy_film_read_min_baseline": {
"value": 1.5,
"status": "ASSUMED",
"note": "Mean human active time to read/report an easy normal PA film (sensitivity 0.75-3.0 min).",
},
"cxr_audit_read_min_baseline": {
"value": 2.0,
"status": "ASSUMED",
"note": "Mean human active time per post-hoc QA audit read including logging (sensitivity 1.0-4.0 min).",
},
"cxr_programme_oversight_hr_per_1000": {
"value": 0.5,
"status": "ASSUMED",
"note": "Allocated governance/QA review hours per 1,000 exams.",
},
"cxr_overall_critical_prevalence_assumed": {
"value": 0.05,
"status": "ASSUMED",
"note": "Illustrative overall prevalence of critical findings used strictly to keep referred-branch prevalence consistent; cancels out of Delta M.",
},
# Workflow 3: Acute CTPA Triage (Aidoc K241727; Rothenberg et al. Radiology 2023) & Experimental Draft Stress Test
"rothenberg_ctpa_total": {
"value": 1526,
"status": "OBSERVED",
"source": "Rothenberg et al., Radiology 2023, 309(1):e230702: 503 Phase 1 (no AI) + 1,023 Phase 2 (Aidoc US 8.0/8.1, preceding K241727).",
},
"rothenberg_pe_prevalence_phase2": {
"value": 0.159,
"status": "OBSERVED",
"source": "Rothenberg et al., Radiology 2023, Table 3: 15.9% PE-positive in Phase 2 (14.5% in Phase 1).",
},
"rothenberg_pe_report_start_wait_usual_min": {
"value": 21.5,
"status": "OBSERVED",
"source": "Rothenberg et al., Radiology 2023, Figure 3 and Table 4: mean exam-completion-to-report-start wait for PE-positive scans without AI (NOT patient treatment time or radiologist labour).",
},
"rothenberg_pe_report_start_wait_ai_min": {
"value": 11.3,
"status": "OBSERVED",
"source": "Rothenberg et al., Radiology 2023, Figure 3 and Table 4: mean exam-completion-to-report-start wait for PE-positive scans with AI (p < 0.001; all scans 22.8 -> 15.9 min, PE-negative 22.9 -> 16.7 min, both p < 0.001).",
},
"rothenberg_elapsed_start_to_sign_no_resident_min": {
"value": 15.5,
"status": "OBSERVED",
"source": "Rothenberg et al., Radiology 2023, Table 4: pooled elapsed start-to-sign timestamp without a resident (15.7 min before AI vs 15.4 min with AI, p=0.22; all studies 28.4 min pooled, 28.9 vs 28.1, p=0.66). Used as an ASSUMED active-time scenario baseline in Table 4B.",
},
"cms_fy2027_ntap_max_usd": {
"value": 137.53,
"status": "OBSERVED",
"source": "CMS FY 2027 IPPS Final Rule (91 FR 49570, pp. 49680, 49737-49738, 49787; 42 CFR 412.88): separate CARE Multi-Triage CT Body (K252970 / XEZ5XKC), up to $137.53 (65% of $211.59) per eligible inpatient discharge; alternative pathway repealed from FY 2028 with transition through FY 2029 for Breakthrough designations by 30 Sep 2026 authorised by 1 May 2028.",
},
"ctpa_ai_pe_sensitivity_assumed": {
"value": 0.87,
"status": "ASSUMED",
"note": "Illustrative real-world PE triage sensitivity (87%; leaving 13% of PEs AI-silent in ordinary queue).",
},
"ctpa_incidental_lesion_prevalence_assumed": {
"value": 0.05,
"status": "ASSUMED",
"note": "Illustrative prevalence of actionable non-PE incidental lesions (50 per 1,000 CTPAs). K241727 has 0% labelled sensitivity for these.",
},
"ctpa_non_alerted_fraction_f_scenarios": {
"value": [1.0, 0.80],
"status": "ASSUMED",
"note": "Fraction f of incidental lesions lying on non-alerted scans: f = 1.00 represents a whole-workflow vigilance change across all 50 lesions; f = 0.80 represents a silence-only effect when ~20% of scans carry a PE alert (e.g. ~14% true-positive + ~6% false-positive alerts).",
},
"ctpa_human_usual_catch_rate_assumed": {
"value": 0.85,
"status": "ASSUMED",
"note": "Illustrative independent-first radiologist detection probability for the specified AI-silent or incidental lesion class.",
},
"ctpa_draft_time_multipliers": {
"value": [0.5, 0.75, 0.9, 1.0, 1.1, 1.25, 1.5],
"status": "ASSUMED",
"note": "Stress-test sweep for experimental draft-reporting total review + prior-comparison + edit + sign-off time relative to an assumed 15.5 min active-time baseline (1.0x = break-even).",
},
}
# ---------------------------------------------------------------------------
# Exact binomial 95% CI helper (Clopper-Pearson for k = 1, n = 130)
# ---------------------------------------------------------------------------
def clopper_pearson_k1(n: int, alpha: float = 0.05) -> tuple[float, float]:
"""Exact two-sided (1-alpha) binomial CI for k = 1 successes in n trials.
Lower bound: for k = 1, P(X >= 1 | p_lo) = 1 - (1 - p_lo)^n = alpha/2,
so p_lo = 1 - (1 - alpha/2)^(1/n).
Upper bound solves P(X <= 1 | p_hi) = (1 - p_hi)^n + n * p_hi * (1 - p_hi)^(n-1) = alpha/2
via deterministic bisection.
"""
p_lo = 1.0 - (1.0 - alpha / 2.0) ** (1.0 / n)
lo, hi = 0.0, 1.0
for _ in range(100):
mid = 0.5 * (lo + hi)
cdf = ((1.0 - mid) ** n) + n * mid * ((1.0 - mid) ** (n - 1))
if cdf > alpha / 2.0:
lo = mid
else:
hi = mid
p_hi = 0.5 * (lo + hi)
return p_lo, p_hi
# ---------------------------------------------------------------------------
# 1. Mammography screening (MASAI 1,000-exam cohort)
# ---------------------------------------------------------------------------
def build_mammography_rows() -> list[dict]:
ai_n = INPUTS["masai_ai_participants"]["value"]
ctrl_n = INPUTS["masai_control_participants"]["value"]
ai_reads_per_1000 = COHORT * INPUTS["masai_ai_screen_readings"]["value"] / ai_n
ctrl_reads_per_1000 = COHORT * INPUTS["masai_control_screen_readings"]["value"] / ctrl_n
ai_cons_per_1000 = COHORT * INPUTS["masai_ai_consensus_meetings"]["value"] / ai_n
ctrl_cons_per_1000 = COHORT * INPUTS["masai_control_consensus_meetings"]["value"] / ctrl_n
reads_avoided = ctrl_reads_per_1000 - ai_reads_per_1000
extra_consensus = ai_cons_per_1000 - ctrl_cons_per_1000
rows = []
for read_min in INPUTS["mammography_read_minutes_sweep"]["value"]:
for extra_cons_pmin in INPUTS["mammography_extra_consensus_person_min_sweep"]["value"]:
t_usual = ctrl_reads_per_1000 * read_min + ctrl_cons_per_1000 * extra_cons_pmin
t_ai = ai_reads_per_1000 * read_min + ai_cons_per_1000 * extra_cons_pmin
h_released = (t_usual - t_ai) / 60.0
rows.append(
{
"cohort_exams": COHORT,
"read_min_assumed": read_min,
"extra_consensus_person_min_assumed": extra_cons_pmin,
"usual_reads_per_1000_obs": round(ctrl_reads_per_1000, 1),
"ai_reads_per_1000_obs": round(ai_reads_per_1000, 1),
"gross_reads_avoided_per_1000": round(reads_avoided, 1),
"workload_reduction_pct": round(100.0 * reads_avoided / ctrl_reads_per_1000, 1),
"usual_consensus_per_1000_obs": round(ctrl_cons_per_1000, 2),
"ai_consensus_per_1000_obs": round(ai_cons_per_1000, 2),
"delta_consensus_per_1000": round(extra_consensus, 3),
"net_hours_released_per_1000": round(h_released, 2),
"obs_interval_cancer_usual_per_1000": 1.76,
"obs_interval_cancer_ai_per_1000": 1.55,
}
)
return rows
# ---------------------------------------------------------------------------
# 2. Autonomous Normal CXR (Plesner replay + hospital-wide + drift scenarios)
# ---------------------------------------------------------------------------
def odds_scale(prob: float, mult: float) -> float:
odds = prob / (1.0 - prob)
scaled = odds * mult
return scaled / (1.0 + scaled)
def build_cxr_rows() -> list[dict]:
c_base = INPUTS["plesner_ai_high_conf_normal_total"]["value"] / INPUTS["plesner_eligible_pa_films"]["value"]
q_clear_base = INPUTS["plesner_ai_critical_miss_in_clears"]["value"] / INPUTS["plesner_ai_high_conf_normal_total"]["value"]
q_total = INPUTS["cxr_overall_critical_prevalence_assumed"]["value"]
p_human_referred = 0.90 # ASSUMED conditional catch probability on critical findings
p_audit = p_human_referred # ASSUMED equal sensitivity on post-hoc audit (apples-to-apples)
rows = []
for e in INPUTS["cxr_eligible_fraction_scenarios"]["value"]:
for a in INPUTS["cxr_audit_fraction_scenarios"]["value"]:
for time_mult in (0.5, 1.0, 2.0):
t_easy = INPUTS["cxr_easy_film_read_min_baseline"]["value"] * time_mult
t_audit = INPUTS["cxr_audit_read_min_baseline"]["value"] * time_mult
oversight_hr = INPUTS["cxr_programme_oversight_hr_per_1000"]["value"]
cleared = COHORT * e * c_base
audited = cleared * a
t_saved_min = cleared * t_easy - audited * t_audit - oversight_hr * 60.0
h_released = t_saved_min / 60.0
for drift_mult in (1.0,) if time_mult != 1.0 else (0.5, 1.0, 2.0):
q_clear = odds_scale(q_clear_base, drift_mult)
n_elig = COHORT * e
n_ref = n_elig - cleared
q_ref = (n_elig * q_total - cleared * q_clear) / n_ref if n_ref > 0 else 0.0
m_usual = n_elig * q_total * (1.0 - p_human_referred)
m_ai_release = cleared * q_clear * 1.0 + n_ref * q_ref * (1.0 - p_human_referred)
m_ai_post_audit = cleared * q_clear * (1.0 - a * p_audit) + n_ref * q_ref * (1.0 - p_human_referred)
rows.append(
{
"cohort_exams": COHORT,
"eligible_fraction_e": e,
"clearance_rate_c_obs": round(c_base, 4),
"audit_fraction_a": a,
"time_multiplier": time_mult,
"drift_odds_mult": drift_mult,
"gross_reads_avoided": round(cleared, 1),
"audit_reads_added": round(audited, 1),
"net_hours_released": round(h_released, 2),
"q_clear_critical_pct": round(100.0 * q_clear, 3),
"expected_misses_usual": round(m_usual, 3),
"expected_misses_ai_at_release": round(m_ai_release, 3),
"delta_misses_at_release": round(m_ai_release - m_usual, 3),
"expected_misses_ai_post_audit": round(m_ai_post_audit, 3),
"delta_misses_post_audit": round(m_ai_post_audit - m_usual, 3),
}
)
return rows
# ---------------------------------------------------------------------------
# 2b. Audit detection power table (uses exact 1/130 for the Danish row!)
# ---------------------------------------------------------------------------
def build_audit_power_rows() -> list[dict]:
c_base = INPUTS["plesner_ai_high_conf_normal_total"]["value"] / INPUTS["plesner_eligible_pa_films"]["value"]
clears_per_1000_pa = COHORT * c_base # 85.023 clears
n_fixed_9 = 9 # Rounded fixed sample illustrating ~10% of 85 clears
n_fixed_21 = 21 # Rounded fixed sample illustrating ~25% of 85 clears
n_fixed_85 = 85 # Rounded fixed sample illustrating ~100% of 85 clears
# Exact fractions (label, exact probability)
rate_specs = [
("0.25%", 0.0025),
("0.5%", 0.005),
("1/130 (0.769%)", 1.0 / 130.0),
("1%", 0.01),
("2%", 0.02),
("5%", 0.05),
]
rows = []
for label, r in rate_specs:
for p_audit in (1.0, 0.8):
eff_r = r * p_audit
p_detect_9 = 1.0 - (1.0 - eff_r) ** n_fixed_9
p_detect_21 = 1.0 - (1.0 - eff_r) ** n_fixed_21
p_detect_85 = 1.0 - (1.0 - eff_r) ** n_fixed_85
n_80 = math.ceil(math.log(0.20) / math.log(1.0 - eff_r))
n_90 = math.ceil(math.log(0.10) / math.log(1.0 - eff_r))
n_95 = math.ceil(math.log(0.05) / math.log(1.0 - eff_r))
# Expected eligible PA throughput required to accumulate n_95 audited clears
exams_for_n95_at_100pct = math.ceil(n_95 / c_base)
exams_for_n95_at_10pct = math.ceil(n_95 / (c_base * 0.10))
rows.append(
{
"miss_rate_label": label,
"miss_rate_exact": round(r, 6),
"audit_human_sensitivity": p_audit,
"detect_prob_n9_pct": round(100.0 * p_detect_9, 2),
"detect_prob_n21_pct": round(100.0 * p_detect_21, 2),
"detect_prob_n85_pct": round(100.0 * p_detect_85, 2),
"audits_needed_80pct": n_80,
"audits_needed_90pct": n_90,
"audits_needed_95pct": n_95,
"expected_pa_throughput_95pct_100pct_audit": exams_for_n95_at_100pct,
"expected_pa_throughput_95pct_10pct_audit": exams_for_n95_at_10pct,
}
)
return rows
# ---------------------------------------------------------------------------
# 3. Acute CTPA triage & experimental draft-reporting stress test
# ---------------------------------------------------------------------------
def build_ctpa_rows() -> list[dict]:
pe_prev = INPUTS["rothenberg_pe_prevalence_phase2"]["value"]
ai_pe_sens = INPUTS["ctpa_ai_pe_sensitivity_assumed"]["value"]
inc_prev = INPUTS["ctpa_incidental_lesion_prevalence_assumed"]["value"]
p_usual = INPUTS["ctpa_human_usual_catch_rate_assumed"]["value"]
interp_min = INPUTS["rothenberg_elapsed_start_to_sign_no_resident_min"]["value"]
silent_pe_cases = COHORT * pe_prev * (1.0 - ai_pe_sens) # 20.67
incidental_cases_all = COHORT * inc_prev # 50.0 (f = 1.0 whole-workflow)
f_non_alert = 0.80 # ASSUMED ~80% of scans have no PE alert (silence-only denominator = 40.0)
incidental_cases_silent = incidental_cases_all * f_non_alert # 40.0
m_usual_silent_pe = silent_pe_cases * (1.0 - p_usual)
m_usual_inc_all = incidental_cases_all * (1.0 - p_usual)
m_usual_inc_silent = incidental_cases_silent * (1.0 - p_usual)
rows = []
for p_catch in (0.0, 0.50, 0.65, 0.75, 0.80, 0.85, 0.90, 0.95, 1.0):
m_ai_silent_pe = silent_pe_cases * (1.0 - p_catch)
m_ai_inc_all = incidental_cases_all * (1.0 - p_catch)
m_ai_inc_silent = incidental_cases_silent * (1.0 - p_catch)
rows.append(
{
"scenario_type": "anchoring_catch_sweep",
"draft_time_mult": 1.0,
"p_catch_assumed": p_catch,
"p_usual_assumed": p_usual,
"gross_reads_avoided": 0,
"net_hours_released": 0.0,
"pe_report_start_earlier_min_obs": round(
INPUTS["rothenberg_pe_report_start_wait_usual_min"]["value"]
- INPUTS["rothenberg_pe_report_start_wait_ai_min"]["value"],
1,
),
"silent_pe_cases_per_1000": round(silent_pe_cases, 2),
"delta_misses_silent_pe": round(m_ai_silent_pe - m_usual_silent_pe, 2),
"incidental_cases_f080_non_alerted": round(incidental_cases_silent, 2),
"delta_misses_incidental_f080_silence_only": round(m_ai_inc_silent - m_usual_inc_silent, 2),
"incidental_cases_f100_whole_workflow": round(incidental_cases_all, 2),
"delta_misses_incidental_f100_whole_workflow": round(m_ai_inc_all - m_usual_inc_all, 2),
}
)
for mult in INPUTS["ctpa_draft_time_multipliers"]["value"]:
t_usual = COHORT * interp_min
t_ai = COHORT * interp_min * mult
h_rel = (t_usual - t_ai) / 60.0
rows.append(
{
"scenario_type": "experimental_draft_time_sweep",
"draft_time_mult": mult,
"p_catch_assumed": p_usual,
"p_usual_assumed": p_usual,
"gross_reads_avoided": 0,
"net_hours_released": round(h_rel, 2),
"pe_report_start_earlier_min_obs": 0.0,
"silent_pe_cases_per_1000": round(silent_pe_cases, 2),
"delta_misses_silent_pe": 0.0,
"incidental_cases_f080_non_alerted": round(incidental_cases_silent, 2),
"delta_misses_incidental_f080_silence_only": 0.0,
"incidental_cases_f100_whole_workflow": round(incidental_cases_all, 2),
"delta_misses_incidental_f100_whole_workflow": 0.0,
}
)
return rows
# ---------------------------------------------------------------------------
# 4. Zero-dependency publication-grade SVG generators (clean, metadata-free)
# ---------------------------------------------------------------------------
def write_audit_power_svg(path: Path) -> None:
"""SVG plot: detection probability vs audited clears for r = 0.5%, 1%, 2%."""
w, h = 760, 420
pad_l, pad_r, pad_t, pad_b = 72, 34, 48, 62
pw, ph = w - pad_l - pad_r, h - pad_t - pad_b
max_n = 350
def sx(n: float) -> float:
return pad_l + (n / max_n) * pw
def sy(prob: float) -> float:
return pad_t + ph - prob * ph
curves = [
("2.0% miss rate (95% at n = 149)", 0.02, "#a44a2b", "2.6"),
("1.0% miss rate (95% at n = 299)", 0.01, "#1b4d6e", "2.6"),
("0.5% miss rate (95% at n = 598)", 0.005, "#6b655c", "2.2"),
]
lines = [
f'")
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
def write_anchoring_svg(path: Path) -> None:
"""SVG plot: Delta misses per 1,000 CTPAs vs human catch rate p_catch (f=0.80 silence-only and f=1.00 whole-workflow)."""
w, h = 760, 420
pad_l, pad_r, pad_t, pad_b = 72, 34, 48, 62
pw, ph = w - pad_l - pad_r, h - pad_t - pad_b
p_usual = INPUTS["ctpa_human_usual_catch_rate_assumed"]["value"]
inc_all = COHORT * INPUTS["ctpa_incidental_lesion_prevalence_assumed"]["value"] # 50.0
inc_silent = inc_all * 0.80 # 40.0 (silence-only, f = 0.80)
pe_silent = COHORT * INPUTS["rothenberg_pe_prevalence_phase2"]["value"] * (1.0 - INPUTS["ctpa_ai_pe_sensitivity_assumed"]["value"]) # 20.67
y_min, y_max = -10.0, 25.0
def sx(p: float) -> float:
return pad_l + ((p - 0.40) / 0.60) * pw
def sy(dm: float) -> float:
return pad_t + ph - ((dm - y_min) / (y_max - y_min)) * ph
lines = [
f'")
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
# ---------------------------------------------------------------------------
# Writers
# ---------------------------------------------------------------------------
def signed(x: float, nd: int) -> str:
"""Format with an explicit sign, but print a value that rounds to zero as plain zero."""
s = f"{x:+.{nd}f}"
return s[1:] if float(s) == 0.0 else s
def half_up(x: float, nd: int) -> str:
"""Round half away from zero for display (avoids 11.625 -> 11.62 under round-half-even)."""
return str(Decimal(repr(x)).quantize(Decimal(1).scaleb(-nd), rounding=ROUND_HALF_UP))
def write_csv(path: Path, rows: list[dict]) -> None:
with path.open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
writer.writeheader()
writer.writerows(rows)
def write_tables_md(
path: Path,
mammo: list[dict],
cxr: list[dict],
audit: list[dict],
ctpa: list[dict],
cp_lo: float,
cp_hi: float,
) -> None:
out = [
"# Generated Reference Tables (`models.py`)",
"",
"Every input is tagged **OBSERVED** or **ASSUMED** in `inputs.json`. All workflow outputs are expressed per **1,000 consecutive examinations** paired against usual care. Queue waiting time (exam completion to report start) is kept separate from radiologist labour.",
"",
"## Table 1: Mammography Screening (MASAI, 1,000-Exam Cohort)",
"",
"MASAI reported `61,248` total screen readings across `53,043` women (`1,154.7 / 1,000`; including `368` unprocessed exams routed to standard care) in the AI arm versus `109,692` across `52,872` women (`2,074.7 / 1,000`) in the control arm - a **44.2%** raw reduction (**44.3%** normalised, `920.0` gross reads avoided per 1,000). MASAI's published methods explicitly include consensus-meeting readings in those totals; `extra_consensus_person_min` tests only incremental coordination overhead (`+1.106` meetings per 1,000).",
"",
"| Mean 2D read time (ASSUMED) | Extra consensus overhead (ASSUMED) | Gross reads avoided / 1,000 (OBS) | Delta consensus meetings / 1,000 (OBS) | Net reader-hours released / 1,000 | Observed interval cancer rate (AI vs usual, / 1,000) |",
"|---:|---:|---:|---:|---:|:---:|",
]
for r in mammo:
out.append(
f"| {r['read_min_assumed']:.1f} min | +{r['extra_consensus_person_min_assumed']:.1f} person-min | "
f"{r['gross_reads_avoided_per_1000']:.1f} ({r['workload_reduction_pct']:.1f}%) | "
f"+{r['delta_consensus_per_1000']:.3f} | **{r['net_hours_released_per_1000']:.2f} hr** | "
f"{r['obs_interval_cancer_ai_per_1000']:.2f} vs {r['obs_interval_cancer_usual_per_1000']:.2f} (NI met; CI 0.65-1.18) |"
)
out += [
"",
"## Table 2: Autonomous Normal Chest X-Ray (Plesner Replay & Hospital-Wide Policy, 1,000-Exam Cohort)",
"",
f"Anchored in Plesner et al. (`130 / 1,529 = 8.50%` cleared from worklist; `120 / 1,529 = 7.85%` true normals; `1 / 130 = 0.769%` critical miss in clears, exact binomial 95% CI `{100*cp_lo:.3f}%` to `{100*cp_hi:.2f}%`). Baseline timing ASSUMED: `1.5 min` easy normal read, `2.0 min` audit read, `0.5 hr` programme QA oversight per 1,000 exams; human catch probability ASSUMED equal (`90%`) on contemporaneous and post-hoc reads (ignoring delay; zero post-audit delta at 100% audit says nothing about harm before correction).",
"",
"| Eligible PA share `e` | Random audit `a` | Drift odds mult | Gross reads avoided | Audit reads added | Net hours released (1x time) | Expected additional missed critical films at release | Residual delta after audit (ignoring delay) |",
"|---:|---:|---:|---:|---:|---:|---:|---:|",
]
for r in cxr:
if r["time_multiplier"] == 1.0 and (
(r["eligible_fraction_e"] == 1.0 and r["drift_odds_mult"] == 1.0)
or (r["eligible_fraction_e"] == 1.0 and r["audit_fraction_a"] == 0.10)
or (r["eligible_fraction_e"] == 0.7 and r["audit_fraction_a"] in (0.0, 0.10, 1.0) and r["drift_odds_mult"] == 1.0)
):
out.append(
f"| {r['eligible_fraction_e']:.2f} | {int(r['audit_fraction_a'] * 100)}% | {r['drift_odds_mult']:.1f}x | "
f"{r['gross_reads_avoided']:.1f} | {r['audit_reads_added']:.1f} | **{r['net_hours_released']:.2f} hr** | "
f"{signed(r['delta_misses_at_release'], 3)} | {signed(r['delta_misses_post_audit'], 3)} |"
)
out += [
"",
"## Table 3: Random QA Audit Detection Power on Autonomously Cleared Chest X-Rays",
"",
"At Plesner's `8.50%` clearance rate (`~85` clears per 1,000 eligible PA films), `n = 9` is the rounded fixed sample illustrating a 10% audit. The `1/130` row uses the exact fraction (giving **388** clears for 95% power, rather than 389 from rounded 0.769%). Throughput columns show expected eligible PA films needed to accumulate the required audit sample.",
"",
"| Serious miss rate in clears `r` | Human audit sensitivity | P(detect), fixed n = 9 | P(detect), fixed n = 85 | Clears audited for 95% power | Expected PA throughput for 95% (100% audit) | Expected PA throughput for 95% (10% audit) |",
"|:---|---:|---:|---:|---:|---:|---:|",
]
for r in audit:
out.append(
f"| {r['miss_rate_label']} | {int(r['audit_human_sensitivity'] * 100)}% | "
f"{r['detect_prob_n9_pct']:.2f}% | {r['detect_prob_n85_pct']:.2f}% | "
f"**{r['audits_needed_95pct']:,}** | {r['expected_pa_throughput_95pct_100pct_audit']:,} | "
f"{r['expected_pa_throughput_95pct_10pct_audit']:,} |"
)
out += [
"",
"## Table 4A: Acute CTPA Triage - Anchoring & Vigilance Catch-Rate Sweep (1,000-Exam Cohort)",
"",
"Aidoc `K241727` removes **0** diagnostic reads and confers **0%** labelled sensitivity for non-PE incidental lesions. In Rothenberg et al. (Aidoc US 8.0/8.1, 2021), PE-positive report starts occurred **10.2 min** earlier on average (`21.5 -> 11.3 min`; all scans `22.8 -> 15.9 min`, PE-negative `22.9 -> 16.7 min`, all `p < 0.001`) with zero reads removed. Baseline independent catch rate ASSUMED at `85%`; AI-silent PE share ASSUMED at `13%` of `15.9%` PE prevalence (`20.67 / 1,000`). For actionable incidental lesions (`5.0%` ASSUMED = `50 / 1,000`), a silence-only effect applies only to the fraction `f` on non-alerted scans (`f = 0.80` -> `40 / 1,000`, giving `+5f = +4.0` per 10-point drop); `f = 1.00` (`50 / 1,000`) shows a whole-workflow vigilance effect across all scans.",
"",
"| Human catch rate `p_catch` (ASSUMED) | Net labour hours released | Excess AI-silent PE misses / 1,000 | Excess incidental misses, silence-only (`f = 0.80`, 40/1k) | Excess incidental misses, whole-workflow (`f = 1.00`, 50/1k) |",
"|---:|---:|---:|---:|---:|",
]
for r in ctpa:
if r["scenario_type"] == "anchoring_catch_sweep":
out.append(
f"| {int(r['p_catch_assumed'] * 100)}% | {r['net_hours_released']:.1f} hr | "
f"{signed(r['delta_misses_silent_pe'], 2)} | {signed(r['delta_misses_incidental_f080_silence_only'], 2)} | "
f"{signed(r['delta_misses_incidental_f100_whole_workflow'], 2)} |"
)
out += [
"",
"## Table 4B: Experimental CT Draft-Reporting - Assumed Active Review & Edit Time Stress Test (1,000-Exam Cohort)",
"",
"Uses `15.5 min` as an **ASSUMED** active-time baseline (matching Rothenberg et al.'s pooled elapsed start-to-sign timestamp of `15.5 min` without a resident - `15.7` before vs `15.4` with AI, `p = 0.22`; all-study pooled elapsed time was `28.4 min`, `28.9` vs `28.1`, `p = 0.66`). Elapsed reporting timestamps are not pure active labour; multipliers are ASSUMED stress-test bounds.",
"",
"| Total review + prior-check + edit time vs. 15.5 min baseline (ASSUMED) | Gross reads avoided | Net hours released / 1,000 |",
"|---:|---:|---:|",
]
for r in ctpa:
if r["scenario_type"] == "experimental_draft_time_sweep":
out.append(
f"| {r['draft_time_mult']:.2f}x ({half_up(15.5 * r['draft_time_mult'], 2)} min) | 0 | **{signed(r['net_hours_released'], 2)} hr** |"
)
path.write_text("\n".join(out) + "\n", encoding="utf-8")
def main() -> None:
cp_lo, cp_hi = clopper_pearson_k1(INPUTS["plesner_ai_high_conf_normal_total"]["value"])
INPUTS["plesner_ai_critical_miss_ci95_exact_binomial"] = {
"value": [round(100.0 * cp_lo, 4), round(100.0 * cp_hi, 4)],
"status": "OBSERVED",
"source": "Exact Clopper-Pearson two-sided 95% binomial CI (%) for 1 critical miss in 130 cleared films.",
}
mammo = build_mammography_rows()
cxr = build_cxr_rows()
audit = build_audit_power_rows()
ctpa = build_ctpa_rows()
(OUT / "inputs.json").write_text(json.dumps(INPUTS, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
write_csv(OUT / "mammography_masai.csv", mammo)
write_csv(OUT / "cxr_autonomous.csv", cxr)
write_csv(OUT / "cxr_audit_power.csv", audit)
write_csv(OUT / "ctpa_triage_draft.csv", ctpa)
(OUT / "results.json").write_text(
json.dumps(
{
"inputs": INPUTS,
"mammography_masai": mammo,
"cxr_autonomous": cxr,
"cxr_audit_power": audit,
"ctpa_triage_draft": ctpa,
},
indent=2,
ensure_ascii=False,
)
+ "\n",
encoding="utf-8",
)
write_tables_md(OUT / "TABLES.md", mammo, cxr, audit, ctpa, cp_lo, cp_hi)
write_audit_power_svg(OUT / "audit_power.svg")
write_anchoring_svg(OUT / "anchoring_breakeven.svg")
print(f"Regenerated all v2.0 model outputs cleanly. Clopper-Pearson 1/130 95% CI: {100*cp_lo:.3f}%-{100*cp_hi:.2f}%.")
if __name__ == "__main__":
main()