junidude14 commited on
Commit
ee02d12
·
verified ·
1 Parent(s): 658f29a

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261008T121550Z-deck-fig4-rules-no-broadcast/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/fig3_time_days.pdf ADDED
Binary file (24 kB). View file
 
paper-releases/pbisc-diffusion/updates/20261008T121550Z-deck-fig4-rules-no-broadcast/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/fig3_time_days.png ADDED

Git LFS Details

  • SHA256: 4da2cafa5f961ae8de06ab77f87bee2d8279856062fdae3635460fd9dbfd85bc
  • Pointer size: 131 Bytes
  • Size of remote file: 133 kB
paper-releases/pbisc-diffusion/updates/20261008T121550Z-deck-fig4-rules-no-broadcast/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/secS_deconvolution.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Fig. 4 (since 2026-10-08): cell-type deconvolution given the same paired donors vs LoRA (2026-10-07). User
3
+ decisions of 2026-10-08: the comparison moves to Fig. 4, explicitly labelled as cell-type deconvolution; no
4
+ bulk-broadcast baseline; the 5-donor draws are the main comparison.
5
+
6
+ Source: plans/bayesprism_paired_20261006/results/ (tools/score_bp.py, aggregate_bp.py): BayesPrism with its recommended
7
+ gene set (gene mode "full") and official CIBERSORTx (Docker, S-mode Fractions; HiRes when it ran) on the paired
8
+ benchmark's own splits, donors, observed truth and scorer; the reference is the split's paired donors' observed cells
9
+ (5-donor draws: the draw's 5 training donors; 5-fold CV: each fold's LoRA training + inner-validation pairs).
10
+ Two slides:
11
+ "Cell-type deconvolution, same pairs: composition" composition L1, 5-donor draws (mean +- SD) and pooled 5-fold CV
12
+ "Cell-type deconvolution, same pairs: disease signal" per-type case-vs-control logFC r, partial r beyond the bulk,
13
+ top-50 DEG overlap (5-donor draws, the four disease cohorts)
14
+ Outputs: figures/secS_deconv_{composition,disease}.{png,pdf}, data/secS_deconvolution.csv,
15
+ data/secS_deconvolution_slide_text.json. CPU only, plotting only.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import sys
21
+ from pathlib import Path
22
+
23
+ import numpy as np
24
+ import pandas as pd
25
+
26
+ TOOLS = Path(__file__).resolve().parent
27
+ sys.path.insert(0, str(TOOLS))
28
+ import style as ST # noqa: E402
29
+ from grouped_bars import grouped_bars # noqa: E402
30
+ import matplotlib.pyplot as plt # noqa: E402
31
+
32
+ DECK = TOOLS.parent
33
+ FIGDIR, OUTDATA = DECK / "figures", DECK / "data"
34
+ RES = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/bayesprism_paired_20261006/results")
35
+ ORDER = ["immicro", "ye2026_sepsis", "ji2025_chili", "imperial_eskd", "giroux2022"]
36
+ NAME = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis", "ji2025_chili": "Ji ChILI", "imperial_eskd": "Imperial",
37
+ "giroux2022": "Giroux"}
38
+ COL = {"lora": ST.ARM["lora"], "bp": "#009E73", "cx": "#CC79A7", "scsemi": ST.ARM["scsemi"]}
39
+
40
+
41
+ def load(mode: str, kind: str) -> pd.DataFrame:
42
+ f = RES / f"TABLE_{kind}{'' if mode == 'score' else '_' + mode}.csv"
43
+ return pd.read_csv(f) if f.exists() else pd.DataFrame()
44
+
45
+
46
+ def main() -> int:
47
+ bp_f, bp_c = load("full", "fewshot"), load("full", "cv")
48
+ cx_f, cx_c = load("cibersortx", "fewshot"), load("cibersortx", "cv")
49
+ if bp_f.empty:
50
+ raise SystemExit("no BayesPrism results")
51
+ for t in (bp_f, cx_f):
52
+ if not t.empty:
53
+ t["best_l1"] = t[["bp_l1_final", "bp_l1_first"]].min(1)
54
+ for t in (bp_c, cx_c):
55
+ if not t.empty:
56
+ t["best_l1"] = t[["bp_l1_final", "bp_l1_first"]].min(1)
57
+ have_cx = not cx_f.empty
58
+ have_cx_z = have_cx and cx_f["bp_r"].notna().any()
59
+ rows = []
60
+
61
+ def agg(t, ds, col):
62
+ g = t[t.cohort == ds][col] if not t.empty else pd.Series(dtype=float)
63
+ g = g.dropna()
64
+ return (float(g.mean()), float(g.std(ddof=1)) if len(g) > 1 else np.nan, int(len(g)))
65
+
66
+ # ---------------------------------------------------------------- slide 1: composition
67
+ fig, axes = plt.subplots(1, 2, figsize=ST.FULL, sharey=True)
68
+ arms = [("lora", "PBISC LoRA", COL["lora"], None), ("bp", "BayesPrism", COL["bp"], None)]
69
+ if have_cx:
70
+ arms.append(("cx", "CIBERSORTx", COL["cx"], None))
71
+ vals = {}
72
+ for ds in ORDER:
73
+ vals[("f", ds, "lora")] = agg(bp_f, ds, "lora_l1")
74
+ vals[("f", ds, "bp")] = agg(bp_f, ds, "best_l1")
75
+ vals[("f", ds, "cx")] = agg(cx_f, ds, "best_l1") if have_cx else (np.nan, np.nan, 0)
76
+ vals[("c", ds, "lora")] = agg(bp_c, ds, "lora_l1")
77
+ vals[("c", ds, "bp")] = agg(bp_c, ds, "best_l1")
78
+ vals[("c", ds, "cx")] = agg(cx_c, ds, "best_l1") if not cx_c.empty else (np.nan, np.nan, 0)
79
+ vals[("c", ds, "scsemi")] = agg(bp_c, ds, "scsemi_l1") if "scsemi_l1" in bp_c else (np.nan, np.nan, 0)
80
+ for pi, (key, ax, title) in enumerate((("f", axes[0], "5 donors (mean of 5 draws)"),
81
+ ("c", axes[1], "5-fold CV, pooled"))):
82
+ arms_p = arms + ([("scsemi", "scSemiProfiler", COL["scsemi"], None)] if key == "c" else [])
83
+ grouped_bars(ax, [NAME[d] for d in ORDER], [a for a in arms_p],
84
+ lambda i, a: vals[(key, ORDER[i], a)][0], ST.FS, fmt=None if key == "f" else (lambda v: f"{v:.2f}"))
85
+ if key == "f": # error bars = SD over draws; value labels above the caps
86
+ for k_, (a, _l, c, _h) in enumerate(arms_p):
87
+ xs = np.arange(len(ORDER)) + (k_ - (len(arms_p) - 1) / 2) * (0.8 / len(arms_p))
88
+ ys = np.asarray([vals[(key, d, a)][0] for d in ORDER])
89
+ es = np.nan_to_num(np.asarray([vals[(key, d, a)][1] for d in ORDER]))
90
+ ax.errorbar(xs, ys, yerr=es, fmt="none", ecolor=ST.SUBINK, elinewidth=1, capsize=2, zorder=3)
91
+ for x_, y_, e_ in zip(xs, ys, es):
92
+ if np.isfinite(y_):
93
+ ax.text(x_, y_ + e_ + 0.015, f"{y_:.2f}", ha="center", va="bottom", fontsize=ST.FS - 6,
94
+ color=ST.SUBINK)
95
+ ax.set_title(title, fontsize=ST.FS - 1, loc="left")
96
+ if pi == 0:
97
+ ax.set_ylabel("Composition L1 (lower is better)")
98
+ handles = [plt.Rectangle((0, 0), 1, 1, color=c) for _a, _l, c, _h in arms + [("scsemi", "", COL["scsemi"], None)]]
99
+ labels = [l for _a, l, _c, _h in arms] + ["scSemiProfiler"]
100
+ axes[1].legend(handles, labels, loc="upper left", fontsize=ST.FS - 3)
101
+ fig.tight_layout()
102
+ ST.save(fig, "secS_deconv_composition", FIGDIR)
103
+ # ---------------------------------------------------------------- slide 2: disease signal (5-donor draws)
104
+ dis = [d for d in ORDER if d != "immicro"]
105
+ fig, axes = plt.subplots(1, 3, figsize=ST.FULL)
106
+ arms2 = [("lora", "PBISC LoRA", COL["lora"], None), ("bp", "BayesPrism Z", COL["bp"], None)]
107
+ if have_cx_z:
108
+ arms2.append(("cx", "CIBERSORTx HiRes", COL["cx"], None))
109
+ for ax, (metric, lab) in zip(axes, (("r", "Cell-type logFC r"), ("partial", "Partial r beyond bulk"),
110
+ ("deg", "Top-50 DEG overlap"))):
111
+ a2 = arms2 # no bulk-broadcast baseline (user decision 2026-10-08)
112
+
113
+ def val(i, a, metric=metric):
114
+ ds = dis[i]
115
+ t = cx_f if a == "cx" else bp_f
116
+ col = {"r": "lora_r", "partial": "lora_partial", "deg": "lora_deg"}[metric] if a == "lora" else \
117
+ {"r": "bp_r", "partial": "bp_partial", "deg": "bp_deg"}[metric]
118
+ return agg(t, ds, col)[0]
119
+ grouped_bars(ax, [NAME[d] for d in dis], a2, val, ST.FS - 1,
120
+ fmt=(lambda v: f"{v:.0f}") if metric == "deg" else (lambda v: f"{v:.2f}"))
121
+ ax.set_title(lab, fontsize=ST.FS - 1, loc="left", fontweight="bold" if metric == "partial" else "normal")
122
+ ax.tick_params(axis="x", labelsize=ST.FS - 4)
123
+ handles = [plt.Rectangle((0, 0), 1, 1, color=c) for _a, _l, c, _h in arms2]
124
+ axes[0].legend(handles, [l for _a, l, _c, _h in arms2], loc="upper left", fontsize=ST.FS - 4)
125
+ fig.tight_layout()
126
+ ST.save(fig, "secS_deconv_disease", FIGDIR)
127
+ # ---------------------------------------------------------------- numbers, keywords
128
+ for ds in ORDER:
129
+ r = {"cohort": NAME[ds]}
130
+ for key in ("f", "c"):
131
+ for a in ("lora", "bp", "cx", "scsemi"):
132
+ if (key, ds, a) in vals:
133
+ r[f"{key}_{a}_l1"] = vals[(key, ds, a)][0]
134
+ for a, t, cols in (("lora", bp_f, ("lora_r", "lora_partial", "lora_deg")), ("bp", bp_f, ("bp_r", "bp_partial", "bp_deg")),
135
+ ("cx", cx_f, ("bp_r", "bp_partial", "bp_deg"))):
136
+ for m, c in zip(("r", "partial", "deg"), cols):
137
+ r[f"f_{a}_{m}"] = agg(t, ds, c)[0] if (c and not t.empty) else np.nan
138
+ rows.append(r)
139
+ tab = pd.DataFrame(rows)
140
+ tab.to_csv(OUTDATA / "secS_deconvolution.csv", index=False)
141
+ def wins(t):
142
+ """draw counts where LoRA-5 beats the method (rows with both values only)"""
143
+ m = t.bp_r.notna() & t.lora_r.notna()
144
+ return {"l1": (int((t.lora_l1 < t.best_l1).sum()), len(t)),
145
+ "r": (int((t.lora_r > t.bp_r)[m].sum()), int(m.sum())),
146
+ "partial": (int((t.lora_partial > t.bp_partial)[m].sum()), int(m.sum())),
147
+ "deg": (int((t.lora_deg > t.bp_deg)[m].sum()), int((t.lora_deg < t.bp_deg)[m].sum()),
148
+ int((t.lora_deg == t.bp_deg)[m].sum()), int(m.sum()))}
149
+ wb = wins(bp_f)
150
+ wc = wins(cx_f) if have_cx_z else None
151
+ # 5-fold: cohorts where PBISC has the lowest composition L1 of every method shown
152
+ best_cv = []
153
+ for ds in ORDER:
154
+ others = [vals[("c", ds, a)][0] for a in ("bp", "cx", "scsemi")]
155
+ others = [x for x in others if np.isfinite(x)]
156
+ best_cv.append(bool(others) and vals[("c", ds, "lora")][0] < min(others))
157
+ beaten_by = [NAME[d] + " (scSemiProfiler)" for d, b in zip(ORDER, best_cv) if not b]
158
+ # CIBERSORTx draws without any HiRes-imputed gene in the contrast types (no cell-type logFC)
159
+ cx_noz = ({NAME[d]: int(cx_f[(cx_f.cohort == d)].bp_r.isna().sum()) for d in dis} if have_cx_z else {})
160
+ cx_noz = {k: v for k, v in cx_noz.items() if v}
161
+ if have_cx:
162
+ kw1 = [f"PBISC closer than BayesPrism in {wb['l1'][0]}/{wb['l1'][1]} draws, "
163
+ f"than CIBERSORTx in {wins(cx_f)['l1'][0]}/{wins(cx_f)['l1'][1]}",
164
+ "Deconvolution misreads real bulk",
165
+ f"5-fold: PBISC lowest in {sum(best_cv)} of {len(ORDER)} cohorts"]
166
+ else:
167
+ kw1 = [f"PBISC closer in {wb['l1'][0]} of {wb['l1'][1]} draws", "Deconvolution misreads real bulk",
168
+ f"5-fold: PBISC lowest in {sum(best_cv)} of {len(ORDER)} cohorts"]
169
+ if wc:
170
+ kw2 = [f"logFC r: PBISC ahead in {wb['r'][0]}/{wb['r'][1]} draws (BayesPrism), {wc['r'][0]}/{wc['r'][1]} "
171
+ "(CIBERSORTx)",
172
+ f"Beyond bulk: PBISC ahead in {wb['partial'][0]}/{wb['partial'][1]} and {wc['partial'][0]}/{wc['partial'][1]}",
173
+ f"Top-50 DEG mixed: PBISC ahead in {wb['deg'][0]}/{wb['deg'][3]} and {wc['deg'][0]}/{wc['deg'][3]}"]
174
+ else:
175
+ kw2 = [f"logFC r: PBISC ahead in {wb['r'][0]}/{wb['r'][1]} draws", f"Beyond bulk: PBISC {wb['partial'][0]}/{wb['partial'][1]}",
176
+ f"Top-50 DEG mixed: {wb['deg'][0]} vs {wb['deg'][1]}"]
177
+ num1 = [{"value": "; ".join(f"{NAME[d]}: 5 donors L1 PBISC {vals[('f', d, 'lora')][0]:.3f} / BayesPrism "
178
+ f"{vals[('f', d, 'bp')][0]:.3f}" + (f" / CIBERSORTx {vals[('f', d, 'cx')][0]:.3f}" if have_cx else "")
179
+ + f"; 5-fold PBISC {vals[('c', d, 'lora')][0]:.3f} / BayesPrism {vals[('c', d, 'bp')][0]:.3f}"
180
+ + (f" / CIBERSORTx {vals[('c', d, 'cx')][0]:.3f}" if np.isfinite(vals[('c', d, 'cx')][0]) else "")
181
+ + (f" / scSemiProfiler {vals[('c', d, 'scsemi')][0]:.3f}" if np.isfinite(vals[('c', d, 'scsemi')][0])
182
+ else " / scSemiProfiler running")
183
+ for d in ORDER), "source": "data/secS_deconvolution.csv"}]
184
+ ti = tab.set_index("cohort")
185
+ num2 = [{"value": "; ".join(f"{NAME[d]}: logFC r PBISC {ti.loc[NAME[d], 'f_lora_r']:.3f} / BayesPrism "
186
+ f"{ti.loc[NAME[d], 'f_bp_r']:.3f} / CIBERSORTx {ti.loc[NAME[d], 'f_cx_r']:.3f}; "
187
+ f"partial r {ti.loc[NAME[d], 'f_lora_partial']:.3f} / "
188
+ f"{ti.loc[NAME[d], 'f_bp_partial']:.3f} / {ti.loc[NAME[d], 'f_cx_partial']:.3f}; DEG "
189
+ f"{ti.loc[NAME[d], 'f_lora_deg']:.1f} / {ti.loc[NAME[d], 'f_bp_deg']:.1f} / "
190
+ f"{ti.loc[NAME[d], 'f_cx_deg']:.1f}" for d in dis),
191
+ "source": "data/secS_deconvolution.csv"},
192
+ {"value": f"draws where PBISC LoRA-5 beats BayesPrism: logFC r {wb['r'][0]}/{wb['r'][1]}, partial r "
193
+ f"{wb['partial'][0]}/{wb['partial'][1]}, top-50 DEG {wb['deg'][0]} (BayesPrism ahead "
194
+ f"{wb['deg'][1]}, ties {wb['deg'][2]})" + (
195
+ f"; beats CIBERSORTx: logFC r {wc['r'][0]}/{wc['r'][1]}, partial r {wc['partial'][0]}/"
196
+ f"{wc['partial'][1]}, top-50 DEG {wc['deg'][0]} (CIBERSORTx ahead {wc['deg'][1]}, ties "
197
+ f"{wc['deg'][2]})" if wc else ""),
198
+ "source": "plans/bayesprism_paired_20261006/results/TABLE_fewshot_full.csv, TABLE_fewshot_cibersortx.csv"}]
199
+ cx_note = ("CIBERSORTx: official Docker images (x86, run under qemu emulation on server_1), single-cell "
200
+ "reference mode with S-mode batch correction (up to 400 reference cells per type), fractions in cell "
201
+ "units (divided by each type's mean UMI per reference cell). " if have_cx else
202
+ "CIBERSORTx: not yet available. ")
203
+ cx_note += ("CIBERSORTx HiRes gives per-sample cell-type expression for the genes it imputes per type (others "
204
+ "are written as 1 and count as zero here)"
205
+ + (("; it imputed no gene of the four contrast types in "
206
+ + " and ".join(f"{v} {k}" for k, v in cx_noz.items())
207
+ + f" draw{'s' if sum(cx_noz.values()) > 1 else ''}, which therefore have no CIBERSORTx disease "
208
+ "score") if cx_noz else "") + ". "
209
+ if have_cx_z else
210
+ "CIBERSORTx HiRes (cell-type expression) did not run on these inputs, so the disease slide shows "
211
+ "BayesPrism only. ")
212
+ full1 = ("Cell-type deconvolution (cell-type fractions and per-type expression, not single cells) given the same "
213
+ "paired donors as PBISC LoRA, on the paired benchmark's own "
214
+ "splits, observed truth and scorer: 5-donor draws (reference = the draw's 5 training donors' observed "
215
+ "cells, mixture = the test samples' real bulk) and 5-fold CV (reference = each fold's LoRA training + "
216
+ "inner-validation pairs; pooled). BayesPrism: recommended gene set (protein-coding minus chrX/Y/M and "
217
+ "ribosomal genes, 15-19k), reference states = gate | AIFI L2; its better theta (initial or final) in cell "
218
+ "units is shown. " + cx_note + "Composition L1 over the six-type gate, lower is better. 5-fold: "
219
+ + (f"PBISC has the lowest L1 except in {', '.join(beaten_by)}" if beaten_by else
220
+ "PBISC has the lowest L1 in every cohort")
221
+ + ("; scSemiProfiler bars appear as its 5-fold runs finish ('n/a' = still running)"
222
+ if any(not np.isfinite(vals[("c", d, "scsemi")][0]) for d in ORDER) else "")
223
+ + ". Pipeline check: "
224
+ "on pseudobulk mixtures BayesPrism recovers the observed mRNA shares (e.g. T 0.39 vs 0.38), so the error "
225
+ "comes from real bulk. Source: plans/bayesprism_paired_20261006/results/RESULTS_full.md, "
226
+ "RESULTS_cibersortx.md.")
227
+ full2 = ("Cell-type deconvolution, not single cells. Case-vs-control per-cell-type logFC (mean CP10K; T, B, "
228
+ "Monocyte, NK) from BayesPrism's posterior cell-type expression Z and CIBERSORTx HiRes, scored with the "
229
+ "benchmark's own functions; partial r = the same r after both logFCs are residualised on the input bulk's "
230
+ "logFC (the cell-type signal the bulk does not carry); top-50 DEG = Welch, summed over types (many ties at "
231
+ "0 in Ji and Giroux). 5-donor draws (the 5-pair comparison), mean "
232
+ "over draws with a score. Giroux excludes sex-linked genes, as everywhere in the deck. " + cx_note
233
+ + "Source: plans/bayesprism_paired_20261006/results/RESULTS_full.md, RESULTS_cibersortx.md.")
234
+ slides = [
235
+ {"title": "Cell-type deconvolution, same pairs: composition", "layout": "full",
236
+ "figures": [str(FIGDIR / "secS_deconv_composition.png")], "keywords": kw1,
237
+ "footnote_short": "Same donors, truth and scorer as PBISC. Reference = the paired donors' cells.",
238
+ "footnote": full1, "numbers": num1},
239
+ {"title": "Cell-type deconvolution, same pairs: disease signal", "layout": "full",
240
+ "figures": [str(FIGDIR / "secS_deconv_disease.png")], "keywords": kw2,
241
+ "footnote_short": "5-donor draws, mean over draws. Partial r = cell-type signal beyond the bulk.",
242
+ "footnote": full2, "numbers": num2}]
243
+ for s in slides:
244
+ if len(s["footnote_short"]) > 110:
245
+ raise SystemExit("short footnote too long")
246
+ out = {"section": "S-deconvolution", "scripts": [str(Path(__file__).resolve())],
247
+ "generated_from": "tools/secS_deconvolution.py (rerun to refresh; do not edit by hand)", "slides": slides}
248
+ (OUTDATA / "secS_deconvolution_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))
249
+ print("\n".join(kw1 + kw2))
250
+ print(tab.round(3).to_string(index=False))
251
+ return 0
252
+
253
+
254
+ if __name__ == "__main__":
255
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261008T121550Z-deck-fig4-rules-no-broadcast/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sync_sec09_text.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Copy generated slide text into data/slides_spec.json.
3
+
4
+ sec09_paired_validation.py regenerates titles, keywords and footnotes from the
5
+ scores (the scSemiProfiler verdicts can change when the missing draws arrive).
6
+ Run after that script and before generate_deck.py:
7
+
8
+ python3 tools/sec09_paired_validation.py
9
+ python3 tools/sync_sec09_text.py
10
+ python3 generate_deck.py
11
+
12
+ Two kinds of spec slides are synced:
13
+ - "sec09_index": i -> slide i of data/sec09_slide_text.json (section 9 main slides)
14
+ - "text_source": {"file": "data/<x>_slide_text.json", "index": i}
15
+ -> slide i of that file (added 2026-10-02: data/sec09_extra_slide_text.json from
16
+ tools/sec09_extra_metrics.py, data/sec07_rank_sweep_slide_text.json from
17
+ tools/sec07_rank_sweep.py)
18
+
19
+ Titles, keywords, footnote_full, numbers and (from footnote_short) the on-slide footnote
20
+ are overwritten; if footnote_full changed, the script lists the slide so the
21
+ short copy can be checked by hand (the deck build fails if it exceeds 2 lines).
22
+ """
23
+ import json
24
+ import sys
25
+ from pathlib import Path
26
+
27
+ DECK = Path(__file__).resolve().parents[1]
28
+ SPEC = Path(sys.argv[1]) if len(sys.argv) > 1 else DECK / "data" / "slides_spec.json"
29
+ SRC = DECK / "data" / "sec09_slide_text.json"
30
+ # section-9 slides deliberately left out of the deck (index -> why); every other index must be used exactly once
31
+ RETIRED = {2: "5 donors: LoRA vs scSemiProfiler — disease signal; superseded 2026-10-08 by tools/fig4_disease.py "
32
+ "(5-pair comparison without the bulk-broadcast baseline, partial r added)"}
33
+
34
+
35
+ def copy_text(s: dict, g: dict, review: list) -> None:
36
+ figs = [str(Path(f).relative_to(DECK)) for f in g["figures"]]
37
+ have = [str(Path(f).relative_to(DECK)) if Path(f).is_absolute() else f for f in s["figures"]]
38
+ if figs != have:
39
+ raise SystemExit(f"figure mismatch for '{g['title']}': {figs} vs {s['figures']}")
40
+ s["figures"] = figs
41
+ s["title"] = g["title"]
42
+ s["keywords"] = g["keywords"]
43
+ if s.get("footnote_full", s.get("footnote")) != g["footnote"]:
44
+ review.append(g["title"])
45
+ s["footnote_full"] = g["footnote"]
46
+ if g.get("footnote_short"):
47
+ s["footnote"] = g["footnote_short"]
48
+ s["numbers"] = g["numbers"] # quoted numbers + sources, kept in step with the slide text (2026-10-01)
49
+
50
+
51
+ def main() -> None:
52
+ spec = json.loads(SPEC.read_text())
53
+ src = json.loads(SRC.read_text())["slides"]
54
+ review = []
55
+ n = 0
56
+ other: dict = {}
57
+ for s in spec["slides"]:
58
+ i = s.get("sec09_index")
59
+ if i is not None:
60
+ copy_text(s, src[i], review)
61
+ n += 1
62
+ continue
63
+ ts = s.get("text_source")
64
+ if ts:
65
+ f = DECK / ts["file"]
66
+ g = json.loads(f.read_text())["slides"]
67
+ copy_text(s, g[int(ts["index"])], review)
68
+ other.setdefault(ts["file"], set()).add(int(ts["index"]))
69
+ used = {s.get("sec09_index") for s in spec["slides"] if s.get("sec09_index") is not None}
70
+ if used & set(RETIRED) or n + len(RETIRED) != len(src) or src[2]["title"] != RETIRED[2].split(";")[0]:
71
+ raise SystemExit(f"spec has {n} sec09 slides + {len(RETIRED)} retired, source has {len(src)}")
72
+ for f, idx in other.items():
73
+ m = len(json.loads((DECK / f).read_text())["slides"])
74
+ if idx != set(range(m)):
75
+ raise SystemExit(f"spec uses slides {sorted(idx)} of {f}, which has {m}")
76
+ SPEC.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n")
77
+ print(f"synced {n} section 9 slides and " + ", ".join(f"{len(v)} from {k}" for k, v in other.items()))
78
+ for t in review:
79
+ print(f"REVIEW short footnote (source footnote changed): {t}")
80
+
81
+
82
+ if __name__ == "__main__":
83
+ main()