junidude14 commited on
Commit
c9009bb
·
verified ·
1 Parent(s): bb5b6ee

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/figures/make_figures.py ADDED
@@ -0,0 +1,1271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Paper figures for the paired bulk -> single-cell fine-tuning benchmark.
3
+
4
+ CPU only. Never imports torch or any CUDA library. Every plotted number is read
5
+ from score files written by tools/score_ft.py (summary.json, per_donor.csv,
6
+ contrast.csv) or from runs/<ds>/fold<k>/<arm>/RUN.json.
7
+
8
+ Outputs (in this directory):
9
+ fig1_fewpair.{png,pdf} few-pair scenario, 5 datasets
10
+ fig2_fivefold.{png,pdf} 5-fold CV, pooled scoring, 5 datasets
11
+ fig3_learning_curve.{png,pdf} LoRA learning curve, ImMicro + sepsis
12
+ figS1_celltype_contrast.{png,pdf}
13
+ figS2_k_augmentation.{png,pdf}
14
+ source_data/<figure>_<panel>.csv one CSV per panel, with source file per row
15
+ source_data/scsemi_status.csv which scSemiProfiler draws were found / used
16
+ source_data/consistency_checks.csv plotted values vs the pipeline aggregate.json
17
+ FIGURES.md figure legends + takeaways (numbers filled from data)
18
+
19
+ Re-run (idempotent; picks up any new scores/<ds>/fewshot_n5/draw<j>_scsemi5/):
20
+ python3 figures/make_figures.py
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import datetime as _dt
26
+ import json
27
+ import os
28
+ import re
29
+ import sys
30
+ import warnings
31
+ from pathlib import Path
32
+
33
+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only; make any accidental CUDA use impossible
34
+
35
+ import numpy as np
36
+ import pandas as pd
37
+ import matplotlib
38
+
39
+ matplotlib.use("Agg")
40
+ import matplotlib.pyplot as plt # noqa: E402
41
+ from matplotlib.lines import Line2D # noqa: E402
42
+ from matplotlib.patches import Patch # noqa: E402
43
+ from scipy.stats import wilcoxon # noqa: E402
44
+
45
+ HERE = Path(__file__).resolve().parent
46
+ T = HERE.parent
47
+
48
+ # --------------------------------------------------------------------------------------
49
+ # Constants: datasets, arms, colours (Okabe-Ito, colour-blind safe), line styles
50
+ # --------------------------------------------------------------------------------------
51
+ DATASETS = ["immicro", "ye2026_sepsis", "ji2025_chili", "giroux2022", "imperial_eskd"]
52
+ DS_LABEL = {
53
+ "immicro": "ImMicro",
54
+ "ye2026_sepsis": "Sepsis",
55
+ "ji2025_chili": "Ji",
56
+ "giroux2022": "Giroux",
57
+ "imperial_eskd": "Imperial",
58
+ }
59
+ DS_LONG = {
60
+ "immicro": "ImMicro (healthy PBMC)",
61
+ "ye2026_sepsis": "Ye 2026 sepsis (sepsis vs control)",
62
+ "ji2025_chili": "Ji 2025 ChILI (whole-blood bulk; liver injury vs ICI controls)",
63
+ "giroux2022": "Giroux 2022 (severe vs mild COVID)",
64
+ "imperial_eskd": "Imperial ESKD (COVID+ vs COVID- haemodialysis)",
65
+ }
66
+ DISEASE_DS = [d for d in DATASETS if d != "immicro"]
67
+ CELLTYPES = ["T cell", "B cell", "Monocyte", "NK cell"]
68
+ CT_SHORT = {"T cell": "T", "B cell": "B", "Monocyte": "Mono", "NK cell": "NK"}
69
+
70
+ # canonical arm key -> (legend label, colour)
71
+ STYLE = {
72
+ "zs_raw": ("Zero-shot, raw bulk", "#A6CBE3"),
73
+ "zs_cal": ("Zero-shot, paired calibration", "#0072B2"),
74
+ "zs_len": ("Zero-shot, exon-length-corrected bulk", "#DDCC77"),
75
+ "scsemi5": ("scSemiProfiler, 5 pairs", "#E69F00"),
76
+ "lora": ("LoRA fine-tune", "#D55E00"),
77
+ "sconly_cal": ("sc-only fine-tune + calibration", "#CC79A7"),
78
+ "lora_multik": ("LoRA + multi-K bulk", "#009E73"),
79
+ "lora_recipe": ("LoRA + pretraining recipes", "#F0E442"),
80
+ "broadcast": ("Real-bulk broadcast", "#9A9A9A"),
81
+ }
82
+ REF = {
83
+ "pseudo": dict(ls=(0, (4, 2)), color="#1A1A1A", lw=0.9, label="Zero-shot from sc pseudobulk"),
84
+ "broadcast": dict(ls=(0, (1, 1.3)), color="#000000", lw=1.1, label="Real-bulk broadcast"),
85
+ "null": dict(ls=(0, (5, 1.5, 1, 1.5)), color="#8C8C8C", lw=0.8, label="Cohort-mean null"),
86
+ }
87
+ # file arm names -> canonical keys
88
+ FEW_ARMS = {"zs_raw": "zs_raw", "zs_cal": "zs_cal", "scsemi5": "scsemi5", "lora5": "lora", "zs_pseudo": "pseudo"}
89
+ POOLED_ARMS = {
90
+ "zs__raw": "zs_raw",
91
+ "zs__cal": "zs_cal",
92
+ "zs__pseudo": "pseudo",
93
+ "real_lora__raw": "lora",
94
+ "pseudo_full__cal": "sconly_cal",
95
+ "lora_multik__raw": "lora_multik",
96
+ "lora_recipe__raw": "lora_recipe",
97
+ }
98
+ LC_N = [5, 10, 20, 40]
99
+ POOLED_DEG_DIFFS: list[dict] = []
100
+ SCORES_ROOT = T / "scores" # overridden by --scores-root # sepsis pooled vs pooled_deg differences below tolerance (logged)
101
+
102
+ METRIC_LABEL = {
103
+ "comp_l1": "Composition L1 ↓",
104
+ "coverage": "Coverage ↑",
105
+ "precision": "Precision ↑",
106
+ "contrast_r": "Disease logFC r ↑",
107
+ "deg": "Top-50 DEG ↑",
108
+ }
109
+ NOTE_NO_CONTRAST = "healthy\ncohort:\nno contrast"
110
+
111
+ # --------------------------------------------------------------------------------------
112
+ # Style
113
+ # --------------------------------------------------------------------------------------
114
+ FS = 6.5 # base font size (pt) at print size
115
+ plt.rcParams.update(
116
+ {
117
+ "font.family": "sans-serif",
118
+ "font.sans-serif": ["Arial", "Liberation Sans", "DejaVu Sans"],
119
+ "font.size": FS,
120
+ "axes.labelsize": FS,
121
+ "axes.titlesize": FS + 0.5,
122
+ "xtick.labelsize": FS - 0.5,
123
+ "ytick.labelsize": FS - 0.5,
124
+ "legend.fontsize": FS - 0.5,
125
+ "axes.linewidth": 0.6,
126
+ "xtick.major.width": 0.6,
127
+ "ytick.major.width": 0.6,
128
+ "xtick.major.size": 2.5,
129
+ "ytick.major.size": 2.5,
130
+ "axes.spines.top": False,
131
+ "axes.spines.right": False,
132
+ "pdf.fonttype": 42,
133
+ "ps.fonttype": 42,
134
+ "savefig.dpi": 300,
135
+ "figure.dpi": 150,
136
+ }
137
+ )
138
+ SINGLE_COL_IN = 3.5 # 89 mm
139
+
140
+
141
+ # --------------------------------------------------------------------------------------
142
+ # Loading
143
+ # --------------------------------------------------------------------------------------
144
+ def relp(path) -> str:
145
+ """Path relative to the task dir when inside it (portable source column), else absolute."""
146
+ path = Path(path)
147
+ try:
148
+ return str(path.resolve().relative_to(T))
149
+ except ValueError:
150
+ return str(path)
151
+
152
+
153
+ class Call:
154
+ """One score_ft.py scoring call (one output directory)."""
155
+
156
+ def __init__(self, path: Path):
157
+ self.path = Path(path)
158
+ self.summary = json.loads((self.path / "summary.json").read_text())
159
+ cpath = self.path / "contrast.csv"
160
+ self.contrast = pd.read_csv(cpath) if cpath.exists() else None
161
+ self._per_donor = None
162
+
163
+ @property
164
+ def per_donor(self) -> pd.DataFrame:
165
+ if self._per_donor is None:
166
+ self._per_donor = pd.read_csv(self.path / "per_donor.csv")
167
+ return self._per_donor
168
+
169
+ @property
170
+ def arms(self):
171
+ return list(self.summary["arms"])
172
+
173
+ @property
174
+ def donors(self):
175
+ return list(self.summary["donors"])
176
+
177
+ @property
178
+ def contrast_enabled(self) -> bool:
179
+ return bool(self.summary.get("contrast_definition", {}).get("enabled", False))
180
+
181
+ @property
182
+ def deg_enabled(self) -> bool:
183
+ return bool(self.summary.get("deg_definition", {}).get("enabled", False))
184
+
185
+ def rel(self, name="summary.json") -> str:
186
+ return relp(self.path / name)
187
+
188
+
189
+ def arm_metrics(call: Call, arm: str) -> dict:
190
+ """All plotted metrics for one arm of one scoring call, with consistency checks."""
191
+ h = call.summary["headline"][arm]
192
+ out = {
193
+ "comp_l1": float(h["comp_l1"]),
194
+ "null": float(h["comp_l1_obs_loo_null"]),
195
+ "precision": float(h["precision"]),
196
+ "coverage": float(h["coverage"]),
197
+ "n_scored": int(call.summary["n_donors"]),
198
+ "contrast_r": np.nan,
199
+ "broadcast_r": np.nan,
200
+ "deg": np.nan,
201
+ "deg_broadcast": np.nan,
202
+ "deg_max": np.nan,
203
+ "r_type": {},
204
+ "bc_type": {},
205
+ }
206
+ if call.contrast_enabled and call.contrast is not None:
207
+ c = call.contrast
208
+ c = c[(c["arm"] == arm) & (c["statistic"] == "mean_cp10k") & (c["celltype"].isin(CELLTYPES))]
209
+ c = c.set_index("celltype")
210
+ if set(c.index) != set(CELLTYPES):
211
+ raise ValueError(f"{call.path}: arm {arm} lacks mean_cp10k rows for {set(CELLTYPES) - set(c.index)}")
212
+ c = c.loc[CELLTYPES]
213
+ out["r_type"] = c["r_generated"].astype(float).to_dict()
214
+ out["bc_type"] = c["r_broadcast"].astype(float).to_dict()
215
+ out["contrast_r"] = float(np.mean(c["r_generated"]))
216
+ out["broadcast_r"] = float(np.mean(c["r_broadcast"]))
217
+ hr = h.get("contrast_mean_cp10k_r_gen")
218
+ if hr is not None and abs(hr - out["contrast_r"]) > 1e-9:
219
+ raise ValueError(f"{call.path}: {arm} contrast mean {out['contrast_r']} != headline {hr}")
220
+ if call.deg_enabled and h.get("deg_top50_sum") is not None:
221
+ out["deg"] = float(h["deg_top50_sum"])
222
+ out["deg_broadcast"] = float(h["deg_top50_sum_broadcast"])
223
+ out["deg_max"] = float(h.get("deg_top50_max", np.nan))
224
+ if call.contrast is not None:
225
+ d = call.contrast
226
+ d = d[(d["arm"] == arm) & (d["statistic"] == "welch_top50_deg")]
227
+ if len(d) and abs(d["top50_overlap"].sum() - out["deg"]) > 1e-9:
228
+ raise ValueError(f"{call.path}: {arm} DEG rows sum {d['top50_overlap'].sum()} != headline {out['deg']}")
229
+ return out
230
+
231
+
232
+ def across_donor_r(call: Call, arm: str, celltype: str) -> float:
233
+ """Pearson r across scored units of generated vs observed fraction of one cell type."""
234
+ d = call.per_donor
235
+ d = d[d["arm"] == arm]
236
+ g, o = d[f"gen_{celltype}"].astype(float), d[f"obs_{celltype}"].astype(float)
237
+ return float(np.corrcoef(g, o)[0, 1])
238
+
239
+
240
+ def draw_dirs(ds_root: Path):
241
+ out = []
242
+ for p in sorted(ds_root.glob("draw*")):
243
+ m = re.fullmatch(r"draw(\d+)", p.name)
244
+ if m and (p / "summary.json").exists():
245
+ out.append((int(m.group(1)), p))
246
+ return sorted(out)
247
+
248
+
249
+ # --------------------------------------------------------------------------------------
250
+ # Source-data bookkeeping
251
+ # --------------------------------------------------------------------------------------
252
+ class Sources:
253
+ def __init__(self, outdir: Path):
254
+ self.dir = outdir / "source_data"
255
+ self.dir.mkdir(parents=True, exist_ok=True)
256
+ self.written = []
257
+
258
+ def write(self, name: str, rows: list[dict]):
259
+ """<name>.csv with every panel (column `panel`), plus <name>/panel_<id>.csv per panel."""
260
+ df = pd.DataFrame(rows)
261
+ p = self.dir / f"{name}.csv"
262
+ df.to_csv(p, index=False, float_format="%.6g")
263
+ self.written.append(p)
264
+ if "panel" in df.columns and len(df):
265
+ sub = self.dir / name
266
+ sub.mkdir(exist_ok=True)
267
+ for old in sub.glob("panel_*.csv"):
268
+ old.unlink()
269
+ for panel, g in df.groupby("panel", sort=True):
270
+ g.dropna(axis=1, how="all").to_csv(sub / f"panel_{panel}.csv", index=False, float_format="%.6g")
271
+ return df
272
+
273
+
274
+ def rows_long(panel, dataset, series, kind, value, source, draw="", n="", extra=None):
275
+ r = {"panel": panel, "dataset": dataset, "series": series, "kind": kind, "draw": draw,
276
+ "value": value, "n": n, "source": source}
277
+ if extra:
278
+ r.update(extra)
279
+ return r
280
+
281
+
282
+ # --------------------------------------------------------------------------------------
283
+ # Data assembly
284
+ # --------------------------------------------------------------------------------------
285
+ def load_fewpair(scores_root: Path):
286
+ """Per-draw metrics for the few-pair scenario, plus scSemiProfiler status."""
287
+ recs, status = [], []
288
+ for ds in DATASETS:
289
+ root = scores_root / ds / "fewshot_n5"
290
+ for j, p in draw_dirs(root):
291
+ call = Call(p)
292
+ per = {}
293
+ for farm, key in FEW_ARMS.items():
294
+ if farm == "scsemi5" or farm not in call.arms:
295
+ continue
296
+ per[key] = (arm_metrics(call, farm), call.rel())
297
+ # real-bulk broadcast = the raw real-bulk condition (lora5 and zs_raw share it)
298
+ bc_l, bc_z = per["lora"][0], per["zs_raw"][0]
299
+ for k in ("broadcast_r", "deg_broadcast"):
300
+ if not (np.isnan(bc_l[k]) and np.isnan(bc_z[k])) and abs(bc_l[k] - bc_z[k]) > 1e-9:
301
+ raise ValueError(f"{p}: {k} differs between lora5 and zs_raw conditions")
302
+ sc_dir = root / f"draw{j}_scsemi5"
303
+ st = {"dataset": ds, "draw": j, "dir": relp(sc_dir), "status": "missing", "reason": ""}
304
+ if (sc_dir / "summary.json").exists():
305
+ try:
306
+ sc = Call(sc_dir)
307
+ reasons = []
308
+ if "scsemi5" not in sc.arms:
309
+ reasons.append(f"arm scsemi5 not in {sc.arms}")
310
+ if set(sc.donors) != set(call.donors):
311
+ reasons.append(f"donor set differs ({len(sc.donors)} vs {len(call.donors)})")
312
+ if sc.summary["reference"]["reference_sha256"] != call.summary["reference"]["reference_sha256"]:
313
+ reasons.append("reference sha differs")
314
+ if not sc.summary.get("per_arm", {}).get("scsemi5", {}).get("receipt_verified", False):
315
+ reasons.append("receipt not verified")
316
+ if reasons:
317
+ st.update(status="rejected", reason="; ".join(reasons))
318
+ else:
319
+ per["scsemi5"] = (arm_metrics(sc, "scsemi5"), sc.rel())
320
+ st.update(status="used")
321
+ except Exception as e: # incomplete/partial output: report, never crash
322
+ st.update(status="rejected", reason=f"unreadable: {e}")
323
+ status.append(st)
324
+ for key, (m, src) in per.items():
325
+ recs.append({"dataset": ds, "draw": j, "arm": key, "source": src, **m})
326
+ df = pd.DataFrame(recs)
327
+ return df, pd.DataFrame(status)
328
+
329
+
330
+ def load_pooled(scores_root: Path):
331
+ """Pooled 5-fold metrics (one scoring call per dataset over all donors)."""
332
+ out, calls = {}, {}
333
+ for ds in DATASETS:
334
+ call = Call(scores_root / ds / "pooled")
335
+ calls[ds] = call
336
+ res = {}
337
+ for farm in call.arms:
338
+ res[farm] = arm_metrics(call, farm)
339
+ res[farm]["source"] = call.rel()
340
+ if ds == "ye2026_sepsis": # DEG from pooled_deg; every other metric must agree with pooled
341
+ deg_call = Call(scores_root / ds / "pooled_deg")
342
+ calls[ds + "__deg"] = deg_call
343
+ for farm in call.arms:
344
+ if farm not in deg_call.arms:
345
+ continue
346
+ md = arm_metrics(deg_call, farm)
347
+ # Same NPZs and reference; precision/coverage can differ by a single cell between two
348
+ # scoring runs (k-NN tie order), so allow 1e-3 and log it. Non-DEG metrics come from `pooled`.
349
+ for k in ("comp_l1", "precision", "coverage", "contrast_r", "broadcast_r"):
350
+ if np.isnan(md[k]) and np.isnan(res[farm][k]):
351
+ continue
352
+ d = abs(md[k] - res[farm][k])
353
+ if d > 1e-3:
354
+ raise ValueError(f"sepsis pooled vs pooled_deg differ on {farm} {k} by {d}")
355
+ if d > 1e-9:
356
+ POOLED_DEG_DIFFS.append({"arm": farm, "metric": k, "pooled": res[farm][k],
357
+ "pooled_deg": md[k], "abs_diff": d})
358
+ res[farm]["deg"] = md["deg"]
359
+ res[farm]["deg_broadcast"] = md["deg_broadcast"]
360
+ res[farm]["deg_max"] = md["deg_max"]
361
+ res[farm]["deg_source"] = deg_call.rel()
362
+ # 2026-10-02: zero-pair point of the learning curve, exon-length-corrected bulk (tools/build_tpm_zeroshot.py),
363
+ # scored in its own call over the same donors and reference cells; its zs__raw arm must reproduce `pooled`
364
+ lp = scores_root / ds / "zeroshot_tpm_20261002" / "pooled"
365
+ if (lp / "summary.json").exists():
366
+ lcall = Call(lp)
367
+ calls[ds + "__len"] = lcall
368
+ chk = arm_metrics(lcall, "zs__raw")
369
+ for k in ("comp_l1", "precision", "coverage"):
370
+ if abs(chk[k] - res["zs__raw"][k]) > 1e-3:
371
+ raise ValueError(f"{ds} zero-shot raw differs between pooled and the length-corrected call: {k}")
372
+ res["zs__len"] = arm_metrics(lcall, "zs__len")
373
+ res["zs__len"]["source"] = lcall.rel()
374
+ res["zs__len"]["deg_source"] = lcall.rel()
375
+ out[ds] = res
376
+ return out, calls
377
+
378
+
379
+ def load_steps(runs_root: Path, ds: str):
380
+ rows = []
381
+ for k in range(5):
382
+ for arm in [f"lora_n{n}" for n in LC_N] + ["real_lora"]:
383
+ p = runs_root / ds / f"fold{k}" / arm / "RUN.json"
384
+ if not p.exists():
385
+ continue
386
+ r = json.loads(p.read_text())
387
+ rows.append({
388
+ "dataset": ds, "fold": k, "arm": arm,
389
+ "n_train": len(r.get("train_rows", [])),
390
+ "n_inner_val": len(r.get("inner_val_rows", []) or []),
391
+ "selected_step": r.get("selected_step"),
392
+ "max_steps": r.get("max_steps"),
393
+ "steps_run": r.get("steps_run"),
394
+ "source": relp(p),
395
+ })
396
+ return pd.DataFrame(rows)
397
+
398
+
399
+ def load_fewshot_runs(runs_root: Path):
400
+ """Few-pair LoRA RUN.json files present on this host (Imperial runs live on server_2)."""
401
+ rows = []
402
+ for ds in DATASETS:
403
+ for p in sorted((runs_root / ds / "fewshot_n5").glob("draw*/lora/RUN.json")):
404
+ r = json.loads(p.read_text())
405
+ rows.append({"dataset": ds, "draw": p.parent.parent.name, "steps_run": r.get("steps_run"),
406
+ "selected_step": r.get("selected_step"), "n_train_rows": len(r.get("train_rows", [])),
407
+ "source": relp(p)})
408
+ return pd.DataFrame(rows)
409
+
410
+
411
+ # --------------------------------------------------------------------------------------
412
+ # Drawing helpers
413
+ # --------------------------------------------------------------------------------------
414
+ def fmt_n(vals):
415
+ vals = sorted(set(int(v) for v in vals))
416
+ return f"{vals[0]}" if len(vals) == 1 else f"{vals[0]}–{vals[-1]}"
417
+
418
+
419
+ def ref_segment(ax, x0, x1, y, kind):
420
+ if y is None or np.isnan(y):
421
+ return
422
+ s = REF[kind]
423
+ ax.plot([x0, x1], [y, y], ls=s["ls"], color=s["color"], lw=s["lw"], zorder=6, solid_capstyle="butt")
424
+
425
+
426
+ def bar_with_points(ax, x, w, vals, color, show_dots=True, err=True):
427
+ vals = np.asarray([v for v in vals if not np.isnan(v)], float)
428
+ if len(vals) == 0:
429
+ return None
430
+ m = float(vals.mean())
431
+ sd = float(vals.std(ddof=1)) if len(vals) > 1 else 0.0
432
+ ax.bar(x, m, width=w, color=color, edgecolor="#333333", linewidth=0.4, zorder=2)
433
+ if m == 0 and not (show_dots and len(vals) > 1):
434
+ # a true zero has no visible bar: label it so it is not read as missing
435
+ ax.annotate("0", (x, 0), xytext=(0, 1), textcoords="offset points", ha="center", va="bottom",
436
+ fontsize=FS - 1.5, color="#333333", zorder=8)
437
+ if err and len(vals) > 1:
438
+ ax.errorbar(x, m, yerr=sd, fmt="none", ecolor="#111111", elinewidth=0.6, capsize=1.3, capthick=0.6, zorder=4)
439
+ if show_dots and len(vals) > 1:
440
+ rng = np.random.default_rng(abs(hash((round(x, 3), len(vals)))) % (2**32))
441
+ jit = (rng.random(len(vals)) - 0.5) * w * 0.55
442
+ ax.scatter(x + jit, vals, s=4.5, facecolor="white", edgecolor="#111111", linewidth=0.4, zorder=5)
443
+ return m, sd, len(vals)
444
+
445
+
446
+ def panel_letter(fig, ax, letter, dx=-0.30, dy=0.0):
447
+ """Bold panel letter left of the axes, top-aligned with the axes box (dx in inches)."""
448
+ bb = ax.get_position()
449
+ fig.text(bb.x0 + dx / fig.get_figwidth(), bb.y1 + dy, letter, fontsize=FS + 2.5, fontweight="bold",
450
+ va="top", ha="left")
451
+
452
+
453
+ def group_separators(ax, n_groups, start=0):
454
+ for g in range(start, start + n_groups - 1):
455
+ ax.axvline(g + 0.5, color="#E3E3E3", lw=0.5, zorder=0)
456
+
457
+
458
+ def note(ax, x, y, text, **kw):
459
+ kw.setdefault("fontsize", FS - 1.2)
460
+ kw.setdefault("color", "#6E6E6E")
461
+ kw.setdefault("style", "italic")
462
+ kw.setdefault("ha", "center")
463
+ kw.setdefault("va", "center")
464
+ ax.text(x, y, text, zorder=7, **kw)
465
+
466
+
467
+ def save(fig, outdir: Path, name: str):
468
+ for ext in ("png", "pdf"):
469
+ fig.savefig(outdir / f"{name}.{ext}", dpi=300, bbox_inches="tight", pad_inches=0.03)
470
+ plt.close(fig)
471
+
472
+
473
+ # --------------------------------------------------------------------------------------
474
+ # Grouped-by-dataset metric panels (Fig 1, Fig 2)
475
+ # --------------------------------------------------------------------------------------
476
+ def grouped_metric_figure(get_vals, get_ref, arms, ds_xlabels, title_rows, fig_name, outdir, sources,
477
+ panel_prefix, show_dots, highlight=None, extra_annot=None, scsemi_n=None,
478
+ legend_refs=("pseudo", "broadcast", "null"), legend_labels=None, row_height=1.08):
479
+ """Rows = metrics, x = datasets (Imperial last). DEG row is split so Imperial gets its own y-scale.
480
+
481
+ get_vals(ds, arm, metric) -> list[(value, draw, source)]
482
+ get_ref(ds, kind, metric) -> (value, source) or (nan, '')
483
+ """
484
+ metrics = ["comp_l1", "coverage", "precision", "contrast_r", "deg"]
485
+ order = DATASETS # imperial_eskd is last on purpose
486
+ nds = len(order)
487
+ na = len(arms)
488
+ width = 0.8 / na
489
+ offs = (np.arange(na) - (na - 1) / 2) * width
490
+
491
+ fig_h = 0.62 + row_height * len(metrics) + 0.34
492
+ fig = plt.figure(figsize=(SINGLE_COL_IN, fig_h))
493
+ left, right = 0.62 / SINGLE_COL_IN, 1 - 0.30 / SINGLE_COL_IN
494
+ top = 1 - 0.62 / fig_h
495
+ bottom = 0.34 / fig_h
496
+ gap = 0.20 / fig_h
497
+ ah = (top - bottom - gap * (len(metrics) - 1)) / len(metrics)
498
+ axes = {}
499
+ all_rows = []
500
+ letters = "abcde"
501
+ for i, metric in enumerate(metrics):
502
+ y0 = top - (i + 1) * ah - i * gap
503
+ panel = f"{panel_prefix}{letters[i]}"
504
+ if metric == "deg":
505
+ split = (nds - 1) / nds
506
+ g = 0.035
507
+ axL = fig.add_axes([left, y0, (right - left) * split - g, ah])
508
+ axR = fig.add_axes([left + (right - left) * split + g * 0.55, y0, (right - left) * (1 - split) - g * 0.55, ah])
509
+ parts = [(axL, order[:-1], 0), (axR, order[-1:], nds - 1)]
510
+ else:
511
+ ax = fig.add_axes([left, y0, right - left, ah])
512
+ parts = [(ax, order, 0)]
513
+ for ax, dss, start in parts:
514
+ ymax_seen = 0.0
515
+ ymin_seen = 0.0
516
+ for gi, ds in enumerate(dss):
517
+ gx = start + gi
518
+ if highlight and ds in highlight:
519
+ ax.axvspan(gx - 0.5, gx + 0.5, color="#FFF1C9", zorder=0, lw=0)
520
+ missing_metric = metric in ("contrast_r", "deg") and ds == "immicro"
521
+ if missing_metric:
522
+ note(ax, gx, 0.5, NOTE_NO_CONTRAST, transform=ax.get_xaxis_transform())
523
+ all_rows.append(rows_long(panel, ds, "note", "missing", np.nan, "",
524
+ extra={"note": "ImMicro is a healthy cohort: no case-control contrast"}))
525
+ continue
526
+ for ai, arm in enumerate(arms):
527
+ trip = get_vals(ds, arm, metric)
528
+ vals = [t[0] for t in trip]
529
+ x = gx + offs[ai]
530
+ if arm == "scsemi5" and len(vals) == 0:
531
+ note(ax, x, 0.03, "n=0", rotation=90, va="bottom", color=STYLE[arm][1],
532
+ transform=ax.get_xaxis_transform(), style="normal", fontsize=FS - 1.5)
533
+ all_rows.append(rows_long(panel, ds, arm, "missing", np.nan, "", n=0))
534
+ continue
535
+ res = bar_with_points(ax, x, width * 0.92, vals, STYLE[arm][1], show_dots=show_dots)
536
+ if res is None:
537
+ continue
538
+ m, sd, n = res
539
+ for v, dr, src in trip:
540
+ all_rows.append(rows_long(panel, ds, arm, "draw" if show_dots else "pooled", v, src, draw=dr))
541
+ if show_dots:
542
+ all_rows.append(rows_long(panel, ds, arm, "mean", m, "derived: mean/SD of the draw rows",
543
+ n=n, extra={"sd": sd}))
544
+ top_v = m + (sd if n > 1 else 0)
545
+ if show_dots:
546
+ top_v = max(top_v, max(vals))
547
+ ymax_seen = max(ymax_seen, top_v)
548
+ ymin_seen = min(ymin_seen, min(vals), m - sd)
549
+ if arm == "scsemi5" and scsemi_n is not None and n < scsemi_n:
550
+ ax.annotate(f"n={n}", (x, top_v), xytext=(0, 1.5), textcoords="offset points",
551
+ ha="center", va="bottom", rotation=90, fontsize=FS - 1.5,
552
+ color="#8A5A00", zorder=8,
553
+ bbox=dict(boxstyle="square,pad=0.08", fc="white", ec="none"))
554
+ if extra_annot:
555
+ extra_annot(ax, ds, arm, metric, x, m)
556
+ # reference segments
557
+ refs = ["pseudo"]
558
+ if metric in ("contrast_r", "deg"):
559
+ refs.append("broadcast")
560
+ if metric == "comp_l1":
561
+ refs.append("null")
562
+ for rk in refs:
563
+ v, src = get_ref(ds, rk, metric)
564
+ if v is None or np.isnan(v):
565
+ continue
566
+ ref_segment(ax, gx - 0.46, gx + 0.46, v, rk)
567
+ ymax_seen = max(ymax_seen, v)
568
+ ymin_seen = min(ymin_seen, v)
569
+ all_rows.append(rows_long(panel, ds, f"ref_{rk}", "reference", v, src))
570
+ group_separators(ax, len(dss), start)
571
+ ax.set_xlim(start - 0.5, start + len(dss) - 0.5)
572
+ if metric in ("coverage", "precision"):
573
+ ax.set_ylim(0, 1.05)
574
+ elif metric == "comp_l1":
575
+ ax.set_ylim(0, max(0.5, ymax_seen * 1.08))
576
+ elif metric == "contrast_r":
577
+ ax.set_ylim(min(0, ymin_seen * 1.15 - 0.02), max(0.5, ymax_seen * 1.12))
578
+ ax.axhline(0, color="#555555", lw=0.5, zorder=1)
579
+ else:
580
+ ax.set_ylim(0, max(5, ymax_seen * 1.12))
581
+ if scsemi_n is not None and "scsemi5" in arms:
582
+ # leave headroom for the rotated n= labels
583
+ lo, hi = ax.get_ylim()
584
+ ax.set_ylim(lo, hi + (hi - lo) * 0.10)
585
+ ax.set_xticks([start + gi for gi in range(len(dss))])
586
+ if i == len(metrics) - 1:
587
+ ax.set_xticklabels([ds_xlabels[d] for d in dss], fontsize=FS - 0.8, linespacing=1.05)
588
+ else:
589
+ ax.set_xticklabels([])
590
+ ax.tick_params(axis="x", length=0, pad=2)
591
+ axes[metric] = parts
592
+ ax0 = parts[0][0]
593
+ ax0.set_ylabel(title_rows[metric], labelpad=2)
594
+ if metric == "deg":
595
+ axR = parts[1][0]
596
+ axR.spines["left"].set_visible(True)
597
+ axR.tick_params(axis="y", pad=1)
598
+ panel_letter(fig, ax0, letters[i], dx=-0.58)
599
+
600
+ # legend
601
+ handles = [Patch(facecolor=STYLE[a][1], edgecolor="#333333", linewidth=0.4,
602
+ label=(legend_labels or {}).get(a, STYLE[a][0])) for a in arms]
603
+ handles += [Line2D([0], [0], ls=REF[k]["ls"], color=REF[k]["color"], lw=REF[k]["lw"] + 0.2, label=REF[k]["label"])
604
+ for k in legend_refs]
605
+ fig.legend(handles=handles, loc="upper left", bbox_to_anchor=(0.02, 1 - 0.02 / fig_h), ncol=2,
606
+ frameon=False, handlelength=2.1, handleheight=0.8, columnspacing=1.0, labelspacing=0.35,
607
+ borderaxespad=0.0)
608
+ sources.write(fig_name, all_rows)
609
+ save(fig, outdir, fig_name)
610
+ return all_rows
611
+
612
+
613
+ # --------------------------------------------------------------------------------------
614
+ # Figure 1: few-pair scenario
615
+ # --------------------------------------------------------------------------------------
616
+ def make_fig1(few: pd.DataFrame, sc_status: pd.DataFrame, outdir, sources):
617
+ n_test = few[few.arm == "lora"].groupby("dataset")["n_scored"].apply(list).to_dict()
618
+ n_draws = few[few.arm == "lora"].groupby("dataset")["draw"].nunique().to_dict()
619
+ xl = {}
620
+ for d in DATASETS:
621
+ extra = "\nwhole blood" if d == "ji2025_chili" else ""
622
+ xl[d] = f"{DS_LABEL[d]}{extra}\nn={fmt_n(n_test[d])}"
623
+
624
+ def get_vals(ds, arm, metric):
625
+ s = few[(few.dataset == ds) & (few.arm == arm)].sort_values("draw")
626
+ return [(float(v), int(dr), src) for v, dr, src in zip(s[metric], s["draw"], s["source"]) if not np.isnan(v)]
627
+
628
+ def get_ref(ds, kind, metric):
629
+ if kind == "pseudo":
630
+ s = few[(few.dataset == ds) & (few.arm == "pseudo")]
631
+ v = s[metric]
632
+ elif kind == "broadcast":
633
+ s = few[(few.dataset == ds) & (few.arm == "lora")]
634
+ v = s["broadcast_r" if metric == "contrast_r" else "deg_broadcast"]
635
+ else:
636
+ s = few[(few.dataset == ds) & (few.arm == "lora")]
637
+ v = s["null"]
638
+ v = v.dropna()
639
+ return (float(v.mean()) if len(v) else np.nan, ";".join(sorted(set(s["source"]))))
640
+
641
+ n_full = max(n_draws.values())
642
+ labels = {"zs_raw": "Zero-shot, raw bulk", "zs_cal": "Zero-shot, paired cal. (same 5 pairs)",
643
+ "scsemi5": "scSemiProfiler, 5 pairs (n=draws if <5)", "lora": "LoRA, 5 pairs"}
644
+ grouped_metric_figure(get_vals, get_ref, ["zs_raw", "zs_cal", "scsemi5", "lora"], xl, METRIC_LABEL,
645
+ "fig1_fewpair", outdir, sources, "1", show_dots=True, scsemi_n=n_full,
646
+ legend_labels=labels)
647
+ return n_test
648
+
649
+
650
+ # --------------------------------------------------------------------------------------
651
+ # Figure 2: 5-fold pooled
652
+ # --------------------------------------------------------------------------------------
653
+ def make_fig2(pooled, outdir, sources):
654
+ arms_file = {"zs_cal": "zs__cal", "sconly_cal": "pseudo_full__cal", "lora": "real_lora__raw"}
655
+ xl = {}
656
+ for d in DATASETS:
657
+ n = pooled[d]["real_lora__raw"]["n_scored"]
658
+ extra = "\nwhole blood" if d == "ji2025_chili" else ""
659
+ xl[d] = f"{DS_LABEL[d]}{extra}\nn={n}"
660
+
661
+ def src_of(m, metric):
662
+ return m.get("deg_source", m["source"]) if metric == "deg" else m["source"]
663
+
664
+ def get_vals(ds, arm, metric):
665
+ m = pooled[ds][arms_file[arm]]
666
+ v = m[metric]
667
+ return [] if np.isnan(v) else [(float(v), "pooled", src_of(m, metric))]
668
+
669
+ def get_ref(ds, kind, metric):
670
+ if kind == "pseudo":
671
+ m = pooled[ds]["zs__pseudo"]
672
+ return m[metric], src_of(m, metric)
673
+ m = pooled[ds]["real_lora__raw"]
674
+ if kind == "broadcast":
675
+ return (m["broadcast_r"] if metric == "contrast_r" else m["deg_broadcast"]), src_of(m, metric)
676
+ return m["null"], m["source"]
677
+
678
+ def annot(ax, ds, arm, metric, x, m):
679
+ if ds == "ji2025_chili" and metric == "coverage" and arm == "sconly_cal":
680
+ ax.annotate("sc-only\nfails", (x, m), xytext=(-7, 6), textcoords="offset points", ha="center",
681
+ va="bottom", fontsize=FS - 1.2, color="#7A2E62",
682
+ arrowprops=dict(arrowstyle="-|>", lw=0.5, color="#7A2E62", shrinkA=0, shrinkB=1,
683
+ mutation_scale=4))
684
+
685
+ labels = {"zs_cal": "Zero-shot, paired calibration", "sconly_cal": "sc-only fine-tune + paired cal.",
686
+ "lora": "LoRA, 5-fold CV (other 4 folds)"}
687
+ grouped_metric_figure(get_vals, get_ref, ["zs_cal", "sconly_cal", "lora"], xl, METRIC_LABEL, "fig2_fivefold",
688
+ outdir, sources, "2", show_dots=False, highlight={"ji2025_chili"}, extra_annot=annot,
689
+ legend_labels=labels)
690
+
691
+
692
+ # --------------------------------------------------------------------------------------
693
+ # Figure 3: learning curve
694
+ # --------------------------------------------------------------------------------------
695
+ def make_fig3(pooled, calls, steps, outdir, sources):
696
+ dsets = ["immicro", "ye2026_sepsis"]
697
+ xs = list(range(6)) # 0 = zero-shot (no pairs: raw and exon-length-corrected bulk), 1..4 = n5..n40, 5 = every training donor
698
+ lora_arms = [f"lora_n{n}__raw" for n in LC_N] + ["real_lora__raw"]
699
+ rows_spec = [
700
+ ("comp_l1", "Composition L1 ↓"),
701
+ ("coverage", "Coverage ↑"),
702
+ ("signal", None),
703
+ ("deg", "Top-50 DEG ↑"),
704
+ ("steps", "Selected step\n(×1,000)"),
705
+ ]
706
+ fig_h = 6.3
707
+ fig, axs = plt.subplots(len(rows_spec), 2, figsize=(SINGLE_COL_IN, fig_h), sharex="col",
708
+ gridspec_kw=dict(hspace=0.30, wspace=0.55, left=0.175, right=0.98, top=0.905,
709
+ bottom=0.075))
710
+ all_rows = []
711
+ for ci, ds in enumerate(dsets):
712
+ P = pooled[ds]
713
+ st = steps[steps.dataset == ds]
714
+ n_all = fmt_n(st[st.arm == "real_lora"]["n_train"])
715
+ xt = ["0", "5", "10", "20", "40", n_all]
716
+ for ri, (key, ylab) in enumerate(rows_spec):
717
+ ax = axs[ri, ci]
718
+ panel = f"3{'abcdefghij'[ri * 2 + ci]}" # letters run row-wise
719
+ if key == "signal":
720
+ if ds == "immicro":
721
+ ylab = "Across-donor NK\nfraction r ↑"
722
+ call = calls[ds]
723
+ getv = lambda farm: across_donor_r(calls[ds + "__len"] if farm == "zs__len" else call, farm, # noqa: E731
724
+ "NK cell")
725
+ srcv = lambda farm: (calls[ds + "__len"] if farm == "zs__len" else call).rel("per_donor.csv") # noqa: E731
726
+ ref_list = [("pseudo", getv("zs__pseudo"), srcv("zs__pseudo"))]
727
+ else:
728
+ ylab = "Disease logFC r ↑"
729
+ getv = lambda farm: P[farm]["contrast_r"] # noqa: E731
730
+ srcv = lambda farm: P[farm]["source"] # noqa: E731
731
+ ref_list = [("pseudo", P["zs__pseudo"]["contrast_r"], P["zs__pseudo"]["source"]),
732
+ ("broadcast", P["real_lora__raw"]["broadcast_r"], P["real_lora__raw"]["source"])]
733
+ elif key == "deg":
734
+ if ds == "immicro":
735
+ note(ax, 0.5, 0.5, "no case–control\ncontrast\n(healthy cohort)", transform=ax.transAxes)
736
+ ax.set_yticks([])
737
+ ax.spines["left"].set_visible(False)
738
+ all_rows.append(rows_long(panel, ds, "note", "missing", np.nan, "",
739
+ extra={"note": "ImMicro has no case-control contrast"}))
740
+ ax.set_ylabel(ylab if ci == 0 else "")
741
+ panel_letter(fig, ax, panel[1:], dx=-0.60)
742
+ continue
743
+ getv = lambda farm: P[farm]["deg"] # noqa: E731
744
+ srcv = lambda farm: P[farm]["deg_source"] # noqa: E731
745
+ ref_list = [("pseudo", P["zs__pseudo"]["deg"], P["zs__pseudo"]["deg_source"]),
746
+ ("broadcast", P["real_lora__raw"]["deg_broadcast"], P["real_lora__raw"]["deg_source"])]
747
+ elif key == "steps":
748
+ arm_order = [f"lora_n{n}" for n in LC_N] + ["real_lora"]
749
+ for xi, arm in enumerate(arm_order, start=1):
750
+ s = st[st.arm == arm].sort_values("fold")
751
+ v = s["selected_step"].astype(float).values / 1000
752
+ rng = np.random.default_rng(xi)
753
+ jit = (rng.random(len(v)) - 0.5) * 0.35
754
+ ax.scatter(xi + jit, v, s=7, facecolor=STYLE["lora"][1], edgecolor="#222222", lw=0.35,
755
+ zorder=4, alpha=0.9)
756
+ if len(v):
757
+ med = float(np.median(v))
758
+ ax.plot([xi - 0.28, xi + 0.28], [med, med], color="#222222", lw=0.9, zorder=5)
759
+ for _, r in s.iterrows():
760
+ all_rows.append(rows_long(panel, ds, arm, "fold", r["selected_step"], r["source"],
761
+ draw=f"fold{r['fold']}",
762
+ extra={"n_train": r["n_train"], "max_steps": r["max_steps"]}))
763
+ cap = st["max_steps"].dropna().unique()
764
+ for c in cap:
765
+ ax.axhline(c / 1000, color="#8C8C8C", lw=0.6, ls=(0, (2, 1.5)), zorder=1)
766
+ ax.text(0.2, c / 1000, "cap", fontsize=FS - 1.5, color="#6E6E6E", va="bottom", ha="left")
767
+ ax.set_ylim(0, max(cap) / 1000 * 1.12 if len(cap) else 21)
768
+ note(ax, 0, 0.5, "zero-\nshot", transform=ax.get_xaxis_transform(), fontsize=FS - 1.6)
769
+ ax.set_ylabel(ylab if ci == 0 else "")
770
+ ax.set_xticks(xs)
771
+ ax.set_xticklabels(xt)
772
+ ax.set_xlim(-0.5, 5.5)
773
+ ax.set_xlabel("Training pairs")
774
+ panel_letter(fig, ax, panel[1:], dx=-0.60)
775
+ continue
776
+ else:
777
+ getv = lambda farm, k=key: P[farm][k] # noqa: E731
778
+ srcv = lambda farm: P[farm]["source"] # noqa: E731
779
+ ref_list = [("pseudo", P["zs__pseudo"][key], P["zs__pseudo"]["source"])]
780
+ if key == "comp_l1":
781
+ ref_list.append(("null", P["real_lora__raw"]["null"], P["real_lora__raw"]["source"]))
782
+ # x = 0 uses no pairs: zero-shot on the real bulk as measured and after exon-length correction
783
+ # (2026-10-02; the calibrated zero-shot point was dropped here because its alpha uses every training pair)
784
+ z0 = [("zs_raw", "zs__raw", -0.17)] + ([("zs_len", "zs__len", 0.17)] if "zs__len" in P else [])
785
+ for skey, farm, dx in z0:
786
+ v = getv(farm)
787
+ ax.scatter([dx], [v], s=16, color=STYLE[skey][1], edgecolor="#222222", lw=0.4, zorder=5)
788
+ all_rows.append(rows_long(panel, ds, skey, "pooled", v, srcv(farm), draw="n=0"))
789
+ v0s = [getv(farm) for _, farm, _ in z0]
790
+ vl = [getv(a) for a in lora_arms]
791
+ ax.plot(xs[1:], vl, color=STYLE["lora"][1], lw=1.1, zorder=3)
792
+ ax.scatter(xs[1:], vl, s=16, color=STYLE["lora"][1], edgecolor="#222222", lw=0.4, zorder=5)
793
+ for a, v, lab in zip(lora_arms, vl, ["5", "10", "20", "40", "all"]):
794
+ all_rows.append(rows_long(panel, ds, "lora", "pooled", v, srcv(a), draw=f"n={lab}"))
795
+ lo, hi = min(v0s + vl), max(v0s + vl)
796
+ for rk, rv, rs in ref_list:
797
+ if rv is None or np.isnan(rv):
798
+ continue
799
+ s = REF[rk]
800
+ ax.axhline(rv, ls=s["ls"], color=s["color"], lw=s["lw"], zorder=2)
801
+ lo, hi = min(lo, rv), max(hi, rv)
802
+ all_rows.append(rows_long(panel, ds, f"ref_{rk}", "reference", rv, rs))
803
+ pad = (hi - lo) * 0.18 + 1e-6
804
+ if key == "deg":
805
+ ax.set_ylim(0, hi + pad)
806
+ else:
807
+ ax.set_ylim(lo - pad, hi + pad)
808
+ ax.set_ylabel(ylab, labelpad=2)
809
+ panel_letter(fig, ax, panel[1:], dx=-0.60)
810
+ axs[0, ci].set_title(f"{DS_LABEL[ds]} (pooled, n={P['real_lora__raw']['n_scored']})", pad=4)
811
+ handles = [
812
+ Line2D([0], [0], marker="o", color=STYLE["zs_raw"][1], lw=0, markeredgecolor="#222222", markersize=4,
813
+ label="Zero-shot, real bulk (no pairs)"),
814
+ Line2D([0], [0], marker="o", color=STYLE["zs_len"][1], lw=0, markeredgecolor="#222222", markersize=4,
815
+ label="Zero-shot, exon-length-corrected (no pairs)"),
816
+ Line2D([0], [0], marker="o", color=STYLE["lora"][1], lw=1.1, markeredgecolor="#222222", markersize=4,
817
+ label="LoRA fine-tune"),
818
+ ] + [Line2D([0], [0], ls=REF[k]["ls"], color=REF[k]["color"], lw=REF[k]["lw"] + 0.2, label=REF[k]["label"])
819
+ for k in ("pseudo", "broadcast", "null")]
820
+ fig.legend(handles=handles, loc="upper left", bbox_to_anchor=(0.01, 0.999), ncol=2, frameon=False,
821
+ handlelength=2.1, columnspacing=1.0, labelspacing=0.35, borderaxespad=0.0)
822
+ sources.write("fig3_learning_curve", all_rows)
823
+ save(fig, outdir, "fig3_learning_curve")
824
+
825
+
826
+ # --------------------------------------------------------------------------------------
827
+ # Supp S1: per-cell-type contrast r
828
+ # --------------------------------------------------------------------------------------
829
+ def make_figS1(few, pooled, outdir, sources):
830
+ fig_h = 5.4
831
+ fig, axs = plt.subplots(len(DISEASE_DS), 2, figsize=(SINGLE_COL_IN, fig_h), sharey=True, sharex=True,
832
+ gridspec_kw=dict(hspace=0.28, wspace=0.13, left=0.15, right=0.99, top=0.90,
833
+ bottom=0.06))
834
+ series = [("zs_cal", STYLE["zs_cal"][1]), ("lora", STYLE["lora"][1]), ("broadcast", STYLE["broadcast"][1])]
835
+ w = 0.8 / len(series)
836
+ offs = (np.arange(len(series)) - 1) * w
837
+ all_rows = []
838
+ letters = iter("abcdefgh")
839
+ for ri, ds in enumerate(DISEASE_DS):
840
+ for ci, setting in enumerate(["fewpair", "pooled"]):
841
+ ax = axs[ri, ci]
842
+ panel = f"S1{next(letters)}"
843
+ for ti, ct in enumerate(CELLTYPES):
844
+ for si, (sk, col) in enumerate(series):
845
+ x = ti + offs[si]
846
+ if setting == "fewpair":
847
+ arm = "lora" if sk == "broadcast" else sk
848
+ s = few[(few.dataset == ds) & (few.arm == arm)].sort_values("draw")
849
+ vals = [(r["bc_type"] if sk == "broadcast" else r["r_type"])[ct] for _, r in s.iterrows()]
850
+ bar_with_points(ax, x, w * 0.92, vals, col, show_dots=False)
851
+ for v, (_, r) in zip(vals, s.iterrows()):
852
+ all_rows.append(rows_long(panel, ds, sk, "draw", v, r["source"], draw=r["draw"],
853
+ extra={"celltype": ct}))
854
+ else:
855
+ m = pooled[ds]["real_lora__raw" if sk in ("lora", "broadcast") else "zs__cal"]
856
+ v = (m["bc_type"] if sk == "broadcast" else m["r_type"])[ct]
857
+ bar_with_points(ax, x, w * 0.92, [v], col, show_dots=False)
858
+ all_rows.append(rows_long(panel, ds, sk, "pooled", v, m["source"], extra={"celltype": ct}))
859
+ ax.axhline(0, color="#555555", lw=0.5)
860
+ group_separators(ax, len(CELLTYPES))
861
+ ax.set_xlim(-0.5, len(CELLTYPES) - 0.5)
862
+ ax.set_xticks(range(len(CELLTYPES)))
863
+ ax.set_xticklabels([CT_SHORT[c] for c in CELLTYPES])
864
+ ax.tick_params(axis="x", length=0)
865
+ if ci == 0:
866
+ ax.set_ylabel(f"{DS_LABEL[ds]}" + (" (whole blood)" if ds == "ji2025_chili" else "") +
867
+ "\nlogFC r", labelpad=2)
868
+ if ri == 0:
869
+ ax.set_title("5 pairs (mean ± SD, 5 draws)" if setting == "fewpair"
870
+ else "5-fold CV, other 4 folds (pooled)", pad=4)
871
+ panel_letter(fig, ax, panel[2:], dx=-0.42 if ci == 0 else -0.17)
872
+ axs[0, 0].set_ylim(-0.25, 1.0)
873
+ handles = [Patch(facecolor=STYLE["zs_cal"][1], edgecolor="#333333", lw=0.4, label="Zero-shot, paired calibration"),
874
+ Patch(facecolor=STYLE["lora"][1], edgecolor="#333333", lw=0.4, label="LoRA fine-tune"),
875
+ Patch(facecolor=STYLE["broadcast"][1], edgecolor="#333333", lw=0.4,
876
+ label="Real-bulk broadcast (input bulk logFC)")]
877
+ fig.legend(handles=handles, loc="upper left", bbox_to_anchor=(0.01, 0.999), ncol=2, frameon=False,
878
+ columnspacing=1.0, labelspacing=0.35, borderaxespad=0.0)
879
+ sources.write("figS1_celltype_contrast", all_rows)
880
+ save(fig, outdir, "figS1_celltype_contrast")
881
+
882
+
883
+ # --------------------------------------------------------------------------------------
884
+ # Supp S2: K augmentation
885
+ # --------------------------------------------------------------------------------------
886
+ def paired_wilcoxon(call: Call, arm_a: str, arm_b: str):
887
+ d = call.per_donor.pivot(index="donor", columns="arm", values="comp_l1")
888
+ x = (d[arm_a] - d[arm_b]).dropna()
889
+ return float(x.mean()), float(wilcoxon(x).pvalue), int(len(x))
890
+
891
+
892
+ def make_figS2(pooled, calls, outdir, sources):
893
+ dsets = ["immicro", "ye2026_sepsis"]
894
+ arms = [("lora", "real_lora__raw"), ("lora_multik", "lora_multik__raw"), ("lora_recipe", "lora_recipe__raw")]
895
+ w = 0.8 / len(arms)
896
+ offs = (np.arange(len(arms)) - 1) * w
897
+ fig_h = 4.9
898
+ fig, axs = plt.subplots(3, 2, figsize=(SINGLE_COL_IN, fig_h),
899
+ gridspec_kw=dict(hspace=0.55, wspace=0.50, left=0.17, right=0.99, top=0.855,
900
+ bottom=0.07))
901
+ all_rows = []
902
+ pvals = {}
903
+ for ci, ds in enumerate(dsets):
904
+ P, call = pooled[ds], calls[ds]
905
+ # row 0: comp L1, precision, coverage
906
+ ax = axs[0, ci]
907
+ panel = f"S2{'abcdef'[0 * 2 + ci]}" # letters run row-wise
908
+ mets = [("comp_l1", "L1 ↓"), ("precision", "Precision"), ("coverage", "Coverage")]
909
+ for mi, (mk, _) in enumerate(mets):
910
+ for ai, (key, farm) in enumerate(arms):
911
+ v = P[farm][mk]
912
+ bar_with_points(ax, mi + offs[ai], w * 0.92, [v], STYLE[key][1], show_dots=False)
913
+ all_rows.append(rows_long(panel, ds, key, "pooled", v, P[farm]["source"], extra={"metric": mk}))
914
+ for ai, (key, farm) in enumerate(arms[1:], start=1):
915
+ dm, p, n = paired_wilcoxon(call, farm, "real_lora__raw")
916
+ pvals[(ds, key)] = (dm, p, n)
917
+ ax.annotate(f"p={fmt_p(p)}", (0 + offs[ai], P[farm]["comp_l1"]), xytext=(0, 2), textcoords="offset points",
918
+ rotation=90, ha="center", va="bottom", fontsize=FS - 1.6, color="#333333")
919
+ all_rows.append(rows_long(panel, ds, key, "wilcoxon_p_vs_plain_lora", p, call.rel("per_donor.csv"),
920
+ n=n, extra={"metric": "comp_l1", "mean_diff": dm}))
921
+ ax.set_xticks(range(len(mets)))
922
+ ax.set_xticklabels([m[1] for m in mets])
923
+ ax.tick_params(axis="x", length=0)
924
+ ax.set_ylim(0, 1.15)
925
+ group_separators(ax, len(mets))
926
+ ax.set_xlim(-0.5, len(mets) - 0.5)
927
+ ax.set_title(f"{DS_LABEL[ds]} (pooled, n={P['real_lora__raw']['n_scored']})", pad=4)
928
+ ax.set_ylabel("Score", labelpad=2)
929
+ panel_letter(fig, ax, panel[2:], dx=-0.58)
930
+ # row 1: per-type r
931
+ ax = axs[1, ci]
932
+ panel = f"S2{'abcdef'[1 * 2 + ci]}" # letters run row-wise
933
+ for ti, ct in enumerate(CELLTYPES):
934
+ for ai, (key, farm) in enumerate(arms):
935
+ if ds == "immicro":
936
+ v, src = across_donor_r(call, farm, ct), call.rel("per_donor.csv")
937
+ else:
938
+ v, src = P[farm]["r_type"][ct], P[farm]["source"]
939
+ bar_with_points(ax, ti + offs[ai], w * 0.92, [v], STYLE[key][1], show_dots=False)
940
+ all_rows.append(rows_long(panel, ds, key, "pooled", v, src, extra={"celltype": ct}))
941
+ ax.set_xticks(range(len(CELLTYPES)))
942
+ ax.set_xticklabels([CT_SHORT[c] for c in CELLTYPES])
943
+ ax.tick_params(axis="x", length=0)
944
+ ax.set_ylim(0, 1.0)
945
+ group_separators(ax, len(CELLTYPES))
946
+ ax.set_xlim(-0.5, len(CELLTYPES) - 0.5)
947
+ ax.set_ylabel("Across-donor\nfraction r ↑" if ds == "immicro" else "Disease logFC r ↑", labelpad=2)
948
+ panel_letter(fig, ax, panel[2:], dx=-0.58)
949
+ # row 2: DEG
950
+ ax = axs[2, ci]
951
+ panel = f"S2{'abcdef'[2 * 2 + ci]}" # letters run row-wise
952
+ if ds == "immicro":
953
+ note(ax, 0.5, 0.5, "no case–control contrast\n(healthy cohort)", transform=ax.transAxes)
954
+ ax.set_xticks([])
955
+ ax.set_yticks([])
956
+ for sp in ("left", "bottom"):
957
+ ax.spines[sp].set_visible(False)
958
+ all_rows.append(rows_long(panel, ds, "note", "missing", np.nan, "",
959
+ extra={"note": "ImMicro has no case-control contrast"}))
960
+ else:
961
+ for ai, (key, farm) in enumerate(arms):
962
+ v = P[farm]["deg"]
963
+ bar_with_points(ax, offs[ai], w * 0.92, [v], STYLE[key][1], show_dots=False)
964
+ all_rows.append(rows_long(panel, ds, key, "pooled", v, P[farm]["deg_source"]))
965
+ bc = P["real_lora__raw"]["deg_broadcast"]
966
+ ref_segment(ax, -0.46, 0.46, bc, "broadcast")
967
+ all_rows.append(rows_long(panel, ds, "ref_broadcast", "reference", bc, P["real_lora__raw"]["deg_source"]))
968
+ ax.set_xlim(-0.9, 0.9)
969
+ ax.set_xticks([])
970
+ ax.set_ylim(0, max(bc, max(P[f]["deg"] for _, f in arms)) * 1.2)
971
+ ax.set_ylabel("Top-50 DEG ↑", labelpad=2)
972
+ panel_letter(fig, ax, panel[2:], dx=-0.58)
973
+ handles = [Patch(facecolor=STYLE[k][1], edgecolor="#333333", lw=0.4,
974
+ label={"lora": "Plain LoRA (K = 1000)", "lora_multik": "LoRA + multi-K real bulk (K 250–4000)",
975
+ "lora_recipe": "LoRA + half-batch pretraining recipes"}[k]) for k, _ in arms]
976
+ handles.append(Line2D([0], [0], ls=REF["broadcast"]["ls"], color=REF["broadcast"]["color"],
977
+ lw=REF["broadcast"]["lw"] + 0.2, label="Real-bulk broadcast (panel f)"))
978
+ fig.legend(handles=handles, loc="upper left", bbox_to_anchor=(0.01, 0.999), ncol=1, frameon=False,
979
+ labelspacing=0.3, borderaxespad=0.0)
980
+ sources.write("figS2_k_augmentation", all_rows)
981
+ save(fig, outdir, "figS2_k_augmentation")
982
+ return pvals
983
+
984
+
985
+ # --------------------------------------------------------------------------------------
986
+ # Consistency checks against the pipeline's own few-pair aggregate.json
987
+ # --------------------------------------------------------------------------------------
988
+ def consistency_checks(few, scores_root, sources):
989
+ rows = []
990
+ amap = {"zs_raw": "zs_raw", "zs_cal": "zs_cal", "lora": "lora5", "pseudo": "zs_pseudo"}
991
+ for ds in DATASETS:
992
+ p = scores_root / ds / "fewshot_n5" / "aggregate.json"
993
+ if not p.exists():
994
+ continue
995
+ agg = json.loads(p.read_text())
996
+ for key, farm in amap.items():
997
+ s = few[(few.dataset == ds) & (few.arm == key)]
998
+ for mk in ("comp_l1", "precision", "coverage", "deg"):
999
+ aname = "deg_top50_sum" if mk == "deg" else mk
1000
+ if aname not in agg["arms"].get(farm, {}):
1001
+ continue
1002
+ a_mean, a_sd = agg["arms"][farm][aname]
1003
+ v = s[mk].dropna()
1004
+ ok = abs(v.mean() - a_mean) < 1e-9 and abs(v.std(ddof=1) - a_sd) < 1e-9 and len(v) == len(agg["draws"])
1005
+ rows.append({"dataset": ds, "arm": farm, "metric": aname, "plotted_mean": v.mean(),
1006
+ "plotted_sd": v.std(ddof=1), "aggregate_mean": a_mean, "aggregate_sd": a_sd,
1007
+ "n_draws": len(v), "match": ok, "aggregate": relp(p)})
1008
+ if farm in agg.get("contrast", {}):
1009
+ a = agg["contrast"][farm]
1010
+ v = s["contrast_r"].dropna()
1011
+ ok = abs(v.mean() - a["r_generated"][0]) < 1e-9 and abs(s["broadcast_r"].mean() - a["r_broadcast"]) < 1e-9
1012
+ rows.append({"dataset": ds, "arm": farm, "metric": "contrast_r (T/B/Mono/NK mean)",
1013
+ "plotted_mean": v.mean(), "plotted_sd": v.std(ddof=1),
1014
+ "aggregate_mean": a["r_generated"][0], "aggregate_sd": a["r_generated"][1],
1015
+ "n_draws": len(v), "match": ok, "aggregate": relp(p)})
1016
+ df = sources.write("consistency_checks", rows)
1017
+ bad = df[~df["match"]] if len(df) else df
1018
+ return df, bad
1019
+
1020
+
1021
+ # --------------------------------------------------------------------------------------
1022
+ # FIGURES.md
1023
+ # --------------------------------------------------------------------------------------
1024
+ def fmt_p(p):
1025
+ return f"{p:.2f}" if p >= 0.01 else f"{p:.1e}"
1026
+
1027
+
1028
+ def f2(x):
1029
+ return f"{x:.2f}"
1030
+
1031
+
1032
+ def f3(x):
1033
+ return f"{x:.3f}"
1034
+
1035
+
1036
+ def write_figures_md(outdir, few, sc_status, pooled, calls, steps, pvals, n_test, bad_checks, fs_runs):
1037
+ def fm(ds, arm, k):
1038
+ s = few[(few.dataset == ds) & (few.arm == arm)][k].dropna()
1039
+ return s.mean(), s.std(ddof=1), len(s)
1040
+
1041
+ used = sc_status[sc_status.status == "used"]
1042
+ per_ds_sc = {d: int((used.dataset == d).sum()) for d in DATASETS}
1043
+ n_draws = {d: int(few[(few.dataset == d) & (few.arm == "lora")]["draw"].nunique()) for d in DATASETS}
1044
+ sc_line = ", ".join(f"{DS_LABEL[d]} {per_ds_sc[d]}/{n_draws[d]}" for d in DATASETS)
1045
+ rejected = sc_status[sc_status.status == "rejected"]
1046
+
1047
+ # few-pair takeaways (computed)
1048
+ cov_up = [d for d in DATASETS if fm(d, "lora", "coverage")[0] > fm(d, "zs_cal", "coverage")[0]]
1049
+ r_txt = ", ".join(f"{DS_LABEL[d]} {f2(fm(d, 'zs_cal', 'contrast_r')[0])} → {f2(fm(d, 'lora', 'contrast_r')[0])}"
1050
+ for d in DISEASE_DS)
1051
+ bc_txt = ", ".join(f"{DS_LABEL[d]} {f2(fm(d, 'lora', 'broadcast_r')[0])}" for d in DISEASE_DS)
1052
+ l1_im = (fm("immicro", "zs_cal", "comp_l1")[0], fm("immicro", "lora", "comp_l1")[0])
1053
+
1054
+ if len(used):
1055
+ comp = []
1056
+ for mk, better in (("comp_l1", "lower"), ("coverage", "higher"), ("precision", "higher"),
1057
+ ("contrast_r", "higher"), ("deg", "higher")):
1058
+ wins, tot = 0, 0
1059
+ for d in DATASETS:
1060
+ dr = used[used.dataset == d]["draw"].tolist()
1061
+ if not dr:
1062
+ continue
1063
+ a = few[(few.dataset == d) & (few.arm == "lora") & (few.draw.isin(dr))][mk].mean()
1064
+ b = few[(few.dataset == d) & (few.arm == "scsemi5") & (few.draw.isin(dr))][mk].mean()
1065
+ if np.isnan(a) or np.isnan(b):
1066
+ continue
1067
+ tot += 1
1068
+ wins += int(a < b if better == "lower" else a > b)
1069
+ if tot:
1070
+ comp.append(f"{METRIC_LABEL[mk].split(' ')[0] if mk != 'contrast_r' else 'disease r'} "
1071
+ f"{wins}/{tot}")
1072
+ sc_take = ("On the draws where both exist, LoRA-5 is better than scSemiProfiler-5 in this many datasets "
1073
+ "(same draws only): " + "; ".join(comp) + ". "
1074
+ "This sentence is computed by the script; rewrite it by hand once all 25 draws are in.")
1075
+ else:
1076
+ sc_take = "No scSemiProfiler-5 draw has been scored yet, so its bars are empty (marked n=0)."
1077
+
1078
+ # fig2
1079
+ P = pooled
1080
+ ji = P["ji2025_chili"]
1081
+ im = P["imperial_eskd"]
1082
+ # fig3
1083
+ se, mm = P["ye2026_sepsis"], P["immicro"]
1084
+ nk = {a: across_donor_r(calls["immicro"], a, "NK cell")
1085
+ for a in ["zs__cal", "lora_n5__raw", "lora_n10__raw", "lora_n20__raw", "lora_n40__raw", "real_lora__raw"]}
1086
+ st_se = steps[(steps.dataset == "ye2026_sepsis")]
1087
+ st_im = steps[(steps.dataset == "immicro")]
1088
+
1089
+ def rng_steps(st, arm):
1090
+ v = st[st.arm == arm]["selected_step"]
1091
+ return f"{int(v.min()):,}–{int(v.max()):,}"
1092
+
1093
+ n_cap_im = {a: int((st_im[st_im.arm == a]["selected_step"] >= st_im[st_im.arm == a]["max_steps"] - 500).sum())
1094
+ for a in ["lora_n5", "lora_n10", "lora_n20", "lora_n40", "real_lora"]}
1095
+
1096
+ def names(ds_list):
1097
+ ds_list = [DS_LABEL[d] for d in ds_list]
1098
+ if not ds_list:
1099
+ return "none"
1100
+ return ds_list[0] if len(ds_list) == 1 else ", ".join(ds_list[:-1]) + " and " + ds_list[-1]
1101
+
1102
+ # Fig 1: which datasets have LoRA-5 r above the broadcast; composition p from the pipeline aggregate
1103
+ above_bc = [d for d in DISEASE_DS if fm(d, "lora", "contrast_r")[0] > fm(d, "lora", "broadcast_r")[0]]
1104
+ below_bc = [d for d in DISEASE_DS if d not in above_bc]
1105
+ agg_p = {}
1106
+ for d in DATASETS:
1107
+ ap_ = SCORES_ROOT / d / "fewshot_n5" / "aggregate.json"
1108
+ if ap_.exists():
1109
+ agg_p[d] = json.loads(ap_.read_text())["lora5_vs_zs_cal_l1"]
1110
+ sig1 = [d for d in DATASETS if d in agg_p and agg_p[d]["wilcoxon_p"] < 0.01 and agg_p[d]["mean_diff"] < 0]
1111
+ ns1 = [d for d in DATASETS if d in agg_p and d not in sig1]
1112
+ comp1 = (f"Composition improves significantly only in {names(sig1)} "
1113
+ f"(paired Wilcoxon over donor-draws, p {', '.join(fmt_p(agg_p[d]['wilcoxon_p']) for d in sig1)}; "
1114
+ f"{names(ns1)}: p ≥ {min(agg_p[d]['wilcoxon_p'] for d in ns1):.2f}).") if ns1 else ""
1115
+ # Fig 2: computed rankings and composition tests (paired Wilcoxon over scored samples)
1116
+ best_cov = [d for d in DATASETS if P[d]["real_lora__raw"]["coverage"] >= max(P[d]["zs__cal"]["coverage"],
1117
+ P[d]["pseudo_full__cal"]["coverage"])]
1118
+ best_r = [d for d in DISEASE_DS if P[d]["real_lora__raw"]["contrast_r"] >= max(P[d]["zs__cal"]["contrast_r"],
1119
+ P[d]["pseudo_full__cal"]["contrast_r"])]
1120
+ w2 = {d: paired_wilcoxon(calls[d], "real_lora__raw", "zs__cal") for d in DATASETS}
1121
+ sig2 = [d for d in DATASETS if w2[d][1] < 0.01 and w2[d][0] < 0]
1122
+ pseudo_better = [d for d in DATASETS if P[d]["zs__pseudo"]["comp_l1"] < P[d]["real_lora__raw"]["comp_l1"]]
1123
+ lora_better = [d for d in DATASETS if d not in pseudo_better]
1124
+ # Fig 3: first n from which every later LoRA point beats the broadcast
1125
+ lc_labels = ["5", "10", "20", "40", "all"]
1126
+ lc_arms = ["lora_n5__raw", "lora_n10__raw", "lora_n20__raw", "lora_n40__raw", "real_lora__raw"]
1127
+
1128
+ def first_sustained(vals, thr):
1129
+ for i in range(len(vals)):
1130
+ if all(v > thr for v in vals[i:]):
1131
+ return lc_labels[i]
1132
+ return None
1133
+
1134
+ r_from = first_sustained([se[a]["contrast_r"] for a in lc_arms], se["real_lora__raw"]["broadcast_r"])
1135
+ deg_from = first_sustained([se[a]["deg"] for a in lc_arms], se["real_lora__raw"]["deg_broadcast"] - 1e-9)
1136
+ dmax = {d: P[d]["real_lora__raw"]["deg_max"] for d in DISEASE_DS}
1137
+ short = [d for d in DISEASE_DS if dmax[d] < 250]
1138
+ deg_max_txt = ("; " + ", ".join(f"{DS_LABEL[d]} {int(dmax[d])}" for d in short) +
1139
+ ", because some observed top lists hold fewer than 50 significant genes") if short else ""
1140
+ # few-pair LoRA runs present locally
1141
+ fs_steps = sorted(set(int(x) for x in fs_runs["steps_run"])) if len(fs_runs) else []
1142
+ fs_steps_txt = (f"{fs_steps[0]:,} steps" if len(fs_steps) == 1 else f"{fs_steps} steps") if fs_steps else "steps n/a"
1143
+ fs_rows_txt = "; ".join(f"{DS_LABEL[d]} {fmt_n(fs_runs[fs_runs.dataset == d]['n_train_rows'])}"
1144
+ for d in DATASETS if (fs_runs.dataset == d).any())
1145
+ fs_missing = [d for d in DATASETS if not (fs_runs.dataset == d).any()]
1146
+ inner_val = fmt_n(steps[steps.arm.str.startswith("lora_n")]["n_inner_val"])
1147
+ # S1: draw-to-draw SD of LoRA-5 per-type r, averaged over types
1148
+ s1_sd = {}
1149
+ for d in DISEASE_DS:
1150
+ s = few[(few.dataset == d) & (few.arm == "lora")]
1151
+ s1_sd[d] = float(np.mean([np.std([r[c] for r in s["r_type"]], ddof=1) for c in CELLTYPES]))
1152
+ s1_sd_max = max(s1_sd, key=s1_sd.get)
1153
+ # S1: per dataset, cell types where pooled LoRA beats the broadcast
1154
+ s1_win = {d: [CT_SHORT[c] for c in CELLTYPES
1155
+ if P[d]["real_lora__raw"]["r_type"][c] > P[d]["real_lora__raw"]["bc_type"][c]] for d in DISEASE_DS}
1156
+ s1_all = [d for d in DISEASE_DS if len(s1_win[d]) == len(CELLTYPES)]
1157
+ s1_part = [d for d in DISEASE_DS if d not in s1_all]
1158
+ s1_part_txt = "; ".join(f"in {DS_LABEL[d]} LoRA wins only {', '.join(s1_win[d]) or 'none'}" for d in s1_part)
1159
+ gain = {d: {c: P[d]["real_lora__raw"]["r_type"][c] - P[d]["real_lora__raw"]["bc_type"][c] for c in CELLTYPES}
1160
+ for d in DISEASE_DS}
1161
+ s1_gain_txt = ", ".join(f"{DS_LABEL[d]} {CT_SHORT[max(gain[d], key=gain[d].get)]} "
1162
+ f"(+{max(gain[d].values()):.2f})" for d in DISEASE_DS)
1163
+
1164
+ now = _dt.datetime.now().strftime("%Y-%m-%d %H:%M")
1165
+ md = f"""# Figures: paired bulk → single-cell fine-tuning benchmark
1166
+
1167
+ Generated by `figures/make_figures.py` on {now}. Do not edit by hand: the numbers below are filled in from the score files. Re-run the script after new scores arrive.
1168
+
1169
+ Every figure is PNG (300 dpi) + PDF, sized for one column (89 mm wide). Each panel's plotted numbers, with the score file they came from, are in `source_data/<figure>.csv` (column `panel`) and `source_data/<figure>/panel_<id>.csv`. Colours are the same in every figure (Okabe–Ito palette): zero-shot raw light blue, zero-shot paired calibration blue, scSemiProfiler orange, LoRA vermillion, sc-only fine-tune purple. Reference lines: dashed = zero-shot generation from the sc-derived pseudobulk; dotted = real-bulk broadcast; dash-dot = cohort-mean null.
1170
+
1171
+ **Metric definitions (all from `tools/score_ft.py`).**
1172
+ - **Composition L1**: sum over six scANVI labels of |generated − observed| cell-type fraction, averaged over scored samples. Lower is better. The null is each sample's observed composition vs the mean of the other donors' samples (`comp_l1_obs_loo_null`).
1173
+ - **Precision / coverage**: PCA-50, k = 10 nearest-neighbour balls on up to 150 observed reference cells per scored sample. They depend on which samples are scored, so arms are compared only inside one scoring call (one draw, or one pooled call).
1174
+ - **Disease logFC r**: per cell type (T, B, monocyte, NK), Pearson r between the generated and observed case-vs-control log2 fold change of donor-averaged mean CP10K; the plotted value is the mean of the four r. **Real-bulk broadcast** = the same r for the input real bulk's own logFC, copied to every cell type.
1175
+ - **Top-50 DEG**: per cell type, Welch test + BH on donor pseudobulk (log1p CPM); overlap of the observed and generated top-50 lists (FDR < 0.05, ranked by |logFC|), summed over T/B/Mono/NK/DC (maximum 250{deg_max_txt}).
1176
+ - **Across-donor fraction r**: Pearson r across scored samples of generated vs observed fraction of one cell type (from `per_donor.csv`).
1177
+
1178
+ ## Fig. 1 — Few-pair scenario (`fig1_fewpair`)
1179
+
1180
+ **Plotted.** Rows a–e: composition L1, coverage, precision, disease logFC r, top-50 DEG. Columns: the five datasets. Each draw fine-tunes on 5 training donors (all their pairs) and scores every other usable sample (n under each dataset name = scored samples per draw). Arms: zero-shot on raw real bulk; zero-shot with paired calibration fitted on the same 5 pairs; scSemiProfiler with the same 5 pairs as representatives; LoRA on the same 5 pairs (fixed {fs_steps_txt}, no inner validation; training rows per draw: {fs_rows_txt}{'; ' + names(fs_missing) + ' runs are on server_2 and not checked here' if fs_missing else ''}). Bars = mean over draws; whiskers = SD; dots = single draws (5 draws). Reference segments are means over draws. In row e, Imperial has its own y-axis on the right because its DEG counts are about 5× larger. ImMicro has no case–control groups, so rows d–e are blank there. scSemiProfiler draws available: {sc_line}. When fewer than {max(n_draws.values())} draws exist, the count is printed above its bar ("n=0" = none yet).
1181
+
1182
+ **Takeaway.** Five pairs are enough to fix most of the real-bulk shift in cell realism: LoRA-5 raises coverage over zero-shot calibration in {len(cov_up)}/5 datasets. It raises the disease signal in every disease dataset ({r_txt}). That is above the real-bulk broadcast ({bc_txt}) in {names(above_bc)}, but not in {names(below_bc)}. {comp1} In ImMicro, L1 goes {f3(l1_im[0])} → {f3(l1_im[1])}. {sc_take}
1183
+
1184
+ ## Fig. 2 — Five-fold CV, pooled (`fig2_fivefold`)
1185
+
1186
+ **Plotted.** Same rows as Fig. 1. Each sample is scored once, by the fold model that never trained on it, in one pooled scoring call per dataset (n under each name = scored samples). Arms: zero-shot with paired calibration (α fitted on the fold's training donors); sc-only fine-tune (full model on the training donors' sc pseudobulk, no real bulk) with paired-calibrated input; LoRA fine-tuned on all training donors' real bulk → cells (early stopping on inner-validation donors). One value per arm, so no error bars. Sepsis DEG comes from `scores/ye2026_sepsis/pooled_deg/`. The Ji column is shaded: its bulk is whole blood, not PBMC.
1187
+
1188
+ **Takeaway.** Trained on every training donor of the other four folds (never the test fold), LoRA has the highest coverage of the three arms in {len(best_cov)}/5 datasets and the highest disease signal in {len(best_r)}/4 disease datasets. On Ji whole-blood bulk the sc-only model fails (coverage {f2(ji['pseudo_full__cal']['coverage'])}, disease r {f2(ji['pseudo_full__cal']['contrast_r'])}) while LoRA reaches coverage {f2(ji['real_lora__raw']['coverage'])} and r {f2(ji['real_lora__raw']['contrast_r'])}: the paired bulk is what teaches the whole-blood → PBMC map. Composition improves significantly over zero-shot calibration only in {names(sig2)} ({'; '.join(f"{DS_LABEL[d]} L1 {f3(P[d]['zs__cal']['comp_l1'])} → {f3(P[d]['real_lora__raw']['comp_l1'])}, p {fmt_p(w2[d][1])}" for d in sig2)}; paired Wilcoxon over scored samples). Zero-shot generation from the sc pseudobulk, which real-bulk users do not have, is still better on composition in {names(pseudo_better)}; LoRA matches or beats it in {names(lora_better)}.
1189
+
1190
+ ## Fig. 3 — LoRA learning curve (`fig3_learning_curve`)
1191
+
1192
+ **Plotted.** ImMicro (left) and sepsis (right), pooled 5-fold scoring (n = {mm['real_lora__raw']['n_scored']} and {se['real_lora__raw']['n_scored']} samples). x = training pairs per fold: 0 = no pairs, zero-shot on the real bulk as measured (pale) and after exon-length correction (sand); 5, 10, 20, 40 = nested stratified subsets (one subset per fold); the last point = every training donor of the fold ({fmt_n(st_im[st_im.arm == 'real_lora']['n_train'])} ImMicro, {fmt_n(st_se[st_se.arm == 'real_lora']['n_train'])} sepsis; the other four folds minus inner-val, never the test fold). Inner-validation donors ({inner_val} per fold, from RUN.json) are outside every subset. Rows: composition L1; coverage; ImMicro across-donor NK fraction r / sepsis disease logFC r; sepsis top-50 DEG (from `pooled_deg`); selected early-stopping step per fold (dots; bar = median; dashed line = 20,000-step cap), from `runs/<ds>/fold<k>/<arm>/RUN.json`. One pooled value per point, so no error bars.
1193
+
1194
+ **Takeaway.** Five pairs already remove most of the systematic shift: coverage goes {f2(mm['zs__raw']['coverage'])} (zero-shot; {f2(mm['zs__len']['coverage'])} after length correction) → {f2(mm['lora_n5__raw']['coverage'])} (ImMicro) and {f2(se['zs__raw']['coverage'])} ({f2(se['zs__len']['coverage'])}) → {f2(se['lora_n5__raw']['coverage'])} (sepsis). Donor-level and disease signals keep improving with more pairs: ImMicro NK r {f2(nk['lora_n5__raw'])} → {f2(nk['lora_n10__raw'])} → {f2(nk['lora_n20__raw'])} → {f2(nk['lora_n40__raw'])} → {f2(nk['real_lora__raw'])}; sepsis logFC r {f2(se['lora_n5__raw']['contrast_r'])} → {f2(se['lora_n10__raw']['contrast_r'])} → {f2(se['lora_n20__raw']['contrast_r'])} → {f2(se['lora_n40__raw']['contrast_r'])} → {f2(se['real_lora__raw']['contrast_r'])}, above the broadcast ({f2(se['real_lora__raw']['broadcast_r'])}) from {r_from} pairs on. Sepsis DEG reaches the broadcast level ({int(se['real_lora__raw']['deg_broadcast'])}) only from {deg_from} pairs on. With 5 pairs early stopping lands at {rng_steps(st_se, 'lora_n5')} steps (sepsis) and {rng_steps(st_im, 'lora_n5')} (ImMicro); ImMicro runs with 20+ pairs mostly hit the cap ({n_cap_im['lora_n20']}/5 folds at 20 pairs, {n_cap_im['lora_n40']}/5 at 40).
1195
+
1196
+ ## Supp. Fig. S1 — Per-cell-type disease signal (`figS1_celltype_contrast`)
1197
+
1198
+ **Plotted.** For each disease dataset (rows) and setting (left: 5 pairs, mean ± SD over 5 draws; right: 5-fold CV, each fold model trained on the other four folds, pooled): the per-cell-type logFC r (T, B, Mono, NK) of zero-shot with paired calibration, LoRA, and the real-bulk broadcast. Statistic `mean_cp10k` from `contrast.csv`. Group sizes (pooled, case vs control): sepsis {calls['ye2026_sepsis'].summary['contrast_definition']['n_case_donors']} vs {calls['ye2026_sepsis'].summary['contrast_definition']['n_control_donors']}, Ji {calls['ji2025_chili'].summary['contrast_definition']['n_case_donors']} vs {calls['ji2025_chili'].summary['contrast_definition']['n_control_donors']}, Giroux {calls['giroux2022'].summary['contrast_definition']['n_case_donors']} vs {calls['giroux2022'].summary['contrast_definition']['n_control_donors']}, Imperial {calls['imperial_eskd'].summary['contrast_definition']['n_case_donors']} vs {calls['imperial_eskd'].summary['contrast_definition']['n_control_donors']} samples.
1199
+
1200
+ **Takeaway.** With all pairs, LoRA beats the broadcast in every cell type in {names(s1_all)}. {('The exception: ' + s1_part_txt + '. There the case-control difference is shared across cell types, so the bulk logFC alone already fits each type well.') if s1_part else ''} The largest gain over the broadcast is in {s1_gain_txt}. With 5 pairs the per-type r varies between draws; the mean SD over cell types is largest in {DS_LABEL[s1_sd_max]} ({s1_sd[s1_sd_max]:.2f}; {', '.join(f"{DS_LABEL[d]} {s1_sd[d]:.2f}" for d in DISEASE_DS if d != s1_sd_max)}).
1201
+
1202
+ ## Supp. Fig. S2 — K augmentation gives no gain (`figS2_k_augmentation`)
1203
+
1204
+ **Plotted.** ImMicro and sepsis, pooled 5-fold scoring. Arms: plain LoRA (real bulk at K = 1000); LoRA where each training cell also sees its donor's real bulk at K ∈ {{250, 500, 1000, 2000, 4000}}; LoRA where half of each batch is a pretraining-style recipe. Panels a\u2013b: composition L1, precision, coverage (p = paired Wilcoxon of per-sample L1 vs plain LoRA). Panels c\u2013d: per-type across-donor fraction r (ImMicro) or disease logFC r (sepsis). Panel f: sepsis top-50 DEG with the real-bulk broadcast (dotted); panel e is blank (ImMicro has no contrast). One pooled value per bar.
1205
+
1206
+ **Takeaway.** Neither augmentation helps. Multi-K is slightly worse on ImMicro composition (ΔL1 {pvals[('immicro', 'lora_multik')][0]:+.3f}, p {fmt_p(pvals[('immicro', 'lora_multik')][1])}); every other difference is within noise (p ≥ {min(p for (d, k), (_, p, _) in pvals.items() if not (d == 'immicro' and k == 'lora_multik')):.2f}). The protocol keeps a single K = 1000.
1207
+
1208
+ ## Status
1209
+
1210
+ - scSemiProfiler-5 draws used: {sc_line}.
1211
+ - Rejected scSemiProfiler outputs (not plotted): {('; '.join(f"{DS_LABEL[r.dataset]} draw {r.draw}: {r.reason}" for r in rejected.itertuples()) or 'none')}.
1212
+ - Consistency checks vs `scores/<ds>/fewshot_n5/aggregate.json`: {('all match' if len(bad_checks) == 0 else f'{len(bad_checks)} MISMATCHES, see source_data/consistency_checks.csv')}.
1213
+
1214
+ ## Re-run
1215
+
1216
+ ```bash
1217
+ cd {T}
1218
+ python3 figures/make_figures.py
1219
+ ```
1220
+ CPU only; about a minute. It re-reads every score file, so new `scores/<ds>/fewshot_n5/draw<j>_scsemi5/` directories are picked up automatically. A scSemiProfiler output is used only if its donor set and reference equal those of the same draw's other arms and its receipt is verified; otherwise it is listed as rejected above.
1221
+ """
1222
+ (outdir / "FIGURES.md").write_text(md)
1223
+
1224
+
1225
+ # --------------------------------------------------------------------------------------
1226
+ def main(argv=None):
1227
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
1228
+ ap.add_argument("--scores-root", type=Path, default=T / "scores")
1229
+ ap.add_argument("--runs-root", type=Path, default=T / "runs")
1230
+ ap.add_argument("--out", type=Path, default=HERE)
1231
+ ap.add_argument("--no-md", action="store_true", help="skip writing FIGURES.md")
1232
+ args = ap.parse_args(argv)
1233
+ args.out.mkdir(parents=True, exist_ok=True)
1234
+ global SCORES_ROOT
1235
+ SCORES_ROOT = args.scores_root
1236
+ sources = Sources(args.out)
1237
+
1238
+ few, sc_status = load_fewpair(args.scores_root)
1239
+ sources.write("scsemi_status", sc_status.to_dict("records"))
1240
+ pooled, calls = load_pooled(args.scores_root)
1241
+ sources.write("sepsis_pooled_vs_pooled_deg_diffs", POOLED_DEG_DIFFS or [{"arm": "", "metric": "", "abs_diff": 0}])
1242
+ steps = pd.concat([load_steps(args.runs_root, d) for d in ("immicro", "ye2026_sepsis")], ignore_index=True)
1243
+ sources.write("fig3_selected_steps_all", steps.to_dict("records"))
1244
+ fs_runs = load_fewshot_runs(args.runs_root)
1245
+ sources.write("fig1_lora5_runs", fs_runs.to_dict("records"))
1246
+
1247
+ with warnings.catch_warnings():
1248
+ warnings.simplefilter("error", UserWarning) # fail on missing glyphs or layout problems
1249
+ warnings.filterwarnings("ignore", message=".*tight_layout.*")
1250
+ n_test = make_fig1(few, sc_status, args.out, sources)
1251
+ make_fig2(pooled, args.out, sources)
1252
+ make_fig3(pooled, calls, steps, args.out, sources)
1253
+ make_figS1(few, pooled, args.out, sources)
1254
+ pvals = make_figS2(pooled, calls, args.out, sources)
1255
+
1256
+ checks, bad = consistency_checks(few, args.scores_root, sources)
1257
+ if not args.no_md:
1258
+ write_figures_md(args.out, few, sc_status, pooled, calls, steps, pvals, n_test, bad, fs_runs)
1259
+
1260
+ used = sc_status[sc_status.status == "used"]
1261
+ print(f"scSemiProfiler draws used: {len(used)}/{len(sc_status)}; rejected: {(sc_status.status == 'rejected').sum()}")
1262
+ for r in sc_status[sc_status.status == "rejected"].itertuples():
1263
+ print(f" REJECTED {r.dataset} draw{r.draw}: {r.reason}")
1264
+ print(f"consistency checks: {len(checks)} rows, {len(bad)} mismatches")
1265
+ for p in sorted(args.out.glob("fig*.png")):
1266
+ print("wrote", p.relative_to(args.out.parent) if args.out.parent in p.parents else p)
1267
+ return 1 if len(bad) else 0
1268
+
1269
+
1270
+ if __name__ == "__main__":
1271
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tests/test_contrast_extra.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Synthetic checks of tools/contrast_extra.py (CPU, a few seconds; the limma test runs Rscript once, ~20 s).
2
+
3
+ Run: CUDA_VISIBLE_DEVICES= OMP_NUM_THREADS=4 <cxg_corpus python> -m pytest -q tests/test_contrast_extra.py
4
+
5
+ 1. RBO_ext (Webber, Moffat & Zobel 2010, ACM TOIS 28:20): identical lists -> 1; disjoint -> 0; a prefix of a ranking
6
+ -> 1 (eq. 32 extrapolates the agreement of the seen part); a hand-computed even-length case of eq. 30; the closed
7
+ form equals the defining infinite sum (1-p) sum_d A_d p^(d-1) with the paper's extrapolated agreements, for random
8
+ even and uneven lists; symmetry; the eq. 11 lower bound RBO_min <= RBO_ext.
9
+ 2. CAT: perfect agreement -> 1, sign-flipped -> 0 (same-sign) / 1 (any sign); the Monte-Carlo mean of random rankings
10
+ with random signs equals the stated chance k / (2 G) (any sign: k / G).
11
+ 3. Spearman-Brown: 2 r / (1 + r) and the noise-free ceiling sqrt(.); simulated split halves of a noisy vector recover
12
+ the full-data reliability and the expected r of a noise-free predictor.
13
+ 4. Hypergeometric chance of a top-list overlap (n m / G) against simulation.
14
+ 5. Spearman = Pearson of average-tie ranks (scipy.stats.spearmanr).
15
+ 6. limma batch: the Rscript wrapper on a toy count matrix with a planted effect recovers it, keeps the gene order,
16
+ leaves untested genes NaN and marks a < 2-per-group job undefined.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ import sys
22
+ from pathlib import Path
23
+
24
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
25
+ import numpy as np # noqa: E402
26
+ import pytest # noqa: E402
27
+ from scipy.stats import spearmanr # noqa: E402
28
+
29
+ TASK = Path(__file__).resolve().parents[1]
30
+ sys.path.insert(0, str(TASK / "tools"))
31
+ import contrast_extra as C # noqa: E402
32
+
33
+
34
+ # --------------------------------------------------------------------------- 1. RBO
35
+ def rbo_bruteforce(a: list, b: list, p: float, depth: int = 20000) -> float:
36
+ """(1-p) sum_{d>=1} A_d p^(d-1), truncated at a large depth, with Webber et al.'s extrapolation: for s < d <= l the
37
+ unseen items of the shorter list agree in proportion X_s / s (X_d^ext = X_d + (d - s) X_s / s); beyond l the
38
+ agreement stays at A_l^ext."""
39
+ short, long = (a, b) if len(a) <= len(b) else (b, a)
40
+ s, l_ = len(short), len(long)
41
+ A = []
42
+ for d in range(1, depth + 1):
43
+ if d <= l_:
44
+ x = len(set(short[:min(d, s)]) & set(long[:d]))
45
+ if d > s:
46
+ xs = len(set(short) & set(long[:s]))
47
+ x = x + (d - s) * xs / s
48
+ A.append(x / d)
49
+ else:
50
+ A.append(A[l_ - 1])
51
+ A = np.asarray(A)
52
+ return float((1 - p) * np.sum(A * p ** np.arange(depth)))
53
+
54
+
55
+ def test_rbo_identical_disjoint_prefix():
56
+ a = list("abcdefghij")
57
+ assert C.rbo_ext(a, a, 0.9) == pytest.approx(1.0, abs=1e-12)
58
+ assert C.rbo_ext(a, list("klmnopqrst"), 0.9) == pytest.approx(0.0, abs=1e-12)
59
+ assert C.rbo_ext(a[:4], a, 0.9) == pytest.approx(1.0, abs=1e-12) # shorter list = prefix of the longer
60
+ assert C.rbo_ext(a, a[:4], 0.98) == pytest.approx(1.0, abs=1e-12)
61
+
62
+
63
+ def test_rbo_hand_computed_even():
64
+ # S = a b c d, L = a c b e, p = 0.9: X = 1, 1, 3, 3 -> eq. 30: X_k/k p^k + (1-p)/p sum X_d/d p^d
65
+ p = 0.9
66
+ want = 0.75 * p ** 4 + (1 - p) / p * (1 * p + 0.5 * p ** 2 + 1 * p ** 3 + 0.75 * p ** 4)
67
+ assert C.rbo_ext(list("abcd"), list("acbe"), p) == pytest.approx(want, abs=1e-12)
68
+ assert want == pytest.approx(0.772750, abs=1e-6)
69
+
70
+
71
+ @pytest.mark.parametrize("seed", range(6))
72
+ def test_rbo_equals_definition_random(seed):
73
+ rng = np.random.default_rng(seed)
74
+ universe = [f"g{i}" for i in range(80)]
75
+ n1, n2 = int(rng.integers(5, 40)), int(rng.integers(5, 40))
76
+ a = list(rng.permutation(universe)[:n1])
77
+ b = list(rng.permutation(universe)[:n2])
78
+ for p in (0.9, 0.98):
79
+ assert C.rbo_ext(a, b, p) == pytest.approx(rbo_bruteforce(a, b, p), abs=1e-9)
80
+ assert C.rbo_ext(a, b, p) == pytest.approx(C.rbo_ext(b, a, p), abs=1e-12)
81
+
82
+
83
+ def test_rbo_min_lower_bound_even():
84
+ # eq. 11: RBO_min = (1-p)/p ( sum_{d<=k} (X_d - X_k)/d p^d - X_k ln(1-p) ) <= RBO_ext
85
+ rng = np.random.default_rng(7)
86
+ for _ in range(20):
87
+ u = [f"g{i}" for i in range(60)]
88
+ a, b = list(rng.permutation(u)[:25]), list(rng.permutation(u)[:25])
89
+ p = 0.9
90
+ X = C.prefix_overlaps(a, b).astype(float)
91
+ d = np.arange(1, 26)
92
+ rmin = (1 - p) / p * (np.sum((X - X[-1]) / d * p ** d) - X[-1] * np.log(1 - p))
93
+ assert rmin <= C.rbo_ext(a, b, p) + 1e-12
94
+
95
+
96
+ def test_rbo_rejects_duplicates_and_empty():
97
+ with pytest.raises(ValueError):
98
+ C.rbo_ext(["a", "a"], ["a"], 0.9)
99
+ assert np.isnan(C.rbo_ext([], ["a"], 0.9))
100
+
101
+
102
+ # --------------------------------------------------------------------------- 2. CAT
103
+ def test_cat_perfect_and_flipped():
104
+ G = 300
105
+ order = np.arange(G)
106
+ sign = np.ones(G)
107
+ for r in C.cat_curve(order, sign, order, sign):
108
+ assert r["cat_same_sign"] == 1.0 and r["cat_any_sign"] == 1.0
109
+ for r in C.cat_curve(order, sign, order, -sign):
110
+ assert r["cat_same_sign"] == 0.0 and r["cat_any_sign"] == 1.0
111
+ for r in C.cat_curve(order, sign, None, None): # undefined predictor scores 0
112
+ assert r["cat_same_sign"] == 0.0
113
+
114
+
115
+ def test_cat_chance_matches_simulation():
116
+ rng = np.random.default_rng(1)
117
+ G, nsim = 1000, 3000
118
+ ks = (10, 50, 100, 200)
119
+ acc_s = {k: [] for k in ks}
120
+ acc_a = {k: [] for k in ks}
121
+ for _ in range(nsim):
122
+ o, p_ = rng.permutation(G), rng.permutation(G)
123
+ so, sp_ = rng.choice([-1.0, 1.0], G), rng.choice([-1.0, 1.0], G)
124
+ for r in C.cat_curve(o, so, p_, sp_, ks):
125
+ acc_s[r["k"]].append(r["cat_same_sign"])
126
+ acc_a[r["k"]].append(r["cat_any_sign"])
127
+ for k in ks:
128
+ cs, ca = C.cat_chance(k, G)
129
+ assert cs == pytest.approx(k / (2 * G))
130
+ assert ca == pytest.approx(k / G)
131
+ se = np.std(acc_s[k]) / np.sqrt(nsim)
132
+ assert abs(np.mean(acc_s[k]) - cs) < 5 * se + 1e-4
133
+ assert abs(np.mean(acc_a[k]) - ca) < 5 * np.std(acc_a[k]) / np.sqrt(nsim) + 1e-4
134
+
135
+
136
+ # --------------------------------------------------------------------------- 3. Spearman-Brown
137
+ def test_spearman_brown_values():
138
+ assert C.spearman_brown(0.5) == pytest.approx(2 / 3)
139
+ assert C.spearman_brown(1.0) == pytest.approx(1.0)
140
+ assert C.spearman_brown(0.0) == 0.0
141
+ assert C.noise_free_ceiling(0.5) == pytest.approx(np.sqrt(2 / 3))
142
+ assert np.isnan(C.noise_free_ceiling(-0.2))
143
+ assert np.isnan(C.spearman_brown(float("nan")))
144
+
145
+
146
+ def test_spearman_brown_simulation():
147
+ """truth t; each cell carries t + noise; half means have noise var 2 s^2 / n, the full mean s^2 / n."""
148
+ rng = np.random.default_rng(3)
149
+ G, n, sd = 4000, 40, 3.0
150
+ t = rng.normal(size=G)
151
+ cells = t[None, :] + sd * rng.normal(size=(n, G))
152
+ A, B, full = cells[: n // 2].mean(0), cells[n // 2:].mean(0), cells.mean(0)
153
+ r_ab = np.corrcoef(A, B)[0, 1]
154
+ rel_full = 1.0 / (1.0 + sd ** 2 / n) # var(t) / var(full mean)
155
+ assert C.spearman_brown(r_ab) == pytest.approx(rel_full, abs=0.03)
156
+ # a noise-free predictor (t itself) correlates with the full-data vector at sqrt(reliability)
157
+ assert np.corrcoef(t, full)[0, 1] == pytest.approx(C.noise_free_ceiling(r_ab), abs=0.03)
158
+
159
+
160
+ # --------------------------------------------------------------------------- 4. hypergeometric chance
161
+ def test_expected_overlap_simulation():
162
+ rng = np.random.default_rng(5)
163
+ G, n, m = 2000, 50, 50
164
+ A = set(range(n))
165
+ sims = [len(A & set(rng.choice(G, m, replace=False))) for _ in range(5000)]
166
+ assert C.expected_overlap(n, m, G) == pytest.approx(n * m / G)
167
+ assert np.mean(sims) == pytest.approx(n * m / G, abs=0.05)
168
+ assert np.isnan(C.expected_overlap(5, 5, 0))
169
+
170
+
171
+ # --------------------------------------------------------------------------- 5. Spearman
172
+ def test_spearman_matches_scipy_with_ties():
173
+ rng = np.random.default_rng(11)
174
+ a = rng.integers(0, 6, 300).astype(float)
175
+ b = a + rng.normal(size=300)
176
+ assert C.spearman(a, b) == pytest.approx(spearmanr(a, b).statistic, abs=1e-12)
177
+ assert np.isnan(C.spearman(np.ones(10), np.arange(10.0)))
178
+
179
+
180
+ def test_rank_orders():
181
+ t = np.array([0.5, np.nan, -3.0, 2.0, -0.1])
182
+ o = C.rank_orders(t)
183
+ assert list(o["abs"]) == [2, 3, 0, 4]
184
+ assert list(o["up"]) == [3, 0, 4, 2]
185
+ assert list(o["down"]) == [2, 4, 0, 3]
186
+ assert list(o["tested"]) == [True, False, True, True, True]
187
+
188
+
189
+ # --------------------------------------------------------------------------- 6. limma wrapper
190
+ @pytest.mark.skipif(not C.RSCRIPT.exists(), reason="Rscript not available")
191
+ def test_limma_batch_planted_effect(tmp_path):
192
+ rng = np.random.default_rng(2)
193
+ G, n_case, n_ctrl = 400, 6, 6
194
+ mu = rng.gamma(2.0, 50.0, size=G)
195
+ mu[-5:] = 0.0 # untested genes (all zero)
196
+ fc = np.ones(G)
197
+ fc[:20] = 4.0 # planted up-regulated genes
198
+ is_case = np.r_[np.ones(n_case, bool), np.zeros(n_ctrl, bool)]
199
+ lam = mu[None, :] * np.where(is_case[:, None], fc[None, :], 1.0)
200
+ counts = rng.negative_binomial(10, 10 / (10 + lam)).astype(float)
201
+ lb = C.LimmaBatch(tmp_path / "w", G)
202
+ lb.add("toy", counts, is_case)
203
+ lb.add("small", counts[[0, 1, 6]], is_case[[0, 1, 6]]) # 2 case + 1 control: undefined, no job
204
+ res = lb.run(2, tmp_path / "R.log")
205
+ assert not lb.meta["small"]["defined"]
206
+ for flt in C.LIMMA_FILTERS:
207
+ r = res["results"][f"toy|{flt}"]
208
+ assert r["status"] == "ok"
209
+ assert np.isnan(r["t"][-5:]).all()
210
+ top = np.argsort(-np.nan_to_num(r["t"], nan=-np.inf))[:20]
211
+ assert len(set(top) & set(range(20))) >= 18
212
+ assert (r["q"][:20] < 0.05).mean() > 0.9
213
+ assert np.nanmean(r["logFC"][:20]) == pytest.approx(2.0, abs=0.4)
214
+ assert any("limma 3." in x for x in res["versions"]) and any("edgeR" in x for x in res["versions"])
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/build_archive_request.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Archive-maintenance request for the paired fine-tuning benchmark (PBISC-Diffusion paper, pbisc-diffusion).
3
+
4
+ Follows paper-release-20260928/maintenance/POLICY.md: every payload is listed explicitly (host, exact path, kind,
5
+ state); generated arrays are not payloads but inference locations with their receipts; work that is still running
6
+ (the scSemiProfiler baseline) is registered as running/planned locations only.
7
+
8
+ Payloads (completed): code, documents, figures and their source CSVs, score tables, paired-data manifests and
9
+ small data (features, pairs, folds, splits, cell metadata), the condition NPZs every sampler read, run receipts
10
+ (RUN.json / history.json, which carry every fine-tuned checkpoint's sha256), queues, and the recommended-protocol
11
+ LoRA checkpoints (all-training-donor LoRA per fold, and the 5-pair LoRA per draw) on both hosts.
12
+ Not uploaded (location/provenance only): other fine-tuned checkpoints (sha256 in their RUN.json), the per-cell
13
+ count arrays cells_panel6k.npz / cells_full.npz (sha256 in BUILD.json / MANIFEST.json; rebuilt from the datalake
14
+ processing outputs), generated NPZs.
15
+ usage: build_archive_request.py OUT.json
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import glob
20
+ import json
21
+ import os
22
+ import subprocess
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ T = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
27
+ DATASETS = ("immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
28
+
29
+
30
+ def files(patterns, root=T):
31
+ out = []
32
+ for p in patterns:
33
+ for f in sorted(glob.glob(str(root / p), recursive=True)):
34
+ q = Path(f)
35
+ if q.is_file() and not q.is_symlink() and "__pycache__" not in q.parts and not q.name.endswith((".bak", ".pyc")) \
36
+ and ".bak_" not in q.name:
37
+ out.append(str(q))
38
+ return sorted(set(out))
39
+
40
+
41
+ def remote_files(patterns):
42
+ # symlinks are skipped: server_2's Imperial checkpoints point into the archive itself, which prepare refuses
43
+ cmd = ("cd %s && for p in %s; do for f in $p; do [ -f \"$f\" ] && [ ! -L \"$f\" ] && echo \"$f\"; done; done; true"
44
+ % (T, " ".join(patterns)))
45
+ res = subprocess.run(["ssh", "-n", "spark-0110", cmd], capture_output=True, text=True, check=True)
46
+ return sorted({str(T / l.strip()) for l in res.stdout.splitlines() if l.strip()})
47
+
48
+
49
+ def remote_json(path):
50
+ res = subprocess.run(["ssh", "-n", "spark-0110", f"cat '{path}'"], capture_output=True, text=True)
51
+ return json.loads(res.stdout) if res.returncode == 0 and res.stdout.strip() else None
52
+
53
+
54
+ def main(out: str) -> int:
55
+ assets = []
56
+
57
+ def add(paths, kind, host="server_1", state="completed"):
58
+ for p in paths:
59
+ assets.append({"host": host, "source": p, "kind": kind, "state": state})
60
+
61
+ add(files(["tools/*.py", "tools/*.sh", "tests/*.py", "figures/make_figures.py",
62
+ "scsemi/tools/*.py", "scsemi/tools/*.sh", "scsemi/tests/*.py"]), "code")
63
+ add(files(["README.md", "FEASIBILITY.md", "figures/FIGURES.md", "scsemi/README.md",
64
+ "data/*/QC_REPORT.md"]), "document")
65
+ add(files(["figures/*.png", "figures/*.pdf"]), "figure")
66
+ add(files(["figures/source_data/**/*.csv"]), "table")
67
+ add(files(["scores/*/*/summary.json", "scores/*/*/per_donor.csv", "scores/*/*/contrast.csv", "scores/*/*/README.md",
68
+ "scores/*/fewshot_n5/*/summary.json", "scores/*/fewshot_n5/*/per_donor.csv",
69
+ "scores/*/fewshot_n5/*/contrast.csv", "scores/*/fewshot_n5/*/README.md",
70
+ "scores/*/AGGREGATE.md", "scores/*/aggregate.json",
71
+ "scores/*/fewshot_n5/AGGREGATE.md", "scores/*/fewshot_n5/aggregate.json"]), "table")
72
+ # 2026-10-01: Giroux sex-linked-gene rescoring (scores_nosex, chrY-only sensitivity scores_nochrY) and its gene list
73
+ add(files([f"{d}/{p}" for d in ("scores_nosex", "scores_nochrY")
74
+ for p in ("README.md", "**/summary.json", "**/per_donor.csv", "**/contrast.csv", "**/README.md")]), "table")
75
+ add(files(["data/sex_linked_genes/*.csv", "data/sex_linked_genes/*.md", # BUILD.json is caught by data/*/BUILD.json
76
+ "data/sex_linked_genes/sources/*.txt", "data/sex_linked_genes/sources/README*"]), "metadata")
77
+ # 2026-10-01 LoRA rank sweep (r4/r64) and equal-pair-budget calibration: per-fold and pooled scores + comparison tables
78
+ add(files([f"scores/*/{d}/*/{p}" for d in ("lora_rank_20261001", "cal_budget_20261001")
79
+ for p in ("summary.json", "per_donor.csv", "contrast.csv", "README.md")]), "table")
80
+ add(files(["scores/*/rankcal_20261001.md", "scores/*/rankcal_20261001.json"]), "table")
81
+ # 2026-10-02 extra realism/diversity metrics (classifier AUC, 1-NN, MMD2, scSemiProfiler E_N, k = 3/5/10 P/C)
82
+ add(files(["scores_extra/**/*.csv", "scores_extra/**/*.json", "scores_extra/**/*.md"]), "table")
83
+ add(files(["scores_extra/_code/*.py"]), "code")
84
+ add(files(["logs/extraA_*.log", "logs/extraA_*.jobs", "logs/extraB_*.log", "logs/extraB_*.jobs"]), "log")
85
+ # equal-pair-budget calibration (alpha fitted on each lora_n<n> run's own pairs)
86
+ add(files(["data/*/fold*/alpha_n*.npy"]), "data")
87
+ add(files(["data/*/CAL_BUDGET.json"]), "metadata")
88
+ add(files(["data/*/features.npz", "data/*/cells_obs.parquet", "data/*/fold*/alpha.npy",
89
+ "data/*/fewshot_n5/draw*/alpha.npy"]), "data")
90
+ add(files(["data/*/pairs.csv", "data/*/folds.csv", "data/*/samples.csv", "data/*/identity_*.csv",
91
+ "data/*/pairs_sensitivity_offday.csv", "data/*/MANIFEST.json", "data/*/PREPARE.json",
92
+ "data/*/BUILD.json", "data/*/cells_full.BUILD.json", "data/*/fewshot_n5/DRAWS.json",
93
+ "data/*/fewshot_n5/draw*/*.txt"]), "metadata")
94
+ add(files(["data/*/conditions_*.npz", "data/*/fold*/*.npz", "data/*/fewshot_n5/*.npz",
95
+ "data/*/fewshot_n5/draw*/*.npz"]), "condition")
96
+ add(files(["runs/**/RUN.json", "runs/**/history.json"]), "log")
97
+ # server_2 ran its own copies of the scSemiProfiler queues (some exist only there): keep them as the as-run record
98
+ subprocess.run(["rsync", "-a", f"spark-0110:{T}/scsemi/queues/", f"{T}/scsemi/queues/as_run_server2/",
99
+ "--include=server2_*.txt", "--exclude=*"], check=True)
100
+ add(files(["queues/*.txt", "scsemi/queues/*.txt", "scsemi/queues/as_run_server2/*.txt",
101
+ "scsemi/vendor/compatibility.patch",
102
+ "scsemi/vendor/source_manifest.json"]), "config")
103
+ # recommended protocol weights (LoRA merged into the base weights): server_1 datasets here, Imperial on server_2
104
+ add(files(["runs/*/fold*/real_lora/checkpoint_ft.pt", "runs/*/fewshot_n5/draw*/lora/checkpoint_ft.pt"]), "checkpoint")
105
+ add(remote_files(["runs/imperial_eskd/fold*/real_lora/checkpoint_ft.pt",
106
+ "runs/imperial_eskd/fewshot_n5/draw*/lora/checkpoint_ft.pt"]), "checkpoint", host="server_2")
107
+ add(remote_files(["runs/imperial_eskd/*/*/RUN.json", "runs/imperial_eskd/*/*/history.json",
108
+ "runs/imperial_eskd/fewshot_n5/*/*/RUN.json", "runs/imperial_eskd/fewshot_n5/*/*/history.json"]),
109
+ "log", host="server_2")
110
+
111
+ # ---- inference locations (not payloads) ------------------------------------------------------------------------
112
+ locs = []
113
+
114
+ def receipt_fields(rec: dict | None) -> dict:
115
+ if not rec:
116
+ return {}
117
+ keep = {}
118
+ for k in ("output_sha256", "checkpoint", "checkpoint_sha256", "input_condition_path", "input_condition_sha256",
119
+ "condition_npz", "condition_sha256", "seed", "steps", "generated_counts_rows"):
120
+ if k in rec and not isinstance(rec[k], (dict, list)):
121
+ keep[k] = rec[k]
122
+ if "output_sha256" in keep:
123
+ keep["sha256"] = keep["output_sha256"]
124
+ return keep
125
+
126
+ def loc(host, npz, experiment, cohort, rec=None, state="completed"):
127
+ rpath = npz[:-4] + ".log"
128
+ item = {"host": host, "path": npz, "state": state, "experiment": experiment, "cohort": cohort,
129
+ "artifact_role": "inference_output"}
130
+ if state in ("completed", "final"):
131
+ item["receipt"] = rpath
132
+ item.update(receipt_fields(rec))
133
+ locs.append(item)
134
+
135
+ for ds in DATASETS:
136
+ # present on server_1
137
+ for npz in files([f"generated/{ds}/**/*.npz"]):
138
+ rel = Path(npz).relative_to(T / "generated" / ds)
139
+ rp = Path(npz[:-4] + ".log")
140
+ rec = json.loads(rp.read_text()) if rp.is_file() and rp.stat().st_size else None
141
+ if rec is None:
142
+ continue
143
+ loc("server_1", npz, f"paired_finetune_{rel.parts[0]}", ds, rec)
144
+ # moved to server_2 (sha-verified move; .moved marker kept on server_1)
145
+ for mk in files([f"generated/{ds}/**/*.moved"]):
146
+ npz = mk[:-6] + ".npz"
147
+ rp = Path(mk[:-6] + ".log")
148
+ rec = json.loads(rp.read_text()) if rp.is_file() and rp.stat().st_size else None
149
+ rel = Path(npz).relative_to(T / "generated" / ds)
150
+ item_state = "completed" if rec else "presence_only"
151
+ loc("server_2", npz, f"paired_finetune_{rel.parts[0]}", ds, rec, state=item_state)
152
+ locs[-1]["move_marker_server_1"] = mk
153
+ # Imperial outputs live on server_2
154
+ for npz in remote_files(["generated/imperial_eskd/*/*.npz", "generated/imperial_eskd/fewshot_n5/*/*.npz",
155
+ "generated/imperial_eskd/pooled/*.npz"]):
156
+ rec = remote_json(npz[:-4] + ".log")
157
+ if rec is None:
158
+ continue
159
+ rel = Path(npz).relative_to(T / "generated" / "imperial_eskd")
160
+ loc("server_2", npz, f"paired_finetune_{rel.parts[0]}", "imperial_eskd", rec)
161
+ # scSemiProfiler draws of the other datasets that ran on server_2 (queues server2_*.txt)
162
+ for npz in remote_files([f"generated/{ds}/fewshot_n5/draw*/scsemi5__raw.npz" for ds in DATASETS
163
+ if ds != "imperial_eskd"]):
164
+ rec = remote_json(npz[:-4] + ".log")
165
+ if rec is None:
166
+ continue
167
+ rel = Path(npz).relative_to(T / "generated")
168
+ loc("server_2", npz, "paired_finetune_fewshot_n5", rel.parts[0], rec)
169
+ # scSemiProfiler baseline still running: register in-progress / planned draws by their future output path
170
+ done = {l["path"] for l in locs}
171
+ run_queues = [T / "scsemi" / "queues" / "server1_fewshot_d0first.txt"] + \
172
+ sorted((T / "scsemi" / "queues" / "as_run_server2").glob("server2_*.txt"))
173
+ for qf in run_queues:
174
+ host = "server_1" if qf.name.startswith("server1_") else "server_2"
175
+ for line in qf.read_text().splitlines():
176
+ if not line.startswith("fewshot|"):
177
+ continue
178
+ _, ds, j = line.split("|")[:3]
179
+ npz = str(T / "generated" / ds / "fewshot_n5" / f"draw{j}" / "scsemi5__raw.npz")
180
+ if npz in done:
181
+ continue
182
+ state = "planned"
183
+ locs.append({"host": host, "path": npz, "state": state, "experiment": "paired_finetune_fewshot_n5_scsemiprofiler",
184
+ "cohort": ds, "artifact_role": "inference_output",
185
+ "note": "scSemiProfiler 5-pair baseline queued or running on this host at request time"})
186
+ done.add(npz)
187
+ req = {
188
+ "project_id": "pbisc-diffusion",
189
+ "summary": (
190
+ "Within-dataset paired fine-tuning benchmark of the final 6k 1x E16 model (plans/paired_finetune_intradataset_20260927): "
191
+ "LoRA (recommended protocol), full and condition-encoder fine-tuning, sc-only control, LoRA learning curve, "
192
+ "K-augmentation null, 5-pair deployment scenario, on ImMicro, Ye 2026 sepsis, Imperial ESKD COVID, Giroux 2022 and "
193
+ "Ji 2025 (whole-blood bulk); scores (scANVI composition, precision/coverage, contrast logFC r, top-50 DEG), figures, "
194
+ "paired-data manifests, conditions, run receipts and the recommended-protocol LoRA checkpoints. The scSemiProfiler "
195
+ "5-pair baseline: every finished draw is included as score tables and a completed location; draws not yet "
196
+ "finished at request time (none on 2026-09-30: 25/25 done) are planned locations. Not uploaded: per-cell count "
197
+ "arrays and non-recommended fine-tuned checkpoints (sha256 recorded in BUILD/MANIFEST and RUN.json)."),
198
+ "assets": assets,
199
+ "inference_locations": locs,
200
+ }
201
+ Path(out).write_text(json.dumps(req, indent=1))
202
+ kinds = {}
203
+ for a in assets:
204
+ kinds[(a["host"], a["kind"])] = kinds.get((a["host"], a["kind"]), 0) + 1
205
+ print(json.dumps({"assets": len(assets), "by_host_kind": {f"{h}/{k}": v for (h, k), v in sorted(kinds.items())},
206
+ "locations": len(locs), "location_states": {s: sum(l["state"] == s for l in locs) for s in {l["state"] for l in locs}}},
207
+ indent=1))
208
+ return 0
209
+
210
+
211
+ if __name__ == "__main__":
212
+ sys.exit(main(sys.argv[1]))
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/build_tpm_zeroshot.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Zero-pair baseline with exon-length correction: length-corrected (TPM-like) real bulk -> base model (CPU only).
3
+
4
+ Added 2026-10-02 for the "pairs needed" learning curve. Its x = 0 point must not use any paired data, so it shows:
5
+ zero-shot, real bulk as measured (generated/<ds>/fewshot_n5/zs__raw_all.npz, existing)
6
+ zero-shot, length-corrected bulk (this script: each bulk count divided by the gene's union-exon length in kb, then
7
+ the same fixed-depth condition arithmetic)
8
+ The calibration arm fitted on n pairs stays at x = n (cal_budget_20261001); the old x = 0 calibration point, whose alpha
9
+ came from every training pair of the fold, is dropped from the learning curve.
10
+
11
+ The length rule is imported unchanged from conditions_more (union_exon_kb / length_corrected: Ensembl 95 union-exon
12
+ lengths, rows with status == "valid"; a measured gene with no valid length becomes unmeasured). Everything else is the
13
+ paired benchmark's own code path (prepare_dataset.load / RB.to_condition_counts / write_npz), and the raw arm rebuilt
14
+ through that path must equal data/<ds>/fewshot_n5/all_usable_raw.npz bit for bit, so the two arms differ only in the
15
+ expression vector. Rows = every usable row (fold >= 0), the same rows and order as all_usable_raw.npz; sampled with the
16
+ same seed (20260927), so cell i of a sample starts from the same noise as in the raw arm.
17
+
18
+ usage: CUDA_VISIBLE_DEVICES= build_tpm_zeroshot.py immicro ye2026_sepsis
19
+ writes data/<ds>/zeroshot_tpm_20261002/{all_usable_tpm.npz, BUILD.json} and prints the queue lines for run_queue.sh
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import hashlib
24
+ import importlib.util
25
+ import json
26
+ import os
27
+ import sys
28
+ from datetime import datetime, timezone
29
+ from pathlib import Path
30
+
31
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
32
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
33
+ import numpy as np
34
+ import pandas as pd
35
+
36
+ TASK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
37
+ sys.path.insert(0, str(TASK / "tools"))
38
+ import prepare_dataset as PD # noqa: E402
39
+
40
+ LENGTH_RULE = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/utility_studies_final6k_20260925/"
41
+ "conditions_more/tools/build_realbulk_conditions_rawtpm.py")
42
+ _spec = importlib.util.spec_from_file_location("build_realbulk_conditions_rawtpm", LENGTH_RULE)
43
+ LR = importlib.util.module_from_spec(_spec)
44
+ sys.modules[_spec.name] = LR
45
+ _spec.loader.exec_module(LR)
46
+ SUB = "zeroshot_tpm_20261002"
47
+ SEED = 20260927
48
+ CELLS_PER_BULK = 1500
49
+
50
+
51
+ def sha(p: Path) -> str:
52
+ h = hashlib.sha256()
53
+ with open(p, "rb") as f:
54
+ for b in iter(lambda: f.read(1 << 20), b""):
55
+ h.update(b)
56
+ return h.hexdigest()
57
+
58
+
59
+ def build(name: str) -> list[str]:
60
+ ds = TASK / "data" / name
61
+ d = PD.load(ds)
62
+ folds = pd.read_csv(ds / "folds.csv")
63
+ if not np.array_equal(folds["sample_id"].astype(str).to_numpy(), d["sample_ids"]):
64
+ raise SystemExit(f"{name}: folds.csv rows differ from features.npz")
65
+ usable = folds.index[folds["fold"] >= 0].to_numpy()
66
+ ref = np.load(ds / "fewshot_n5" / "all_usable_raw.npz", allow_pickle=True)
67
+ if not np.array_equal(ref["dataset_rows"], usable):
68
+ raise SystemExit(f"{name}: all_usable_raw.npz rows differ from the usable rows")
69
+ out = ds / SUB
70
+ out.mkdir(exist_ok=True)
71
+ # 1. the raw arm through this exact path must reproduce the published all-usable raw NPZ
72
+ raw = PD.RB.to_condition_counts(d["bulk"], d["bulk_valid"])
73
+ tmp = out / "_check_raw.npz"
74
+ PD.write_npz(tmp, d, usable, raw, d["bulk_valid"], CELLS_PER_BULK, "raw")
75
+ chk = np.load(tmp, allow_pickle=True)
76
+ for k in ref.files:
77
+ if not np.array_equal(chk[k], ref[k]):
78
+ raise SystemExit(f"{name}: rebuilt raw arm differs from all_usable_raw.npz in {k}")
79
+ tmp.unlink()
80
+ # 2. length-corrected arm: per-kb counts on the genes that have a valid length, same depth arithmetic
81
+ kb = LR.union_exon_kb(d["gene_ids"])
82
+ rate, support = LR.length_corrected(d["bulk"], d["bulk_valid"], kb)
83
+ tpm = PD.RB.to_condition_counts(rate, support)
84
+ path = out / "all_usable_tpm.npz"
85
+ digest = PD.write_npz(path, d, usable, tpm, support.astype(np.float32), CELLS_PER_BULK, "zs_tpm")
86
+ new = np.load(path, allow_pickle=True)
87
+ same = [k for k in ref.files if k not in ("bulk_counts", "bulk_measurement_fraction", "arm")]
88
+ for k in same:
89
+ if not np.array_equal(new[k], ref[k]):
90
+ raise SystemExit(f"{name}: {k} differs between the length-corrected and raw arms")
91
+ lost = d["bulk_valid"][usable] & ~support[usable]
92
+ man = {"dataset": name, "written_utc": datetime.now(timezone.utc).isoformat(), "script": str(Path(__file__).resolve()),
93
+ "script_sha256": sha(Path(__file__)), "length_rule": str(LENGTH_RULE), "length_rule_sha256": sha(LENGTH_RULE),
94
+ "gene_lengths": str(LR.GENE_LENGTHS), "gene_lengths_sha256": sha(LR.GENE_LENGTHS),
95
+ "features_sha256": sha((ds / "features.npz").resolve()), "raw_reference": str(ds / "fewshot_n5/all_usable_raw.npz"),
96
+ "raw_reference_sha256": sha(ds / "fewshot_n5/all_usable_raw.npz"), "raw_rebuilt_identical": True,
97
+ "rows": int(usable.size), "seed": SEED, "cells_per_bulk": CELLS_PER_BULK,
98
+ "measured_genes_without_length_dropped": int(lost.any(axis=0).sum()),
99
+ "model_genes_with_length": int(np.isfinite(kb).sum()), "genes": int(kb.size),
100
+ "files": {"all_usable_tpm.npz": digest}}
101
+ (out / "BUILD.json").write_text(json.dumps(man, indent=1))
102
+ tag = {"immicro": "imm", "ye2026_sepsis": "ye2"}.get(name, name[:3])
103
+ g = TASK / "generated" / name / SUB
104
+ g.mkdir(parents=True, exist_ok=True)
105
+ print(json.dumps({k: man[k] for k in ("dataset", "rows", "measured_genes_without_length_dropped", "model_genes_with_length")}))
106
+ return [f"sample|{tag}_zs_tpm_all|base|{path}|{SEED}|{g / 'zs__tpm_all.npz'}"]
107
+
108
+
109
+ def main(argv: list[str]) -> int:
110
+ lines = [ln for name in argv for ln in build(name)]
111
+ q = TASK / "queues" / "zeroshot_tpm_20261002.txt"
112
+ q.write_text("# 2026-10-02: zero-pair, exon-length-corrected bulk -> base model (learning curve x = 0)\n" + "\n".join(lines) + "\n")
113
+ print(q.read_text())
114
+ return 0
115
+
116
+
117
+ if __name__ == "__main__":
118
+ sys.exit(main(sys.argv[1:]))