Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/fold_sizes.py +34 -0
- paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/restructure_20261002.py +143 -0
- paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/scsemi_results.py +112 -0
- paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec01_overview.py +633 -0
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/fold_sizes.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared wording for the 5-fold "every training donor" arm (2026-10-02).
|
| 2 |
+
|
| 3 |
+
The deck used to call this arm "all" / "all training pairs", which reads as if test pairs were used. They never are:
|
| 4 |
+
each fold's LoRA trains on the other four folds minus 7-8 inner-validation donors, and its RUN.json lists the test rows
|
| 5 |
+
as "test_rows_never_loaded_for_training". Every figure now shows the actual number of training pairs instead.
|
| 6 |
+
"""
|
| 7 |
+
import json
|
| 8 |
+
from functools import lru_cache
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
|
| 12 |
+
"paired_finetune_intradataset_20260927")
|
| 13 |
+
FOLD_ARM_LABEL = "5-fold CV (other 4 folds)" # arm suffix, e.g. "LoRA, 5-fold CV (other 4 folds)"
|
| 14 |
+
FOLD_TITLE = "5-fold CV: train on the other 4 folds"
|
| 15 |
+
FOLD_NOTE = "each fold model trains on the other 4 folds (minus inner-val); its test fold is never trained on"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@lru_cache(maxsize=None)
|
| 19 |
+
def train_pairs(ds: str, run: str = "real_lora") -> tuple[int, int]:
|
| 20 |
+
"""(min, max) training pairs per fold of the 5-fold LoRA run, from runs/<ds>/fold<k>/<run>/RUN.json."""
|
| 21 |
+
n = []
|
| 22 |
+
for k in range(5):
|
| 23 |
+
r = json.loads((PLAN / "runs" / ds / f"fold{k}" / run / "RUN.json").read_text())
|
| 24 |
+
tr, te = r["train_rows"], r["test_rows_never_loaded_for_training"]
|
| 25 |
+
if set(tr) & set(te):
|
| 26 |
+
raise SystemExit(f"{ds} fold {k}: train and test rows overlap")
|
| 27 |
+
n.append(len(tr))
|
| 28 |
+
return min(n), max(n)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def all_label(ds: str) -> str:
|
| 32 |
+
"""Tick label for the 'every training donor' point: '78–79' (ImMicro), '58–59' (sepsis)."""
|
| 33 |
+
lo, hi = train_pairs(ds)
|
| 34 |
+
return f"{lo}" if lo == hi else f"{lo}–{hi}"
|
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/restructure_20261002.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""One-off restructure of data/slides_spec.json (2026-10-02, user request): no Backup section.
|
| 3 |
+
|
| 4 |
+
The backup slides move into the sections they support, a metric-overview slide opens section 4, and every slide that
|
| 5 |
+
uses a published method, metric or baseline gets a one-line reference footer (short citations; full citations with
|
| 6 |
+
DOI in the speaker notes). Slide content (titles, keywords, footnotes) is left to the section scripts and
|
| 7 |
+
tools/sync_sec09_text.py; this script only orders slides, sets section labels, the agenda and the references.
|
| 8 |
+
Run once on the pre-restructure spec (it refuses to run twice). The pre-restructure spec is in
|
| 9 |
+
_archive/2026-10-02_before_restructure/.
|
| 10 |
+
"""
|
| 11 |
+
import json
|
| 12 |
+
import sys
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
DECK = Path(__file__).resolve().parents[1]
|
| 16 |
+
SPEC = DECK / "data" / "slides_spec.json"
|
| 17 |
+
|
| 18 |
+
# short citation for the footer, full citation for the notes (verified 2026-10-02; PDFs in reference-papers/)
|
| 19 |
+
REF = {
|
| 20 |
+
"SDD": ("Ostheimer 2025, arXiv", "Ostheimer et al. Sparse Data Diffusion for scientific simulations in biology and physics. arXiv:2502.02448 (2025)"),
|
| 21 |
+
"DDIM": ("Song 2021, ICLR", "Song, Meng & Ermon. Denoising Diffusion Implicit Models. ICLR 2021"),
|
| 22 |
+
"scDiffusion": ("Luo 2024, Bioinformatics", "Luo et al. scDiffusion: conditional generation of high-quality single-cell data using diffusion model. Bioinformatics 40(9):btae518 (2024)"),
|
| 23 |
+
"scSemi": ("Wang 2024, Nat Commun", "Wang et al. scSemiProfiler: advancing large-scale single-cell studies through semi-profiling with deep generative models and active learning. Nat Commun 15:5989 (2024). doi:10.1038/s41467-024-50150-1"),
|
| 24 |
+
"scANVI": ("Xu 2021, Mol Syst Biol", "Xu et al. Probabilistic harmonization and annotation of single-cell transcriptomics data with deep generative models. Mol Syst Biol 17:e9620 (2021)"),
|
| 25 |
+
"LoRA": ("Hu 2022, ICLR", "Hu et al. LoRA: Low-Rank Adaptation of Large Language Models. ICLR 2022"),
|
| 26 |
+
"Kyn": ("Kynkäänniemi 2019, NeurIPS", "Kynkäänniemi et al. Improved precision and recall metric for assessing generative models. NeurIPS 2019"),
|
| 27 |
+
"Naeem": ("Naeem 2020, ICML", "Naeem et al. Reliable fidelity and diversity metrics for generative models. ICML 2020"),
|
| 28 |
+
"Khayat": ("Khayatkhoei 2023, ICML", "Khayatkhoei & AbdAlmageed. Emergent asymmetry of precision and recall for measuring fidelity and diversity of generative models in high dimensions. ICML 2023"),
|
| 29 |
+
"LopezPaz": ("Lopez-Paz 2017, ICLR", "Lopez-Paz & Oquab. Revisiting classifier two-sample tests. ICLR 2017"),
|
| 30 |
+
"Gretton": ("Gretton 2012, JMLR", "Gretton et al. A kernel two-sample test. JMLR 13:723-773 (2012)"),
|
| 31 |
+
"GEARS": ("Roohani 2024, Nat Biotechnol", "Roohani, Huang & Leskovec. Predicting transcriptional outcomes of novel multigene perturbations with GEARS. Nat Biotechnol 42:927-935 (2024). doi:10.1038/s41587-023-01905-6"),
|
| 32 |
+
"Systema": ("Viñas Torné 2026, Nat Biotechnol", "Viñas Torné et al. Systema: a framework for evaluating genetic perturbation response prediction beyond systematic variation. Nat Biotechnol 44:1050-1059 (2026). doi:10.1038/s41587-025-02777-8"),
|
| 33 |
+
"AhlmannEltze": ("Ahlmann-Eltze 2025, Nat Methods", "Ahlmann-Eltze, Huber & Anders. Deep-learning-based gene perturbation effect prediction does not yet outperform simple linear baselines. Nat Methods 22:1657-1661 (2025). doi:10.1038/s41592-025-02772-6"),
|
| 34 |
+
"Li2026": ("Li 2026, Sci Adv", "Li et al. A systematic comparison of single-cell perturbation response prediction models. Sci Adv 12:eaed3414 (2026). doi:10.1126/sciadv.aed3414"),
|
| 35 |
+
"Squair": ("Squair 2021, Nat Commun", "Squair et al. Confronting false discoveries in single-cell differential expression. Nat Commun 12:5692 (2021). doi:10.1038/s41467-021-25960-2"),
|
| 36 |
+
"voom": ("Law 2014, Genome Biol", "Law, Chen, Shi & Smyth. voom: precision weights unlock linear model analysis tools for RNA-seq read counts. Genome Biol 15:R29 (2014)"),
|
| 37 |
+
"Irizarry": ("Irizarry 2005, Nat Methods", "Irizarry et al. Multiple-laboratory comparison of microarray platforms. Nat Methods 2:345-350 (2005). doi:10.1038/nmeth756"),
|
| 38 |
+
"BayesPrism": ("Chu 2022, Nat Cancer", "Chu et al. Cell type and gene expression deconvolution with BayesPrism enables Bayesian integrative analysis across bulk and single-cell RNA sequencing in oncology. Nat Cancer 3:505-517 (2022)"),
|
| 39 |
+
}
|
| 40 |
+
METRIC_REFS = ["Kyn", "Naeem", "LopezPaz", "Gretton", "scSemi", "GEARS", "Systema", "Li2026", "Squair", "voom", "Irizarry"]
|
| 41 |
+
|
| 42 |
+
AGENDA = [
|
| 43 |
+
"Model overview: diffusion from bulk to cells",
|
| 44 |
+
"Backbone: SDD, scDiffusion, bulk conditioning",
|
| 45 |
+
"Architecture ablation: width, context, gene panel",
|
| 46 |
+
"How we score cells; SLE benchmark vs scSemiProfiler",
|
| 47 |
+
"Real bulk ≠ pseudobulk: why zero-shot fails",
|
| 48 |
+
"Fine-tuning on paired bulk–sc data; evaluation design",
|
| 49 |
+
"LoRA: compute, rank and K ablations",
|
| 50 |
+
"How many bulk–sc pairs are needed",
|
| 51 |
+
"Paired-cohort validation vs scSemiProfiler",
|
| 52 |
+
"Next: cohorts with a paired subset (planned)",
|
| 53 |
+
]
|
| 54 |
+
SECTION = {"1": "1 Model overview", "2": "2 Backbone", "3": "3 Architecture ablation", "4": "4 Metrics + SLE benchmark",
|
| 55 |
+
"5": "5 Real bulk vs pseudobulk", "6": "6 Paired fine-tuning", "7": "7 LoRA ablations", "8": "8 Pairs needed",
|
| 56 |
+
"9": "9 Paired validation", "10": "10 Paired-subset cohorts"}
|
| 57 |
+
METRICS_SLIDE = {
|
| 58 |
+
"kind": "content", "section": "4", "title": "How we score generated cells", "layout": "full",
|
| 59 |
+
"figures": ["figures/sec04_metrics_overview.png"],
|
| 60 |
+
"keywords": ["Cells, composition and disease signal, separately",
|
| 61 |
+
"Every metric next to its control or ceiling",
|
| 62 |
+
"Same donors and reference cells for every method"],
|
| 63 |
+
"footnote": "Definitions follow the cited papers; scorers: tools/score_ft.py, extra_metrics.py, contrast_extra.py.",
|
| 64 |
+
"sources": "tools/sec04_metrics_overview.py; data/sec04_metrics_overview.csv",
|
| 65 |
+
"refs_full": [REF[k][1] for k in METRIC_REFS],
|
| 66 |
+
}
|
| 67 |
+
# new order: (title, section, refs); the metric slide is inserted by key "METRICS"
|
| 68 |
+
ORDER = [
|
| 69 |
+
("PBISC-Diffusion: bulk-to-single-cell generation", None, []),
|
| 70 |
+
("Outline", None, []),
|
| 71 |
+
("PBISC-Diffusion: bulk in, cells out", "1", ["SDD", "DDIM"]),
|
| 72 |
+
("Denoiser: joint value + support diffusion", "1", ["SDD"]),
|
| 73 |
+
("Backbone: SDD → PBISC-Diffusion", "2", ["SDD", "scDiffusion"]),
|
| 74 |
+
("Bulk conditioning", "2", []),
|
| 75 |
+
("Width & context ablation: loss saturation", "3", []),
|
| 76 |
+
("Width & context ablation: benchmark", "3", []),
|
| 77 |
+
("Gene context: 2k / 3k / 6k / 15k", "3", []),
|
| 78 |
+
("METRICS", "4", []),
|
| 79 |
+
("SLE benchmark: PBISC vs scSemiProfiler", "4", ["scSemi", "scANVI"]),
|
| 80 |
+
("SLE benchmark: per cell type", "4", ["scSemi"]),
|
| 81 |
+
("Bulk broadcast baseline", "4", ["Systema", "AhlmannEltze", "BayesPrism"]),
|
| 82 |
+
("Real bulk ≠ pseudobulk (model input)", "5", []),
|
| 83 |
+
("Same shift in three paired cohorts", "5", []),
|
| 84 |
+
("Consequence: cells off-manifold", "5", ["Kyn", "Naeem"]),
|
| 85 |
+
("Consequence: disease direction flips", "5", []),
|
| 86 |
+
("Fine-tuning with paired bulk + sc", "6", ["LoRA"]),
|
| 87 |
+
("Evaluation design", "6", []),
|
| 88 |
+
("Full vs LoRA vs cond.-encoder-only", "7", ["LoRA"]),
|
| 89 |
+
("LoRA rank: r = 4, 16, 64", "7", ["LoRA"]),
|
| 90 |
+
("K diversification: no gain", "7", []),
|
| 91 |
+
("Pairs needed: composition, coverage, training steps", "8", ["Kyn", "Naeem"]),
|
| 92 |
+
("Pairs needed: donor and disease signal", "8", ["GEARS", "Li2026"]),
|
| 93 |
+
("Five paired cohorts", "9", []),
|
| 94 |
+
("5 donors: LoRA vs scSemiProfiler — cells", "9", ["Kyn", "Naeem", "scSemi"]),
|
| 95 |
+
("5 donors: realism beyond precision/coverage", "9", ["LopezPaz", "Gretton", "scSemi"]),
|
| 96 |
+
("5 donors: precision/coverage at k = 3, 5, 10", "9", ["Naeem", "Khayat"]),
|
| 97 |
+
("scSemiProfiler copies its representative", "9", ["scSemi"]),
|
| 98 |
+
("5 donors: LoRA vs scSemiProfiler — disease signal", "9", ["GEARS", "Systema", "Li2026", "voom", "Irizarry"]),
|
| 99 |
+
("5 donors: time to apply", "9", ["scSemi"]),
|
| 100 |
+
("5-fold CV: train on the other 4 folds", "9", ["Systema", "Li2026"]),
|
| 101 |
+
("5-fold: realism beyond precision/coverage", "9", ["LopezPaz", "Gretton"]),
|
| 102 |
+
("Next: cohorts with a paired subset (planned)", "10", []),
|
| 103 |
+
]
|
| 104 |
+
OLD_TITLE = {"5-fold CV: train on the other 4 folds": "All pairs, 5-fold"}
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def main() -> int:
|
| 108 |
+
spec = json.loads(SPEC.read_text())
|
| 109 |
+
sl = spec["slides"]
|
| 110 |
+
if any(s.get("title") == METRICS_SLIDE["title"] for s in sl):
|
| 111 |
+
sys.exit("already restructured")
|
| 112 |
+
by = {s["title"]: s for s in sl}
|
| 113 |
+
out, used = [], set()
|
| 114 |
+
for title, sec, refs in ORDER:
|
| 115 |
+
if title == "METRICS":
|
| 116 |
+
s = dict(METRICS_SLIDE)
|
| 117 |
+
else:
|
| 118 |
+
key = title if title in by else OLD_TITLE.get(title, title)
|
| 119 |
+
if key not in by:
|
| 120 |
+
sys.exit(f"slide not found: {title!r}")
|
| 121 |
+
s = by[key]
|
| 122 |
+
used.add(key)
|
| 123 |
+
if sec:
|
| 124 |
+
s["section"] = sec
|
| 125 |
+
s["section_label"] = SECTION[sec]
|
| 126 |
+
s.pop("backup", None)
|
| 127 |
+
if refs:
|
| 128 |
+
s["refs"] = [REF[k][0] for k in refs]
|
| 129 |
+
s["refs_full"] = [REF[k][1] for k in refs]
|
| 130 |
+
if s.get("kind") == "agenda":
|
| 131 |
+
s["items"] = AGENDA
|
| 132 |
+
out.append(s)
|
| 133 |
+
left = [t for t in by if t not in used and by[t].get("kind") != "divider"]
|
| 134 |
+
if left:
|
| 135 |
+
sys.exit(f"slides not placed: {left}")
|
| 136 |
+
spec["slides"] = out
|
| 137 |
+
SPEC.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n")
|
| 138 |
+
print(f"{len(out)} slides (was {len(sl)})")
|
| 139 |
+
return 0
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
if __name__ == "__main__":
|
| 143 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/scsemi_results.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Where the scSemiProfiler 5-fold (CV) and equal-budget results will appear, and a tolerant lookup for them.
|
| 2 |
+
|
| 3 |
+
Shared helper of the 2026-09-30 paper-summary deck (not run directly). CPU only; reads files, never writes.
|
| 4 |
+
|
| 5 |
+
Planned locations (2026-10-02; the GPU runs are prepared by another agent and may not exist yet):
|
| 6 |
+
CV arm scsemi__raw <PLAN>/scores/<ds>/scsemi_cv_20261002/{fold<k>,pooled}/
|
| 7 |
+
equal budget arms scsemi_n{5,10,20,40}__raw <PLAN>/scores/<ds>/scsemi_budget_20261002/{fold<k>,pooled}/
|
| 8 |
+
(ImMicro and sepsis only)
|
| 9 |
+
extra metrics (classifier AUC, MMD^2, E_N, P/C at k = 3/5/10)
|
| 10 |
+
<PLAN>/scores_extra/<ds>/scsemi_cv_20261002/ and .../scsemi_budget_20261002/ (any depth below)
|
| 11 |
+
Giroux disease metrics without sex-linked genes, if rescored:
|
| 12 |
+
<PLAN>/scores_nosex/giroux2022/scsemi_cv_20261002/...
|
| 13 |
+
|
| 14 |
+
The deck uses cross-fitted pooled calls only: directories below <exp>/ with a path part starting with "pooled"
|
| 15 |
+
(pooled, pooled_deg, ...), never fold<k>/ or arms/. A call is accepted only if it scores the same donors with the
|
| 16 |
+
same reference cells as the main pooled call and its generation receipt is not marked unverified (accept()).
|
| 17 |
+
|
| 18 |
+
Every script that uses this module prints a note and draws nothing for scSemiProfiler when no accepted call exists.
|
| 19 |
+
DECK_SCSEMI_PLAN_ROOT overrides <PLAN> for these lookups only (the synthetic presence test in a scratch copy).
|
| 20 |
+
"""
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import json
|
| 24 |
+
import os
|
| 25 |
+
import re
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
PLAN_DEFAULT = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
|
| 29 |
+
"paired_finetune_intradataset_20260927")
|
| 30 |
+
CV_EXP = "scsemi_cv_20261002"
|
| 31 |
+
BUDGET_EXP = "scsemi_budget_20261002"
|
| 32 |
+
CV_ARM = "scsemi__raw"
|
| 33 |
+
BUDGET_RE = re.compile(r"^scsemi_n(\d+)__raw$")
|
| 34 |
+
FOLD_RE = re.compile(r"^fold\d+$")
|
| 35 |
+
LABEL_CV = "scSemiProfiler, 5-fold CV (other 4 folds)"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def plan_root() -> Path:
|
| 39 |
+
return Path(os.environ.get("DECK_SCSEMI_PLAN_ROOT", str(PLAN_DEFAULT)))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def is_test_root() -> bool:
|
| 43 |
+
return plan_root() != PLAN_DEFAULT
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _pooled_dir(rel: Path) -> bool:
|
| 47 |
+
parts = rel.parts
|
| 48 |
+
return (not any(FOLD_RE.match(p) or p == "arms" for p in parts)) and any(p.startswith("pooled") for p in parts)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def pooled_dirs(ds: str, exp: str, tree: str = "scores") -> list[Path]:
|
| 52 |
+
"""Directories with a summary.json of the pooled calls of one experiment, 'pooled' before 'pooled_deg' etc."""
|
| 53 |
+
root = plan_root() / tree / ds / exp
|
| 54 |
+
if not root.is_dir():
|
| 55 |
+
return []
|
| 56 |
+
out = [sp.parent for sp in root.rglob("summary.json") if _pooled_dir(sp.parent.relative_to(root))]
|
| 57 |
+
return sorted(out, key=lambda p: (len(p.relative_to(root).parts), p.name != "pooled", str(p)))
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _arms(d: Path) -> list[str]:
|
| 61 |
+
try:
|
| 62 |
+
return list(json.loads((d / "summary.json").read_text()).get("arms") or [])
|
| 63 |
+
except (OSError, ValueError):
|
| 64 |
+
return []
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def cv_calls(ds: str, tree: str = "scores") -> list[Path]:
|
| 68 |
+
"""Pooled call directories that contain the CV arm."""
|
| 69 |
+
return [d for d in pooled_dirs(ds, CV_EXP, tree) if CV_ARM in _arms(d)]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def budget_calls(ds: str, tree: str = "scores") -> dict[int, list[tuple[str, Path]]]:
|
| 73 |
+
"""n -> [(arm, pooled call dir)] for the equal-budget arms scsemi_n<n>__raw."""
|
| 74 |
+
out: dict[int, list[tuple[str, Path]]] = {}
|
| 75 |
+
for d in pooled_dirs(ds, BUDGET_EXP, tree):
|
| 76 |
+
for a in _arms(d):
|
| 77 |
+
m = BUDGET_RE.match(a)
|
| 78 |
+
if m:
|
| 79 |
+
out.setdefault(int(m.group(1)), []).append((a, d))
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def accept(summary: dict, ref_summary: dict, arm: str) -> list[str]:
|
| 84 |
+
"""Reasons to reject one scSemiProfiler arm of a call against the main pooled call ([] = accepted)."""
|
| 85 |
+
why = []
|
| 86 |
+
if arm not in (summary.get("arms") or []):
|
| 87 |
+
why.append(f"arm {arm} not in the call")
|
| 88 |
+
if set(map(str, summary.get("donors", []))) != set(map(str, ref_summary.get("donors", []))):
|
| 89 |
+
why.append(f"donor set differs ({len(summary.get('donors', []))} vs {len(ref_summary.get('donors', []))})")
|
| 90 |
+
rs = summary.get("reference", {}).get("reference_sha256")
|
| 91 |
+
if rs != ref_summary.get("reference", {}).get("reference_sha256"):
|
| 92 |
+
why.append("reference cells differ (reference_sha256)")
|
| 93 |
+
if summary.get("per_arm", {}).get(arm, {}).get("receipt_verified", True) is False:
|
| 94 |
+
why.append("generation receipt not verified")
|
| 95 |
+
return why
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def extra_units(ds: str, exp: str) -> list[Path]:
|
| 99 |
+
"""Extra-metric unit directories (metrics.csv + en.csv) below scores_extra/<ds>/<exp>/, pooled ones first;
|
| 100 |
+
fold<k>/ units are skipped (the deck shows the pooled design)."""
|
| 101 |
+
root = plan_root() / "scores_extra" / ds / exp
|
| 102 |
+
if not root.is_dir():
|
| 103 |
+
return []
|
| 104 |
+
out = []
|
| 105 |
+
for mp in root.rglob("metrics.csv"):
|
| 106 |
+
d = mp.parent
|
| 107 |
+
rel = d.relative_to(root)
|
| 108 |
+
if any(FOLD_RE.match(p) for p in rel.parts) or not (d / "en.csv").is_file():
|
| 109 |
+
continue
|
| 110 |
+
out.append(d)
|
| 111 |
+
return sorted(out, key=lambda p: (not any(x.startswith("pooled") for x in p.relative_to(root).parts),
|
| 112 |
+
len(p.relative_to(root).parts), str(p)))
|
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec01_overview.py
ADDED
|
@@ -0,0 +1,633 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Section 1 (model overview) figures for the 2026-09-30 paper-summary deck.
|
| 2 |
+
|
| 3 |
+
Outputs (deck folder only):
|
| 4 |
+
figures/sec01_fig1a_denoiser.{svg,png,pdf} deck redraw of manuscript Fig. 1a with slide-size labels
|
| 5 |
+
(temporary) sec01_fig1b_inference.{svg,png,pdf} deck redraw of manuscript Fig. 1b, placed into sec01_slide_a
|
| 6 |
+
(not saved) sec01_corpus pretraining corpus panel, drawn inside sec01_slide_a
|
| 7 |
+
figures/sec01_slide_a.{png,pdf} slide (a) composite, exactly 12.3 in wide
|
| 8 |
+
data/sec01_corpus_datasets.csv, data/sec01_recipe_k.csv, data/sec01_model_numbers.csv,
|
| 9 |
+
data/sec01_fig1_label_pt.csv (on-slide point size of every text line in the two redraws)
|
| 10 |
+
|
| 11 |
+
The manuscript SVG is only read. The deck copies change label sizes, drop the panel letters and the
|
| 12 |
+
legend row, widen a few boxes so the larger labels fit, and (panel b) say that cells differ by x_T and by
|
| 13 |
+
the Bernoulli support draw (drawn read-out, manuscript Methods). CPU only; every number is read from the
|
| 14 |
+
source files named below.
|
| 15 |
+
"""
|
| 16 |
+
import html
|
| 17 |
+
import json
|
| 18 |
+
import re
|
| 19 |
+
import sys
|
| 20 |
+
from collections import defaultdict
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00")
|
| 24 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 25 |
+
import style # noqa: E402
|
| 26 |
+
|
| 27 |
+
import cairosvg # 2.9.1, the renderer recorded in fig01_architecture.provenance.json # noqa: E402
|
| 28 |
+
import fitz # PyMuPDF, only to check page sizes # noqa: E402
|
| 29 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 30 |
+
import numpy as np # noqa: E402
|
| 31 |
+
import pandas as pd # noqa: E402
|
| 32 |
+
from PIL import ImageFont # noqa: E402
|
| 33 |
+
|
| 34 |
+
FIG = DECK / "figures"
|
| 35 |
+
DATA = DECK / "data"
|
| 36 |
+
|
| 37 |
+
MS = Path("/home/sj_server_1/PBISC/paper-release-20260928/manuscript")
|
| 38 |
+
FIG1_SVG = MS / "figures/fig01_architecture.svg"
|
| 39 |
+
METHODS = MS / "sections/methods.tex"
|
| 40 |
+
SRC_MANIFEST = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_7_no_annotation_sh_hwang/data/e2_full_source/dataset_manifest.json")
|
| 41 |
+
IDX_MANIFEST = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_7_no_annotation_sh_hwang/data/e2_full_index/dataset_manifest.json")
|
| 42 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 43 |
+
RUN = M8 / "runs/f01_6k_1x_seed20260627"
|
| 44 |
+
CFG = RUN / "effective_config.json"
|
| 45 |
+
STATUS = RUN / "RUN_STATUS.json"
|
| 46 |
+
CONTRACT = RUN / "ALLCELL_DATA_CONTRACT.json"
|
| 47 |
+
PLAN = M8 / "plans/full_recipe_allcells_6k_broad_20260909"
|
| 48 |
+
TOPUP_CSV = PLAN / "topup_v1/topup_recipes.csv"
|
| 49 |
+
SHARD_OFFSETS = PLAN / "topup_v1/shard_offsets.csv"
|
| 50 |
+
COVERAGE = PLAN / "coverage_v1/summary.json"
|
| 51 |
+
MODEL_PY = M8 / "src/pbisc_sdd/model.py"
|
| 52 |
+
|
| 53 |
+
# Short readable labels for the 22 corpus datasets (text only; counts come from the manifest).
|
| 54 |
+
LABELS = {
|
| 55 |
+
"001": "Perez SLE", "005": "OneK1K", "006": "AIDA", "007": "Miao RA", "009": "AIFI Health Atlas",
|
| 56 |
+
"010": "ScaleBio PBMC", "053": "Hao CITE-seq", "058": "COVID immunodeficiency",
|
| 57 |
+
"061": "RA at-risk (Savage)", "065": "Sound Life", "071": "JDM CITE-seq", "074": "COMBAT",
|
| 58 |
+
"081": "COVID atlas (Seq-Well)", "093": "SARS-CoV-2 local/systemic", "200": "Immunobiology of Aging",
|
| 59 |
+
"202": "Fatal COVID time course", "203": "Indonesia diversity", "204": "cHSPC aging / MDS",
|
| 60 |
+
"300b": "DRESS / DiHS", "301": "SLE B-cell study", "302": "SLE IL-36 stim", "304": "Parse 10M cytokine",
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
# On-slide sizes (inches). Slide (b): one keyword line under the diagram leaves about 5.25 in.
|
| 64 |
+
A_HEIGHT_IN = 5.25
|
| 65 |
+
SLIDE_A_H = 5.30 # composite height: leaves room for one keyword line in the 5.7-in content area
|
| 66 |
+
W_FULL = style.FULL[0] # 12.3 in
|
| 67 |
+
|
| 68 |
+
# ============================================================== SVG copy with slide-size labels
|
| 69 |
+
FONT_R = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 100)
|
| 70 |
+
FONT_B = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 100)
|
| 71 |
+
LS = 0.5 # letter-spacing set on the outer <g> of the figure
|
| 72 |
+
SKEW = 0.2126
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def text_w(s, fs, bold=False):
|
| 76 |
+
s = html.unescape(s)
|
| 77 |
+
return (FONT_B if bold else FONT_R).getlength(s) * fs / 100.0 + LS * len(s)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def attr(a, name):
|
| 81 |
+
m = re.search(rf'(?<![\w-]){name}="([^"]*)"', a)
|
| 82 |
+
return m.group(1) if m else None
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def set_attr(a, name, val):
|
| 86 |
+
new, n = re.subn(rf'(?<![\w-]){name}="[^"]*"', f'{name}="{val}"', a, count=1)
|
| 87 |
+
assert n == 1, (name, a)
|
| 88 |
+
return new
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def fmt(v):
|
| 92 |
+
return f"{v:.2f}".rstrip("0").rstrip(".")
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def map_d(d, fx, fy):
|
| 96 |
+
"""Map absolute M/L/H/V/Z path data (one coordinate group per command, as in the manuscript SVG)."""
|
| 97 |
+
segs = []
|
| 98 |
+
for cmd, args in re.findall(r"([MLHVZ])([^MLHVZ]*)", d):
|
| 99 |
+
nums = [float(v) for v in re.findall(r"-?\d+(?:\.\d+)?", args)]
|
| 100 |
+
if cmd in "ML":
|
| 101 |
+
assert len(nums) == 2, d
|
| 102 |
+
segs.append(f"{cmd}{fmt(fx(nums[0]))},{fmt(fy(nums[1]))}")
|
| 103 |
+
elif cmd == "H":
|
| 104 |
+
assert len(nums) == 1, d
|
| 105 |
+
segs.append(f"H{fmt(fx(nums[0]))}")
|
| 106 |
+
elif cmd == "V":
|
| 107 |
+
assert len(nums) == 1, d
|
| 108 |
+
segs.append(f"V{fmt(fy(nums[0]))}")
|
| 109 |
+
else:
|
| 110 |
+
segs.append("Z")
|
| 111 |
+
return " ".join(segs)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def d_xs(d):
|
| 115 |
+
toks = re.findall(r"[MLHVZ]|-?\d+(?:\.\d+)?", d)
|
| 116 |
+
xs, cmd, i = [], None, 0
|
| 117 |
+
while i < len(toks):
|
| 118 |
+
t = toks[i]
|
| 119 |
+
if t in "MLHVZ":
|
| 120 |
+
cmd = t
|
| 121 |
+
i += 1
|
| 122 |
+
elif cmd in "ML":
|
| 123 |
+
xs.append(float(t))
|
| 124 |
+
i += 2
|
| 125 |
+
elif cmd == "H":
|
| 126 |
+
xs.append(float(t))
|
| 127 |
+
i += 1
|
| 128 |
+
else:
|
| 129 |
+
i += 1
|
| 130 |
+
return xs
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def piecewise(knots):
|
| 134 |
+
xs = np.array([k[0] for k in knots], float)
|
| 135 |
+
ys = np.array([k[1] for k in knots], float)
|
| 136 |
+
|
| 137 |
+
def X(x):
|
| 138 |
+
if x <= xs[0]:
|
| 139 |
+
return x + (ys[0] - xs[0])
|
| 140 |
+
if x >= xs[-1]:
|
| 141 |
+
return x + (ys[-1] - xs[-1])
|
| 142 |
+
return float(np.interp(x, xs, ys))
|
| 143 |
+
return X
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
# Panel a: widen the Expression column (+36) and the Conditioning column (+20); the main column only shifts.
|
| 147 |
+
X_A = piecewise([(24, 24), (232, 268), (1184, 1220), (1416, 1472)])
|
| 148 |
+
X_ID = piecewise([(0, 0), (1, 1)])
|
| 149 |
+
|
| 150 |
+
TOKEN = re.compile(
|
| 151 |
+
r'<g transform="matrix\(1,0,-0\.2126,1,(?P<gtx>[-\d.]+),0\)">(?P<ginner>.*?)</g>'
|
| 152 |
+
r'|<text (?P<tattrs>[^>]*)>(?P<tbody>.*?)</text>'
|
| 153 |
+
r'|<path (?P<pattrs>[^>]*)/>')
|
| 154 |
+
INNER_TEXT = re.compile(r'<text (?P<attrs>[^>]*)>(?P<body>.*?)</text>')
|
| 155 |
+
INNER_PATH = re.compile(r'<path (?P<attrs>[^>]*)/>')
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def process_text_line(line, X, target=None, mode="c", dy=0.0, ax_fixed=None):
|
| 159 |
+
"""Rescale one visual text line (several runs, skew groups, hat paths) about its anchor.
|
| 160 |
+
target: new main font size (None keeps it); mode 'c' centres on the old centre, 'l' keeps the left edge;
|
| 161 |
+
ax_fixed: old-coordinate centre to use instead of the measured one (re-centres a line in its box)."""
|
| 162 |
+
runs = []
|
| 163 |
+
for m in TOKEN.finditer(line):
|
| 164 |
+
if m.group("gtx") is not None:
|
| 165 |
+
t = INNER_TEXT.search(m.group("ginner"))
|
| 166 |
+
runs.append(dict(attrs=t.group("attrs"), body=t.group("body")))
|
| 167 |
+
elif m.group("tattrs") is not None:
|
| 168 |
+
runs.append(dict(attrs=m.group("tattrs"), body=m.group("tbody")))
|
| 169 |
+
for r in runs:
|
| 170 |
+
a = r["attrs"]
|
| 171 |
+
r.update(x=float(attr(a, "x")), y=float(attr(a, "y")), fs=float(attr(a, "font-size")),
|
| 172 |
+
bold=attr(a, "font-weight") == "700", anchor=attr(a, "text-anchor") or "start")
|
| 173 |
+
r["w"] = text_w(r["body"], r["fs"], r["bold"])
|
| 174 |
+
fs0 = max(r["fs"] for r in runs)
|
| 175 |
+
yb = next(r["y"] for r in runs if r["fs"] == fs0)
|
| 176 |
+
if any(r["anchor"] in ("middle", "end") for r in runs):
|
| 177 |
+
assert len(runs) == 1, line
|
| 178 |
+
ax_old = runs[0]["x"]
|
| 179 |
+
extent = (runs[0]["x"] - runs[0]["w"] / 2, runs[0]["x"] + runs[0]["w"] / 2) if runs[0]["anchor"] == "middle" \
|
| 180 |
+
else (runs[0]["x"] - runs[0]["w"], runs[0]["x"])
|
| 181 |
+
else:
|
| 182 |
+
x0 = min(r["x"] for r in runs)
|
| 183 |
+
x1 = max(r["x"] + r["w"] for r in runs)
|
| 184 |
+
extent = (x0, x1)
|
| 185 |
+
ax_old = x0 if mode == "l" else (x0 + x1) / 2
|
| 186 |
+
f = (target / fs0) if target else 1.0
|
| 187 |
+
# the measured centre goes to the mapped box centre when one is given
|
| 188 |
+
ax_new = X(ax_fixed) if ax_fixed is not None else X(ax_old)
|
| 189 |
+
yb_new = yb + dy
|
| 190 |
+
fx = lambda x: ax_new + (x - ax_old) * f # noqa: E731
|
| 191 |
+
fy = lambda y: yb_new + (y - yb) * f # noqa: E731
|
| 192 |
+
|
| 193 |
+
def fix_text(a):
|
| 194 |
+
x, y, fs = float(attr(a, "x")), float(attr(a, "y")), float(attr(a, "font-size"))
|
| 195 |
+
a = set_attr(a, "x", fmt(fx(x)))
|
| 196 |
+
a = set_attr(a, "y", fmt(fy(y)))
|
| 197 |
+
return set_attr(a, "font-size", fmt(fs * f)), fy(y)
|
| 198 |
+
|
| 199 |
+
def fix_path(a):
|
| 200 |
+
return set_attr(a, "d", map_d(attr(a, "d"), fx, fy))
|
| 201 |
+
|
| 202 |
+
def repl(m):
|
| 203 |
+
if m.group("gtx") is not None:
|
| 204 |
+
inner = m.group("ginner")
|
| 205 |
+
t = INNER_TEXT.search(inner)
|
| 206 |
+
ta, ynew = fix_text(t.group("attrs"))
|
| 207 |
+
inner = inner.replace(t.group(0), f'<text {ta}>{t.group("body")}</text>')
|
| 208 |
+
inner = INNER_PATH.sub(lambda p: f'<path {fix_path(p.group("attrs"))}/>', inner)
|
| 209 |
+
return f'<g transform="matrix(1,0,-0.2126,1,{fmt(SKEW * ynew)},0)">{inner}</g>'
|
| 210 |
+
if m.group("tattrs") is not None:
|
| 211 |
+
ta, _ = fix_text(m.group("tattrs"))
|
| 212 |
+
return f'<text {ta}>{m.group("tbody")}</text>'
|
| 213 |
+
return f'<path {fix_path(m.group("pattrs"))}/>'
|
| 214 |
+
|
| 215 |
+
new = TOKEN.sub(repl, line)
|
| 216 |
+
w_new = (extent[1] - extent[0]) * f
|
| 217 |
+
info = dict(fs_old=fs0, fs_new=fs0 * f, width_new=w_new, center_new=fx((extent[0] + extent[1]) / 2),
|
| 218 |
+
text=" ".join(html.unescape(r["body"]) for r in runs))
|
| 219 |
+
return new, info
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def process_geometry_line(line, X):
|
| 223 |
+
def rect(m):
|
| 224 |
+
a = m.group(1)
|
| 225 |
+
x, w = float(attr(a, "x")), float(attr(a, "width"))
|
| 226 |
+
a = set_attr(a, "x", fmt(X(x)))
|
| 227 |
+
a = set_attr(a, "width", fmt(X(x + w) - X(x)))
|
| 228 |
+
return f"<rect {a}/>"
|
| 229 |
+
|
| 230 |
+
def circ(m):
|
| 231 |
+
a = m.group(1)
|
| 232 |
+
return f'<circle {set_attr(a, "cx", fmt(X(float(attr(a, "cx")))))}/>'
|
| 233 |
+
|
| 234 |
+
def path(m):
|
| 235 |
+
a = m.group(1)
|
| 236 |
+
d = attr(a, "d")
|
| 237 |
+
rigid = attr(a, "stroke") == "#FFFFFF" or d.count("M") > 1 # bar rulings and plus signs keep their size
|
| 238 |
+
if rigid:
|
| 239 |
+
xs = d_xs(d)
|
| 240 |
+
c = (min(xs) + max(xs)) / 2
|
| 241 |
+
dx = X(c) - c
|
| 242 |
+
return f'<path {set_attr(a, "d", map_d(d, lambda x: x + dx, lambda y: y))}/>'
|
| 243 |
+
return f'<path {set_attr(a, "d", map_d(d, X, lambda y: y))}/>'
|
| 244 |
+
|
| 245 |
+
line = re.sub(r"<rect ([^>]*)/>", rect, line)
|
| 246 |
+
line = re.sub(r"<circle ([^>]*)/>", circ, line)
|
| 247 |
+
line = re.sub(r"<path ([^>]*)/>", path, line)
|
| 248 |
+
return line
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def run_line(y, parts, fill, cx, fs=19.0):
|
| 252 |
+
"""Build a centred text line from (text, style, space_before) parts at font fs.
|
| 253 |
+
style: 'n' upright, 'i' italic (skew group, as in the manuscript), 'sub' upright subscript at 0.7 fs."""
|
| 254 |
+
fsub = round(fs * 0.7, 2)
|
| 255 |
+
sp = text_w(" ", fs)
|
| 256 |
+
widths = [text_w(t, fsub if s == "sub" else fs) for t, s, _ in parts]
|
| 257 |
+
total = sum(widths) + sp * sum(1 for *_, g in parts if g)
|
| 258 |
+
x = cx - total / 2
|
| 259 |
+
out = []
|
| 260 |
+
for (t, s, gap), w in zip(parts, widths):
|
| 261 |
+
x += sp if gap else 0.0
|
| 262 |
+
size, yy = (fsub, y + round(fs * 0.17, 1)) if s == "sub" else (fs, y)
|
| 263 |
+
el = (f'<text x="{fmt(x)}" y="{fmt(yy)}" font-size="{fmt(size)}" font-weight="400" fill="{fill}" '
|
| 264 |
+
f'letter-spacing="0.5" text-anchor="start">{t}</text>')
|
| 265 |
+
if s == "i":
|
| 266 |
+
el = f'<g transform="matrix(1,0,-0.2126,1,{fmt(SKEW * yy)},0)">{el}</g>'
|
| 267 |
+
out.append(el)
|
| 268 |
+
x += w
|
| 269 |
+
return "".join(out), total
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
# Line-specific geometry edits (1-based line numbers of the manuscript SVG); each old string must occur once.
|
| 273 |
+
EDITS = {
|
| 274 |
+
126: [("M677.5,548 H657", "M677.5,548 H663")],
|
| 275 |
+
132: [('<rect x="577" y="511" width="80" height="73"', '<rect x="571" y="511" width="92" height="73"')],
|
| 276 |
+
135: [('<rect x="404" y="480" width="130" height="48"', '<rect x="398" y="480" width="142" height="48"')],
|
| 277 |
+
137: [('<rect x="404" y="551" width="130" height="48"', '<rect x="398" y="548" width="142" height="60"')],
|
| 278 |
+
140: [("M577,548 H560 V504 H542", "M571,548 H560 V504 H549")],
|
| 279 |
+
141: [("M560,548 V575 H542", "M560,548 V578 H549")],
|
| 280 |
+
142: [("M404,504 H366", "M398,504 H366")],
|
| 281 |
+
143: [("M404,575 H366 V539", "M398,578 H366 V539")],
|
| 282 |
+
190: [('<rect x="658" y="694" width="266" height="58"', '<rect x="658" y="694" width="266" height="64"')],
|
| 283 |
+
# panel b: wider reverse-sampling box for the longer last line
|
| 284 |
+
262: [("H782", "H772")], 264: [("H782", "H772")], 266: [("H782", "H772")],
|
| 285 |
+
270: [('<rect x="790" y="1000" width="276" height="164"', '<rect x="780" y="1000" width="296" height="164"')],
|
| 286 |
+
275: [("M1066,1082 H1098", "M1076,1082 H1098")],
|
| 287 |
+
}
|
| 288 |
+
# Text lines: (new main font size, anchor mode, baseline shift in SVG units)
|
| 289 |
+
TEXT_A = {
|
| 290 |
+
31: (21, "c", 0), 32: (21, "c", 0), 33: (21, "c", 0), 37: (21, "c", 0), 38: (21, "c", 1),
|
| 291 |
+
42: (21, "c", -3), 44: (21, "c", -2),
|
| 292 |
+
43: (21, "c", -5, 128.0), # manuscript line sits ~5 units right of its box centre (128); re-centred
|
| 293 |
+
59: (20, "c", 0), 60: (20, "c", 0),
|
| 294 |
+
61: (21, "l", 0), 75: (21, "c", 0), 76: (21, "c", 0), 77: (21, "l", 0), 83: (21, "c", 0),
|
| 295 |
+
89: (21, "c", 0), 130: (21, "c", 3), 133: (21, "c", -1), 134: (21, "c", 1), 138: (21, "c", -2),
|
| 296 |
+
139: (21, "c", 4), 158: (21, "c", 0), 159: (21, "c", 0), 160: (21, "l", 0), 162: (21, "l", 0),
|
| 297 |
+
176: (21, "c", 0), 177: (21, "c", 0), 178: (21, "l", 0), 182: (21, "l", 0), 191: (21, "c", -1),
|
| 298 |
+
192: (21, "c", 4), 195: (21, "c", -3), 198: (21, "c", 0), 199: (21, "c", 0), 208: (21, "c", 0),
|
| 299 |
+
214: (21, "c", 0), 217: (21, "c", 0), 221: (21, "c", 0), 222: (21, "c", 0),
|
| 300 |
+
}
|
| 301 |
+
TEXT_B = {
|
| 302 |
+
234: (19, "c", 0), 251: (19, "c", 0), 256: (19, "c", 0), 257: (19, "c", 0), 259: (19, "c", -2),
|
| 303 |
+
260: (19, "c", 2), 278: (19, "c", 0), 287: (19, "c", 0), 295: (19, "c", 0), 303: (19, "c", 0),
|
| 304 |
+
311: (19, "c", 0), 312: (19, "c", 0), 314: (19, "c", 0),
|
| 305 |
+
}
|
| 306 |
+
# panel a: lines 17-223 (drop the letter "a" 14-16 and the legend 224-229); panel b: 232-315 (drop letter "b")
|
| 307 |
+
A_LINES = list(range(17, 224))
|
| 308 |
+
B_LINES = [230] + list(range(232, 316)) # 230 opens the panel-b group, 315 closes it
|
| 309 |
+
CROP_A = (18, 110, 1478, 777) # after widening; boxes span y 116-771
|
| 310 |
+
CROP_B = (18, 918, 1422, 1216) # connector lines at y 926 and 1208
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def build_svg(lines, rng, X, text_cfg, crop, width_in, drop_bg=True):
|
| 314 |
+
head = lines[:12] # xml decl .. defs .. outer <g>
|
| 315 |
+
x0, y0, x1, y1 = crop
|
| 316 |
+
vw, vh = x1 - x0, y1 - y0
|
| 317 |
+
h_in = width_in * vh / vw
|
| 318 |
+
head[1] = re.sub(r'width="[^"]*" height="[^"]*" viewBox="[^"]*"',
|
| 319 |
+
f'width="{width_in:.4f}in" height="{h_in:.4f}in" viewBox="{x0} {y0} {vw} {vh}"', head[1])
|
| 320 |
+
body = [f'<rect x="{x0}" y="{y0}" width="{vw}" height="{vh}" fill="#FFFFFF" stroke="none"/>']
|
| 321 |
+
infos = []
|
| 322 |
+
for ln in rng:
|
| 323 |
+
s = lines[ln - 1]
|
| 324 |
+
for old, new in EDITS.get(ln, []):
|
| 325 |
+
assert s.count(old) == 1, (ln, old)
|
| 326 |
+
s = s.replace(old, new)
|
| 327 |
+
if ln == 274: # panel b: cells differ by x_T and by the Bernoulli support draw (drawn read-out)
|
| 328 |
+
assert "the draw of" in s and 'font-size="18"' in s
|
| 329 |
+
s, w = run_line(1138.0, [("x", "i", False), ("T", "sub", False), ("and support draw differ", "n", True)],
|
| 330 |
+
"#5C6C74", 928.0)
|
| 331 |
+
infos.append(dict(line=ln, fs_old=18.0, fs_new=19.0, width_new=w, center_new=928.0,
|
| 332 |
+
text="x T and support draw differ (deck wording; manuscript: the draw of x T differs)"))
|
| 333 |
+
elif "<text" in s:
|
| 334 |
+
tgt, mode, dy, *fixed = text_cfg.get(ln, (None, "c", 0))
|
| 335 |
+
s, info = process_text_line(s, X, tgt, mode, dy, fixed[0] if fixed else None)
|
| 336 |
+
info["line"] = ln
|
| 337 |
+
infos.append(info)
|
| 338 |
+
elif X is not X_ID:
|
| 339 |
+
s = process_geometry_line(s, X)
|
| 340 |
+
body.append(s)
|
| 341 |
+
svg = "\n".join(head + body + ["</g></svg>"])
|
| 342 |
+
return svg, infos, h_in
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def render(svg, stem, width_in, outdir=None):
|
| 346 |
+
"""outdir: where the svg/png/pdf go (default figures/). Intermediate panels that only feed a composite go to a
|
| 347 |
+
temporary folder (2026-10-02: figures/ holds only what a slide shows)."""
|
| 348 |
+
out = FIG if outdir is None else Path(outdir)
|
| 349 |
+
p_svg = out / f"{stem}.svg"
|
| 350 |
+
p_svg.write_text(svg)
|
| 351 |
+
cairosvg.svg2png(bytestring=svg.encode(), write_to=str(out / f"{stem}.png"), dpi=300)
|
| 352 |
+
cairosvg.svg2pdf(bytestring=svg.encode(), write_to=str(out / f"{stem}.pdf"), dpi=72)
|
| 353 |
+
doc = fitz.open(out / f"{stem}.pdf")
|
| 354 |
+
wpt = doc[0].rect.width
|
| 355 |
+
doc.close()
|
| 356 |
+
assert abs(wpt - width_in * 72) < 1.0, (stem, wpt, width_in * 72)
|
| 357 |
+
return out / f"{stem}.png"
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
# ============================================================== corpus tables
|
| 361 |
+
def fmt_cells(v):
|
| 362 |
+
if v >= 1e7:
|
| 363 |
+
return f"{v / 1e6:.1f}M"
|
| 364 |
+
if v >= 1e6:
|
| 365 |
+
return f"{v / 1e6:.2f}M"
|
| 366 |
+
return f"{v / 1e3:.0f}K"
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def corpus_tables():
|
| 370 |
+
src = json.loads(SRC_MANIFEST.read_text())
|
| 371 |
+
idx = json.loads(IDX_MANIFEST.read_text())
|
| 372 |
+
cov = json.loads(COVERAGE.read_text())
|
| 373 |
+
con = json.loads(CONTRACT.read_text())
|
| 374 |
+
base, over, raw, nsrc = (defaultdict(int) for _ in range(4))
|
| 375 |
+
for s in src["source_audit"]:
|
| 376 |
+
d = s["dataset_id"]
|
| 377 |
+
base[d] += int(s["base_rows"])
|
| 378 |
+
over[d] += int(s["overlay_rows"])
|
| 379 |
+
raw[d] += int(s["raw_rows"])
|
| 380 |
+
nsrc[d] += 1
|
| 381 |
+
ds = pd.DataFrame({"dataset_id": list(base)})
|
| 382 |
+
ds["base_rows"] = ds["dataset_id"].map(base)
|
| 383 |
+
ds["overlay_rows"] = ds["dataset_id"].map(over)
|
| 384 |
+
ds["cells"] = ds["base_rows"] + ds["overlay_rows"]
|
| 385 |
+
assert (ds["cells"] == ds["dataset_id"].map(raw)).all()
|
| 386 |
+
# cross-check against the index shards used by the run (base + overlay shards)
|
| 387 |
+
sh = pd.read_csv(SHARD_OFFSETS).groupby("dataset_id")["n_cells"].sum()
|
| 388 |
+
assert (ds.set_index("dataset_id")["cells"] == sh.reindex(ds["dataset_id"]).values).all()
|
| 389 |
+
ds["n_source_files"] = ds["dataset_id"].map(nsrc)
|
| 390 |
+
ds["label"] = ds["dataset_id"].str.split("_").str[0].map(LABELS)
|
| 391 |
+
assert ds["label"].notna().all()
|
| 392 |
+
ds = ds.sort_values("cells", ascending=False).reset_index(drop=True)
|
| 393 |
+
ds["rank"] = np.arange(1, len(ds) + 1)
|
| 394 |
+
ds["source"] = (f"{SRC_MANIFEST} :: source_audit[].base_rows + overlay_rows (= raw_rows) summed by dataset_id; "
|
| 395 |
+
f"equals {SHARD_OFFSETS} n_cells by dataset_id")
|
| 396 |
+
total = int(ds["cells"].sum())
|
| 397 |
+
assert len(ds) == src["n_datasets"] == idx["n_datasets"] == 22
|
| 398 |
+
assert total == src["logical_cells"] == idx["n_cells"] == cov["source_cells_all_splits"]
|
| 399 |
+
assert int(ds["base_rows"].sum()) == src["base_cells"] and int(ds["overlay_rows"].sum()) == src["overlay_cells"]
|
| 400 |
+
ds[["rank", "label", "cells", "base_rows", "overlay_rows", "n_source_files", "dataset_id", "source"]].to_csv(
|
| 401 |
+
DATA / "sec01_corpus_datasets.csv", index=False)
|
| 402 |
+
|
| 403 |
+
kq = idx["k_quotas_per_epoch"]
|
| 404 |
+
kk = pd.DataFrame({"K": [f"{k:,}" for k in idx["k_values"]], "k_weight": idx["k_weights"],
|
| 405 |
+
"recipes_per_epoch": [float(kq[str(k)]) for k in idx["k_values"]],
|
| 406 |
+
"recipes_per_epoch_min": [int(kq[str(k)]) for k in idx["k_values"]],
|
| 407 |
+
"recipes_per_epoch_max": [int(kq[str(k)]) for k in idx["k_values"]],
|
| 408 |
+
"kind": "registered K grid"})
|
| 409 |
+
kk["source"] = f"{IDX_MANIFEST} :: k_values, k_weights, k_quotas_per_epoch"
|
| 410 |
+
assert int(kk["recipes_per_epoch"].sum()) == idx["train_recipes_per_epoch"]
|
| 411 |
+
|
| 412 |
+
pairing = con["pairing"]
|
| 413 |
+
cat = con["coverage_after_topup"]
|
| 414 |
+
reg = pairing["registered_recipes_per_epoch"]
|
| 415 |
+
per_ep = np.array(pairing["total_recipe_counts_by_epoch"]) - reg
|
| 416 |
+
slot = pd.DataFrame(cat["slot_coverage"])
|
| 417 |
+
assert (np.sort(per_ep) == np.sort(slot["topup_recipes"].values)).all()
|
| 418 |
+
assert int(per_ep.sum()) == cat["topup_recipes"]
|
| 419 |
+
tu = pd.read_csv(TOPUP_CSV)
|
| 420 |
+
assert len(tu) == cat["topup_recipes"] and tu["is_topup"].all() and (tu["split"] == "train").all()
|
| 421 |
+
topup = dict(n=int(len(tu)), k_min=int(tu["k"].min()), k_max=int(tu["k"].max()),
|
| 422 |
+
k_median=float(tu["k"].median()), n_k_below_250=int((tu["k"] < 250).sum()),
|
| 423 |
+
per_epoch_mean=float(per_ep.mean()), per_epoch_min=int(per_ep.min()), per_epoch_max=int(per_ep.max()),
|
| 424 |
+
target_cells=int(cat["topup_target_cells"]), train_cells=int(cat["train_universe_cells"]),
|
| 425 |
+
coverage=float(cat["train_cell_coverage_after_topup"]),
|
| 426 |
+
recipes_by_epoch_min=int(min(pairing["total_recipe_counts_by_epoch"])),
|
| 427 |
+
recipes_by_epoch_max=int(max(pairing["total_recipe_counts_by_epoch"])))
|
| 428 |
+
kk = pd.concat([kk, pd.DataFrame([{
|
| 429 |
+
"K": "top-up", "k_weight": np.nan, "recipes_per_epoch": topup["per_epoch_mean"],
|
| 430 |
+
"recipes_per_epoch_min": topup["per_epoch_min"], "recipes_per_epoch_max": topup["per_epoch_max"],
|
| 431 |
+
"kind": f"top-up, K {topup['k_min']}-{topup['k_max']:,} (mean over 16 epochs)",
|
| 432 |
+
"source": f"{CONTRACT} :: pairing.total_recipe_counts_by_epoch - registered_recipes_per_epoch; {TOPUP_CSV} :: k"}])],
|
| 433 |
+
ignore_index=True)
|
| 434 |
+
kk.to_csv(DATA / "sec01_recipe_k.csv", index=False)
|
| 435 |
+
meta = {"n_datasets": src["n_datasets"], "cells": total, "base_cells": src["base_cells"],
|
| 436 |
+
"overlay_cells": src["overlay_cells"], "train_recipes_per_epoch": idx["train_recipes_per_epoch"],
|
| 437 |
+
"train_recipe_pool_size": idx["train_recipe_pool_size"], "max_disjoint_epochs": idx["max_disjoint_epochs"],
|
| 438 |
+
"split_unit": idx["split_unit"], "split_fractions": idx["split_fractions"],
|
| 439 |
+
"corpus_fingerprint": idx["corpus_fingerprint"], "topup": topup,
|
| 440 |
+
"all_members_targets": cov["all_k_member_occurrences_become_targets"],
|
| 441 |
+
"original_target_exposures": con["coverage_after_topup"]["original_target_exposures"],
|
| 442 |
+
"observed_target_cells_by_epoch": con["observed_target_cells_by_epoch"]}
|
| 443 |
+
return ds, kk, meta
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def overlaps(fig, texts):
|
| 447 |
+
fig.canvas.draw()
|
| 448 |
+
r = fig.canvas.get_renderer()
|
| 449 |
+
bbs = [(t.get_text(), t.get_window_extent(r)) for t in texts if t.get_text()]
|
| 450 |
+
bad = []
|
| 451 |
+
for i in range(len(bbs)):
|
| 452 |
+
for j in range(i + 1, len(bbs)):
|
| 453 |
+
if bbs[i][1].overlaps(bbs[j][1]):
|
| 454 |
+
bad.append((bbs[i][0], bbs[j][0]))
|
| 455 |
+
return bad
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def draw_corpus(fig, W, H, y0, h, ds, kk, meta, fs=12):
|
| 459 |
+
"""Corpus panels placed in inches: two sorted dataset columns on one shared log scale (values printed,
|
| 460 |
+
no axis), then recipes per epoch by K. y0 = bottom of the bar area, h = its height (inches)."""
|
| 461 |
+
half = int(np.ceil(len(ds) / 2))
|
| 462 |
+
parts = [ds.iloc[:half], ds.iloc[half:]]
|
| 463 |
+
lo, hi = 1e4, 3e7
|
| 464 |
+
cols = [(2.2, 2.35), (7.2, 2.35)] # (left, width) in inches
|
| 465 |
+
texts = []
|
| 466 |
+
for (left, width), part in zip(cols, parts):
|
| 467 |
+
ax = fig.add_axes([left / W, y0 / H, width / W, h / H])
|
| 468 |
+
y = np.arange(len(part))
|
| 469 |
+
ax.barh(y, part["cells"], color=style.GREY, height=0.66)
|
| 470 |
+
for yi, v in zip(y, part["cells"]):
|
| 471 |
+
texts.append(ax.text(v * 1.2, yi, fmt_cells(v), va="center", ha="left", fontsize=fs, color=style.INK))
|
| 472 |
+
ax.set_xscale("log")
|
| 473 |
+
ax.set_xlim(lo, hi)
|
| 474 |
+
ax.set_ylim(half - 0.5, -0.5)
|
| 475 |
+
ax.set_yticks(y)
|
| 476 |
+
ax.set_yticklabels(part["label"], fontsize=fs)
|
| 477 |
+
texts += ax.get_yticklabels()
|
| 478 |
+
ax.tick_params(axis="y", length=0, pad=4)
|
| 479 |
+
ax.set_xticks([])
|
| 480 |
+
ax.minorticks_off()
|
| 481 |
+
for sp in ("left", "bottom"):
|
| 482 |
+
ax.spines[sp].set_visible(False)
|
| 483 |
+
t = meta["topup"]
|
| 484 |
+
texts.append(fig.text((cols[0][0] + cols[1][0] + cols[1][1]) / 2 / W, (y0 - 0.1) / H,
|
| 485 |
+
f"cells per dataset (log scale) · {meta['n_datasets']} datasets · "
|
| 486 |
+
f"{fmt_cells(meta['cells'])} cells · {fmt_cells(t['train_cells'])} in train split",
|
| 487 |
+
ha="center", va="top", fontsize=fs + 1))
|
| 488 |
+
|
| 489 |
+
ax = fig.add_axes([10.75 / W, y0 / H, 0.95 / W, h / H])
|
| 490 |
+
y = np.arange(len(kk))
|
| 491 |
+
is_top = (kk["K"] == "top-up").values
|
| 492 |
+
ax.barh(y[~is_top], kk.loc[~is_top, "recipes_per_epoch"], color=style.INK, height=0.62)
|
| 493 |
+
ax.barh(y[is_top], kk.loc[is_top, "recipes_per_epoch"], color=style.GREY, height=0.62)
|
| 494 |
+
vmax = kk["recipes_per_epoch"].max()
|
| 495 |
+
for yi, v, top in zip(y, kk["recipes_per_epoch"], is_top):
|
| 496 |
+
lab = f"~{v:.0f}" if top else f"{v:,.0f}"
|
| 497 |
+
texts.append(ax.text(v + vmax * 0.05, yi, lab, va="center", ha="left", fontsize=fs))
|
| 498 |
+
ax.set_ylim(len(kk) - 0.5, -0.5)
|
| 499 |
+
ax.set_yticks(y)
|
| 500 |
+
ax.set_yticklabels(kk["K"], fontsize=fs)
|
| 501 |
+
texts += ax.get_yticklabels()
|
| 502 |
+
ax.tick_params(axis="y", length=0, pad=4)
|
| 503 |
+
ax.set_xlim(0, vmax * 1.02)
|
| 504 |
+
ax.set_xticks([])
|
| 505 |
+
for sp in ("left", "bottom"):
|
| 506 |
+
ax.spines[sp].set_visible(False)
|
| 507 |
+
ax.set_ylabel("K cells / recipe", fontsize=fs + 1, labelpad=6)
|
| 508 |
+
texts.append(ax.yaxis.label)
|
| 509 |
+
texts.append(fig.text((10.75 + 0.5) / W, (y0 - 0.1) / H, "recipes / epoch", ha="center", va="top", fontsize=fs + 1))
|
| 510 |
+
return texts
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def main():
|
| 514 |
+
FIG.mkdir(exist_ok=True)
|
| 515 |
+
DATA.mkdir(exist_ok=True)
|
| 516 |
+
lines = FIG1_SVG.read_text().split("\n")
|
| 517 |
+
assert len(lines) >= 316 and lines[230].startswith('<text x="24" y="914"') and 'y="813"' in lines[225]
|
| 518 |
+
|
| 519 |
+
# ---------- panel a (slide b) and panel b (slide a) deck copies
|
| 520 |
+
a_w = A_HEIGHT_IN * (CROP_A[2] - CROP_A[0]) / (CROP_A[3] - CROP_A[1])
|
| 521 |
+
svg_a, info_a, _ = build_svg(lines, A_LINES, X_A, TEXT_A, CROP_A, a_w)
|
| 522 |
+
render(svg_a, "sec01_fig1a_denoiser", a_w)
|
| 523 |
+
svg_b, info_b, b_h = build_svg(lines, B_LINES, X_ID, TEXT_B, CROP_B, W_FULL)
|
| 524 |
+
import tempfile
|
| 525 |
+
tmp = Path(tempfile.mkdtemp(prefix="sec01_")) # panel b only feeds the slide (a) composite
|
| 526 |
+
b_png = render(svg_b, "sec01_fig1b_inference", W_FULL, outdir=tmp)
|
| 527 |
+
|
| 528 |
+
# on-slide point size of every text line
|
| 529 |
+
pt_a = A_HEIGHT_IN * 72 / (CROP_A[3] - CROP_A[1])
|
| 530 |
+
pt_b = W_FULL * 72 / (CROP_B[2] - CROP_B[0])
|
| 531 |
+
rows = [dict(panel="a (slide b)", placed_in=f"{a_w:.2f} x {A_HEIGHT_IN:.2f}", pt_per_unit=pt_a, **i) for i in info_a]
|
| 532 |
+
rows += [dict(panel="b (slide a)", placed_in=f"{W_FULL:.2f} x {b_h:.3f}", pt_per_unit=pt_b, **i) for i in info_b]
|
| 533 |
+
lab = pd.DataFrame(rows)
|
| 534 |
+
lab["pt_on_slide"] = lab["fs_new"] * lab["pt_per_unit"]
|
| 535 |
+
lab = lab[["panel", "line", "text", "fs_old", "fs_new", "pt_on_slide", "width_new", "center_new", "placed_in", "pt_per_unit"]]
|
| 536 |
+
lab.to_csv(DATA / "sec01_fig1_label_pt.csv", index=False)
|
| 537 |
+
|
| 538 |
+
# ---------- corpus
|
| 539 |
+
ds, kk, meta = corpus_tables()
|
| 540 |
+
W = W_FULL
|
| 541 |
+
fig = plt.figure(figsize=(W, 2.75))
|
| 542 |
+
texts = draw_corpus(fig, W, 2.75, 0.45, 2.2, ds, kk, meta)
|
| 543 |
+
bad = overlaps(fig, texts)
|
| 544 |
+
assert not bad, bad
|
| 545 |
+
plt.close(fig) # standalone corpus panel: layout check only; the slide shows it inside sec01_slide_a
|
| 546 |
+
|
| 547 |
+
# ---------- slide (a) composite: exactly 12.3 x 5.3 in, panel b redraw on top
|
| 548 |
+
H = SLIDE_A_H
|
| 549 |
+
img = plt.imread(b_png)
|
| 550 |
+
fig = plt.figure(figsize=(W, H))
|
| 551 |
+
ax_img = fig.add_axes([0, 1 - b_h / H, 1, b_h / H])
|
| 552 |
+
ax_img.imshow(img, interpolation="lanczos")
|
| 553 |
+
ax_img.set_axis_off()
|
| 554 |
+
y0 = 0.45
|
| 555 |
+
texts = draw_corpus(fig, W, H, y0, H - b_h - 0.16 - y0, ds, kk, meta)
|
| 556 |
+
bad = overlaps(fig, texts)
|
| 557 |
+
assert not bad, bad
|
| 558 |
+
r = fig.canvas.get_renderer()
|
| 559 |
+
for t in texts: # every corpus label stays on the canvas
|
| 560 |
+
bb = t.get_window_extent(r)
|
| 561 |
+
assert bb.x0 >= 0 and bb.x1 <= W * fig.dpi and bb.y0 >= 0, t.get_text()
|
| 562 |
+
with plt.rc_context({"savefig.bbox": "standard"}): # keep the canvas at exactly 12.3 x 5.3 in
|
| 563 |
+
for ext in ("png", "pdf"):
|
| 564 |
+
fig.savefig(FIG / f"sec01_slide_a.{ext}", dpi=300)
|
| 565 |
+
plt.close(fig)
|
| 566 |
+
|
| 567 |
+
# ---------- numbers used on the slides, with sources
|
| 568 |
+
cfg = json.loads(CFG.read_text())
|
| 569 |
+
st = json.loads(STATUS.read_text())
|
| 570 |
+
idx = json.loads(IDX_MANIFEST.read_text())
|
| 571 |
+
con = json.loads(CONTRACT.read_text())
|
| 572 |
+
hd = cfg["model"]["hidden_dims"]
|
| 573 |
+
blocks = hd + hd[-2::-1]
|
| 574 |
+
assert "descending half of the symmetric MLP" in MODEL_PY.read_text()
|
| 575 |
+
meth = METHODS.read_text().split("\n")
|
| 576 |
+
assert "Generation used EMA weights and 50 deterministic DDIM steps ($\\eta=0$)" in meth[57]
|
| 577 |
+
assert "The drawn read-out is implemented in the standalone sampler that generated every set scored in this paper" in meth[98]
|
| 578 |
+
t = meta["topup"]
|
| 579 |
+
nums = [
|
| 580 |
+
("n_datasets", meta["n_datasets"], f"{SRC_MANIFEST} :: n_datasets (= {IDX_MANIFEST} :: n_datasets)"),
|
| 581 |
+
("corpus_cells", meta["cells"], f"{SRC_MANIFEST} :: logical_cells = base_cells + overlay_cells (= {IDX_MANIFEST} :: n_cells; = {COVERAGE} :: source_cells_all_splits)"),
|
| 582 |
+
("corpus_base_cells", meta["base_cells"], f"{SRC_MANIFEST} :: base_cells"),
|
| 583 |
+
("corpus_overlay_cells", meta["overlay_cells"], f"{SRC_MANIFEST} :: overlay_cells"),
|
| 584 |
+
("train_split_cells", t["train_cells"], f"{CONTRACT} :: coverage_after_topup.train_universe_cells"),
|
| 585 |
+
("split", f"{idx['split_unit']} {idx['split_fractions']}", f"{IDX_MANIFEST} :: split_unit, split_fractions"),
|
| 586 |
+
("k_values", " ".join(str(k) for k in idx["k_values"]), f"{IDX_MANIFEST} :: k_values"),
|
| 587 |
+
("registered_recipes_per_epoch", idx["train_recipes_per_epoch"], f"{IDX_MANIFEST} :: train_recipes_per_epoch"),
|
| 588 |
+
("train_recipe_pool_size", idx["train_recipe_pool_size"], f"{IDX_MANIFEST} :: train_recipe_pool_size"),
|
| 589 |
+
("max_disjoint_epochs", idx["max_disjoint_epochs"], f"{IDX_MANIFEST} :: max_disjoint_epochs (schedule_slots)"),
|
| 590 |
+
("topup_recipes_total", t["n"], f"{CONTRACT} :: coverage_after_topup.topup_recipes (= rows of {TOPUP_CSV})"),
|
| 591 |
+
("topup_recipes_per_epoch_mean_min_max", f"{t['per_epoch_mean']:.1f} {t['per_epoch_min']} {t['per_epoch_max']}", f"{CONTRACT} :: pairing.total_recipe_counts_by_epoch - pairing.registered_recipes_per_epoch"),
|
| 592 |
+
("recipes_per_epoch_actual_min_max", f"{t['recipes_by_epoch_min']} {t['recipes_by_epoch_max']}", f"{CONTRACT} :: pairing.total_recipe_counts_by_epoch"),
|
| 593 |
+
("topup_k_min_median_max", f"{t['k_min']} {t['k_median']:.0f} {t['k_max']}", f"{TOPUP_CSV} :: k"),
|
| 594 |
+
("topup_recipes_k_below_250", t["n_k_below_250"], f"{TOPUP_CSV} :: k < 250"),
|
| 595 |
+
("train_cell_coverage_after_topup", t["coverage"], f"{CONTRACT} :: coverage_after_topup.train_cell_coverage_after_topup"),
|
| 596 |
+
("all_member_cells_are_targets", meta["all_members_targets"], f"{COVERAGE} :: all_k_member_occurrences_become_targets"),
|
| 597 |
+
("target_cells_per_epoch_min_max", f"{min(meta['observed_target_cells_by_epoch'])} {max(meta['observed_target_cells_by_epoch'])}", f"{CONTRACT} :: observed_target_cells_by_epoch"),
|
| 598 |
+
("corpus_fingerprint_matches_run", idx["corpus_fingerprint"] == st["corpus_fingerprint"] == con["pairing"]["source_corpus_fingerprint"],
|
| 599 |
+
f"{IDX_MANIFEST} :: corpus_fingerprint vs {STATUS} :: corpus_fingerprint and {CONTRACT} :: pairing.source_corpus_fingerprint"),
|
| 600 |
+
("n_genes", cfg["data"]["n_genes"], f"{CFG} :: data.n_genes (= {STATUS} :: n_genes)"),
|
| 601 |
+
("condition_dim", st["condition_dim"], f"{STATUS} :: condition_dim (= 3G+6)"),
|
| 602 |
+
("parameters", st["parameters"], f"{STATUS} :: parameters"),
|
| 603 |
+
("hidden_dims_descending_half", "-".join(map(str, hd)), f"{CFG} :: model.hidden_dims ({MODEL_PY} SparseDenoiserConfig: descending half of a symmetric skip MLP)"),
|
| 604 |
+
("denoiser_blocks", f"{len(blocks)} blocks: {'-'.join(map(str, blocks))}", f"derived: hidden_dims + reversed(hidden_dims[:-1]); matches Fig. 1a '7 blocks + skip sums'"),
|
| 605 |
+
("context_dim", cfg["model"]["context_dim"], f"{CFG} :: model.context_dim"),
|
| 606 |
+
("time_embedding_dim", cfg["model"]["time_embedding_dim"], f"{CFG} :: model.time_embedding_dim"),
|
| 607 |
+
("sampler", "EMA weights, 50 DDIM steps, eta 0", f"{METHODS} l.58"),
|
| 608 |
+
("support_readout", "drawn (Bernoulli): keep gene g if u < sigmoid(logit); used for every scored set", f"{METHODS} l.99 (Support read-out)"),
|
| 609 |
+
("ema_decay", cfg["training"]["ema_decay"], f"{CFG} :: training.ema_decay"),
|
| 610 |
+
("epochs_completed", st["epochs_completed"], f"{STATUS} :: epochs_completed (= 16 disjoint schedule slots; {IDX_MANIFEST} :: schedule_slots)"),
|
| 611 |
+
("status", st["status"], f"{STATUS} :: status"),
|
| 612 |
+
]
|
| 613 |
+
assert cfg["data"]["n_genes"] == st["n_genes"]
|
| 614 |
+
assert st["condition_dim"] == 3 * st["n_genes"] + 6
|
| 615 |
+
assert st["epochs_completed"] == idx["schedule_slots"] == idx["max_disjoint_epochs"] == 16
|
| 616 |
+
assert idx["train_recipes_per_epoch"] * idx["schedule_slots"] == idx["train_recipe_pool_size"]
|
| 617 |
+
assert meta["original_target_exposures"] == sum(int(k) * int(v) for k, v in zip(
|
| 618 |
+
idx["k_values"], [idx["k_quotas_per_epoch"][str(k)] for k in idx["k_values"]])) * idx["schedule_slots"]
|
| 619 |
+
pd.DataFrame(nums, columns=["key", "value", "source"]).to_csv(DATA / "sec01_model_numbers.csv", index=False)
|
| 620 |
+
|
| 621 |
+
print(f"panel a placed {a_w:.2f} x {A_HEIGHT_IN} in, {pt_a:.4f} pt/unit; panel b {W_FULL} x {b_h:.3f} in, {pt_b:.4f} pt/unit")
|
| 622 |
+
for p, g in lab.groupby("panel"):
|
| 623 |
+
g = g.sort_values("pt_on_slide")
|
| 624 |
+
print(p, "min label pt", round(g["pt_on_slide"].min(), 2), "|", g.iloc[0]["text"][:40])
|
| 625 |
+
print("datasets", meta["n_datasets"], "cells", meta["cells"], fmt_cells(meta["cells"]))
|
| 626 |
+
print(ds[["label", "cells"]].to_string(index=False))
|
| 627 |
+
print(kk[["K", "recipes_per_epoch", "recipes_per_epoch_min", "recipes_per_epoch_max"]].to_string(index=False))
|
| 628 |
+
for k, v, _ in nums:
|
| 629 |
+
print(k, v)
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
if __name__ == "__main__":
|
| 633 |
+
main()
|