junidude14 commited on
Commit
836e2f8
·
verified ·
1 Parent(s): 3d7da7f

Archive 4 checkpoints (1-4)

Browse files
.gitattributes CHANGED
@@ -92,3 +92,5 @@ paper-releases/pbisc-diffusion/updates/20261005T175437Z-deck-supplementary-other
92
  paper-releases/pbisc-diffusion/updates/20261006T121425Z-fig1-architecture-plus-corpus/diffusion/dataset/server_1/manuscript/main.pdf filter=lfs diff=lfs merge=lfs -text
93
  paper-releases/pbisc-diffusion/updates/20261006T125143Z-supp-fig-s1-corpus/diffusion/dataset/server_1/manuscript/main.pdf filter=lfs diff=lfs merge=lfs -text
94
  paper-releases/pbisc-diffusion/updates/20261006T125143Z-supp-fig-s1-corpus/diffusion/dataset/server_1/manuscript/supplementary.pdf filter=lfs diff=lfs merge=lfs -text
 
 
 
92
  paper-releases/pbisc-diffusion/updates/20261006T121425Z-fig1-architecture-plus-corpus/diffusion/dataset/server_1/manuscript/main.pdf filter=lfs diff=lfs merge=lfs -text
93
  paper-releases/pbisc-diffusion/updates/20261006T125143Z-supp-fig-s1-corpus/diffusion/dataset/server_1/manuscript/main.pdf filter=lfs diff=lfs merge=lfs -text
94
  paper-releases/pbisc-diffusion/updates/20261006T125143Z-supp-fig-s1-corpus/diffusion/dataset/server_1/manuscript/supplementary.pdf filter=lfs diff=lfs merge=lfs -text
95
+ paper-releases/pbisc-diffusion/updates/20261006T145850Z-deck-six-figure-order/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pdf filter=lfs diff=lfs merge=lfs -text
96
+ paper-releases/pbisc-diffusion/updates/20261006T145850Z-deck-six-figure-order/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pptx filter=lfs diff=lfs merge=lfs -text
paper-releases/pbisc-diffusion/updates/20261006T145850Z-deck-six-figure-order/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c990d1b7a4562b53e03591cd9ea52276789289a7e61cb5ae0a622f995eddb263
3
+ size 8740044
paper-releases/pbisc-diffusion/updates/20261006T145850Z-deck-six-figure-order/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pptx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:99ed7675ef69913f55b9bad7c0d78457fddd8b4b17ba505424df21a5bc6ea119
3
+ size 9798501
paper-releases/pbisc-diffusion/updates/20261006T145850Z-deck-six-figure-order/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/README.md ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PBISC-Diffusion paper summary deck (2026-09-30, r00; ordered by the six manuscript figures since 2026-10-06)
2
+
3
+ 60-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.
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, Decide);
10
+ - the existing slides that serve its panels, each labelled "Fig. 2c" etc. in the top-right corner.
11
+ - The Supplementary block (from-scratch results) and the Appendix block (modified scSemiProfiler run), unchanged.
12
+
13
+ Only order, section labels, the agenda and two new content slides changed. The new slides are "Overview draft
14
+ (Nature style)", the manuscript's candidate Fig. 1, and "Pretraining corpus", the Fig. 1d strip. No new result figures
15
+ were made. The plan lives in `data/figure_plan.json`. `tools/figure_plan.py` draws the plan tables and the slide text,
16
+ and checks that every slide is placed exactly once. `tools/restructure_figure_order_20261006.py` made the order (it
17
+ refuses to run twice). The earlier section order (10 sections, 45 slides) is in
18
+ `_archive/2026-10-06_before_figure_order/`.
19
+
20
+ Short keyword lines only; the figures carry the results. Every slide that uses a published method, metric or
21
+ baseline has a one-line "References:" footer; full citations are in the speaker notes.
22
+
23
+ - `PBISC-Diffusion_paper_summary_20260930.pptx`: the deck
24
+ - `PBISC-Diffusion_paper_summary_20260930.pdf`: LibreOffice PDF of the deck
25
+ - `data/slides_spec.json`: slide order, titles, keywords, footnotes, references, speaker-note text
26
+ - `generate_deck.py`: builds the pptx from `data/slides_spec.json` only (python-pptx)
27
+ - `figures/`: exactly the figures the slides show (PNG + PDF), made by `tools/sec*.py`. Intermediate panels go to a
28
+ temporary folder; superseded figures are deleted, not kept (2026-10-02, user request; every deleted file was
29
+ checked to be in the paper archive by sha256 first).
30
+ - `data/sec*.csv` and `data/*_slide_text.json`: every plotted or quoted number with its source path
31
+ - `render/`: PDF and 70-dpi slide JPGs for checking
32
+
33
+ ## Slide order
34
+
35
+ | section | slides |
36
+ |---|---|
37
+ | 1 Model overview | bulk in, cells out; denoiser |
38
+ | 2 Backbone | SDD → PBISC-Diffusion; bulk conditioning |
39
+ | 3 Architecture ablation | width & context (loss, benchmark); gene panel |
40
+ | 4 Metrics + SLE benchmark | **how we score generated cells** (metric table with references); SLE benchmark; per cell type; bulk broadcast baseline |
41
+ | 5 Real bulk vs pseudobulk | input shift; same shift in three cohorts; cells off-manifold; disease direction flips |
42
+ | 6 Paired fine-tuning | method; evaluation design |
43
+ | 7 LoRA ablations | full vs LoRA vs cond.-encoder-only; LoRA rank r = 4 / 16 / 64; K diversification |
44
+ | 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) |
45
+ | 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 |
46
+ | 10 Next steps | paired-subset cohorts (planned); other tissues from a few dozen pairs (Discussion framing of the from-scratch results) |
47
+ | Supplementary | no pretraining: same cohort, from scratch (pilot); no pretraining: other cohorts, from scratch (pilot); rare states: from scratch vs pretrained |
48
+ | Appendix | scSemiProfiler without its output threshold (sensitivity; modified read-out, not the official output) |
49
+
50
+ ## Rebuild
51
+
52
+ Everything is CPU only; no GPU or checkpoint is touched.
53
+
54
+ ```bash
55
+ # prerequisites (plan folder plans/paired_finetune_intradataset_20260927/, CPU):
56
+ # scsemi/tools/representative_dependence.py -> scsemi/analysis/representative_dependence_20261002/
57
+ # tools/contrast_extra.py (+ tools/contrast_extra_tables.py) -> scores_contrast/ (Spearman, ceiling, limma, CAT, RBO)
58
+ # tools/build_tpm_zeroshot.py + tools/score_tpm_zeroshot.sh -> scores/<ds>/zeroshot_tpm_20261002/pooled/
59
+ # (the length-corrected zero-shot arm needs one GPU sampling step: tools/sample_lockwait.sh, coordinator only)
60
+ cd /home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00
61
+ # shared helpers, not run directly: style.py, sec03_common.py, scsemi_results.py, fold_sizes.py
62
+ for f in sec01_overview sec02_backbone sec03_width_loss sec03_width_bench sec03_panel \
63
+ sec04_metrics_overview sec04_sle_benchmark sec05_condition_space sec05_cells_offmanifold \
64
+ sec05_behcet_direction sec05_shift_cohorts sec06_finetune_method sec07_ft_modes \
65
+ sec07_k_aug sec07_rank_sweep sec08_pairs_needed sec08_cross_cohort sec09_paired_validation sec09_extra_metrics \
66
+ sec09_time_to_apply sec09_scsemi_representative sec09_cat_curves sec10_paired_subset_cohorts \
67
+ secA_scsemi_readout sec07_no_pretraining sec08_cross_scratch sec09_same_pairs \
68
+ secS_scratch_rare_states sec10_other_tissues figure_plan; do # keep this order (sec10 reads secS; figure_plan last)
69
+ python3 "tools/$f.py" || break
70
+ done
71
+ python3 tools/sync_sec09_text.py # copy every generated slide text (sec09_index / text_source) into the spec
72
+ python3 generate_deck.py # -> PBISC-Diffusion_paper_summary_20260930.pptx
73
+ soffice --headless --convert-to pdf --outdir render PBISC-Diffusion_paper_summary_20260930.pptx
74
+ pdftoppm -jpeg -r 70 render/PBISC-Diffusion_paper_summary_20260930.pdf render/slide
75
+ cp render/PBISC-Diffusion_paper_summary_20260930.pdf .
76
+ ```
77
+
78
+ `generate_deck.py` stops with an error if a figure is missing, a title does not fit on one line, a footnote needs
79
+ more than 2 lines (1 line when the slide has references), the reference line needs more than 1 line, or any text
80
+ contains Korean or placeholder words. `tools/restructure_20261002.py` is the one-off script that produced the current
81
+ slide order and the references (it refuses to run twice).
82
+
83
+ ## Notes
84
+
85
+ - **No "all" label (2026-10-02).** The 5-fold arm trains each fold model on the other four folds minus 7–8
86
+ inner-validation donors; its test fold is never trained on (RUN.json `test_rows_never_loaded_for_training`). Figures
87
+ label it "5-fold CV (other 4 folds)" and learning-curve ticks show the training-pair count per fold (78–79 ImMicro,
88
+ 58–59 sepsis), read by `tools/fold_sizes.py`.
89
+ - **Learning curve x = 0 uses no pairs (2026-10-02).** It shows the zero-shot model fed the real bulk as measured
90
+ and after exon-length correction (counts / Ensembl union-exon kb, then the same fixed-depth arithmetic;
91
+ `plans/.../tools/build_tpm_zeroshot.py`, scored in `scores/<ds>/zeroshot_tpm_20261002/pooled`). The old x = 0
92
+ calibration point, whose alpha used every training pair of the fold, is gone; calibration appears only fitted on the
93
+ same n pairs as the LoRA point (squares; `cal_budget_20261001`).
94
+ - **Disease metrics (2026-10-02).** Next to Pearson logFC r and the Welch top-50 DEG overlap: Spearman r, the
95
+ split-half ceiling (observed vs observed, Spearman–Brown), limma-voom top-50 DEG, each arm's chance overlap, and
96
+ CAT curves with the k / 2G chance line (`plans/.../scores_contrast/`, tools/contrast_extra.py; every Pearson r and
97
+ Welch count reproduced exactly). Repeated samples of one patient (Imperial, Giroux, Ji) count as separate samples in
98
+ both DE tests, as in the scorer (footnote).
99
+ - Section 9 text is generated: `tools/sec09_paired_validation.py`, `sec09_extra_metrics.py`, `sec07_rank_sweep.py`,
100
+ `sec09_time_to_apply.py`, `sec09_scsemi_representative.py`, `sec09_cat_curves.py` write slide text JSON; sync copies
101
+ it. Hand-written: the keywords of the two "Pairs needed" slides (section 8) and of every slide in sections 1–7 and 10.
102
+ - Giroux's disease metrics exclude 196 sex-linked genes (severity is confounded with sex), from
103
+ `plans/.../scores_nosex/`. The calibration comparator is "Zero-shot + calibration" (user decision 2026-10-01).
104
+ - Story rule (user decision 2026-09-30): no PBISC-VAE and no reference calibration (refcal). The exon-length-corrected
105
+ input is used only as the no-pair x = 0 point of the learning curve (user decision 2026-10-02).
106
+ `tools/sec04_immicro.py` (refcal vs scSemiProfiler on ImMicro) is kept but is not part of the deck or the rebuild.
107
+ - scSemiProfiler 5-fold and equal-budget results are picked up automatically when they appear (`tools/scsemi_results.py`;
108
+ arm `scsemi__raw` in `scores/<cohort>/scsemi_cv_20261002/pooled*/`, `scsemi_n{5,10,20,40}__raw` in
109
+ `scores/<cohort>/scsemi_budget_20261002/pooled*/`; same donors and reference cells as the main pooled call only).
110
+ Then rerun sections 8 and 9, sync, recheck the section 8 keywords and rebuild.
111
+ - Earlier versions: `_archive/2026-09-30_before_no_vae_refcal/`, `_archive/2026-10-01_before_extra_metrics/`,
112
+ `_archive/2026-10-02_before_time_to_apply/`, `_archive/2026-10-02_before_restructure/` (pptx, PDF, spec; their
113
+ figures are in the paper archive). `DRAFT_1150_*`: the copy shown at the 2026-09-30 12:00 meeting.
114
+
115
+ - Added 2026-10-03 (user decision: the cross-cohort experiment is reported at K = 1000 only and is the figure that explains
116
+ why PBISC fits LoRA on a few pairs of each cohort): slides 25-26 in section 8, `tools/sec08_cross_cohort.py`.
117
+ - Slide 25 "Pairs from other cohorts do not transfer": per held-out cohort, composition L1 / coverage / disease logFC r of
118
+ zero-shot, calibration fitted on the other cohorts, LoRA r16 / r64 / full fine-tune trained on the other cohorts
119
+ (+ Liu 2021) at step saturation, and LoRA on the cohort's own pairs (5-fold pooled).
120
+ - Slide 26 "Longer training on other cohorts" (": gap stays" since 2026-10-06): the same metrics at every 20k-step
121
+ milestone.
122
+ - Source plan: `plans/paired_crosscohort_20261002/` (README; same-reference and same-sample checks in the script).
123
+ Agenda item 8 now reads "How many pairs, and do other cohorts' pairs transfer". The deck has 37 slides.
124
+ Pre-update copy: `_archive/2026-10-03_before_cross_cohort/`.
125
+
126
+ ## Sources
127
+
128
+ Final model: `runs/f01_6k_1x_seed20260627` (epoch 16, EMA). Scores and receipts come from
129
+ `plans/utility_studies_final6k_20260925/`, `plans/paired_finetune_intradataset_20260927/`,
130
+ `plans/immicro_scsemi_comparison_20260927/`, `plans/floor01_campaign_20260923/`,
131
+ `analysis/scsemi_benchmark_diffusion_20260913/` and the run folders named in each `data/sec*.csv`. Reference PDFs:
132
+ `/home/sj_server_1/PBISC/paper-release-20260928/reference-papers/` (INDEX.md). Manuscript:
133
+ `/home/sj_server_1/PBISC/paper-release-20260928/manuscript/`.
134
+ - 2026-10-04 appendix (user decision: supplementary, appendix only, because it changes scSemiProfiler's official
135
+ output). Slide 38 is the divider "Appendix" and slide 39 is "Appendix: scSemiProfiler without output threshold"
136
+ (`tools/secA_scsemi_readout.py`, `data/secA_scsemi_readout{.csv,_slide_text.json}`).
137
+ - Inputs: `plans/paired_finetune_intradataset_20260927/scsemi/analysis/output_variants_20261003/`. The script checks
138
+ that its LoRA-5 and official scSemiProfiler values equal the section 9 slide data draw by draw.
139
+ - Result: without upstream's output threshold, scSemiProfiler's coverage rises in 5/5 cohorts, and 23/23 LoRA-5
140
+ comparisons (coverage, precision, composition, logFC r, DEG) keep their winner.
141
+ - The outline keeps its 10 sections (the builder requires 10). The pre-change copy is in
142
+ `_archive/2026-10-04_before_appendix/`. The deck has 39 slides.
143
+ - 2026-10-05 update (user request: put the results so far into the deck). Pre-change copy: `_archive/2026-10-05_before_scratch_cv/`.
144
+ - New slide 23, "No pretraining: same cohort, from scratch" (`tools/sec07_no_pretraining.py`). Pilot on sepsis fold 0
145
+ (17 donors). Reads `fold0_scratch_20261005/` and the runs' RUN.json. The donor composition r is recomputed from
146
+ per_donor.csv and reproduces ablation_extra_donor.csv.
147
+ - New slide 28, "No pretraining: other cohorts, from scratch" (`tools/sec08_cross_scratch.py`). Held-out sepsis pilot.
148
+ Every arm is read from `paired_crosscohort_20261002/scores_masked/`: genes no training cohort measured are zeroed
149
+ in all arms, because the unmasked scratch arm puts 91–94 % of its UMI there (read from the generated_masked logs
150
+ since 2026-10-06).
151
+ - New slide 38, "Same training pairs: LoRA vs scSemiProfiler" (`tools/sec09_same_pairs.py`). scSemiProfiler 5-fold
152
+ CV with LoRA's own training pairs, plus GPU hours per fold from the receipts on either host. Cohorts that are still
153
+ running show "in progress"; rerun the script as they finish.
154
+ - These two slides now draw the scSemiProfiler CV / budget runs automatically:
155
+ - Slide 24, "Pairs needed" (diamonds; ImMicro so far): keyword 2 reworded, footnote extended.
156
+ - Slide 37, "5-fold CV" (yellow bar; ImMicro and Ji so far).
157
+ - `tools/sec09_paired_validation.py` reads the scSemiProfiler CV arm's Spearman / limma values from
158
+ `scores_contrast/<cohort>/scsemi_cv_20261002/pooled/` (contrast_extra.py --design scored). Pearson r and the Welch
159
+ DEG must match the scorer; the values stay blank until computed. Cohorts not yet run say "in progress".
160
+ - Agenda item 7 now reads "LoRA: compute, rank, K; training from scratch". The deck has 42 slides.
161
+ - New helper: `tools/grouped_bars.py`.
162
+ - 2026-10-06 update (user request: check that the cross-cohort LoRA / full FT, cross-cohort from-scratch and
163
+ same-cohort from-scratch (+ recipes) results, with benchmarks and training times, and the scratch-vs-pretrained rare
164
+ states are in the deck; user decision: the from-scratch results go to the paper's Supplementary and the Discussion
165
+ presents them as a route to other tissues). Pre-change copy: `_archive/2026-10-06_before_supplementary/`.
166
+ - **Supplementary block (new divider, slides 40-43).**
167
+ - "No pretraining: same cohort, from scratch" and "No pretraining: other cohorts, from scratch" moved here from
168
+ sections 7 and 8. Their content is unchanged; slide 42's notes now name the cross-cohort slides by title.
169
+ - New "Rare states: from scratch vs pretrained" (`tools/secS_scratch_rare_states.py`).
170
+ - It reads the rare-state screen (`plans/rare_states_screen_20261004/out/sepsis_fold0_*` and
171
+ `sepsis_loco_masked_*`).
172
+ - The cross-cohort arms use the masked scoring (46 never-measured genes zeroed in every arm).
173
+ - The donor bootstrap reproduces the verified analysis in `out/scratch_vs_lora_20261005/REPORT.md`.
174
+ - **Section 10 "Next steps".**
175
+ - New "Next: other tissues from a few dozen pairs" (`tools/sec10_other_tissues.py`): a comparison table, pretrained
176
+ + LoRA vs from scratch.
177
+ - Every value is read from the deck's own source tables. The say text is the user's Discussion framing.
178
+ - **Slide 26 "Longer training on other cohorts".** The first keyword is now training minutes to saturation (RUN.json
179
+ wall seconds), with per-cohort minutes and steps in the notes (`tools/sec08_cross_cohort.py`).
180
+ - **Slide 34 "5 donors: time to apply".**
181
+ - The pretraining hours are read from `data/sec06_ft_method.csv`, no longer hard-coded.
182
+ - The note names the 'Fine-tuning with paired bulk + sc' slide by title. Its old "slide 15" pointed at the wrong
183
+ slide.
184
+ - Agenda items 7 and 10 updated. Spec change: `tools/restructure_20261006.py` (refuses to run twice). The deck has 45
185
+ slides; no Korean text.
186
+ - **Review pass (same day).** An independent 5-agent review of the changed slides confirmed 39 issues; all are
187
+ fixed. Pre-review copies of the touched scripts and the spec: `_archive/2026-10-06_before_supplementary/*.pre_review`.
188
+ - Slide 39: pretraining now reads 33.1 M train cells (`train_split_cells`; the 41.4 M corpus includes val/test).
189
+ The rare-state row follows the bootstrap verdicts on both sides (closer on ISG-high T / on DN2 B; labels and
190
+ states both arms miss by > 4-fold are not counted). "No corpus" became "come close": the scratch runs still took
191
+ the panel, value scaler and z-score constants from the PBMC checkpoint (RUN.json `kept_from_checkpoint`, now in
192
+ the notes). The say text carries the one-fold pilot qualifier; the footnote names both pilots.
193
+ - Slide 43: "no significant difference on average" (not "no difference"). Keyword 2 is the cycling T/NK count
194
+ (8 of 8 comparisons). The notes add the ISG-high T split by panel, the scratch-closer states (DN2 B, MS1), the
195
+ 52-call tally, the fold-0 caveat (fold 0 is the own-pair LoRA's best fold for C1Q-high and cycling T/NK,
196
+ computed from `folds.csv`), label states unthinned, and "8 of 13 states shown".
197
+ - Slide 26: title "...: gap stays" and "drifts in Sepsis and Ji" are computed from the milestones (gap = no milestone
198
+ reaches the own-cohort coverage; drift = full fine-tune L1 up by >= 0.05). Minutes are in
199
+ `data/sec08_cross_cohort.csv` (wall_seconds, minutes, run_receipt) and in the numbers list.
200
+ - Slide 42: UMI share (94 %, 91–94 % across milestones), the observed share (0.014 %, from `cells_panel6k.npz`)
201
+ and both arms' stopping settings are read from the receipts; the "none" label sits inside the axes.
202
+ - 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
203
+ notes. The right panel shares the bars' rows and has a title.
204
+ - Talk text and pointers: slides 23, 25, 26, 45 (say), 22 (recipes description), 32 and 36 (slide pointers by
205
+ title), slide 1 subtitle "updated 2026-10-06".
paper-releases/pbisc-diffusion/updates/20261006T145850Z-deck-six-figure-order/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/generate_deck.py ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build the PBISC-Diffusion paper-summary deck.
3
+
4
+ Reads data/slides_spec.json only and writes
5
+ PBISC-Diffusion_paper_summary_20260930.pptx next to this script.
6
+ Rerunnable; CPU only.
7
+
8
+ Design rules (user request: plain, clean, no decoration):
9
+ 16:9 13.333 x 7.5 in, white background, Arial only.
10
+ Text #1A1A1A, footnotes / labels #6E6E6E. Colour only inside figures.
11
+ Title 26 pt bold at (0.45, 0.30); section label 11 pt grey, top right.
12
+ Figures fill x 0.45-12.9, y 1.05-6.75, aspect kept, never cropped.
13
+ Keywords 16 pt, max 3 lines of content, beside or below the figure.
14
+ Footnote 9 pt grey from y 7.0, at most 2 lines; slide number bottom right.
15
+ With 'refs' (short citations) the footer is one footnote line plus one 'References:' line;
16
+ 'refs_full' (full citations with DOI) goes to the speaker notes.
17
+
18
+ The script measures text with the Arial TrueType metrics and fails loudly
19
+ if a title, keyword block or footnote would not fit.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import re
25
+ import sys
26
+ from pathlib import Path
27
+
28
+ from PIL import Image, ImageFont
29
+ from pptx import Presentation
30
+ from pptx.dml.color import RGBColor
31
+ from pptx.enum.text import MSO_ANCHOR, PP_ALIGN
32
+ from pptx.util import Emu, Inches, Pt
33
+
34
+ DECK = Path(__file__).resolve().parent
35
+ SPEC = DECK / "data" / "slides_spec.json"
36
+
37
+ # ---------------------------------------------------------------- geometry
38
+ SLIDE_W, SLIDE_H = 13.333, 7.5
39
+ X0, X1 = 0.45, 12.9 # content left / right
40
+ Y0, YFIG1 = 1.05, 6.75 # figure top / bottom limit
41
+ KW_BOTTOM = 6.85 # keywords below a figure must end here
42
+ FOOT_Y = 7.0 # footnote top
43
+ FOOT_W = 11.6 # leaves room for the slide number
44
+ GAP_BELOW = 0.20 # figure -> keywords (below)
45
+ GAP_RIGHT = 0.35 # figure -> keyword column (right)
46
+ MIN_COL = 2.9 # narrowest keyword column
47
+ FIG_GAP = 0.25 # between two figures
48
+
49
+ INK = RGBColor(0x1A, 0x1A, 0x1A)
50
+ GREY = RGBColor(0x6E, 0x6E, 0x6E)
51
+ WHITE = RGBColor(0xFF, 0xFF, 0xFF)
52
+ FONT = "Arial"
53
+
54
+ TITLE_PT, LABEL_PT, KW_PT, FOOT_PT, NUM_PT = 26, 11, 16, 9, 9
55
+ AGENDA_PT, COVER_PT, COVER_SUB_PT = 18, 36, 18
56
+ LINE = 1.2 # line height / font size used for layout
57
+ KW_PARA_GAP_PT = 6
58
+
59
+ _FONT_FILES = {
60
+ False: "/usr/share/fonts/truetype/msttcorefonts/Arial.ttf",
61
+ True: "/usr/share/fonts/truetype/msttcorefonts/arialbd.ttf",
62
+ }
63
+ _font_cache: dict = {}
64
+
65
+ HANGUL = re.compile("[ᄀ-ᇿ㄰-㆏가-힣]")
66
+
67
+
68
+ def text_w_in(text: str, pt: float, bold: bool = False) -> float:
69
+ """Rendered width of one line in inches (Arial metrics)."""
70
+ key = bold
71
+ if key not in _font_cache:
72
+ _font_cache[key] = ImageFont.truetype(_FONT_FILES[bold], 1000)
73
+ return _font_cache[key].getlength(text) * pt / 1000.0 / 72.0
74
+
75
+
76
+ def wrap(text: str, pt: float, width_in: float, bold: bool = False) -> list[str]:
77
+ words, lines, cur = text.split(" "), [], ""
78
+ for w in words:
79
+ trial = w if not cur else cur + " " + w
80
+ if text_w_in(trial, pt, bold) <= width_in:
81
+ cur = trial
82
+ else:
83
+ if cur:
84
+ lines.append(cur)
85
+ cur = w
86
+ if cur:
87
+ lines.append(cur)
88
+ return lines
89
+
90
+
91
+ def line_h(pt: float) -> float:
92
+ return pt * LINE / 72.0
93
+
94
+
95
+ def kw_block_h(keywords: list[str], width_in: float) -> float:
96
+ n_lines = sum(len(wrap(k, KW_PT, width_in)) for k in keywords)
97
+ return n_lines * line_h(KW_PT) + (len(keywords) - 1) * KW_PARA_GAP_PT / 72.0
98
+
99
+
100
+ # ---------------------------------------------------------------- helpers
101
+ def check_text(s: str, where: str) -> None:
102
+ if HANGUL.search(s):
103
+ sys.exit(f"Korean text in {where}: {s!r}")
104
+ for bad in ("TODO", "TBD", "lorem", "xxxx", "PLACEHOLDER"):
105
+ if bad.lower() in s.lower():
106
+ sys.exit(f"placeholder text {bad!r} in {where}: {s!r}")
107
+
108
+
109
+ def white_bg(slide) -> None:
110
+ fill = slide.background.fill
111
+ fill.solid()
112
+ fill.fore_color.rgb = WHITE
113
+
114
+
115
+ def add_text(slide, x, y, w, h, paras, pt, color=INK, bold=False,
116
+ align=PP_ALIGN.LEFT, anchor=MSO_ANCHOR.TOP, wrap_text=True,
117
+ space_before_pt=0):
118
+ """paras: list of strings, one paragraph each."""
119
+ tb = slide.shapes.add_textbox(Inches(x), Inches(y), Inches(w), Inches(h))
120
+ tf = tb.text_frame
121
+ tf.word_wrap = wrap_text
122
+ tf.auto_size = None
123
+ tf.margin_left = tf.margin_right = tf.margin_top = tf.margin_bottom = Emu(0)
124
+ tf.vertical_anchor = anchor
125
+ for i, text in enumerate(paras):
126
+ p = tf.paragraphs[0] if i == 0 else tf.add_paragraph()
127
+ p.alignment = align
128
+ p.line_spacing = 1.0
129
+ if i > 0 and space_before_pt:
130
+ p.space_before = Pt(space_before_pt)
131
+ r = p.add_run()
132
+ r.text = text
133
+ f = r.font
134
+ f.name = FONT
135
+ f.size = Pt(pt)
136
+ f.bold = bold
137
+ f.color.rgb = color
138
+ return tb
139
+
140
+
141
+ def add_title(slide, title: str, label: str | None) -> None:
142
+ label_w = text_w_in(label, LABEL_PT) if label else 0.0
143
+ room = (X1 - X0) - (label_w + 0.3 if label else 0.0)
144
+ tw = text_w_in(title, TITLE_PT, bold=True)
145
+ if tw > room:
146
+ sys.exit(f"title too long ({tw:.2f} > {room:.2f} in): {title!r}")
147
+ # title box stops short of the section label so the two never overlap
148
+ add_text(slide, X0, 0.30, min(12.4, room), 0.5, [title], TITLE_PT,
149
+ bold=True, wrap_text=False)
150
+ if label:
151
+ # baseline of the label aligned with the title baseline
152
+ asc = 0.905
153
+ y = 0.30 + asc * TITLE_PT / 72.0 - asc * LABEL_PT / 72.0
154
+ add_text(slide, X1 - label_w - 0.05, y, label_w + 0.05, 0.25, [label],
155
+ LABEL_PT,
156
+ color=GREY, align=PP_ALIGN.RIGHT, wrap_text=False)
157
+
158
+
159
+ def refs_line(refs: list[str] | None) -> str | None:
160
+ return ("References: " + "; ".join(refs)) if refs else None
161
+
162
+
163
+ def add_footer(slide, footnote: str | None, number: int, refs: list[str] | None = None) -> None:
164
+ ref = refs_line(refs)
165
+ if ref:
166
+ # one footnote line + one reference line (2026-10-02: every slide cites the papers behind its method or metric)
167
+ if footnote and len(wrap(footnote, FOOT_PT, FOOT_W)) > 1:
168
+ sys.exit(f"footnote must fit one line when the slide has references: {footnote!r}")
169
+ if len(wrap(ref, FOOT_PT, FOOT_W)) > 1:
170
+ sys.exit(f"reference line needs more than one line: {ref!r}")
171
+ check_text(ref, "references")
172
+ y = FOOT_Y
173
+ if footnote:
174
+ add_text(slide, X0, y, FOOT_W, line_h(FOOT_PT) + 0.02, [footnote], FOOT_PT, color=GREY)
175
+ y += line_h(FOOT_PT) + 0.02
176
+ add_text(slide, X0, y, FOOT_W, line_h(FOOT_PT) + 0.02, [ref], FOOT_PT, color=GREY)
177
+ elif footnote:
178
+ lines = wrap(footnote, FOOT_PT, FOOT_W)
179
+ if len(lines) > 2:
180
+ sys.exit(f"footnote needs {len(lines)} lines (max 2): {footnote!r}")
181
+ add_text(slide, X0, FOOT_Y, FOOT_W, 2 * line_h(FOOT_PT) + 0.02,
182
+ [footnote], FOOT_PT, color=GREY)
183
+ add_text(slide, X1 - 0.6, FOOT_Y, 0.6, line_h(NUM_PT), [str(number)],
184
+ NUM_PT, color=GREY, align=PP_ALIGN.RIGHT, wrap_text=False)
185
+
186
+
187
+ def add_notes(slide, s: dict) -> None:
188
+ parts = []
189
+ if s.get("say"):
190
+ parts.append(s["say"])
191
+ full = s.get("footnote_full")
192
+ if full and full != s.get("footnote"):
193
+ parts.append("Full footnote: " + full)
194
+ if s.get("refs_full"):
195
+ parts.append("References: " + " | ".join(s["refs_full"]))
196
+ if s.get("sources"):
197
+ parts.append("Sources: " + s["sources"])
198
+ if parts:
199
+ slide.notes_slide.notes_text_frame.text = "\n\n".join(parts)
200
+
201
+
202
+ # ---------------------------------------------------------------- layout
203
+ def aspect(path: Path) -> float:
204
+ with Image.open(path) as im:
205
+ w, h = im.size
206
+ return w / h
207
+
208
+
209
+ def fit(total_aspect: float, extra_w: float, wmax: float, hmax: float):
210
+ """Largest (w, h) with w = h * total_aspect + extra_w inside the box."""
211
+ h = min(hmax, (wmax - extra_w) / total_aspect)
212
+ return h * total_aspect + extra_w, h
213
+
214
+
215
+ def plan(aspects: list[float], keywords: list[str], layout: str):
216
+ """Return dict with figure height/width and keyword placement."""
217
+ n = len(aspects)
218
+ tot = sum(aspects)
219
+ extra = FIG_GAP * (n - 1)
220
+ full_w, full_h = X1 - X0, YFIG1 - Y0
221
+ options = []
222
+ if not keywords:
223
+ w, h = fit(tot, extra, full_w, full_h)
224
+ return {"mode": "none", "w": w, "h": h}
225
+ # keywords below
226
+ kh = kw_block_h(keywords, full_w)
227
+ hmax = min(full_h, KW_BOTTOM - GAP_BELOW - kh - Y0)
228
+ w, h = fit(tot, extra, full_w, hmax)
229
+ kh = kw_block_h(keywords, full_w) # keywords sit at the text margin X0
230
+ if Y0 + h + GAP_BELOW + kh <= KW_BOTTOM + 1e-6:
231
+ options.append({"mode": "below", "w": w, "h": h, "area": w * h,
232
+ "kw_w": full_w, "kw_h": kh})
233
+ # keywords right
234
+ w, h = fit(tot, extra, full_w - GAP_RIGHT - MIN_COL, full_h)
235
+ col = X1 - (X0 + w) - GAP_RIGHT
236
+ kh = kw_block_h(keywords, col)
237
+ if kh <= full_h:
238
+ options.append({"mode": "right", "w": w, "h": h, "area": w * h,
239
+ "kw_w": col, "kw_h": kh})
240
+ if not options:
241
+ sys.exit(f"no layout fits keywords {keywords!r}")
242
+ best = max(options, key=lambda o: o["area"])
243
+ if layout == "figure_keywords":
244
+ right = [o for o in options if o["mode"] == "right"]
245
+ if right and right[0]["area"] * 1.15 >= best["area"]:
246
+ best = right[0]
247
+ return best
248
+
249
+
250
+ def build_content(prs, s: dict, number: int) -> None:
251
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
252
+ white_bg(slide)
253
+ for fld in ("title", "footnote", "section_label"):
254
+ if s.get(fld):
255
+ check_text(s[fld], f"slide {number} {fld}")
256
+ kws = s.get("keywords", [])
257
+ if len(kws) > 3:
258
+ sys.exit(f"slide {number}: more than 3 keywords")
259
+ for k in kws:
260
+ check_text(k, f"slide {number} keyword")
261
+ add_title(slide, s["title"], s.get("section_label"))
262
+
263
+ paths = [DECK / f for f in s["figures"]]
264
+ for p in paths:
265
+ if not p.is_file():
266
+ sys.exit(f"slide {number}: missing figure {p}")
267
+ asp = [aspect(p) for p in paths]
268
+ L = plan(asp, kws, s.get("layout", "full"))
269
+ w, h = L["w"], L["h"]
270
+ if L["mode"] == "below":
271
+ fx = X0 + ((X1 - X0) - w) / 2.0 # centred; keywords at the text margin
272
+ else:
273
+ fx = X0
274
+ fy = Y0
275
+ x = fx
276
+ for p, a in zip(paths, asp):
277
+ pw = h * a
278
+ slide.shapes.add_picture(str(p), Inches(x), Inches(fy),
279
+ Inches(pw), Inches(h))
280
+ x += pw + FIG_GAP
281
+ assert fy + h <= YFIG1 + 1e-6 and fx + w <= X1 + 1e-6, s["title"]
282
+
283
+ if L["mode"] == "below":
284
+ add_text(slide, X0, fy + h + GAP_BELOW, L["kw_w"], L["kw_h"] + 0.05,
285
+ kws, KW_PT, space_before_pt=KW_PARA_GAP_PT)
286
+ elif L["mode"] == "right":
287
+ kx = fx + w + GAP_RIGHT
288
+ add_text(slide, kx, fy + 0.15, L["kw_w"], L["kw_h"] + 0.05, kws,
289
+ KW_PT, space_before_pt=KW_PARA_GAP_PT)
290
+ add_footer(slide, s.get("footnote"), number, s.get("refs"))
291
+ add_notes(slide, s)
292
+ print(f"{number:>2} {L['mode']:<5} fig {w:5.2f}x{h:4.2f} in {s['title']}")
293
+
294
+
295
+ def build_title(prs, s: dict) -> None:
296
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
297
+ white_bg(slide)
298
+ check_text(s["title"] + s.get("subtitle", ""), "title slide")
299
+ if text_w_in(s["title"], COVER_PT, bold=True) > X1 - X0:
300
+ sys.exit("cover title too long")
301
+ add_text(slide, X0, 2.95, X1 - X0, 0.7, [s["title"]], COVER_PT, bold=True,
302
+ wrap_text=False)
303
+ if s.get("subtitle"):
304
+ add_text(slide, X0, 3.8, X1 - X0, 0.4, [s["subtitle"]], COVER_SUB_PT,
305
+ color=GREY, wrap_text=False)
306
+
307
+
308
+ def build_agenda(prs, s: dict, number: int) -> None:
309
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
310
+ white_bg(slide)
311
+ add_title(slide, s["title"], None)
312
+ items = s["items"]
313
+ if not 6 <= len(items) <= 10: # 10 lines fit the slide; the figure-order deck (2026-10-06) lists 8
314
+ sys.exit("agenda must list 6 to 10 sections")
315
+ step = 0.52
316
+ for i, item in enumerate(items):
317
+ check_text(item, "agenda")
318
+ y = 1.3 + i * step
319
+ add_text(slide, X0, y, 0.45, 0.35, [str(i + 1)], AGENDA_PT, color=GREY,
320
+ align=PP_ALIGN.RIGHT, wrap_text=False)
321
+ add_text(slide, X0 + 0.65, y, 10.5, 0.35, [item], AGENDA_PT,
322
+ wrap_text=False)
323
+ add_footer(slide, None, number)
324
+
325
+
326
+ def build_divider(prs, s: dict, number: int) -> None:
327
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
328
+ white_bg(slide)
329
+ check_text(s["title"], "divider")
330
+ add_text(slide, X0, 2.95, X1 - X0, 0.7, [s["title"]], COVER_PT, bold=True,
331
+ wrap_text=False)
332
+ add_footer(slide, None, number)
333
+
334
+
335
+ def main() -> None:
336
+ spec = json.loads(SPEC.read_text())
337
+ out = DECK / spec["deck"]["output_pptx"]
338
+ prs = Presentation()
339
+ prs.slide_width = Inches(SLIDE_W)
340
+ prs.slide_height = Inches(SLIDE_H)
341
+ for i, s in enumerate(spec["slides"], start=1):
342
+ kind = s["kind"]
343
+ if kind == "title":
344
+ build_title(prs, s)
345
+ print(f"{i:>2} title {s['title']}")
346
+ elif kind == "agenda":
347
+ build_agenda(prs, s, i)
348
+ print(f"{i:>2} agenda {s['title']}")
349
+ elif kind == "divider":
350
+ build_divider(prs, s, i)
351
+ print(f"{i:>2} divider {s['title']}")
352
+ elif kind == "content":
353
+ build_content(prs, s, i)
354
+ else:
355
+ sys.exit(f"unknown slide kind {kind!r}")
356
+ prs.save(out)
357
+ print(f"wrote {out} ({len(spec['slides'])} slides)")
358
+
359
+
360
+ if __name__ == "__main__":
361
+ main()