junidude14 commited on
Commit
f946ad5
·
verified ·
1 Parent(s): a97f658

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261008T022410Z-deconv-scsemi-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/figplan_fig3.png ADDED

Git LFS Details

  • SHA256: c984b8fb4c4cd0ae60642a046d9fa286b7db4843d6661c57cfb54c7b7f56fded
  • Pointer size: 131 Bytes
  • Size of remote file: 201 kB
paper-releases/pbisc-diffusion/updates/20261008T022410Z-deconv-scsemi-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/figplan_supp.png ADDED

Git LFS Details

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