junidude14 commited on
Commit
679aff1
·
verified ·
1 Parent(s): 4ee2286

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec07_ft_modes.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Section 7, slide (a): full FT vs LoRA vs condition-encoder-only vs sc-only FT vs zero-shot paired cal,
2
+ plus the compute cost (trainable parameters, wall-clock time per training step).
3
+
4
+ Accuracy: ImMicro and sepsis, 5-fold cross-fitted, pooled scoring (one call over all donors).
5
+ The condition-encoder-only arm exists only in the fold-0 pilot, so the L1 and coverage panels also show
6
+ every arm from the fold-0 scoring call (open diamonds). Metrics are only comparable within one scoring call,
7
+ so filled circles (pooled call) and open diamonds (fold-0 call) are never compared with each other.
8
+ The sepsis-vs-control logFC r is shown for the pooled call only: the fold-0 contrast rests on 5 controls
9
+ and the source README calls the per-fold contrast too noisy to use.
10
+
11
+ Compute: time per training step (median over runs), not minutes per run, because runs early-stop at
12
+ different steps (sepsis full 5.75k-20k, LoRA 5.75k-15k). All three modes use batch 256 and validate every
13
+ 250 steps (asserted from RUN.json), so wall seconds / steps_run is a like-for-like per-step cost.
14
+
15
+ Every number is read from the score summaries / RUN.json receipts below. CPU only.
16
+ """
17
+ import json
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ import pandas as pd
23
+ from scipy.stats import wilcoxon
24
+
25
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
26
+ "2026-09-30--paper-summary--r00")
27
+ sys.path.insert(0, str(DECK / "tools"))
28
+ import style # noqa: E402
29
+ import matplotlib.pyplot as plt # noqa: E402
30
+ from matplotlib.lines import Line2D # noqa: E402
31
+
32
+ PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
33
+ "paired_finetune_intradataset_20260927")
34
+ FIGDIR, DATADIR = DECK / "figures", DECK / "data"
35
+ DATASETS = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis"}
36
+ CELLTYPES = ["T cell", "B cell", "Monocyte", "NK cell"]
37
+
38
+ # rows top -> bottom: (score arm key, run dir name or None, label, colour)
39
+ ARMS = [
40
+ ("real_full__raw", "real_full", "full FT", style.ARM["full_ft"]),
41
+ ("real_lora__raw", "real_lora", "LoRA FT (r 16)", style.ARM["lora"]),
42
+ ("real_condenc__raw", "real_condenc", "cond.-encoder-only FT", style.ARM["other"]),
43
+ ("pseudo_full__cal", None, "sc-only FT + cal", style.ARM["sconly"]),
44
+ ("zs__cal", None, "zero-shot + paired cal", style.ARM["zs_cal"]),
45
+ ]
46
+ COMPUTE_ARMS = ARMS[:3]
47
+
48
+
49
+ def load_call(ds, call):
50
+ root = PLAN / "scores" / ds / call
51
+ summ = json.loads((root / "summary.json").read_text())
52
+ con = pd.read_csv(root / "contrast.csv") if (root / "contrast.csv").exists() else None
53
+ per = pd.read_csv(root / "per_donor.csv")
54
+ return root, summ, con, per
55
+
56
+
57
+ def arm_metrics(ds, call):
58
+ root, summ, con, per = load_call(ds, call)
59
+ rows = []
60
+ for arm, _, label, _ in ARMS:
61
+ if arm not in summ["arms"]:
62
+ continue
63
+ h = summ["headline"][arm]
64
+ r = {"dataset": ds, "call": call, "arm": arm, "label": label, "n_donors": summ["n_donors"],
65
+ "comp_l1": h["comp_l1"], "coverage": h["coverage"], "precision": h["precision"],
66
+ "source_summary": str(root / "summary.json")}
67
+ if con is not None:
68
+ c = con[(con["arm"] == arm) & (con["statistic"] == "mean_cp10k") & con["celltype"].isin(CELLTYPES)]
69
+ assert set(c["celltype"]) == set(CELLTYPES), (ds, call, arm)
70
+ r["logfc_r"] = float(c["r_generated"].mean())
71
+ assert abs(r["logfc_r"] - h["contrast_mean_cp10k_r_gen"]) < 1e-9
72
+ r["n_case"] = int(c["n_case_donors_obs"].iloc[0])
73
+ r["n_control"] = int(c["n_control_donors_obs"].iloc[0])
74
+ r["source_contrast"] = str(root / "contrast.csv")
75
+ rows.append(r)
76
+ return pd.DataFrame(rows), per
77
+
78
+
79
+ def compute_receipts():
80
+ rows = []
81
+ for ds in DATASETS:
82
+ for arm, run, label, _ in COMPUTE_ARMS:
83
+ for f in sorted((PLAN / "runs" / ds).glob(f"fold[0-9]/{run}/RUN.json")):
84
+ d = json.loads(f.read_text())
85
+ rows.append({"dataset": ds, "arm": arm, "label": label, "fold": d["fold"], "mode": d["mode"],
86
+ "lr": d["lr"], "batch_size": d["batch_size"], "eval_every": d["eval_every"],
87
+ "n_trainable": d["trainable"]["n_trainable"],
88
+ "n_total_base": d["trainable"]["n_total_base"],
89
+ "wall_seconds": d["wall_seconds"], "steps_run": d["steps_run"],
90
+ "sec_per_step": d["wall_seconds"] / d["steps_run"],
91
+ "selected_step": d["selected_step"],
92
+ "selected_inner_val_loss": d["selected_inner_val_loss"],
93
+ "pretrained_inner_val_loss": d["pretrained_inner_val_loss"],
94
+ "source_checkpoint": d["source_checkpoint"], "run_json": str(f)})
95
+ return pd.DataFrame(rows)
96
+
97
+
98
+ def main():
99
+ acc, pers = [], {}
100
+ for ds in DATASETS:
101
+ for call in ("pooled", "fold0"):
102
+ df, per = arm_metrics(ds, call)
103
+ acc.append(df)
104
+ pers[(ds, call)] = per
105
+ acc = pd.concat(acc, ignore_index=True)
106
+ # sanity: the condition-encoder arm is only in the fold-0 call
107
+ assert not ((acc["call"] == "pooled") & (acc["arm"] == "real_condenc__raw")).any()
108
+
109
+ # paired Wilcoxon of donor-level L1, full vs LoRA, pooled call
110
+ wil = []
111
+ for ds in DATASETS:
112
+ p = pers[(ds, "pooled")].pivot(index="donor", columns="arm", values="comp_l1")
113
+ x = (p["real_full__raw"] - p["real_lora__raw"]).dropna()
114
+ wil.append({"dataset": ds, "comparison": "full - LoRA comp_l1", "mean_diff": float(x.mean()),
115
+ "wilcoxon_p": float(wilcoxon(x).pvalue), "n": int(len(x)),
116
+ "source": str(PLAN / "scores" / ds / "pooled" / "per_donor.csv")})
117
+ wil = pd.DataFrame(wil)
118
+
119
+ rec = compute_receipts()
120
+ # per-step cost is like-for-like only if batch size and validation cadence match across modes
121
+ assert rec["batch_size"].nunique() == 1 and rec["eval_every"].nunique() == 1
122
+ agg = dict(n_runs=("fold", "size"), folds=("fold", lambda s: ",".join(map(str, sorted(s)))),
123
+ n_trainable=("n_trainable", "first"), n_trainable_nunique=("n_trainable", "nunique"),
124
+ lr=("lr", "first"),
125
+ wall_min_median=("wall_seconds", lambda s: float(np.median(s)) / 60.0),
126
+ wall_min_min=("wall_seconds", lambda s: float(np.min(s)) / 60.0),
127
+ wall_min_max=("wall_seconds", lambda s: float(np.max(s)) / 60.0),
128
+ steps_run_median=("steps_run", "median"), steps_run_min=("steps_run", "min"),
129
+ steps_run_max=("steps_run", "max"),
130
+ sec_per_step_median=("sec_per_step", "median"))
131
+ comp = rec.groupby(["dataset", "arm", "label"]).agg(**agg).reset_index()
132
+ comp_all = rec.groupby(["arm", "label"]).agg(**agg).reset_index().assign(dataset="both")
133
+ comp = pd.concat([comp, comp_all], ignore_index=True)
134
+ assert (comp["n_trainable_nunique"] == 1).all()
135
+ n_full = int(rec.loc[rec["arm"] == "real_full__raw", "n_trainable"].iloc[0])
136
+ n_lora = int(rec.loc[rec["arm"] == "real_lora__raw", "n_trainable"].iloc[0])
137
+ ratio = n_full / n_lora
138
+ sps = comp[comp["dataset"] == "both"].set_index("arm")["sec_per_step_median"]
139
+ step_ratio = float(sps["real_full__raw"] / sps["real_lora__raw"])
140
+
141
+ acc.to_csv(DATADIR / "sec07_ft_modes_accuracy.csv", index=False)
142
+ rec.to_csv(DATADIR / "sec07_ft_modes_compute_runs.csv", index=False)
143
+ comp.to_csv(DATADIR / "sec07_ft_modes_compute.csv", index=False)
144
+ wil.to_csv(DATADIR / "sec07_ft_modes_wilcoxon.csv", index=False)
145
+
146
+ # ------------------------------------------------------------------ figure
147
+ W, H = 12.2, 4.95
148
+ fig = plt.figure(figsize=(W, H))
149
+
150
+ def ax_in(x, y, w, h):
151
+ return fig.add_axes([x / W, y / H, w / W, h / H])
152
+
153
+ ny = len(ARMS)
154
+ ypos = {a[0]: ny - 1 - i for i, a in enumerate(ARMS)}
155
+ x0, gap, ggap = 2.3, 0.36, 0.62
156
+ pw = (W - x0 - ggap - 3 * gap) / 5
157
+ top_y, top_h = 2.3, 2.1
158
+ # (dataset, metric, x label, xlim, ticks, show fold-0 diamonds)
159
+ # last tick sits inside the axis so it never touches the next panel's "0" (logFC r is the last panel)
160
+ panels = [("immicro", "comp_l1", "L1 ↓", (0, 0.5), [0, 0.2, 0.4], True),
161
+ ("immicro", "coverage", "coverage ↑", (0, 1.0), [0, 0.4, 0.8], True),
162
+ ("ye2026_sepsis", "comp_l1", "L1 ↓", (0, 0.5), [0, 0.2, 0.4], True),
163
+ ("ye2026_sepsis", "coverage", "coverage ↑", (0, 1.0), [0, 0.4, 0.8], True),
164
+ ("ye2026_sepsis", "logfc_r", "logFC r ↑", (0, 0.65), [0, 0.2, 0.4, 0.6], False)]
165
+ xs = []
166
+ x = x0
167
+ for i in range(len(panels)):
168
+ xs.append(x)
169
+ x += pw + (ggap if i == 1 else gap)
170
+ for i, (ds, met, xlabel, xlim, ticks, show_f0) in enumerate(panels):
171
+ ax = ax_in(xs[i], top_y, pw, top_h)
172
+ for arm, _, label, col in ARMS:
173
+ y = ypos[arm]
174
+ ax.axhline(y, color="#E6E6E6", lw=0.8, zorder=0)
175
+ calls = (("pooled", 0.14, "o", True), ("fold0", -0.14, "D", False)) if show_f0 else \
176
+ (("pooled", 0.0, "o", True),)
177
+ drawn = False
178
+ for call, dy, mk, fill in calls:
179
+ s = acc[(acc["dataset"] == ds) & (acc["call"] == call) & (acc["arm"] == arm)]
180
+ if len(s) == 0:
181
+ continue
182
+ v = float(s[met].iloc[0])
183
+ ax.plot([v], [y + dy], marker=mk, ms=9 if mk == "o" else 7.5, mec=col,
184
+ mfc=col if fill else "white", mew=1.8, ls="none", zorder=3)
185
+ drawn = True
186
+ if not drawn:
187
+ ax.text(0.02, y, "no pooled contrast", ha="left", va="center", fontsize=style.FS - 3,
188
+ color="#6E6E6E", transform=ax.get_yaxis_transform())
189
+ ax.set_xlim(*xlim)
190
+ ax.set_xticks(ticks)
191
+ ax.set_xticklabels([f"{t:g}" for t in ticks])
192
+ ax.set_ylim(-0.6, ny - 0.4)
193
+ ax.set_yticks([ypos[a[0]] for a in ARMS])
194
+ if i == 0:
195
+ ax.set_yticklabels([a[2] for a in ARMS], fontsize=style.FS - 1)
196
+ else:
197
+ ax.set_yticklabels([])
198
+ ax.tick_params(axis="y", length=0)
199
+ ax.spines["left"].set_visible(False)
200
+ ax.set_xlabel(xlabel, labelpad=3)
201
+ # dataset headers (group labels, not figure titles)
202
+ im_n = int(acc[(acc["dataset"] == "immicro") & (acc["call"] == "pooled")]["n_donors"].iloc[0])
203
+ im_n0 = int(acc[(acc["dataset"] == "immicro") & (acc["call"] == "fold0")]["n_donors"].iloc[0])
204
+ se = acc[(acc["dataset"] == "ye2026_sepsis") & (acc["call"] == "pooled")].iloc[0]
205
+ se_n0 = int(acc[(acc["dataset"] == "ye2026_sepsis") & (acc["call"] == "fold0")]["n_donors"].iloc[0])
206
+ hy = (top_y + top_h + 0.12) / H
207
+ fig.text((xs[0] + (xs[1] + pw)) / 2 / W, hy, f"ImMicro, healthy (n {im_n})", ha="center", va="bottom",
208
+ fontsize=style.FS, color=style.INK)
209
+ fig.text((xs[2] + (xs[4] + pw)) / 2 / W, hy,
210
+ f"Sepsis {int(se['n_case'])} vs control {int(se['n_control'])} (n {int(se['n_donors'])})",
211
+ ha="center", va="bottom", fontsize=style.FS, color=style.INK)
212
+ for xa, xb in ((xs[0], xs[1] + pw), (xs[2], xs[4] + pw)):
213
+ fig.add_artist(Line2D([xa / W, xb / W], [hy - 0.005, hy - 0.005], color=style.GREY, lw=0.8))
214
+
215
+ # ------------------------------------------------------------------ compute row
216
+ cy, ch = 0.45, 1.0
217
+ carms = COMPUTE_ARMS
218
+ cpos = {a[0]: len(carms) - 1 - i for i, a in enumerate(carms)}
219
+ bx = [x0, x0 + 2.75]
220
+ bw = [2.15, 2.0]
221
+ # trainable params (log)
222
+ ax = ax_in(bx[0], cy, bw[0], ch)
223
+ for arm, _, label, col in carms:
224
+ n = int(comp.loc[comp["arm"] == arm, "n_trainable"].iloc[0])
225
+ ax.barh(cpos[arm], n / 1e6, height=0.62, color=col, lw=0)
226
+ ax.text(n / 1e6 * 1.12, cpos[arm], f"{n / 1e6:.1f} M", va="center", ha="left", fontsize=style.FS - 2)
227
+ ax.set_xscale("log")
228
+ ax.set_xlim(0.5, 400)
229
+ ax.set_xticks([1, 10, 100])
230
+ ax.set_xticklabels(["1 M", "10 M", "100 M"])
231
+ ax.minorticks_off()
232
+ ax.set_yticks([cpos[a[0]] for a in carms])
233
+ ax.set_yticklabels([a[2] for a in carms], fontsize=style.FS - 1)
234
+ ax.tick_params(axis="y", length=0)
235
+ ax.spines["left"].set_visible(False)
236
+ ax.set_ylim(-0.6, len(carms) - 0.4)
237
+ ax.set_xlabel("trainable params (log)", labelpad=3)
238
+ # wall-clock ms per training step, median over all runs of both cohorts
239
+ ax = ax_in(bx[1], cy, bw[1], ch)
240
+ both = comp[comp["dataset"] == "both"].set_index("arm")
241
+ for arm, _, label, col in carms:
242
+ s = both.loc[arm]
243
+ v = 1000.0 * s["sec_per_step_median"]
244
+ ax.barh(cpos[arm], v, height=0.62, color=col, lw=0)
245
+ txt = f"{v:.0f} ms" if s["n_runs"] > 2 else f"{v:.0f} ms (fold 0)"
246
+ ax.text(v + 1.2, cpos[arm], txt, va="center", ha="left", fontsize=style.FS - 2)
247
+ ax.set_xlim(0, 80)
248
+ ax.set_xticks([0, 25, 50])
249
+ ax.set_yticks([cpos[a[0]] for a in carms])
250
+ ax.set_yticklabels([])
251
+ ax.tick_params(axis="y", length=0)
252
+ ax.spines["left"].set_visible(False)
253
+ ax.set_ylim(-0.6, len(carms) - 0.4)
254
+ ax.set_xlabel("wall ms / step", labelpad=3)
255
+
256
+ # legend for the two scoring calls (bottom right)
257
+ lx = (bx[1] + bw[1] + 0.75) / W
258
+ handles = [Line2D([], [], marker="o", ms=9, mfc=style.INK, mec=style.INK, ls="none",
259
+ label=f"5-fold pooled (n {im_n} / {int(se['n_donors'])})"),
260
+ Line2D([], [], marker="D", ms=7.5, mfc="white", mec=style.INK, mew=1.8, ls="none",
261
+ label=f"fold-0 pilot (n {im_n0} / {se_n0})")]
262
+ fig.legend(handles=handles, loc="lower left", bbox_to_anchor=(lx, (cy + 0.42) / H), frameon=False,
263
+ fontsize=style.FS - 2, handletextpad=0.4, labelspacing=0.5)
264
+ fig.text(lx + 0.004, (cy - 0.02) / H,
265
+ "compare same marker only\ncond.-encoder-only: fold 0 only\nlogFC r: pooled only",
266
+ ha="left", va="bottom", fontsize=style.FS - 3, color="#4D4D4D", linespacing=1.3)
267
+
268
+ style.save(fig, "sec07_ft_modes", FIGDIR)
269
+
270
+ # print the numbers used on the slide
271
+ print(f"trainable full {n_full} lora {n_lora} ratio {ratio:.2f}; per-step full/LoRA {step_ratio:.2f}")
272
+ print(comp[["dataset", "label", "n_runs", "folds", "lr", "n_trainable", "wall_min_median", "wall_min_min",
273
+ "wall_min_max", "steps_run_min", "steps_run_max", "sec_per_step_median"]]
274
+ .round(4).to_string(index=False))
275
+ print(acc[["dataset", "call", "label", "n_donors", "comp_l1", "coverage", "precision", "logfc_r",
276
+ "n_case", "n_control"]].round(3).to_string(index=False))
277
+ print(wil.to_string(index=False))
278
+
279
+
280
+ if __name__ == "__main__":
281
+ main()
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec07_k_aug.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Section 7, slide (b): K diversification does not help LoRA fine-tuning.
2
+
3
+ Arms (5-fold cross-fitted, pooled scoring, one call per dataset):
4
+ plain LoRA (K = 1000) real_lora__raw
5
+ LoRA, multi-K real bulk (K 250-4000) lora_multik__raw
6
+ plain LoRA (K 1000) + half-batch recipes lora_recipe__raw (no multi-K; asserted from RUN.json)
7
+ Metrics: composition L1 (paired Wilcoxon over donors vs plain LoRA, uncorrected), coverage, sepsis-vs-control logFC r
8
+ (mean of T/B/Mono/NK, mean_cp10k statistic). Inner-validation loss differences come from RUN.json.
9
+ Every number is read from the files below. CPU only.
10
+ """
11
+ import json
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+ from scipy.stats import wilcoxon
18
+
19
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
20
+ "2026-09-30--paper-summary--r00")
21
+ sys.path.insert(0, str(DECK / "tools"))
22
+ import style # noqa: E402
23
+ import matplotlib.pyplot as plt # noqa: E402
24
+
25
+ PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
26
+ "paired_finetune_intradataset_20260927")
27
+ FIGDIR, DATADIR = DECK / "figures", DECK / "data"
28
+ DATASETS = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis"}
29
+ CELLTYPES = ["T cell", "B cell", "Monocyte", "NK cell"]
30
+ ARMS = [ # score arm, run dir, label, colour
31
+ ("real_lora__raw", "real_lora", "plain LoRA, K 1000", style.ARM["lora"]),
32
+ ("lora_multik__raw", "lora_multik", "LoRA, multi-K 250–4000", "#5E5E5E"),
33
+ ("lora_recipe__raw", "lora_recipe", "LoRA + ½-batch recipes", "#BDBDBD"),
34
+ ]
35
+ # expected RUN.json "augmentation" per run dir (checked for every fold of both cohorts)
36
+ AUG = {"real_lora": None,
37
+ "lora_multik": {"multi_k": [250, 500, 1000, 2000, 4000], "recipe_frac": 0.0},
38
+ "lora_recipe": {"multi_k": [], "recipe_frac": 0.5}}
39
+ BASE = "real_lora__raw"
40
+
41
+
42
+ def main():
43
+ rows, wil, loss = [], [], []
44
+ for ds in DATASETS:
45
+ root = PLAN / "scores" / ds / "pooled"
46
+ summ = json.loads((root / "summary.json").read_text())
47
+ per = pd.read_csv(root / "per_donor.csv")
48
+ con = pd.read_csv(root / "contrast.csv") if (root / "contrast.csv").exists() else None
49
+ piv = per.pivot(index="donor", columns="arm", values="comp_l1")
50
+ for arm, run, label, _ in ARMS:
51
+ h = summ["headline"][arm]
52
+ r = {"dataset": ds, "arm": arm, "label": label, "n_donors": summ["n_donors"],
53
+ "comp_l1": h["comp_l1"], "coverage": h["coverage"], "precision": h["precision"],
54
+ "logfc_r": np.nan, "source_summary": str(root / "summary.json")}
55
+ # composition L1 from per-donor rows must match the headline
56
+ assert abs(per.loc[per["arm"] == arm, "comp_l1"].mean() - h["comp_l1"]) < 1e-9
57
+ if con is not None:
58
+ c = con[(con["arm"] == arm) & (con["statistic"] == "mean_cp10k") & con["celltype"].isin(CELLTYPES)]
59
+ assert set(c["celltype"]) == set(CELLTYPES)
60
+ r["logfc_r"] = float(c["r_generated"].mean())
61
+ assert abs(r["logfc_r"] - h["contrast_mean_cp10k_r_gen"]) < 1e-9
62
+ r["r_broadcast"] = float(c["r_broadcast"].mean())
63
+ r["n_case"] = int(c["n_case_donors_obs"].iloc[0])
64
+ r["n_control"] = int(c["n_control_donors_obs"].iloc[0])
65
+ r["source_contrast"] = str(root / "contrast.csv")
66
+ rows.append(r)
67
+ if arm != BASE:
68
+ x = (piv[arm] - piv[BASE]).dropna()
69
+ wil.append({"dataset": ds, "arm": arm, "comparison": f"{arm} - {BASE} comp_l1",
70
+ "mean_diff": float(x.mean()), "wilcoxon_p": float(wilcoxon(x).pvalue),
71
+ "n": int(len(x)), "source": str(root / "per_donor.csv")})
72
+ for f in sorted((PLAN / "runs" / ds).glob(f"fold[0-9]/{run}/RUN.json")):
73
+ d = json.loads(f.read_text())
74
+ a, e = d.get("augmentation"), AUG[run]
75
+ assert (a is None) if e is None else all(a[k] == v for k, v in e.items()), (f, a)
76
+ loss.append({"dataset": ds, "arm": arm, "fold": d["fold"],
77
+ "selected_inner_val_loss": d["selected_inner_val_loss"],
78
+ "selected_step": d["selected_step"], "wall_seconds": d["wall_seconds"],
79
+ "n_trainable": d["trainable"]["n_trainable"], "run_json": str(f)})
80
+ df, wil, loss = pd.DataFrame(rows), pd.DataFrame(wil), pd.DataFrame(loss)
81
+ lp = loss.pivot_table(index=["dataset", "fold"], columns="arm", values="selected_inner_val_loss")
82
+ dloss = pd.DataFrame({a: lp[a] - lp[BASE] for a, *_ in ARMS if a != BASE})
83
+ max_abs_dloss = float(dloss.abs().to_numpy().max())
84
+
85
+ # cross-check against the paper figure's source data (same arithmetic, independent read)
86
+ sd = pd.read_csv(PLAN / "figures/source_data/figS2_k_augmentation.csv")
87
+ sdw = sd[sd["kind"] == "wilcoxon_p_vs_plain_lora"]
88
+ key = {"lora_multik": "lora_multik__raw", "lora_recipe": "lora_recipe__raw"}
89
+ for _, s in sdw.iterrows():
90
+ mine = wil[(wil["dataset"] == s["dataset"]) & (wil["arm"] == key[s["series"]])]["wilcoxon_p"].iloc[0]
91
+ assert abs(mine - s["value"]) < 1e-5, (s["dataset"], s["series"], mine, s["value"])
92
+
93
+ df.to_csv(DATADIR / "sec07_k_aug.csv", index=False)
94
+ wil.to_csv(DATADIR / "sec07_k_aug_wilcoxon.csv", index=False)
95
+ loss.to_csv(DATADIR / "sec07_k_aug_inner_val_runs.csv", index=False)
96
+ dloss.reset_index().to_csv(DATADIR / "sec07_k_aug_inner_val_delta.csv", index=False)
97
+
98
+ # ------------------------------------------------------------------ figure
99
+ W, H = style.TALL
100
+ fig = plt.figure(figsize=(W, H))
101
+
102
+ def ax_in(x, y, w, h):
103
+ return fig.add_axes([x / W, y / H, w / W, h / H])
104
+
105
+ x0, pw, gap = 2.3, 1.55, 0.42
106
+ row_y = {"immicro": 3.3, "ye2026_sepsis": 0.62}
107
+ rh = 1.55
108
+ cols = [("comp_l1", "L1 ↓", 0.62, [0, 0.25, 0.5]),
109
+ ("coverage", "coverage ↑", 1.3, [0, 0.5, 1.0]),
110
+ ("logfc_r", "logFC r ↑", 0.78, [0, 0.3, 0.6])]
111
+ ypos = {a[0]: len(ARMS) - 1 - i for i, a in enumerate(ARMS)}
112
+ for ds, dname in DATASETS.items():
113
+ sub = df[df["dataset"] == ds].set_index("arm")
114
+ n = int(sub["n_donors"].iloc[0])
115
+ head = f"{dname}, healthy (n {n})" if ds == "immicro" else \
116
+ f"{dname} {int(sub['n_case'].iloc[0])} vs control {int(sub['n_control'].iloc[0])} (n {n})"
117
+ fig.text(x0 / W, (row_y[ds] + rh + 0.14) / H, head, ha="left", va="bottom", fontsize=style.FS,
118
+ color=style.INK)
119
+ for j, (met, xlabel, xmax, ticks) in enumerate(cols):
120
+ ax = ax_in(x0 + j * (pw + gap), row_y[ds], pw, rh)
121
+ if met == "logfc_r" and ds == "immicro":
122
+ ax.axis("off")
123
+ ax.text(0.0, 0.5, "no case–control\ncontrast", transform=ax.transAxes, ha="left",
124
+ va="center", fontsize=style.FS - 2, color=style.GREY)
125
+ continue
126
+ for arm, _, label, col in ARMS:
127
+ v = float(sub.loc[arm, met])
128
+ ax.barh(ypos[arm], v, height=0.66, color=col, lw=0)
129
+ txt = f"{v:.3f}" if met == "comp_l1" else f"{v:.2f}"
130
+ if met == "comp_l1" and arm != BASE:
131
+ p = wil[(wil["dataset"] == ds) & (wil["arm"] == arm)]["wilcoxon_p"].iloc[0]
132
+ txt += f" p {p:.2f}"
133
+ ax.text(v + xmax * 0.02, ypos[arm], txt, va="center", ha="left", fontsize=style.FS - 3)
134
+ ax.set_xlim(0, xmax)
135
+ ax.set_xticks(ticks)
136
+ ax.set_xticklabels([f"{t:g}" for t in ticks])
137
+ ax.set_ylim(-0.6, len(ARMS) - 0.4)
138
+ ax.set_yticks([ypos[a[0]] for a in ARMS])
139
+ ax.set_yticklabels([a[2] for a in ARMS] if j == 0 else [], fontsize=style.FS - 2)
140
+ ax.tick_params(axis="y", length=0)
141
+ ax.spines["left"].set_visible(False)
142
+ ax.set_xlabel(xlabel, labelpad=2)
143
+
144
+ style.save(fig, "sec07_k_aug", FIGDIR)
145
+
146
+ print(df[["dataset", "label", "n_donors", "comp_l1", "coverage", "precision", "logfc_r"]].round(4)
147
+ .to_string(index=False))
148
+ print(wil[["dataset", "arm", "mean_diff", "wilcoxon_p", "n"]].to_string(index=False))
149
+ print(f"max |inner-val loss - plain LoRA| over folds/arms/datasets: {max_abs_dloss:.6f}")
150
+ print(dloss.round(6).to_string())
151
+
152
+
153
+ if __name__ == "__main__":
154
+ main()
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec08_pairs_needed.py ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Section 8 of the 2026-09-30 paper-summary deck: how many bulk-sc pairs LoRA needs (learning curve).
2
+
3
+ CPU only. Reads the pooled 5-fold scoring calls of the paired fine-tune plan and the per-fold RUN.json files,
4
+ then draws two slide figures:
5
+ figures/sec08_pairs_realism.{png,pdf} FULL: composition L1, coverage, selected step x (ImMicro, sepsis)
6
+ figures/sec08_pairs_signal.{png,pdf} TALL: ImMicro NK fraction r, sepsis logFC r, sepsis top-50 DEG
7
+ Every plotted/quoted number is read from a score file here and written with its source to data/sec08_*.csv.
8
+ Model: final f01 6k 1x epoch-16 checkpoint + LoRA (checked against every RUN.json).
9
+ x axis: "cal" = zero-shot + gene calibration whose alpha is fitted on ALL paired fold donors (train + inner-val,
10
+ PREPARE.json), so it is not a 0-pair point; LoRA n = training pairs, and every LoRA run also early-stops on
11
+ 7-8 paired inner-val donors (RUN.json inner_val_rows). Cap-limited = ran to max_steps before the patience window
12
+ closed; its late inner-val loss drop is read from history.json.
13
+ """
14
+ import json
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import pandas as pd
20
+
21
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
22
+ "2026-09-30--paper-summary--r00")
23
+ sys.path.insert(0, str(DECK / "tools"))
24
+ import style # noqa: E402
25
+ import matplotlib.pyplot as plt # noqa: E402
26
+ from matplotlib.lines import Line2D # noqa: E402
27
+
28
+ PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
29
+ "paired_finetune_intradataset_20260927")
30
+ FINAL_CKPT = ("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/runs/"
31
+ "f01_6k_1x_seed20260627/checkpoint_epoch_016.pt")
32
+ FIGDIR, DATADIR = DECK / "figures", DECK / "data"
33
+ FIGDIR.mkdir(exist_ok=True)
34
+ DATADIR.mkdir(exist_ok=True)
35
+
36
+ DSETS = ["immicro", "ye2026_sepsis"]
37
+ DS_LABEL = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis"}
38
+ LC_N = [5, 10, 20, 40]
39
+ LORA_ARMS = [f"lora_n{n}__raw" for n in LC_N] + ["real_lora__raw"]
40
+ RUN_ARMS = [f"lora_n{n}" for n in LC_N] + ["real_lora"]
41
+ # x=0 is NOT pair-free: the zs__cal gene multiplier alpha is fitted on every paired fold donor
42
+ # (train + inner-val; tools/prepare_dataset.py `fit = fold != f`), so it is labelled "cal", not "0".
43
+ X_LAB = ["cal", "5", "10", "20", "40", "all"]
44
+ X_POS = [0.0, 1.3, 2.3, 3.3, 4.3, 5.3] # small gap after the calibrated zero-shot point (different arm)
45
+ CELLTYPES = ["T cell", "B cell", "Monocyte", "NK cell"]
46
+ DEG_TYPES = ["T cell", "B cell", "Monocyte", "NK cell", "DC"]
47
+ RAW_ARMS = LORA_ARMS + ["zs__raw", "real_full__raw", "pseudo_full__raw"] # all conditioned on raw real bulk
48
+
49
+ REF = { # reference-line styles; pseudo/broadcast copied from sec09 REFSTYLE so the deck is consistent
50
+ "pseudo": dict(ls=(0, (4, 2)), color=style.ARM["pseudo"], lw=1.6, label="Zero-shot from sc pseudobulk"),
51
+ "broadcast": dict(ls=(0, (1, 1.2)), color=style.ARM["broadcast"], lw=2.4, label="Real-bulk broadcast"),
52
+ "null": dict(ls=(0, (6, 2, 1.5, 2)), color=style.GREY, lw=1.4, label="Cohort-mean null"),
53
+ }
54
+ LEG_CAL = "cal = zero-shot + calibration (α from all fold pairs)"
55
+
56
+
57
+ def xlabel(st):
58
+ """x-axis label; the inner-val range is read from the RUN.json files."""
59
+ return f"LoRA training pairs (each run +{rng_txt(st.n_inner_val)} inner-val pairs for early stopping)"
60
+
61
+
62
+ def close(a, b, tol=1e-6):
63
+ return abs(float(a) - float(b)) <= tol
64
+
65
+
66
+ class Call:
67
+ """One pooled score_ft.py scoring call."""
68
+
69
+ def __init__(self, path: Path):
70
+ self.path = path
71
+ self.summary = json.loads((path / "summary.json").read_text())
72
+ self.contrast = pd.read_csv(path / "contrast.csv") if (path / "contrast.csv").exists() else None
73
+ self.per_donor = pd.read_csv(path / "per_donor.csv")
74
+ self.src_summary = str(path / "summary.json")
75
+ self.src_contrast = str(path / "contrast.csv")
76
+ self.src_per_donor = str(path / "per_donor.csv")
77
+
78
+ def head(self, arm, key):
79
+ return float(self.summary["headline"][arm][key])
80
+
81
+ def contrast_r(self, arm, col="r_generated"):
82
+ c = self.contrast
83
+ c = c[(c.arm == arm) & (c.statistic == "mean_cp10k") & (c.celltype.isin(CELLTYPES))]
84
+ assert set(c.celltype) == set(CELLTYPES), (self.path, arm)
85
+ return float(c[col].mean())
86
+
87
+ def deg(self, arm, col="top50_overlap"):
88
+ d = self.contrast
89
+ d = d[(d.arm == arm) & (d.statistic == "welch_top50_deg")]
90
+ assert len(d) == 5, (self.path, arm, len(d)) # T/B/Mono/NK/DC
91
+ return float(d[col].sum())
92
+
93
+ def deg_type(self, arm, ct, col="top50_overlap"):
94
+ d = self.contrast
95
+ d = d[(d.arm == arm) & (d.statistic == "welch_top50_deg") & (d.celltype == ct)]
96
+ assert len(d) == 1, (self.path, arm, ct, len(d))
97
+ return float(d[col].iloc[0])
98
+
99
+ def frac_r(self, arm, ct):
100
+ d = self.per_donor[self.per_donor.arm == arm]
101
+ return float(np.corrcoef(d[f"gen_{ct}"].astype(float), d[f"obs_{ct}"].astype(float))[0, 1])
102
+
103
+
104
+ def load():
105
+ calls = {ds: Call(PLAN / "scores" / ds / "pooled") for ds in DSETS}
106
+ deg_call = Call(PLAN / "scores" / "ye2026_sepsis" / "pooled_deg")
107
+ for ds, c in calls.items():
108
+ for a in LORA_ARMS + ["zs__cal", "zs__pseudo"]:
109
+ assert a in c.summary["arms"], (ds, a)
110
+ assert c.summary["per_arm"][a].get("receipt_verified", True) is not False, (ds, a)
111
+ # headline contrast means equal the per-type mean of contrast.csv
112
+ se = calls["ye2026_sepsis"]
113
+ for a in LORA_ARMS + ["zs__cal", "zs__pseudo"]:
114
+ assert close(se.contrast_r(a), se.head(a, "contrast_mean_cp10k_r_gen"), 1e-9), a
115
+ assert close(deg_call.deg(a), deg_call.head(a, "deg_top50_sum"), 1e-9), a
116
+ # broadcast is the same for every arm conditioned on raw real bulk
117
+ bc = {a: se.contrast_r(a, "r_broadcast") for a in RAW_ARMS}
118
+ assert max(bc.values()) - min(bc.values()) < 1e-12, bc
119
+ bcd = {a: deg_call.deg(a, "top50_overlap_broadcast") for a in RAW_ARMS}
120
+ assert len(set(bcd.values())) == 1, bcd
121
+ assert close(bcd["real_lora__raw"], deg_call.head("real_lora__raw", "deg_top50_sum_broadcast"), 1e-9)
122
+ # non-DEG metrics agree between the two sepsis scoring calls (k-NN ties allow 1e-3)
123
+ for a in LORA_ARMS + ["zs__cal"]:
124
+ for k in ("comp_l1", "coverage"):
125
+ assert abs(se.head(a, k) - deg_call.head(a, k)) <= 1e-3, (a, k)
126
+ return calls, deg_call
127
+
128
+
129
+ def load_steps():
130
+ rows = []
131
+ for ds in DSETS:
132
+ for k in range(5):
133
+ for arm in RUN_ARMS:
134
+ p = PLAN / "runs" / ds / f"fold{k}" / arm / "RUN.json"
135
+ r = json.loads(p.read_text())
136
+ assert r["source_checkpoint"] == FINAL_CKPT, (p, r["source_checkpoint"])
137
+ assert r["mode"] == "lora", p
138
+ assert r["inner_val_rows"], p # every LoRA run early-stops on paired inner-val donors
139
+ hist = json.loads((p.parent / "history.json").read_text())
140
+ h = {int(e["step"]): float(e["inner_val_loss"]) for e in hist}
141
+ # cap-limited = ran to max_steps without the patience window closing
142
+ cap_limited = (r["steps_run"] >= r["max_steps"]
143
+ and r["steps_run"] - r["selected_step"] < r["patience"] * r["eval_every"])
144
+ last = max(h)
145
+ win = r["patience"] * r["eval_every"] # last patience window (2,000 steps)
146
+ drop_total = h[0] - h[last]
147
+ drop_last = h[last - win] - h[last]
148
+ rows.append({"dataset": ds, "fold": k, "arm": arm, "n_train": len(r["train_rows"]),
149
+ "n_inner_val": len(r["inner_val_rows"]), "selected_step": r["selected_step"],
150
+ "max_steps": r["max_steps"], "steps_run": r["steps_run"],
151
+ "patience_steps": win, "cap_limited": bool(cap_limited),
152
+ "val_loss_step0": h[0], "val_loss_last": h[last],
153
+ "val_loss_last_window_drop_frac": drop_last / drop_total,
154
+ "wall_seconds": r.get("wall_seconds"), "source": str(p),
155
+ "history": str(p.parent / "history.json")})
156
+ st = pd.DataFrame(rows)
157
+ # nested subsets: n_train equals the arm size for lora_n*
158
+ for n in LC_N:
159
+ assert (st[st.arm == f"lora_n{n}"].n_train == n).all(), n
160
+ return st
161
+
162
+
163
+ def load_alpha_fit():
164
+ """Number of paired donors the zs__cal alpha is fitted on per fold (train + inner-val, PREPARE.json)."""
165
+ out = {}
166
+ for ds in DSETS:
167
+ p = PLAN / "data" / ds / "PREPARE.json"
168
+ fs = json.loads(p.read_text())["fold_sizes"]
169
+ out[ds] = dict(n=[int(v["train"]) + int(v["inner_val"]) for v in fs.values()],
170
+ test=[int(v["test"]) for v in fs.values()], source=str(p))
171
+ return out
172
+
173
+
174
+ def load_fewshot():
175
+ """Sec. 9 few-pair call: alpha from the same 5 pairs, fixed 3k steps, no inner-val (mean over 5 draws)."""
176
+ out = {}
177
+ for ds in DSETS:
178
+ p = PLAN / "scores" / ds / "fewshot_n5" / "aggregate.json"
179
+ a = json.loads(p.read_text())["arms"]
180
+ out[ds] = dict(zs_cal=float(a["zs_cal"]["coverage"][0]), lora5=float(a["lora5"]["coverage"][0]),
181
+ source=str(p))
182
+ return out
183
+
184
+
185
+ def rng_txt(v):
186
+ v = sorted(int(x) for x in v)
187
+ return f"{v[0]}" if v[0] == v[-1] else f"{v[0]}–{v[-1]}"
188
+
189
+
190
+ def curve(ax, v0, vl, refs, rows, panel, ds, src0, srcl, ylim0=None):
191
+ """Zero-shot calibrated point at x=0, LoRA curve at 5..all, reference lines."""
192
+ ax.scatter([X_POS[0]], [v0], s=70, color=style.ARM["zs_cal"], edgecolor=style.INK, lw=0.6, zorder=5)
193
+ ax.plot(X_POS[1:], vl, color=style.ARM["lora"], lw=2.0, zorder=3)
194
+ ax.scatter(X_POS[1:], vl, s=70, color=style.ARM["lora"], edgecolor=style.INK, lw=0.6, zorder=5)
195
+ rows.append(dict(panel=panel, dataset=ds, series="zs_cal", pairs="cal", value=v0, source=src0))
196
+ for lab, v, s in zip(X_LAB[1:], vl, srcl):
197
+ rows.append(dict(panel=panel, dataset=ds, series="lora", pairs=lab, value=v, source=s))
198
+ lo, hi = min([v0] + list(vl)), max([v0] + list(vl))
199
+ for key, val, src in refs:
200
+ r = REF[key]
201
+ ax.axhline(val, ls=r["ls"], color=r["color"], lw=r["lw"], zorder=2)
202
+ rows.append(dict(panel=panel, dataset=ds, series=f"ref_{key}", pairs="", value=val, source=src))
203
+ lo, hi = min(lo, val), max(hi, val)
204
+ pad = (hi - lo) * 0.15
205
+ ax.set_ylim(ylim0 if ylim0 is not None else lo - pad, hi + pad)
206
+ ax.set_xlim(-0.5, X_POS[-1] + 0.5)
207
+ ax.set_xticks(X_POS)
208
+ ax.set_xticklabels(X_LAB)
209
+
210
+
211
+ def fig_realism(calls, st, alpha_fit, rows, steprows):
212
+ fig, axs = plt.subplots(2, 3, figsize=style.FULL,
213
+ gridspec_kw=dict(left=0.168, right=0.99, top=0.83, bottom=0.12,
214
+ hspace=0.36, wspace=0.30))
215
+ heads = ["Composition L1 ↓", "Coverage ↑", "Selected step (×1,000)"]
216
+ for ri, ds in enumerate(DSETS):
217
+ c = calls[ds]
218
+ for ci, key in enumerate(["comp_l1", "coverage"]):
219
+ ax = axs[ri, ci]
220
+ refs = [("pseudo", c.head("zs__pseudo", key), c.src_summary)]
221
+ if key == "comp_l1":
222
+ refs.append(("null", c.head("real_lora__raw", "comp_l1_obs_loo_null"), c.src_summary))
223
+ curve(ax, c.head("zs__cal", key), [c.head(a, key) for a in LORA_ARMS], refs, rows,
224
+ f"{key}", ds, c.src_summary, [c.src_summary] * 5)
225
+ # selected early-stopping step per fold
226
+ ax = axs[ri, 2]
227
+ s = st[st.dataset == ds]
228
+ for xi, arm in zip(X_POS[1:], RUN_ARMS):
229
+ f = s[s.arm == arm].sort_values("fold")
230
+ v = f.selected_step.astype(float).values / 1000
231
+ jit = np.linspace(-0.22, 0.22, len(v))
232
+ ax.scatter(xi + jit, v, s=36, color=style.ARM["lora"], edgecolor=style.INK, lw=0.5, zorder=4)
233
+ med = float(np.median(v))
234
+ ax.plot([xi - 0.36, xi + 0.36], [med, med], color=style.INK, lw=2.0, zorder=5)
235
+ steprows.append(dict(dataset=ds, arm=arm, pairs=X_LAB[X_POS.index(xi)], median_step=med * 1000,
236
+ min_step=v.min() * 1000, max_step=v.max() * 1000,
237
+ n_cap_limited=int(f.cap_limited.sum()),
238
+ max_last_window_drop_frac=(float(f[f.cap_limited].val_loss_last_window_drop_frac.max())
239
+ if f.cap_limited.any() else np.nan),
240
+ n_train=rng_txt(f.n_train), n_inner_val=rng_txt(f.n_inner_val),
241
+ source=";".join(f.source)))
242
+ cap = float(s.max_steps.max()) / 1000
243
+ ax.axhline(cap, color=style.GREY, lw=1.0, ls=(0, (2, 2)), zorder=1)
244
+ ax.text(X_POS[0] - 0.4, cap + 0.6, f"cap {cap:g}k", color=style.GREY, fontsize=12, va="bottom")
245
+ ax.text(X_POS[0], cap * 0.45, "no training", color=style.GREY, fontsize=12, ha="center",
246
+ va="center", rotation=90)
247
+ ax.set_ylim(0, cap * 1.18)
248
+ ax.set_xlim(-0.5, X_POS[-1] + 0.5)
249
+ ax.set_xticks(X_POS)
250
+ ax.set_xticklabels(X_LAB)
251
+ n_all = rng_txt(s[s.arm == "real_lora"].n_train)
252
+ n_iv = rng_txt(s.n_inner_val)
253
+ n_cal = rng_txt(alpha_fit[ds]["n"])
254
+ n_scored = int(c.summary["n_donors"])
255
+ assert n_scored == sum(alpha_fit[ds]["test"]), (ds, n_scored, alpha_fit[ds]["test"])
256
+ ymid = (axs[ri, 0].get_position().y0 + axs[ri, 0].get_position().y1) / 2
257
+ fig.text(0.005, ymid + 0.075, DS_LABEL[ds], fontsize=15, fontweight="bold", va="bottom", ha="left")
258
+ fig.text(0.005, ymid + 0.065, f"{n_scored} donors\nall = {n_all} pairs\ninner-val = {n_iv}\ncal α = {n_cal}",
259
+ fontsize=12.5, va="top", ha="left", linespacing=1.35)
260
+ rows.append(dict(panel="meta", dataset=ds, series="n_scored_donors", pairs="", value=n_scored,
261
+ source=c.src_summary))
262
+ rows.append(dict(panel="meta", dataset=ds, series="n_pairs_all", pairs="all", value=n_all,
263
+ source="RUN.json train_rows: " + ";".join(s[s.arm == "real_lora"].source)))
264
+ rows.append(dict(panel="meta", dataset=ds, series="n_inner_val", pairs="", value=n_iv,
265
+ source="RUN.json inner_val_rows (all LoRA arms, 5 folds)"))
266
+ rows.append(dict(panel="meta", dataset=ds, series="n_alpha_fit_pairs", pairs="cal", value=n_cal,
267
+ source=alpha_fit[ds]["source"] + " fold_sizes train+inner_val"))
268
+ for ci, h in enumerate(heads):
269
+ axs[0, ci].set_title(h, fontsize=14, pad=8)
270
+ x0, x1 = axs[1, 0].get_position().x0, axs[1, 2].get_position().x1
271
+ fig.text((x0 + x1) / 2, 0.005, xlabel(st), ha="center", va="bottom", fontsize=14)
272
+ handles = [
273
+ Line2D([0], [0], marker="o", color=style.ARM["zs_cal"], lw=0, markeredgecolor=style.INK, markersize=8,
274
+ label=LEG_CAL),
275
+ Line2D([0], [0], marker="o", color=style.ARM["lora"], lw=2.0, markeredgecolor=style.INK, markersize=8,
276
+ label="LoRA fine-tune (dots in step panel = folds)"),
277
+ Line2D([0], [0], color=style.INK, lw=2.0, label="Median of 5 folds"),
278
+ Line2D([0], [0], ls=REF["pseudo"]["ls"], color=REF["pseudo"]["color"], lw=REF["pseudo"]["lw"],
279
+ label=REF["pseudo"]["label"]),
280
+ Line2D([0], [0], ls=REF["null"]["ls"], color=REF["null"]["color"], lw=REF["null"]["lw"],
281
+ label=REF["null"]["label"]),
282
+ ]
283
+ fig.legend(handles=handles, loc="upper left", bbox_to_anchor=(0.005, 1.0), ncol=3, frameon=False,
284
+ fontsize=12, handlelength=2.4, columnspacing=1.6, labelspacing=0.4, borderaxespad=0.0)
285
+ style.save(fig, "sec08_pairs_realism", FIGDIR)
286
+
287
+
288
+ def fig_signal(calls, deg_call, st, rows):
289
+ fig, axs = plt.subplots(1, 3, figsize=style.TALL,
290
+ gridspec_kw=dict(left=0.085, right=0.99, top=0.79, bottom=0.115, wspace=0.42))
291
+ im, se = calls["immicro"], calls["ye2026_sepsis"]
292
+ # a: ImMicro across-donor NK fraction r
293
+ curve(axs[0], im.frac_r("zs__cal", "NK cell"), [im.frac_r(a, "NK cell") for a in LORA_ARMS],
294
+ [("pseudo", im.frac_r("zs__pseudo", "NK cell"), im.src_per_donor)], rows, "nk_fraction_r", "immicro",
295
+ im.src_per_donor, [im.src_per_donor] * 5)
296
+ # other cell types, recorded for the footnote
297
+ for ct in ["T cell", "B cell", "Monocyte"]:
298
+ for a, lab in zip(["zs__cal"] + LORA_ARMS, X_LAB):
299
+ rows.append(dict(panel="other_fraction_r", dataset="immicro", series=ct, pairs=lab,
300
+ value=im.frac_r(a, ct), source=im.src_per_donor))
301
+ # b: sepsis disease logFC r (mean of T/B/Mono/NK, mean_cp10k)
302
+ curve(axs[1], se.contrast_r("zs__cal"), [se.contrast_r(a) for a in LORA_ARMS],
303
+ [("pseudo", se.contrast_r("zs__pseudo"), se.src_contrast),
304
+ ("broadcast", se.contrast_r("real_lora__raw", "r_broadcast"), se.src_contrast)],
305
+ rows, "logfc_r", "ye2026_sepsis", se.src_contrast, [se.src_contrast] * 5)
306
+ # c: sepsis top-50 DEG (Welch, sum over T/B/Mono/NK/DC)
307
+ curve(axs[2], deg_call.deg("zs__cal"), [deg_call.deg(a) for a in LORA_ARMS],
308
+ [("pseudo", deg_call.deg("zs__pseudo"), deg_call.src_contrast),
309
+ ("broadcast", deg_call.deg("real_lora__raw", "top50_overlap_broadcast"), deg_call.src_contrast)],
310
+ rows, "top50_deg", "ye2026_sepsis", deg_call.src_contrast, [deg_call.src_contrast] * 5, ylim0=0)
311
+ # top-50 DEG overlap per cell type (footnote: which types carry the gain), incl. broadcast
312
+ for ct in DEG_TYPES:
313
+ for a, lab in zip(["zs__cal"] + LORA_ARMS + ["zs__pseudo"], X_LAB + ["pseudo"]):
314
+ rows.append(dict(panel="top50_deg_by_type", dataset="ye2026_sepsis", series=ct, pairs=lab,
315
+ value=deg_call.deg_type(a, ct), source=deg_call.src_contrast))
316
+ rows.append(dict(panel="top50_deg_by_type", dataset="ye2026_sepsis", series=ct, pairs="broadcast",
317
+ value=deg_call.deg_type("real_lora__raw", ct, "top50_overlap_broadcast"),
318
+ source=deg_call.src_contrast))
319
+ cd = se.summary["contrast_definition"]
320
+ grp = f"Sepsis {cd['n_case_donors']} vs {cd['n_control_donors']}"
321
+ heads = [f"ImMicro, {int(im.summary['n_donors'])} donors\ndonor NK fraction r",
322
+ f"{grp}\ndisease logFC r", f"{grp}\ntop-50 DEG overlap"]
323
+ for ax, h in zip(axs, heads):
324
+ ax.set_title(h, fontsize=14, pad=8, linespacing=1.3)
325
+ x0, x1 = axs[0].get_position().x0, axs[2].get_position().x1
326
+ fig.text((x0 + x1) / 2, 0.005, xlabel(st), ha="center", va="bottom", fontsize=13)
327
+ rows.append(dict(panel="meta", dataset="ye2026_sepsis", series="n_case_vs_control", pairs="",
328
+ value=f"{se.summary['contrast_definition']['n_case_donors']} vs "
329
+ f"{se.summary['contrast_definition']['n_control_donors']}", source=se.src_summary))
330
+ handles = [ # column-wise fill: [cal, pseudo] | [LoRA, broadcast]
331
+ Line2D([0], [0], marker="o", color=style.ARM["zs_cal"], lw=0, markeredgecolor=style.INK, markersize=8,
332
+ label=LEG_CAL),
333
+ Line2D([0], [0], ls=REF["pseudo"]["ls"], color=REF["pseudo"]["color"], lw=REF["pseudo"]["lw"],
334
+ label=REF["pseudo"]["label"]),
335
+ Line2D([0], [0], marker="o", color=style.ARM["lora"], lw=2.0, markeredgecolor=style.INK, markersize=8,
336
+ label="LoRA fine-tune"),
337
+ Line2D([0], [0], ls=REF["broadcast"]["ls"], color=REF["broadcast"]["color"], lw=REF["broadcast"]["lw"],
338
+ label=REF["broadcast"]["label"]),
339
+ ]
340
+ fig.legend(handles=handles, loc="upper left", bbox_to_anchor=(0.005, 1.0), ncol=2, frameon=False,
341
+ fontsize=12, handlelength=2.4, columnspacing=1.2, labelspacing=0.4, borderaxespad=0.0)
342
+ style.save(fig, "sec08_pairs_signal", FIGDIR)
343
+
344
+
345
+ def slide_numbers(calls, deg_call, st, alpha_fit, fewshot):
346
+ """Numbers quoted in the slide keywords/footnote, each with its source file."""
347
+ im, se = calls["immicro"], calls["ye2026_sepsis"]
348
+ out = []
349
+
350
+ def add(key, value, src):
351
+ out.append(dict(key=key, value=value, source=src))
352
+
353
+ for ds, c in calls.items():
354
+ add(f"{ds}.coverage.zs_cal", round(c.head("zs__cal", "coverage"), 3), c.src_summary)
355
+ add(f"{ds}.coverage.lora_n5", round(c.head("lora_n5__raw", "coverage"), 3), c.src_summary)
356
+ add(f"{ds}.coverage.lora_all", round(c.head("real_lora__raw", "coverage"), 3), c.src_summary)
357
+ add(f"{ds}.comp_l1.zs_cal", round(c.head("zs__cal", "comp_l1"), 3), c.src_summary)
358
+ add(f"{ds}.comp_l1.lora_n5", round(c.head("lora_n5__raw", "comp_l1"), 3), c.src_summary)
359
+ add(f"{ds}.comp_l1.lora_all", round(c.head("real_lora__raw", "comp_l1"), 3), c.src_summary)
360
+ add(f"{ds}.comp_l1.zs_pseudo", round(c.head("zs__pseudo", "comp_l1"), 3), c.src_summary)
361
+ add(f"{ds}.comp_l1.null", round(c.head("real_lora__raw", "comp_l1_obs_loo_null"), 3), c.src_summary)
362
+ add(f"{ds}.n_scored_donors", int(c.summary["n_donors"]), c.src_summary)
363
+ # zs__cal alpha is fitted on train + inner-val donors of the fold (prepare_dataset.py: fit = fold != f)
364
+ add(f"{ds}.cal_alpha_fit_pairs", rng_txt(alpha_fit[ds]["n"]),
365
+ alpha_fit[ds]["source"] + " fold_sizes train+inner_val; tools/prepare_dataset.py fit = fold != f")
366
+ # Sec. 9 few-pair call: alpha from the same 5 pairs, fixed 3k steps, no inner-val (within-call comparison)
367
+ add(f"{ds}.fewshot_n5.coverage.zs_cal_same5", round(fewshot[ds]["zs_cal"], 3), fewshot[ds]["source"])
368
+ add(f"{ds}.fewshot_n5.coverage.lora5_fixed3k", round(fewshot[ds]["lora5"], 3), fewshot[ds]["source"])
369
+ s = st[st.dataset == ds]
370
+ add(f"{ds}.selected_step.lora_n5.range", rng_txt(s[s.arm == "lora_n5"].selected_step), "RUN.json: "
371
+ + ";".join(s[s.arm == "lora_n5"].source))
372
+ add(f"{ds}.n_train.all", rng_txt(s[s.arm == "real_lora"].n_train), "RUN.json: "
373
+ + ";".join(s[s.arm == "real_lora"].source))
374
+ add(f"{ds}.n_inner_val", rng_txt(s.n_inner_val), "RUN.json inner_val_rows (all LoRA arms, 5 folds)")
375
+ for arm in RUN_ARMS:
376
+ f = s[s.arm == arm]
377
+ add(f"{ds}.folds_cap_limited.{arm}", f"{int(f.cap_limited.sum())}/{len(f)}",
378
+ "RUN.json steps_run == max_steps and steps_run - selected_step < patience*eval_every: "
379
+ + ";".join(f.source))
380
+ capped = s[s.cap_limited]
381
+ if len(capped):
382
+ add(f"{ds}.cap_limited.max_val_loss_drop_frac_last_2k_steps",
383
+ round(float(capped.val_loss_last_window_drop_frac.max()), 4),
384
+ "history.json inner_val_loss (drop over last patience window / drop from step 0): "
385
+ + ";".join(capped.history))
386
+ for a, lab in zip(["zs__cal"] + LORA_ARMS + ["zs__pseudo"], X_LAB + ["pseudo"]):
387
+ add(f"immicro.nk_fraction_r.{lab}", round(im.frac_r(a, "NK cell"), 2), im.src_per_donor)
388
+ add(f"sepsis.logfc_r.{lab}", round(se.contrast_r(a), 2), se.src_contrast)
389
+ add(f"sepsis.top50_deg.{lab}", int(deg_call.deg(a)), deg_call.src_contrast)
390
+ add("sepsis.logfc_r.broadcast", round(se.contrast_r("real_lora__raw", "r_broadcast"), 2), se.src_contrast)
391
+ add("sepsis.top50_deg.broadcast", int(deg_call.deg("real_lora__raw", "top50_overlap_broadcast")),
392
+ deg_call.src_contrast)
393
+
394
+ def first_sustained(v, thr, strict=True):
395
+ """First LoRA n from which every later n is above (or >=) thr."""
396
+ for i in range(len(v)):
397
+ if all((x > thr) if strict else (x >= thr) for x in v[i:]):
398
+ return X_LAB[1 + i]
399
+ return "never"
400
+ bc_r = se.contrast_r("real_lora__raw", "r_broadcast")
401
+ bc_d = deg_call.deg("real_lora__raw", "top50_overlap_broadcast")
402
+ vr = [se.contrast_r(a) for a in LORA_ARMS]
403
+ vd = [deg_call.deg(a) for a in LORA_ARMS]
404
+ add("sepsis.logfc_r.first_n_above_broadcast", first_sustained(vr, bc_r), se.src_contrast)
405
+ add("sepsis.top50_deg.first_n_at_or_above_broadcast", first_sustained(vd, bc_d, strict=False),
406
+ deg_call.src_contrast)
407
+ add("sepsis.top50_deg.first_n_above_cal", first_sustained(vd, deg_call.deg("zs__cal")), deg_call.src_contrast)
408
+ # across-donor fraction r per cell type: first n from which LoRA stays at/above cal (footnote)
409
+ for ct, key in [("T cell", "T"), ("B cell", "B"), ("Monocyte", "Mono"), ("NK cell", "NK")]:
410
+ v = [im.frac_r(a, ct) for a in LORA_ARMS]
411
+ add(f"immicro.fraction_r.{key}.first_n_at_or_above_cal",
412
+ first_sustained(v, im.frac_r("zs__cal", ct), strict=False), im.src_per_donor)
413
+ add(f"immicro.fraction_r.{key}.cal", round(im.frac_r("zs__cal", ct), 2), im.src_per_donor)
414
+ add(f"immicro.fraction_r.{key}.lora_5_10_20_40_all", "/".join(f"{x:.2f}" for x in v), im.src_per_donor)
415
+ # top-50 DEG overlap by cell type (which types carry the gain)
416
+ for ct, key in [("T cell", "T"), ("B cell", "B"), ("Monocyte", "Mono"), ("NK cell", "NK"), ("DC", "DC")]:
417
+ v = [deg_call.deg_type(a, ct) for a in ["zs__cal"] + LORA_ARMS]
418
+ add(f"sepsis.top50_deg.{key}.cal_5_10_20_40_all", "/".join(f"{x:g}" for x in v), deg_call.src_contrast)
419
+ add(f"sepsis.top50_deg.{key}.broadcast", int(deg_call.deg_type("real_lora__raw", ct,
420
+ "top50_overlap_broadcast")),
421
+ deg_call.src_contrast)
422
+ add("sepsis.n_case", int(se.summary["contrast_definition"]["n_case_donors"]), se.src_summary)
423
+ add("sepsis.n_control", int(se.summary["contrast_definition"]["n_control_donors"]), se.src_summary)
424
+ add("final_checkpoint", FINAL_CKPT, "RUN.json source_checkpoint (all 50 LoRA runs)")
425
+ return pd.DataFrame(out)
426
+
427
+
428
+ def check_against_fig3(rows):
429
+ """Cross-check with the plan's own fig3 source data (same numbers, independent code path)."""
430
+ ref = pd.read_csv(PLAN / "figures" / "source_data" / "fig3_learning_curve.csv")
431
+ pmap = {("comp_l1", "immicro"): "3a", ("comp_l1", "ye2026_sepsis"): "3b",
432
+ ("coverage", "immicro"): "3c", ("coverage", "ye2026_sepsis"): "3d",
433
+ ("nk_fraction_r", "immicro"): "3e", ("logfc_r", "ye2026_sepsis"): "3f",
434
+ ("top50_deg", "ye2026_sepsis"): "3h"}
435
+ n = 0
436
+ for r in rows:
437
+ p = pmap.get((r["panel"], r["dataset"]))
438
+ if p is None:
439
+ continue
440
+ if r["series"] in ("zs_cal", "lora"):
441
+ n_key = "0" if r["pairs"] == "cal" else r["pairs"] # the plan's fig3 calls the cal point n=0
442
+ m = ref[(ref.panel == p) & (ref.series == r["series"]) & (ref.draw == f"n={n_key}")]
443
+ else:
444
+ m = ref[(ref.panel == p) & (ref.series == r["series"])]
445
+ assert len(m) == 1, (r, len(m))
446
+ assert abs(float(m.value.iloc[0]) - float(r["value"])) < 1e-5, (r, float(m.value.iloc[0]))
447
+ n += 1
448
+ return n
449
+
450
+
451
+ def main():
452
+ calls, deg_call = load()
453
+ st = load_steps()
454
+ alpha_fit, fewshot = load_alpha_fit(), load_fewshot()
455
+ rows, steprows = [], []
456
+ fig_realism(calls, st, alpha_fit, rows, steprows)
457
+ rows_sig = []
458
+ fig_signal(calls, deg_call, st, rows_sig)
459
+ n_checked = check_against_fig3(rows + rows_sig)
460
+ pd.DataFrame(rows).to_csv(DATADIR / "sec08_pairs_realism.csv", index=False, float_format="%.6g")
461
+ pd.DataFrame(steprows).to_csv(DATADIR / "sec08_selected_steps.csv", index=False, float_format="%.6g")
462
+ st.to_csv(DATADIR / "sec08_selected_steps_per_fold.csv", index=False)
463
+ pd.DataFrame(rows_sig).to_csv(DATADIR / "sec08_pairs_signal.csv", index=False, float_format="%.6g")
464
+ nums = slide_numbers(calls, deg_call, st, alpha_fit, fewshot)
465
+ nums.to_csv(DATADIR / "sec08_slide_numbers.csv", index=False)
466
+ print(nums.to_string(index=False, max_colwidth=70))
467
+ print(f"cross-checked {n_checked} plotted values against fig3_learning_curve.csv")
468
+
469
+
470
+ if __name__ == "__main__":
471
+ main()
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_paired_validation.py ADDED
@@ -0,0 +1,1113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Section 9 of the 2026-09-30 paper-summary deck: the final method in five paired cohorts,
3
+ and scSemiProfiler trained on the same 5 donors.
4
+
5
+ CPU only: reads score files, draws slide-sized figures. No torch, no CUDA, no generation, no scANVI.
6
+
7
+ Data loading is imported unchanged from the benchmark's own figure script
8
+ (plans/paired_finetune_intradataset_20260927/figures/make_figures.py: load_fewpair, load_pooled),
9
+ so every plotted number and every scSemiProfiler acceptance check (same donor set, same reference
10
+ sha, receipt verified) is the same as in the paper figures. Only the drawing is new.
11
+
12
+ Outputs (deck folder):
13
+ figures/sec09_cohorts.{png,pdf} slide a: five paired cohorts (table)
14
+ figures/sec09_fewpair_cells.{png,pdf} slide b: 5 donors, cell-level metrics
15
+ figures/sec09_fewpair_disease.{png,pdf} slide c: 5 donors, disease signal
16
+ figures/sec09_fivefold.{png,pdf} slide d: all pairs, 5-fold pooled
17
+ data/sec09_*.csv every plotted number with its source file
18
+ data/sec09_slide_text.json slide titles, keywords, footnotes and quoted numbers (+ sources),
19
+ all built by this script from the same data as the figures
20
+ data/sec09_quoted_numbers.csv the quoted numbers as a flat table
21
+
22
+ RERUN CHECKLIST (e.g. when scores/immicro/fewshot_n5/draw4_scsemi5 and scores/ye2026_sepsis/fewshot_n5/draw4_scsemi5
23
+ arrive; today 23 of 25 scSemiProfiler draws exist):
24
+ 1. /home/sj_server_1/miniforge3/bin/python3 tools/sec09_paired_validation.py (no edits needed; must exit 0)
25
+ 2. Rebuild the four slides from data/sec09_slide_text.json: every title, keyword line, footnote and quoted
26
+ number there is regenerated. Do not keep hand-copied slide text (the Sepsis verdicts are the most likely to move).
27
+ 3. Look at the four PNGs again.
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import os
32
+
33
+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
34
+
35
+ import gzip
36
+ import importlib
37
+ import importlib.util
38
+ import json
39
+ import re
40
+ import sys
41
+ from pathlib import Path
42
+
43
+ import numpy as np
44
+ import pandas as pd
45
+ from scipy.stats import wilcoxon
46
+
47
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
48
+ "2026-09-30--paper-summary--r00")
49
+ T = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
50
+ "paired_finetune_intradataset_20260927")
51
+ SCORES = T / "scores"
52
+ DATA = T / "data"
53
+ FIGDIR = DECK / "figures"
54
+ OUTDATA = DECK / "data"
55
+ SCRIPT = DECK / "tools" / "sec09_paired_validation.py"
56
+ DATALAKE = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc")
57
+
58
+ # 1) the benchmark's loaders (this import sets print-size rcParams) ...
59
+ _spec = importlib.util.spec_from_file_location("pf_make_figures", T / "figures" / "make_figures.py")
60
+ mf = importlib.util.module_from_spec(_spec)
61
+ _spec.loader.exec_module(mf)
62
+ # 2) ... then the deck style, which must win the rcParams
63
+ sys.path.insert(0, str(DECK / "tools"))
64
+ import style # noqa: E402
65
+
66
+ importlib.reload(style)
67
+ import matplotlib.pyplot as plt # noqa: E402
68
+ from matplotlib.lines import Line2D # noqa: E402
69
+ from matplotlib.patches import Patch # noqa: E402
70
+ from matplotlib.ticker import MaxNLocator # noqa: E402
71
+
72
+ # deck order: healthy first, whole-blood cohort last
73
+ ORDER = ["immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili"]
74
+ DISEASE = [d for d in ORDER if d != "immicro"]
75
+ NAME = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis", "imperial_eskd": "Imperial",
76
+ "giroux2022": "Giroux", "ji2025_chili": "Ji"}
77
+ ROWNAME = {**NAME, "ji2025_chili": "Ji (whole blood)"}
78
+ COL = {"zs_cal": style.ARM["zs_cal"], "scsemi5": style.ARM["scsemi"], "lora": style.ARM["lora"],
79
+ "sconly_cal": style.ARM["sconly"]}
80
+ LAB = {"zs_cal": "Zero-shot + paired calibration", "scsemi5": "scSemiProfiler, 5 donors",
81
+ "lora": "LoRA, 5 donors", "sconly_cal": "sc-only fine-tune + calibration",
82
+ "lora_all": "LoRA, all training pairs"}
83
+ ARM_FILE = {"lora": "lora5", "scsemi5": "scsemi5", "zs_cal": "zs_cal", "zs_raw": "zs_raw", "pseudo": "zs_pseudo"}
84
+ REFSTYLE = {"pseudo": dict(ls=(0, (4, 2)), color=style.ARM["pseudo"], lw=1.6, label="Zero-shot, sc pseudobulk input"),
85
+ "broadcast": dict(ls=(0, (1, 1.2)), color=style.ARM["broadcast"], lw=2.4, label="Real-bulk broadcast")}
86
+ EDGE = "#333333"
87
+ SUB = "#595959"
88
+ FS = style.FS
89
+ HILITE = "#FFF3D1"
90
+ LEFT_IN = 2.25 # room for the row labels (cohort + train/test pairs)
91
+ WIN_FRAC = 0.8 # a cohort verdict needs one method better in >= 80 % of the shared draws
92
+ QC = {d: DATA / d / "QC_REPORT.md" for d in DISEASE}
93
+ ARGS = T / "tools" / "contrast_args.sh"
94
+ README = T / "README.md"
95
+ SCORE_FT = T / "tools" / "score_ft.py"
96
+ PREPARE = T / "tools" / "prepare_dataset.py"
97
+ INV = DATALAKE / "docs" / "dataset_inventory.csv"
98
+ SOFT_SC = DATALAKE / "datasets" / "GSE314416" / "metadata" / "GSE314416_family.soft.gz"
99
+ SOFT_BULK = DATALAKE / "datasets" / "GSE314922" / "metadata" / "GSE314922_family.soft.gz"
100
+
101
+ CKPT = "runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt"
102
+ NUMS = {k: [] for k in "abcd"} # slide -> [{"value", "source"}] quoted on the slide
103
+ EXTRA = [] # further numbers written to the CSV only
104
+
105
+
106
+ def num(slide, value, source):
107
+ NUMS[slide].append({"value": str(value), "source": str(source)})
108
+
109
+
110
+ def extra(slide, item, value, source):
111
+ EXTRA.append({"slide": slide, "item": item, "value": str(value), "source": str(source)})
112
+
113
+
114
+ def rng(vals, fmt="{:d}"):
115
+ vals = sorted(set(vals))
116
+ return fmt.format(vals[0]) if len(vals) == 1 else f"{fmt.format(vals[0])}–{fmt.format(vals[-1])}"
117
+
118
+
119
+ # ------------------------------------------------------------------------------------------
120
+ # Evidence: every label on the cohort table must match ONE line of its source file
121
+ # ------------------------------------------------------------------------------------------
122
+ _TEXT_CACHE: dict = {}
123
+
124
+
125
+ def _read_text(p: Path) -> str:
126
+ if p not in _TEXT_CACHE:
127
+ if p.suffix == ".gz":
128
+ with gzip.open(p, "rt", encoding="utf-8", errors="replace") as fh:
129
+ _TEXT_CACHE[p] = fh.read()
130
+ else:
131
+ _TEXT_CACHE[p] = p.read_text(encoding="utf-8", errors="replace")
132
+ return _TEXT_CACHE[p]
133
+
134
+
135
+ def evidence(p: Path, pattern: str) -> str:
136
+ """The full source line (with its number) that contains a match of `pattern`; the match may not span lines."""
137
+ text = _read_text(p)
138
+ m = re.search(pattern, text, flags=re.M)
139
+ if not m:
140
+ raise ValueError(f"evidence not found: /{pattern}/ in {p}")
141
+ if "\n" in m.group(0):
142
+ raise ValueError(f"evidence /{pattern}/ spans lines in {p}")
143
+ a = text.rfind("\n", 0, m.start()) + 1
144
+ b = text.find("\n", m.end())
145
+ line = text[a:(len(text) if b < 0 else b)].strip()
146
+ return f"L{text.count(chr(10), 0, m.start()) + 1}: {line[:240]}"
147
+
148
+
149
+ def match_text(p: Path, pattern: str) -> str:
150
+ """Only the matched text (one line) of `pattern` in p, after the same checks as evidence()."""
151
+ evidence(p, pattern)
152
+ return re.search(pattern, _read_text(p), flags=re.M).group(0)
153
+
154
+
155
+ def evidences(pairs) -> tuple[str, str]:
156
+ ev = [evidence(p, pat) for p, pat in pairs]
157
+ return " || ".join(ev), " ; ".join(sorted({str(p) for p, _ in pairs}))
158
+
159
+
160
+ # display text -> [(file, one-line regex), ...]; each regex must match a single line of its file
161
+ COHORT_TEXT = {
162
+ "immicro": {
163
+ "study": ("ImMicro 2026", [(INV, r"Babdor et al\., Cell 2026 ImMicro")]),
164
+ "disease": ("healthy", [(INV, r'Babdor et al\., Cell 2026 ImMicro",Healthy humans')]),
165
+ "bulk": ("PBMC, mRNA-Seq", [(SOFT_BULK, r"^!Sample_source_name_ch1 = PBMC *$"),
166
+ (SOFT_BULK, r"Universal Plus mRNA-Seq with NuQuant kit")]),
167
+ "sc": ("10x 5′ v1.1 CITE-seq", [(SOFT_SC, r"Chromium Next GEM Single Cell 5.{1,2} v1\.1 Library Kit"),
168
+ (SOFT_SC, r"Library strategy: CITE-seq")]),
169
+ },
170
+ "ye2026_sepsis": {
171
+ "study": ("Ye 2026", [(QC["ye2026_sepsis"], r"Ye Q et al\., Nat Immunol 2026")]),
172
+ "disease": ("sepsis", [(QC["ye2026_sepsis"], r"^# Ye 2026 sepsis")]),
173
+ # extraction is total RNA (Trizol) but the library (polyA vs rRNA depletion) is not stated -> show PBMC only
174
+ "bulk": ("PBMC", [(QC["ye2026_sepsis"], r"GEO protocol: PBMC total RNA \(Trizol\).*polyA vs rRNA depletion not stated")]),
175
+ "sc": ("10x 5′", [(QC["ye2026_sepsis"], r"Chemistry: GEO says .*but the data show 5'")]),
176
+ },
177
+ "imperial_eskd": {
178
+ "study": ("Imperial ESKD", [(QC["imperial_eskd"], r"patients with COVID-19, Imperial cohort")]),
179
+ "disease": ("COVID-19, dialysis", [(QC["imperial_eskd"], r"haemodialysis \(end-stage kidney disease\) patients with COVID-19")]),
180
+ "bulk": ("PBMC", [(QC["imperial_eskd"], r"^- Bulk: .*PBMC RNA-seq")]),
181
+ "sc": ("10x 5′ v2 CITE-seq", [(QC["imperial_eskd"], r"^- scRNA: .*PBMC CITE-seq"),
182
+ (QC["imperial_eskd"], r"Chemistry: 10x 5′ v2")]),
183
+ },
184
+ "giroux2022": {
185
+ "study": ("Giroux 2022", [(QC["giroux2022"], r"Giroux NS et al\., Sci Rep 2022")]),
186
+ "disease": ("COVID-19, outpatient", [(QC["giroux2022"], r"Duke outpatients, early COVID-19")]),
187
+ "bulk": ("PBMC, total RNA (SoLo)", [(QC["giroux2022"], r"^# Giroux 2022 COVID-19: paired PBMC bulk and scRNA"),
188
+ (QC["giroux2022"], r"GEO protocol: Zymo Direct-zol total RNA, NuGEN Ovation SoLo")]),
189
+ "sc": ("10x 5′ v1", [(QC["giroux2022"], r"10x library per subject-day \(5' v1")]),
190
+ },
191
+ "ji2025_chili": {
192
+ "study": ("Ji 2025", [(QC["ji2025_chili"], r"Ji C et al\., Cancer Immunol Immunother 2025")]),
193
+ "disease": ("ICI liver injury", [(QC["ji2025_chili"], r"liver injury on checkpoint inhibitors \(ChILI\)")]),
194
+ "bulk": ("whole blood, 3′ QuantSeq", [(QC["ji2025_chili"], r"\*\*PAXgene whole-blood tubes\*\*"),
195
+ (QC["ji2025_chili"], r"Protocol: Lexogen QuantSeq 3′ FWD")]),
196
+ "sc": ("10x 5′", [(QC["ji2025_chili"], r"Chemistry: 10x 5′ GEX")]),
197
+ },
198
+ }
199
+ # display labels of the scorer's case / control groups; the group lists are asserted against summary.json and
200
+ # contrast_args.sh; `neither` = groups scored in neither arm of the contrast
201
+ CONTRAST = {
202
+ "ye2026_sepsis": dict(case="sepsis", control="control", case_groups=["adult_sepsis", "ped_sepsis"],
203
+ control_groups=["adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"], neither=[],
204
+ ev=[(ARGS, r'ye2026_sepsis\) echo "--case-groups adult_sepsis,ped_sepsis '
205
+ r'--control-groups adult_HC,adult_ICU_ctrl,ped_HC,ped_ICU_ctrl"')]),
206
+ "imperial_eskd": dict(case="COVID+", control="COVID−", case_groups=["covid_positive"],
207
+ control_groups=["covid_negative"], neither=["recovery"],
208
+ ev=[(ARGS, r"COVID-positive vs COVID-negative haemodialysis patients \(recovery samples in neither group\)"),
209
+ (ARGS, r'imperial_eskd\) echo "--case-groups covid_positive --control-groups covid_negative"')]),
210
+ # the GEO label is "severe"; the paper and the author sheet call this group "moderate" (all are outpatients)
211
+ "giroux2022": dict(case="moderate", control="mild", case_groups=["severe"], control_groups=["mild"], neither=[],
212
+ ev=[(QC["giroux2022"], r'The paper and the author sheet call the "severe" group "moderate"'),
213
+ (ARGS, r'giroux2022\) echo "--case-groups severe --control-groups mild"')]),
214
+ "ji2025_chili": dict(case="ChILI", control="ICI control", case_groups=["TOL", "FU1"], control_groups=["BC", "AC"],
215
+ neither=[],
216
+ ev=[(ARGS, r"ChILI patients \(liver injury and its follow-up\) vs checkpoint-inhibitor controls"),
217
+ (ARGS, r'ji2025_chili\) echo "--case-groups TOL,FU1 --control-groups BC,AC"')]),
218
+ }
219
+
220
+
221
+ def usable_folds(ds):
222
+ f = pd.read_csv(DATA / ds / "folds.csv")
223
+ f["donor_id"] = f["donor_id"].astype(str)
224
+ f["sample_id"] = f["sample_id"].astype(str)
225
+ return f[f.fold >= 0].copy()
226
+
227
+
228
+ def min_cells() -> int:
229
+ return int(re.search(r"^MIN_CELLS = (\d+)", _read_text(PREPARE), flags=re.M).group(1))
230
+
231
+
232
+ def cohort_rows():
233
+ mc = min_cells()
234
+ rows = []
235
+ for ds in ORDER:
236
+ r = {"dataset": ds}
237
+ for key, (txt, pairs) in COHORT_TEXT[ds].items():
238
+ r[key] = txt
239
+ r[f"{key}_evidence"], r[f"{key}_source"] = evidences(pairs)
240
+ dj = DATA / ds / "fewshot_n5" / "DRAWS.json"
241
+ draws = json.loads(dj.read_text())
242
+ used = usable_folds(ds)
243
+ if len(used) != draws["n_usable_rows"] or used.donor_id.nunique() != draws["n_usable_donors"]:
244
+ raise ValueError(f"{ds}: folds.csv and DRAWS.json disagree on usable rows/donors")
245
+ # exclusion tally, re-derived with prepare_dataset.py's rule: identity_pass & n_cells >= MIN_CELLS
246
+ feats = np.load(DATA / ds / "features.npz", allow_pickle=False)
247
+ samples = pd.read_csv(DATA / ds / "samples.csv")
248
+ n_all = int(feats["bulk_raw"].shape[0])
249
+ idp = feats["identity_pass"].astype(bool) if "identity_pass" in feats.files else np.ones(n_all, bool)
250
+ chk = (pd.Series(feats["identity_check"].astype(str)).str.split(":").str[0].str.strip()
251
+ if "identity_check" in feats.files else pd.Series(["(no flag)"] * n_all))
252
+ low = (samples["n_cells"].to_numpy() < mc)
253
+ n_fail, n_border = int((chk == "fail").sum()), int((chk == "borderline").sum())
254
+ if int((~idp).sum()) != n_fail + n_border:
255
+ raise ValueError(f"{ds}: identity_pass False rows != fail + borderline")
256
+ n_low = int((idp & low).sum())
257
+ if n_all - n_fail - n_border - n_low != draws["n_usable_rows"]:
258
+ raise ValueError(f"{ds}: exclusion tally does not reproduce the usable rows")
259
+ pooled_sum = json.loads((SCORES / ds / "pooled" / "summary.json").read_text())
260
+ if pooled_sum["n_donors"] != draws["n_usable_rows"]:
261
+ raise ValueError(f"{ds}: pooled scored n {pooled_sum['n_donors']} != usable rows {draws['n_usable_rows']}")
262
+ r.update(n_pairs_all=n_all, n_identity_fail=n_fail, n_identity_borderline=n_border,
263
+ n_low_cells=n_low, min_cells=mc, identity_flag=("identity_pass" in feats.files),
264
+ n_rows=draws["n_usable_rows"], n_donors=draws["n_usable_donors"], n_rows_source=str(dj),
265
+ exclusion_source=f"{DATA / ds / 'features.npz'} (identity_pass, identity_check); "
266
+ f"{DATA / ds / 'samples.csv'} (n_cells); {PREPARE} (MIN_CELLS)")
267
+ cd = pooled_sum["contrast_definition"]
268
+ psrc = str(SCORES / ds / "pooled" / "summary.json")
269
+ if ds in CONTRAST:
270
+ C = CONTRAST[ds]
271
+ if list(cd["case_groups"]) != C["case_groups"] or list(cd["control_groups"]) != C["control_groups"]:
272
+ raise ValueError(f"{ds}: contrast groups changed: {cd['case_groups']} / {cd['control_groups']}")
273
+ neither = sorted({g for g, a, b in zip(cd["groups"], cd["case"], cd["ctrl"]) if not a and not b})
274
+ if neither != sorted(C["neither"]) or (int(cd.get("n_donors_in_neither", 0)) > 0) != bool(neither):
275
+ raise ValueError(f"{ds}: groups in neither arm {neither} != expected {C['neither']}")
276
+ ev, evsrc = evidences(C["ev"])
277
+ r.update(case_label=C["case"], control_label=C["control"], n_case=int(cd["n_case_donors"]),
278
+ n_control=int(cd["n_control_donors"]), n_neither=int(cd.get("n_donors_in_neither", 0)),
279
+ neither_label=",".join(neither), contrast_source=psrc, contrast_label_evidence=ev,
280
+ contrast_label_source=evsrc)
281
+ else:
282
+ if cd.get("enabled"):
283
+ raise ValueError(f"{ds}: expected no contrast")
284
+ r.update(case_label="", control_label="", n_case=np.nan, n_control=np.nan, n_neither=0,
285
+ neither_label="", contrast_source=psrc)
286
+ rows.append(r)
287
+ return pd.DataFrame(rows)
288
+
289
+
290
+ def fig_cohorts(tab: pd.DataFrame):
291
+ """Plain table: columns are placed by measuring the rendered text, so nothing overlaps."""
292
+ headers = ["Cohort", "Condition", "Bulk", "scRNA-seq", "Pairs (donors)", "Case vs control"]
293
+ center = {4}
294
+ body = []
295
+ for r in tab.itertuples():
296
+ pd_txt = f"{r.n_rows}" if r.n_rows == r.n_donors else f"{r.n_rows} ({r.n_donors})"
297
+ ctxt = (f"{r.case_label} {int(r.n_case)} vs {r.control_label} {int(r.n_control)}" if r.case_label
298
+ else "none (healthy)")
299
+ csub = f"+{r.n_neither} {r.neither_label} (neither)" if r.n_neither else None
300
+ body.append([(r.study, {}, None), (r.disease, {}, None),
301
+ (r.bulk, {"fontweight": "bold"} if r.dataset == "ji2025_chili" else {}, None),
302
+ (r.sc, {}, None), (pd_txt, {}, None), (ctxt, {} if r.case_label else {"color": SUB}, csub)])
303
+ W, H = style.FULL[0], 3.7
304
+ fig = plt.figure(figsize=(W, H))
305
+ ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
306
+ ax.set_axis_off()
307
+ ax.set_xlim(0, 1)
308
+ ax.set_ylim(0, 1)
309
+ n = len(body)
310
+ top, rowh = 0.87, 0.84 / n
311
+ texts = [[] for _ in headers]
312
+ for j, h in enumerate(headers):
313
+ texts[j].append(ax.text(0, top + 0.055, h, ha="left", va="center", fontsize=FS, fontweight="bold",
314
+ color=style.INK))
315
+ for i, row in enumerate(body):
316
+ y = top - rowh * (i + 0.5)
317
+ for j, (txt, kw, sub) in enumerate(row):
318
+ if sub:
319
+ texts[j].append(ax.text(0, y + 0.03, txt, ha="left", va="center", fontsize=FS,
320
+ **{"color": style.INK, **kw}))
321
+ texts[j].append(ax.text(0, y - 0.035, sub, ha="left", va="center", fontsize=FS - 3, color=SUB))
322
+ else:
323
+ texts[j].append(ax.text(0, y, txt, ha="left", va="center", fontsize=FS,
324
+ **{"color": style.INK, **kw}))
325
+ fig.canvas.draw()
326
+ rend = fig.canvas.get_renderer()
327
+ widths = [max(t.get_window_extent(rend).width for t in col) / (fig.dpi * W) for col in texts]
328
+ gap = (1.0 - sum(widths)) / (len(headers) - 1)
329
+ if gap < 0.012:
330
+ raise ValueError(f"cohort table too wide for the slide (gap {gap:.3f})")
331
+ x = 0.0
332
+ for j, col in enumerate(texts):
333
+ for t in col:
334
+ if j in center:
335
+ t.set_x(x + widths[j] / 2)
336
+ t.set_ha("center")
337
+ else:
338
+ t.set_x(x)
339
+ x += widths[j] + gap
340
+ ax.plot([0, 1], [top + 0.005] * 2, color=style.INK, lw=1.2)
341
+ for i in range(1, n):
342
+ ax.plot([0, 1], [top - rowh * i] * 2, color="#C8C8C8", lw=0.7)
343
+ ax.plot([0, 1], [top - rowh * n] * 2, color=style.INK, lw=1.2)
344
+ style.save(fig, "sec09_cohorts", FIGDIR)
345
+
346
+
347
+ # ------------------------------------------------------------------------------------------
348
+ # Shared drawing helpers: rows = cohorts, columns = metrics, horizontal bars
349
+ # ------------------------------------------------------------------------------------------
350
+ BAR_H = 0.72
351
+
352
+
353
+ def jitter(n, seed):
354
+ r = np.random.default_rng(seed)
355
+ return (r.random(n) - 0.5) * BAR_H * 0.6
356
+
357
+
358
+ def hbars(ax, arms, vals_of, seed=0, dots=True):
359
+ """arms drawn top to bottom at y = 0..na-1. vals_of(arm) -> list of floats. Returns stats."""
360
+ out = {}
361
+ for i, arm in enumerate(arms):
362
+ vals = np.asarray([v for v in vals_of(arm) if not np.isnan(v)], float)
363
+ if len(vals) == 0:
364
+ ax.text(0.01, i, "not run", transform=ax.get_yaxis_transform(), va="center", fontsize=FS - 3,
365
+ color=SUB)
366
+ out[arm] = (np.nan, np.nan, 0)
367
+ continue
368
+ m = float(vals.mean())
369
+ sd = float(vals.std(ddof=1)) if len(vals) > 1 else 0.0
370
+ ax.barh(i, m, height=BAR_H, color=COL[arm], edgecolor=EDGE, linewidth=0.6, zorder=2)
371
+ if dots and len(vals) > 1:
372
+ ax.errorbar(m, i, xerr=sd, fmt="none", ecolor="#111111", elinewidth=1.0, capsize=3, capthick=1.0,
373
+ zorder=4)
374
+ ax.scatter(vals, i + jitter(len(vals), seed + i), s=16, facecolor="white", edgecolor="#111111",
375
+ linewidth=0.7, zorder=5)
376
+ out[arm] = (m, sd, len(vals))
377
+ ax.set_ylim(len(arms) - 0.5, -0.5)
378
+ ax.set_yticks([])
379
+ return out
380
+
381
+
382
+ def ref_line(ax, x, kind, na):
383
+ """Reference line above the bars (zorder 2) but below error bars (4) and draw dots (5)."""
384
+ if x is None or np.isnan(x):
385
+ return
386
+ s = REFSTYLE[kind]
387
+ ax.plot([x, x], [-0.5, na - 0.5], ls=s["ls"], color=s["color"], lw=s["lw"], zorder=3,
388
+ solid_capstyle="butt")
389
+
390
+
391
+ def row_label(ax, name, subs):
392
+ """Cohort name (FS) with grey sub-lines (FS-3) stacked below it, the block centred on the row."""
393
+ lines = [(name, FS, style.INK)] + [(s, FS - 3, SUB) for s in subs]
394
+ y = sum(fs * 1.3 for _, fs, _ in lines) / 2
395
+ for txt, fs, col in lines:
396
+ h = fs * 1.3
397
+ ax.annotate(txt, xy=(0, 0.5), xycoords="axes fraction", xytext=(-12, y - h / 2), textcoords="offset points",
398
+ ha="right", va="center", fontsize=fs, color=col)
399
+ y -= h
400
+
401
+
402
+ def label_header(ax, text):
403
+ ax.annotate(text, xy=(0, 1), xycoords="axes fraction", xytext=(-12, 10), textcoords="offset points",
404
+ ha="right", va="bottom", fontsize=FS - 3, color=SUB, style="italic")
405
+
406
+
407
+ def blank(ax, text):
408
+ for sp in ax.spines.values():
409
+ sp.set_visible(False)
410
+ ax.set_xticks([])
411
+ ax.set_yticks([])
412
+ ax.text(0.5, 0.5, text, transform=ax.transAxes, ha="center", va="center", fontsize=FS - 3, color=SUB,
413
+ style="italic")
414
+
415
+
416
+ def grid(nrows, ncols, figsize, left, right, top, bottom, hspace, wspace):
417
+ fig = plt.figure(figsize=figsize)
418
+ gs = fig.add_gridspec(nrows, ncols, left=left / figsize[0], right=1 - right / figsize[0],
419
+ top=1 - top / figsize[1], bottom=bottom / figsize[1], hspace=hspace, wspace=wspace)
420
+ axs = np.empty((nrows, ncols), dtype=object)
421
+ for i in range(nrows):
422
+ for j in range(ncols):
423
+ axs[i, j] = fig.add_subplot(gs[i, j])
424
+ return fig, axs
425
+
426
+
427
+ def shared_x(axs_col, lo, hi, xlabel, ticks=None):
428
+ for k, ax in enumerate(axs_col):
429
+ ax.set_xlim(lo, hi)
430
+ if ticks is not None:
431
+ ax.set_xticks(ticks)
432
+ if k < len(axs_col) - 1:
433
+ ax.tick_params(axis="x", labelbottom=False, length=0)
434
+ ax.spines["bottom"].set_visible(False)
435
+ axs_col[-1].set_xlabel(xlabel)
436
+
437
+
438
+ def legend_bottom(fig, handles, ncol, y=0.0):
439
+ fig.legend(handles=handles, loc="lower center", bbox_to_anchor=(0.5, y), ncol=ncol, frameon=False,
440
+ fontsize=FS - 2, handlelength=2.2, columnspacing=1.6, borderaxespad=0.0)
441
+
442
+
443
+ def patch(key, label=None):
444
+ return Patch(facecolor=COL[key], edgecolor=EDGE, linewidth=0.6, label=label or LAB[key])
445
+
446
+
447
+ def refh(kind):
448
+ s = REFSTYLE[kind]
449
+ return Line2D([0], [0], ls=s["ls"], color=s["color"], lw=s["lw"], label=s["label"])
450
+
451
+
452
+ def dot_handle(n_draws):
453
+ lab = "one draw; bar = mean ± SD" + (f" of {n_draws}" if n_draws else "")
454
+ return Line2D([0], [0], marker="o", lw=0, markerfacecolor="white", markeredgecolor="#111111",
455
+ markersize=5, label=lab)
456
+
457
+
458
+ # ------------------------------------------------------------------------------------------
459
+ # Few-pair (5 donors) data
460
+ # ------------------------------------------------------------------------------------------
461
+ _JSON: dict = {}
462
+
463
+
464
+ def jload(p: Path):
465
+ if p not in _JSON:
466
+ _JSON[p] = json.loads(Path(p).read_text())
467
+ return _JSON[p]
468
+
469
+
470
+ def fewpair():
471
+ few, status = mf.load_fewpair(SCORES)
472
+ status.to_csv(OUTDATA / "sec09_scsemi_status.csv", index=False)
473
+ # depth-matched precision / coverage are in each call's summary.json headline (not in load_fewpair's metrics)
474
+ for k in ("precision_dm", "coverage_dm"):
475
+ few[k] = [float(jload(T / s)["headline"][ARM_FILE[a]][k]) for s, a in zip(few.source, few.arm)]
476
+ return few, status
477
+
478
+
479
+ def few_vals(few, ds, arm, metric):
480
+ s = few[(few.dataset == ds) & (few.arm == arm)].sort_values("draw")
481
+ return s[metric].astype(float).tolist(), s["draw"].tolist(), s["source"].tolist()
482
+
483
+
484
+ def few_ref(few, ds, kind, metric):
485
+ """pseudo = zero-shot from sc pseudobulk (zs_pseudo arm); broadcast = raw real bulk logFC/DEG; mean over draws."""
486
+ if kind == "pseudo":
487
+ s = few[(few.dataset == ds) & (few.arm == "pseudo")]
488
+ v = s[metric]
489
+ else:
490
+ s = few[(few.dataset == ds) & (few.arm == "lora")]
491
+ v = s["broadcast_r" if metric == "contrast_r" else "deg_broadcast"]
492
+ v = v.dropna()
493
+ return (float(v.mean()) if len(v) else np.nan), ";".join(sorted(set(s["source"])))
494
+
495
+
496
+ def n_draws(few, ds, arm):
497
+ return int(few[(few.dataset == ds) & (few.arm == arm)]["draw"].nunique())
498
+
499
+
500
+ def draw_info(few, ds):
501
+ """Training / test pairs of the scored LoRA draws (DRAWS.json), and test subjects per contrast arm."""
502
+ dj = DATA / ds / "fewshot_n5" / "DRAWS.json"
503
+ D = jload(dj)["draw"]
504
+ u = usable_folds(ds)
505
+ lora = few[(few.dataset == ds) & (few.arm == "lora")].sort_values("draw")
506
+ tr, te, n_sub, sub_cc = [], [], [], []
507
+ for r in lora.itertuples():
508
+ v = D[str(int(r.draw))] if str(int(r.draw)) in D else D[int(r.draw)]
509
+ if int(r.n_scored) != int(v["n_test_rows"]):
510
+ raise ValueError(f"{ds} draw {r.draw}: scored n {r.n_scored} != DRAWS n_test_rows {v['n_test_rows']}")
511
+ train = {str(x) for x in v["train_donors"]}
512
+ if int(u[u.donor_id.isin(train)].shape[0]) != int(v["n_train_rows"]):
513
+ raise ValueError(f"{ds} draw {r.draw}: train rows in folds.csv != DRAWS n_train_rows")
514
+ tr.append(int(v["n_train_rows"]))
515
+ te.append(int(r.n_scored))
516
+ test = u[~u.donor_id.isin(train)]
517
+ n_sub.append(int(test.donor_id.nunique()))
518
+ if ds in CONTRAST:
519
+ C = CONTRAST[ds]
520
+ cs = set(test[test.group.isin(C["case_groups"])].donor_id)
521
+ ct = set(test[test.group.isin(C["control_groups"])].donor_id)
522
+ sub_cc.append((len(cs), len(ct)))
523
+ return {"train": rng(tr), "test": rng(te), "n_train": tr, "n_test": te, "n_test_subjects": n_sub,
524
+ "subjects_cc": sub_cc, "n_draws": len(tr), "source": str(dj)}
525
+
526
+
527
+ def subjects_text(info):
528
+ """'2 vs 2' when a cohort's test set holds few subjects (< 10) per draw; else ''."""
529
+ if not info["subjects_cc"] or max(info["n_test_subjects"]) >= 10:
530
+ return ""
531
+ a = rng([c for c, _ in info["subjects_cc"]])
532
+ b = rng([t for _, t in info["subjects_cc"]])
533
+ return f"{a} vs {b}"
534
+
535
+
536
+ def row_subs(info, per_row_draws):
537
+ subs = [f"train {info['train']} / test {info['test']}"]
538
+ st = subjects_text(info)
539
+ if st:
540
+ subs.append(f"test = {st} subjects")
541
+ if per_row_draws:
542
+ subs.append(f"{info['n_draws']} draws")
543
+ return subs
544
+
545
+
546
+ def long_rows(fig, few, datasets, arms, metrics, refs):
547
+ rows = []
548
+ for ds in datasets:
549
+ for metric in metrics:
550
+ for arm in arms:
551
+ vals, draws, srcs = few_vals(few, ds, arm, metric)
552
+ for v, d, s in zip(vals, draws, srcs):
553
+ rows.append({"figure": fig, "dataset": ds, "metric": metric, "series": arm, "kind": "draw",
554
+ "draw": d, "value": v, "source": s})
555
+ vv = [v for v in vals if not np.isnan(v)]
556
+ if vv:
557
+ rows.append({"figure": fig, "dataset": ds, "metric": metric, "series": arm, "kind": "mean",
558
+ "draw": "", "value": float(np.mean(vv)),
559
+ "sd": float(np.std(vv, ddof=1)) if len(vv) > 1 else 0.0, "n_draws": len(vv),
560
+ "source": "derived: mean/SD of the draw rows"})
561
+ for kind in refs.get(metric, []):
562
+ v, s = few_ref(few, ds, kind, metric)
563
+ rows.append({"figure": fig, "dataset": ds, "metric": metric, "series": f"ref_{kind}",
564
+ "kind": "reference (mean over draws)", "draw": "", "value": v, "source": s})
565
+ return rows
566
+
567
+
568
+ def same_draw_compare(few, status, datasets, metric, lower_better=False, min_margin=0.0):
569
+ """LoRA-5 vs scSemi-5 draw by draw, on the draws where both exist (same test pairs).
570
+
571
+ Per draw: LoRA better / scSemi better / tie (equal values). Cohort verdict:
572
+ 'tie' if at least half the shared draws tie, or |mean difference| < min_margin;
573
+ 'lora' if LoRA is better in >= WIN_FRAC of the shared draws;
574
+ 'scsemi' if scSemi is better in >= WIN_FRAC of the shared draws;
575
+ 'split' otherwise.
576
+ """
577
+ used = status[status.status == "used"]
578
+ res = {}
579
+ for ds in datasets:
580
+ a = few[(few.dataset == ds) & (few.arm == "lora")].set_index("draw")[metric].astype(float)
581
+ b = few[(few.dataset == ds) & (few.arm == "scsemi5")].set_index("draw")[metric].astype(float)
582
+ dr = [d for d in sorted(used[used.dataset == ds]["draw"])
583
+ if d in a.index and d in b.index and not (np.isnan(a[d]) or np.isnan(b[d]))]
584
+ if not dr:
585
+ continue
586
+ d = (a[dr] - b[dr]) * (-1.0 if lower_better else 1.0) # > 0: LoRA better
587
+ nL, nS = int((d > 0).sum()), int((d < 0).sum())
588
+ nT = len(dr) - nL - nS
589
+ mdiff = float(a[dr].mean() - b[dr].mean())
590
+ if 2 * nT >= len(dr) or abs(mdiff) < min_margin:
591
+ verdict = "tie"
592
+ elif nL >= WIN_FRAC * len(dr):
593
+ verdict = "lora"
594
+ elif nS >= WIN_FRAC * len(dr):
595
+ verdict = "scsemi"
596
+ else:
597
+ verdict = "split"
598
+ res[ds] = dict(lora=float(a[dr].mean()), scsemi=float(b[dr].mean()), n=len(dr), n_lora=nL, n_scsemi=nS,
599
+ n_tie=nT, verdict=verdict, draws=dr)
600
+ return res
601
+
602
+
603
+ def l1_vs_zeroshot_per_donor(ds):
604
+ """LoRA-5 minus zero-shot-cal composition L1, averaged per donor over every draw the donor was tested in,
605
+ then a Wilcoxon signed-rank test over donors (units repeat across draws, so donor-draw rows are not independent)."""
606
+ s2d = dict(zip(usable_folds(ds).sample_id, usable_folds(ds).donor_id))
607
+ parts = []
608
+ for j, p in mf.draw_dirs(SCORES / ds / "fewshot_n5"):
609
+ pdn = pd.read_csv(p / "per_donor.csv", usecols=["arm", "donor", "comp_l1"])
610
+ w = pdn[pdn.arm.isin(["lora5", "zs_cal"])].pivot(index="donor", columns="arm", values="comp_l1")
611
+ x = (w["lora5"] - w["zs_cal"]).rename("diff").reset_index()
612
+ x["draw"] = j
613
+ parts.append(x)
614
+ x = pd.concat(parts)
615
+ x["donor_id"] = x["donor"].astype(str).map(s2d)
616
+ if x["donor_id"].isna().any():
617
+ raise ValueError(f"{ds}: per_donor units missing from folds.csv")
618
+ per = x.groupby("donor_id")["diff"].mean()
619
+ return dict(n_donors=int(len(per)), n_rows=int(len(x)), mean_diff=float(per.mean()),
620
+ frac_better=float((per < 0).mean()), p=float(wilcoxon(per).pvalue),
621
+ source=f"{SCORES / ds / 'fewshot_n5'}/draw<j>/per_donor.csv (comp_l1, arms lora5 / zs_cal); "
622
+ f"{DATA / ds / 'folds.csv'} (sample -> donor)")
623
+
624
+
625
+ # ------------------------------------------------------------------------------------------
626
+ # Slide b: 5 donors, cells
627
+ # ------------------------------------------------------------------------------------------
628
+ def fig_fewpair_cells(few, info):
629
+ arms = ["zs_cal", "scsemi5", "lora"]
630
+ metrics = [("coverage", "Coverage ↑", (0, 1.0), [0, 0.5, 1.0]),
631
+ ("precision", "Precision ↑", (0, 1.0), [0, 0.5, 1.0]),
632
+ ("comp_l1", "Composition L1 ↓", None, None)]
633
+ nd_all = {info[d]["n_draws"] for d in ORDER}
634
+ per_row = len(nd_all) > 1
635
+ fig, axs = grid(len(ORDER), len(metrics), style.FULL, left=LEFT_IN, right=0.15, top=0.45, bottom=1.25,
636
+ hspace=0.22, wspace=0.10)
637
+ l1max = 0.0
638
+ for i, ds in enumerate(ORDER):
639
+ nl = n_draws(few, ds, "lora")
640
+ ns = n_draws(few, ds, "scsemi5")
641
+ for j, (mk, _, _, _) in enumerate(metrics):
642
+ ax = axs[i, j]
643
+ st = hbars(ax, arms, lambda a: few_vals(few, ds, a, mk)[0], seed=17 * i + j)
644
+ ref_line(ax, few_ref(few, ds, "pseudo", mk)[0], "pseudo", len(arms))
645
+ if mk == "comp_l1":
646
+ allv = [v for a in arms for v in few_vals(few, ds, a, mk)[0] if not np.isnan(v)]
647
+ l1max = max([l1max, max(allv)] + [m + sd for m, sd, n in st.values() if n])
648
+ if j == 0 and 0 < ns < nl:
649
+ m, sd, n = st["scsemi5"]
650
+ ax.text(max(m + sd, max(few_vals(few, ds, "scsemi5", mk)[0])) + 0.03, 1, f"{ns} of {nl} draws",
651
+ va="center", ha="left", fontsize=FS - 3, color="#8A5A00")
652
+ row_label(axs[i, 0], ROWNAME[ds], row_subs(info[ds], per_row))
653
+ label_header(axs[0, 0], "pairs per draw")
654
+ for j, (mk, lab, lim, ticks) in enumerate(metrics):
655
+ if lim is None:
656
+ lim = (0, np.ceil(l1max * 1.08 * 10) / 10)
657
+ ticks = [0, 0.2, 0.4, 0.6, 0.8][: int(lim[1] / 0.2) + 1]
658
+ shared_x(axs[:, j], lim[0], lim[1], lab, ticks)
659
+ handles = [patch("zs_cal"), patch("scsemi5"), patch("lora"), refh("pseudo"),
660
+ dot_handle(None if per_row else nd_all.pop())]
661
+ legend_bottom(fig, handles, ncol=3)
662
+ style.save(fig, "sec09_fewpair_cells", FIGDIR)
663
+ rows = long_rows("sec09_fewpair_cells", few, ORDER, arms, [m[0] for m in metrics] + ["precision_dm", "coverage_dm"],
664
+ {"coverage": ["pseudo"], "precision": ["pseudo"], "comp_l1": ["pseudo"]})
665
+ pd.DataFrame(rows).to_csv(OUTDATA / "sec09_fewpair_cells.csv", index=False, float_format="%.6g")
666
+
667
+
668
+ # ------------------------------------------------------------------------------------------
669
+ # Slide c: 5 donors, disease signal
670
+ # ------------------------------------------------------------------------------------------
671
+ def fmt_deg(v):
672
+ return f"{v:.1f}" if v < 10 else f"{v:.0f}"
673
+
674
+
675
+ def fig_fewpair_disease(few, info):
676
+ arms = ["zs_cal", "scsemi5", "lora"]
677
+ nd_all = {info[d]["n_draws"] for d in DISEASE}
678
+ per_row = len(nd_all) > 1
679
+ fig, axs = grid(len(DISEASE), 2, style.TALL, left=LEFT_IN, right=0.25, top=0.45, bottom=1.55,
680
+ hspace=0.45, wspace=0.12)
681
+ rmin, rmax = 0.0, 0.0
682
+ for i, ds in enumerate(DISEASE):
683
+ nl = n_draws(few, ds, "lora")
684
+ ns = n_draws(few, ds, "scsemi5")
685
+ # logFC r
686
+ ax = axs[i, 0]
687
+ hbars(ax, arms, lambda a: few_vals(few, ds, a, "contrast_r")[0], seed=31 * i)
688
+ bc = few_ref(few, ds, "broadcast", "contrast_r")[0]
689
+ ref_line(ax, bc, "broadcast", len(arms))
690
+ ax.axvline(0, color="#555555", lw=0.8, zorder=1)
691
+ ax.spines["left"].set_visible(False)
692
+ allv = [v for a in arms for v in few_vals(few, ds, a, "contrast_r")[0] if not np.isnan(v)] + [bc]
693
+ rmin, rmax = min(rmin, min(allv)), max(rmax, max(allv))
694
+ if ns < nl:
695
+ ax.text(1.0, 1, f"{ns} of {nl} draws", transform=ax.get_yaxis_transform(), va="center", ha="right",
696
+ fontsize=FS - 3, color="#8A5A00")
697
+ # top-50 DEG, own scale per cohort
698
+ ax = axs[i, 1]
699
+ st = hbars(ax, arms, lambda a: few_vals(few, ds, a, "deg")[0], seed=37 * i)
700
+ bcd = few_ref(few, ds, "broadcast", "deg")[0]
701
+ ref_line(ax, bcd, "broadcast", len(arms))
702
+ hi = max([bcd] + [v for a in arms for v in few_vals(few, ds, a, "deg")[0] if not np.isnan(v)])
703
+ hi = max(hi, 4.0)
704
+ ax.set_xlim(0, hi * 1.40)
705
+ ax.xaxis.set_major_locator(MaxNLocator(nbins=3, integer=True))
706
+ for k, a in enumerate(arms):
707
+ m, sd, n = st[a]
708
+ if n:
709
+ ax.text(0.995, k, fmt_deg(m), transform=ax.get_yaxis_transform(), va="center", ha="right",
710
+ fontsize=FS - 3, color=SUB)
711
+ row_label(axs[i, 0], ROWNAME[ds], row_subs(info[ds], per_row))
712
+ label_header(axs[0, 0], "pairs per draw")
713
+ lo = min(-0.1, np.floor(rmin * 10) / 10)
714
+ hi = max(0.9, np.ceil(rmax * 10) / 10 + 0.05)
715
+ shared_x(axs[:, 0], lo, hi, "Disease logFC r ↑", [0, 0.4, 0.8])
716
+ axs[-1, 1].set_xlabel("Top-50 DEG overlap ↑")
717
+ for ax in axs[:, 1]:
718
+ ax.tick_params(axis="x", labelsize=FS - 3)
719
+ handles = [patch("zs_cal"), patch("scsemi5"), patch("lora"), refh("broadcast"),
720
+ dot_handle(None if per_row else nd_all.pop())]
721
+ legend_bottom(fig, handles, ncol=2)
722
+ style.save(fig, "sec09_fewpair_disease", FIGDIR)
723
+ rows = long_rows("sec09_fewpair_disease", few, DISEASE, arms, ["contrast_r", "deg"],
724
+ {"contrast_r": ["broadcast"], "deg": ["broadcast"]})
725
+ pd.DataFrame(rows).to_csv(OUTDATA / "sec09_fewpair_disease.csv", index=False, float_format="%.6g")
726
+
727
+
728
+ # ------------------------------------------------------------------------------------------
729
+ # Slide d: all pairs, 5-fold pooled
730
+ # ------------------------------------------------------------------------------------------
731
+ POOLED_ARMS = {"zs_cal": "zs__cal", "sconly_cal": "pseudo_full__cal", "lora": "real_lora__raw"}
732
+
733
+
734
+ def baselines_text(vals):
735
+ """'0.11' when both baselines round to the same 2 decimals, else '0.10–0.12'."""
736
+ s = sorted({f"{v:.2f}" for v in vals})
737
+ return s[0] if len(s) == 1 else f"{s[0]}–{s[-1]}"
738
+
739
+
740
+ def fig_fivefold(pooled, tab):
741
+ arms = ["zs_cal", "sconly_cal", "lora"]
742
+ metrics = [("coverage", "Coverage ↑"), ("contrast_r", "Disease logFC r ↑"), ("deg", "Top-50 DEG overlap ↑")]
743
+ fig, axs = grid(len(ORDER), 3, style.FULL, left=LEFT_IN, right=0.35, top=0.45, bottom=1.25,
744
+ hspace=0.40, wspace=0.12)
745
+ rows = []
746
+ ji_note = None
747
+ tabi = tab.set_index("dataset")
748
+
749
+ def src(m, mk):
750
+ return m.get("deg_source", m["source"]) if mk == "deg" else m["source"]
751
+
752
+ for i, ds in enumerate(ORDER):
753
+ P = pooled[ds]
754
+ for j, (mk, _) in enumerate(metrics):
755
+ ax = axs[i, j]
756
+ if ds == "ji2025_chili":
757
+ ax.set_facecolor(HILITE)
758
+ if mk in ("contrast_r", "deg") and ds == "immicro":
759
+ blank(ax, "healthy cohort: no contrast")
760
+ continue
761
+ hbars(ax, arms, lambda a: [P[POOLED_ARMS[a]][mk]], dots=False)
762
+ for a in arms:
763
+ rows.append({"figure": "sec09_fivefold", "dataset": ds, "metric": mk, "series": a,
764
+ "arm_file": POOLED_ARMS[a], "value": P[POOLED_ARMS[a]][mk],
765
+ "n_scored": P[POOLED_ARMS[a]]["n_scored"], "source": src(P[POOLED_ARMS[a]], mk)})
766
+ if mk == "coverage":
767
+ ref = P["zs__pseudo"]["coverage"]
768
+ ref_line(ax, ref, "pseudo", len(arms))
769
+ rows.append({"figure": "sec09_fivefold", "dataset": ds, "metric": mk, "series": "ref_pseudo",
770
+ "arm_file": "zs__pseudo", "value": ref, "source": P["zs__pseudo"]["source"]})
771
+ else:
772
+ m = P["real_lora__raw"]
773
+ ref = m["broadcast_r"] if mk == "contrast_r" else m["deg_broadcast"]
774
+ ref_line(ax, ref, "broadcast", len(arms))
775
+ rows.append({"figure": "sec09_fivefold", "dataset": ds, "metric": mk, "series": "ref_broadcast",
776
+ "arm_file": "real_lora__raw (raw real bulk)", "value": ref, "source": src(m, mk)})
777
+ if mk == "deg":
778
+ hi = max([ref] + [P[POOLED_ARMS[a]]["deg"] for a in arms] + [4.0])
779
+ ax.set_xlim(0, hi * 1.25)
780
+ ax.xaxis.set_major_locator(MaxNLocator(nbins=3, integer=True))
781
+ ax.tick_params(axis="x", labelsize=FS - 3)
782
+ for k, a in enumerate(arms):
783
+ v = P[POOLED_ARMS[a]]["deg"]
784
+ ax.text(v + hi * 0.03, k, f"{v:.0f}", va="center", ha="left", fontsize=FS - 3, color=SUB)
785
+ if mk == "contrast_r":
786
+ ax.axvline(0, color="#555555", lw=0.8, zorder=1)
787
+ ax.spines["left"].set_visible(False)
788
+ if ds == "ji2025_chili" and mk == "coverage":
789
+ v_zs = P["zs__cal"]["coverage"]
790
+ v_sc = P["pseudo_full__cal"]["coverage"]
791
+ v_lo = P["real_lora__raw"]["coverage"]
792
+ txt = ax.text(max(v_zs, v_sc) + 0.03, 0.5, f"baselines {baselines_text([v_zs, v_sc])}",
793
+ va="center", ha="left", fontsize=FS - 2, color="#5A5A5A")
794
+ ji_note = (txt, ax, P["zs__pseudo"]["coverage"])
795
+ ax.text(v_lo + 0.02, 2, f"{v_lo:.2f}", va="center", ha="left", fontsize=FS - 3, color=SUB)
796
+ n = P["real_lora__raw"]["n_scored"]
797
+ nd = int(tabi.loc[ds, "n_donors"])
798
+ if int(tabi.loc[ds, "n_rows"]) != int(n):
799
+ raise ValueError(f"{ds}: pooled n {n} != usable rows")
800
+ row_label(axs[i, 0], ROWNAME[ds], [f"n={n}" + (f" ({nd} donors)" if nd != n else "")])
801
+ shared_x(axs[:, 0], 0, 1.0, metrics[0][1], [0, 0.5, 1.0])
802
+ # the Ji annotation must end left of the pseudobulk reference line (checked on the final x scale)
803
+ txt, ax, ref = ji_note
804
+ fig.canvas.draw()
805
+ x1 = ax.transData.inverted().transform(txt.get_window_extent(fig.canvas.get_renderer()))[1, 0]
806
+ if x1 >= ref - 0.01:
807
+ raise ValueError(f"Ji annotation ends at {x1:.2f}, over the pseudobulk reference line at {ref:.2f}")
808
+ rvals = [r["value"] for r in rows if r["metric"] == "contrast_r"]
809
+ shared_x(axs[1:, 1], min(-0.1, np.floor(min(rvals) * 10) / 10), max(0.9, np.ceil(max(rvals) * 10) / 10),
810
+ metrics[1][1], [0, 0.4, 0.8])
811
+ axs[-1, 2].set_xlabel(metrics[2][1])
812
+ handles = [patch("zs_cal"), patch("sconly_cal"), patch("lora", LAB["lora_all"]), refh("pseudo"),
813
+ refh("broadcast")]
814
+ legend_bottom(fig, handles, ncol=3)
815
+ style.save(fig, "sec09_fivefold", FIGDIR)
816
+ pd.DataFrame(rows).to_csv(OUTDATA / "sec09_fivefold.csv", index=False, float_format="%.6g")
817
+ return rows
818
+
819
+
820
+ # ------------------------------------------------------------------------------------------
821
+ # Slide text: every keyword / footnote / quoted number is built here from the same data
822
+ # ------------------------------------------------------------------------------------------
823
+ BANNED = ("novel", "powerful", "robust", "state-of-the-art", "seamless", "leverage")
824
+
825
+
826
+ def n_words(s):
827
+ return sum(1 for t in s.split() if re.search(r"[A-Za-z0-9]", t))
828
+
829
+
830
+ def check_keywords(kws):
831
+ if len(kws) > 3:
832
+ raise ValueError(f"more than 3 keyword lines: {kws}")
833
+ for k in kws:
834
+ if n_words(k) > 7:
835
+ raise ValueError(f"keyword over 7 words: {k!r}")
836
+ if any(b in k.lower() for b in BANNED) or re.search(r"[가-힣]", k):
837
+ raise ValueError(f"banned word / Korean in keyword: {k!r}")
838
+ return kws
839
+
840
+
841
+ def names(dss):
842
+ return ", ".join(NAME[d] for d in dss)
843
+
844
+
845
+ def main():
846
+ FIGDIR.mkdir(parents=True, exist_ok=True)
847
+ OUTDATA.mkdir(parents=True, exist_ok=True)
848
+
849
+ tab = cohort_rows()
850
+ tab.to_csv(OUTDATA / "sec09_cohorts.csv", index=False)
851
+ fig_cohorts(tab)
852
+
853
+ few, status = fewpair()
854
+ info = {ds: draw_info(few, ds) for ds in ORDER}
855
+ pooled, calls = mf.load_pooled(SCORES)
856
+ fig_fewpair_cells(few, info)
857
+ fig_fewpair_disease(few, info)
858
+ fig_fivefold(pooled, tab)
859
+
860
+ used = status[status.status == "used"]
861
+ run_json = T / "runs" / "immicro" / "fewshot_n5" / "draw0" / "lora" / "RUN.json"
862
+ evidence(run_json, re.escape(CKPT)) # the few-pair LoRA runs start from the final checkpoint
863
+ steps = int(re.search(r'"fixed_steps": (\d+)', evidence(run_json, r'"fixed_steps": \d+')).group(1))
864
+ lora_r = re.search(r"LoRA r = (\d+)", evidence(README, r"LoRA r = \d+ \(1\.3 M")).group(1)
865
+ sampling = match_text(README, r"test donors only, 1,500 cells each, seed \d+, DDIM 50, EMA, Bernoulli read-out")
866
+ early = match_text(README, r"About 10 % of each fold's training donors are inner-validation, used only for early stopping")
867
+ pc_def = match_text(SCORE_FT, r"precision/coverage/density \(PCA-50 \+ k = 10 balls fitted on the scored donors' observed R1 cells\)")
868
+ pca_n = {int(jload(SCORES / ds / "fewshot_n5" / "draw0" / "summary.json")["reference"]["pca"]["n_components"])
869
+ for ds in ORDER}
870
+ if pca_n != {50}:
871
+ raise ValueError(f"PCA components differ from the footnote: {pca_n}")
872
+ ddef = jload(SCORES / "ji2025_chili" / "fewshot_n5" / "draw0" / "summary.json")["deg_definition"]
873
+ if not ("welch_bh_deg" in ddef["functions"] and ddef["top_n"] == 50 and len(ddef["types"]) == 5):
874
+ raise ValueError("DEG definition differs from the footnote")
875
+ n_types = len(ddef["types"])
876
+ base_src = f"{run_json}; {README}"
877
+ slides = []
878
+
879
+ # ---------------- slide a ----------------
880
+ tot_rows, tot_donors = int(tab.n_rows.sum()), int(tab.n_donors.sum())
881
+ n_all = int(tab.n_pairs_all.sum())
882
+ n_fail, n_bord, n_low = int(tab.n_identity_fail.sum()), int(tab.n_identity_borderline.sum()), int(tab.n_low_cells.sum())
883
+ ji = tab.set_index("dataset").loc["ji2025_chili"]
884
+ if not ji.bulk.startswith("whole blood"):
885
+ raise ValueError("Ji bulk label changed")
886
+ noflag = [NAME[d] for d in tab[~tab.identity_flag].dataset]
887
+ multi = [NAME[d] for d in tab[tab.n_rows != tab.n_donors].dataset]
888
+ kw_a = check_keywords([f"{tot_rows} paired samples, {tot_donors} donors",
889
+ "Only identity-pass pairs; donor-level splits",
890
+ "Ji bulk: whole blood, not PBMC"])
891
+ foot_a = (f"Usable pair = passed the pairing identity check and >= {int(tab.min_cells.iloc[0])} cells "
892
+ f"(fold >= 0 in data/<cohort>/folds.csv); dropped {n_fail} identity-fail, {n_bord} borderline and "
893
+ f"{n_low} low-cell pairs of {n_all}. {', '.join(noflag)}: no identity flag, all used. "
894
+ f"{', '.join(multi)}: several pairs per donor. Case vs control = samples in "
895
+ f"scores/<cohort>/pooled/summary.json. Giroux 'moderate' = GEO 'severe' (paper term). "
896
+ f"Labels: data/<cohort>/QC_REPORT.md; ImMicro: GEO GSE314922/GSE314416.")
897
+ num("a", f"{tot_rows} paired samples (sum of usable rows)", f"{DATA}/<cohort>/fewshot_n5/DRAWS.json (n_usable_rows)")
898
+ num("a", f"{tot_donors} donors (sum of usable donors)", f"{DATA}/<cohort>/fewshot_n5/DRAWS.json (n_usable_donors)")
899
+ num("a", f"dropped {n_fail} identity-fail, {n_bord} borderline, {n_low} < {int(tab.min_cells.iloc[0])} cells, of {n_all}",
900
+ f"{DATA}/<cohort>/features.npz (identity_pass, identity_check); samples.csv (n_cells); {PREPARE} (MIN_CELLS)")
901
+ for r in tab.itertuples():
902
+ v = f"{NAME[r.dataset]} {r.n_rows} pairs / {r.n_donors} donors"
903
+ s = r.n_rows_source
904
+ if r.case_label:
905
+ v += f"; {r.case_label} {int(r.n_case)} vs {r.control_label} {int(r.n_control)}"
906
+ if r.n_neither:
907
+ v += f" (+{r.n_neither} {r.neither_label}, neither)"
908
+ s += f"; {r.contrast_source}"
909
+ num("a", v, s)
910
+ slides.append({"title": "Five paired cohorts", "layout": "full",
911
+ "figures": [str(FIGDIR / "sec09_cohorts.png")], "keywords": kw_a, "footnote": foot_a,
912
+ "numbers": NUMS["a"]})
913
+
914
+ # ---------------- slide b ----------------
915
+ cmp_b = {mk: same_draw_compare(few, status, ORDER, mk, lower) for mk, lower in
916
+ (("coverage", False), ("precision", False), ("comp_l1", True), ("coverage_dm", False),
917
+ ("precision_dm", False))}
918
+ wins = {mk: sum(v["verdict"] == "lora" for v in c.values()) for mk, c in cmp_b.items()}
919
+ ncoh = {mk: len(c) for mk, c in cmp_b.items()}
920
+ if ncoh["coverage"] != len(ORDER):
921
+ raise ValueError("a cohort has no shared scSemiProfiler draw")
922
+ if wins["coverage"] == wins["precision"]:
923
+ kw_b1 = f"LoRA-5 > scSemi-5: coverage, precision {wins['coverage']}/{ncoh['coverage']}; L1 {wins['comp_l1']}/{ncoh['comp_l1']}"
924
+ else:
925
+ kw_b1 = (f"LoRA-5 > scSemi-5: coverage {wins['coverage']}/{ncoh['coverage']}, precision "
926
+ f"{wins['precision']}/{ncoh['precision']}; L1 {wins['comp_l1']}/{ncoh['comp_l1']}")
927
+ cov_mean = {a: [float(np.mean(few_vals(few, d, a, "coverage")[0])) for d in ORDER] for a in ("lora", "scsemi5")}
928
+ kw_b2 = (f"Coverage: LoRA-5 {min(cov_mean['lora']):.2f}–{max(cov_mean['lora']):.2f} vs scSemi-5 "
929
+ f"{min(cov_mean['scsemi5']):.2f}–{max(cov_mean['scsemi5']):.2f}")
930
+ l1t = {ds: l1_vs_zeroshot_per_donor(ds) for ds in ORDER}
931
+ gain = [d for d in ORDER if l1t[d]["p"] < 0.05 and l1t[d]["mean_diff"] < 0]
932
+ if not gain:
933
+ kw_b3 = "No composition gain vs zero-shot"
934
+ elif len(gain) < len(ORDER):
935
+ kw_b3 = f"Composition gain vs zero-shot: {names(gain)} only"
936
+ else:
937
+ kw_b3 = "Composition gain vs zero-shot: all cohorts"
938
+ kw_b = check_keywords([kw_b1, kw_b2, kw_b3])
939
+ l1_split = [d for d, v in cmp_b["comp_l1"].items() if v["verdict"] != "lora"]
940
+ dm_c = {a: [cmp_b["coverage_dm"][d][k] for d in ORDER] for a, k in (("lora", "lora"), ("scsemi5", "scsemi"))}
941
+ if wins["coverage_dm"] != wins["coverage"] or wins["precision_dm"] != wins["precision"]:
942
+ raise ValueError("depth-matched ranking differs from raw P/C: rewrite the 'same ranking' footnote")
943
+ others = [d for d in ORDER if d not in gain]
944
+ tr_all = [x for d in ORDER for x in info[d]["n_train"]]
945
+ missing = status[status.status != "used"]
946
+ miss_txt = ", ".join(f"{NAME[r.dataset]} draw{r.draw}" for r in missing.itertuples()) or "none"
947
+ ns_used, ns_all = len(used), len(status)
948
+ foot_b = (f"Base f01 6k·1x·E16 (EMA, DDIM 50) + LoRA r={lora_r}, {steps:,} steps. LoRA-5 / scSemi-5 = LoRA / "
949
+ f"scSemiProfiler trained on the same 5 donors ({min(tr_all)}–{max(tr_all)} pairs); test = all other usable "
950
+ f"pairs. scSemi-5 scored in a separate call, same test set and reference (sha-checked); {ns_used}/{ns_all} "
951
+ f"draws (missing: {miss_txt}). Verdict = better in >= 80% of shared draws "
952
+ f"(L1: {', '.join(f'{NAME[d]} {cmp_b['comp_l1'][d]['verdict']} {cmp_b['comp_l1'][d]['n_lora']}/{cmp_b['comp_l1'][d]['n']}' for d in l1_split)}). "
953
+ f"Depth-matched P/C: same ranking, coverage LoRA-5 {min(dm_c['lora']):.2f}–{max(dm_c['lora']):.2f} vs "
954
+ f"scSemi-5 {min(dm_c['scsemi5']):.2f}–{max(dm_c['scsemi5']):.2f}. L1 vs zero-shot: per-donor Wilcoxon, "
955
+ + (f"{names(gain)} p {', '.join(f'{l1t[d]['p']:.0e}' for d in gain)}; " if gain else "")
956
+ + (f"others p >= {min(l1t[d]['p'] for d in others):.2f}. " if others else "")
957
+ + "scANVI labels; P/C = PCA-50, k=10 balls. Scores: scores/<cohort>/fewshot_n5/.")
958
+ scs = f"{SCORES}/<cohort>/fewshot_n5/draw<j>/summary.json and draw<j>_scsemi5/summary.json"
959
+ for mk in ("coverage", "precision", "comp_l1", "coverage_dm", "precision_dm"):
960
+ c = cmp_b[mk]
961
+ num("b", f"LoRA-5 vs scSemi-5 {mk} (shared-draw means; LoRA-better draws/n; verdict): " +
962
+ "; ".join(f"{NAME[d]} {v['lora']:.3f} vs {v['scsemi']:.3f} ({v['n_lora']}/{v['n']}, {v['verdict']})"
963
+ for d, v in c.items()) + f" -> LoRA verdicts {wins[mk]}/{ncoh[mk]}", scs)
964
+ num("b", f"coverage cohort means over all draws: LoRA-5 " +
965
+ ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, cov_mean["lora"])) + "; scSemi-5 " +
966
+ ", ".join(f"{NAME[d]} {v:.3f}" for d, v in zip(ORDER, cov_mean["scsemi5"])), scs)
967
+ num("b", "LoRA-5 minus zero-shot-cal composition L1, per-donor Wilcoxon (draw-averaged): " +
968
+ "; ".join(f"{NAME[d]} {v['mean_diff']:+.3f}, n={v['n_donors']}, p={v['p']:.2g}" for d, v in l1t.items()),
969
+ f"{SCORES}/<cohort>/fewshot_n5/draw<j>/per_donor.csv; {DATA}/<cohort>/folds.csv")
970
+ num("b", "scSemiProfiler draws used / LoRA draws: " +
971
+ ", ".join(f"{NAME[d]} {int((used.dataset == d).sum())}/{n_draws(few, d, 'lora')}" for d in ORDER),
972
+ OUTDATA / "sec09_scsemi_status.csv")
973
+ num("b", "training pairs per draw: " + ", ".join(f"{NAME[d]} {info[d]['train']}" for d in ORDER) +
974
+ "; test pairs: " + ", ".join(f"{NAME[d]} {info[d]['test']}" for d in ORDER),
975
+ f"{DATA}/<cohort>/fewshot_n5/DRAWS.json (n_train_rows, n_test_rows)")
976
+ num("b", f"LoRA r = {lora_r}; {steps} fixed steps; base {CKPT}; sampling: {sampling}", base_src)
977
+ num("b", f"P/C definition: {pc_def}; PCA components in every summary.json = 50", SCORE_FT)
978
+ for ds in ORDER:
979
+ agg = jload(SCORES / ds / "fewshot_n5" / "aggregate.json")["lora5_vs_zs_cal_l1"]
980
+ extra("b", f"{ds} aggregate.json LoRA-5 vs zero-shot L1 Wilcoxon over donor-draw rows (pseudo-replicated; "
981
+ f"not quoted, replaced by the per-donor test)", f"{agg['mean_diff']:+.3f}, p {agg['wilcoxon_p']:.2g}",
982
+ SCORES / ds / "fewshot_n5" / "aggregate.json")
983
+ slides.append({"title": "5 donors: LoRA vs scSemiProfiler — cells", "layout": "full",
984
+ "figures": [str(FIGDIR / "sec09_fewpair_cells.png")], "keywords": kw_b, "footnote": foot_b,
985
+ "numbers": NUMS["b"]})
986
+
987
+ # ---------------- slide c ----------------
988
+ cmp_r = same_draw_compare(few, status, DISEASE, "contrast_r")
989
+ cmp_d = same_draw_compare(few, status, DISEASE, "deg", min_margin=1.0)
990
+ deg_l = [d for d, v in cmp_d.items() if v["verdict"] == "lora"]
991
+ deg_tie = [d for d, v in cmp_d.items() if v["verdict"] == "tie"]
992
+ deg_other = [d for d, v in cmp_d.items() if v["verdict"] not in ("lora", "tie")]
993
+ near0 = [d for d in deg_tie if max(cmp_d[d]["lora"], cmp_d[d]["scsemi"]) < 1.0]
994
+ kw_c1 = f"Top-50 DEG: LoRA-5 higher {len(deg_l)}/{len(cmp_d)}"
995
+ if near0:
996
+ kw_c1 += f"; {names(near0)} ~0"
997
+ if [d for d in deg_tie if d not in near0]:
998
+ kw_c1 += f"; {names([d for d in deg_tie if d not in near0])} tied"
999
+ if deg_other:
1000
+ kw_c1 += f"; {names(deg_other)} not"
1001
+ r_s = [d for d, v in cmp_r.items() if v["verdict"] == "scsemi"]
1002
+ r_split = [d for d, v in cmp_r.items() if v["verdict"] in ("split", "tie")]
1003
+ r_l = [d for d, v in cmp_r.items() if v["verdict"] == "lora"]
1004
+ parts = []
1005
+ if r_s:
1006
+ parts.append(f"scSemi-5 wins {names(r_s)}")
1007
+ if r_split:
1008
+ parts.append(f"{names(r_split)} split")
1009
+ kw_c2 = ("logFC r: " + "; ".join(parts)) if parts else f"logFC r: LoRA-5 higher {len(r_l)}/{len(cmp_r)}"
1010
+ arms3 = ("zs_cal", "scsemi5", "lora")
1011
+
1012
+ def arm_mean(ds, a, mk):
1013
+ v = [x for x in few_vals(few, ds, a, mk)[0] if not np.isnan(x)]
1014
+ return float(np.mean(v)) if v else np.nan
1015
+
1016
+ bc_all = [d for d in DISEASE
1017
+ if few_ref(few, d, "broadcast", "contrast_r")[0] > np.nanmax([arm_mean(d, a, "contrast_r") for a in arms3])
1018
+ and few_ref(few, d, "broadcast", "deg")[0] > np.nanmax([arm_mean(d, a, "deg") for a in arms3])]
1019
+ kw_c3 = f"{names(bc_all)}: real-bulk broadcast beats all arms" if bc_all else "Every cohort: some arm beats broadcast"
1020
+ kw_c = check_keywords([kw_c1, kw_c2, kw_c3])
1021
+ dmax = {d: sorted({int(x) for x in few[(few.dataset == d) & (few.arm == "lora")]["deg_max"].dropna()}) for d in DISEASE}
1022
+ small = [d for d in DISEASE if subjects_text(info[d])]
1023
+ foot_c = (f"Same draws and verdict rule as the previous slide; DEG tie = half the draws equal or mean gap < 1 gene. "
1024
+ f"logFC r = mean over T/B/Mono/NK of case-vs-control log2FC r (generated vs observed); top-50 DEG = "
1025
+ f"Welch+BH overlap summed over {n_types} types (max 250; "
1026
+ + ", ".join(f"{NAME[d]} {rng(dmax[d])}" for d in DISEASE if dmax[d] != [250]) + " per draw). "
1027
+ + "".join(f"{NAME[d]} test = {subjects_text(info[d])} subjects per draw. " for d in small)
1028
+ + "Broadcast = the input real bulk's own logFC. Scores: scores/<cohort>/fewshot_n5/draw<j>{,_scsemi5}/.")
1029
+ srcc = f"{SCORES}/<cohort>/fewshot_n5/draw<j>{{,_scsemi5}}/summary.json and contrast.csv"
1030
+ num("c", "Top-50 DEG LoRA-5 vs scSemi-5 (shared-draw means; LoRA-better / tied draws; verdict): " +
1031
+ "; ".join(f"{NAME[d]} {v['lora']:.1f} vs {v['scsemi']:.1f} ({v['n_lora']}/{v['n']}, {v['n_tie']} tied, {v['verdict']})"
1032
+ for d, v in cmp_d.items()), srcc)
1033
+ num("c", "logFC r LoRA-5 vs scSemi-5 (shared-draw means; LoRA-better draws; verdict): " +
1034
+ "; ".join(f"{NAME[d]} {v['lora']:.3f} vs {v['scsemi']:.3f} ({v['n_lora']}/{v['n']}, {v['verdict']})"
1035
+ for d, v in cmp_r.items()), srcc)
1036
+ for d in bc_all:
1037
+ num("c", f"{NAME[d]} broadcast logFC r {few_ref(few, d, 'broadcast', 'contrast_r')[0]:.3f} vs best arm "
1038
+ f"{max(arm_mean(d, a, 'contrast_r') for a in arms3):.3f}; broadcast DEG "
1039
+ f"{few_ref(few, d, 'broadcast', 'deg')[0]:.1f} vs best arm {max(arm_mean(d, a, 'deg') for a in arms3):.1f} "
1040
+ f"(means over all draws)", f"{SCORES}/{d}/fewshot_n5/draw<j>{{,_scsemi5}}/summary.json")
1041
+ num("c", "DEG maximum per draw: " + ", ".join(f"{NAME[d]} {rng(dmax[d])}" for d in DISEASE),
1042
+ f"{SCORES}/<cohort>/fewshot_n5/draw<j>/summary.json (deg_top50_max)")
1043
+ for d in small:
1044
+ num("c", f"{NAME[d]} test subjects per draw: {subjects_text(info[d])} ({CONTRAST[d]['case']} vs "
1045
+ f"{CONTRAST[d]['control']}); test pairs {info[d]['test']}",
1046
+ f"{info[d]['source']} (train_donors); {DATA / d / 'folds.csv'} (group)")
1047
+ slides.append({"title": "5 donors: LoRA vs scSemiProfiler — disease signal", "layout": "figure_keywords",
1048
+ "figures": [str(FIGDIR / "sec09_fewpair_disease.png")], "keywords": kw_c, "footnote": foot_c,
1049
+ "numbers": NUMS["c"]})
1050
+
1051
+ # ---------------- slide d ----------------
1052
+ L = {d: pooled[d]["real_lora__raw"] for d in ORDER}
1053
+ B = {d: [pooled[d]["zs__cal"], pooled[d]["pseudo_full__cal"]] for d in ORDER}
1054
+ best = {mk: [d for d in (ORDER if mk == "coverage" else DISEASE) if L[d][mk] >= max(b[mk] for b in B[d])]
1055
+ for mk in ("coverage", "contrast_r", "deg")}
1056
+ kw_d1 = f"LoRA tops coverage {len(best['coverage'])}/{len(ORDER)}, logFC r {len(best['contrast_r'])}/{len(DISEASE)}"
1057
+ jb = baselines_text([b["coverage"] for b in B["ji2025_chili"]])
1058
+ kw_d2 = f"Ji whole blood: baselines {jb}, LoRA {L['ji2025_chili']['coverage']:.2f}"
1059
+ bc_win = [d for d in DISEASE if L[d]["broadcast_r"] > L[d]["contrast_r"]]
1060
+ kw_d3 = ("; ".join(f"{NAME[d]}: broadcast r {L[d]['broadcast_r']:.2f} > LoRA {L[d]['contrast_r']:.2f}" for d in bc_win)
1061
+ if bc_win else "LoRA above broadcast in every cohort")
1062
+ kw_d = check_keywords([kw_d1, kw_d2, kw_d3])
1063
+ foot_d = (f"Donor-level 5-fold CV; each pair scored once, by the fold model that never trained on its donor "
1064
+ f"(one pooled call per cohort). LoRA r={lora_r} on all training donors' real bulk, early stop on "
1065
+ f"inner-val donors; sc-only = full fine-tune on training donors' sc pseudobulk, calibrated input. "
1066
+ f"Base f01 6k·1x·E16. Top-50 DEG: LoRA best {len(best['deg'])}/{len(DISEASE)}. Sepsis DEG from pooled_deg. "
1067
+ f"Scores: scores/<cohort>/pooled/summary.json.")
1068
+ psrc = f"{SCORES}/<cohort>/pooled/summary.json (Sepsis DEG: {SCORES}/ye2026_sepsis/pooled_deg/summary.json)"
1069
+ num("d", f"LoRA best of 3 arms: coverage {len(best['coverage'])}/{len(ORDER)}, logFC r "
1070
+ f"{len(best['contrast_r'])}/{len(DISEASE)}, top-50 DEG {len(best['deg'])}/{len(DISEASE)}", psrc)
1071
+ num("d", f"Ji coverage: zero-shot cal {B['ji2025_chili'][0]['coverage']:.3f}, sc-only "
1072
+ f"{B['ji2025_chili'][1]['coverage']:.3f}, LoRA {L['ji2025_chili']['coverage']:.3f}",
1073
+ SCORES / "ji2025_chili" / "pooled" / "summary.json")
1074
+ for d in bc_win:
1075
+ num("d", f"{NAME[d]} logFC r: broadcast {L[d]['broadcast_r']:.3f} vs LoRA {L[d]['contrast_r']:.3f}; "
1076
+ f"DEG broadcast {L[d]['deg_broadcast']:.0f} vs LoRA {L[d]['deg']:.0f}", SCORES / d / "pooled" / "summary.json")
1077
+ num("d", "LoRA logFC r vs broadcast: " + ", ".join(f"{NAME[d]} {L[d]['contrast_r']:.3f} vs {L[d]['broadcast_r']:.3f}"
1078
+ for d in DISEASE), psrc)
1079
+ num("d", "Pooled n (pairs / donors): " + ", ".join(f"{NAME[r.dataset]} {r.n_rows}/{r.n_donors}" for r in tab.itertuples()),
1080
+ f"{SCORES}/<cohort>/pooled/summary.json (n_donors); {DATA}/<cohort>/fewshot_n5/DRAWS.json")
1081
+ num("d", f"early stopping: {early}", README)
1082
+ for d in ORDER:
1083
+ for a, f in POOLED_ARMS.items():
1084
+ extra("d", f"{d} pooled {a} coverage / r / DEG",
1085
+ f"{pooled[d][f]['coverage']:.3f} / {pooled[d][f]['contrast_r']:.3f} / {pooled[d][f]['deg']:.0f}",
1086
+ pooled[d][f]["source"])
1087
+ slides.append({"title": "All pairs, 5-fold", "layout": "full", "figures": [str(FIGDIR / "sec09_fivefold.png")],
1088
+ "keywords": kw_d, "footnote": foot_d, "numbers": NUMS["d"]})
1089
+
1090
+ spec = {"section": "09", "slides": slides, "scripts": [str(SCRIPT)],
1091
+ "generated_from": "tools/sec09_paired_validation.py (rerun to refresh; do not edit by hand)",
1092
+ "scsemi_draws_used": f"{ns_used}/{ns_all}"}
1093
+ (OUTDATA / "sec09_slide_text.json").write_text(json.dumps(spec, indent=1, ensure_ascii=False))
1094
+ flat = [{"slide": k, "item": "quoted on slide", "value": n["value"], "source": n["source"]}
1095
+ for k in "abcd" for n in NUMS[k]] + EXTRA
1096
+ pd.DataFrame(flat).to_csv(OUTDATA / "sec09_quoted_numbers.csv", index=False)
1097
+
1098
+ print("scSemiProfiler draws used per dataset:",
1099
+ {NAME[d]: f"{int((used.dataset == d).sum())}/{n_draws(few, d, 'lora')}" for d in ORDER})
1100
+ for s in slides:
1101
+ print(f"\n== {s['title']} [{s['layout']}]")
1102
+ for k in s["keywords"]:
1103
+ print(" *", k, f"({n_words(k)} words)")
1104
+ print(" footnote:", s["footnote"])
1105
+ for n in s["numbers"]:
1106
+ print(" #", n["value"])
1107
+ for p in sorted(FIGDIR.glob("sec09_*.png")):
1108
+ print("wrote", p)
1109
+ return 0
1110
+
1111
+
1112
+ if __name__ == "__main__":
1113
+ sys.exit(main())