junidude14 commited on
Commit
5374ec4
·
verified ·
1 Parent(s): 084d607

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261008T050202Z-scsemi-imperial-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/README.md ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PBISC-Diffusion paper summary deck (2026-09-30, r00; ordered by the six manuscript figures since 2026-10-06)
2
+
3
+ 64-slide English deck, ordered by the six main figures of the Nature-style manuscript plan (user request 2026-10-06,
4
+ following `paper-release-20260928/reference-papers/Nature Style Manuscript Writing.pdf`):
5
+ - Title and outline: 6 figures, Supplementary, Appendix, Discussion.
6
+ - "Manuscript plan: six main figures": a table of each figure's claim and how many panels are ready.
7
+ - For each figure:
8
+ - a divider;
9
+ - a plan slide, a table of panel / content / evidence slide / status (Ready, Adapt, Draft, Build, Run, Plan);
10
+ - the existing slides that serve its panels, each labelled "Fig. 2c" etc. in the top-right corner.
11
+ - Supplementary: a plan slide plus the from-scratch results. Appendix: the modified scSemiProfiler run. Discussion: the
12
+ other-tissues outlook.
13
+
14
+ User decisions of 2026-10-06:
15
+ - No PBISC-VAE: scSemiProfiler, a VAE-based method, is the comparison (Fig. 3).
16
+ - Fig. 2 shows LoRA first on the healthy cohort (ImMicro) with the realism metrics (precision, coverage, classifier
17
+ AUROC, MMD, E_N); the disease-cohort comparison comes later.
18
+ - CYBERSORTx and other bulk deconvolution methods go to the Supplementary only (PBISC generates single cells).
19
+ - Figs 4 and 6 stay unplanned. Their existing slides are kept in the section as "Fig. 4 candidate" / "Fig. 6 candidate".
20
+
21
+ Only order, section labels, the agenda and new plan or draft slides changed. The new slides are "Overview draft (Nature
22
+ style)", the manuscript's candidate Fig. 1, and "Pretraining corpus", the Fig. 1d strip. No new result figures were
23
+ made.
24
+ - The plan lives in `data/figure_plan.json`.
25
+ - `tools/figure_plan.py` draws the plan tables and the slide text, and checks that every slide is placed exactly once.
26
+ - `tools/restructure_figure_order_20261006.py` rebuilds the order from the plan. It is rerun after every plan change and
27
+ keeps all slide fields.
28
+ - The earlier section order (10 sections, 45 slides) is in `_archive/2026-10-06_before_figure_order/`.
29
+
30
+ Short keyword lines only; the figures carry the results. Every slide that uses a published method, metric or
31
+ baseline has a one-line "References:" footer; full citations are in the speaker notes.
32
+
33
+ - `PBISC-Diffusion_paper_summary_20260930.pptx`: the deck
34
+ - `PBISC-Diffusion_paper_summary_20260930.pdf`: LibreOffice PDF of the deck
35
+ - `data/slides_spec.json`: slide order, titles, keywords, footnotes, references, speaker-note text
36
+ - `generate_deck.py`: builds the pptx from `data/slides_spec.json` only (python-pptx)
37
+ - `figures/`: exactly the figures the slides show (PNG + PDF), made by `tools/sec*.py`. Intermediate panels go to a
38
+ temporary folder; superseded figures are deleted, not kept (2026-10-02, user request; every deleted file was
39
+ checked to be in the paper archive by sha256 first).
40
+ - `data/sec*.csv` and `data/*_slide_text.json`: every plotted or quoted number with its source path
41
+ - `render/`: PDF and 70-dpi slide JPGs for checking
42
+
43
+ ## Slide order
44
+
45
+ | section | slides |
46
+ |---|---|
47
+ | 1 Model overview | bulk in, cells out; denoiser |
48
+ | 2 Backbone | SDD → PBISC-Diffusion; bulk conditioning |
49
+ | 3 Architecture ablation | width & context (loss, benchmark); gene panel |
50
+ | 4 Metrics + SLE benchmark | **how we score generated cells** (metric table with references); SLE benchmark; per cell type; bulk broadcast baseline |
51
+ | 5 Real bulk vs pseudobulk | input shift; same shift in three cohorts; cells off-manifold; disease direction flips |
52
+ | 6 Paired fine-tuning | method; evaluation design |
53
+ | 7 LoRA ablations | full vs LoRA vs cond.-encoder-only; LoRA rank r = 4 / 16 / 64; K diversification |
54
+ | 8 Pairs needed | composition / coverage / steps (with scSemiProfiler at the same n); donor and disease signal; pairs from other cohorts; longer training on them (with training minutes) |
55
+ | 9 Paired validation | cohorts; 5 donors: cells, realism beyond P/C, P/C at k = 3 / 5 / 10, scSemiProfiler copies its representative, disease signal, CAT curves, time to apply; 5-fold CV (with scSemiProfiler on the same pairs); same training pairs: LoRA vs scSemiProfiler; 5-fold realism metrics |
56
+ | 10 Next steps | paired-subset cohorts (planned); other tissues from a few dozen pairs (Discussion framing of the from-scratch results) |
57
+ | Supplementary | no pretraining: same cohort, from scratch (pilot); no pretraining: other cohorts, from scratch (pilot); rare states: from scratch vs pretrained; deconvolution with the same pairs: composition; deconvolution with the same pairs: disease signal |
58
+ | Appendix | scSemiProfiler without its output threshold (sensitivity; modified read-out, not the official output) |
59
+
60
+ ## Rebuild
61
+
62
+ Everything is CPU only; no GPU or checkpoint is touched.
63
+
64
+ ```bash
65
+ # prerequisites (plan folder plans/paired_finetune_intradataset_20260927/, CPU):
66
+ # scsemi/tools/representative_dependence.py -> scsemi/analysis/representative_dependence_20261002/
67
+ # tools/contrast_extra.py (+ tools/contrast_extra_tables.py) -> scores_contrast/ (Spearman, ceiling, limma, CAT, RBO)
68
+ # tools/build_tpm_zeroshot.py + tools/score_tpm_zeroshot.sh -> scores/<ds>/zeroshot_tpm_20261002/pooled/
69
+ # (the length-corrected zero-shot arm needs one GPU sampling step: tools/sample_lockwait.sh, coordinator only)
70
+ cd /home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00
71
+ # shared helpers, not run directly: style.py, sec03_common.py, scsemi_results.py, fold_sizes.py
72
+ for f in sec01_overview sec02_backbone sec03_width_loss sec03_width_bench sec03_panel \
73
+ sec04_metrics_overview sec04_sle_benchmark sec05_condition_space sec05_cells_offmanifold \
74
+ sec05_behcet_direction sec05_shift_cohorts sec06_finetune_method sec07_ft_modes \
75
+ sec07_k_aug sec07_rank_sweep sec08_pairs_needed sec08_cross_cohort sec09_paired_validation sec09_extra_metrics \
76
+ sec09_time_to_apply sec09_scsemi_representative sec09_cat_curves sec10_paired_subset_cohorts \
77
+ secA_scsemi_readout sec07_no_pretraining sec08_cross_scratch sec09_same_pairs \
78
+ secS_scratch_rare_states secS_deconvolution sec10_other_tissues figure_plan; do # keep this order (sec10 reads secS; figure_plan last)
79
+ python3 "tools/$f.py" || break
80
+ done
81
+ python3 tools/restructure_figure_order_20261006.py # order the slides by data/figure_plan.json
82
+ python3 tools/sync_sec09_text.py # copy every generated slide text (sec09_index / text_source) into the spec
83
+ python3 generate_deck.py # -> PBISC-Diffusion_paper_summary_20260930.pptx
84
+ soffice --headless --convert-to pdf --outdir render PBISC-Diffusion_paper_summary_20260930.pptx
85
+ pdftoppm -jpeg -r 70 render/PBISC-Diffusion_paper_summary_20260930.pdf render/slide
86
+ cp render/PBISC-Diffusion_paper_summary_20260930.pdf .
87
+ ```
88
+
89
+ `generate_deck.py` stops with an error if a figure is missing, a title does not fit on one line, a footnote needs
90
+ more than 2 lines (1 line when the slide has references), the reference line needs more than 1 line, or any text
91
+ contains Korean or placeholder words. `tools/restructure_20261002.py` is the one-off script that produced the current
92
+ slide order and the references (it refuses to run twice).
93
+
94
+ ## Notes
95
+
96
+ - **No "all" label (2026-10-02).** The 5-fold arm trains each fold model on the other four folds minus 7–8
97
+ inner-validation donors; its test fold is never trained on (RUN.json `test_rows_never_loaded_for_training`). Figures
98
+ label it "5-fold CV (other 4 folds)" and learning-curve ticks show the training-pair count per fold (78–79 ImMicro,
99
+ 58–59 sepsis), read by `tools/fold_sizes.py`.
100
+ - **Learning curve x = 0 uses no pairs (2026-10-02).** It shows the zero-shot model fed the real bulk as measured
101
+ and after exon-length correction (counts / Ensembl union-exon kb, then the same fixed-depth arithmetic;
102
+ `plans/.../tools/build_tpm_zeroshot.py`, scored in `scores/<ds>/zeroshot_tpm_20261002/pooled`). The old x = 0
103
+ calibration point, whose alpha used every training pair of the fold, is gone; calibration appears only fitted on the
104
+ same n pairs as the LoRA point (squares; `cal_budget_20261001`).
105
+ - **Disease metrics (2026-10-02).** Next to Pearson logFC r and the Welch top-50 DEG overlap: Spearman r, the
106
+ split-half ceiling (observed vs observed, Spearman–Brown), limma-voom top-50 DEG, each arm's chance overlap, and
107
+ CAT curves with the k / 2G chance line (`plans/.../scores_contrast/`, tools/contrast_extra.py; every Pearson r and
108
+ Welch count reproduced exactly). Repeated samples of one patient (Imperial, Giroux, Ji) count as separate samples in
109
+ both DE tests, as in the scorer (footnote).
110
+ - Section 9 text is generated: `tools/sec09_paired_validation.py`, `sec09_extra_metrics.py`, `sec07_rank_sweep.py`,
111
+ `sec09_time_to_apply.py`, `sec09_scsemi_representative.py`, `sec09_cat_curves.py` write slide text JSON; sync copies
112
+ it. Hand-written: the keywords of the two "Pairs needed" slides (section 8) and of every slide in sections 1–7 and 10.
113
+ - Giroux's disease metrics exclude 196 sex-linked genes (severity is confounded with sex), from
114
+ `plans/.../scores_nosex/`. The calibration comparator is "Zero-shot + calibration" (user decision 2026-10-01).
115
+ - Story rule (user decision 2026-09-30): no PBISC-VAE and no reference calibration (refcal). The exon-length-corrected
116
+ input is used only as the no-pair x = 0 point of the learning curve (user decision 2026-10-02).
117
+ `tools/sec04_immicro.py` (refcal vs scSemiProfiler on ImMicro) is kept but is not part of the deck or the rebuild.
118
+ - scSemiProfiler 5-fold and equal-budget results are picked up automatically when they appear (`tools/scsemi_results.py`;
119
+ arm `scsemi__raw` in `scores/<cohort>/scsemi_cv_20261002/pooled*/`, `scsemi_n{5,10,20,40}__raw` in
120
+ `scores/<cohort>/scsemi_budget_20261002/pooled*/`; same donors and reference cells as the main pooled call only).
121
+ Then rerun sections 8 and 9, sync, recheck the section 8 keywords and rebuild.
122
+ - Earlier versions: `_archive/2026-09-30_before_no_vae_refcal/`, `_archive/2026-10-01_before_extra_metrics/`,
123
+ `_archive/2026-10-02_before_time_to_apply/`, `_archive/2026-10-02_before_restructure/` (pptx, PDF, spec; their
124
+ figures are in the paper archive). `DRAFT_1150_*`: the copy shown at the 2026-09-30 12:00 meeting.
125
+
126
+ - Added 2026-10-03 (user decision: the cross-cohort experiment is reported at K = 1000 only and is the figure that explains
127
+ why PBISC fits LoRA on a few pairs of each cohort): slides 25-26 in section 8, `tools/sec08_cross_cohort.py`.
128
+ - Slide 25 "Pairs from other cohorts do not transfer": per held-out cohort, composition L1 / coverage / disease logFC r of
129
+ zero-shot, calibration fitted on the other cohorts, LoRA r16 / r64 / full fine-tune trained on the other cohorts
130
+ (+ Liu 2021) at step saturation, and LoRA on the cohort's own pairs (5-fold pooled).
131
+ - Slide 26 "Longer training on other cohorts" (": gap stays" since 2026-10-06): the same metrics at every 20k-step
132
+ milestone.
133
+ - Source plan: `plans/paired_crosscohort_20261002/` (README; same-reference and same-sample checks in the script).
134
+ Agenda item 8 now reads "How many pairs, and do other cohorts' pairs transfer". The deck has 37 slides.
135
+ Pre-update copy: `_archive/2026-10-03_before_cross_cohort/`.
136
+
137
+ ## Sources
138
+
139
+ Final model: `runs/f01_6k_1x_seed20260627` (epoch 16, EMA). Scores and receipts come from
140
+ `plans/utility_studies_final6k_20260925/`, `plans/paired_finetune_intradataset_20260927/`,
141
+ `plans/immicro_scsemi_comparison_20260927/`, `plans/floor01_campaign_20260923/`,
142
+ `analysis/scsemi_benchmark_diffusion_20260913/` and the run folders named in each `data/sec*.csv`. Reference PDFs:
143
+ `/home/sj_server_1/PBISC/paper-release-20260928/reference-papers/` (INDEX.md). Manuscript:
144
+ `/home/sj_server_1/PBISC/paper-release-20260928/manuscript/`.
145
+ - 2026-10-04 appendix (user decision: supplementary, appendix only, because it changes scSemiProfiler's official
146
+ output). Slide 38 is the divider "Appendix" and slide 39 is "Appendix: scSemiProfiler without output threshold"
147
+ (`tools/secA_scsemi_readout.py`, `data/secA_scsemi_readout{.csv,_slide_text.json}`).
148
+ - Inputs: `plans/paired_finetune_intradataset_20260927/scsemi/analysis/output_variants_20261003/`. The script checks
149
+ that its LoRA-5 and official scSemiProfiler values equal the section 9 slide data draw by draw.
150
+ - Result: without upstream's output threshold, scSemiProfiler's coverage rises in 5/5 cohorts, and 23/23 LoRA-5
151
+ comparisons (coverage, precision, composition, logFC r, DEG) keep their winner.
152
+ - The outline keeps its 10 sections (the builder requires 10). The pre-change copy is in
153
+ `_archive/2026-10-04_before_appendix/`. The deck has 39 slides.
154
+ - 2026-10-05 update (user request: put the results so far into the deck). Pre-change copy: `_archive/2026-10-05_before_scratch_cv/`.
155
+ - New slide 23, "No pretraining: same cohort, from scratch" (`tools/sec07_no_pretraining.py`). Pilot on sepsis fold 0
156
+ (17 donors). Reads `fold0_scratch_20261005/` and the runs' RUN.json. The donor composition r is recomputed from
157
+ per_donor.csv and reproduces ablation_extra_donor.csv.
158
+ - New slide 28, "No pretraining: other cohorts, from scratch" (`tools/sec08_cross_scratch.py`). Held-out sepsis pilot.
159
+ Every arm is read from `paired_crosscohort_20261002/scores_masked/`: genes no training cohort measured are zeroed
160
+ in all arms, because the unmasked scratch arm puts 91–94 % of its UMI there (read from the generated_masked logs
161
+ since 2026-10-06).
162
+ - New slide 38, "Same training pairs: LoRA vs scSemiProfiler" (`tools/sec09_same_pairs.py`). scSemiProfiler 5-fold
163
+ CV with LoRA's own training pairs, plus GPU hours per fold from the receipts on either host. Cohorts that are still
164
+ running show "in progress"; rerun the script as they finish.
165
+ - These two slides now draw the scSemiProfiler CV / budget runs automatically:
166
+ - Slide 24, "Pairs needed" (diamonds; ImMicro so far): keyword 2 reworded, footnote extended.
167
+ - Slide 37, "5-fold CV" (yellow bar; ImMicro and Ji so far).
168
+ - `tools/sec09_paired_validation.py` reads the scSemiProfiler CV arm's Spearman / limma values from
169
+ `scores_contrast/<cohort>/scsemi_cv_20261002/pooled/` (contrast_extra.py --design scored). Pearson r and the Welch
170
+ DEG must match the scorer; the values stay blank until computed. Cohorts not yet run say "in progress".
171
+ - Agenda item 7 now reads "LoRA: compute, rank, K; training from scratch". The deck has 42 slides.
172
+ - New helper: `tools/grouped_bars.py`.
173
+ - 2026-10-06 update (user request: check that the cross-cohort LoRA / full FT, cross-cohort from-scratch and
174
+ same-cohort from-scratch (+ recipes) results, with benchmarks and training times, and the scratch-vs-pretrained rare
175
+ states are in the deck; user decision: the from-scratch results go to the paper's Supplementary and the Discussion
176
+ presents them as a route to other tissues). Pre-change copy: `_archive/2026-10-06_before_supplementary/`.
177
+ - **Supplementary block (new divider, slides 40-43).**
178
+ - "No pretraining: same cohort, from scratch" and "No pretraining: other cohorts, from scratch" moved here from
179
+ sections 7 and 8. Their content is unchanged; slide 42's notes now name the cross-cohort slides by title.
180
+ - New "Rare states: from scratch vs pretrained" (`tools/secS_scratch_rare_states.py`).
181
+ - It reads the rare-state screen (`plans/rare_states_screen_20261004/out/sepsis_fold0_*` and
182
+ `sepsis_loco_masked_*`).
183
+ - The cross-cohort arms use the masked scoring (46 never-measured genes zeroed in every arm).
184
+ - The donor bootstrap reproduces the verified analysis in `out/scratch_vs_lora_20261005/REPORT.md`.
185
+ - **Section 10 "Next steps".**
186
+ - New "Next: other tissues from a few dozen pairs" (`tools/sec10_other_tissues.py`): a comparison table, pretrained
187
+ + LoRA vs from scratch.
188
+ - Every value is read from the deck's own source tables. The say text is the user's Discussion framing.
189
+ - **Slide 26 "Longer training on other cohorts".** The first keyword is now training minutes to saturation (RUN.json
190
+ wall seconds), with per-cohort minutes and steps in the notes (`tools/sec08_cross_cohort.py`).
191
+ - **Slide 34 "5 donors: time to apply".**
192
+ - The pretraining hours are read from `data/sec06_ft_method.csv`, no longer hard-coded.
193
+ - The note names the 'Fine-tuning with paired bulk + sc' slide by title. Its old "slide 15" pointed at the wrong
194
+ slide.
195
+ - Agenda items 7 and 10 updated. Spec change: `tools/restructure_20261006.py` (refuses to run twice). The deck has 45
196
+ slides; no Korean text.
197
+ - **Review pass (same day).** An independent 5-agent review of the changed slides confirmed 39 issues; all are
198
+ fixed. Pre-review copies of the touched scripts and the spec: `_archive/2026-10-06_before_supplementary/*.pre_review`.
199
+ - Slide 39: pretraining now reads 33.1 M train cells (`train_split_cells`; the 41.4 M corpus includes val/test).
200
+ The rare-state row follows the bootstrap verdicts on both sides (closer on ISG-high T / on DN2 B; labels and
201
+ states both arms miss by > 4-fold are not counted). "No corpus" became "come close": the scratch runs still took
202
+ the panel, value scaler and z-score constants from the PBMC checkpoint (RUN.json `kept_from_checkpoint`, now in
203
+ the notes). The say text carries the one-fold pilot qualifier; the footnote names both pilots.
204
+ - Slide 43: "no significant difference on average" (not "no difference"). Keyword 2 is the cycling T/NK count
205
+ (8 of 8 comparisons). The notes add the ISG-high T split by panel, the scratch-closer states (DN2 B, MS1), the
206
+ 52-call tally, the fold-0 caveat (fold 0 is the own-pair LoRA's best fold for C1Q-high and cycling T/NK,
207
+ computed from `folds.csv`), label states unthinned, and "8 of 13 states shown".
208
+ - Slide 26: title "...: gap stays" and "drifts in Sepsis and Ji" are computed from the milestones (gap = no milestone
209
+ reaches the own-cohort coverage; drift = full fine-tune L1 up by >= 0.05). Minutes are in
210
+ `data/sec08_cross_cohort.csv` (wall_seconds, minutes, run_receipt) and in the numbers list.
211
+ - Slide 42: UMI share (94 %, 91–94 % across milestones), the observed share (0.014 %, from `cells_panel6k.npz`)
212
+ and both arms' stopping settings are read from the receipts; the "none" label sits inside the axes.
213
+ - Slide 34: keywords use the cohort means of the figure (17–59×, 57 min–4.1 h); the per-draw range 11–63× is in the
214
+ notes. The right panel shares the bars' rows and has a title.
215
+ - Talk text and pointers: slides 23, 25, 26, 45 (say), 22 (recipes description), 32 and 36 (slide pointers by
216
+ title), slide 1 subtitle "updated 2026-10-06".
217
+ - 2026-10-08 update (user request: put the BayesPrism, CIBERSORTx and scSemiProfiler 5-fold results into the deck).
218
+ Pre-change copy: `_archive/2026-10-08_before_deconvolution/`.
219
+ - **Two new Supplementary slides** (`tools/secS_deconvolution.py`, `data/secS_deconvolution{.csv,_slide_text.json}`):
220
+ "Deconvolution with the same pairs: composition" and "...: disease signal".
221
+ - Source: `plans/bayesprism_paired_20261006/` (README, `results/RESULTS_full.md`, `RESULTS_cibersortx.md`).
222
+ - BayesPrism (recommended genes) and official CIBERSORTx (Fractions S-mode + HiRes) use the same paired donors
223
+ as the reference and the test samples' real bulk as the mixture, with the benchmark's own truth and scorer.
224
+ - Keywords and notes are computed from the tables.
225
+ - **Supplementary plan.** The planned "Bulk deconvolution methods" row is replaced by the two Ready slides.
226
+ `tools/figure_plan.py` now takes an optional per-slide note (`supplementary.notes`) and drops "Planned:" when
227
+ nothing is planned.
228
+ - **New scSemiProfiler results picked up (server_1):**
229
+ - Sepsis and Giroux 5-fold CV. Giroux was finalized on server_1 from sha-checked copies of its fold NPZs, and
230
+ rescored without sex-linked genes in `scores_nosex/giroux2022/scsemi_cv_20261002/pooled`.
231
+ - Sepsis equal-budget n = 5/10/20/40.
232
+ - Imperial 5-fold: finished on server_2 at 13:45 and was finalized on server_1 from sha-checked fold copies.
233
+ scSemiProfiler 5-fold now covers all five cohorts.
234
+ - Spearman/limma extras for sepsis, Giroux and Imperial; realism extras for all five cohorts.
235
+ - **Text changes from the new results:**
236
+ - "Same training pairs": keywords are data-driven. LoRA leads on coverage and precision in 5/5 cohorts;
237
+ composition 4/5 and logFC r 3/4, where scSemiProfiler leads in Giroux. The GPU-time ratio is 19–62×.
238
+ - sec09_same_pairs.py now reads the sepsis fold-0 pilot queue tag (`sep_f0`). For Giroux it quotes DEG from
239
+ scores_nosex, and for older pooled LoRA calls from pooled_deg.
240
+ - "5-fold CV" keyword: logFC r 3/4.
241
+ - "Pairs needed" (hand-written): scSemiProfiler coverage 0.04 / 0.10. On sepsis disease logFC r,
242
+ scSemiProfiler at 5–40 pairs (0.52–0.58) is above LoRA (0.29–0.48), while its top-50 DEG stays at 2–6.
paper-releases/pbisc-diffusion/updates/20261008T050202Z-scsemi-imperial-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/figplan_fig3.png ADDED

Git LFS Details

  • SHA256: 99c3acb87cead14461525e72424f0ef2f7fa350f7b1f5ae22e0316f83d7499a1
  • Pointer size: 131 Bytes
  • Size of remote file: 191 kB
paper-releases/pbisc-diffusion/updates/20261008T050202Z-scsemi-imperial-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/20261008T050202Z-scsemi-imperial-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/secS_deconvolution.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """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)"
223
+ if any(not np.isfinite(vals[("c", d, "scsemi")][0]) for d in ORDER) else "")
224
+ + ". Pipeline check: "
225
+ "on pseudobulk mixtures BayesPrism recovers the observed mRNA shares (e.g. T 0.39 vs 0.38), so the error "
226
+ "comes from real bulk. Source: plans/bayesprism_paired_20261006/results/RESULTS_full.md, "
227
+ "RESULTS_cibersortx.md.")
228
+ full2 = ("Supplementary. Case-vs-control per-cell-type logFC (mean CP10K; T, B, Monocyte, NK) from BayesPrism's "
229
+ "posterior cell-type expression Z and CIBERSORTx HiRes, scored with the benchmark's own functions (the "
230
+ "recomputed bulk broadcast equals the stored one in every split); partial r = the part beyond the bulk "
231
+ "broadcast; top-50 DEG = Welch, summed over types (many ties at 0 in Ji and Giroux). 5-donor draws, mean "
232
+ "over draws with a score. Giroux excludes sex-linked genes, as everywhere in the deck. " + cx_note
233
+ + "Source: plans/bayesprism_paired_20261006/results/RESULTS_full.md, RESULTS_cibersortx.md.")
234
+ slides = [
235
+ {"title": "Deconvolution with the same pairs: composition", "layout": "full",
236
+ "figures": [str(FIGDIR / "secS_deconv_composition.png")], "keywords": kw1,
237
+ "footnote_short": "Same donors, truth and scorer as PBISC. Reference = the paired donors' cells.",
238
+ "footnote": full1, "numbers": num1},
239
+ {"title": "Deconvolution with the same pairs: disease signal", "layout": "full",
240
+ "figures": [str(FIGDIR / "secS_deconv_disease.png")], "keywords": kw2,
241
+ "footnote_short": "5-donor draws, mean over draws. Partial r = signal beyond the bulk broadcast.",
242
+ "footnote": full2, "numbers": num2}]
243
+ for s in slides:
244
+ if len(s["footnote_short"]) > 110:
245
+ raise SystemExit("short footnote too long")
246
+ out = {"section": "S-deconvolution", "scripts": [str(Path(__file__).resolve())],
247
+ "generated_from": "tools/secS_deconvolution.py (rerun to refresh; do not edit by hand)", "slides": slides}
248
+ (OUTDATA / "secS_deconvolution_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))
249
+ print("\n".join(kw1 + kw2))
250
+ print(tab.round(3).to_string(index=False))
251
+ return 0
252
+
253
+
254
+ if __name__ == "__main__":
255
+ sys.exit(main())