Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261008T125804Z-deck-fig2-3-healthy-fig5-rare/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/fig2_healthy_cells.pdf +0 -0
- paper-releases/pbisc-diffusion/updates/20261008T125804Z-deck-fig2-3-healthy-fig5-rare/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/fig5_rare_states.py +277 -0
- paper-releases/pbisc-diffusion/updates/20261008T125804Z-deck-fig2-3-healthy-fig5-rare/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec10_paired_subset_cohorts.py +448 -0
- paper-releases/pbisc-diffusion/updates/20261008T125804Z-deck-fig2-3-healthy-fig5-rare/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sync_sec09_text.py +85 -0
paper-releases/pbisc-diffusion/updates/20261008T125804Z-deck-fig2-3-healthy-fig5-rare/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/fig2_healthy_cells.pdf
ADDED
|
Binary file (26.8 kB). View file
|
|
|
paper-releases/pbisc-diffusion/updates/20261008T125804Z-deck-fig2-3-healthy-fig5-rare/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/fig5_rare_states.py
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Fig. 5 rare-cell slides of the 2026-09-30 paper-summary deck (2026-10-08; user decision of that day: Fig. 5 shows the
|
| 3 |
+
fraction of rare cells and how well rare states are found, on the paired disease cohorts; main comparison = 5 pairs,
|
| 4 |
+
LoRA-5 vs scSemiProfiler-5; 5-fold reported separately).
|
| 5 |
+
|
| 6 |
+
CPU only, plotting only. Source: plans/rare_states_paired_20261008/out/{summary,contrasts}.csv (tools/rare_paired.py:
|
| 7 |
+
benchmark labels and Poisson read-out reproduced cell by cell; literature marker rules of
|
| 8 |
+
plans/rare_states_screen_20261004/tools/states.json; observed parent cells thinned to the generated parent depth).
|
| 9 |
+
State x cohort pairs are shown when the observed cells hold enough of the state to judge it: >= MIN_OBS state cells
|
| 10 |
+
(native depth, scored donors) in >= MIN_DONORS donors; the negative control is left out.
|
| 11 |
+
fraction generated % / observed % (thinned) of the state within its parent, log2 (0 = exact; band = within 2-fold)
|
| 12 |
+
donors Spearman over donors of generated % vs observed %
|
| 13 |
+
direction case-vs-control difference of donor means has the observed sign (5 donors: share of draws)
|
| 14 |
+
Slides:
|
| 15 |
+
A "Rare states with 5 pairs: how many cells" fraction, LoRA-5 vs scSemiProfiler-5 vs zero-shot
|
| 16 |
+
B "Rare states with 5 pairs: in the right donors" donor Spearman and disease direction
|
| 17 |
+
C "5-fold CV: rare states" both, reported separately
|
| 18 |
+
Outputs: figures/fig5_rare_{fraction,donors,fivefold}.{png,pdf}, data/fig5_rare_states.csv,
|
| 19 |
+
data/fig5_rare_states_slide_text.json
|
| 20 |
+
"""
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import json
|
| 24 |
+
import os
|
| 25 |
+
import sys
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
import pandas as pd
|
| 32 |
+
|
| 33 |
+
DECK = Path(__file__).resolve().parents[1]
|
| 34 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 35 |
+
import style as ST # noqa: E402
|
| 36 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 37 |
+
from matplotlib.lines import Line2D # noqa: E402
|
| 38 |
+
|
| 39 |
+
SRC = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/rare_states_paired_20261008/out")
|
| 40 |
+
FIG, DAT = DECK / "figures", DECK / "data"
|
| 41 |
+
NAME = {"ye2026_sepsis": "Sepsis", "imperial_eskd": "Imperial", "giroux2022": "Giroux", "ji2025_chili": "Ji"}
|
| 42 |
+
MIN_OBS, MIN_DONORS = 30, 3
|
| 43 |
+
NEG = "negative control"
|
| 44 |
+
FEW = [("zs_raw", "Zero-shot, real bulk", ST.ARM["zs_raw"], "o"), ("scsemi5", "scSemiProfiler, 5 donors", ST.ARM["scsemi"], "D"),
|
| 45 |
+
("lora5", "PBISC LoRA, 5 donors", ST.ARM["lora"], "o")]
|
| 46 |
+
POOL = [("zs__raw", "Zero-shot, real bulk", ST.ARM["zs_raw"], "o"), ("scsemi__raw", "scSemiProfiler, same pairs", ST.ARM["scsemi"], "D"),
|
| 47 |
+
("real_lora__raw", "PBISC LoRA", ST.ARM["lora"], "o")]
|
| 48 |
+
SHORT = {"C1Q-high monocyte (reference)": "C1Q-high mono", "Cycling T/NK": "Cycling T/NK",
|
| 49 |
+
"Cycling activated T (CD38/HLA-DR)": "Cycling act. T", "Proliferating T (label)": "Prolif. T (label)",
|
| 50 |
+
"Plasmablast (label)": "Plasmablast (label)", "Plasmablast (markers)": "Plasmablast", "MS1 monocyte (IL1R2+)": "MS1 mono",
|
| 51 |
+
"Cycling monocyte (Ye 2026)": "Cycling mono", "ISG-high monocyte (positive control)": "ISG-high mono",
|
| 52 |
+
"ISG-high T": "ISG-high T", "DN2 / ABC B": "DN2 / ABC B", "HSPC": "HSPC", "Cytotoxic CD4 T": "Cytotoxic CD4 T",
|
| 53 |
+
"Granulocyte-like (LDG)": "Granulocyte-like"}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def load():
|
| 57 |
+
s = pd.read_csv(SRC / "summary.csv")
|
| 58 |
+
c = pd.read_csv(SRC / "contrasts.csv")
|
| 59 |
+
s = s[~s.state.str.contains(NEG, case=False)]
|
| 60 |
+
c = c[~c.state.str.contains(NEG, case=False)]
|
| 61 |
+
s["log2_ratio"] = np.log2(s.gen_over_obs.where(s.gen_over_obs > 0))
|
| 62 |
+
# judgeable state x cohort pairs: from the LoRA arm's observed side (identical cells in every arm)
|
| 63 |
+
ref = s[s.arm.isin(["lora5", "real_lora__raw"])]
|
| 64 |
+
ok = ref.groupby(["dataset", "state"]).agg(obs=("obs_state_native", "min"), don=("donors_with_state_obs", "min"))
|
| 65 |
+
keep = ok[(ok.obs >= MIN_OBS) & (ok.don >= MIN_DONORS)].index
|
| 66 |
+
s = s.set_index(["dataset", "state"]).loc[lambda d: d.index.isin(keep)].reset_index()
|
| 67 |
+
c = c.set_index(["dataset", "state"]).loc[lambda d: d.index.isin(keep)].reset_index()
|
| 68 |
+
return s, c, list(keep)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def agg_few(s, c):
|
| 72 |
+
f = s[s.design == "fewpair"]
|
| 73 |
+
a = f.groupby(["dataset", "state", "arm"]).agg(log2_ratio=("log2_ratio", "mean"), spearman=("spearman_donors", "mean"),
|
| 74 |
+
auroc=("auroc_high_low", "mean")).reset_index()
|
| 75 |
+
d = c[c.design == "fewpair"].groupby(["dataset", "state", "arm"]).same_direction.mean().rename("direction").reset_index()
|
| 76 |
+
return a.merge(d, on=["dataset", "state", "arm"], how="left")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def agg_pool(s, c):
|
| 80 |
+
f = s[s.design == "fivefold"][["dataset", "state", "arm", "log2_ratio", "spearman_donors", "auroc_high_low"]]
|
| 81 |
+
f = f.rename(columns={"spearman_donors": "spearman", "auroc_high_low": "auroc"})
|
| 82 |
+
d = c[c.design == "fivefold"][["dataset", "state", "arm", "same_direction"]].rename(columns={"same_direction": "direction"})
|
| 83 |
+
d["direction"] = d.direction.astype(float)
|
| 84 |
+
return f.merge(d, on=["dataset", "state", "arm"], how="left")
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def dotplot(ax, tab, keys, arms, col, xlab, band=None, xlim=None, ref=None):
|
| 88 |
+
y = np.arange(len(keys))
|
| 89 |
+
for i, (ds, st) in enumerate(keys):
|
| 90 |
+
if i % 2 == 0:
|
| 91 |
+
ax.axhspan(i - 0.5, i + 0.5, color="#F4F4F4", zorder=0)
|
| 92 |
+
if band:
|
| 93 |
+
ax.axvspan(*band, color="#E6E6E6", zorder=0)
|
| 94 |
+
if ref is not None:
|
| 95 |
+
ax.axvline(ref, color=ST.INK, lw=0.8)
|
| 96 |
+
for k, (arm, _l, c, mk) in enumerate(arms):
|
| 97 |
+
v = [tab[(tab.dataset == ds) & (tab.state == st) & (tab.arm == arm)][col] for ds, st in keys]
|
| 98 |
+
v = [float(x.iloc[0]) if len(x) else np.nan for x in v]
|
| 99 |
+
ax.scatter(v, y + (k - 1) * 0.18, s=46 if arm.startswith(("lora", "real_lora")) else 34, marker=mk, color=c,
|
| 100 |
+
edgecolor=ST.INK, lw=0.5, zorder=3)
|
| 101 |
+
ax.set_yticks(y, [f"{NAME[ds]} · {SHORT.get(st, st)}" for ds, st in keys], fontsize=ST.FS - 5)
|
| 102 |
+
ax.set_ylim(len(keys) - 0.5, -0.5)
|
| 103 |
+
if xlim:
|
| 104 |
+
ax.set_xlim(*xlim)
|
| 105 |
+
ax.set_xlabel(xlab, fontsize=ST.FS - 3)
|
| 106 |
+
ax.tick_params(axis="x", labelsize=ST.FS - 4)
|
| 107 |
+
ax.grid(axis="x", color="#E3E3E3", linewidth=0.8)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def counts(tab, keys, a_lora, a_sc):
|
| 111 |
+
"""per metric: states where LoRA is better than scSemiProfiler (and within 2-fold for the fraction)"""
|
| 112 |
+
t = tab.set_index(["dataset", "state", "arm"])
|
| 113 |
+
out = {"n": len(keys)}
|
| 114 |
+
g = lambda ds, st, a, m: float(t.loc[(ds, st, a), m]) if (ds, st, a) in t.index else np.nan # noqa: E731
|
| 115 |
+
err = lambda k, a: abs(g(*k, a, "log2_ratio")) if np.isfinite(g(*k, a, "log2_ratio")) else np.inf # noqa: E731
|
| 116 |
+
rho = lambda k, a: g(*k, a, "spearman") if np.isfinite(g(*k, a, "spearman")) else -np.inf # noqa: E731
|
| 117 |
+
# a state a method never generates has no ratio / rank: it counts as that method's miss
|
| 118 |
+
out["frac_closer"] = sum(err(k, a_lora) < err(k, a_sc) for k in keys)
|
| 119 |
+
out["within2_lora"] = sum(err(k, a_lora) <= 1 for k in keys)
|
| 120 |
+
out["within2_sc"] = sum(err(k, a_sc) <= 1 for k in keys)
|
| 121 |
+
out["not_generated_lora"] = sum(not np.isfinite(g(*k, a_lora, "log2_ratio")) for k in keys)
|
| 122 |
+
out["not_generated_sc"] = sum(not np.isfinite(g(*k, a_sc, "log2_ratio")) for k in keys)
|
| 123 |
+
out["rho_better"] = sum(rho(k, a_lora) > rho(k, a_sc) for k in keys)
|
| 124 |
+
out["rho_median_lora"] = float(np.nanmedian([g(*k, a_lora, "spearman") for k in keys]))
|
| 125 |
+
out["rho_median_sc"] = float(np.nanmedian([g(*k, a_sc, "spearman") for k in keys]))
|
| 126 |
+
out["dir_lora"] = float(np.nanmean([g(*k, a_lora, "direction") for k in keys]))
|
| 127 |
+
out["dir_sc"] = float(np.nanmean([g(*k, a_sc, "direction") for k in keys]))
|
| 128 |
+
return out
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def main() -> int:
|
| 132 |
+
s, c, keys = load()
|
| 133 |
+
fa, pa = agg_few(s, c), agg_pool(s, c)
|
| 134 |
+
keys = sorted(keys, key=lambda k: (list(NAME).index(k[0]), k[1]))
|
| 135 |
+
pd.concat([fa.assign(design="5 donors (mean of 5 draws)"), pa.assign(design="5-fold pooled")]).to_csv(
|
| 136 |
+
DAT / "fig5_rare_states.csv", index=False, float_format="%.5g")
|
| 137 |
+
leg = lambda arms: [Line2D([0], [0], marker=mk, ls="none", color=c, mec=ST.INK, mew=0.5, ms=8) # noqa: E731
|
| 138 |
+
for _a, _l, c, mk in arms]
|
| 139 |
+
COH = {"ye2026_sepsis": "#CC79A7", "imperial_eskd": "#0072B2", "giroux2022": "#009E73", "ji2025_chili": "#E69F00"}
|
| 140 |
+
KEY = [("ye2026_sepsis", "MS1 monocyte (IL1R2+)"), ("ye2026_sepsis", "Plasmablast (label)"),
|
| 141 |
+
("ye2026_sepsis", "ISG-high T"), ("imperial_eskd", "MS1 monocyte (IL1R2+)"),
|
| 142 |
+
("imperial_eskd", "Plasmablast (label)"), ("imperial_eskd", "ISG-high T"), ("imperial_eskd", "Cycling T/NK"),
|
| 143 |
+
("ji2025_chili", "MS1 monocyte (IL1R2+)"), ("ji2025_chili", "ISG-high T"), ("giroux2022", "Cycling T/NK")]
|
| 144 |
+
KEY = [k for k in KEY if k in keys]
|
| 145 |
+
MISS = 11.5 # where 'not generated' is drawn on the |log2| axis
|
| 146 |
+
|
| 147 |
+
def scatter(ax, tab, a_x, a_y, col, lab, lim, miss=None, within=False):
|
| 148 |
+
t = tab.set_index(["dataset", "state", "arm"])[col]
|
| 149 |
+
for ds, st in keys:
|
| 150 |
+
x, y = t.get((ds, st, a_x), np.nan), t.get((ds, st, a_y), np.nan)
|
| 151 |
+
if col == "log2_ratio":
|
| 152 |
+
x = abs(x) if np.isfinite(x) else miss
|
| 153 |
+
y = abs(y) if np.isfinite(y) else miss
|
| 154 |
+
elif not (np.isfinite(x) and np.isfinite(y)):
|
| 155 |
+
x = x if np.isfinite(x) else lim[0] + 0.03
|
| 156 |
+
y = y if np.isfinite(y) else lim[0] + 0.03
|
| 157 |
+
ax.scatter(x, y, s=34, color=COH[ds], edgecolor=ST.INK, lw=0.4, zorder=3)
|
| 158 |
+
ax.plot(lim, lim, color=ST.INK, lw=0.8, zorder=1)
|
| 159 |
+
if within:
|
| 160 |
+
ax.axhspan(lim[0], 1, color="#F6DCC8", zorder=0)
|
| 161 |
+
ax.text(lim[1] * 0.98, 0.5, "LoRA within 2-fold", ha="right", va="center", fontsize=ST.FS - 5, color=ST.SUBINK)
|
| 162 |
+
if miss is None and col != "log2_ratio":
|
| 163 |
+
ax.axvline(lim[0] + 0.08, color=ST.GREY, ls=":", lw=1)
|
| 164 |
+
ax.text(lim[0] + 0.03, lim[1] * 0.98, "not\ngenerated", ha="left", va="top", fontsize=ST.FS - 6,
|
| 165 |
+
color=ST.SUBINK, rotation=0)
|
| 166 |
+
if miss is not None:
|
| 167 |
+
ax.axvline(miss - 0.5, color=ST.GREY, ls=":", lw=1)
|
| 168 |
+
ax.text(miss, lim[1] * 0.98, "not\ngenerated", ha="center", va="top", fontsize=ST.FS - 6, color=ST.SUBINK)
|
| 169 |
+
ax.set_xlim(*lim)
|
| 170 |
+
ax.set_ylim(*lim)
|
| 171 |
+
ax.set_aspect("equal")
|
| 172 |
+
ax.set_title(lab, fontsize=ST.FS - 1, loc="left")
|
| 173 |
+
ax.grid(color="#EEEEEE", linewidth=0.8)
|
| 174 |
+
ax.tick_params(labelsize=ST.FS - 4)
|
| 175 |
+
|
| 176 |
+
coh_leg = [Line2D([0], [0], marker="o", ls="none", color=c, mec=ST.INK, mew=0.4, ms=7) for c in COH.values()]
|
| 177 |
+
# A: fraction
|
| 178 |
+
fig, (a1, a2) = plt.subplots(1, 2, figsize=ST.FULL, gridspec_kw={"wspace": 0.55, "width_ratios": [1, 1.25]})
|
| 179 |
+
scatter(a1, fa, "scsemi5", "lora5", "log2_ratio", "Fraction error, |log2(gen / obs)|", (0, 12.2), miss=MISS, within=True)
|
| 180 |
+
a1.set_xlabel("scSemiProfiler, 5 donors", fontsize=ST.FS - 3)
|
| 181 |
+
a1.set_ylabel("PBISC LoRA, 5 donors", fontsize=ST.FS - 3)
|
| 182 |
+
dotplot(a2, fa, KEY, FEW, "log2_ratio", "log2(generated / observed); band = within 2-fold", band=(-1, 1), xlim=(-8, 3), ref=0)
|
| 183 |
+
a2.set_title("Disease states", fontsize=ST.FS - 1, loc="left")
|
| 184 |
+
fig.legend(coh_leg + leg(FEW), [NAME[d] for d in COH] + [l for _a, l, _c, _m in FEW], loc="lower center", ncol=7,
|
| 185 |
+
bbox_to_anchor=(0.5, -0.09), fontsize=ST.FS - 5)
|
| 186 |
+
ST.save(fig, "fig5_rare_fraction", FIG)
|
| 187 |
+
# B: donors and direction
|
| 188 |
+
fig, (a1, a2) = plt.subplots(1, 2, figsize=ST.FULL, gridspec_kw={"wspace": 0.45, "width_ratios": [1, 1.1]})
|
| 189 |
+
scatter(a1, fa, "scsemi5", "lora5", "spearman", "Donor ranking, Spearman ρ", (-0.5, 1.0))
|
| 190 |
+
a1.set_xlabel("scSemiProfiler, 5 donors", fontsize=ST.FS - 3)
|
| 191 |
+
a1.set_ylabel("PBISC LoRA, 5 donors", fontsize=ST.FS - 3)
|
| 192 |
+
dirs = {a: float(fa[fa.arm == a].direction.mean()) for a, *_ in FEW}
|
| 193 |
+
for i, (a, l, c, _m) in enumerate(FEW):
|
| 194 |
+
a2.barh(i, dirs[a], 0.6, color=c, edgecolor="none")
|
| 195 |
+
a2.text(dirs[a] + 0.01, i, f"{100 * dirs[a]:.0f}%", va="center", fontsize=ST.FS - 4, color=ST.SUBINK)
|
| 196 |
+
a2.axvline(0.5, color=ST.GREY, ls=":", lw=1)
|
| 197 |
+
a2.set_yticks(range(len(FEW)), [l for _a, l, _c, _m in FEW], fontsize=ST.FS - 4)
|
| 198 |
+
a2.set_ylim(len(FEW) - 0.4, -0.6)
|
| 199 |
+
a2.set_xlim(0, 1)
|
| 200 |
+
a2.set_title("Disease direction kept (states x draws)", fontsize=ST.FS - 1, loc="left")
|
| 201 |
+
a2.tick_params(axis="y", length=0)
|
| 202 |
+
fig.legend(coh_leg, [NAME[d] for d in COH], loc="lower center", ncol=4, bbox_to_anchor=(0.3, -0.08), fontsize=ST.FS - 4)
|
| 203 |
+
ST.save(fig, "fig5_rare_donors", FIG)
|
| 204 |
+
# C: five-fold
|
| 205 |
+
fig, (a1, a2) = plt.subplots(1, 2, figsize=ST.FULL, gridspec_kw={"wspace": 0.35})
|
| 206 |
+
scatter(a1, pa, "scsemi__raw", "real_lora__raw", "log2_ratio", "Fraction error, |log2(gen / obs)|", (0, 12.2),
|
| 207 |
+
miss=MISS, within=True)
|
| 208 |
+
scatter(a2, pa, "scsemi__raw", "real_lora__raw", "spearman", "Donor ranking, Spearman ρ", (-0.5, 1.0))
|
| 209 |
+
for a in (a1, a2):
|
| 210 |
+
a.set_xlabel("scSemiProfiler, same pairs", fontsize=ST.FS - 3)
|
| 211 |
+
a.set_ylabel("PBISC LoRA", fontsize=ST.FS - 3)
|
| 212 |
+
fig.legend(coh_leg, [NAME[d] for d in COH], loc="lower center", ncol=4, bbox_to_anchor=(0.5, -0.08), fontsize=ST.FS - 4)
|
| 213 |
+
ST.save(fig, "fig5_rare_fivefold", FIG)
|
| 214 |
+
vs_zs = {m: sum((abs(fa[(fa.dataset == d) & (fa.state == st) & (fa.arm == "lora5")].log2_ratio.iloc[0])
|
| 215 |
+
< abs(fa[(fa.dataset == d) & (fa.state == st) & (fa.arm == "zs_raw")].log2_ratio.iloc[0]))
|
| 216 |
+
if m == "frac" else
|
| 217 |
+
(fa[(fa.dataset == d) & (fa.state == st) & (fa.arm == "lora5")].spearman.iloc[0]
|
| 218 |
+
> fa[(fa.dataset == d) & (fa.state == st) & (fa.arm == "zs_raw")].spearman.iloc[0])
|
| 219 |
+
for d, st in keys) for m in ("frac", "rho")}
|
| 220 |
+
|
| 221 |
+
cf, cp = counts(fa, keys, "lora5", "scsemi5"), counts(pa, keys, "real_lora__raw", "scsemi__raw")
|
| 222 |
+
n = cf["n"]
|
| 223 |
+
rule = (f"State × cohort pairs with ≥ {MIN_OBS} observed state cells in ≥ {MIN_DONORS} donors (native depth); "
|
| 224 |
+
"negative control left out. Marker rules from the literature (plans/rare_states_screen_20261004/tools/"
|
| 225 |
+
"states.json); observed parent cells thinned to the generated depth; labels = the benchmark's frozen "
|
| 226 |
+
"scANVI calls; the benchmark's Poisson read-out reproduced cell by cell. ")
|
| 227 |
+
slides = [
|
| 228 |
+
{"title": "Rare states with 5 pairs: how many cells", "figure": "fig5_rare_fraction",
|
| 229 |
+
"keywords": [f"Within 2-fold: LoRA-5 {cf['within2_lora']}/{n}, scSemiProfiler-5 {cf['within2_sc']}/{n}",
|
| 230 |
+
f"Closer to the observed fraction than scSemiProfiler-5: {cf['frac_closer']}/{n}",
|
| 231 |
+
"Rare states kept, not averaged away"],
|
| 232 |
+
"short": "4 paired disease cohorts; 5 donors, mean of 5 draws. 0 = observed fraction; band = within 2-fold.",
|
| 233 |
+
"full": ("Main comparison: 5 donors per draw (LoRA-5 vs scSemiProfiler with the same 5 donors as representatives, "
|
| 234 |
+
"and zero-shot), every other usable sample tested, mean over 5 draws of log2(generated % / observed %) "
|
| 235 |
+
"of the state within its parent type. Left: one point per state x cohort; below the diagonal = LoRA-5 "
|
| 236 |
+
f"closer; states a method never generates are drawn as 'not generated' (scSemiProfiler-5: "
|
| 237 |
+
f"{cf['not_generated_sc']} of {n}; LoRA-5: {cf['not_generated_lora']}). Zero-shot (no pairs) is "
|
| 238 |
+
f"closer than LoRA-5 on {n - vs_zs['frac']} of {n} fractions, LoRA-5 ranks donors better on "
|
| 239 |
+
f"{vs_zs['rho']} of {n}. " + rule + "Source: data/fig5_rare_states.csv "
|
| 240 |
+
"(plans/rare_states_paired_20261008/out/summary.csv).")},
|
| 241 |
+
{"title": "Rare states with 5 pairs: in the right donors", "figure": "fig5_rare_donors",
|
| 242 |
+
"keywords": [f"Donor ranking: median ρ {cf['rho_median_lora']:.2f} vs {cf['rho_median_sc']:.2f} (scSemiProfiler-5)",
|
| 243 |
+
f"Better donor ranking than scSemiProfiler-5: {cf['rho_better']}/{n}",
|
| 244 |
+
f"Disease direction kept: {100 * cf['dir_lora']:.0f}% vs {100 * cf['dir_sc']:.0f}% of draws"],
|
| 245 |
+
"short": "Spearman over donors of generated vs observed state %; direction = case-vs-control sign.",
|
| 246 |
+
"full": ("Main comparison (5 donors, 5 draws). Left: Spearman over the tested donors of the generated vs observed "
|
| 247 |
+
"(thinned) state percentage, mean over draws. Right: share of draws where the case-vs-control difference "
|
| 248 |
+
"of donor means has the observed sign (sepsis vs controls, COVID+ vs COVID-, severe vs mild, ChILI vs "
|
| 249 |
+
"controls). " + rule + "Source: data/fig5_rare_states.csv (out/summary.csv, out/contrasts.csv).")},
|
| 250 |
+
{"title": "5-fold CV: rare states", "figure": "fig5_rare_fivefold",
|
| 251 |
+
"keywords": [f"Within 2-fold: LoRA {cp['within2_lora']}/{n}, scSemiProfiler {cp['within2_sc']}/{n}",
|
| 252 |
+
f"Donor ranking: median ρ {cp['rho_median_lora']:.2f} vs {cp['rho_median_sc']:.2f}",
|
| 253 |
+
f"Better donor ranking: {cp['rho_better']}/{n}"],
|
| 254 |
+
"short": "Donor-level 5-fold CV, pooled; reported separately from the 5-pair comparison.",
|
| 255 |
+
"full": ("Reported separately: 5-fold CV, every sample generated by the fold model that never trained on it; "
|
| 256 |
+
"scSemiProfiler with exactly LoRA's training pairs as representatives. " + rule
|
| 257 |
+
+ "Source: data/fig5_rare_states.csv.")}]
|
| 258 |
+
out_slides = []
|
| 259 |
+
for sl in slides:
|
| 260 |
+
if len(sl["short"]) > 110:
|
| 261 |
+
raise SystemExit(f"short footnote too long: {sl['title']}")
|
| 262 |
+
out_slides.append({"title": sl["title"], "layout": "full", "figures": [str(FIG / f"{sl['figure']}.png")],
|
| 263 |
+
"keywords": sl["keywords"], "footnote_short": sl["short"], "footnote": sl["full"],
|
| 264 |
+
"numbers": [{"value": json.dumps({"5 donors": cf, "5-fold": cp}), "source": "data/fig5_rare_states.csv"}]})
|
| 265 |
+
(DAT / "fig5_rare_states_slide_text.json").write_text(json.dumps(
|
| 266 |
+
{"section": "fig5-rare", "scripts": [str(Path(__file__).resolve())],
|
| 267 |
+
"generated_from": "tools/fig5_rare_states.py (rerun to refresh; do not edit by hand)", "slides": out_slides},
|
| 268 |
+
indent=1, ensure_ascii=False))
|
| 269 |
+
print(f"{len(keys)} state x cohort pairs")
|
| 270 |
+
print(json.dumps({"5 donors": cf, "5-fold": cp}, indent=1))
|
| 271 |
+
for sl in out_slides:
|
| 272 |
+
print(sl["title"], "|", " | ".join(sl["keywords"]))
|
| 273 |
+
return 0
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
if __name__ == "__main__":
|
| 277 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261008T125804Z-deck-fig2-3-healthy-fig5-rare/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec10_paired_subset_cohorts.py
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Section 10 (planned): cohorts that have a paired bulk-sc subset plus bulk-only samples.
|
| 2 |
+
|
| 3 |
+
Counts only; no new model output. Every number is read from the pairing manifests / tables below.
|
| 4 |
+
Outputs
|
| 5 |
+
data/sec10_cohort_counts.csv one row per cohort (samples, donors, flags, LoRA status, sources)
|
| 6 |
+
data/sec10_bulk_only_groups.csv paired-usable vs bulk-only samples per clinical group
|
| 7 |
+
data/sec10_quoted_numbers.csv every number on the slide with its source
|
| 8 |
+
figures/sec10_paired_subset_cohorts.png/.pdf
|
| 9 |
+
"""
|
| 10 |
+
import json
|
| 11 |
+
import re
|
| 12 |
+
import sys
|
| 13 |
+
from collections import Counter
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import pandas as pd
|
| 18 |
+
|
| 19 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00")
|
| 20 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 21 |
+
import style # noqa: E402
|
| 22 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 23 |
+
from matplotlib.patches import Patch # noqa: E402
|
| 24 |
+
|
| 25 |
+
FIG = DECK / "figures"
|
| 26 |
+
DATA = DECK / "data"
|
| 27 |
+
PFT = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
|
| 28 |
+
PF = PFT / "data"
|
| 29 |
+
SCORES = PFT / "scores"
|
| 30 |
+
GEN = PFT / "generated"
|
| 31 |
+
US = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/utility_studies_final6k_20260925")
|
| 32 |
+
IMPERIAL_HTSEQ = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/datasets/Zenodo_6497251/raw/htseq_counts.csv")
|
| 33 |
+
JI_SC_LIBS = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/ji2025_chili_v1_20260928/pairing/"
|
| 34 |
+
"sc_gex_libraries_with_bulk_match.csv")
|
| 35 |
+
|
| 36 |
+
rows, groups, quoted = [], [], []
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def q(item, value, source):
|
| 40 |
+
quoted.append(dict(item=item, value=value, source=str(source)))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def add_groups(cohort, paired_usable_by_group, bulk_only_by_group, src):
|
| 44 |
+
for g in sorted(set(paired_usable_by_group) | set(bulk_only_by_group)):
|
| 45 |
+
groups.append(dict(cohort=cohort, group=g,
|
| 46 |
+
paired_usable=int(paired_usable_by_group.get(g, 0)),
|
| 47 |
+
bulk_only=int(bulk_only_by_group.get(g, 0)), source=src))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def excl_breakdown(pairs, usable_mask):
|
| 51 |
+
"""Why paired rows are excluded: identity fail / borderline, or identity pass but <200 cells."""
|
| 52 |
+
ex = pairs[~usable_mask]
|
| 53 |
+
kind = ex.identity_check.str.split(":").str[0].str.strip()
|
| 54 |
+
c = Counter(kind)
|
| 55 |
+
c["below_200_cells_only"] = int((kind == "pass").sum())
|
| 56 |
+
c.pop("pass", None)
|
| 57 |
+
return dict(c)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def lora_status(ds):
|
| 61 |
+
"""5-fold LoRA composition L1 (fold mean) and the leave-one-out composition null from AGGREGATE."""
|
| 62 |
+
agg = json.load(open(SCORES / ds / "aggregate.json"))
|
| 63 |
+
md = (SCORES / ds / "AGGREGATE.md").read_text()
|
| 64 |
+
null = float(re.search(r"Leave-one-out composition null \(fold mean\): ([0-9.]+)", md).group(1))
|
| 65 |
+
lora = agg["arms"]["real_lora__raw"]
|
| 66 |
+
assert lora["n_folds"] == 5
|
| 67 |
+
return lora["comp_l1"]["mean"], null, agg["contrast"]["real_lora__raw"], agg["contrast"]["zs__raw"]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def no_bulk_only_generation(ds, n_paired_usable):
|
| 71 |
+
"""PLANNED check: nothing generated for this cohort's bulk-only samples (file names + pooled manifests)."""
|
| 72 |
+
names = [p.name.lower() for p in (GEN / ds).rglob("*")]
|
| 73 |
+
assert not [n for n in names if "bulkonly" in n or "bulk_only" in n], f"{ds}: bulk-only generation exists"
|
| 74 |
+
pm = GEN / ds / "pooled" / "POOL_MANIFEST.json"
|
| 75 |
+
if pm.exists():
|
| 76 |
+
for arm, v in json.load(open(pm))["arms"].items():
|
| 77 |
+
assert v["n_samples"] <= n_paired_usable, (ds, arm, v["n_samples"])
|
| 78 |
+
return True
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# ---------------- Ye 2026 sepsis (GSE279448 bulk / GSE279452 sc) ----------------
|
| 82 |
+
ds = "ye2026_sepsis"
|
| 83 |
+
d = PF / ds
|
| 84 |
+
man = json.load(open(d / "MANIFEST.json"))
|
| 85 |
+
pairs = pd.read_csv(d / "pairs.csv")
|
| 86 |
+
bulk_all = pd.read_csv(d / "identity_sex_bulk_all.csv")
|
| 87 |
+
bulk_only = man["excluded"]["bulk_samples_without_sc"]
|
| 88 |
+
assert len(pairs) == man["rows"]
|
| 89 |
+
assert len(pairs) + len(bulk_only) == len(bulk_all), "Ye: paired + bulk-only != all bulks"
|
| 90 |
+
umask = pairs.identity_pass.astype(bool)
|
| 91 |
+
usable = pairs[umask]
|
| 92 |
+
ye_map_bo = {"Adult Sepsis": "sepsis", "Adult Healthy Control": "control", "Adult ICU Control": "control",
|
| 93 |
+
"Pediatric ICU Control": "control", "Pediatric Sepsis": "sepsis",
|
| 94 |
+
"Pediatric Healthy Control": "control"}
|
| 95 |
+
bo_raw = Counter(x["ch_group"] for x in bulk_only)
|
| 96 |
+
assert set(bo_raw) <= set(ye_map_bo), bo_raw
|
| 97 |
+
bo_grp = Counter()
|
| 98 |
+
for k, v in bo_raw.items():
|
| 99 |
+
bo_grp[ye_map_bo[k]] += v
|
| 100 |
+
pu_grp = Counter("sepsis" if "sepsis" in g else "control" for g in usable.group)
|
| 101 |
+
bo_ids = {x["sample_id"] for x in bulk_only}
|
| 102 |
+
flag_list = man["findings"]["sex_vs_geo"]["bulk_all_samples_discordant_or_ambiguous"]
|
| 103 |
+
ye_flag_bo = sorted(x["sample_id"] for x in flag_list if x["sample_id"] in bo_ids)
|
| 104 |
+
assert len(ye_flag_bo) == len(flag_list), "Ye: a sex-flagged bulk is paired"
|
| 105 |
+
paired_don, usable_don = set(pairs.donor_id), set(usable.donor_id)
|
| 106 |
+
comp, null, c_lora, c_zs = lora_status(ds)
|
| 107 |
+
no_bulk_only_generation(ds, len(usable))
|
| 108 |
+
add_groups("Ye 2026 sepsis", pu_grp, bo_grp, f"{d/'MANIFEST.json'} (excluded.bulk_samples_without_sc); {d/'pairs.csv'}")
|
| 109 |
+
rows.append(dict(
|
| 110 |
+
cohort="Ye 2026 sepsis", specimen="PBMC bulk",
|
| 111 |
+
bulk_total=len(bulk_all), paired=len(pairs), seg_train=len(usable), seg_nocomp=0,
|
| 112 |
+
seg_excl=len(pairs) - len(usable), excl_why=json.dumps(excl_breakdown(pairs, umask)), bulk_only=len(bulk_only),
|
| 113 |
+
donors_bulk_total=len(bulk_all), # one sample per donor (QC_REPORT: donor = sample)
|
| 114 |
+
donors_paired_usable=len(usable_don), donors_bulk_only=len(bo_ids), donors_excl_only=len(paired_don - usable_don),
|
| 115 |
+
bulk_only_groups=f"{bo_grp['sepsis']} sepsis, {bo_grp['control']} control",
|
| 116 |
+
sex_flag_bulk_only=len(ye_flag_bo), sex_flag_ids=";".join(ye_flag_bo),
|
| 117 |
+
lora_cv="5-fold", lora_comp_l1=comp, comp_null=null,
|
| 118 |
+
lora_logfc_r=c_lora["r_generated"], zs_raw_logfc_r=c_zs["r_generated"],
|
| 119 |
+
extra=f"controls: paired QC pass {pu_grp['control']} + bulk-only {bo_grp['control']}",
|
| 120 |
+
usable_rule="identity_pass",
|
| 121 |
+
source=f"{d/'MANIFEST.json'}; {d/'pairs.csv'}; {d/'identity_sex_bulk_all.csv'}; {SCORES/ds/'aggregate.json'}; "
|
| 122 |
+
f"{SCORES/ds/'AGGREGATE.md'}",
|
| 123 |
+
))
|
| 124 |
+
ye_controls_paired, ye_controls_bulk_only = pu_grp["control"], bo_grp["control"]
|
| 125 |
+
q("Sepsis controls, paired QC pass", ye_controls_paired, d / "pairs.csv")
|
| 126 |
+
q("Sepsis controls, bulk-only (36 adult HC + 17 adult ICU + 1 ped ICU)", ye_controls_bulk_only,
|
| 127 |
+
f"{d/'MANIFEST.json'} excluded.bulk_samples_without_sc ch_group")
|
| 128 |
+
|
| 129 |
+
# ---------------- Imperial ESKD COVID (Zenodo 6497251 bulk / COVID-19 Cell Atlas sc) ----------------
|
| 130 |
+
ds = "imperial_eskd"
|
| 131 |
+
d = PF / ds
|
| 132 |
+
man = json.load(open(d / "MANIFEST.json"))
|
| 133 |
+
pairs = pd.read_csv(d / "pairs.csv")
|
| 134 |
+
with open(IMPERIAL_HTSEQ) as fh: # header only; the matrix is never loaded
|
| 135 |
+
header = [c.strip().strip('"') for c in fh.readline().rstrip("\n").split(",")]
|
| 136 |
+
bulk_cols = header[1:]
|
| 137 |
+
assert header[0] == "gencode_id"
|
| 138 |
+
bulk_only = man["excluded"]["bulk_samples_without_sc"]
|
| 139 |
+
assert len(pairs) + len(bulk_only) == len(bulk_cols), "Imperial: paired + bulk-only != htseq columns"
|
| 140 |
+
assert set(pairs.bulk_sample) | {x["bulk_sample"] for x in bulk_only} == set(bulk_cols)
|
| 141 |
+
umask = pairs.identity_pass.astype(bool) & ~pairs.below_200_cells.astype(bool)
|
| 142 |
+
usable = pairs[umask]
|
| 143 |
+
pid = lambda s: s.split("_")[0] # noqa: E731 column names are <patient>_<status>[_<day>]
|
| 144 |
+
bulk_pat = {pid(c) for c in bulk_cols}
|
| 145 |
+
paired_pat, usable_pat = set(pairs.donor_id), set(usable.donor_id)
|
| 146 |
+
assert paired_pat <= bulk_pat
|
| 147 |
+
sexb = pd.read_csv(d / "identity_sex_bulk_all.csv")
|
| 148 |
+
assert set(sexb.donor_id) == bulk_pat and len(sexb) == len(bulk_cols)
|
| 149 |
+
bo_sex = sexb[~sexb.paired.astype(bool)]
|
| 150 |
+
imp_flag = bo_sex[(bo_sex.bulk_sex_call == "ambiguous")
|
| 151 |
+
| (bo_sex.bulk_sex_call.str[0].str.upper() != bo_sex.sex_meta.str.upper())]
|
| 152 |
+
bo_grp = Counter({"covid_positive": 0, "covid_negative": 0, "recovery": 0})
|
| 153 |
+
for x in bulk_only:
|
| 154 |
+
bo_grp[{"positive": "covid_positive", "negative": "covid_negative", "recovery": "recovery"}[x["status"]]] += 1
|
| 155 |
+
pu_grp = Counter(usable.group)
|
| 156 |
+
comp, null, c_lora, c_zs = lora_status(ds)
|
| 157 |
+
no_bulk_only_generation(ds, len(usable))
|
| 158 |
+
add_groups("Imperial ESKD COVID", pu_grp, bo_grp, f"{d/'MANIFEST.json'} (excluded.bulk_samples_without_sc); {d/'pairs.csv'}")
|
| 159 |
+
rows.append(dict(
|
| 160 |
+
cohort="Imperial ESKD COVID", specimen="PBMC bulk, longitudinal",
|
| 161 |
+
bulk_total=len(bulk_cols), paired=len(pairs), seg_train=len(usable), seg_nocomp=0,
|
| 162 |
+
seg_excl=len(pairs) - len(usable), excl_why=json.dumps(excl_breakdown(pairs, umask)), bulk_only=len(bulk_only),
|
| 163 |
+
donors_bulk_total=len(bulk_pat),
|
| 164 |
+
donors_paired_usable=len(usable_pat), donors_bulk_only=len(bulk_pat - paired_pat),
|
| 165 |
+
donors_excl_only=len(paired_pat - usable_pat),
|
| 166 |
+
bulk_only_groups=f"{bo_grp['covid_positive']} COVID+, {bo_grp['covid_negative']} COVID−, "
|
| 167 |
+
f"{bo_grp['recovery']} recovery",
|
| 168 |
+
sex_flag_bulk_only=len(imp_flag), sex_flag_ids=";".join(imp_flag.bulk_sample),
|
| 169 |
+
lora_cv="5-fold", lora_comp_l1=comp, comp_null=null,
|
| 170 |
+
lora_logfc_r=c_lora["r_generated"], zs_raw_logfc_r=c_zs["r_generated"],
|
| 171 |
+
extra="donors excluded-only: " + ";".join(sorted(paired_pat - usable_pat)),
|
| 172 |
+
usable_rule="identity_pass and not below_200_cells",
|
| 173 |
+
source=f"{d/'MANIFEST.json'}; {d/'pairs.csv'}; {d/'identity_sex_bulk_all.csv'}; header of {IMPERIAL_HTSEQ}; "
|
| 174 |
+
f"{SCORES/ds/'aggregate.json'}; {SCORES/ds/'AGGREGATE.md'}",
|
| 175 |
+
))
|
| 176 |
+
|
| 177 |
+
# ---------------- Ji 2025 ChILI (GSE287540 bulk = PAXgene whole blood / GSE287541 sc) ----------------
|
| 178 |
+
ds = "ji2025_chili"
|
| 179 |
+
d = PF / ds
|
| 180 |
+
man = json.load(open(d / "MANIFEST.json"))
|
| 181 |
+
pairs = pd.read_csv(d / "pairs.csv")
|
| 182 |
+
bulk_all = pd.read_csv(d / "identity_sex_bulk_all.csv")
|
| 183 |
+
bulk_only = man["excluded"]["bulk_samples_without_sc"]
|
| 184 |
+
assert len(pairs) + len(bulk_only) == len(bulk_all), "Ji: paired + bulk-only != all bulks"
|
| 185 |
+
assert "whole blood" in json.dumps(man["specimen_warning"]).lower()
|
| 186 |
+
umask = pairs.identity_pass.astype(bool)
|
| 187 |
+
usable = pairs[umask]
|
| 188 |
+
norm = lambda s: "N%03d" % int(re.match(r"N0*(\d+)", s).group(1)) # noqa: E731 N87 == N087
|
| 189 |
+
bulk_pat = {norm(s) for s in bulk_all.sample_id}
|
| 190 |
+
paired_pat, usable_pat = {norm(s) for s in pairs.donor_id}, {norm(s) for s in usable.donor_id}
|
| 191 |
+
assert paired_pat <= bulk_pat
|
| 192 |
+
bo_gsm = {x["gsm"] for x in bulk_only}
|
| 193 |
+
bo_raw = Counter(x["Sample_title"].split("_", 1)[1] for x in bulk_only) # e.g. chili_BC, control_AC
|
| 194 |
+
bo_grp = Counter()
|
| 195 |
+
for k, v in bo_raw.items():
|
| 196 |
+
bo_grp["ChILI" if k.startswith("chili") else "control"] += v
|
| 197 |
+
pu_grp = Counter("ChILI" if o == "ChILI" else "control" for o in usable.outcome)
|
| 198 |
+
chili_bc_bulk_only = int(bo_raw.get("chili_BC", 0))
|
| 199 |
+
chili_bc_paired = int(man["pairs_by_outcome_timepoint"].get("ChILI_BC", 0))
|
| 200 |
+
flag = bulk_all[bulk_all.sex_discordant_with_geo.astype(bool) | (bulk_all.bulk_sex_call == "ambiguous")]
|
| 201 |
+
assert set(flag.bulk_gsm) <= bo_gsm, "Ji: a sex-flagged bulk is paired"
|
| 202 |
+
ji_flag_bo = sorted(flag.sample_id)
|
| 203 |
+
ji_flag_bc = [s for s in ji_flag_bo if s.endswith("_chili_BC")]
|
| 204 |
+
sclib = pd.read_csv(JI_SC_LIBS)
|
| 205 |
+
ji_bc_sc_unpaired = sclib[(sclib.outcome == "ChILI") & (sclib.timepoint == "BC") & ~sclib.paired.astype(bool)]
|
| 206 |
+
comp, null, c_lora, c_zs = lora_status(ds)
|
| 207 |
+
no_bulk_only_generation(ds, len(usable))
|
| 208 |
+
add_groups("Ji 2025 ChILI", pu_grp, bo_grp, f"{d/'MANIFEST.json'} (excluded.bulk_samples_without_sc); {d/'pairs.csv'}")
|
| 209 |
+
for k in sorted(bo_raw):
|
| 210 |
+
groups.append(dict(cohort="Ji 2025 ChILI", group="detail:" + k, paired_usable=int(
|
| 211 |
+
((usable.outcome == ("ChILI" if k.startswith("chili") else "control")) & (usable.timepoint == k.split("_")[1])).sum()),
|
| 212 |
+
bulk_only=int(bo_raw[k]), source=str(d / "MANIFEST.json")))
|
| 213 |
+
rows.append(dict(
|
| 214 |
+
cohort="Ji 2025 ChILI", specimen="whole-blood bulk",
|
| 215 |
+
bulk_total=len(bulk_all), paired=len(pairs), seg_train=len(usable), seg_nocomp=0,
|
| 216 |
+
seg_excl=len(pairs) - len(usable), excl_why=json.dumps(excl_breakdown(pairs, umask)), bulk_only=len(bulk_only),
|
| 217 |
+
donors_bulk_total=len(bulk_pat),
|
| 218 |
+
donors_paired_usable=len(usable_pat), donors_bulk_only=len(bulk_pat - paired_pat),
|
| 219 |
+
donors_excl_only=len(paired_pat - usable_pat),
|
| 220 |
+
bulk_only_groups=f"{bo_grp['ChILI']} ChILI ({chili_bc_bulk_only} pre-ICI), {bo_grp['control']} control",
|
| 221 |
+
sex_flag_bulk_only=len(ji_flag_bo), sex_flag_ids=";".join(ji_flag_bo),
|
| 222 |
+
lora_cv="5-fold", lora_comp_l1=comp, comp_null=null,
|
| 223 |
+
lora_logfc_r=c_lora["r_generated"], zs_raw_logfc_r=c_zs["r_generated"],
|
| 224 |
+
extra=(f"ChILI before ICI (BC): paired {chili_bc_paired}, bulk-only {chili_bc_bulk_only} "
|
| 225 |
+
f"({len(ji_flag_bc)} sex-flagged: {';'.join(ji_flag_bc)}), unpaired ChILI BC sc libraries "
|
| 226 |
+
f"{len(ji_bc_sc_unpaired)} ({';'.join(ji_bc_sc_unpaired.sample_id)}); donors excluded-only: "
|
| 227 |
+
+ ";".join(sorted(paired_pat - usable_pat))),
|
| 228 |
+
usable_rule="identity_pass",
|
| 229 |
+
source=f"{d/'MANIFEST.json'}; {d/'pairs.csv'}; {d/'identity_sex_bulk_all.csv'}; {JI_SC_LIBS}; "
|
| 230 |
+
f"{SCORES/ds/'aggregate.json'}; {SCORES/ds/'AGGREGATE.md'}",
|
| 231 |
+
))
|
| 232 |
+
q("ChILI before ICI (BC), bulk-only", chili_bc_bulk_only, f"{d/'MANIFEST.json'} excluded.bulk_samples_without_sc Sample_title")
|
| 233 |
+
q("ChILI before ICI (BC), paired", chili_bc_paired, f"{d/'MANIFEST.json'} pairs_by_outcome_timepoint")
|
| 234 |
+
q("ChILI before ICI (BC), unpaired sc libraries (patients absent from bulk)", len(ji_bc_sc_unpaired), JI_SC_LIBS)
|
| 235 |
+
q("ChILI before ICI (BC), bulk-only sex-flagged", len(ji_flag_bc), f"{d/'identity_sex_bulk_all.csv'} sex_discordant_with_geo")
|
| 236 |
+
|
| 237 |
+
# ---------------- Arunachalam 2020 COVID (GSE152418 bulk / GSE155673 sc) ----------------
|
| 238 |
+
meta = US / "arunachalam" / "metadata"
|
| 239 |
+
bc = pd.read_csv(meta / "bulk_cohort.csv")
|
| 240 |
+
rec = pd.read_csv(meta / "pairs_reconciliation.csv")
|
| 241 |
+
assert int(bc.has_sc.sum()) == len(rec)
|
| 242 |
+
assert set(rec.sample_id) == set(bc.sample_id[bc.has_sc.astype(bool)])
|
| 243 |
+
id_ok = rec.sex_all_four_agree.astype(bool) & rec.expr_identity_own_is_best.astype(bool)
|
| 244 |
+
comp_ok = rec.composition_eligible.astype(bool)
|
| 245 |
+
n_train = int((id_ok & comp_ok).sum())
|
| 246 |
+
n_nocomp = int((id_ok & ~comp_ok).sum())
|
| 247 |
+
n_excl = int((~id_ok).sum())
|
| 248 |
+
n_strict = int(rec.strict_identity_eligible.astype(bool).sum())
|
| 249 |
+
bo = bc[~bc.has_sc.astype(bool)]
|
| 250 |
+
pu = bc[bc.sample_id.isin(set(rec.sample_id[id_ok & comp_ok]))]
|
| 251 |
+
bo_grp, pu_grp = Counter(bo.group), Counter(pu.group)
|
| 252 |
+
add_groups("Arunachalam 2020 COVID", pu_grp, bo_grp, str(meta / "bulk_cohort.csv"))
|
| 253 |
+
paired_subj = set(bc.subject_norm[bc.has_sc.astype(bool)])
|
| 254 |
+
arun_flag = bo[~bo.expr_sex_matches_geo.astype(bool)]
|
| 255 |
+
# zero-shot (no LoRA) cells for all bulk-only samples already exist: base model, raw / TPM / cal inputs
|
| 256 |
+
rc = json.load(open(US / "arunachalam_4arm" / "receipts" / "receipt_checks.json"))
|
| 257 |
+
assert rc["all_ok"]
|
| 258 |
+
zs_bo = {k: v for k, v in rc["tags"].items() if v["block"].startswith("bulkonly")}
|
| 259 |
+
zs_bo_arms = sorted({v["arm"] for v in zs_bo.values()})
|
| 260 |
+
zs_bo_bulks = {a: sum(v["bulks"] for v in zs_bo.values() if v["arm"] == a) for a in zs_bo_arms}
|
| 261 |
+
assert set(zs_bo_bulks.values()) == {len(bo)}, zs_bo_bulks
|
| 262 |
+
zs_ckpt = rc["checkpoint"]["path"]
|
| 263 |
+
assert zs_ckpt.endswith("f01_6k_1x_seed20260627/checkpoint_epoch_016.pt")
|
| 264 |
+
dr = pd.read_csv(US / "arunachalam_4arm" / "global_r" / "decision_rule.csv")
|
| 265 |
+
dr_pre = dr[dr.preregistered.astype(bool)]
|
| 266 |
+
arun_best_pass = int(dr_pre["n_populations_exceeding_raw_broadcast_by_0.018"].max())
|
| 267 |
+
arun_npop = int(dr_pre.populations.iloc[0])
|
| 268 |
+
rows.append(dict(
|
| 269 |
+
cohort="Arunachalam 2020 COVID", specimen="PBMC bulk; DC-enriched sc",
|
| 270 |
+
bulk_total=len(bc), paired=len(rec), seg_train=n_train, seg_nocomp=n_nocomp, seg_excl=n_excl,
|
| 271 |
+
excl_why=json.dumps({"identity_fail": n_excl}), bulk_only=len(bo),
|
| 272 |
+
donors_bulk_total=bc.subject_norm.nunique(),
|
| 273 |
+
donors_paired_usable=pu.subject_norm.nunique(), donors_bulk_only=len(set(bc.subject_norm) - paired_subj),
|
| 274 |
+
donors_excl_only=0,
|
| 275 |
+
bulk_only_groups=f"{bo_grp.get('COVID', 0)} COVID, {bo_grp.get('HC', 0)} healthy, {bo_grp.get('CONV', 0)} conv.",
|
| 276 |
+
sex_flag_bulk_only=len(arun_flag), sex_flag_ids=";".join(arun_flag.sample_id),
|
| 277 |
+
lora_cv="none", lora_comp_l1=np.nan, comp_null=np.nan, lora_logfc_r=np.nan, zs_raw_logfc_r=np.nan,
|
| 278 |
+
extra=(f"paired identity pass {int(id_ok.sum())}/{len(rec)}, composition_eligible {int(comp_ok.sum())}/{len(rec)} "
|
| 279 |
+
f"(material {';'.join(sorted(set(rec.material_status)))}), strict_identity_eligible {n_strict}; "
|
| 280 |
+
f"zero-shot bulk-only generated: arms {','.join(zs_bo_arms)}, {len(bo)} bulks each ({zs_ckpt}); "
|
| 281 |
+
f"prereg decision rule: best arm beats broadcast in {arun_best_pass}/{arun_npop} populations"),
|
| 282 |
+
usable_rule="identity pass (sex_all_four_agree & expr_identity_own_is_best) AND composition_eligible",
|
| 283 |
+
source=f"{meta/'bulk_cohort.csv'}; {meta/'pairs_reconciliation.csv'}; "
|
| 284 |
+
f"{US/'arunachalam_4arm/receipts/receipt_checks.json'}; {US/'arunachalam_4arm/global_r/decision_rule.csv'}",
|
| 285 |
+
))
|
| 286 |
+
q("Arunachalam paired, composition-eligible", int(comp_ok.sum()), f"{meta/'pairs_reconciliation.csv'} composition_eligible")
|
| 287 |
+
q("Arunachalam zero-shot bulk-only samples generated (per input arm)", len(bo),
|
| 288 |
+
f"{US/'arunachalam_4arm/receipts/receipt_checks.json'} tags *_bulkonly_a/b bulks")
|
| 289 |
+
q("Arunachalam prereg: populations where any zero-shot arm beats broadcast", f"{arun_best_pass}/{arun_npop}",
|
| 290 |
+
US / "arunachalam_4arm" / "global_r" / "decision_rule.csv")
|
| 291 |
+
|
| 292 |
+
# ---------------- not plotted: Asan vaccine (no donor map), Giroux 2022 (broadcast beats LoRA) ----------------
|
| 293 |
+
asan_bulk = pd.read_csv(US / "asan_cll" / "conditions" / "asan" / "samples.csv")
|
| 294 |
+
asan_sc = pd.read_csv(US / "asan_cll" / "observed" / "asan" / "libraries.csv")
|
| 295 |
+
asan_note = dict(bulk=len(asan_bulk), subjects=asan_bulk.subject.nunique(), sc_libraries=len(asan_sc),
|
| 296 |
+
reason="no bulk-sc donor map (asan_cll/RESULTS.md section 1)")
|
| 297 |
+
gd = PF / "giroux2022"
|
| 298 |
+
gpairs = pd.read_csv(gd / "pairs.csv")
|
| 299 |
+
gman = json.load(open(gd / "MANIFEST.json"))
|
| 300 |
+
g_bo = [x for x in gman["excluded"]["bulk_count_columns_without_pair"]
|
| 301 |
+
if x["unpaired_reason"] == "no_sc_library_for_this_subject_day"]
|
| 302 |
+
gh = json.load(open(SCORES / "giroux2022" / "pooled" / "summary.json"))["headline"]["real_lora__raw"]
|
| 303 |
+
g_r, g_rb = gh["contrast_mean_cp10k_r_gen"], gh["contrast_mean_cp10k_r_broadcast"]
|
| 304 |
+
g_deg, g_degb = gh["deg_top50_sum"], gh["deg_top50_sum_broadcast"]
|
| 305 |
+
assert g_rb > g_r and g_degb > g_deg, "Giroux: broadcast no longer beats LoRA"
|
| 306 |
+
giroux_note = dict(pairs_qc_pass=int(gpairs.identity_pass.astype(bool).sum()), bulk_only_author_columns=len(g_bo),
|
| 307 |
+
lora_r=g_r, broadcast_r=g_rb, lora_deg=g_deg, broadcast_deg=g_degb)
|
| 308 |
+
q("Giroux QC-pass pairs (not shown)", giroux_note["pairs_qc_pass"], gd / "pairs.csv")
|
| 309 |
+
q("Giroux author bulk columns without sc (not shown)", len(g_bo),
|
| 310 |
+
f"{gd/'MANIFEST.json'} excluded.bulk_count_columns_without_pair (no_sc_library_for_this_subject_day)")
|
| 311 |
+
q("Giroux pooled LoRA vs broadcast: severe-mild r / top-50 DEG sum",
|
| 312 |
+
f"{g_r:.2f} vs {g_rb:.2f} / {g_deg} vs {g_degb}", SCORES / "giroux2022" / "pooled" / "summary.json")
|
| 313 |
+
lora_rank = int(re.search(r"Rank (\d+), alpha", (PFT / "README.md").read_text()).group(1))
|
| 314 |
+
q("LoRA rank", lora_rank, PFT / "README.md")
|
| 315 |
+
|
| 316 |
+
tab = pd.DataFrame(rows)
|
| 317 |
+
assert (tab.seg_train + tab.seg_nocomp + tab.seg_excl == tab.paired).all()
|
| 318 |
+
assert (tab.paired + tab.bulk_only == tab.bulk_total).all()
|
| 319 |
+
assert (tab.donors_paired_usable + tab.donors_bulk_only + tab.donors_excl_only
|
| 320 |
+
+ np.where(tab.seg_nocomp > 0, tab.donors_bulk_total - tab.donors_bulk_only, 0) == tab.donors_bulk_total).all()
|
| 321 |
+
tab["lora_cv_source"] = [str(SCORES / k / "AGGREGATE.md") if r.lora_cv != "none" else "no paired-FT dataset built"
|
| 322 |
+
for k, r in zip(["ye2026_sepsis", "imperial_eskd", "ji2025_chili", None], tab.itertuples())]
|
| 323 |
+
for r in tab.itertuples():
|
| 324 |
+
for item in ["bulk_total", "seg_train", "seg_nocomp", "seg_excl", "bulk_only", "donors_paired_usable",
|
| 325 |
+
"donors_bulk_only", "donors_excl_only", "donors_bulk_total", "sex_flag_bulk_only"]:
|
| 326 |
+
q(f"{r.cohort}: {item}", getattr(r, item), r.source)
|
| 327 |
+
if r.lora_cv != "none":
|
| 328 |
+
q(f"{r.cohort}: LoRA 5-fold comp L1 / LOO null", f"{r.lora_comp_l1:.2f} / {r.comp_null:.2f}", r.lora_cv_source)
|
| 329 |
+
tab.to_csv(DATA / "sec10_cohort_counts.csv", index=False)
|
| 330 |
+
pd.DataFrame(groups).to_csv(DATA / "sec10_bulk_only_groups.csv", index=False)
|
| 331 |
+
qt = pd.DataFrame(quoted)
|
| 332 |
+
qt.to_csv(DATA / "sec10_quoted_numbers.csv", index=False)
|
| 333 |
+
print(tab.drop(columns=["source"]).T.to_string())
|
| 334 |
+
print("Asan (not plotted):", asan_note)
|
| 335 |
+
print("Giroux (not plotted):", giroux_note)
|
| 336 |
+
|
| 337 |
+
# ---------------- figure ----------------
|
| 338 |
+
C_TRAIN = style.INK
|
| 339 |
+
C_BO, C_BO_EDGE = style.PBISC_PALE, style.ARM["pbisc"]
|
| 340 |
+
DASH = (0, (3, 2))
|
| 341 |
+
W = style.TALL[0]
|
| 342 |
+
ROW = 1.10 # inches per cohort block
|
| 343 |
+
BAR_Y, BAR_H = 0.40, 0.27 # bar centre offset from block top, bar height (inches)
|
| 344 |
+
TOP = 0.78 # inches above the first block for the PLANNED line and the legend
|
| 345 |
+
AX_BOTTOM = 0.48 # inches for the x axis under the last block
|
| 346 |
+
n = len(tab)
|
| 347 |
+
H = TOP + n * ROW + AX_BOTTOM
|
| 348 |
+
fig = plt.figure(figsize=(W, H))
|
| 349 |
+
ax = fig.add_axes([0.0, AX_BOTTOM / H, 1.0, (n * ROW) / H])
|
| 350 |
+
xmax = tab.bulk_total.max()
|
| 351 |
+
XR = xmax * 1.30 # room right of the longest bar for its total label
|
| 352 |
+
ax.set_xlim(0, XR)
|
| 353 |
+
ax.set_ylim(n * ROW, 0) # y in inches from the top of the first block
|
| 354 |
+
FS_MAIN, FS_SUB = 13, 11
|
| 355 |
+
|
| 356 |
+
inbar = [] # (text, patch, row index)
|
| 357 |
+
for i, r in enumerate(tab.itertuples()):
|
| 358 |
+
y0 = i * ROW
|
| 359 |
+
yb = y0 + BAR_Y
|
| 360 |
+
ax.text(0, y0, r.cohort, ha="left", va="top", fontsize=FS_MAIN, fontweight="bold", color=style.INK)
|
| 361 |
+
if r.lora_cv != "none":
|
| 362 |
+
status = f"LoRA 5-fold: comp L1 {r.lora_comp_l1:.2f} vs null {r.comp_null:.2f}"
|
| 363 |
+
else:
|
| 364 |
+
status = "no LoRA: DC-enriched sc, no composition truth" # no broadcast comparison (2026-10-08)
|
| 365 |
+
ax.text(XR, y0, status, ha="right", va="top", fontsize=FS_SUB, color=style.SUBINK)
|
| 366 |
+
x = 0
|
| 367 |
+
p_tr = ax.barh(yb, r.seg_train, left=x, height=BAR_H, color=C_TRAIN, edgecolor=C_TRAIN, linewidth=0.8)[0]
|
| 368 |
+
x += r.seg_train
|
| 369 |
+
p_nc = ax.barh(yb, r.seg_nocomp, left=x, height=BAR_H, facecolor="white", edgecolor=style.INK, hatch="////",
|
| 370 |
+
linewidth=0.8)[0]
|
| 371 |
+
x += r.seg_nocomp
|
| 372 |
+
ax.barh(yb, r.seg_excl, left=x, height=BAR_H, facecolor="white", edgecolor=style.GREY, hatch="xxx", linewidth=0.8)
|
| 373 |
+
x += r.seg_excl
|
| 374 |
+
p_bo = ax.barh(yb, r.bulk_only, left=x, height=BAR_H, color=C_BO, edgecolor=C_BO_EDGE, linewidth=1.0,
|
| 375 |
+
linestyle=DASH)[0]
|
| 376 |
+
if r.seg_train:
|
| 377 |
+
inbar.append((ax.text(r.seg_train / 2, yb, f"{r.seg_train}", ha="center", va="center", color="white",
|
| 378 |
+
fontsize=12, fontweight="bold"), p_tr, i))
|
| 379 |
+
if r.seg_nocomp:
|
| 380 |
+
inbar.append((ax.text(r.seg_train + r.seg_nocomp / 2, yb, f"{r.seg_nocomp}", ha="center", va="center",
|
| 381 |
+
color=style.INK, fontsize=12, fontweight="bold",
|
| 382 |
+
bbox=dict(facecolor="white", edgecolor="none", pad=0.6)), p_nc, i))
|
| 383 |
+
inbar.append((ax.text(r.paired + r.bulk_only / 2, yb, f"{r.bulk_only}", ha="center", va="center",
|
| 384 |
+
color=style.INK, fontsize=12, fontweight="bold"), p_bo, i))
|
| 385 |
+
excl = f" ({r.seg_excl} excl.)" if r.seg_excl else ""
|
| 386 |
+
ax.text(r.bulk_total + xmax * 0.015, yb, f"{r.bulk_total}{excl}", ha="left", va="center", color=style.INK,
|
| 387 |
+
fontsize=12, gid=f"total{i}")
|
| 388 |
+
flag = f"; {r.sex_flag_bulk_only} sex-flagged" if r.sex_flag_bulk_only else ""
|
| 389 |
+
if r.cohort.startswith("Ji"):
|
| 390 |
+
flag += f" ({len(ji_flag_bc)} ChILI pre-ICI)"
|
| 391 |
+
if r.cohort.startswith("Arunachalam"):
|
| 392 |
+
flag += "; zero-shot cells made"
|
| 393 |
+
line1 = f"{r.specimen} · bulk-only: {r.bulk_only_groups}{flag}"
|
| 394 |
+
if r.seg_nocomp:
|
| 395 |
+
line2 = (f"donors: {r.donors_bulk_total - r.donors_bulk_only} paired "
|
| 396 |
+
f"({r.seg_train}/{r.paired} composition-eligible), {r.donors_bulk_only} bulk-only")
|
| 397 |
+
else:
|
| 398 |
+
line2 = (f"donors: {r.donors_paired_usable} paired, {r.donors_bulk_only} bulk-only, "
|
| 399 |
+
f"{r.donors_excl_only} excluded")
|
| 400 |
+
if r.cohort.startswith("Ji"):
|
| 401 |
+
line2 += f"; {len(ji_bc_sc_unpaired)} pre-ICI ChILI sc, no bulk"
|
| 402 |
+
ax.text(0, yb + BAR_H / 2 + 0.07, line1, ha="left", va="top", fontsize=FS_SUB, color=style.SUBINK)
|
| 403 |
+
ax.text(0, yb + BAR_H / 2 + 0.27, line2, ha="left", va="top", fontsize=FS_SUB, color=style.SUBINK)
|
| 404 |
+
|
| 405 |
+
ax.set_yticks([])
|
| 406 |
+
ax.spines["left"].set_visible(False)
|
| 407 |
+
ax.set_xticks([0, 100, 200, 300])
|
| 408 |
+
ax.spines["bottom"].set_bounds(0, 300)
|
| 409 |
+
ax.set_xlabel("bulk samples", fontsize=12)
|
| 410 |
+
ax.xaxis.set_label_coords(150 / XR, -0.05) # centred under the drawn 0-300 spine
|
| 411 |
+
|
| 412 |
+
leg = [Patch(facecolor=C_TRAIN, edgecolor=C_TRAIN, label="paired, QC pass: LoRA training"),
|
| 413 |
+
Patch(facecolor="white", edgecolor=style.GREY, hatch="xxx", label="paired, excluded (fail / borderline / <200 cells)"),
|
| 414 |
+
Patch(facecolor="white", edgecolor=style.INK, hatch="////", label="paired, DC-enriched sc: no composition"),
|
| 415 |
+
Patch(facecolor=C_BO, edgecolor=C_BO_EDGE, linestyle=DASH, label="bulk only: LoRA cells to generate")]
|
| 416 |
+
fig.legend(handles=leg, loc="upper left", bbox_to_anchor=(0.0, 1 - 0.30 / H), ncol=2, fontsize=11,
|
| 417 |
+
handlelength=1.5, handleheight=1.0, columnspacing=1.0, labelspacing=0.35, borderaxespad=0.0, borderpad=0.0)
|
| 418 |
+
fig.text(1.0, 1.0, "PLANNED: no LoRA cells for bulk-only yet", ha="right", va="top", fontsize=13,
|
| 419 |
+
fontweight="bold", color=style.INK)
|
| 420 |
+
|
| 421 |
+
# in-bar numbers that do not fit their segment move to one "a + b = total" label right of the bar
|
| 422 |
+
fig.canvas.draw()
|
| 423 |
+
rend = fig.canvas.get_renderer()
|
| 424 |
+
misfit = {i for t, pch, i in inbar if t.get_window_extent(rend).width > pch.get_window_extent(rend).width - 6}
|
| 425 |
+
for i in misfit:
|
| 426 |
+
r = tab.iloc[i]
|
| 427 |
+
for t, pch, j in inbar:
|
| 428 |
+
if j == i:
|
| 429 |
+
t.remove()
|
| 430 |
+
tot = [t for t in ax.texts if t.get_gid() == f"total{i}"][0]
|
| 431 |
+
parts = [str(v) for v in (r.seg_train, r.seg_nocomp, r.seg_excl) if v] + [str(r.bulk_only)]
|
| 432 |
+
tot.set_text(" + ".join(parts) + f" = {r.bulk_total}")
|
| 433 |
+
print("rows with outside labels:", [tab.iloc[i].cohort for i in sorted(misfit)])
|
| 434 |
+
|
| 435 |
+
# guard: no two text boxes overlap, and every text stays inside the figure
|
| 436 |
+
fig.canvas.draw()
|
| 437 |
+
texts = [t for t in ax.texts + fig.texts if t.get_visible() and t.get_text()]
|
| 438 |
+
boxes = [(t.get_text()[:30], t.get_window_extent(rend)) for t in texts]
|
| 439 |
+
boxes.append(("legend", fig.legends[0].get_window_extent(rend)))
|
| 440 |
+
fb = fig.bbox
|
| 441 |
+
for k, (s1, b1) in enumerate(boxes):
|
| 442 |
+
assert b1.x0 >= fb.x0 - 1 and b1.x1 <= fb.x1 + 1 and b1.y0 >= fb.y0 - 1 and b1.y1 <= fb.y1 + 1, f"outside: {s1}"
|
| 443 |
+
for s2, b2 in boxes[k + 1:]:
|
| 444 |
+
assert not b1.overlaps(b2), f"text overlap: {s1!r} / {s2!r}"
|
| 445 |
+
print(f"figure {W:.2f} x {H:.2f} in; {len(boxes)} text boxes, no overlap")
|
| 446 |
+
style.save(fig, "sec10_paired_subset_cohorts", FIG)
|
| 447 |
+
print("saved", FIG / "sec10_paired_subset_cohorts.png")
|
| 448 |
+
print(qt.to_string())
|
paper-releases/pbisc-diffusion/updates/20261008T125804Z-deck-fig2-3-healthy-fig5-rare/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sync_sec09_text.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Copy generated slide text into data/slides_spec.json.
|
| 3 |
+
|
| 4 |
+
sec09_paired_validation.py regenerates titles, keywords and footnotes from the
|
| 5 |
+
scores (the scSemiProfiler verdicts can change when the missing draws arrive).
|
| 6 |
+
Run after that script and before generate_deck.py:
|
| 7 |
+
|
| 8 |
+
python3 tools/sec09_paired_validation.py
|
| 9 |
+
python3 tools/sync_sec09_text.py
|
| 10 |
+
python3 generate_deck.py
|
| 11 |
+
|
| 12 |
+
Two kinds of spec slides are synced:
|
| 13 |
+
- "sec09_index": i -> slide i of data/sec09_slide_text.json (section 9 main slides)
|
| 14 |
+
- "text_source": {"file": "data/<x>_slide_text.json", "index": i}
|
| 15 |
+
-> slide i of that file (added 2026-10-02: data/sec09_extra_slide_text.json from
|
| 16 |
+
tools/sec09_extra_metrics.py, data/sec07_rank_sweep_slide_text.json from
|
| 17 |
+
tools/sec07_rank_sweep.py)
|
| 18 |
+
|
| 19 |
+
Titles, keywords, footnote_full, numbers and (from footnote_short) the on-slide footnote
|
| 20 |
+
are overwritten; if footnote_full changed, the script lists the slide so the
|
| 21 |
+
short copy can be checked by hand (the deck build fails if it exceeds 2 lines).
|
| 22 |
+
"""
|
| 23 |
+
import json
|
| 24 |
+
import sys
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
DECK = Path(__file__).resolve().parents[1]
|
| 28 |
+
SPEC = Path(sys.argv[1]) if len(sys.argv) > 1 else DECK / "data" / "slides_spec.json"
|
| 29 |
+
SRC = DECK / "data" / "sec09_slide_text.json"
|
| 30 |
+
# section-9 slides deliberately left out of the deck (index -> why); every other index must be used exactly once
|
| 31 |
+
RETIRED = {2: "5 donors: LoRA vs scSemiProfiler — disease signal; superseded 2026-10-08 by tools/fig4_disease.py "
|
| 32 |
+
"(5-pair comparison without the bulk-broadcast baseline, partial r added)",
|
| 33 |
+
3: "5-fold CV: train on the other 4 folds; superseded 2026-10-08 by tools/fig4_disease.py (5-fold disease, "
|
| 34 |
+
"no broadcast) and tools/fig23_healthy.py (ImMicro cells)"}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def copy_text(s: dict, g: dict, review: list) -> None:
|
| 38 |
+
figs = [str(Path(f).relative_to(DECK)) for f in g["figures"]]
|
| 39 |
+
have = [str(Path(f).relative_to(DECK)) if Path(f).is_absolute() else f for f in s["figures"]]
|
| 40 |
+
if figs != have:
|
| 41 |
+
raise SystemExit(f"figure mismatch for '{g['title']}': {figs} vs {s['figures']}")
|
| 42 |
+
s["figures"] = figs
|
| 43 |
+
s["title"] = g["title"]
|
| 44 |
+
s["keywords"] = g["keywords"]
|
| 45 |
+
if s.get("footnote_full", s.get("footnote")) != g["footnote"]:
|
| 46 |
+
review.append(g["title"])
|
| 47 |
+
s["footnote_full"] = g["footnote"]
|
| 48 |
+
if g.get("footnote_short"):
|
| 49 |
+
s["footnote"] = g["footnote_short"]
|
| 50 |
+
s["numbers"] = g["numbers"] # quoted numbers + sources, kept in step with the slide text (2026-10-01)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def main() -> None:
|
| 54 |
+
spec = json.loads(SPEC.read_text())
|
| 55 |
+
src = json.loads(SRC.read_text())["slides"]
|
| 56 |
+
review = []
|
| 57 |
+
n = 0
|
| 58 |
+
other: dict = {}
|
| 59 |
+
for s in spec["slides"]:
|
| 60 |
+
i = s.get("sec09_index")
|
| 61 |
+
if i is not None:
|
| 62 |
+
copy_text(s, src[i], review)
|
| 63 |
+
n += 1
|
| 64 |
+
continue
|
| 65 |
+
ts = s.get("text_source")
|
| 66 |
+
if ts:
|
| 67 |
+
f = DECK / ts["file"]
|
| 68 |
+
g = json.loads(f.read_text())["slides"]
|
| 69 |
+
copy_text(s, g[int(ts["index"])], review)
|
| 70 |
+
other.setdefault(ts["file"], set()).add(int(ts["index"]))
|
| 71 |
+
used = {s.get("sec09_index") for s in spec["slides"] if s.get("sec09_index") is not None}
|
| 72 |
+
if used & set(RETIRED) or n + len(RETIRED) != len(src) or any(src[i]["title"] != t.split(";")[0] for i, t in RETIRED.items()):
|
| 73 |
+
raise SystemExit(f"spec has {n} sec09 slides + {len(RETIRED)} retired, source has {len(src)}")
|
| 74 |
+
for f, idx in other.items():
|
| 75 |
+
m = len(json.loads((DECK / f).read_text())["slides"])
|
| 76 |
+
if idx != set(range(m)):
|
| 77 |
+
raise SystemExit(f"spec uses slides {sorted(idx)} of {f}, which has {m}")
|
| 78 |
+
SPEC.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n")
|
| 79 |
+
print(f"synced {n} section 9 slides and " + ", ".join(f"{len(v)} from {k}" for k, v in other.items()))
|
| 80 |
+
for t in review:
|
| 81 |
+
print(f"REVIEW short footnote (source footnote changed): {t}")
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
if __name__ == "__main__":
|
| 85 |
+
main()
|