junidude14 commited on
Commit
ca61c05
·
verified ·
1 Parent(s): cac97e4

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261013T034842Z-expanded-131-slide-master/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/expanded_disease_materials.py ADDED
@@ -0,0 +1,802 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Existing disease/rare-state evidence for the expanded original 76-slide master.
2
+
3
+ Only small saved tables, completed score receipts and existing figures are read.
4
+ No arrays, checkpoints, annotation, model inference or statistical fitting occurs.
5
+ All new files are confined to the expanded_master_20261013 disease directories.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import math
12
+ import os
13
+ import shutil
14
+ from datetime import datetime, timezone
15
+ from pathlib import Path
16
+
17
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+ import style as ST
22
+ import matplotlib.pyplot as plt
23
+ from matplotlib.patches import Patch
24
+ from matplotlib.ticker import MaxNLocator
25
+
26
+ D = Path(__file__).resolve().parents[1]
27
+ M = D.parents[1]
28
+ P = M / "plans/paper_figures_strictpairs_20261012"
29
+ U = M / "plans/utility_studies_final6k_20260925"
30
+ R = M / "plans/rare_states_screen_20261004"
31
+ B = M / "plans/bayesprism_paired_20261006"
32
+ BC = M / "plans/behcet_c1q_lora3_20261004"
33
+ BO = M / "plans/bulkonly_lora5_20261006"
34
+ K4 = M / "plans/bulkonly_lora5_k4000_20261006"
35
+ FIG = D / "figures/expanded_master_20261013/disease"
36
+ DATA = D / "data/expanded_master_20261013/disease"
37
+ MANIFEST = D / "data/expanded_master_20261013/disease_additions.json"
38
+
39
+ GOLD, BLUE, GREY, INK = "#C5AA4B", "#2166AC", "#909090", "#1A1A1A"
40
+ ARMS = ["raw", "refcal", "pairedcal", "scsemi", "lora"]
41
+ LABELS = {"raw": "Raw", "refcal": "Ref.\ncal.", "pairedcal": "Pair\ncal.",
42
+ "scsemi": "scSemi", "lora": "LoRA", "real_R2": "Real /\nreal"}
43
+ COLORS = {"raw": "#E9DFB9", "refcal": "#D7C788", "pairedcal": "#97802C",
44
+ "scsemi": BLUE, "lora": GOLD, "real_R2": GREY}
45
+ COHORTS = ["ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili"]
46
+ COHORT_LABELS = ["Sepsis", "Imperial", "Giroux", "Ji"]
47
+ TYPES = ["T cell", "B cell", "Monocyte", "NK cell", "DC"]
48
+ TYPE_LABELS = ["T cells", "B cells", "Monocytes", "NK cells", "DC"]
49
+ STATE_SHORT = {
50
+ "C1Q-high monocyte (reference)": "C1Q-high mono",
51
+ "Cycling activated T (CD38/HLA-DR)": "Cycling activated T",
52
+ "Cycling monocyte (Ye 2026)": "Cycling mono",
53
+ "ISG-high monocyte (positive control)": "ISG-high mono (+ control)",
54
+ "Platelet signal in monocytes (negative control)": "Platelet in mono (− control)",
55
+ "MS1 monocyte (IL1R2+)": "MS1 mono (IL1R2+)",
56
+ }
57
+ HISTORICAL = ("Historical five-donor training can include multiple paired visits in Imperial, Giroux and Ji. "
58
+ "It is not the strict five-sample protocol. Existing predictions and frozen marker/label rules are reused.")
59
+ STRICT_NOTE = ("Exactly one paired sample from each of five donors, no extra validation, fixed 3000-step LoRA. "
60
+ "Only completed score receipts are used. Raw, external-reference calibration, same-pair calibration, "
61
+ "scSemiProfiler and LoRA share the recorded held-out targets. Dots are support draws, not independent "
62
+ "population replicates. These slides do not certify the unfinished four-cohort campaign.")
63
+
64
+
65
+ class Unavailable(ValueError):
66
+ """A requested panel has insufficient existing, verifiable evidence."""
67
+
68
+
69
+ def sha(path: Path) -> str:
70
+ with path.open("rb") as f:
71
+ return hashlib.file_digest(f, "sha256").hexdigest()
72
+
73
+
74
+ def short_state(state: str) -> str:
75
+ return STATE_SHORT.get(state, state)
76
+
77
+
78
+ def truth(series: pd.Series) -> pd.Series:
79
+ values = series.astype(str).str.lower()
80
+ if not values.isin(["true", "false"]).all():
81
+ raise Unavailable("boolean gate contains missing or unrecognized values")
82
+ return values.eq("true")
83
+
84
+
85
+ class Builder:
86
+ def __init__(self):
87
+ self.sources: dict[str, dict] = {}
88
+ self.assets: list[str] = []
89
+ self.slides: list[dict] = []
90
+ self.dropped: list[dict] = []
91
+ self.strict: dict[tuple[str, int], dict] = {}
92
+ self.started_at = datetime.now(timezone.utc).isoformat()
93
+ FIG.mkdir(parents=True, exist_ok=True)
94
+ DATA.mkdir(parents=True, exist_ok=True)
95
+
96
+ def source(self, path: Path, role: str = "existing scientific evidence") -> Path:
97
+ path = path.resolve()
98
+ if not path.is_file():
99
+ raise Unavailable(f"missing source: {path}")
100
+ if path.suffix.lower() in {".npz", ".npy", ".h5ad", ".pt", ".pth", ".rds"}:
101
+ raise Unavailable(f"large-array/model input is outside saved-table plotting scope: {path}")
102
+ if path.stat().st_size > 20_000_000:
103
+ raise Unavailable(f"source exceeds bounded saved-table budget: {path}")
104
+ record = {"path": str(path), "sha256": sha(path), "bytes": path.stat().st_size, "role": role}
105
+ if str(path) in self.sources and self.sources[str(path)]["sha256"] != record["sha256"]:
106
+ raise Unavailable(f"source changed during the build: {path}")
107
+ self.sources[str(path)] = record
108
+ return path
109
+
110
+ def table(self, path: Path, role: str = "saved score table") -> pd.DataFrame:
111
+ path = self.source(path, role)
112
+ if path.is_relative_to(P / "scores"):
113
+ target = DATA / "strict_snapshot_tables" / path.relative_to(P)
114
+ target.parent.mkdir(parents=True, exist_ok=True)
115
+ shutil.copy2(path, target)
116
+ if sha(target) != self.sources[str(path)]["sha256"]:
117
+ raise Unavailable("strict table changed during snapshot")
118
+ self.assets.append(str(target))
119
+ return pd.read_csv(path)
120
+
121
+ def document(self, path: Path, role: str = "saved protocol/provenance") -> dict:
122
+ return json.loads(self.source(path, role).read_text())
123
+
124
+ def save_table(self, frame: pd.DataFrame, key: str) -> Path:
125
+ path = DATA / f"{key}.csv"
126
+ frame.to_csv(path, index=False)
127
+ self.assets.append(str(path))
128
+ self.source(path, "derived display table; no new statistical fit")
129
+ return path
130
+
131
+ def save(self, fig, key: str) -> Path:
132
+ for ext in ("png", "pdf", "svg"):
133
+ path = FIG / f"{key}.{ext}"
134
+ fig.savefig(path, dpi=ST.DPI, bbox_inches="tight", pad_inches=0.07, facecolor="white")
135
+ self.assets.append(str(path))
136
+ plt.close(fig)
137
+ return FIG / f"{key}.png"
138
+
139
+ def add(self, key: str, title: str, figure: Path, after: int, footnote: str, notes: str,
140
+ refs: list[Path], *, section: str = "Additional evidence", palette: str = "native"):
141
+ if len(title) > 60 or len(footnote) > 180:
142
+ raise ValueError(f"slide text exceeds agreed length: {key}")
143
+ if "disease_" + key in {s["key"] for s in self.slides}:
144
+ raise ValueError(f"duplicate addition key: {key}")
145
+ figure = self.source(figure, "display figure")
146
+ records = [self.source(p) for p in refs]
147
+ source_text = "; ".join(str(p.relative_to(M)) if p.is_relative_to(M) else str(p) for p in records)
148
+ full = notes + "\nSources: " + source_text
149
+ self.slides.append({"kind": "content", "layout": "full", "key": "disease_" + key,
150
+ "title": title, "section_label": section, "figures": [str(figure.relative_to(D)) if figure.is_relative_to(D) else str(figure)],
151
+ "keywords": [], "footnote": footnote, "footnote_full": full,
152
+ "sources": source_text, "notes": full, "after_original": after,
153
+ "palette": palette, "new_experiment": False})
154
+
155
+ def ready(self, key, title, figure, after, footnote, notes, refs, section="External diagnostic"):
156
+ self.add(key, title, figure, after, footnote, notes, refs, section=section, palette="biological")
157
+
158
+ def attempt(self, key: str, operation):
159
+ try:
160
+ operation()
161
+ except (Unavailable, FileNotFoundError, KeyError) as e:
162
+ self.dropped.append({"candidate": key, "reason": str(e), "action": "not displayed; no replacement experiment"})
163
+
164
+ def snapshot_unit(self, cohort: str, draw: int) -> dict:
165
+ unit = (cohort, draw)
166
+ if unit in self.strict:
167
+ return self.strict[unit]
168
+ receipt = P / f"receipts/{cohort}-disease-draw{draw}-score.json"
169
+ record = self.document(receipt, "completed strict score receipt")
170
+ if record.get("state") != "completed":
171
+ raise Unavailable(f"score receipt is not completed: {receipt}")
172
+ base = P / f"scores/{cohort}/disease/draw{draw}"
173
+ support_path = P / f"protocol/splits/{cohort}/disease/draw{draw}/support.json"
174
+ support = self.document(support_path, "strict exact-support manifest")
175
+ body = {k: v for k, v in support.items() if k != "sha256"}
176
+ digest = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
177
+ if support.get("sha256") != digest or len(set(support["train_sample_ids"])) != 5 or len(set(support["train_donor_ids"])) != 5:
178
+ raise Unavailable("strict support identity/hash is invalid")
179
+ verified = []
180
+ for output in record.get("outputs", []):
181
+ path = self.source(Path(output["path"]), "completed strict score output")
182
+ if sha(path) != output["sha256"] or path.stat().st_size != output["bytes"]:
183
+ raise Unavailable(f"completed receipt/output mismatch: {path}")
184
+ verified.append(path)
185
+ required = {base / "score/summary.json", base / "statistics/status.json"}
186
+ if not required <= set(verified):
187
+ raise Unavailable("score receipt does not bind both summary and corrected statistics")
188
+ status = self.document(base / "statistics/status.json")
189
+ if status.get("support_sha256") != support["sha256"] or status.get("disease_deg", {}).get("status") != "ok":
190
+ raise Unavailable("corrected strict statistics are incomplete or support differs")
191
+ summary = self.document(base / "score/summary.json")
192
+ if set(summary.get("headline", {})) != set(ARMS):
193
+ raise Unavailable("strict comparator family is incomplete")
194
+ folder = DATA / "strict_snapshot" / cohort / f"draw{draw}"
195
+ folder.mkdir(parents=True, exist_ok=True)
196
+ for path in [receipt, support_path, *verified]:
197
+ rel = path.relative_to(P)
198
+ target = folder / rel
199
+ target.parent.mkdir(parents=True, exist_ok=True)
200
+ shutil.copy2(path, target)
201
+ if sha(target) != sha(path):
202
+ raise Unavailable("strict snapshot copy hash mismatch")
203
+ self.assets.append(str(target))
204
+ result = {"base": base, "receipt": receipt, "support": support_path, "summary": summary,
205
+ "status": status, "verified_outputs": [str(x) for x in verified]}
206
+ self.strict[unit] = result
207
+ return result
208
+
209
+
210
+ def bar_metrics(builder: Builder, rows: pd.DataFrame, columns: list[tuple[str, str]], key: str,
211
+ order: list[str] = ARMS, control: bool = False) -> Path:
212
+ fig, axes = plt.subplots(1, len(columns), figsize=ST.FULL, squeeze=False)
213
+ fig.subplots_adjust(left=0.075, right=0.98, bottom=0.26 if len(order) > 5 else 0.21,
214
+ top=0.91, wspace=0.36)
215
+ for ax, (metric, label) in zip(axes[0], columns):
216
+ for i, arm in enumerate(order):
217
+ values = pd.to_numeric(rows.loc[rows.arm == arm, metric], errors="raise").to_numpy()
218
+ if len(values) == 0 or not np.isfinite(values).all():
219
+ raise Unavailable(f"missing/nonfinite values for {key}/{arm}/{metric}")
220
+ ax.bar(i, values.mean(), color=COLORS[arm], width=0.72, zorder=2)
221
+ if len(values) > 1:
222
+ ax.scatter(i + np.linspace(-0.11, 0.11, len(values)), values, s=20, color="white",
223
+ edgecolor=INK, linewidth=0.55, zorder=3)
224
+ dense_labels = {"real_R2": "Real", "raw": "Raw", "refcal": "Ref", "pairedcal": "Pair",
225
+ "scsemi": "scSP", "lora": "LoRA"}
226
+ ax.set_xticks(range(len(order)), [dense_labels[x] if len(order) > 5 else LABELS[x] for x in order], fontsize=12)
227
+ ax.tick_params(axis="x", length=0, pad=8)
228
+ ax.set_ylabel(label)
229
+ ax.grid(axis="y", color="#E8E8E8", linewidth=0.7, zorder=0)
230
+ ax.set_axisbelow(True)
231
+ ax.yaxis.set_major_locator(MaxNLocator(nbins=5))
232
+ if metric in ("precision", "coverage", "c2st_knn_auc"):
233
+ ax.set_ylim(0, 1.05)
234
+ if metric == "c2st_knn_auc":
235
+ ax.axhline(0.5, color=INK, linestyle="--", linewidth=0.8)
236
+ if len(order) > 5:
237
+ fig.text(0.53, 0.055,
238
+ "Real: real/real control · Ref: external-reference calibration · Pair: same-pair calibration · scSP: scSemiProfiler",
239
+ ha="center", fontsize=12, color="#4D4D4D")
240
+ return builder.save(fig, key)
241
+
242
+
243
+ def heat(ax, values: pd.DataFrame, title: str = "", *, vmin=0, vmax=None, cmap="Greys",
244
+ fmt=".2g", show_y=True, text_size=12):
245
+ matrix = values.to_numpy(dtype=float)
246
+ cm = plt.get_cmap(cmap).copy(); cm.set_bad("#F2F2F2")
247
+ if vmax is None:
248
+ vmax = float(np.nanmax(matrix)) if np.isfinite(matrix).any() else 1
249
+ if vmax <= vmin:
250
+ vmax = vmin + 1
251
+ im = ax.imshow(matrix, aspect="auto", interpolation="nearest", vmin=vmin, vmax=vmax, cmap=cm)
252
+ ax.set_xticks(range(len(values.columns)), values.columns, fontsize=12)
253
+ ax.xaxis.tick_top()
254
+ if show_y:
255
+ ax.set_yticks(range(len(values)), values.index, fontsize=12)
256
+ else:
257
+ ax.set_yticks([])
258
+ ax.tick_params(axis="both", length=0, pad=7)
259
+ ax.set_xticks(np.arange(-0.5, len(values.columns), 1), minor=True)
260
+ ax.set_yticks(np.arange(-0.5, len(values), 1), minor=True)
261
+ ax.grid(which="minor", color="white", linewidth=1.2); ax.tick_params(which="minor", length=0)
262
+ for spine in ax.spines.values(): spine.set_visible(False)
263
+ for i in range(len(values)):
264
+ for j in range(len(values.columns)):
265
+ x = matrix[i, j]
266
+ rgb = im.cmap(im.norm(x))[:3] if np.isfinite(x) else (1, 1, 1)
267
+ luminance = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]
268
+ ax.text(j, i, "NA" if not np.isfinite(x) else format(x, fmt), ha="center", va="center",
269
+ fontsize=text_size, color="white" if luminance < 0.45 else INK)
270
+ if title: ax.set_title(title, fontsize=14, loc="left", pad=36)
271
+ return im
272
+
273
+
274
+ def strict_panels(b: Builder):
275
+ units = [b.snapshot_unit("ye2026_sepsis", draw) for draw in range(5)]
276
+ rows = pd.DataFrame([dict(arm=arm, draw=draw, **unit["summary"]["headline"][arm])
277
+ for draw, unit in enumerate(units) for arm in ARMS])
278
+ table = b.save_table(rows, "strict_sepsis_quality")
279
+ refs = [unit["receipt"] for unit in units] + [table]
280
+ fig = bar_metrics(b, rows, [("precision", "Precision ↑"), ("coverage", "Coverage ↑"),
281
+ ("comp_l1", "Composition L1 ↓")], "strict_sepsis_quality")
282
+ b.add("strict_sepsis_quality", "Sepsis: exact-five reconstruction across five draws", fig, 38,
283
+ "Completed exact-five Sepsis draws. Bars = means; dots = support draws. Five matched methods; no new generation.",
284
+ STRICT_NOTE + " Precision, coverage and composition are read directly from completed score summaries.", refs, section="Fig. 4 update")
285
+ extras = []
286
+ extra_refs = []
287
+ for draw, unit in enumerate(units):
288
+ root = unit["base"] / "extras/ye2026_sepsis/strict"
289
+ mf, ef = root / "metrics.csv", root / "en.csv"
290
+ metrics, en = b.table(mf), b.table(ef)
291
+ metrics = metrics[(metrics.real_side == "R1") & (metrics["mode"] == "raw")].copy()
292
+ en = en[(en.cellset == "pc") & (en.distance == "sq")]
293
+ for arm in ["real_R2", *ARMS]:
294
+ a = metrics[metrics["set"] == arm]; e = en[en["set"] == arm]
295
+ if len(a) != 1 or len(e) != 1: raise Unavailable("strict realism selection is not unique")
296
+ extras.append({"draw": draw, "arm": arm, "c2st_knn_auc": a.iloc[0].c2st_knn_auc,
297
+ "mmd2_bw1": a.iloc[0]["mmd2_bw1"], "en": e.iloc[0].en})
298
+ extra_refs += [mf, ef]
299
+ extra = pd.DataFrame(extras); ex = b.save_table(extra, "strict_sepsis_realism")
300
+ fig = bar_metrics(b, extra, [("c2st_knn_auc", "C2ST AUROC (0.5 ideal)"), ("mmd2_bw1", "MMD² ↓"),
301
+ ("en", "E_N, PC sample ↓")], "strict_sepsis_realism", ["real_R2", *ARMS])
302
+ b.add("strict_sepsis_realism", "Sepsis: realism beyond precision and coverage", fig, 38,
303
+ "Completed exact-five outputs; raw readout, fixed R1 reference. Real/real control shown. Dots are five support draws.",
304
+ STRICT_NOTE + " C2ST uses cached kNN AUROC; MMD uses bandwidth 1; E_N uses the saved PC subsample, squared distance and exact lower bound. No refitting.",
305
+ extra_refs + [ex], section="Fig. 4 update")
306
+ strict_deg(b, "ye2026_sepsis", units, 40)
307
+
308
+
309
+ def strict_deg(b: Builder, cohort: str, units: list[dict], after: int):
310
+ frames, refs = [], []
311
+ for j, unit in enumerate(units):
312
+ path = unit["base"] / "statistics/donor_deg/donor_deg_summary.csv"
313
+ frame = b.table(path); frame["draw"] = j
314
+ if not frame.status.eq("ok").all(): raise Unavailable("corrected DEG rows are not all complete")
315
+ if len(frame) != 25: raise Unavailable("unexpected corrected DEG comparator/type count")
316
+ frames.append(frame); refs += [path, unit["receipt"], unit["base"] / "statistics/status.json"]
317
+ table = pd.concat(frames, ignore_index=True)
318
+ vals = table.groupby(["celltype", "arm"]).top50_overlap_count.mean().unstack().reindex(index=TYPES, columns=ARMS)
319
+ vals.index = TYPE_LABELS; vals.columns = [LABELS[x] for x in ARMS]
320
+ fig, ax = plt.subplots(figsize=ST.FULL); fig.subplots_adjust(left=0.18, right=0.90, bottom=0.13, top=0.90)
321
+ heat(ax, vals, vmax=50, cmap="YlOrBr", fmt=".1f")
322
+ fig.text(0.54, 0.045, "Observed / generated top-50 overlap (0–50)", ha="center", fontsize=14)
323
+ key = "strict_" + cohort + "_deg"
324
+ display = b.save_table(table, key)
325
+ figure = b.save(fig, key)
326
+ name = "Sepsis" if cohort == "ye2026_sepsis" else "Imperial"
327
+ title = f"{name}: patient-aware disease-gene agreement"
328
+ foot = "Completed corrected count-based DEG fits; mean of five support draws." if len(units) == 5 else "Single completed exact-five draw 0; patient-aware DEG fits. Other draws are outside this frozen snapshot."
329
+ b.add(key, title, figure, after, foot,
330
+ STRICT_NOTE + " Values are saved FDR-filtered top-50 list overlap counts, not correlations or cell classification accuracy. "
331
+ "The recorded method is edgeR/TMM/limma-voom, with donor duplicateCorrelation for Imperial. "
332
+ "A donor can contribute to both disease conditions; group donor counts must not be summed as independent people. "
333
+ "Historical sample-level Welch metrics are different endpoints.", refs + [display], section="Fig. 4 update")
334
+
335
+
336
+ def imperial_panels(b: Builder):
337
+ unit = b.snapshot_unit("imperial_eskd", 0)
338
+ rows = pd.DataFrame([dict(arm=arm, draw=0, **unit["summary"]["headline"][arm]) for arm in ARMS])
339
+ table = b.save_table(rows, "strict_imperial_draw0_quality")
340
+ fig = bar_metrics(b, rows, [("precision", "Precision ↑"), ("coverage", "Coverage ↑"),
341
+ ("comp_l1", "Composition L1 ↓")], "strict_imperial_draw0_quality")
342
+ b.add("strict_imperial_quality", "Imperial: first completed exact-five comparison", fig, 38,
343
+ "One completed support draw (draw 0). Exact five paired samples; all five methods scored. Not the final five-draw comparison.",
344
+ STRICT_NOTE + " Single-draw evidence is shown separately from the complete Sepsis set. Repeated held-out visits remain linked to actual donor IDs.",
345
+ [unit["receipt"], unit["support"], table], section="Fig. 4 update")
346
+ strict_deg(b, "imperial_eskd", [unit], 40)
347
+
348
+
349
+ def external_figures(b: Builder):
350
+ b.ready("sle_broadcast", "SLE: what is added beyond the bulk broadcast?",
351
+ D / "figures/sec04_sle_broadcast.png", 43,
352
+ "Existing SLE pseudobulk development benchmark; bulk broadcast is an explicit comparator. Separate from paired real-bulk validation.",
353
+ "Existing figure omitted from the original 76-slide specification. Retain its gene axis, cell-type units and seed counts. "
354
+ "This is a pseudobulk-conditioned benchmark, not a new external real-bulk result.",
355
+ [D / "data/sec04_sle_broadcast.csv", D / "tools/sec04_sle_benchmark.py"], section="Development benchmark")
356
+ q = U / "randolph"
357
+ b.ready("influenza_response", "Influenza: response order versus response genes",
358
+ q / "out/fig_randolph_celltype_response.png", 43,
359
+ "Historical zero-shot influenza test. Response-strength ordering is recovered; gene-wise agreement remains below the matched bulk broadcast.",
360
+ "Generated cells rank monocytes as strongest and T cells as weakest responders, but fail the preregistered "
361
+ "gene-wise beyond-broadcast rule. Different arms can have different eligible donor counts; each broadcast matches its arm's donors. "
362
+ "Observed-PBMC broadcast is an oracle. No new fitting or cell generation.",
363
+ [q / "RESULTS.md", q / "MANIFEST.json", q / "out/extended/extended_analysis.json"])
364
+ q = U / "refcal_scoring/arunachalam"
365
+ common = [q / "RESULTS.md", q / "MANIFEST.json", q / "receipts/receipt_checks.json"]
366
+ b.ready("covid_map", "COVID: calibration on a shared real-cell map",
367
+ q / "placement/figures/fig1_umap_seven_panels_by_label_depth1000.png", 43,
368
+ "Historical 7 COVID / 5 HC samples, common depth. High-resolution reference overview; following detail panels provide readable quantitative results.",
369
+ "This is an existing zero-shot input/calibration study, not LoRA/scSemiProfiler. Observed cells define the reference map. "
370
+ "Use saved quantitative endpoints rather than interpreting overlap as a performance score. Biological cell-type colors are preserved.",
371
+ common + [q / "placement/tables/prec_cov.csv", q / "placement/tables/composition_full_chain.csv"])
372
+ b.ready("covid_direction", "COVID monocytes: direction after depth matching",
373
+ q / "placement/figures/fig2_covid_hc_monocyte_arrows_depth1000.png", 43,
374
+ "Historical 7 COVID / 5 HC samples, common depth. High-resolution reference overview; following panels separate direction, magnitude and relabeling null.",
375
+ "Native-depth and depth-matched results differ. Relabelling-null shares are descriptive; not every directional cosine "
376
+ "exceeds its null. No claim of independent significance or completed Figure 6 reproduction.",
377
+ common + [q / "placement/tables/displacement.csv", q / "placement/tables/displacement_relabel_null.csv"])
378
+
379
+
380
+ def covid_endpoints(b: Builder):
381
+ q = U / "refcal_scoring/arunachalam"
382
+ src = q / "effects_final/endpoints_paired12.csv"
383
+ rows = b.table(src)
384
+ endpoints = ["P1", "P2", "P3", "P4"]
385
+ names = ["ISG / monocyte", "HLA-DR / CD14 mono", "Plasma-cell fraction", "Plasmablast genes"]
386
+ arms = ["gen_raw", "gen_tpm", "gen_refcalHC", "gen_cal", "gen_pseudo"]
387
+ arm_names = ["Raw", "TPM", "Ref.\ncal.", "Pair\ncal.", "Pseudo"]
388
+ show = rows[rows.endpoint.isin(endpoints) & rows.source.isin(arms)].copy()
389
+ if len(show) != 20: raise Unavailable("COVID endpoint selection is not exactly four endpoints by five arms")
390
+ fig, axes = plt.subplots(1, 2, figsize=ST.FULL); fig.subplots_adjust(left=0.22, right=0.98, top=0.80, bottom=0.13, wspace=0.18)
391
+ for ax, metric, title, low, high in zip(axes, ["ratio_to_observed", "donor_spearman_with_observed"],
392
+ ["Effect / observed (1 = matched)", "Donor ranking (Spearman ρ)"], [0, -1], [2, 1]):
393
+ vals = show.pivot(index="endpoint", columns="source", values=metric).reindex(index=endpoints, columns=arms)
394
+ vals.index = names; vals.columns = arm_names
395
+ heat(ax, vals, title, vmin=low, vmax=high, cmap="Greys", show_y=ax is axes[0], fmt=".2f")
396
+ table = b.save_table(show, "covid_endpoints")
397
+ b.add("covid_endpoints", "COVID: biological endpoints give a mixed verdict", b.save(fig, "covid_endpoints"), 43,
398
+ "Historical 7 COVID / 5 HC samples. Saved effect ratios and donor ranks; no new fits. Reference calibration is not uniformly best.",
399
+ "Four predefined endpoints are all retained. Reference calibration improves some plasmablast/composition endpoints "
400
+ "but loses HLA-DR donor ranking and overshoots the ISG effect. All generated arms fail the original preregistered "
401
+ "gene-wide beyond-broadcast criterion; the alternate pipeline definition is not substituted.",
402
+ [src, table, q / "RESULTS.md", q / "global_r/global_logfc_r_two_definitions.csv"], section="External diagnostic")
403
+
404
+
405
+ def covid_direction_details(b: Builder):
406
+ """Enlarge saved direction/length/null metrics without fitting an embedding."""
407
+ q = U / "refcal_scoring/arunachalam"
408
+ src = q / "placement/tables/displacement.csv"
409
+ rows = b.table(src)
410
+ arms = ["real_holdout", "gen_raw", "gen_tpm", "gen_refcalHC", "gen_refcalAll", "gen_cal", "gen_pseudo"]
411
+ labels = ["Real held-out", "Raw bulk", "TPM bulk", "Ref-cal HC", "Ref-cal all", "Paired cal", "sc pseudobulk"]
412
+ for population, name, key in [("Monocyte (L1)", "monocytes", "covid_monocyte_direction_detail"),
413
+ ("CD14 monocyte (L2)", "CD14 monocytes", "covid_cd14_direction_detail")]:
414
+ # The label is required exactly as recorded; no population substitution.
415
+ sub = rows[(rows.population == population) & rows["set"].isin(arms) & rows.depth.isin(["native", "depth1000"])].copy()
416
+ if len(sub) != 14 or sub.duplicated(["depth", "set"]).any():
417
+ raise Unavailable(f"saved displacement rows incomplete: {population}")
418
+ fig, axes = plt.subplots(1, 3, figsize=ST.FULL, sharey=True)
419
+ fig.subplots_adjust(left=0.19, right=0.985, bottom=0.15, top=0.81, wspace=0.22)
420
+ metrics = [("cos_pca50", "Direction cosine"), ("length_ratio_pca50", "Step length / real"),
421
+ ("share_relabelings_cos_ge_true", "Relabeling-null share")]
422
+ for ax, (metric, xlabel) in zip(axes, metrics):
423
+ for depth, offset, marker, face, edge in [("native", -0.13, "o", "white", INK),
424
+ ("depth1000", 0.13, "D", GOLD, INK)]:
425
+ values = sub[sub.depth == depth].set_index("set").loc[arms, metric].to_numpy(dtype=float)
426
+ if not np.isfinite(values).all(): raise Unavailable("saved COVID direction metric is nonfinite")
427
+ ax.scatter(values, np.arange(7) + offset, s=55, marker=marker,
428
+ facecolor=face, edgecolor=edge, linewidth=0.8, zorder=3)
429
+ ax.set_xlabel(xlabel)
430
+ ax.grid(axis="x", color="#EAEAEA", linewidth=0.7)
431
+ ax.set_axisbelow(True)
432
+ ax.tick_params(axis="y", length=0, labelsize=12)
433
+ ax.xaxis.set_major_locator(MaxNLocator(nbins=4))
434
+ if metric == "cos_pca50":
435
+ ax.set_xlim(-0.05, 1.05)
436
+ ax.axvline(1, color=GREY, linewidth=0.8, linestyle="--")
437
+ elif metric == "length_ratio_pca50":
438
+ ax.set_xlim(0, max(1.1, float(sub[metric].max()) * 1.08))
439
+ ax.axvline(1, color=GREY, linewidth=0.8, linestyle="--")
440
+ else:
441
+ ax.set_xlim(0, max(0.1, float(sub[metric].max()) * 1.12))
442
+ axes[0].set_yticks(np.arange(7), labels)
443
+ axes[0].set_ylim(6.6, -0.6)
444
+ from matplotlib.lines import Line2D
445
+ fig.legend([Line2D([], [], linestyle="none", marker="o", markerfacecolor="white", markeredgecolor=INK, markersize=7),
446
+ Line2D([], [], linestyle="none", marker="D", markerfacecolor=GOLD, markeredgecolor=INK, markersize=7)],
447
+ ["Native depth", "Depth-matched to 1,000"], loc="upper center", ncol=2, fontsize=12)
448
+ fig.text(0.58, 0.035, "Saved PCA-50 metrics; no new embedding, projection or statistical fit", ha="center", fontsize=12, color="#4D4D4D")
449
+ out = b.save_table(sub, key)
450
+ b.add(key, f"COVID {name}: direction, magnitude and null", b.save(fig, key), 43,
451
+ "Readable detail of the retained COVID overview. Existing 7 COVID / 5 HC paired samples; native and depth-matched results stay separate.",
452
+ "Every saved arm is retained, including the held-out real-cell reference, raw, TPM, both reference calibrations, "
453
+ "paired calibration and own-sc-pseudobulk conditions. Cosine and length ratio use the recorded PCA-50 disease displacement; "
454
+ "they are not read from the 2D UMAP. Relabeling-null share is the existing descriptive fraction of label permutations "
455
+ "whose cosine is at least the observed one, not a newly fitted p-value or proof of biological reproduction. "
456
+ "The full original depth-matched spatial overview remains in the deck. Only native UMAP coordinates were persisted "
457
+ "in embedding_native_cells.parquet; these detail panels use saved numeric displacement tables instead of refitting depth-matched UMAP.",
458
+ [src, out, q / "placement/tables/displacement_relabel_null.csv", q / "RESULTS.md"], section="External diagnostic")
459
+
460
+
461
+ def rare_misses(b: Builder):
462
+ src = P / "source_data/rare_all_states_aggregate.csv"
463
+ rows = b.table(src)
464
+ order_source = b.table(P / "source_data/rare_all_states.csv")
465
+ states = list(dict.fromkeys(order_source.state))
466
+ if len(states) != 15: raise Unavailable("rare rule set changed; do not silently omit states")
467
+ for number, selected in enumerate([states[:8], states[8:]], 1):
468
+ fig, axes = plt.subplots(1, 2, figsize=ST.FULL)
469
+ fig.subplots_adjust(left=0.30, right=0.98, top=0.80, bottom=0.10, wspace=0.12)
470
+ display = []
471
+ for ax, arm, title, color in zip(axes, ["lora5", "scsemi5"], ["PBISC LoRA", "scSemiProfiler"], [GOLD, BLUE]):
472
+ frame = rows[rows.arm == arm]
473
+ vals = frame.pivot(index="state", columns="cohort", values="missed_observed_fraction").reindex(index=selected, columns=COHORTS) * 100
474
+ display.append(vals.reset_index().assign(arm=arm))
475
+ vals.index = [short_state(x) for x in selected]; vals.columns = COHORT_LABELS
476
+ heat(ax, vals, title, vmax=100, cmap="Greys", show_y=ax is axes[0], fmt=".0f")
477
+ ax.title.set_color(color)
478
+ fig.text(0.64, 0.025, "Observed-positive donors missed (%) · lower is better", ha="center", fontsize=13)
479
+ key = f"rare_misses_{number}"
480
+ table = b.save_table(pd.concat(display, ignore_index=True), key)
481
+ b.add(key, f"Rare-state misses: rules {1 if number == 1 else 9}–{8 if number == 1 else 15}",
482
+ b.save(fig, key), 50,
483
+ "Saved zero-aware diagnostic; all 15 predefined rules are shown across two slides. NA means not evaluable, not zero error.",
484
+ HISTORICAL + " Each percentage is the saved mean across support draws of missed observed-positive donor fraction. "
485
+ "Actual donor IDs, zero draws and common depth/cell budget are retained by the existing analysis. "
486
+ "Mandatory IGLL5 is absent for the Ji plasmablast marker rule, which stays unavailable.",
487
+ [src, table, P / "reports/rare_provenance.json", P / "reports/rare_readiness.md"], section="Fig. 5 detail")
488
+
489
+
490
+ def rare_support(b: Builder):
491
+ src = R / "out/sepsis_summary.csv"
492
+ rows = b.table(src)
493
+ states = list(dict.fromkeys(rows.state))
494
+ arms = ["zs__raw", "lora_n5__raw", "lora_n10__raw", "lora_n20__raw", "lora_n40__raw", "real_lora__raw", "zs__pseudo"]
495
+ vals = rows.pivot(index="state", columns="arm", values="gen_over_obs").reindex(index=states, columns=arms)
496
+ if vals.shape != (15, 7) or not np.isfinite(vals.to_numpy()).all(): raise Unavailable("incomplete historical support screen")
497
+ vals.index = [short_state(x) for x in states]
498
+ vals.columns = ["Raw", "5", "10", "20", "40", "Full", "Pseudo"]
499
+ fig, ax = plt.subplots(figsize=ST.FULL); fig.subplots_adjust(left=0.30, right=0.97, bottom=0.08, top=0.93)
500
+ heat(ax, vals, vmax=float(vals.to_numpy().max()), cmap="YlOrBr", fmt=".2g")
501
+ fig.text(0.63, 0.015, "Generated / observed within parent (1 = matched)", ha="center", fontsize=13)
502
+ display = b.save_table(rows, "sepsis_rare_support")
503
+ b.add("sepsis_rare_support", "Sepsis rare states across paired-data budgets", b.save(fig, "sepsis_rare_support"), 51,
504
+ "Historical cross-fitted learning curve: n training pairs plus validation, not strict total n. All 15 rules; arm-specific depth matching.",
505
+ "Existing pooled predictions for 82 donors and 1500 generated cells per sample. Each donor was held out from its fold model. "
506
+ "Raw and pseudobulk are zero-shot controls; numbered/full columns are historical LoRA budgets. "
507
+ "Observed cells were thinned separately to each arm's depth, so compare gen/obs within an arm. "
508
+ "No new generation or rare-state scoring; the full 15-rule family, including controls, is preserved.",
509
+ [src, display, R / "README.md", R / "tools/states.json"], section="Fig. 5 detail")
510
+ src = R / "out/sepsis_contrasts.csv"
511
+ contrasts = b.table(src)
512
+ contrasts["kept"] = truth(contrasts.same_direction)
513
+ contrasts["eligible"] = 1
514
+ grouped = contrasts.groupby(["contrast", "arm"])[["kept", "eligible"]].sum().reset_index()
515
+ names = ["adult sepsis vs adult HC", "paediatric sepsis vs paediatric HC", "all sepsis vs all controls"]
516
+ vals = grouped.pivot(index="contrast", columns="arm", values="kept").reindex(index=names, columns=arms)
517
+ den = grouped.pivot(index="contrast", columns="arm", values="eligible").reindex(index=names, columns=arms)
518
+ if not (den == 15).all().all(): raise Unavailable("rare contrast rule denominator differs")
519
+ vals.index = ["Adult sepsis / HC", "Pediatric sepsis / HC", "All sepsis / controls"]
520
+ vals.columns = ["Raw", "5", "10", "20", "40", "Full", "Pseudo"]
521
+ fig, ax = plt.subplots(figsize=ST.FULL); fig.subplots_adjust(left=0.25, right=0.97, bottom=0.21, top=0.86)
522
+ heat(ax, vals, vmax=15, cmap="YlOrBr", fmt=".0f", text_size=16)
523
+ fig.text(0.60, 0.08, "Rules with the observed disease direction, out of 15", ha="center", fontsize=14)
524
+ display = b.save_table(grouped, "sepsis_rare_direction")
525
+ b.add("sepsis_rare_direction", "Sepsis rare-state direction across support budgets", b.save(fig, "sepsis_rare_direction"), 51,
526
+ "Saved sign-agreement counts across all 15 rules, including controls. Historical n + validation; directions are not effect-size accuracy.",
527
+ "Counts summarize existing same_direction booleans; no thresholds or p-values are recomputed. "
528
+ "All rule-family members are retained, including weak or failed states and positive/negative controls. "
529
+ "A matching sign does not establish that a rare state's abundance or marker co-expression is reproduced.",
530
+ [src, display, R / "README.md"], section="Fig. 5 detail")
531
+
532
+
533
+ def rare_external(b: Builder):
534
+ src = R / "out/summary.csv"
535
+ rows = b.table(src); states = list(dict.fromkeys(rows.state)); cohorts = ["dress", "kawasaki", "sle"]
536
+ fig, axes = plt.subplots(1, 2, figsize=ST.FULL)
537
+ fig.subplots_adjust(left=0.31, right=0.97, top=0.84, bottom=0.05, wspace=0.18)
538
+ for ax, metric, title, low, high in zip(axes, ["gen_over_obs", "spearman"],
539
+ ["Generated / observed", "Sample ranking (ρ)"], [0, -1], [2.5, 1]):
540
+ vals = rows.pivot(index="state", columns="dataset", values=metric).reindex(index=states, columns=cohorts)
541
+ vals.index = [short_state(x) for x in states]; vals.columns = ["DRESS", "Kawasaki", "SLE"]
542
+ heat(ax, vals, title, vmin=low, vmax=high, cmap="Greys", show_y=ax is axes[0], fmt=".2g")
543
+ table = b.save_table(rows, "external_rare_screen")
544
+ b.add("external_rare_screen", "Rare-state screen in DRESS, Kawasaki and SLE", b.save(fig, "external_rare_screen"), 51,
545
+ "Historical one-seed zero-shot screen conditioned on each sample's own sc pseudobulk. DRESS was in training; real-bulk validation is separate.",
546
+ "All 15 predefined states are shown. Samples' own sc pseudobulk conditions remove the real-bulk shift. "
547
+ "Observed marker states are thinned to generated depth. DRESS includes cultured/stimulated samples and was seen during training. "
548
+ "This is descriptive capability evidence, not an unseen-disease paired validation or Figure 6 reproduction.",
549
+ [src, table, R / "README.md", R / "tools/states.json"], section="Rare-state appendix")
550
+ q = M / "plans/c1q_crossdisease_20261004"
551
+ src = q / "out/summary.csv"; data = b.table(src).set_index("dataset").loc[cohorts]
552
+ fig, axes = plt.subplots(1, 2, figsize=ST.FULL); fig.subplots_adjust(left=0.08, right=0.98, bottom=0.18, top=0.82, wspace=0.30)
553
+ for ax, metric, ylabel in zip(axes, ["ratio_c1q_", "spearman_c1q_"], ["Generated / observed rate", "Sample ranking (Spearman ρ)"]):
554
+ for j, (rule, label, color) in enumerate([("ge1_pct", "Any C1Q gene", "#DDD0A0"), ("ge2_pct", "≥2 C1Q genes", GOLD)]):
555
+ values = data[metric + rule].to_numpy(dtype=float)
556
+ ax.bar(np.arange(3) + (j - 0.5) * 0.32, values, width=0.30, color=color, label=label)
557
+ ax.set_xticks(range(3), ["DRESS", "Kawasaki", "SLE"]); ax.set_ylabel(ylabel)
558
+ ax.set_ylim(0, 1.05); ax.axhline(1, color=GREY, linewidth=0.8, linestyle="--")
559
+ ax.set_axisbelow(True); ax.grid(axis="y", color="#EAEAEA")
560
+ handles, labels = axes[0].get_legend_handles_labels(); fig.legend(handles, labels, loc="upper center", ncol=2, fontsize=12)
561
+ table = b.save_table(data.reset_index(), "c1q_cross_disease")
562
+ b.add("c1q_cross_disease", "C1Q: single-gene detection versus co-detection", b.save(fig, "c1q_cross_disease"), 52,
563
+ "Existing pseudobulk-conditioned comparison at matched depth. Multi-gene C1Q rates remain compressed, including in-corpus DRESS.",
564
+ "One sampling seed. DRESS has seven samples, including four cultured/stimulated samples; Kawasaki has 15 and SLE 56. "
565
+ "Corpus inclusion is not randomized and DRESS samples were seen in training. Retain the distinction between any-gene detection "
566
+ "and at least two C1Q genes in the same cell; no causal claim about pretraining exposure.",
567
+ [src, table, q / "README.md"], section="Rare-state appendix")
568
+
569
+
570
+ def behcet_k(b: Builder):
571
+ group = pd.concat([b.table(BC / "out/group_table.csv"), b.table(BC / "out/group_table_k4000.csv")], ignore_index=True)
572
+ cap = pd.concat([b.table(BC / "out/capability.csv"), b.table(BC / "out/capability_k4000.csv")], ignore_index=True)
573
+ settings = [("zs_raw", "Raw\nK1000", "#DDD0A0"), ("lora3_raw", "LoRA\nK1000", GOLD),
574
+ ("lora3k4_raw", "LoRA\nK4000", "#826B22")]
575
+ fig, axes = plt.subplots(1, 2, figsize=ST.FULL); fig.subplots_adjust(left=0.09, right=0.98, top=0.86, bottom=0.20, wspace=0.32)
576
+ display = []
577
+ for i, (prefix, label, color) in enumerate(settings):
578
+ for j, seed in enumerate(["s13", "s04"]):
579
+ arm = f"{prefix}_{seed}"
580
+ g = group[(group.arm == arm) & (group.rows == "test") & (group.metric == "c1q_high_rule_A")]
581
+ c = cap[cap.arm == arm]
582
+ if len(g) != 1 or len(c) != 1: raise Unavailable("Behcet seed/arm table row missing or duplicated")
583
+ gap, rate = float(g.iloc[0].gap_pp), float(c.iloc[0].pooled_rule_B_pct)
584
+ axes[0].scatter(i + (j - 0.5) * 0.12, gap, color=color, s=70, edgecolor=INK, linewidth=0.5)
585
+ axes[1].scatter(i + (j - 0.5) * 0.12, rate, color=color, s=70, edgecolor=INK, linewidth=0.5)
586
+ display.append({"arm": arm, "any_c1q_bd_minus_hc_pp": gap, "multi_gene_pooled_pct": rate})
587
+ for ax in axes:
588
+ ax.set_xticks(range(3), [s[1] for s in settings]); ax.set_xlim(-0.5, 2.5)
589
+ ax.set_axisbelow(True); ax.grid(axis="y", color="#EAEAEA")
590
+ axes[0].set_ylabel("Any-C1Q BD − HC gap (pp)"); axes[0].axhline(0, color=GREY, linewidth=0.8)
591
+ axes[1].set_ylabel("≥2 C1Q genes / monocytes (%)")
592
+ for arm, label, color in [("obs_thin_lora3", "Observed at K1000 LoRA depth", GREY),
593
+ ("obs_thin_lora3k4", "Observed at K4000 LoRA depth", INK)]:
594
+ row = cap[cap.arm == arm]
595
+ if len(row) != 1: raise Unavailable("Behcet observed depth reference missing")
596
+ axes[1].axhline(float(row.iloc[0].pooled_rule_B_pct), color=color, linestyle="--", linewidth=1.2, label=label)
597
+ axes[1].legend(fontsize=11, loc="upper left", bbox_to_anchor=(0.02, 0.82))
598
+ table = b.save_table(pd.DataFrame(display), "behcet_k4000")
599
+ b.add("behcet_k4000", "Behçet: K=4,000 changes direction more than identity", b.save(fig, "behcet_k4000"), 52,
600
+ "Two existing sampling seeds; 6 BD / 10 HC held-out bulks. K is condition size; each bulk still generates 5,000 cells. Descriptive.",
601
+ "The real reference is 4 BD and 4 HC sc donors, mostly unmatched and including training donors. "
602
+ "The three BD-only training candidates include two primary identity passes and one uncertain candidate. "
603
+ "K4000 strengthens the any-C1Q group direction, but ≥2-gene cells remain far below observed. "
604
+ "Same-pair calibration can also recover direction; this plot does not claim LoRA uniquely does so. No p-values are promoted.",
605
+ [BC / "out/group_table.csv", BC / "out/group_table_k4000.csv", BC / "out/capability.csv", BC / "out/capability_k4000.csv",
606
+ BC / "README.md", P / "reports/rare_behcet_provenance.json", table], section="Behçet diagnostic")
607
+
608
+
609
+ def k4000_panels(b: Builder):
610
+ frames, refs = [], []
611
+ for cohort in COHORTS[:2]:
612
+ src = K4 / "analysis/benchmark" / cohort / "per_draw.csv"
613
+ table = b.table(src); table["cohort"] = cohort
614
+ if len(table) != 10 or set(table.arm) != {"lora5", "lora5_k4000"}: raise Unavailable("K comparison lacks all paired draws")
615
+ frames.append(table); refs += [src, src.with_name("AGGREGATE.md")]
616
+ rows = pd.concat(frames, ignore_index=True)
617
+ for key, title, metrics, after in [
618
+ ("k4000_quality", "K=4,000 recipe: paired reconstruction quality", [("comp_l1", "Composition L1 ↓"), ("precision", "Precision ↑"), ("coverage", "Coverage ↑")], 67),
619
+ ("k4000_disease", "K=4,000 recipe: disease signal does not improve uniformly", [("logfc_r_gen", "Disease logFC Pearson r"), ("logfc_partial_r", "Partial r given bulk"), ("deg_top50_sum", "Top-50 DEG overlap (sum)")], 67)]:
620
+ fig, axes = plt.subplots(1, 3, figsize=ST.FULL); fig.subplots_adjust(left=0.07, right=0.99, bottom=0.18, top=0.84, wspace=0.36)
621
+ for ax, (metric, ylabel) in zip(axes, metrics):
622
+ for ci, cohort in enumerate(COHORTS[:2]):
623
+ for mi, (arm, color) in enumerate([("lora5", GOLD), ("lora5_k4000", "#826B22")]):
624
+ values = rows[(rows.cohort == cohort) & (rows.arm == arm)].sort_values("draw")[metric].to_numpy()
625
+ x = ci + (mi - 0.5) * 0.32
626
+ ax.bar(x, values.mean(), width=0.30, color=color)
627
+ ax.scatter(x + np.linspace(-0.06, 0.06, 5), values, s=20, color="white", edgecolor=INK, linewidth=0.5, zorder=3)
628
+ ax.set_xticks([0, 1], COHORT_LABELS[:2]); ax.set_ylabel(ylabel); ax.set_axisbelow(True); ax.grid(axis="y", color="#EAEAEA")
629
+ fig.legend([Patch(color=GOLD), Patch(color="#826B22")], ["PBISC LoRA, K1000", "PBISC LoRA, K4000"], loc="upper center", ncol=2, fontsize=12)
630
+ display = b.save_table(rows[["cohort", "draw", "arm", *[m[0] for m in metrics]]], key)
631
+ b.add(key, title, b.save(fig, key), after,
632
+ "Existing paired benchmark, five support draws per cohort and 1,500 cells/test sample. Bars = means; dots = draws. No new runs.",
633
+ "The stored K1000 re-score exactly matched 25 original metrics in every draw. K4000 uses a changed condition recipe "
634
+ "and draw-specific seeds; it is not a perfectly isolated one-factor K test. Imperial training uses all visits from five donors. "
635
+ "Disease logFC/DEG are the historical sample-level estimators, not the new patient-aware strict metrics. "
636
+ "No donor-draw p-values are used here; overlapping test donors are not independent replicates.", refs + [display, K4 / "README.md"], section="Recipe sensitivity")
637
+ records, sources = [], []
638
+ for cohort in COHORTS[:2]:
639
+ src = K4 / "analysis/compare_k1000" / cohort / "per_feature.csv"; frame = b.table(src)
640
+ if len(frame) != 250: raise Unavailable("calibration table lacks 50 features × five draws")
641
+ contrast = "adult sepsis vs adult HC" if cohort == "ye2026_sepsis" else "COVID+ vs COVID-"
642
+ for gate, label in [("level_ok", "Level + ranking"), (contrast + ": ok", "Disease contrast")]:
643
+ for version in ["k1000", "k4000"]:
644
+ records.append({"cohort": cohort, "gate": label, "version": version,
645
+ "pass_count": int(truth(frame[gate + "_" + version]).sum()), "total": len(frame)})
646
+ sources += [src, src.with_name("SUMMARY.md")]
647
+ display = pd.DataFrame(records)
648
+ fig, axes = plt.subplots(1, 2, figsize=ST.FULL); fig.subplots_adjust(left=0.08, right=0.97, bottom=0.18, top=0.82, wspace=0.28)
649
+ for ax, cohort, name in zip(axes, COHORTS[:2], COHORT_LABELS[:2]):
650
+ for j, (v, color) in enumerate([("k1000", GOLD), ("k4000", "#826B22")]):
651
+ sub = display[(display.cohort == cohort) & (display.version == v)]
652
+ bars = ax.bar(np.arange(2) + (j - 0.5) * 0.32, sub.pass_count, width=0.30, color=color)
653
+ for bar, count in zip(bars, sub.pass_count): ax.text(bar.get_x() + bar.get_width()/2, count + 4, f"{count}/250", ha="center", fontsize=12)
654
+ ax.set_xticks([0, 1], ["Level + ranking", "Disease contrast"]); ax.set_ylim(0, 250)
655
+ ax.set_ylabel("Feature × draw gates passed"); ax.set_title(name, loc="left"); ax.set_axisbelow(True); ax.grid(axis="y", color="#EAEAEA")
656
+ fig.legend([Patch(color=GOLD), Patch(color="#826B22")], ["K1000", "K4000"], loc="upper center", ncol=2, fontsize=12)
657
+ out = b.save_table(display, "k4000_calibration")
658
+ b.add("k4000_calibration", "K=4,000 recipe: calibration gains are selective", b.save(fig, "k4000_calibration"), 67,
659
+ "Saved paired-test gates: 50 features × 5 draws per cohort. Descriptive counts, not 250 independent biological replicates.",
660
+ "Level gate: generated/observed ratio 0.5–2 and Spearman at least 0.3. Contrast gate: same sign and generated magnitude "
661
+ "0.5–2 times observed. Disease contrasts shown are adult sepsis/HC and COVID+/COVID−. "
662
+ "Imperial severity gates are omitted here because historical severity grouping required separate correction. "
663
+ "The K4000 bulk-only discovery workflow was not completed and is not inferred from calibration.", sources + [out], section="Recipe sensitivity")
664
+
665
+
666
+ def bulkonly_history(b: Builder):
667
+ records, refs = [], []
668
+ for cohort in COHORTS[:2]:
669
+ src = BO / f"analysis/wf/findings_{cohort}.json"; data = b.document(src)
670
+ for label in ["confirmed", "qualified", "refuted"]:
671
+ records.append({"cohort": cohort, "grade": label, "count": int(data["counts"][label])})
672
+ refs += [src, BO / f"analysis/wf/REPORT_{cohort}.md"]
673
+ table = pd.DataFrame(records)
674
+ fig, ax = plt.subplots(figsize=ST.FULL); fig.subplots_adjust(left=0.15, right=0.96, bottom=0.20, top=0.86)
675
+ for i, (grade, color) in enumerate([("confirmed", "#333333"), ("qualified", "#BFBFBF"), ("refuted", "#777777")]):
676
+ values = table[table.grade == grade].set_index("cohort").loc[COHORTS[:2], "count"].to_numpy()
677
+ x = np.arange(2) + (i - 1) * 0.24
678
+ bars = ax.bar(x, values, width=0.22, color=color, label=grade.capitalize())
679
+ for bar, count in zip(bars, values): ax.text(bar.get_x()+bar.get_width()/2, count+0.45, str(count), ha="center", fontsize=14)
680
+ ax.set_xticks([0, 1], ["Sepsis · 18 candidates", "Imperial · 21 candidates"])
681
+ ax.set_ylabel("Candidate findings"); ax.set_ylim(0, 22); ax.legend(ncol=3, loc="upper left", fontsize=12)
682
+ ax.set_axisbelow(True); ax.grid(axis="y", color="#EAEAEA")
683
+ out = b.save_table(table, "bulkonly_verification_history")
684
+ b.add("bulkonly_verification_history", "Historical bulk-only search: no confirmed new finding", b.save(fig, "bulkonly_verification_history"), 55,
685
+ "Historical exploratory analysis of existing bulk-only generations. Review dispositions are not experimental validation. Figure 6 reproduction still awaits new data.",
686
+ "The original K1000 workflow considered 18 Sepsis and 21 Imperial candidate findings. Both reports retain zero confirmed "
687
+ "findings under their internal two-verifier grading rule. This is an account of prior exploration, not newly completed biology. "
688
+ "Known weaknesses include shared generation noise across draws, calibration transfer, clinical confounding and some invalid verifier p-values. "
689
+ "No novel cell population survived verification; the user-prepared Figure 6 reproduction is still pending.",
690
+ refs + [out, BO / "README.md"], section="Historical exploration", palette="biological")
691
+ src = BO / "analysis/wf/synthesis_imperial_eskd/i00_samples_by_set_group_wave.csv"
692
+ data = b.table(src)
693
+ vals = data.groupby(["set", "wave"]).n_samples.sum().unstack(fill_value=0).reindex(index=["paired", "bulkonly"], columns=["w1", "w2", "w1|w2"], fill_value=0)
694
+ totals = vals.sum(axis=1); percentages = vals.div(totals, axis=0) * 100
695
+ fig, ax = plt.subplots(figsize=ST.FULL); fig.subplots_adjust(left=0.15, right=0.92, bottom=0.22, top=0.84)
696
+ bottom = np.zeros(2)
697
+ for wave, label, color in [("w1", "Wave 1", "#B7B7B7"), ("w2", "Wave 2", "#5F5F5F"), ("w1|w2", "Recorded w1|w2", "#E4E4E4")]:
698
+ values = percentages[wave].to_numpy()
699
+ ax.bar([0, 1], values, bottom=bottom, color=color, label=label, width=0.48)
700
+ for i, (count, pct) in enumerate(zip(vals[wave], values)):
701
+ if pct > 0: ax.text(i, bottom[i]+pct/2, f"{int(count)} ({pct:.1f}%)", ha="center", va="center", fontsize=13, color="white" if wave=="w2" else INK)
702
+ bottom += values
703
+ ax.set_xticks([0, 1], [f"Paired samples (n={int(totals['paired'])})", f"Bulk-only samples (n={int(totals['bulkonly'])})"])
704
+ ax.set_ylim(0, 100); ax.set_ylabel("Samples (%)"); ax.legend(ncol=3, loc="upper center", bbox_to_anchor=(0.5, 1.16), fontsize=12)
705
+ out = b.save_table(data, "bulkonly_imperial_wave_shift")
706
+ b.add("bulkonly_imperial_wave_shift", "Bulk-only exploration: calibration populations differ", b.save(fig, "bulkonly_imperial_wave_shift"), 55,
707
+ "Historical Imperial sample composition. Paired and bulk-only sets differ in wave; repeated samples are not independent donors.",
708
+ "Counts are read from the original synthesis table, including the recorded mixed w1|w2 category rather than silently reallocating it. "
709
+ "This describes a calibration-transfer limitation and is not a causal wave effect or novel biological discovery. "
710
+ "Figure 6 remains awaiting the user's new reproduction dataset.", [src, out, BO / "analysis/wf/REPORT_imperial_eskd.md"],
711
+ section="Historical exploration", palette="biological")
712
+
713
+
714
+ def deconv_coverage(b: Builder):
715
+ records, refs = [], []
716
+ for cohort in COHORTS:
717
+ for draw in range(5):
718
+ path = B / f"results/{cohort}/fewshot_draw{draw}_cibersortx/summary.json"
719
+ info = b.document(path)
720
+ corr = info["bayesprism"].get("logfc_r_mean_cp10k")
721
+ records.append({"cohort": cohort, "draw": draw, "covered_genes": info["genes_covered_by_Z_all_donors"],
722
+ "disease_correlation_available": corr is not None and math.isfinite(float(corr))})
723
+ refs.append(path)
724
+ data = pd.DataFrame(records)
725
+ fig, axes = plt.subplots(1, 2, figsize=ST.FULL); fig.subplots_adjust(left=0.08, right=0.98, bottom=0.20, top=0.86, wspace=0.30)
726
+ method_color = "#6A51A3" # CIBERSORTx, consistent with the original master.
727
+ for i, cohort in enumerate(COHORTS):
728
+ rows = data[data.cohort == cohort].sort_values("draw")
729
+ for j, row in enumerate(rows.itertuples()):
730
+ axes[0].scatter(i + (j - 2) * 0.055, row.covered_genes, s=55,
731
+ facecolor=method_color if row.disease_correlation_available else "white", edgecolor=method_color, linewidth=1.2)
732
+ count = int(rows.disease_correlation_available.sum())
733
+ axes[1].bar(i, count, color=method_color, width=0.62)
734
+ axes[1].text(i, count+0.12, f"{count}/5", ha="center", fontsize=14)
735
+ for ax in axes: ax.set_xticks(range(4), COHORT_LABELS); ax.set_axisbelow(True); ax.grid(axis="y", color="#EAEAEA")
736
+ axes[0].set_ylabel("HiRes genes covered on all samples"); axes[0].set_ylim(bottom=0)
737
+ axes[1].set_ylabel("Draws with disease correlation"); axes[1].set_ylim(0, 5.7); axes[1].set_yticks(range(6))
738
+ fig.text(0.08, 0.055, "Open points: disease correlation unavailable; not a zero performance score.", fontsize=12, color="#4D4D4D")
739
+ out = b.save_table(data, "deconv_expression_coverage")
740
+ b.add("deconv_expression_coverage", "Deconvolution: expression coverage limits the comparison", b.save(fig, "deconv_expression_coverage"), 46,
741
+ "Completed historical CIBERSORTx five-donor runs. Missing disease correlations remain unavailable; deconvolution does not generate individual cells.",
742
+ HISTORICAL + " Coverage is the saved HiRes covered-gene count; some genes outside the four contrast cell types can be covered "
743
+ "even when the disease correlation is unavailable. Two Giroux draws and one Ji draw lack that score. "
744
+ "The internal summary field named bayesprism is reused by the old scorer for CIBERSORTx; these values are from CIBERSORTx files. "
745
+ "Existing Sepsis method adoption does not mean new corrected strict deconvolution statistics are already complete.",
746
+ refs + [out, B / "results/RESULTS_cibersortx.md"], section="Deconvolution detail")
747
+
748
+
749
+ def build() -> dict:
750
+ b = Builder()
751
+ b.source(Path(__file__), "expanded disease figure/spec builder")
752
+ b.source(D / "tools/style.py", "original on-slide typography and figure geometry")
753
+ b.source(M / "EXPERIMENT_INDEX.md", "existing experiment/reuse navigation")
754
+ style = {"font.family": "sans-serif", "font.sans-serif": ["Arial", "Liberation Sans", "DejaVu Sans"],
755
+ "font.size": 14, "axes.labelsize": 14, "axes.titlesize": 14, "xtick.labelsize": 12, "ytick.labelsize": 12,
756
+ "legend.fontsize": 12, "legend.frameon": False, "axes.spines.top": False, "axes.spines.right": False,
757
+ "axes.linewidth": 1.0, "figure.facecolor": "white", "axes.facecolor": "white", "pdf.fonttype": 42,
758
+ "ps.fonttype": 42, "svg.fonttype": "none"}
759
+ with plt.rc_context(style):
760
+ for key, action in [("strict_sepsis", strict_panels), ("strict_imperial", imperial_panels),
761
+ ("ready_external", external_figures), ("covid_direction_details", covid_direction_details),
762
+ ("covid_endpoints", covid_endpoints),
763
+ ("rare_misses", rare_misses), ("rare_support", rare_support), ("rare_external", rare_external),
764
+ ("behcet_k4000", behcet_k), ("k4000", k4000_panels),
765
+ ("historical_bulkonly", bulkonly_history), ("deconv_coverage", deconv_coverage)]:
766
+ b.attempt(key, lambda action=action: action(b))
767
+ # This addition is an explicit six-unit snapshot, not a moving live-job
768
+ # dashboard. Newly completed receipts are surfaced for the next refresh.
769
+ next_refresh = []
770
+ for cohort in COHORTS:
771
+ for draw in range(5):
772
+ if (cohort, draw) in b.strict:
773
+ continue
774
+ receipt = P / f"receipts/{cohort}-disease-draw{draw}-score.json"
775
+ if receipt.is_file():
776
+ record = json.loads(receipt.read_text())
777
+ if record.get("state") == "completed":
778
+ next_refresh.append({"cohort": cohort, "draw": draw, "receipt": str(receipt),
779
+ "receipt_sha256": sha(receipt),
780
+ "state": "outside requested snapshot; verify outputs before adding"})
781
+ result = {"schema": "pbisc.expanded-master.disease-additions.v1",
782
+ "created_at": datetime.now(timezone.utc).isoformat(), "snapshot_started_at": b.started_at,
783
+ "snapshot_scope": "Sepsis draws 0–4 and Imperial draw 0 only; each included unit must pass receipt/output hash checks",
784
+ "other_completed_receipts_for_next_refresh": next_refresh,
785
+ "slides": b.slides, "assets": list(dict.fromkeys(b.assets)),
786
+ "sources": list(b.sources.values()), "dropped": b.dropped,
787
+ "strict_completed_units": [{"cohort": c, "draw": j, "receipt": str(v["receipt"]),
788
+ "support": str(v["support"]), "verified_outputs": v["verified_outputs"]}
789
+ for (c, j), v in b.strict.items()],
790
+ "new_training": False, "new_generation": False, "new_scoring": False,
791
+ "figure6": "new reproduction dataset still pending; bulk-only additions are historical exploration",
792
+ "deduplicated_root_additions": ["corrected rare-state frequencies", "corrected rare comparison", "Behcet any/multi-C1Q rules"],
793
+ "display_work": "saved-table aggregation/formatting and existing figure reuse only"}
794
+ MANIFEST.parent.mkdir(parents=True, exist_ok=True)
795
+ MANIFEST.write_text(json.dumps(result, indent=2, allow_nan=False) + "\n")
796
+ return result
797
+
798
+
799
+ if __name__ == "__main__":
800
+ result = build()
801
+ print(json.dumps({"slides": len(result["slides"]), "assets": len(result["assets"]),
802
+ "dropped": result["dropped"], "manifest": str(MANIFEST)}, indent=2))
paper-releases/pbisc-diffusion/updates/20261013T034842Z-expanded-131-slide-master/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/expanded_healthy_materials.py ADDED
@@ -0,0 +1,650 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Additional healthy/control slides from saved tables and saved coordinates.
2
+
3
+ No model, checkpoint, expression matrix, new embedding, statistical scorer or
4
+ inference is loaded. Only display transforms (percentages, log-length axes,
5
+ fixed display subsets) are computed. Original assets remain untouched.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import shutil
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ import matplotlib
17
+ matplotlib.use("Agg")
18
+ import matplotlib.pyplot as plt
19
+ from matplotlib.lines import Line2D
20
+ import numpy as np
21
+ import pandas as pd
22
+
23
+ D = Path(__file__).resolve().parents[1]
24
+ M = D.parents[1]
25
+ U = M / "plans/utility_studies_final6k_20260925"
26
+ V = U / "umap/cell_immicro_5arm"
27
+ FIG = D / "figures/expanded_master_20261013/healthy"
28
+ DATA = D / "data/expanded_master_20261013/healthy"
29
+ FULL = (12.3, 5.6)
30
+ INK, GREY, BLUE = "#1A1A1A", "#777777", "#2166AC"
31
+ COL = {"raw": "#E8DDAE", "tpm": "#D2BC70", "refcal": "#B59A50", "cal": "#9C8138",
32
+ "pseudo": "#806A25", "R2": "#777777", "refcal_aida": "#C5AA4B", "refcal_train": "#65521B",
33
+ "tpmrefcal": "#A68B3C"}
34
+ ARM = ["raw", "tpm", "refcal", "cal", "pseudo"]
35
+ LABEL = {"raw": "Raw", "tpm": "TPM", "refcal": "AIFI ref-cal", "cal": "Paired cal. (10)",
36
+ "pseudo": "Pseudobulk", "R2": "Held-out real", "refcal_aida": "AIDA ref-cal",
37
+ "refcal_train": "Training ref-cal", "tpmrefcal": "TPM + AIFI"}
38
+ TYPES = ["T cell", "B cell", "Monocyte", "NK cell", "DC", "Other"]
39
+ SHORT = ["T", "B", "Mono", "NK", "DC", "Other"]
40
+ CELL_COL = {"T cell": "#4E79A7", "B cell": "#F28E2B", "Monocyte": "#E15759",
41
+ "NK cell": "#59A14F", "DC": "#B07AA1", "Other": "#9C755F"}
42
+ NATIVE_FOOT = "Historical native-depth diagnostic: sc-derived depth/masks; 10-pair calibration; AIFI overlaps pretraining. One seed."
43
+ NATIVE_NOTE = (
44
+ "Historical zero-shot input diagnostics, not strict-five LoRA/scSemiProfiler comparison. "
45
+ "Final f01 6k 1x E16 EMA; 107 ImMicro donors; 1,500 generated cells/donor; 50 DDIM steps; "
46
+ "Bernoulli support; generation seed 20260922 shared across input arms. Native depth and cell count, "
47
+ "and the output gene-availability mask, use each donor's sc data. Paired calibration uses 10 paired samples. "
48
+ "AIFI alpha uses no paired ImMicro sc expression, but 85 of its 108 reference donors overlap pretraining; "
49
+ "this is not evidence of a completely sc-free deployment. Most cell-space metrics use 150 cells/donor "
50
+ "and 5,508 common measured genes; PCA50/UMAP fitted only on real R1. Generated counts are Poisson readouts, "
51
+ "not observed UMIs. One cohort and one seed; no new uncertainty tests. The source manifest records exact "
52
+ "reproduction of the earlier four-arm controls."
53
+ )
54
+
55
+
56
+ class MaterialBuilder:
57
+ def __init__(self) -> None:
58
+ self.slides: list[dict[str, Any]] = []
59
+ self.assets: list[str] = []
60
+ self.sources: dict[str, dict[str, str]] = {}
61
+ self.used: set[str] = set()
62
+
63
+ def source(self, path: Path, role: str = "saved analysis input") -> Path:
64
+ path = path.resolve()
65
+ if path.suffix.lower() not in {".csv", ".json", ".md", ".py", ".png"}:
66
+ raise ValueError(f"Only small table/document inputs are allowed: {path}")
67
+ if path.stat().st_size > 16_777_216:
68
+ raise ValueError(f"Input exceeds 16MiB table/document cap: {path}")
69
+ with path.open("rb") as handle:
70
+ sha = hashlib.file_digest(handle, "sha256").hexdigest()
71
+ self.sources[str(path)] = {"path": str(path), "sha256": sha, "role": role}
72
+ self.used.add(str(path))
73
+ return path
74
+
75
+ def frame(self, path: Path, **kwargs: Any) -> pd.DataFrame:
76
+ return pd.read_csv(self.source(path), **kwargs)
77
+
78
+ def document(self, path: Path, role: str = "saved analysis metadata") -> dict[str, Any]:
79
+ return json.loads(self.source(path, role).read_text())
80
+
81
+ def begin(self, native: bool = True) -> None:
82
+ self.used = set()
83
+ if native:
84
+ self.source(V / "MANIFEST.json", "historical input/control provenance")
85
+ self.source(V / "RESULTS.md", "historical scope and limitations")
86
+
87
+ def finish(self, fig: plt.Figure, key: str, title: str, after: int,
88
+ data: pd.DataFrame | None = None, note: str = "", native: bool = True,
89
+ footnote: str | None = None, palette: str = "native") -> None:
90
+ if len(title) > 64:
91
+ raise ValueError(f"Title too long: {title}")
92
+ path = FIG / key
93
+ fig.canvas.draw()
94
+ for suffix in ("png", "pdf", "svg"):
95
+ output = path.with_suffix("." + suffix)
96
+ fig.savefig(output, dpi=200, bbox_inches="tight", pad_inches=0.06, facecolor="white")
97
+ self.assets.append(str(output))
98
+ plt.close(fig)
99
+ if data is not None:
100
+ output = DATA / (key + ".csv")
101
+ data.to_csv(output, index=False)
102
+ self.assets.append(str(output))
103
+ foot = footnote or NATIVE_FOOT
104
+ if len(foot) > 180:
105
+ raise ValueError(f"Footnote too long: {foot}")
106
+ full = ((NATIVE_NOTE + "\n\n") if native else "") + note
107
+ full += "\n\nSource files (existing results, read only):\n" + "\n".join(sorted(self.used))
108
+ self.slides.append({"kind": "content", "key": "healthy_" + key, "after_original": after,
109
+ "title": title, "section_label": "Control evidence", "layout": "full",
110
+ "figures": [str(path.with_suffix(".png").relative_to(D))], "keywords": [],
111
+ "footnote": foot, "footnote_full": full, "sources": "; ".join(sorted(self.used)),
112
+ "palette": palette})
113
+ proof = DATA / (key + ".provenance.json")
114
+ proof.write_text(json.dumps({"key": key, "source_records": [self.sources[p] for p in sorted(self.used)],
115
+ "new_training": False, "new_inference": False, "new_embedding": False,
116
+ "new_statistical_scoring": False, "display_transform_notes": note, "palette": palette}, indent=2) + "\n")
117
+ self.assets.append(str(proof))
118
+
119
+
120
+ def clean(ax: plt.Axes, axis: str = "y") -> None:
121
+ ax.spines[["top", "right"]].set_visible(False)
122
+ ax.grid(axis=axis, color="#E8E8E8", linewidth=0.7)
123
+ ax.set_axisbelow(True)
124
+
125
+
126
+ def legend_methods(fig: plt.Figure, arms: list[str], y: float = 0.01) -> None:
127
+ handles = [Line2D([], [], marker="o", color=COL[a], label=LABEL[a], linewidth=1.5) for a in arms]
128
+ fig.legend(handles=handles, loc="lower center", bbox_to_anchor=(0.5, y), ncol=min(len(arms), 6), fontsize=11,
129
+ frameon=False, columnspacing=1.0, handlelength=1.5)
130
+
131
+
132
+ def coords(builder: MaterialBuilder) -> tuple[pd.DataFrame, dict[str, Any]]:
133
+ doc = builder.document(V / "interactive/cells_5arm.json", "previously computed display coordinates; no embedding recalculated")
134
+ table = pd.DataFrame(doc["cells"])
135
+ table["set_name"] = table["set"].map(dict(enumerate(doc["sets"])))
136
+ table["label"] = table["l1"].map(dict(enumerate(doc["labels_l1"])))
137
+ # The old JSON's illustrative extent excludes 174 cached display points.
138
+ # Widen only the viewing window; every stored coordinate stays unchanged.
139
+ doc["display_extent"] = {}
140
+ for coordinate in ("x", "y"):
141
+ lo = min(float(table[coordinate].min()), doc["meta"]["umap_extent"][coordinate][0])
142
+ hi = max(float(table[coordinate].max()), doc["meta"]["umap_extent"][coordinate][1])
143
+ pad = (hi - lo) * .025
144
+ doc["display_extent"][coordinate] = [lo - pad, hi + pad]
145
+ return table, doc
146
+
147
+
148
+ def stored_umap(builder: MaterialBuilder) -> None:
149
+ builder.begin()
150
+ table, doc = coords(builder)
151
+ arms = ["R2"] + ARM
152
+ fig, axes = plt.subplots(2, 3, figsize=FULL)
153
+ for ax, arm in zip(axes.flat, arms):
154
+ sub = table[table.set_name == arm]
155
+ ax.scatter(sub.x, sub.y, c=sub.label.map(CELL_COL), s=2.1, lw=0, rasterized=True)
156
+ ax.set_title(LABEL[arm], fontsize=13)
157
+ ax.set_xlim(doc["display_extent"]["x"])
158
+ ax.set_ylim(doc["display_extent"]["y"])
159
+ ax.set_xticks([]); ax.set_yticks([])
160
+ for spine in ax.spines.values(): spine.set_visible(False)
161
+ fig.legend(handles=[Line2D([], [], marker="o", ls="", color=CELL_COL[t], label=t) for t in TYPES],
162
+ loc="lower center", ncol=6, frameon=False, fontsize=11)
163
+ fig.subplots_adjust(left=.02, right=.99, top=.93, bottom=.09, hspace=.22, wspace=.08)
164
+ builder.finish(fig, "stored_real_reference_umap", "Input corrections on one real-reference UMAP", 19,
165
+ table[["set_name", "pair_id", "donor_index", "label", "x", "y"]],
166
+ "Replots only the stored interactive coordinates: 3,000 displayed cells per set. "
167
+ "The reference PCA/UMAP was previously fitted to real R1. UMAP overlap is illustrative, not a score. "
168
+ "Cell-type colors are preserved; no new labels or embedding were computed. "
169
+ "Shared display bounds cover all saved coordinates plus 2.5% padding; the narrower old illustrative extent is not reused.", palette="preserved")
170
+
171
+
172
+ def saved_density_reference(builder: MaterialBuilder) -> None:
173
+ builder.begin()
174
+ source = builder.source(V / 'figures/fig2_density_difference.png', 'existing high-resolution quantitative density figure')
175
+ destination = FIG / 'saved_density_difference.png'
176
+ shutil.copyfile(source, destination)
177
+ builder.assets.append(str(destination))
178
+ note = (NATIVE_NOTE + '\n\nThe original high-resolution PNG is copied byte-for-byte, with no crop, pixel recoloring, '
179
+ 'density-grid recomputation, or fresh embedding. Its diverging colors encode signed density differences, '
180
+ 'not PBISC/scSemiProfiler identities. Retained as a full-width working-master reference; zoom may be needed '
181
+ 'for small panel labels. UMAP-space density is a qualitative localization diagnostic, not a calibrated biological score. '
182
+ '\n\nSource files:\n' + '\n'.join(sorted(builder.used)))
183
+ builder.slides.append({'kind':'content','key':'healthy_saved_density_difference','after_original':19,
184
+ 'title':'Where generated-cell density differs from real cells','section_label':'Control evidence','layout':'full',
185
+ 'figures':[str(destination.relative_to(D))],'keywords':[],
186
+ 'footnote':'Original high-resolution density map; zoom for panel labels. Quantitative colors preserved. Historical native-depth controls.',
187
+ 'footnote_full':note,'sources':'; '.join(sorted(builder.used)),'palette':'preserved'})
188
+ proof = DATA / 'saved_density_difference.provenance.json'
189
+ proof.write_text(json.dumps({'key':'saved_density_difference','source_records':[builder.sources[p] for p in sorted(builder.used)],
190
+ 'unchanged_png_copy':True,'no_density_or_embedding_recomputation':True,'palette':'preserved',
191
+ 'readability_note':'Full-width reference; small original panel labels may require zoom.'},indent=2)+'\n')
192
+ builder.assets.append(str(proof))
193
+
194
+
195
+ def composition(builder: MaterialBuilder) -> None:
196
+ builder.begin()
197
+ frame = builder.frame(V / "tables/b_composition_l1.csv").set_index("label").loc[TYPES]
198
+ arms = ["R2"] + ARM
199
+ fig, ax = plt.subplots(figsize=FULL)
200
+ bottom = np.zeros(len(arms))
201
+ for cell in TYPES:
202
+ values = frame.loc[cell, arms].to_numpy(float) * 100
203
+ ax.bar(np.arange(len(arms)), values, bottom=bottom, color=CELL_COL[cell], label=cell, width=.68)
204
+ bottom += values
205
+ ax.set_xticks(np.arange(len(arms)), [LABEL[a] for a in arms])
206
+ ax.set_ylabel("Cell-type share (%)"); ax.set_ylim(0, 101)
207
+ clean(ax)
208
+ ax.legend(ncol=6, frameon=False, loc="upper center", bbox_to_anchor=(.5, 1.14), fontsize=11)
209
+ fig.subplots_adjust(left=.08, right=.98, top=.85, bottom=.17)
210
+ builder.finish(fig, "input_control_composition", "Input calibration changes cell-type composition", 19,
211
+ frame.reset_index(), "Saved fractions from 150 cells/donor; displayed as percent. "
212
+ "Color identifies biological cell type, not method. Do not interpret reference calibration's "
213
+ "composition agreement as proof of within-type state recovery.", palette="preserved")
214
+
215
+
216
+ def matched_trajectories(builder: MaterialBuilder) -> None:
217
+ builder.begin()
218
+ table, doc = coords(builder)
219
+ pseudo = table[table.set_name == "pseudo"].sort_values("pair_id")
220
+ selected = pseudo.groupby("label", sort=False).head(12)
221
+ fig, axes = plt.subplots(2, 2, figsize=FULL)
222
+ outputs = []
223
+ for ax, arm in zip(axes.flat, ARM[:-1]):
224
+ other = table[table.set_name == arm].set_index("pair_id")
225
+ pairs = selected.set_index("pair_id").join(other[["x", "y", "label"]], rsuffix="_input", validate="one_to_one")
226
+ if pairs[["x_input", "y_input"]].isna().any().any():
227
+ raise ValueError("Stored matched coordinates are incomplete")
228
+ for pair_id, row in pairs.iterrows():
229
+ ax.plot([row.x_input, row.x], [row.y_input, row.y], color=COL[arm], lw=.6, alpha=.55)
230
+ outputs.append({"arm": arm, "pair_id": pair_id, "pseudo_label": row.label,
231
+ "input_label": row.label_input, "x_input": row.x_input, "y_input": row.y_input,
232
+ "x_pseudo": row.x, "y_pseudo": row.y})
233
+ ax.scatter(pairs.x_input, pairs.y_input, c=pairs.label_input.map(CELL_COL), s=11, lw=0)
234
+ ax.scatter(pairs.x, pairs.y, facecolors="none", edgecolors=pairs.label.map(CELL_COL), s=17, lw=.6)
235
+ ax.set_title(LABEL[arm] + " → pseudobulk-input twin", fontsize=12)
236
+ ax.set_xlim(doc["display_extent"]["x"]); ax.set_ylim(doc["display_extent"]["y"])
237
+ ax.set_xticks([]); ax.set_yticks([])
238
+ for spine in ax.spines.values(): spine.set_visible(False)
239
+ fig.text(.5, .02, "Filled: input arm Open: matched pseudobulk-input twin Color: frozen cell type", ha="center", fontsize=11)
240
+ fig.subplots_adjust(left=.02, right=.99, top=.93, bottom=.08, hspace=.22, wspace=.12)
241
+ builder.finish(fig, "stored_matched_trajectories", "Same noise, different input: matched-cell shifts", 19,
242
+ pd.DataFrame(outputs), "Display subset: first 12 stored pair IDs within each pseudobulk-predicted type, "
243
+ "at most 72 pairs/arm, selected deterministically from the previously stored display sample. "
244
+ "No embedding or labels recalculated. Lines connect generated samples sharing noise; they are not "
245
+ "longitudinal biological transitions. Exact displayed pairs are saved. "
246
+ "Shared display bounds cover all saved coordinates plus 2.5% padding.", palette="preserved")
247
+
248
+
249
+ def similarity(builder: MaterialBuilder) -> None:
250
+ builder.begin()
251
+ frame = builder.frame(V / "tables/c_matched_cells.csv").set_index("pair")
252
+ arms = ARM[:-1]
253
+ rows = frame.loc[[a + "_vs_pseudo_matched" for a in arms]]
254
+ fig, axes = plt.subplots(1, 3, figsize=FULL)
255
+ metrics = [("median_r_scoring_genes", "Median expression correlation"),
256
+ ("median_support_jaccard", "Median support Jaccard"),
257
+ ("same_frozen_label_fraction", "Same frozen-label fraction")]
258
+ for ax, (metric, label) in zip(axes, metrics):
259
+ values = rows[metric].to_numpy(float)
260
+ ax.bar(np.arange(4), values, color=[COL[a] for a in arms], width=.68)
261
+ if metric == "median_r_scoring_genes":
262
+ lo = values - rows.q25_r_scoring_genes.to_numpy(float)
263
+ hi = rows.q75_r_scoring_genes.to_numpy(float) - values
264
+ ax.errorbar(np.arange(4), values, yerr=[lo, hi], fmt="none", ecolor=INK, capsize=3)
265
+ ax.set_xticks(np.arange(4), [LABEL[a] for a in arms], rotation=25, ha="right", fontsize=11)
266
+ ax.set_ylabel(label); ax.set_ylim(0, 1.08); clean(ax)
267
+ annotation_y = rows.q75_r_scoring_genes.to_numpy(float) if metric == "median_r_scoring_genes" else values
268
+ for i, v in enumerate(values): ax.text(i, annotation_y[i] + .025, f"{v:.2f}", ha="center", fontsize=11)
269
+ fig.subplots_adjust(left=.07, right=.99, top=.91, bottom=.23, wspace=.38)
270
+ builder.finish(fig, "matched_similarity", "Matched noise separates cell state from cell identity", 19,
271
+ rows.reset_index(), "Original model-output comparisons over 160,500 paired generated cells. "
272
+ "Expression-correlation whiskers show saved 25th–75th percentiles, not confidence intervals. "
273
+ "All comparisons are against the pseudobulk-conditioned twin, not observed individual cells.")
274
+
275
+
276
+ def transitions(builder: MaterialBuilder) -> None:
277
+ builder.begin()
278
+ fig, axes = plt.subplots(2, 2, figsize=FULL)
279
+ records = []
280
+ for ax, arm in zip(axes.flat, ARM[:-1]):
281
+ frame = builder.frame(V / f"tables/c_label_transition_pseudo_to_{arm}_counts.csv").set_index("pseudo_label").loc[TYPES, TYPES]
282
+ values = frame.to_numpy(float)
283
+ pct = values / values.sum(axis=1, keepdims=True) * 100
284
+ ax.imshow(pct, cmap="Greys", vmin=0, vmax=100, aspect="auto")
285
+ ax.set_xticks(range(6), SHORT, fontsize=10); ax.set_yticks(range(6), SHORT, fontsize=10)
286
+ ax.set_title(LABEL[arm] + " · row %", fontsize=13)
287
+ for y in range(6):
288
+ for x in range(6):
289
+ ax.text(x, y, f"{pct[y,x]:.0f}", ha="center", va="center", fontsize=9,
290
+ color="white" if pct[y,x] > 55 else INK)
291
+ records.append({"arm": arm, "pseudo_label": TYPES[y], "input_label": TYPES[x],
292
+ "count": values[y,x], "row_percent": pct[y,x]})
293
+ ax.set_ylabel("Pseudobulk-input label", fontsize=11)
294
+ ax.set_xlabel("Input-arm label", fontsize=11)
295
+ fig.subplots_adjust(left=.10, right=.99, top=.91, bottom=.10, wspace=.25, hspace=.55)
296
+ builder.finish(fig, "label_transitions", "Input changes can switch the generated cell label", 19,
297
+ pd.DataFrame(records), "Existing matched-cell transition counts, normalized within each pseudobulk-label row for display. "
298
+ "Numbers are percentages. Frozen model labels, not proof of biological transdifferentiation. "
299
+ "Greyscale represents a quantitative transition fraction.", palette="preserved")
300
+
301
+
302
+ def nearest_real(builder: MaterialBuilder) -> None:
303
+ builder.begin()
304
+ frame = builder.frame(V / "tables/f7_nearest_real_by_type.csv").set_index(["set", "label"])
305
+ arms = ["R2"] + ARM
306
+ fig, axes = plt.subplots(1, 2, figsize=FULL)
307
+ for arm in arms:
308
+ sub = frame.loc[arm].reindex(TYPES)
309
+ for ax, field in zip(axes, ["median_distance_to_nearest_real", "own_label_equals_nearest_real_label"]):
310
+ ax.plot(range(6), sub[field], "o-", color=COL[arm], ms=5, lw=1.5)
311
+ for ax in axes:
312
+ ax.set_xticks(range(6), SHORT); clean(ax)
313
+ axes[0].set_ylabel("Median distance to nearest real cell (PCA50)")
314
+ axes[1].set_ylabel("Same label as nearest real cell (fraction)"); axes[1].set_ylim(0, 1.04)
315
+ legend_methods(fig, arms)
316
+ fig.subplots_adjust(left=.08, right=.98, top=.94, bottom=.20, wspace=.34)
317
+ builder.finish(fig, "nearest_real_by_type", "Nearest real cells: distance and label agreement", 19,
318
+ frame.reset_index(), "Saved PCA50 nearest-reference-cell metrics from 150 cells/donor. "
319
+ "Different cell types have different geometry; distances are not calibrated probabilities or donor-level effect estimates.")
320
+
321
+
322
+ def centroids(builder: MaterialBuilder) -> None:
323
+ builder.begin()
324
+ frame = builder.frame(V / "tables/b_type_centroid_shift_l1.csv").set_index("label").loc[TYPES]
325
+ fig, axes = plt.subplots(1, 2, figsize=FULL)
326
+ for arm in ["R2"] + ARM:
327
+ axes[0].plot(range(6), frame["shift_" + arm], "o-", color=COL[arm], ms=5, lw=1.5)
328
+ for arm in ARM[:-1]:
329
+ axes[1].plot(range(6), frame["shift_" + arm + "_vs_pseudo"], "o-", color=COL[arm], ms=5, lw=1.5)
330
+ for ax in axes:
331
+ ax.set_xticks(range(6), SHORT); ax.set_ylim(bottom=0); clean(ax)
332
+ axes[0].set_ylabel("Centroid shift from real R1 / real RMS spread")
333
+ axes[1].set_ylabel("Centroid shift from pseudobulk twin / spread")
334
+ legend_methods(fig, ["R2"] + ARM)
335
+ fig.subplots_adjust(left=.08, right=.98, top=.94, bottom=.20, wspace=.35)
336
+ builder.finish(fig, "within_type_centroids", "Composition agreement does not ensure state agreement", 19,
337
+ frame.reset_index(), "Centroids and real within-type RMS normalization are previously computed. "
338
+ "No new embedding, centroids or annotation are fitted. Six broad types; small Other/DC groups require caution.")
339
+
340
+
341
+ def depth_quality(builder: MaterialBuilder) -> None:
342
+ builder.begin()
343
+ raw = builder.frame(V / "tables/a_precision_coverage_pca50.csv").set_index("set")
344
+ matched = builder.frame(V / "tables/e_depth_matched_precision_coverage_pca50.csv").set_index("set")
345
+ arms = ["R2"] + ARM
346
+ fig, axes = plt.subplots(1, 2, figsize=FULL)
347
+ records = []
348
+ for ax, field in zip(axes, ["precision", "coverage"]):
349
+ for i, arm in enumerate(arms):
350
+ ax.bar(i-.18, raw.loc[arm, field], .34, color=COL[arm])
351
+ ax.bar(i+.18, matched.loc[arm, field], .34, color=COL[arm], hatch="///", edgecolor=INK, lw=.35)
352
+ records.extend([{"arm": arm, "metric": field, "depth": mode, "value": table.loc[arm,field]}
353
+ for mode,table in [("native",raw),("matched",matched)]])
354
+ ax.set_xticks(range(6), [LABEL[a] for a in arms], rotation=22, ha="right", fontsize=10)
355
+ ax.set_ylabel(field.capitalize()); ax.set_ylim(0, 1.08); clean(ax)
356
+ fig.text(.5,.03,"Solid: native depth Hatched: previously depth-matched readout",ha="center",fontsize=12)
357
+ fig.subplots_adjust(left=.07,right=.99,top=.93,bottom=.27,wspace=.27)
358
+ builder.finish(fig, "depth_matched_quality", "Depth matching changes precision and coverage", 24,
359
+ pd.DataFrame(records), "Both tables already exist. The matched-depth procedure thins all seven source sets "
360
+ "to common detected-gene depth, as documented in the original analysis. Real R2 is a held-out real-real control; "
361
+ "neighborhood k=10 only. Display hatching, not a new sensitivity run.")
362
+
363
+
364
+ def gene_length(builder: MaterialBuilder, stable: bool) -> None:
365
+ builder.begin()
366
+ frame = builder.frame(V / "tables/g_gene_shift_vs_length.csv")
367
+ stats = builder.frame(V / "tables/g_length_stats.csv").set_index("shift")
368
+ fig, axes = plt.subplots(2, 2, figsize=FULL)
369
+ prefix = "stable" if stable else "input"
370
+ x = np.log10(frame.union_exon_kb.to_numpy(float))
371
+ for ax, arm in zip(axes.flat, ARM[:-1]):
372
+ field = f"{prefix}_shift_{arm}_minus_pseudo"
373
+ valid = np.isfinite(x) & np.isfinite(frame[field].to_numpy(float))
374
+ ax.scatter(x[valid], frame.loc[valid,field], color=COL[arm], s=3, alpha=.45, lw=0, rasterized=True)
375
+ ax.axhline(0, color=GREY, lw=.7)
376
+ stat_key = f"{prefix}_{arm}_minus_pseudo"
377
+ if stat_key not in stats.index:
378
+ raise ValueError(f"Missing existing gene-length statistic: {stat_key}")
379
+ rho = stats.loc[stat_key,"spearman_vs_log10kb"]
380
+ ax.set_title(f"{LABEL[arm]} · saved Spearman ρ = {rho:+.2f}", fontsize=12)
381
+ ax.set_xlabel("log10 union-exon length (kb)", fontsize=11)
382
+ ax.set_ylabel("Shift vs pseudobulk twin\n(log1p CP10K)" if stable else "Shift vs pseudobulk input\n(cpm_log1p)", fontsize=11)
383
+ clean(ax)
384
+ fig.subplots_adjust(left=.08,right=.99,top=.91,bottom=.11,hspace=.60,wspace=.28)
385
+ title = "Gene-length effects within label-stable cells" if stable else "Gene-length effects in the bulk input"
386
+ builder.finish(fig, "gene_length_stable" if stable else "gene_length_input", title, 19,
387
+ frame[["gene_id","symbol","union_exon_kb"] + [f"{prefix}_shift_{a}_minus_pseudo" for a in ARM[:-1]]],
388
+ "Only log10 axis conversion and plotting of saved per-gene shifts. The displayed Spearman values "
389
+ "come directly from g_length_stats.csv; no correlation or regression is recomputed. " +
390
+ ("Label-stable means the frozen broad label agrees between generated twins; it does not establish identical biological state. "
391
+ "Y values are generated log1p CP10K differences." if stable else "Y values are input cpm_log1p differences. "
392
+ "Gene length accounts for only part of assay mismatch; these are diagnostic associations."))
393
+
394
+
395
+ def top_genes(builder: MaterialBuilder, reference: bool) -> None:
396
+ builder.begin()
397
+ file = "g_top_genes_refcal.csv" if reference else "g_top_genes_raw_tpm.csv"
398
+ frame = builder.frame(V / "tables" / file)
399
+ frame = frame[frame.cells == "label-stable matched cells"].copy()
400
+ arms = ["refcal"] if reference else ["raw","tpm"]
401
+ fig, axes = plt.subplots(1, 2, figsize=FULL)
402
+ outputs = []
403
+ for ax, arm in zip(axes, (["refcal","refcal"] if reference else arms)):
404
+ if reference:
405
+ direction = "down" if ax is axes[0] else "up"
406
+ sub = frame[frame.direction.str.startswith(direction)].sort_values("rank").head(10).iloc[::-1]
407
+ else:
408
+ sub = frame[frame.arm == arm].sort_values("rank").groupby("direction",sort=False).head(5)
409
+ sub = sub.sort_values("output_shift")
410
+ y=np.arange(len(sub)); ax.barh(y,sub.output_shift,color=COL[arm],height=.70)
411
+ if reference:
412
+ ax.scatter(sub.input_shift,y,marker="|",color=INK,s=90,label="Input shift")
413
+ ax.set_yticks(y,sub.symbol,fontsize=11);ax.axvline(0,color=GREY,lw=.8)
414
+ ax.set_xlabel("Generated-cell shift vs pseudobulk twin",fontsize=11);clean(ax,"x")
415
+ ax.set_title(("AIFI ref-cal: "+direction if reference else LABEL[arm]),fontsize=13)
416
+ outputs.append(sub)
417
+ if reference:
418
+ fig.text(.5,.025,"Gold bars: generated log1p CP10K shift Black ticks: input cpm_log1p shift (different normalization)",ha="center",fontsize=10)
419
+ fig.subplots_adjust(left=.12,right=.99,top=.92,bottom=.16,wspace=.45)
420
+ builder.finish(fig,"refcal_top_genes" if reference else "raw_tpm_top_genes",
421
+ "Reference calibration leaves specific gene-state shifts" if reference else "Raw and TPM shifts persist within cell labels",19,
422
+ pd.concat(outputs,ignore_index=True),"Existing ranked gene lists only; no DEG testing. "
423
+ "Displayed ranks are original saved ranks within direction and label-stable cells. "
424
+ "Immediate-early/stress differences may reflect handling or cohort state; that interpretation is untested. "
425
+ "Input and output shifts use different normalization and should not be interpreted as an identical quantitative scale.")
426
+
427
+
428
+ def donor_axes(builder: MaterialBuilder) -> None:
429
+ builder.begin()
430
+ frame=builder.frame(V/'tables/scorer_summary_5arm.csv')
431
+ def arm_name(value: str) -> str:
432
+ return value.replace('_native','').replace('raw_tpm','tpm')
433
+ frame['input_arm']=frame.arm.map(arm_name)
434
+ if set(frame.input_arm) != set(ARM):
435
+ raise ValueError(f"Unexpected donor-axis arms: {frame.arm.tolist()}")
436
+ frame=frame.set_index('input_arm').loc[ARM]
437
+ fields=['rho_y','rho_ifn_mono','rho_ifn_t','rho_klrc2_vs_obs_klrc2']
438
+ fig,axes=plt.subplots(1,2,figsize=FULL)
439
+ for i,arm in enumerate(ARM):
440
+ axes[0].plot(range(4),frame.loc[arm,fields].to_numpy(float),'o-',color=COL[arm],lw=1.6,ms=6)
441
+ axes[1].bar(i,frame.loc[arm,'pb_top1']*100,color=COL[arm],width=.66)
442
+ axes[0].set_xticks(range(4),['Y-gene\nexpression','IFN\nmonocytes','IFN\nT cells','KLRC2+\nNK'],fontsize=11)
443
+ axes[0].set_ylabel('Saved donor-level Spearman ρ');axes[0].axhline(0,color=GREY,lw=.7)
444
+ axes[1].set_xticks(range(5),[LABEL[a] for a in ARM],rotation=22,ha='right',fontsize=10)
445
+ axes[1].set_ylabel('Own-donor pseudobulk top-1 retrieval (%)')
446
+ axes[1].axhline(100/107,color=GREY,ls='--',lw=1,label='Chance: 1/107')
447
+ axes[1].legend(loc='upper right',frameon=False,fontsize=10)
448
+ for ax in axes:clean(ax)
449
+ legend_methods(fig,ARM)
450
+ fig.subplots_adjust(left=.08,right=.99,top=.93,bottom=.27,wspace=.37)
451
+ builder.finish(fig,'donor_axes','Donor trait axes and donor identification differ',19,frame.reset_index(),
452
+ "All Spearman and retrieval values are copied from the saved summary. Y-gene/sex calls and IFN/KLRC2 axes "
453
+ "are expression-derived proxies, not independent clinical-label validation. Top-1 chance line is 1/107. "
454
+ "High trait-axis agreement does not establish donor identity recovery.")
455
+
456
+
457
+ def reference_choice(builder: MaterialBuilder) -> None:
458
+ builder.begin()
459
+ frame=builder.frame(U/'input_path_compare/immicro_behcet/tables/immicro_table.csv').set_index('arm')
460
+ arms=['raw','tpm','refcal','refcal_aida','refcal_train','tpmrefcal','cal','pseudo']
461
+ if not (frame.loc[arms,'status']=='scored').all():raise ValueError('Unscored input comparison')
462
+ fig,axes=plt.subplots(1,3,figsize=FULL)
463
+ for ax,field,title in zip(axes,['precision','coverage','comp_L1'],['Precision','Coverage','Composition L1']):
464
+ ax.bar(range(8),frame.loc[arms,field],color=[COL[a] for a in arms],width=.7)
465
+ ax.set_xticks(range(8),[LABEL[a] for a in arms],rotation=60,ha='right',fontsize=10)
466
+ ax.set_ylabel(title);clean(ax)
467
+ control=frame.loc['real_R2',field]
468
+ ax.axhline(control,color=GREY,ls='--',lw=1)
469
+ ax.set_title('Observed donor-mean null' if field=='comp_L1' else 'Real–real control',fontsize=11,color=GREY)
470
+ fig.subplots_adjust(left=.06,right=.99,top=.89,bottom=.32,wspace=.38)
471
+ builder.finish(fig,'reference_choice','Reference choice changes different quality endpoints',19,frame.reset_index(),
472
+ "All eight generated arms are already scored in immicro_table.csv. No generation or rescore. "
473
+ "AIDA and the training-mixture reference have their own pretraining overlap; this is not a held-out reference experiment. "
474
+ "The composition dashed line is the observed donor-mean leave-one-out null, NOT a real-R2 composition error. "
475
+ "No method-independent win claim is made across different endpoints.")
476
+
477
+
478
+ def sparsity(builder: MaterialBuilder) -> None:
479
+ builder.begin()
480
+ frame=builder.frame(V/'tables/e_detected_genes.csv')
481
+ readouts=sorted(frame.readout.unique())
482
+ # Real counts and Poisson-read generated counts are the comparable readout.
483
+ selected=frame[(frame['set'].isin(['real_R1','real_R2'])) | frame.readout.str.contains('Poisson',case=False)].copy()
484
+ if len(selected)!=7:raise ValueError(f'Unexpected count readout selection: {readouts}; {len(selected)} rows')
485
+ selected['input_arm']=selected['set'].replace({'real_R1':'R1','real_R2':'R2'})
486
+ order=['R1','R2']+ARM;selected=selected.set_index('input_arm').loc[order]
487
+ fig,axes=plt.subplots(1,2,figsize=FULL)
488
+ colors=[GREY,GREY]+[COL[a] for a in ARM]
489
+ for ax,field,label in zip(axes,['detected_median','library_median'],['Median detected genes per cell','Median library size (scoring genes)']):
490
+ values=selected[field].to_numpy(float);ax.bar(range(7),values,color=colors,width=.66)
491
+ if field=='detected_median':
492
+ ax.errorbar(range(7),values,yerr=[values-selected.detected_p10.to_numpy(float),selected.detected_p90.to_numpy(float)-values],fmt='none',ecolor=INK,capsize=3)
493
+ ax.set_xticks(range(7),['Real R1','Real R2']+[LABEL[a] for a in ARM],rotation=25,ha='right',fontsize=10)
494
+ ax.set_ylabel(label);clean(ax)
495
+ fig.subplots_adjust(left=.09,right=.99,top=.94,bottom=.26,wspace=.35)
496
+ builder.finish(fig,'detection_and_library','Detection and library size are separate diagnostics',24,selected.reset_index(),
497
+ "Observed counts and the previously computed Poisson readout of generated cells. "
498
+ "Whiskers are saved 10th–90th cell percentiles, not donor confidence intervals. "
499
+ "Scoring-gene libraries are not full-transcriptome UMI totals.")
500
+
501
+
502
+ def conditioning(builder: MaterialBuilder) -> None:
503
+ builder.begin(native=False)
504
+ source=U/'sle/conditioning_2279'
505
+ pairs=builder.frame(source/'paired_cells.csv').set_index('set')
506
+ summary=builder.frame(U/'sle/metrics_2279/summary_tidy.csv')
507
+ builder.source(source/'RESULTS.md','existing intervention protocol and provenance')
508
+ tags=['f016k_e16','f016kcondflip_e16','f016kcondperm_e16','f016kcondmean_e16']
509
+ names=['True input','Disease flip','Donor permutation','Cohort mean']
510
+ colors=['#C5AA4B','#806A25','#B59A50','#E8DDAE']
511
+ rows=[]
512
+ for tag in tags:
513
+ q=summary[(summary.method=='diffusion_'+tag)&(summary.celltype_gate=='common_celltype_gate')]
514
+ if len(q)!=1:raise ValueError(f'Ambiguous conditioning summary row: {tag}, {len(q)}')
515
+ rows.append(q.iloc[0])
516
+ sub=pd.DataFrame(rows)
517
+ fig,axes=plt.subplots(1,3,figsize=FULL)
518
+ for ax,field,label in zip(axes,['mean_logFC_pearson','total_top50_overlap','composition_l1'],['Disease logFC correlation','Top-50 DEG overlap (sum)','Composition L1']):
519
+ vals=sub[field].to_numpy(float);ax.bar(range(4),vals,color=colors,width=.65)
520
+ ax.set_xticks(range(4),names,rotation=30,ha='right',fontsize=11);ax.set_ylabel(label);clean(ax)
521
+ ax.axhline(0,color=GREY,lw=.7)
522
+ fig.text(.5,.035,'Same-noise donor swap: closest to source donor, 42/42 (flip) and 42/42 (permutation); uncentered comparison.',ha='center',fontsize=10)
523
+ if pairs.loc['condflip','donors_closest_source']!=42 or pairs.loc['condperm','donors_closest_source']!=42:
524
+ raise ValueError('Saved donor-swap control changed; update caption')
525
+ fig.subplots_adjust(left=.07,right=.99,top=.93,bottom=.28,wspace=.40)
526
+ builder.finish(fig,'sle_conditioning_interventions','Does the model follow its bulk conditioning?',14,sub,
527
+ "SLE development benchmark: 42 donors, 2,279 genes, f01 6k E16 EMA, 1,500 generated cells/donor, "
528
+ "50 DDIM steps, seed20260913. Only conditioning differs; noise is matched. These are pseudobulk inputs, "
529
+ "not an independent paired real-bulk validation. Donor-source caption uses saved uncentered nearest-match counts; "
530
+ "centered flip retrieval is 27/42, permutation42/42. Displayed benchmark metrics use the common six-type gate. "
531
+ "The pre-registered condition-use criterion and earlier-model tolerance context are in source RESULTS.md.",
532
+ native=False,footnote="Existing SLE pseudobulk controls: same noise, 42 donors, 2,279 genes. This is a conditioning intervention, not real-bulk validation.")
533
+
534
+
535
+ def split_half(builder: MaterialBuilder) -> None:
536
+ builder.begin(native=False)
537
+ frame=builder.frame(U/'sle_broadcast/tables/splithalf_summary.csv')
538
+ builder.source(U/'sle_broadcast/RESULTS.md','split-half protocol and caveats')
539
+ methods=['ceiling_halfA','broadcast_disjoint','broadcast_full','diffusion_5seed_mean','scSemiProfiler']
540
+ labels=['Real A → real B','Bulk A → real B','Full bulk → real B','PBISC → real B','scSemi → real B']
541
+ colors=[INK,'#AAAAAA','#CCCCCC','#C5AA4B',BLUE]
542
+ fig,axes=plt.subplots(1,2,figsize=FULL)
543
+ chosen=[]
544
+ for ax,axis in zip(axes,[1006,2279]):
545
+ sub=frame[frame.axis.astype(int)==axis].set_index('method').loc[methods]
546
+ vals=sub.mean_over_types.to_numpy(float)
547
+ ax.barh(range(5),vals,color=colors,height=.64)
548
+ ax.errorbar(vals,range(5),xerr=sub.sd_of_mean_over_splits,fmt='none',ecolor=INK,capsize=3)
549
+ ax.set_yticks(range(5),labels,fontsize=11);ax.invert_yaxis();ax.set_xlim(0,.8)
550
+ ax.set_xlabel('Mean cell-type logFC correlation');ax.set_title(f'{axis:,} genes',fontsize=13);clean(ax,'x')
551
+ chosen.append(sub.reset_index())
552
+ fig.subplots_adjust(left=.15,right=.99,top=.91,bottom=.14,wspace=.55)
553
+ builder.finish(fig,'sle_disjoint_truth_control','Disjoint-cell controls test the bulk-broadcast baseline',43,
554
+ pd.concat(chosen,ignore_index=True),"Existing five random half-A/half-B splits of the same 42 held-out SLE donors. "
555
+ "Bulk A is formed from cells disjoint from per-type half-B truth. The full-bulk control includes B. "
556
+ "The observed type-specific half-A predictor is a split-half reference. Bars and SDs are saved summary values; "
557
+ "no split, expression analysis, or hypothesis test is rerun. PBISC values summarize its five existing sampling seeds.",
558
+ native=False,footnote="SLE pseudobulk benchmark; five existing half-cell splits. Error bars are saved split SDs. No new cell splitting or scoring.")
559
+
560
+
561
+ def technical_repeats(builder: MaterialBuilder) -> None:
562
+ builder.begin(native=False)
563
+ doc=builder.document(U/'immicro/out/observed_summary.json')
564
+ builder.source(U/'immicro/out/build_manifest.json','observed-cell analysis provenance')
565
+ builder.source(U/'immicro/out/replicate_pseudobulk_per_donor.csv','existing donor replicate records')
566
+ records=[]
567
+ for key in ['remeasure','followup_visit','capture_halves']:
568
+ value=doc['replicate_pseudobulk'][key]['all_cells']
569
+ records.append({'replicate':key,**value})
570
+ frame=pd.DataFrame(records)
571
+ labels=['Technical remeasurement','Follow-up visit','Capture halves']
572
+ fig,axes=plt.subplots(1,2,figsize=FULL)
573
+ for ax,field,title in zip(axes,['donor_r_median','top1_retrieval'],['Median own-donor pseudobulk r','Own-donor top-1 retrieval (%)']):
574
+ vals=frame[field].to_numpy(float)*(100 if field=='top1_retrieval' else 1)
575
+ ax.bar(range(3),vals,color=['#555555','#999999','#CCCCCC'],width=.65)
576
+ ax.set_xticks(range(3),[f'{label}\n(n={int(n)})' for label,n in zip(labels,frame.n)],fontsize=11)
577
+ ax.set_ylabel(title);clean(ax)
578
+ for i,v in enumerate(vals):ax.text(i,v+(2 if field=='top1_retrieval' else .005),f'{v:.1f}' if field=='top1_retrieval' else f'{v:.3f}',ha='center',fontsize=12)
579
+ ax.set_ylim(0,110 if field=='top1_retrieval' else 1.06)
580
+ fig.subplots_adjust(left=.08,right=.99,top=.91,bottom=.20,wspace=.35)
581
+ builder.finish(fig,'immicro_replicate_controls','Technical repeats and follow-up are different controls',22,frame,
582
+ "Previously processed ImMicro observations. Technical remeasurement and follow-up have 16 donors; "
583
+ "capture-half control has its own recorded sample count. Follow-up is biological longitudinal variation, "
584
+ "not a technical replicate. Correlation and top-1 retrieval are saved aggregates; no new subsampling, "
585
+ "correlation or retrieval analysis. Use the recorded follow-up gene-support rule in observed_summary.json.",
586
+ native=False,footnote="Observed ImMicro controls. Technical remeasurement and follow-up: 16 donors each. Follow-up is not a technical replicate.",palette='preserved')
587
+
588
+
589
+ def annotation_qc(builder: MaterialBuilder) -> None:
590
+ builder.begin(native=False)
591
+ frame=builder.frame(U/'immicro/out/confusion_author_vs_frozen_baseline.csv')
592
+ labelcol=frame.columns[0];matrix=frame[TYPES].to_numpy(float)
593
+ pct=matrix/matrix.sum(axis=1,keepdims=True)*100
594
+ doc=builder.document(U/'immicro/out/observed_summary.json')
595
+ builder.source(U/'immicro/out/build_manifest.json','frozen annotation comparison provenance')
596
+ summary=doc['agreement_baseline']
597
+ fig,(ax,bx)=plt.subplots(1,2,figsize=FULL,gridspec_kw={'width_ratios':[1.1,1]})
598
+ ax.imshow(pct,cmap='Greys',vmin=0,vmax=100,aspect='auto')
599
+ display_labels=frame[labelcol].replace({'author_mixed':'Mixed','author_unlabelled':'Unlabelled'})
600
+ ax.set_xticks(range(6),SHORT,fontsize=11);ax.set_yticks(range(len(frame)),display_labels,fontsize=10)
601
+ ax.set_xlabel('Frozen annotation');ax.set_ylabel('Author annotation')
602
+ for y in range(len(frame)):
603
+ for x in range(6):ax.text(x,y,f'{pct[y,x]:.0f}',ha='center',va='center',fontsize=9,color='white' if pct[y,x]>55 else INK)
604
+ for offset,key,label,col in [(-.17,'recall_by_author_gate','Recall','#555555'),(.17,'precision_by_frozen_label','Precision','#BBBBBB')]:
605
+ values=[summary[key][cell]*100 for cell in TYPES]
606
+ bx.bar(np.arange(6)+offset,values,.32,label=label,color=col)
607
+ bx.set_xticks(range(6),SHORT);bx.set_ylabel('Agreement metric (%)');bx.set_ylim(0,105);clean(bx)
608
+ bx.legend(frameon=False,fontsize=11)
609
+ ax.set_title('Row percentages, including unlabelled categories',fontsize=11)
610
+ bx.set_title(f"Supported six-type gate: {100*summary['agreement_six_type']:.1f}% agreement",fontsize=11)
611
+ fig.subplots_adjust(left=.14,right=.99,top=.88,bottom=.14,wspace=.42)
612
+ plot=frame.copy()
613
+ for j,t in enumerate(TYPES):plot[t+'_row_percent']=pct[:,j]
614
+ builder.finish(fig,'annotation_agreement','Annotation agreement and difficult categories',22,plot,
615
+ "Saved observed-cell comparison, not generated-cell model performance. Overall 97.17% agreement uses "
616
+ "365,404 author-labelled cells in the supported six-type gate; mixed/unlabelled categories are displayed "
617
+ "in the matrix but excluded from that agreement figure. Other has weak correspondence between taxonomies. "
618
+ "The frozen annotation's comparison to author labels is not an independent gold-standard validation. "
619
+ "Heatmap is a count-row normalization for display; precision/recall are saved summary metrics.",
620
+ native=False,footnote="Observed cells only. Overall agreement uses the supported six-type gate; author mixed/unlabelled cells are separate. Other is difficult.",palette='preserved')
621
+
622
+
623
+ def build() -> dict[str, Any]:
624
+ if os.environ.get('CUDA_VISIBLE_DEVICES') != '':
625
+ raise RuntimeError('Set CUDA_VISIBLE_DEVICES empty for this saved-table plot builder')
626
+ FIG.mkdir(parents=True,exist_ok=True);DATA.mkdir(parents=True,exist_ok=True)
627
+ builder=MaterialBuilder()
628
+ settings={'font.family':'sans-serif','font.sans-serif':['Arial','Liberation Sans','DejaVu Sans'],
629
+ 'font.size':14,'axes.labelsize':14,'axes.titlesize':14,'xtick.labelsize':12,'ytick.labelsize':12,
630
+ 'legend.fontsize':12,'axes.spines.top':False,'axes.spines.right':False,'axes.linewidth':1.0,
631
+ 'pdf.fonttype':42,'ps.fonttype':42,'svg.fonttype':'none','figure.facecolor':'white','axes.facecolor':'white'}
632
+ with plt.rc_context(settings):
633
+ for function in [stored_umap,saved_density_reference,composition,matched_trajectories,similarity,transitions,nearest_real,centroids,depth_quality]:function(builder)
634
+ gene_length(builder,False);gene_length(builder,True)
635
+ top_genes(builder,False);top_genes(builder,True)
636
+ for function in [donor_axes,reference_choice,sparsity,conditioning,split_half,technical_repeats,annotation_qc]:function(builder)
637
+ builder.source(Path(__file__),'new saved-table visualization code')
638
+ result={'slides':builder.slides,'assets':builder.assets,'sources':list(builder.sources.values()),
639
+ 'skipped':[{'candidate':'fresh density-grid restyling','reason':'Exact density grid is not in the small CSV tables; original unchanged high-resolution PNG retained as a reference slide instead.'},
640
+ {'candidate':'older three/four-arm and overlay copies','reason':'Superseded or near-duplicate views; five-arm stored-coordinate and metric evidence selected.'}],
641
+ 'new_training':False,'new_generation':False,'new_embedding':False,'new_statistical_scoring':False}
642
+ if len(result['slides'])!=20:raise AssertionError('Expected 20 saved-evidence additions including the original density reference')
643
+ out=D/'data/expanded_master_20261013/healthy_additions.json'
644
+ out.write_text(json.dumps(result,indent=2,ensure_ascii=False)+'\n')
645
+ return result
646
+
647
+
648
+ if __name__=='__main__':
649
+ result=build()
650
+ print(json.dumps({'slides':len(result['slides']),'assets':len(result['assets']),'sources':len(result['sources'])}))
paper-releases/pbisc-diffusion/updates/20261013T034842Z-expanded-131-slide-master/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/expanded_legacy_rare.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replot saved legacy rare-state estimates with method colours kept distinct.
2
+
3
+ The original module and numerical source CSVs remain unchanged. Only its output
4
+ directories and FEW/POOL method-colour tuples are replaced; local cohort colours
5
+ inside the original plotting routine remain intact.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import hashlib
11
+ import importlib.util
12
+ import io
13
+ import json
14
+ from pathlib import Path
15
+
16
+ import pandas as pd
17
+
18
+ DECK = Path(__file__).resolve().parents[1]
19
+ ORIGINAL = DECK / "tools/fig5_rare_states.py"
20
+ FIGURES = DECK / "figures/expanded_master_20261013/legacy_rare"
21
+ DATA = DECK / "data/expanded_master_20261013/legacy_rare"
22
+ STEMS = ("fig5_rare_fraction", "fig5_rare_donors", "fig5_rare_fivefold")
23
+ METHOD_COLOURS = {
24
+ "zs_raw": "#E8DDAE", "zs__raw": "#E8DDAE",
25
+ "scsemi5": "#2166AC", "scsemi__raw": "#2166AC",
26
+ "lora5": "#C5AA4B", "real_lora__raw": "#C5AA4B",
27
+ }
28
+
29
+
30
+ def _sha(path: Path) -> str:
31
+ with path.open("rb") as stream:
32
+ return hashlib.file_digest(stream, "sha256").hexdigest()
33
+
34
+
35
+ def _binding(path: Path, role: str) -> dict:
36
+ return {"path": str(path), "sha256": _sha(path), "bytes": path.stat().st_size, "role": role}
37
+
38
+
39
+ def _assert_same_csv(original: Path, generated_text: str) -> dict:
40
+ expected = pd.read_csv(original)
41
+ actual = pd.read_csv(io.StringIO(generated_text))
42
+ pd.testing.assert_frame_equal(expected, actual, check_exact=True, check_dtype=False,
43
+ check_like=False, check_names=True)
44
+ return {"rows": len(expected), "columns": expected.columns.tolist(),
45
+ "row_order_equal": True, "all_values_equal": True,
46
+ "numeric_tolerance": 0, "nan_positions_equal": True,
47
+ "byte_equal": original.read_bytes() == generated_text.encode()}
48
+
49
+
50
+ def build() -> dict:
51
+ """Return asset paths, input hashes and a saved equality/preservation proof."""
52
+ spec = importlib.util.spec_from_file_location("_expanded_master_legacy_rare_source", ORIGINAL)
53
+ if spec is None or spec.loader is None:
54
+ raise ValueError("Original legacy rare-state plotting module cannot be loaded")
55
+ module = importlib.util.module_from_spec(spec)
56
+ spec.loader.exec_module(module)
57
+ original_table = DECK / "data/fig5_rare_states.csv"
58
+ inputs = [
59
+ _binding(ORIGINAL, "original plotting and unchanged aggregation implementation"),
60
+ _binding(DECK / "tools/style.py", "original deck styling"),
61
+ _binding(module.SRC / "summary.csv", "saved legacy state-summary input"),
62
+ _binding(module.SRC / "contrasts.csv", "saved legacy disease-contrast input"),
63
+ _binding(original_table, "original plotted numeric table, exact comparison target"),
64
+ _binding(Path(__file__), "colour-and-output routing wrapper"),
65
+ ]
66
+ preserved = [ORIGINAL, original_table, DECK / "data/fig5_rare_states_slide_text.json"]
67
+ preserved.extend(DECK / "figures" / f"{stem}.{ext}" for stem in STEMS for ext in ("png", "pdf"))
68
+ before = {str(path): _sha(path) for path in preserved}
69
+
70
+ # Fail before rendering if the currently saved source no longer reproduces
71
+ # the original plot table. Keep its exact original %.5g display precision.
72
+ summary, contrasts, _ = module.load()
73
+ rows = pd.concat([
74
+ module.agg_few(summary, contrasts).assign(design="5 donors (mean of 5 draws)"),
75
+ module.agg_pool(summary, contrasts).assign(design="5-fold pooled"),
76
+ ])
77
+ preflight_text = rows.to_csv(index=False, float_format="%.5g")
78
+ equality = _assert_same_csv(original_table, preflight_text)
79
+
80
+ FIGURES.mkdir(parents=True, exist_ok=True)
81
+ DATA.mkdir(parents=True, exist_ok=True)
82
+ if (FIGURES.resolve() == (DECK / "figures").resolve()
83
+ or DATA.resolve() == (DECK / "data").resolve()):
84
+ raise ValueError("Wrapper output must not be the original asset directory")
85
+ module.FIG, module.DAT = FIGURES, DATA
86
+ module.FEW = [(arm, label, METHOD_COLOURS[arm], marker) for arm, label, _colour, marker in module.FEW]
87
+ module.POOL = [(arm, label, METHOD_COLOURS[arm], marker) for arm, label, _colour, marker in module.POOL]
88
+ log = io.StringIO()
89
+ with contextlib.redirect_stdout(log):
90
+ status = module.main()
91
+ if status != 0:
92
+ raise RuntimeError("Original legacy plotting routine returned a nonzero status")
93
+ equality = _assert_same_csv(original_table, (DATA / "fig5_rare_states.csv").read_text())
94
+ if any(_sha(Path(path)) != expected for path, expected in before.items()):
95
+ raise ValueError("An original script, figure or numeric table changed")
96
+ if any(_sha(Path(item["path"])) != item["sha256"] for item in inputs):
97
+ raise ValueError("An input changed while generating the palette-only variant")
98
+
99
+ assets = {stem: {ext: str(FIGURES / f"{stem}.{ext}") for ext in ("png", "pdf")} for stem in STEMS}
100
+ outputs = [_binding(Path(path), "palette-only legacy plot") for entry in assets.values() for path in entry.values()]
101
+ outputs.extend(_binding(DATA / name, "rerouted legacy derived table or explanatory text")
102
+ for name in ("fig5_rare_states.csv", "fig5_rare_states_slide_text.json"))
103
+ proof = {
104
+ "schema": "pbisc.expanded-master.legacy-rare-palette.v1",
105
+ "method_colours": METHOD_COLOURS,
106
+ "cohort_colours": "unchanged local COH dictionary in original module",
107
+ "scope": "Legacy estimates retained exactly; this does not repair or upgrade the legacy scientific protocol",
108
+ "new_experiment": False, "new_model_outputs": False,
109
+ "numeric_verification": equality, "inputs": inputs, "outputs": outputs,
110
+ "originals_unchanged": before, "original_stdout": log.getvalue(),
111
+ }
112
+ proof_path = DATA / "PROVENANCE.json"
113
+ proof_path.write_text(json.dumps(proof, indent=2, allow_nan=False) + "\n")
114
+ return {"assets": assets, "inputs": inputs, "proof": str(proof_path),
115
+ "numeric_verification": equality}
116
+
117
+
118
+ if __name__ == "__main__":
119
+ print(json.dumps(build(), indent=2))
paper-releases/pbisc-diffusion/updates/20261013T034842Z-expanded-131-slide-master/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/verify_expanded_master_20261013.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Verify and render the expanded paper master without changing source assets.
3
+
4
+ Automated checks never stand in for visual inspection. All output is confined
5
+ to data/expanded_master_20261013/qa and the visual-review state stays pending.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import hashlib
11
+ import json
12
+ import math
13
+ from collections import Counter
14
+ from datetime import datetime, timezone
15
+ from pathlib import Path
16
+
17
+ import fitz
18
+ from PIL import Image, ImageDraw, ImageFont
19
+ from pptx import Presentation
20
+ from pptx.enum.shapes import MSO_SHAPE_TYPE
21
+
22
+ DECK = Path(__file__).resolve().parents[1]
23
+ ARTIFACT = DECK / "data/expanded_master_20261013"
24
+ QA = ARTIFACT / "qa"
25
+ PDF_BOUND_TOLERANCE_PT = 0.75
26
+ EMU_BOUND_TOLERANCE = 2
27
+ ORIGINAL_FULL_REVIEW = {6, 14, 20, 21, 22, 43, 51, 67, 71, 72}
28
+
29
+
30
+ def sha(path: Path) -> str:
31
+ with path.open("rb") as stream:
32
+ return hashlib.file_digest(stream, "sha256").hexdigest()
33
+
34
+
35
+ def resolve(value: str, *, base: Path = DECK) -> Path:
36
+ path = Path(value)
37
+ return path.resolve() if path.is_absolute() else (base / path).resolve()
38
+
39
+
40
+ def load(path: Path) -> dict:
41
+ return json.loads(path.read_text())
42
+
43
+
44
+ def _font_names(run, paragraph) -> list[str]:
45
+ """Return explicitly declared editable text fonts, including EA/complex-script."""
46
+ found = []
47
+ for node in (run._r, paragraph._p):
48
+ for tag in ("a:latin", "a:ea", "a:cs"):
49
+ for item in node.xpath(f"./a:rPr/{tag}" if node is run._r else f"./a:pPr/a:defRPr/{tag}"):
50
+ value = item.get("typeface")
51
+ if value:
52
+ found.append(value)
53
+ if not found:
54
+ name = run.font.name or paragraph.font.name
55
+ if name:
56
+ found.append(name)
57
+ return found
58
+
59
+
60
+ def _text_frames(shape):
61
+ if shape.has_text_frame:
62
+ yield shape.text_frame
63
+ if shape.has_table:
64
+ for row in shape.table.rows:
65
+ for cell in row.cells:
66
+ yield cell.text_frame
67
+
68
+
69
+ def _image_proofs(slide, record: dict, page_number: int, failures: list[dict]) -> dict:
70
+ expected = []
71
+ for value in record.get("figures", []):
72
+ path = resolve(value)
73
+ if not path.is_file():
74
+ failures.append({"check": "figure_source_exists", "slide": page_number, "path": str(path)})
75
+ else:
76
+ expected.append(sha(path))
77
+ actual, picture_details = [], []
78
+ for shape in slide.shapes:
79
+ if shape.shape_type != MSO_SHAPE_TYPE.PICTURE:
80
+ continue
81
+ digest = hashlib.sha256(shape.image.blob).hexdigest()
82
+ actual.append(digest)
83
+ crops = [float(shape.crop_left), float(shape.crop_top), float(shape.crop_right), float(shape.crop_bottom)]
84
+ if any(abs(value) > 1e-12 for value in crops):
85
+ failures.append({"check": "zero_picture_crop", "slide": page_number,
86
+ "shape": shape.name, "crop": crops})
87
+ picture_details.append({"shape": shape.name, "sha256": digest, "crop": crops})
88
+ if Counter(actual) != Counter(expected):
89
+ failures.append({"check": "embedded_figure_bytes", "slide": page_number,
90
+ "expected": dict(Counter(expected)), "actual": dict(Counter(actual))})
91
+ return {"slide": page_number, "expected_images": len(expected), "actual_images": len(actual),
92
+ "byte_multiset_equal": Counter(actual) == Counter(expected), "pictures": picture_details}
93
+
94
+
95
+ def _check_palette_records(manifest: dict, failures: list[dict]) -> list[dict]:
96
+ records, seen = [], set()
97
+
98
+ def visit(value):
99
+ if isinstance(value, list):
100
+ for child in value:
101
+ visit(child)
102
+ elif isinstance(value, dict):
103
+ if "preservation_pass" in value and value["preservation_pass"] is not True:
104
+ failures.append({"check": "palette_preservation", "record": value})
105
+ for key, child in value.items():
106
+ if key in {"proof", "proof_path", "palette_proof", "precolored_proof"} and isinstance(child, str):
107
+ path = resolve(child)
108
+ if path in seen:
109
+ continue
110
+ seen.add(path)
111
+ if not path.is_file():
112
+ failures.append({"check": "palette_proof_exists", "path": str(path)})
113
+ continue
114
+ proof = load(path)
115
+ passed = proof.get("preservation_pass")
116
+ if passed is not None and passed is not True:
117
+ failures.append({"check": "palette_proof_preservation", "path": str(path)})
118
+ records.append({"path": str(path), "sha256": sha(path),
119
+ "preservation_pass": passed,
120
+ "kind": "vector-preservation" if passed is not None else "native-figure-provenance"})
121
+ elif isinstance(child, (dict, list)):
122
+ visit(child)
123
+
124
+ visit(manifest.get("palette_records", []))
125
+ return records
126
+
127
+
128
+ def _render(document, slides: list[dict]) -> dict:
129
+ pages = []
130
+ for index, page in enumerate(document, 1):
131
+ path = QA / f"slide{index:03d}.png"
132
+ pixmap = page.get_pixmap(matrix=fitz.Matrix(1, 1), alpha=False)
133
+ pixmap.save(path)
134
+ record = slides[index - 1] if index <= len(slides) else {}
135
+ pages.append({"slide": index, "path": str(path), "width": pixmap.width, "height": pixmap.height,
136
+ "original_slide": record.get("original_slide"), "addition_key": record.get("addition_key"),
137
+ "selected_full_review": record.get("original_slide") in ORIGINAL_FULL_REVIEW
138
+ or bool(record.get("addition_key"))})
139
+ font_path = Path("/usr/share/fonts/truetype/msttcorefonts/Arial.ttf")
140
+ font = ImageFont.truetype(str(font_path), 14) if font_path.is_file() else ImageFont.load_default()
141
+ contacts = []
142
+ for start in range(0, len(pages), 12):
143
+ canvas = Image.new("RGB", (2000, 900), "white")
144
+ draw = ImageDraw.Draw(canvas)
145
+ for local, item in enumerate(pages[start:start + 12]):
146
+ x, y = (local % 4) * 500, (local // 4) * 300
147
+ with Image.open(item["path"]) as original:
148
+ thumb = original.convert("RGB")
149
+ thumb.thumbnail((500, 281), Image.Resampling.LANCZOS)
150
+ canvas.paste(thumb, (x + (500 - thumb.width) // 2, y + (281 - thumb.height) // 2))
151
+ origin = f"original {item['original_slide']}" if item["original_slide"] else f"added {item['addition_key']}"
152
+ draw.text((x + 8, y + 282), f"{item['slide']:03d} | {origin}"[:68], fill="#222222", font=font)
153
+ path = QA / f"contact{start // 12 + 1:02d}.png"
154
+ canvas.save(path)
155
+ contacts.append({"path": str(path), "slides": [item["slide"] for item in pages[start:start + 12]],
156
+ "width": 2000, "height": 900})
157
+ return {"page_renders": pages, "contacts": contacts,
158
+ "full_review_slides": [item["slide"] for item in pages if item["selected_full_review"]]}
159
+
160
+
161
+ def verify(*, render: bool = True) -> dict:
162
+ QA.mkdir(parents=True, exist_ok=True)
163
+ failures = []
164
+ spec_path, manifest_path = ARTIFACT / "spec.json", ARTIFACT / "manifest.json"
165
+ spec, manifest = load(spec_path), load(manifest_path)
166
+ records = spec["slides"]
167
+ pptx_path = resolve(spec["deck"]["output_pptx"])
168
+ pdf_path = resolve(spec["deck"]["output_pdf"])
169
+ pptx = Presentation(pptx_path)
170
+ pdf = fitz.open(pdf_path)
171
+ counts = {"spec": len(records), "pptx": len(pptx.slides), "pdf": len(pdf)}
172
+ if len(set(counts.values())) != 1 or len(records) <= 76:
173
+ failures.append({"check": "expanded_page_counts", "counts": counts})
174
+ if manifest.get("slides") != records:
175
+ failures.append({"check": "spec_manifest_slide_equality"})
176
+
177
+ retained = [row["original_slide"] for row in records if "original_slide" in row]
178
+ if retained != list(range(1, 77)):
179
+ failures.append({"check": "original_slide_coverage_and_order", "observed": retained})
180
+ additions = [row for row in records if "original_slide" not in row]
181
+ addition_keys = [row.get("addition_key") for row in additions]
182
+ if any(not key for key in addition_keys) or len(set(addition_keys)) != len(addition_keys):
183
+ failures.append({"check": "addition_identifiers", "observed": addition_keys})
184
+
185
+ source_checks = []
186
+ for value, binding in manifest.get("sources", {}).items():
187
+ path = resolve(value)
188
+ expected = binding["sha256"] if isinstance(binding, dict) else binding
189
+ actual = sha(path) if path.is_file() else None
190
+ source_checks.append({"path": str(path), "expected": expected, "actual": actual, "equal": actual == expected})
191
+ if actual != expected:
192
+ failures.append({"check": "manifest_source_hash", "path": str(path), "expected": expected, "actual": actual})
193
+ if not source_checks:
194
+ failures.append({"check": "manifest_sources_empty"})
195
+ originals = load(ARTIFACT / "original_source_hashes.json")
196
+ original_checks = []
197
+ for value, binding in originals.items():
198
+ path = resolve(value)
199
+ expected = binding["sha256"] if isinstance(binding, dict) else binding
200
+ actual = sha(path) if path.is_file() else None
201
+ original_checks.append({"path": str(path), "expected": expected, "actual": actual, "unchanged": actual == expected})
202
+ if actual != expected:
203
+ failures.append({"check": "original_unchanged", "path": str(path), "expected": expected, "actual": actual})
204
+ if not original_checks:
205
+ failures.append({"check": "original_hash_registry_empty"})
206
+
207
+ picture_proofs = []
208
+ text_runs, shapes_checked = 0, 0
209
+ for index, slide in enumerate(pptx.slides, 1):
210
+ for shape in slide.shapes:
211
+ shapes_checked += 1
212
+ if shape.shape_type == MSO_SHAPE_TYPE.GROUP:
213
+ failures.append({"check": "group_requires_transform_audit", "slide": index, "shape": shape.name})
214
+ edges = (shape.left, shape.top, shape.left + shape.width, shape.top + shape.height)
215
+ if (edges[0] < -EMU_BOUND_TOLERANCE or edges[1] < -EMU_BOUND_TOLERANCE
216
+ or edges[2] > pptx.slide_width + EMU_BOUND_TOLERANCE
217
+ or edges[3] > pptx.slide_height + EMU_BOUND_TOLERANCE):
218
+ failures.append({"check": "pptx_shape_bounds", "slide": index, "shape": shape.name,
219
+ "edges_emu": list(edges)})
220
+ for frame in _text_frames(shape):
221
+ for paragraph in frame.paragraphs:
222
+ for run in paragraph.runs:
223
+ if not run.text.strip():
224
+ continue
225
+ text_runs += 1
226
+ fonts = _font_names(run, paragraph)
227
+ if not fonts or any(font.casefold() != "arial" for font in fonts):
228
+ failures.append({"check": "editable_text_arial", "slide": index,
229
+ "shape": shape.name, "fonts": fonts, "text": run.text[:100]})
230
+ if index <= len(records):
231
+ picture_proofs.append(_image_proofs(slide, records[index - 1], index, failures))
232
+
233
+ pdf_spans = 0
234
+ for index, page in enumerate(pdf, 1):
235
+ bounds = page.rect
236
+ for block in page.get_text("dict", flags=0).get("blocks", []):
237
+ for line in block.get("lines", []):
238
+ for span in line.get("spans", []):
239
+ if not span.get("text", "").strip():
240
+ continue
241
+ pdf_spans += 1
242
+ x0, y0, x1, y1 = span["bbox"]
243
+ if (not all(math.isfinite(value) for value in (x0, y0, x1, y1))
244
+ or x0 < bounds.x0 - PDF_BOUND_TOLERANCE_PT
245
+ or y0 < bounds.y0 - PDF_BOUND_TOLERANCE_PT
246
+ or x1 > bounds.x1 + PDF_BOUND_TOLERANCE_PT
247
+ or y1 > bounds.y1 + PDF_BOUND_TOLERANCE_PT):
248
+ failures.append({"check": "pdf_text_bounds", "slide": index,
249
+ "bbox": list(span["bbox"]), "text": span["text"][:100]})
250
+ palette_checks = _check_palette_records(manifest, failures)
251
+ renders = _render(pdf, records) if render else {"page_renders": [], "contacts": [], "full_review_slides": []}
252
+ pdf.close()
253
+ result = {
254
+ "schema": "pbisc.expanded-master.qa.v1", "checked_at_utc": datetime.now(timezone.utc).isoformat(),
255
+ "automated_checks_pass": not failures,
256
+ "status": "automated_checks_passed_visual_review_pending" if not failures else "automated_checks_failed",
257
+ "artifacts": {"pptx": {"path": str(pptx_path), "sha256": sha(pptx_path)},
258
+ "pdf": {"path": str(pdf_path), "sha256": sha(pdf_path)},
259
+ "spec": {"path": str(spec_path), "sha256": sha(spec_path)},
260
+ "manifest": {"path": str(manifest_path), "sha256": sha(manifest_path)}},
261
+ "page_counts": counts, "original_slide_order": retained,
262
+ "added_slide_count": len(additions), "addition_keys": addition_keys,
263
+ "source_checks": source_checks, "original_checks": original_checks,
264
+ "editable_text_runs_checked": text_runs, "pptx_shapes_checked": shapes_checked,
265
+ "pdf_text_spans_checked": pdf_spans, "pdf_bound_tolerance_pt": PDF_BOUND_TOLERANCE_PT,
266
+ "picture_checks": picture_proofs, "palette_proof_checks": palette_checks,
267
+ "failures": failures, **renders,
268
+ "visual_review": {"status": "pending", "passed": None,
269
+ "reason": "Rendering and structural checks do not establish visual readability; inspect the contact sheets and selected full slides."},
270
+ }
271
+ (QA / "VERIFICATION.json").write_text(json.dumps(result, indent=2, allow_nan=False) + "\n")
272
+ return result
273
+
274
+
275
+ def main() -> int:
276
+ parser = argparse.ArgumentParser(description=__doc__)
277
+ parser.add_argument("--no-render", action="store_true", help="Run structural/hash checks without PNG exports")
278
+ args = parser.parse_args()
279
+ result = verify(render=not args.no_render)
280
+ print(json.dumps({"status": result["status"], "page_counts": result["page_counts"],
281
+ "failures": len(result["failures"]), "report": str(QA / "VERIFICATION.json")}, indent=2))
282
+ return 0 if result["automated_checks_pass"] else 1
283
+
284
+
285
+ if __name__ == "__main__":
286
+ raise SystemExit(main())