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

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/README.md ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ - Spearman/limma extras for sepsis and Giroux; realism extras for ImMicro, sepsis, Ji and Giroux.
233
+ - Imperial 5-fold is still running on server_2.
234
+ - **Text changes from the new results:**
235
+ - "Same training pairs": keywords are data-driven. LoRA leads on coverage and precision in 4/4 cohorts;
236
+ composition 3/4 and logFC r 2/3, where scSemiProfiler leads in Giroux. The GPU-time ratio is 19–62×.
237
+ - sec09_same_pairs.py now reads the sepsis fold-0 pilot queue tag (`sep_f0`). For Giroux it quotes DEG from
238
+ scores_nosex, and for older pooled LoRA calls from pooled_deg.
239
+ - "5-fold CV" keyword: logFC r 3/4.
240
+ - "Pairs needed" (hand-written): scSemiProfiler coverage 0.04 / 0.10. On sepsis disease logFC r,
241
+ 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/20261008T022410Z-deconv-scsemi-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/figure_plan.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Six-figure plan slides for the paper-summary deck (2026-10-06, Nature-style manuscript order).
3
+
4
+ Reads data/figure_plan.json (the hand-written plan: figures, panels, evidence slides, status) and the current spec.
5
+ Checks that every evidence title is a slide of the deck (or one of the two slides made here) and that every content
6
+ slide of the deck is placed exactly once (a panel, a figure's details, Supplementary or Appendix).
7
+ Writes:
8
+ figures/figplan_overview.png, figures/figplan_fig{1..6}.png plan tables (no data)
9
+ figures/fig1b_overview_nature.png, figures/fig1d_corpus.png copies of the manuscript candidates
10
+ data/figure_plan_slide_text.json slide text (synced into the spec)
11
+ CPU only.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import shutil
17
+ import sys
18
+ import textwrap
19
+ from pathlib import Path
20
+
21
+ import matplotlib
22
+
23
+ matplotlib.use("Agg")
24
+ import matplotlib.pyplot as plt # noqa: E402
25
+ from matplotlib.patches import FancyBboxPatch # noqa: E402
26
+
27
+ DECK = Path(__file__).resolve().parents[1]
28
+ MS = Path("/home/sj_server_1/PBISC/paper-release-20260928/manuscript")
29
+ PLAN = DECK / "data" / "figure_plan.json"
30
+ SPEC = DECK / "data" / "slides_spec.json"
31
+ FIG = DECK / "figures"
32
+ NEW = {"Overview draft (Nature style)": MS / "figures" / "fig01_architecture_nature.png",
33
+ "Pretraining corpus": MS / "figures" / "fig01_corpus_nature.png"}
34
+ STATUS_COLOR = {"Ready": "#5E8C6A", "Adapt": "#C98A4B", "Draft": "#8E6C9E", "Build": "#3F6E9E", "Run": "#B5544F",
35
+ "Plan": "#8C8C8C"}
36
+ INK, SUB = "#1A1A1A", "#5A5A5A"
37
+ plt.rcParams.update({"font.family": "Arial", "font.size": 11})
38
+
39
+
40
+ def chip(ax, x, y, s, w=0.085, h=0.05, color=None):
41
+ ax.add_patch(FancyBboxPatch((x, y - h / 2), w, h, boxstyle="round,pad=0.004,rounding_size=0.012",
42
+ fc=color or STATUS_COLOR[s], ec="none", transform=ax.transAxes))
43
+ ax.text(x + w / 2, y, s, ha="center", va="center", color="white", fontsize=10, fontweight="bold",
44
+ transform=ax.transAxes)
45
+
46
+
47
+ def plan_rows(fig_plan):
48
+ """panel rows; a figure without panels shows one row holding the slides kept in its section"""
49
+ if fig_plan["panels"]:
50
+ return fig_plan["panels"]
51
+ return [{"p": "", "content": "No panels planned yet", "evidence": fig_plan.get("candidates", []),
52
+ "status": "Plan", "note": "slides kept in this section until then" if fig_plan.get("candidates") else ""}]
53
+
54
+
55
+ def plan_table(fig_plan, out):
56
+ rows = plan_rows(fig_plan)
57
+ cols = {"p": 0.012, "c": 0.045, "e": 0.355, "s": 0.695, "n": 0.79}
58
+ wrapped = []
59
+ for r in rows:
60
+ ev = "; ".join(f"\u201c{e}\u201d" for e in r["evidence"]) if r["evidence"] else "\u2014"
61
+ wrapped.append((textwrap.wrap(r["content"], 40), textwrap.wrap(ev, 46) or ["\u2014"],
62
+ textwrap.wrap(r.get("note", ""), 30)))
63
+ nlines = [max(len(c), len(e), len(n), 1) for c, e, n in wrapped]
64
+ line_in, pad_in = 0.235, 0.09
65
+ fig_h = 0.45 + sum(nl * line_in + 2 * pad_in for nl in nlines)
66
+ fig = plt.figure(figsize=(12.3, fig_h))
67
+ ax = fig.add_axes([0, 0, 1, 1])
68
+ ax.axis("off")
69
+ f = lambda inch: inch / fig_h # inches -> axes fraction (vertical)
70
+ y = 1 - f(0.2)
71
+ for k, h in zip(cols, ["", "Panel content", "Evidence in this deck (slide title)", "Status", "Note"]):
72
+ ax.text(cols[k], y, h, fontsize=10.5, color=SUB, fontweight="bold", va="center", transform=ax.transAxes)
73
+ y -= f(0.25)
74
+ for k, (r, (c, e, n), nl) in enumerate(zip(rows, wrapped, nlines)):
75
+ hgt = f(nl * line_in + 2 * pad_in)
76
+ if k % 2 == 0:
77
+ ax.add_patch(plt.Rectangle((0, y - hgt), 1, hgt, color="#F4F4F4", transform=ax.transAxes, zorder=0))
78
+ y0 = y - f(pad_in + line_in / 2)
79
+ ax.text(cols["p"] + 0.008, y0, r["p"], fontsize=12, fontweight="bold", va="center", transform=ax.transAxes)
80
+ for x, lines, col in ((cols["c"], c, INK), (cols["e"], e, SUB), (cols["n"], n, SUB)):
81
+ for j, ln in enumerate(lines):
82
+ ax.text(x, y0 - f(j * line_in), ln, fontsize=10.5, color=col, va="center", transform=ax.transAxes)
83
+ chip(ax, cols["s"], y0, r["status"], w=0.075, h=f(0.2))
84
+ y -= hgt
85
+ fig.savefig(out, dpi=200)
86
+ plt.close(fig)
87
+
88
+
89
+ def overview_table(plan, out):
90
+ figs = plan["figures"]
91
+ fig = plt.figure(figsize=(12.3, 5.0))
92
+ ax = fig.add_axes([0, 0, 1, 1])
93
+ ax.axis("off")
94
+ for x, h in ((0.012, "Main figure"), (0.40, "What the figure shows"), (0.735, "Panels by status")):
95
+ ax.text(x, 0.95, h, fontsize=11, color=SUB, fontweight="bold", transform=ax.transAxes)
96
+ step = 0.145
97
+ for k, fg in enumerate(figs):
98
+ y = 0.85 - k * step
99
+ if k % 2 == 0:
100
+ ax.add_patch(plt.Rectangle((0, y - step / 2), 1, step, color="#F4F4F4", transform=ax.transAxes, zorder=0))
101
+ ax.text(0.012, y, f"Fig. {fg['n']}", fontsize=12, fontweight="bold", va="center", transform=ax.transAxes)
102
+ ax.text(0.075, y, fg["title"], fontsize=11.5, va="center", transform=ax.transAxes)
103
+ lines = textwrap.wrap(fg["claim"], 50)
104
+ for j, ln in enumerate(lines):
105
+ ax.text(0.40, y + 0.022 * (len(lines) - 1) - j * 0.044, ln, fontsize=10.5, color=SUB, va="center",
106
+ transform=ax.transAxes)
107
+ counts = {}
108
+ for pnl in plan_rows(fg):
109
+ counts[pnl["status"]] = counts.get(pnl["status"], 0) + 1
110
+ x = 0.735
111
+ if not fg["panels"]:
112
+ chip(ax, x, y, "Not planned", w=0.1, h=0.06, color=STATUS_COLOR["Plan"])
113
+ continue
114
+ for st in STATUS_COLOR:
115
+ if st in counts:
116
+ chip(ax, x, y, f"{st} {counts[st]}", w=0.072, h=0.06, color=STATUS_COLOR[st])
117
+ x += 0.084
118
+ fig.savefig(out, dpi=200)
119
+ plt.close(fig)
120
+
121
+
122
+ def main() -> int:
123
+ plan = json.loads(PLAN.read_text())
124
+ spec = json.loads(SPEC.read_text())
125
+ have = [s["title"] for s in spec["slides"] if s.get("kind") == "content"]
126
+ have = [t for t in have if t not in NEW and not t.startswith(("Figure ", "Manuscript plan", "Supplementary plan"))]
127
+ placed = []
128
+ for f in plan["figures"]:
129
+ for p in f["panels"]:
130
+ placed += p["evidence"]
131
+ placed += f.get("candidates", []) + f["details"]
132
+ placed += plan["supplementary"]["slides"] + plan["appendix"] + plan.get("discussion", [])
133
+ unknown = [t for t in placed if t not in have and t not in NEW]
134
+ missing = [t for t in have if t not in placed]
135
+ twice = sorted({t for t in placed if placed.count(t) > 1})
136
+ if unknown or missing or twice:
137
+ raise SystemExit(f"plan does not match the deck: unknown {unknown}, unplaced {missing}, twice {twice}")
138
+ for title, src in NEW.items():
139
+ if not src.is_file():
140
+ raise SystemExit(f"missing manuscript figure {src}")
141
+ shutil.copyfile(NEW["Overview draft (Nature style)"], FIG / "fig1b_overview_nature.png")
142
+ shutil.copyfile(NEW["Pretraining corpus"], FIG / "fig1d_corpus.png")
143
+ overview_table(plan, FIG / "figplan_overview.png")
144
+ for f in plan["figures"]:
145
+ plan_table(f, FIG / f"figplan_fig{f['n']}.png")
146
+ notes = plan["supplementary"].get("notes", {}) # optional per-slide note (e.g. why it is supplementary)
147
+ sup = {"panels": [{"p": "S", "content": t, "evidence": [t], "status": "Ready", "note": notes.get(t, "")}
148
+ for t in plan["supplementary"]["slides"]]
149
+ + plan["supplementary"]["planned"]
150
+ + [{"p": "A", "content": t, "evidence": [t], "status": "Ready", "note": "modified baseline run"}
151
+ for t in plan["appendix"]]}
152
+ plan_table(sup, FIG / "figplan_supp.png")
153
+
154
+ summ = json.loads((MS / "source_data/corpus/corpus_summary.json").read_text())
155
+ tot = summ["cells"]
156
+ healthy = summ["family_cells"]["Healthy"] / tot
157
+ vitro = summ["handling_cells"]["in vitro"] / tot
158
+ slides = [{
159
+ "title": "Manuscript plan: six main figures", "layout": "full",
160
+ "figures": [str(FIG / "figplan_overview.png")], "keywords": [],
161
+ "footnote_short": "Nature style: short abstract and introduction, descriptive results, short discussion, "
162
+ "detailed methods; up to 17 supplementary figures.",
163
+ "footnote": plan["source"] + " Status: " + "; ".join(f"{k} = {v}" for k, v in plan["status_legend"].items()) + ".",
164
+ "numbers": []}]
165
+ for f in plan["figures"]:
166
+ n_ok = sum(p["status"] == "Ready" for p in f["panels"])
167
+ short = (f"{f['claim']} {n_ok} of {len(f['panels'])} panels ready." if f["panels"] else f["claim"])
168
+ slides.append({
169
+ "title": f"Figure {f['n']} plan: {f['title']}", "layout": "full",
170
+ "figures": [str(FIG / f"figplan_fig{f['n']}.png")], "keywords": [],
171
+ "footnote_short": short,
172
+ "footnote": "Panels: " + " ".join(f"{p['p']}) {p['content']} [{p['status']}"
173
+ + (f"; {p['note']}" if p.get("note") else "") + "]." for p in f["panels"])
174
+ + (" Slides kept in this section until it is planned: " + "; ".join(f["candidates"]) + "."
175
+ if f.get("candidates") else "")
176
+ + (" Details in this section: " + "; ".join(f["details"]) + "." if f["details"] else ""),
177
+ "numbers": []})
178
+ slides.append({
179
+ "title": "Supplementary plan", "layout": "full", "figures": [str(FIG / "figplan_supp.png")], "keywords": [],
180
+ "footnote_short": "Bulk deconvolution methods appear here only: PBISC generates single cells, a different task.",
181
+ "footnote": "Supplementary: " + "; ".join(plan["supplementary"]["slides"]) + "."
182
+ + (" Planned: " + "; ".join(f"{p['content']} [{p['status']}; {p.get('note', '')}]"
183
+ for p in plan["supplementary"]["planned"]) + "."
184
+ if plan["supplementary"]["planned"] else "")
185
+ + " Appendix: " + "; ".join(plan["appendix"]) + ".",
186
+ "numbers": []})
187
+ slides.append({
188
+ "title": "Overview draft (Nature style)", "layout": "full",
189
+ "figures": [str(FIG / "fig1b_overview_nature.png")],
190
+ "keywords": ["Each cell is learned with its own bulk", "Diffusion on each gene's value and detection",
191
+ "One bulk in, K cells out; optional LoRA"],
192
+ "footnote_short": "Draft for Fig. 1b; schematic, no data. Plan: manuscript editorial/fig1_nature_redesign_plan.",
193
+ "footnote": "Candidate replacement for the engineering diagram (kept in this section as details and for Methods). "
194
+ "Source: paper-release-20260928/manuscript/figures/fig01_architecture_nature.svg "
195
+ "(scripts/build_figure1_architecture_nature.py).",
196
+ "numbers": []})
197
+ slides.append({
198
+ "title": "Pretraining corpus", "layout": "full",
199
+ "figures": [str(FIG / "fig1d_corpus.png")],
200
+ "keywords": [f"{tot / 1e6:.1f} M cells, {summ['datasets']} datasets, {summ['donors']:,} donors",
201
+ f"{100 * healthy:.1f}% healthy donors; {100 * vitro:.1f}% cultured in vitro",
202
+ "Labels describe the corpus; never model input"],
203
+ "footnote_short": "Detailed version: Supplementary Fig. S1 of the manuscript.",
204
+ "footnote": "Source: paper-release-20260928/manuscript/source_data/corpus/ (build_corpus_tables.py) and "
205
+ "figures/fig01_corpus_nature.png (build_figure1_corpus.py).",
206
+ "numbers": [{"value": f"{tot:,} cells; {summ['datasets']} datasets; {summ['donors']:,} donors; "
207
+ f"healthy {100 * healthy:.1f}%; in vitro {100 * vitro:.1f}%",
208
+ "source": "manuscript/source_data/corpus/corpus_summary.json"}]})
209
+ out = {"section": "figure-plan", "scripts": [str(Path(__file__).resolve())],
210
+ "generated_from": "tools/figure_plan.py (rerun to refresh; do not edit by hand)", "slides": slides}
211
+ (DECK / "data" / "figure_plan_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))
212
+ print("placed", len(placed), "slides; plan slides", len(slides))
213
+ return 0
214
+
215
+
216
+ if __name__ == "__main__":
217
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261008T022410Z-deconv-scsemi-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/restructure_figure_order_20261006.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Order the deck by the six main figures of the Nature-style manuscript plan (2026-10-06; rerun after every plan
3
+ change).
4
+
5
+ Reads data/figure_plan.json (written by hand) and data/figure_plan_slide_text.json (tools/figure_plan.py) and
6
+ rebuilds the order of data/slides_spec.json from the slides it already holds:
7
+ title, agenda (6 figures + Supplementary + Appendix + Discussion), the manuscript plan,
8
+ for each figure: a divider, its plan slide, its panel slides in panel order (section label "Fig. 1a" ...), the
9
+ slides kept in the section until it is planned ("Fig. 4 candidate") and its details,
10
+ Supplementary (plan slide + slides), Appendix, Discussion.
11
+ Existing slides keep every field except order and section label; dividers and plan slides are rebuilt each run.
12
+ The text of the plan slides is filled by tools/sync_sec09_text.py.
13
+ """
14
+ import json
15
+ from pathlib import Path
16
+
17
+ DECK = Path(__file__).resolve().parents[1]
18
+ SPEC = DECK / "data" / "slides_spec.json"
19
+ PLAN = DECK / "data" / "figure_plan.json"
20
+ TEXT = "data/figure_plan_slide_text.json"
21
+
22
+
23
+ def main() -> None:
24
+ spec = json.loads(SPEC.read_text())
25
+ plan = json.loads(PLAN.read_text())
26
+ gen = json.loads((DECK / TEXT).read_text())["slides"]
27
+ made = {g["title"]: i for i, g in enumerate(gen)}
28
+ old = {s["title"]: s for s in spec["slides"]
29
+ if s.get("kind") == "content" and s.get("text_source", {}).get("file") != TEXT}
30
+ title = next(s for s in spec["slides"] if s.get("kind") == "title")
31
+ agenda = next(s for s in spec["slides"] if s.get("kind") == "agenda")
32
+
33
+ def plan_slide(t, label):
34
+ i = made[t]
35
+ g = gen[i]
36
+ src = "tools/figure_plan.py; data/figure_plan.json"
37
+ if t == "Overview draft (Nature style)":
38
+ src = "tools/figure_plan.py; manuscript figures/fig01_architecture_nature.svg"
39
+ elif t == "Pretraining corpus":
40
+ src = "tools/figure_plan.py; manuscript figures/fig01_corpus_nature.png, source_data/corpus/"
41
+ return {"kind": "content", "section": "plan", "section_label": label,
42
+ "text_source": {"file": TEXT, "index": i}, "title": g["title"], "layout": g["layout"],
43
+ "figures": [str(Path(f).relative_to(DECK)) for f in g["figures"]], "keywords": [], "footnote": "",
44
+ "sources": src}
45
+
46
+ def take(t, label, section):
47
+ s = old.pop(t)
48
+ s["section"], s["section_label"] = section, label
49
+ return s
50
+
51
+ title["subtitle"] = "Paper figure plan (Nature style) · updated 2026-10-08"
52
+ agenda["items"] = ([f"Fig. {f['n']} {f['title']}" for f in plan["figures"]]
53
+ + ["Supplementary", "Appendix"] + (["Discussion"] if plan.get("discussion") else []))
54
+ out = [title, agenda, plan_slide("Manuscript plan: six main figures", "Plan")]
55
+ for f in plan["figures"]:
56
+ n = f["n"]
57
+ out.append({"kind": "divider", "title": f"Figure {n}. {f['title']}"})
58
+ out.append(plan_slide(f"Figure {n} plan: {f['title']}", f"Fig. {n} plan"))
59
+ for p in f["panels"]:
60
+ for t in p["evidence"]:
61
+ out.append(plan_slide(t, f"Fig. {n}{p['p']}") if t in made else take(t, f"Fig. {n}{p['p']}", str(n)))
62
+ out += [take(t, f"Fig. {n} candidate", str(n)) for t in f.get("candidates", [])]
63
+ out += [take(t, f"Fig. {n} details", str(n)) for t in f["details"]]
64
+ out.append({"kind": "divider", "title": "Supplementary"})
65
+ out.append(plan_slide("Supplementary plan", "Supplementary"))
66
+ out += [take(t, "Supplementary", "S") for t in plan["supplementary"]["slides"]]
67
+ out.append({"kind": "divider", "title": "Appendix"})
68
+ out += [take(t, "Appendix", "A") for t in plan["appendix"]]
69
+ if plan.get("discussion"):
70
+ out.append({"kind": "divider", "title": "Discussion"})
71
+ out += [take(t, "Discussion", "D") for t in plan["discussion"]]
72
+ if old:
73
+ raise SystemExit(f"slides not placed: {sorted(old)}")
74
+ spec["slides"] = out
75
+ SPEC.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n")
76
+ for i, s in enumerate(out, 1):
77
+ print(i, s.get("kind"), s.get("section_label", ""), "|", s.get("title"))
78
+
79
+
80
+ if __name__ == "__main__":
81
+ main()
paper-releases/pbisc-diffusion/updates/20261008T022410Z-deconv-scsemi-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_same_pairs.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Section 9 slide of the 2026-09-30 paper-summary deck: scSemiProfiler and LoRA given the SAME training pairs
3
+ (5-fold CV, 2026-10-05; cohorts still running are shown as "in progress").
4
+
5
+ CPU only. Per cohort, both methods use exactly the pairs of the other four folds (LoRA's training + inner-val rows =
6
+ scSemiProfiler's representatives; checked for every fold by scsemi/tools/check_units.py) and are scored on all usable
7
+ samples, each by the fold model that never saw it (one pooled score_ft.py call per method, same donors and reference):
8
+ LoRA scores/<ds>/pooled/summary.json arm real_lora__raw
9
+ scSemiProfiler scores/<ds>/scsemi_cv_20261002/pooled/summary.json arm scsemi__raw
10
+ Giroux disease metrics from scores_nosex/ (sex-linked genes excluded), as in the deck.
11
+ GPU time per fold (one GB10, every step alone on the GPU; data preparation and scoring not counted on either side):
12
+ LoRA runs/<ds>/fold<k>/real_lora/RUN.json wall_seconds + the sampling job's wall clock in logs/run_queue_*.log
13
+ scSemiProfiler scsemi/work/<ds>/cv/fold<k>/scsemi_project/models/*.receipt.json elapsed_seconds (stage 1 + 2 of every
14
+ representative, complete, same run signature as the export) + the export's total_target_seconds
15
+ Read on the host that holds each fold's records (server_1 or spark-0110).
16
+ The equal-pair-budget runs (n = 5..40, ImMicro and sepsis) are drawn on the "Pairs needed: composition, coverage, training steps" slide; quoted here.
17
+ Outputs: figures/sec09_same_pairs.{png,pdf}, data/sec09_same_pairs.csv, data/sec09_same_pairs_slide_text.json
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import os
22
+
23
+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
24
+
25
+ import json
26
+ import subprocess
27
+ import sys
28
+ from pathlib import Path
29
+
30
+ import numpy as np
31
+ import pandas as pd
32
+
33
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
34
+ "2026-09-30--paper-summary--r00")
35
+ sys.path.insert(0, str(DECK / "tools"))
36
+ import sec09_paired_validation as S9 # noqa: E402
37
+ import style # noqa: E402
38
+ import matplotlib.pyplot as plt # noqa: E402
39
+ from matplotlib.patches import Patch # noqa: E402
40
+
41
+ T = S9.T
42
+ ORDER, ROWNAME = S9.ORDER, S9.ROWNAME
43
+ FS, SUB, EDGE = S9.FS, S9.SUB, S9.EDGE
44
+ FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
45
+ OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
46
+ CV = "scsemi_cv_20261002"
47
+ BUDGET = "scsemi_budget_20261002"
48
+ ARMS = [("scsemi", "scSemiProfiler, same pairs", style.ARM["scsemi"]), ("lora", "LoRA, same pairs", style.ARM["lora"])]
49
+ # queue tag prefixes per cohort, tried in order; the sepsis fold-0 pilot queue used "sep"
50
+ # (logs/run_queue_ye2026_sepsis_fold0_pilot_20260927T154613.log: sep_f0_real_lora_raw)
51
+ TAG = {"immicro": ["imm"], "ye2026_sepsis": ["ye2", "sep"], "imperial_eskd": ["imp"], "giroux2022": ["gir"],
52
+ "ji2025_chili": ["ji2"]}
53
+
54
+ COLLECT = r'''
55
+ import glob, json, os, re, sys
56
+ T = sys.argv[1]; TAG = json.loads(sys.argv[2])
57
+ def jl(p):
58
+ try:
59
+ return json.load(open(p))
60
+ except Exception:
61
+ return None
62
+ st, en = {}, {}
63
+ for lg in sorted(glob.glob(os.path.join(T, "logs", "run_queue_*.log"))):
64
+ for line in open(lg, errors="replace"):
65
+ m = re.match(r"^(\S+) --- ([a-z0-9]+_f\d_real_lora_raw) seed=", line)
66
+ if m: st.setdefault(m.group(2), []).append(m.group(1))
67
+ m = re.match(r"^(\S+) ([a-z0-9]+_f\d_real_lora_raw) done:", line)
68
+ if m: en.setdefault(m.group(2), []).append(m.group(1))
69
+ out = {}
70
+ for ds, ps in TAG.items():
71
+ for k in range(5):
72
+ r = {}
73
+ run = jl(os.path.join(T, "runs", ds, f"fold{k}", "real_lora", "RUN.json"))
74
+ for p in ps:
75
+ tag = f"{p}_f{k}_real_lora_raw"
76
+ if run and len(st.get(tag, [])) >= 1 and len(en.get(tag, [])) >= 1:
77
+ r["lora"] = {"train_s": run["wall_seconds"], "start": st[tag][-1], "end": en[tag][-1], "tag": tag}
78
+ break
79
+ ex = jl(os.path.join(T, "generated", ds, f"fold{k}", "scsemi__raw.log"))
80
+ w = os.path.join(T, "scsemi", "work", ds, "cv", f"fold{k}")
81
+ asg = jl(os.path.join(w, "assignment.json"))
82
+ if ex and asg:
83
+ rec = [jl(f) for f in glob.glob(os.path.join(w, "scsemi_project", "models", "*.receipt.json"))]
84
+ rec = [x for x in rec if x and x.get("complete") and x.get("run_signature") == ex["run_signature"]]
85
+ r["scsemi"] = {"n_reps": len(asg["representative_indices"]), "n_rec": len(rec),
86
+ "pretrain_s": sum(x["elapsed_seconds"] for x in rec), "target_s": ex["total_target_seconds"],
87
+ "bulks": ex["bulks"]}
88
+ out[f"{ds}|{k}"] = r
89
+ print(json.dumps(out))
90
+ '''
91
+
92
+
93
+ def collect(host):
94
+ cmd = ["python3", "-", str(T), json.dumps(TAG)]
95
+ if host != "server_1":
96
+ cmd = ["ssh", "spark-0110"] + ["python3", "-", str(T), "'" + json.dumps(TAG) + "'"]
97
+ res = subprocess.run(cmd, input=COLLECT, capture_output=True, text=True, check=True)
98
+ return json.loads(res.stdout)
99
+
100
+
101
+ def load(p):
102
+ f = p / "summary.json"
103
+ return json.loads(f.read_text()) if f.exists() else None
104
+
105
+
106
+ def main() -> int:
107
+ got = {h: collect(h) for h in ("server_1", "server_2")}
108
+ vals, rows, done = {}, [], []
109
+ for ds in ORDER:
110
+ lo, sc = load(T / "scores" / ds / "pooled"), load(T / "scores" / ds / CV / "pooled")
111
+ if sc is None or "scsemi__raw" not in sc["arms"]:
112
+ continue
113
+ if set(lo["donors"]) != set(sc["donors"]) or lo["reference"]["reference_sha256"] != sc["reference"]["reference_sha256"]:
114
+ raise SystemExit(f"{ds}: LoRA and scSemiProfiler pooled calls differ in donors or reference")
115
+ hl, hs = dict(lo["headline"]["real_lora__raw"]), dict(sc["headline"]["scsemi__raw"])
116
+ if ds == "giroux2022":
117
+ nl, ns = load(T / "scores_nosex" / ds / "pooled"), load(T / "scores_nosex" / ds / CV / "pooled")
118
+ if ns is None:
119
+ hs["contrast_mean_cp10k_r_gen"] = np.nan
120
+ hs["deg_top50_sum"] = None
121
+ for h, n, a in ((hl, nl, "real_lora__raw"), (hs, ns, "scsemi__raw")):
122
+ if n is not None:
123
+ h["contrast_mean_cp10k_r_gen"] = n["headline"][a]["contrast_mean_cp10k_r_gen"]
124
+ h["deg_top50_sum"] = n["headline"][a].get("deg_top50_sum")
125
+ if hl.get("deg_top50_sum") is None: # older pooled LoRA scorings keep the DEG score in pooled_deg/
126
+ pd_ = load(T / ("scores_nosex" if ds == "giroux2022" else "scores") / ds / "pooled_deg")
127
+ if pd_ is not None and set(pd_["donors"]) == set(lo["donors"]) and "real_lora__raw" in pd_["headline"]:
128
+ hl["deg_top50_sum"] = pd_["headline"]["real_lora__raw"].get("deg_top50_sum")
129
+ t = {"lora": [], "scsemi": []}
130
+ for k in range(5):
131
+ for m in ("lora", "scsemi"):
132
+ rec = [g[f"{ds}|{k}"][m] for g in got.values() if m in g.get(f"{ds}|{k}", {})
133
+ and (m == "lora" or g[f"{ds}|{k}"][m]["n_rec"] == 2 * g[f"{ds}|{k}"][m]["n_reps"])]
134
+ if len(rec) != 1:
135
+ raise SystemExit(f"{ds} fold {k} {m}: {len(rec)} complete timing records across hosts")
136
+ r = rec[0]
137
+ if m == "lora":
138
+ gen = (pd.Timestamp(r["end"]) - pd.Timestamp(r["start"])).total_seconds()
139
+ t[m].append((r["train_s"] + gen) / 3600)
140
+ else:
141
+ t[m].append((r["pretrain_s"] + r["target_s"]) / 3600)
142
+ for m, h in (("lora", hl), ("scsemi", hs)):
143
+ vals[(ds, m)] = {"comp_l1": h["comp_l1"], "coverage": h["coverage"], "precision": h["precision"],
144
+ "logfc_r": h.get("contrast_mean_cp10k_r_gen", np.nan), "deg": h.get("deg_top50_sum"),
145
+ "hours": float(np.mean(t[m])), "hours_min": min(t[m]), "hours_max": max(t[m])}
146
+ rows.append({"dataset": ds, "arm": m, **vals[(ds, m)], "n_scored": lo["n_donors"],
147
+ "source": str(T / "scores" / ds / (CV + "/pooled" if m == "scsemi" else "pooled") / "summary.json")})
148
+ done.append(ds)
149
+ if not done:
150
+ raise SystemExit("no cohort has a scored scSemiProfiler 5-fold CV yet")
151
+ # equal pair budget (quoted only)
152
+ bud = []
153
+ for ds in ORDER:
154
+ sb, lo = load(T / "scores" / ds / BUDGET / "pooled"), load(T / "scores" / ds / "pooled")
155
+ if sb is None:
156
+ continue
157
+ for n in (5, 10, 20, 40):
158
+ a, b = f"scsemi_n{n}__raw", f"lora_n{n}__raw"
159
+ if a in sb["arms"] and b in lo["arms"]:
160
+ bud.append({"dataset": ds, "n": n, "scsemi_l1": sb["headline"][a]["comp_l1"],
161
+ "lora_l1": lo["headline"][b]["comp_l1"], "scsemi_cov": sb["headline"][a]["coverage"],
162
+ "lora_cov": lo["headline"][b]["coverage"]})
163
+ bud = pd.DataFrame(bud)
164
+
165
+ panels = [("comp_l1", "Composition L1 ↓", None), ("coverage", "Coverage ↑", (0, 1)),
166
+ ("logfc_r", "Disease logFC r ↑", (0, 1)), ("hours", "GPU hours per fold", None)]
167
+ fig, axes = plt.subplots(1, 4, figsize=(12.3, 4.2), gridspec_kw={"wspace": 0.12})
168
+ h = 0.36
169
+ y = np.arange(len(ORDER)) * 1.0
170
+ for ax, (mk, lab, lim) in zip(axes, panels):
171
+ for i, ds in enumerate(ORDER):
172
+ if ds == "immicro" and mk == "logfc_r" and ds in done:
173
+ ax.text(0.03, y[i], "healthy cohort: no contrast", transform=ax.get_yaxis_transform(), va="center",
174
+ fontsize=FS - 4, color=SUB)
175
+ continue
176
+ if ds not in done:
177
+ ax.text(0.03, y[i], "in progress", transform=ax.get_yaxis_transform(), va="center", fontsize=FS - 4,
178
+ color=SUB)
179
+ continue
180
+ for k, (m, _l, col) in enumerate(ARMS):
181
+ v = vals[(ds, m)][mk]
182
+ yy = y[i] + (k - 0.5) * h
183
+ if v is None or np.isnan(v):
184
+ ax.text(0.03, yy, "no contrast" if ds == "immicro" else "n/a", transform=ax.get_yaxis_transform(),
185
+ va="center", fontsize=FS - 5, color=SUB)
186
+ continue
187
+ ax.barh(yy, v, h * 0.9, color=col, edgecolor="none")
188
+ if mk == "hours":
189
+ vv = vals[(ds, m)]
190
+ s = (f"{vv['hours_min'] * 60:.0f}–{vv['hours_max'] * 60:.0f} min" if m == "lora"
191
+ else f"{vv['hours_min']:.1f}–{vv['hours_max']:.1f} h")
192
+ else:
193
+ s = f"{v:.2f}"
194
+ ax.text(v * (1.12 if mk == "hours" else 1.0) + (0 if mk == "hours" else 0.015), yy, s, va="center",
195
+ fontsize=FS - 5, color=SUB)
196
+ ax.set_title(lab, fontsize=FS - 1)
197
+ ax.set_yticks(y, [ROWNAME[d] for d in ORDER] if ax is axes[0] else [""] * len(ORDER), fontsize=FS - 3)
198
+ ax.set_ylim(len(ORDER) - 0.5, -0.5)
199
+ ax.tick_params(axis="y", length=0)
200
+ ax.tick_params(axis="x", labelsize=FS - 4)
201
+ if lim:
202
+ ax.set_xlim(*lim)
203
+ if mk == "comp_l1":
204
+ ax.set_xlim(0, 0.75)
205
+ if mk == "hours":
206
+ ax.set_xscale("log")
207
+ ax.set_xlim(0.03, 40)
208
+ ax.set_xticks([0.1, 1, 10], ["0.1", "1", "10"])
209
+ ax.minorticks_off()
210
+ ax.grid(axis="x", color="#E3E3E3", linewidth=0.8)
211
+ ax.set_axisbelow(True)
212
+ fig.legend(handles=[Patch(color=c, label=l) for _, l, c in ARMS], loc="lower center", ncol=2,
213
+ bbox_to_anchor=(0.5, -0.08), fontsize=FS - 2)
214
+ style.save(fig, "sec09_same_pairs", FIGDIR)
215
+ OUTDATA.mkdir(exist_ok=True)
216
+ pd.DataFrame(rows).to_csv(OUTDATA / "sec09_same_pairs.csv", index=False, float_format="%.6g")
217
+ if len(bud):
218
+ bud.to_csv(OUTDATA / "sec09_same_pairs_budget.csv", index=False, float_format="%.6g")
219
+
220
+ metrics = {"comp_l1": "composition", "coverage": "coverage", "precision": "precision", "logfc_r": "logFC r"}
221
+ valid = {k: [d for d in done if not np.isnan(vals[(d, 'lora')][k]) and not np.isnan(vals[(d, 'scsemi')][k])]
222
+ for k in metrics}
223
+ ahead = lambda d, k: (vals[(d, 'lora')][k] < vals[(d, 'scsemi')][k]) if k == "comp_l1" \
224
+ else (vals[(d, 'lora')][k] > vals[(d, 'scsemi')][k]) # noqa: E731
225
+ lw = {k: sum(ahead(d, k) for d in valid[k]) for k in metrics}
226
+ behind = {k: [S9.NAME[d] for d in valid[k] if not ahead(d, k)] for k in metrics}
227
+ ratio = [vals[(d, "scsemi")]["hours"] / vals[(d, "lora")]["hours"] for d in done]
228
+ allwin = [k for k in metrics if valid[k] and lw[k] == len(valid[k])]
229
+ rest = [k for k in metrics if valid[k] and k not in allwin]
230
+ gpu_kw = f"{min(ratio):.0f}–{max(ratio):.0f}× less GPU time per fold"
231
+ if not rest:
232
+ kw = ["Same pairs: LoRA ahead on every metric",
233
+ f"Coverage {vals[(done[0], 'lora')]['coverage']:.2f} vs {vals[(done[0], 'scsemi')]['coverage']:.2f} "
234
+ f"({S9.NAME[done[0]]})", gpu_kw]
235
+ else:
236
+ kw = ["LoRA ahead in " + ", ".join(f"{metrics[k]} {lw[k]}/{len(valid[k])}" for k in rest), gpu_kw]
237
+ if allwin:
238
+ dens = {len(valid[k]) for k in allwin}
239
+ kw.insert(0, ", ".join(metrics[k] for k in allwin).capitalize() + ": LoRA ahead"
240
+ + (f" in {dens.pop()}/{len(valid[allwin[0]])}" if len(dens) == 1 else " in all"))
241
+ for k in kw:
242
+ if len(k) > 45:
243
+ raise SystemExit(f"keyword too long: {k}")
244
+ numbers = [{"value": f"{S9.NAME[d]}: L1 LoRA {vals[(d, 'lora')]['comp_l1']:.3f} / scSemi {vals[(d, 'scsemi')]['comp_l1']:.3f}; "
245
+ f"coverage {vals[(d, 'lora')]['coverage']:.3f} / {vals[(d, 'scsemi')]['coverage']:.3f}; precision "
246
+ f"{vals[(d, 'lora')]['precision']:.3f} / {vals[(d, 'scsemi')]['precision']:.3f}; logFC r "
247
+ f"{vals[(d, 'lora')]['logfc_r']:.3f} / {vals[(d, 'scsemi')]['logfc_r']:.3f}; top-50 DEG "
248
+ f"{vals[(d, 'lora')]['deg']} / {vals[(d, 'scsemi')]['deg']}; GPU per fold LoRA "
249
+ f"{vals[(d, 'lora')]['hours'] * 60:.1f} min / scSemi {vals[(d, 'scsemi')]['hours']:.2f} h",
250
+ "source": "data/sec09_same_pairs.csv"} for d in done]
251
+ btxt = ""
252
+ if len(bud):
253
+ for d, g in bud.groupby("dataset"):
254
+ btxt += (f" Equal pair budget, {S9.NAME[d]} (n = 5, 10, 20, 40 pairs): scSemiProfiler L1 "
255
+ f"{g.scsemi_l1.min():.3f}–{g.scsemi_l1.max():.3f} and coverage {g.scsemi_cov.min():.2f}–"
256
+ f"{g.scsemi_cov.max():.2f} at every n; LoRA L1 {g.lora_l1.min():.3f}–{g.lora_l1.max():.3f}, coverage "
257
+ f"{g.lora_cov.min():.2f}–{g.lora_cov.max():.2f} (drawn on the 'Pairs needed: composition, coverage, training steps' slide).")
258
+ numbers.append({"value": btxt.strip(), "source": "data/sec09_same_pairs_budget.csv"})
259
+ pending = [S9.NAME[d] for d in ORDER if d not in done]
260
+ full = ("5-fold CV: for every fold, scSemiProfiler's representatives are exactly LoRA's training + inner-val pairs "
261
+ "(the other four folds; checked per fold), test = the fold's samples from their real bulk only. Pooled = one "
262
+ "scoring call per method over every usable sample, same donors and reference (sha-checked). scSemiProfiler = "
263
+ "upstream c2aea02, default settings, official output. GPU time per fold on one GB10: LoRA = fine-tune + "
264
+ "sampling 1,500 cells per test sample; scSemiProfiler = pretraining of every representative + one model per "
265
+ "test sample (receipts); data preparation and scoring not counted on either side. "
266
+ + "".join(f"scSemiProfiler ahead on {metrics[k]}: {', '.join(behind[k])}. " for k in metrics if behind[k])
267
+ + ("Still running (server_1 / server_2): " + ", ".join(pending) + "." if pending else "")
268
+ + btxt + " Source: plans/paired_finetune_intradataset_20260927/scores/<cohort>/{pooled,scsemi_cv_20261002/pooled}/ "
269
+ "and scsemi/analysis/cv_budget_20261005/.")
270
+ txt = {"title": "Same training pairs: LoRA vs scSemiProfiler", "layout": "full",
271
+ "figures": [str(FIGDIR / "sec09_same_pairs.png")], "keywords": kw,
272
+ "footnote_short": ("5-fold CV; scSemiProfiler representatives = LoRA's training pairs. "
273
+ + (f"{', '.join(pending)}: running." if pending else "")),
274
+ "footnote": full, "numbers": numbers}
275
+ if len(txt["footnote_short"]) > 110:
276
+ raise SystemExit("short footnote too long")
277
+ out = {"section": "09-same-pairs", "scripts": [str(Path(__file__).resolve())],
278
+ "generated_from": "tools/sec09_same_pairs.py (rerun to refresh; do not edit by hand)", "slides": [txt]}
279
+ (OUTDATA / "sec09_same_pairs_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))
280
+ print("\n".join(kw))
281
+ for n in numbers:
282
+ print(n["value"])
283
+ return 0
284
+
285
+
286
+ if __name__ == "__main__":
287
+ sys.exit(main())