junidude14 commited on
Commit
fe00bc1
·
verified ·
1 Parent(s): 9e0a3fe

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scores_contrast/README.md ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # scores_contrast: rank-based, threshold-free and reliability-aware disease-signal metrics (added 2026-10-02)
2
+
3
+ Written by `tools/contrast_extra.py` (CPU only, never imports torch; R part `tools/contrast_extra_limma.R`; launcher
4
+ `tools/run_contrast_unit.sh`; tables `tools/contrast_extra_tables.py`; tests `tests/test_contrast_extra.py`, 18 passed).
5
+ Code copies by sha: `_code/`. Nothing under `scores/`, `scores_nosex/`, `scores_extra/` or `generated/` was modified.
6
+ Compact results: `TABLES.md`. Reproduction check: `reproduction_check.csv`.
7
+
8
+ ## Scope
9
+
10
+ Every unit re-reads one existing `score_ft.py` scoring call exactly as it was scored and rebuilds the per-cell-type
11
+ case-vs-control quantities with the scorer's own functions (`ft_common`, `score_ft`, `evaluate_generated_vs_truth`).
12
+
13
+ | design | unit (output dir) | source call(s) | arms |
14
+ |---|---|---|---|
15
+ | few-pair | `<ds>/fewshot_n5/draw<j>/`, 4 cohorts x 5 draws | `scores/<ds>/fewshot_n5/draw<j>` + `draw<j>_scsemi5` (Giroux: `scores_nosex/`) | `zs_raw`, `zs_pseudo` (reference), `zs_cal`, `lora5`, `scsemi5` |
16
+ | 5-fold pooled | `<ds>/pooled/` | `scores/<ds>/pooled` (Giroux: `scores_nosex/giroux2022/pooled`; sepsis: `scores/ye2026_sepsis/pooled_deg`, the DEG source of the deck, whose contrast is also checked against `scores/ye2026_sepsis/pooled`) | all arms of the call (sepsis 13, including the LoRA learning-curve subsets `lora_n{5,10,20,40}__raw`) |
17
+ | learning curve (sepsis) | `ye2026_sepsis/cal_budget_20261001/pooled/` (+ the sepsis pooled unit) | `scores/ye2026_sepsis/cal_budget_20261001/pooled` | `zs__cal_n{5,10,20,40}` |
18
+
19
+ Cohorts with a contrast: Sepsis (sepsis vs control), Imperial ESKD (COVID+ vs COVID−), Giroux (severe vs mild; the 196
20
+ sex-linked genes of `data/sex_linked_genes/sex_linked_genes_exclude.csv` are excluded exactly as in `scores_nosex/`,
21
+ 65 of them scoring genes, 5,563 → 5,498), Ji ChILI (ChILI vs ICI controls). **ImMicro has no case-control contrast
22
+ and is not covered.** Not covered because they do not exist yet: the scSemiProfiler 5-fold CV (`scsemi_cv_20261002`)
23
+ and equal-budget (`scsemi_budget_20261002`) calls; so scSemiProfiler appears only in the few-pair design. Not requested
24
+ and not run: `scores/ye2026_sepsis/lora_rank_20261001/pooled` (runnable with `--design scored`).
25
+
26
+ Adding an arm later (for example a length-corrected zero-shot arm scored by `score_ft.py` into a new call dir):
27
+
28
+ tools/run_contrast_unit.sh NAME 4 16 JOBFILE # JOBFILE line:
29
+ --design scored --dataset ye2026_sepsis --score-dir scores/ye2026_sepsis/<new call> --arms <arm> --unit <new sub-path>
30
+ tools/contrast_extra.py --collect && tools/contrast_extra_tables.py
31
+
32
+ For Giroux pass a `scores_nosex/...` call (its exclusion is applied and checked), or `--exclude-genes
33
+ data/sex_linked_genes/sex_linked_genes_exclude.csv` for a call scored without it (then the reproduction check is
34
+ marked not comparable). The tool refuses a Giroux call without any exclusion unless `--allow-sex-genes`.
35
+
36
+ ## Inputs re-used exactly (checked per unit)
37
+
38
+ - Reference cache `scoring_cache/<ds>/reference.npz` (sha = the call's `reference_sha256`) and `deg_reference.npz`;
39
+ scored samples, case/control vectors and groups from the call's `summary.json` (`contrast_definition`, re-derived and
40
+ compared).
41
+ - Generated cells: the scored NPZ (sha256 = `per_arm.npz_sha256`, receipt `output_sha256` verified by
42
+ `score_ft.open_arm`). NPZs that live on server_2 (Imperial, sepsis pooled, cal-budget) were rsynced to
43
+ `_fetch_tmp/`, sha-checked against the summary and the `.moved` marker, and deleted after use. One Poisson read-out of
44
+ the whole NPZ (seed 20260916, `poisson_integerise`, chunk 4,096), the scored rows; rows, donors and labels must equal
45
+ the call's `arms/<arm>/generated_cells.parquet` and `labels/labels.parquet`.
46
+ - Condition bulk (broadcast): the call's `condition_for_broadcast` file (sha-checked, fetched when remote).
47
+
48
+ ## Definitions
49
+
50
+ Cell types: contrast metrics T, B, Monocyte, NK (`F.CONTRAST_TYPES`); DEG metrics also DC. Genes per contrast type =
51
+ scoring genes detected in >= 1 % of the scored samples' observed cells of the type, minus the excluded genes (the
52
+ scorer's rule); DEG metrics use all kept scoring genes.
53
+
54
+ 1. **Spearman r** (`contrast.csv`): Pearson r of the average-tie ranks of the generated and observed logFC vectors,
55
+ same genes and statistics as the scorer. Primary statistic `mean_cp10k` (per-cell CP10K, donor mean, donor-balanced
56
+ group mean, log2(case + 1) − log2(control + 1)); `pseudobulk_log1p_cpm` also given. `pearson_r_*`, `partial_r_*`
57
+ and `r_generated_vs_broadcast` are recomputed with `F.contrast_scores` and stored next to the scorer's value
58
+ (`*_scorer`). Broadcast = the logFC of the arm's condition bulk (`F.bulk_lfc`), same genes. `mean4` rows = nan-mean
59
+ over the four types (the scorer's headline).
60
+ 2. **Split-half ceiling** (`ceiling.csv`, arm-independent): each scored sample's observed cells of each contrast type
61
+ (canonical reference order, frozen observed labels; the rebuilt full-data donor x type aggregates must equal the
62
+ cache) are split into halves: per sample x type a permutation from `default_rng([seed, uint64 LE of
63
+ sha256("<sample>|<type>")[:8]])`, half A = first floor(n/2) positions, B = the rest; seeds 20260926–20260930 (the
64
+ SLE split-half seeds, `utility_studies_final6k_20260925/sle_broadcast`). `mean_cp10k` logFC of A and of B with the
65
+ same genes and donor balancing → r(A, B) (Pearson, Spearman; mean and SD over the 5 seeds). Spearman–Brown
66
+ full-data reliability `2r/(1+r)` and the noise-free ceiling `sqrt(2r/(1+r))` (the expected r of a predictor that
67
+ equals the true logFC with the full-data observed vector) from the seed-mean r; `mean4` = mean over the types of the
68
+ per-type values. On the same footing: `generated:<arm>` = r(generated full logFC, half-B logFC) and
69
+ `broadcast:<condition>` = r(bulk logFC, half B).
70
+ 3. **limma-voom DEG sensitivity** (`deg_limma.csv`, `method` = `limma_voom_nonzero` | `limma_voom_filterByExpr`;
71
+ Welch rows `method = welch`): the same donor x type pseudobulks the scorer's Welch top-50 uses (rows = samples of
72
+ the two groups with >= 1 cell of the type; observed = summed observed counts; generated = **summed Poisson read-out
73
+ counts of the generated cells**, which is what `score_ft.deg_block` feeds the Welch test — not summed
74
+ `generated_counts` rates; broadcast = the arm's condition `bulk_counts`, case | control samples, one list for all
75
+ types). Per side: gene filter on that side's columns ("nonzero" = rowSums > 0, the default gene filter of the
76
+ evaluator's edgeR backend, primary; "filterByExpr" = `edgeR::filterByExpr(y, design)`, secondary),
77
+ `y[keep, , keep.lib.sizes = FALSE]`, `calcNormFactors(method = "TMM")`, `voom`, `lmFit`, `eBayes`,
78
+ `topTable(coef = case − control, sort.by = "none")`; BH over the tested genes; list = `EV.top_deg_genes`
79
+ (adj.P < 0.05, descending |logFC|, first 50). `overlap` = |observed list ∩ generated list|; headline sums over the
80
+ types whose observed test is defined (>= 2 samples per group), an undefined generated test scores 0 (the
81
+ benchmark's rule). `n_sig_*` = genes at FDR < 0.05; `n_tested_*` = genes in the BH family. Versions: R 4.5.2,
82
+ limma 3.66.0, edgeR 4.8.1 (`limma/versions.txt` per unit). The Welch rows recompute the scorer's top-50 overlap with
83
+ `score_ft.deg_block` and must equal the call's `contrast.csv` and `deg_top50_lists.csv` exactly.
84
+ 4. **CAT** (`cat.csv`) and **RBO** (`rbo.csv`), on the primary limma results: per type, every tested gene ranked by
85
+ |moderated t| (ties keep the fixed gene order). CAT(k) = |observed top-k ∩ predictor top-k with the same logFC
86
+ sign| / k (`cat_same_sign`; `cat_any_sign` without the sign requirement), k = 10, 20, 50, 100, 200, 500. Chance for a
87
+ random ranking with a random sign: **k / (2 G)** (any sign: k / G), G = genes tested on both sides (`G_both`).
88
+ RBO_ext (Webber et al. 2010, eq. 32; eq. 30 for equal lengths; implemented here and unit-tested against the
89
+ defining sum) with p = 0.98 of the signed rankings, `rbo_ext_t_desc` = rank by t descending (up-regulated genes
90
+ first; the headline), `rbo_ext_t_asc` = t ascending, `rbo_ext_mean_up_down` their mean. With p = 0.98 the top 50 ranks carry
91
+ 85 % of the weight and the top 100 carry 96 % (Webber et al. eq. 21). Predictors: `generated:<arm>` and `broadcast:<condition>` (bulk ranked by its
92
+ own limma t). An undefined predictor test scores 0.
93
+ 5. **Chance level of a top-50 overlap** (`chance_overlap`, Welch and limma): hypergeometric mean |obs list| x |pred
94
+ list| / G per type (G = genes tested on both sides), summed over the scored types like the overlap.
95
+
96
+ ## Files
97
+
98
+ Per unit: `contrast.csv`, `ceiling.csv`, `deg_limma.csv`, `cat.csv`, `rbo.csv`, `headline.csv` (one row per arm: the
99
+ numbers of TABLES.md), `repro.json`, `manifest.json` (inputs, shas, params, R versions, runtimes), `limma/{jobs.csv,
100
+ limma_status.csv, versions.txt, R.log}`.
101
+ Collected (`contrast_extra.py --collect`): `{fewshot,pooled,scored}_{contrast,ceiling,deg_limma,cat,rbo,headline}.csv`
102
+ (`scored` = the cal-budget unit), `fewshot_summary.csv` (mean / SD over draws), `learning_curve_*.csv` (sepsis:
103
+ zs__raw, zs__cal, lora_n5..40, real_lora from the pooled unit + zs__cal_n5..40 from the cal-budget unit),
104
+ `reproduction_check.csv`, `run_time.csv`; `contrast_extra_tables.py`: `TABLES.md`, `compact_*.csv`. Logs: `_logs/`.
105
+
106
+ ## References
107
+
108
+ - Squair JW et al. Confronting false discoveries in single-cell differential expression. *Nat Commun* 12:5692 (2021)
109
+ (pseudobulk DE; top-k concordance and signed-statistic rank correlation against matched bulk).
110
+ - Li et al. Systematic comparison of single-cell perturbation response prediction models. *Sci Adv* 12:eaed3414 (2026)
111
+ (top-N DEG overlap with BH Padj < 0.05 ranked by |logFC|, N = 10–500, next to an effect-size correlation).
112
+ - Webber W, Moffat A, Zobel J. A similarity measure for indefinite rankings. *ACM TOIS* 28(4):20 (2010) (RBO).
113
+ - Irizarry RA et al. Multiple-laboratory comparison of microarray platforms. *Nat Methods* 2:345 (2005) (CAT plots).
114
+ - Law CW, Chen Y, Shi W, Smyth GK. voom: precision weights unlock linear model analysis tools for RNA-seq read counts.
115
+ *Genome Biol* 15:R29 (2014).
116
+ - Ritchie ME et al. limma powers differential expression analyses for RNA-sequencing and microarray studies.
117
+ *Nucleic Acids Res* 43:e47 (2015).
118
+ - Robinson MD, McCarthy DJ, Smyth GK. edgeR: a Bioconductor package for differential expression analysis of digital
119
+ gene expression data. *Bioinformatics* 26:139 (2010); TMM: Robinson MD, Oshlack A. *Genome Biol* 11:R25 (2010).
120
+ - Viñas Torné R et al. Systema: perturbation response prediction beyond systematic variation. *Nat Biotechnol* 44:1050
121
+ (2026) (shared systematic variation inflates correlation metrics; the analogue of the broadcast baseline / partial r).
122
+ - Spearman C (1910), Brown W (1910), *Br J Psychol* 3 (split-half reliability correction).
123
+
124
+ ## Run (2026-10-02, server_1, CPU only)
125
+
126
+ 25 units (4 cohorts x 5 few-pair draws, 4 pooled calls, 1 cal-budget call), 135 unit x arm rows, one code version for all
127
+ (`_code/contrast_extra.b1ae7ded9451.py`, `_code/contrast_extra_limma.f0685f68ddfc.R`). Three systemd user units in
128
+ parallel, 4 threads each (`_logs/`): Imperial 27.6 min (26 files, 97.7 GiB fetched from server_2, peak RSS 11.2 GB), sepsis
129
+ 18.5 min (24 files, 46.9 GiB fetched, peak 13.2 GB), Giroux + Ji 5.9 min (peak 3.9 GB); 15:26:49–15:54:34 wall. Per-unit times: `run_time.csv`.
130
+ Fetched server_2 copies were deleted after use.
131
+
132
+ ## Reproduction check (`reproduction_check.csv`, per unit `repro.json`): all 135 pass
133
+
134
+ - Pearson r (generated and broadcast), partial r and r(generated, broadcast), both statistics, all types: max |diff|
135
+ vs the call's `contrast.csv` = 9.9e-17; gene counts equal.
136
+ - Welch top-50: every list in `deg_top50_lists.csv` (observed, generated, broadcast; rank order) and every count in
137
+ `contrast.csv` (`top50_overlap`, `n_sig_obs`, `n_sig_gen`, list sizes, `top50_overlap_broadcast`, `n_sig_broadcast`)
138
+ identical.
139
+ - Observed cells: the full-data donor x type aggregates rebuilt from `cells_panel6k.npz` + frozen observed labels
140
+ equal the reference cache exactly (n, detection, summed counts, float32 CP10K; max |diff| 0).
141
+ - Sepsis pooled: the `pooled_deg` contrast also equals `scores/ye2026_sepsis/pooled/contrast.csv` (max |diff| 8.3e-17).
142
+ - Known published values are reproduced, e.g. pooled LoRA logFC r 0.527 / 0.82 / 0.461 / 0.48 (sepsis / Imperial /
143
+ Giroux without sex-linked genes / Ji) and Welch top-50 23 / 143 / 5 / 15.
144
+
145
+ ## Caveats
146
+
147
+ - The split-half ceiling measures **cell-sampling noise only**: both halves contain the same samples, so donor
148
+ sampling and donor-specific effects are shared by A and B (and by any predictor conditioned on these samples' bulk).
149
+ It is an upper bound for "reproduce these samples' observed logFC", not for "recover the population effect".
150
+ - The generated DEG pseudobulks are sums of the Poisson read-out (integers; the scorer's Welch input). Generated cells
151
+ are sparser than observed ones, so the generated "nonzero" universe is smaller (`n_tested_gen` < `n_tested_obs`).
152
+ - The broadcast limma runs on the condition `bulk_counts` as fed to the model (fixed-depth scaled, non-integer,
153
+ equal library sizes), the same input the scorer's Welch broadcast uses; voom weights are therefore not those of the
154
+ raw bulk counts.
155
+ - RBO with t descending weights the up-regulated genes; the down direction is in `rbo_ext_t_asc`.
156
+ - Imperial (157 samples / 57 patients), Giroux (24 / 9) and Ji (33 / 20) are longitudinal: the scored unit is the
157
+ sample, as in the scorer, so the Welch and limma tests treat repeated samples of one patient as independent
158
+ (no `duplicateCorrelation` block). This inflates significance on the observed, generated and broadcast sides alike.
159
+ - Few-pair Giroux scores 10–12 samples (2 vs 2 test subjects per draw); its observed Welch lists are nearly empty (mean 28.8
160
+ genes summed over five types), so Welch top-50 is degenerate there; limma finds more (mean 117.6).
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scores_contrast/TABLES.md ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # scores_contrast: compact tables
2
+
3
+ Generated by `tools/contrast_extra_tables.py` from the collected CSVs. Means over T/B/Mono/NK (r) or over the scored DEG types T/B/Mono/NK/DC (CAT, RBO); top-50 = sum over the scored types, 'of N' = sum of the observed list lengths; chance = hypergeometric mean. Broadcast = the raw real-bulk condition of the LoRA arm. Few-pair: mean ± SD over 5 draws (other columns: means).
4
+
5
+
6
+ ## Few-pair (5 donors, 5 draws)
7
+
8
+ | cohort | arm | Pearson r | Spearman r | split-half r(A,B) / noise-free ceiling | r vs half B | Welch top-50 (chance) | limma top-50 (chance) | CAT50 / CAT100 (chance@50) | RBO |
9
+ |---|---|---|---|---|---|---|---|---|---|
10
+ | Sepsis | LoRA | 0.35 ± 0.16 | 0.22 ± 0.13 | 0.96 / 0.99 | 0.35 | 16.4 (2.58) of 250.0 | 16.2 (2.19) of 250.0 | 0.054 / 0.075 (0.006) | 0.117 |
11
+ | Sepsis | scSemiProfiler | 0.40 ± 0.08 | 0.16 ± 0.07 | 0.96 / 0.99 | 0.40 | 5.2 (4.61) of 250.0 | 11.4 (6.93) of 250.0 | 0.015 / 0.033 (0.016) | 0.044 |
12
+ | Sepsis | zero-shot raw | -0.02 ± 0.02 | -0.05 ± 0.02 | 0.96 / 0.99 | -0.02 | 10.0 (2.88) of 250.0 | 9.2 (2.15) of 250.0 | 0.010 / 0.023 (0.006) | 0.033 |
13
+ | Sepsis | zero-shot + cal | 0.10 ± 0.04 | 0.13 ± 0.02 | 0.96 / 0.99 | 0.10 | 9.4 (2.50) of 250.0 | 9.6 (1.99) of 250.0 | 0.049 / 0.056 (0.006) | 0.089 |
14
+ | Sepsis | broadcast (real bulk) | 0.32 ± 0.02 | 0.33 ± 0.01 | 0.96 / 0.99 | 0.32 | 20.0 (2.25) of 250.0 | 35.4 (2.25) of 250.0 | 0.045 / 0.067 (0.004) | 0.068 |
15
+ | Imperial ESKD COVID | LoRA | 0.75 ± 0.02 | 0.55 ± 0.04 | 0.89 / 0.97 | 0.74 | 113.6 (3.07) of 250.0 | 102.0 (3.07) of 250.0 | 0.174 / 0.256 (0.006) | 0.284 |
16
+ | Imperial ESKD COVID | scSemiProfiler | 0.56 ± 0.03 | 0.37 ± 0.03 | 0.89 / 0.97 | 0.56 | 46.8 (6.02) of 250.0 | 35.2 (5.48) of 250.0 | 0.118 / 0.128 (0.012) | 0.162 |
17
+ | Imperial ESKD COVID | zero-shot raw | 0.64 ± 0.01 | 0.46 ± 0.02 | 0.89 / 0.97 | 0.63 | 105.6 (2.80) of 250.0 | 89.8 (2.80) of 250.0 | 0.107 / 0.168 (0.006) | 0.196 |
18
+ | Imperial ESKD COVID | zero-shot + cal | 0.68 ± 0.02 | 0.37 ± 0.04 | 0.89 / 0.97 | 0.66 | 103.8 (3.01) of 250.0 | 92.2 (2.99) of 250.0 | 0.154 / 0.212 (0.006) | 0.218 |
19
+ | Imperial ESKD COVID | broadcast (real bulk) | 0.66 ± 0.01 | 0.36 ± 0.01 | 0.89 / 0.97 | 0.64 | 74.8 (2.27) of 250.0 | 59.6 (2.27) of 250.0 | 0.159 / 0.209 (0.005) | 0.161 |
20
+ | Giroux (sex-linked genes excluded) | LoRA | 0.30 ± 0.08 | 0.19 ± 0.04 | 0.89 / 0.97 | 0.29 | 0.2 (0.02) of 28.8 | 0.8 (0.48) of 117.6 | 0.036 / 0.042 (0.008) | 0.026 |
21
+ | Giroux (sex-linked genes excluded) | scSemiProfiler | 0.40 ± 0.04 | 0.27 ± 0.01 | 0.89 / 0.97 | 0.39 | 0.0 (0.01) of 28.8 | 1.6 (0.89) of 117.6 | 0.042 / 0.066 (0.030) | 0.043 |
22
+ | Giroux (sex-linked genes excluded) | zero-shot raw | 0.26 ± 0.13 | 0.14 ± 0.11 | 0.89 / 0.97 | 0.25 | 0.0 (0.00) of 28.8 | 1.0 (0.43) of 117.6 | 0.034 / 0.041 (0.007) | 0.038 |
23
+ | Giroux (sex-linked genes excluded) | zero-shot + cal | 0.23 ± 0.15 | 0.12 ± 0.11 | 0.89 / 0.97 | 0.22 | 0.0 (0.00) of 28.8 | 1.2 (0.41) of 117.6 | 0.029 / 0.041 (0.009) | 0.040 |
24
+ | Giroux (sex-linked genes excluded) | broadcast (real bulk) | 0.49 ± 0.08 | 0.38 ± 0.06 | 0.89 / 0.97 | 0.48 | 0.0 (0.01) of 28.8 | 14.8 (0.41) of 117.6 | 0.166 / 0.160 (0.005) | 0.173 |
25
+ | Ji ChILI (whole-blood bulk) | LoRA | 0.33 ± 0.08 | 0.29 ± 0.07 | 0.88 / 0.96 | 0.33 | 0.2 (0.05) of 176.4 | 3.0 (1.41) of 210.0 | 0.053 / 0.073 (0.007) | 0.045 |
26
+ | Ji ChILI (whole-blood bulk) | scSemiProfiler | 0.15 ± 0.08 | 0.09 ± 0.07 | 0.88 / 0.96 | 0.15 | 0.0 (0.03) of 176.4 | 0.6 (1.23) of 210.0 | 0.026 / 0.039 (0.026) | 0.026 |
27
+ | Ji ChILI (whole-blood bulk) | zero-shot raw | 0.09 ± 0.04 | 0.08 ± 0.04 | 0.88 / 0.96 | 0.09 | 0.0 (0.04) of 176.4 | 0.0 (0.50) of 210.0 | 0.004 / 0.017 (0.008) | 0.013 |
28
+ | Ji ChILI (whole-blood bulk) | zero-shot + cal | 0.14 ± 0.09 | 0.12 ± 0.09 | 0.88 / 0.96 | 0.14 | 0.0 (0.00) of 176.4 | 0.0 (0.02) of 210.0 | 0.014 / 0.028 (0.008) | 0.019 |
29
+ | Ji ChILI (whole-blood bulk) | broadcast (real bulk) | 0.23 ± 0.03 | 0.12 ± 0.02 | 0.88 / 0.96 | 0.23 | 1.0 (0.26) of 176.4 | 6.2 (0.74) of 210.0 | 0.032 / 0.047 (0.005) | 0.052 |
30
+
31
+
32
+ ## 5-fold pooled
33
+
34
+ | cohort | arm | Pearson r | Spearman r | split-half r(A,B) / noise-free ceiling | r vs half B | Welch top-50 (chance) | limma top-50 (chance) | CAT50 / CAT100 (chance@50) | RBO |
35
+ |---|---|---|---|---|---|---|---|---|---|
36
+ | Sepsis | LoRA | 0.53 | 0.41 | 0.96 / 0.99 | 0.52 | 23.0 (1.97) of 250 | 18.0 (2.37) of 250 | 0.104 / 0.136 (0.006) | 0.186 |
37
+ | Sepsis | scSemiProfiler | not computed: no scSemiProfiler arm in this design (5-fold CV / equal-budget calls do not exist yet) |||||||| |
38
+ | Sepsis | zero-shot raw | -0.01 | -0.06 | 0.96 / 0.99 | -0.01 | 9.0 (2.73) of 250 | 12.0 (2.37) of 250 | 0.004 / 0.022 (0.006) | 0.024 |
39
+ | Sepsis | zero-shot + cal | 0.12 | 0.13 | 0.96 / 0.99 | 0.12 | 11.0 (2.73) of 250 | 11.0 (2.48) of 250 | 0.036 / 0.052 (0.006) | 0.080 |
40
+ | Sepsis | broadcast (real bulk) | 0.32 | 0.33 | 0.96 / 0.99 | 0.32 | 21.0 (2.24) of 250 | 36.0 (2.24) of 250 | 0.048 / 0.072 (0.004) | 0.070 |
41
+ | Imperial ESKD COVID | LoRA | 0.82 | 0.63 | 0.90 / 0.97 | 0.81 | 143.0 (2.99) of 250 | 122.0 (2.99) of 250 | 0.196 / 0.304 (0.006) | 0.413 |
42
+ | Imperial ESKD COVID | scSemiProfiler | not computed: no scSemiProfiler arm in this design (5-fold CV / equal-budget calls do not exist yet) |||||||| |
43
+ | Imperial ESKD COVID | zero-shot raw | 0.64 | 0.46 | 0.90 / 0.97 | 0.64 | 106.0 (2.80) of 250 | 96.0 (2.80) of 250 | 0.096 / 0.192 (0.006) | 0.261 |
44
+ | Imperial ESKD COVID | zero-shot + cal | 0.68 | 0.37 | 0.90 / 0.97 | 0.67 | 111.0 (2.98) of 250 | 101.0 (2.98) of 250 | 0.156 / 0.234 (0.006) | 0.263 |
45
+ | Imperial ESKD COVID | broadcast (real bulk) | 0.66 | 0.36 | 0.90 / 0.97 | 0.65 | 84.0 (2.27) of 250 | 63.0 (2.27) of 250 | 0.168 / 0.214 (0.005) | 0.177 |
46
+ | Giroux (sex-linked genes excluded) | LoRA | 0.46 | 0.38 | 0.90 / 0.97 | 0.45 | 5.0 (0.65) of 101 | 4.0 (1.46) of 157 | 0.052 / 0.058 (0.008) | 0.086 |
47
+ | Giroux (sex-linked genes excluded) | scSemiProfiler | not computed: no scSemiProfiler arm in this design (5-fold CV / equal-budget calls do not exist yet) |||||||| |
48
+ | Giroux (sex-linked genes excluded) | zero-shot raw | 0.33 | 0.22 | 0.90 / 0.97 | 0.33 | 1.0 (0.06) of 101 | 0.0 (0.02) of 157 | 0.020 / 0.026 (0.007) | 0.028 |
49
+ | Giroux (sex-linked genes excluded) | zero-shot + cal | 0.27 | 0.17 | 0.90 / 0.97 | 0.27 | 0.0 (0.01) of 101 | 0.0 (0.10) of 157 | 0.008 / 0.022 (0.008) | 0.020 |
50
+ | Giroux (sex-linked genes excluded) | broadcast (real bulk) | 0.58 | 0.50 | 0.90 / 0.97 | 0.56 | 5.0 (0.16) of 101 | 16.0 (0.34) of 157 | 0.128 / 0.134 (0.005) | 0.170 |
51
+ | Ji ChILI (whole-blood bulk) | LoRA | 0.48 | 0.38 | 0.89 / 0.97 | 0.47 | 15.0 (0.68) of 250 | 16.0 (1.82) of 250 | 0.080 / 0.142 (0.007) | 0.102 |
52
+ | Ji ChILI (whole-blood bulk) | scSemiProfiler | not computed: no scSemiProfiler arm in this design (5-fold CV / equal-budget calls do not exist yet) |||||||| |
53
+ | Ji ChILI (whole-blood bulk) | zero-shot raw | 0.08 | 0.07 | 0.89 / 0.97 | 0.08 | 0.0 (0.05) of 250 | 0.0 (0.02) of 250 | 0.012 / 0.030 (0.008) | 0.016 |
54
+ | Ji ChILI (whole-blood bulk) | zero-shot + cal | 0.14 | 0.11 | 0.89 / 0.97 | 0.14 | 0.0 (0.00) of 250 | 0.0 (0.02) of 250 | 0.016 / 0.032 (0.008) | 0.017 |
55
+ | Ji ChILI (whole-blood bulk) | broadcast (real bulk) | 0.24 | 0.11 | 0.89 / 0.97 | 0.23 | 4.0 (0.70) of 250 | 15.0 (2.34) of 250 | 0.044 / 0.068 (0.005) | 0.065 |
56
+
57
+
58
+ ## Sepsis learning curve (pooled, 82 samples)
59
+
60
+ | series | pairs | arm | Pearson | Spearman | Welch top-50 (chance) | limma top-50 (chance) | CAT50 / CAT100 | RBO |
61
+ |---|---|---|---|---|---|---|---|---|
62
+ | zs__raw | 0 | zs__raw | -0.01 | -0.06 | 9 (2.73) of 250 | 12 (2.37) of 250 | 0.004 / 0.022 | 0.024 |
63
+ | zs__cal | 0 | zs__cal | 0.12 | 0.13 | 11 (2.73) of 250 | 11 (2.48) of 250 | 0.036 / 0.052 | 0.080 |
64
+ | lora | 5 | lora_n5__raw | 0.29 | 0.18 | 5 (1.46) of 250 | 2 (0.82) of 250 | 0.064 / 0.076 | 0.125 |
65
+ | lora | 10 | lora_n10__raw | 0.42 | 0.32 | 8 (2.35) of 250 | 10 (1.63) of 250 | 0.084 / 0.108 | 0.180 |
66
+ | lora | 20 | lora_n20__raw | 0.37 | 0.31 | 18 (1.87) of 250 | 13 (1.78) of 250 | 0.084 / 0.110 | 0.162 |
67
+ | lora | 40 | lora_n40__raw | 0.48 | 0.38 | 22 (2.16) of 250 | 17 (2.13) of 250 | 0.080 / 0.128 | 0.182 |
68
+ | lora | all | real_lora__raw | 0.53 | 0.41 | 23 (1.97) of 250 | 18 (2.37) of 250 | 0.104 / 0.136 | 0.186 |
69
+ | zs_cal_budget | 5 | zs__cal_n5 | 0.08 | 0.11 | 12 (3.05) of 250 | 13 (2.30) of 250 | 0.048 / 0.064 | 0.074 |
70
+ | zs_cal_budget | 10 | zs__cal_n10 | 0.10 | 0.12 | 10 (2.73) of 250 | 6 (2.04) of 250 | 0.056 / 0.060 | 0.083 |
71
+ | zs_cal_budget | 20 | zs__cal_n20 | 0.10 | 0.12 | 7 (2.41) of 250 | 9 (1.92) of 250 | 0.060 / 0.062 | 0.100 |
72
+ | zs_cal_budget | 40 | zs__cal_n40 | 0.12 | 0.13 | 7 (2.73) of 250 | 11 (2.43) of 250 | 0.056 / 0.064 | 0.085 |
73
+
74
+ Broadcast (real bulk): Pearson 0.32, CAT50 0.048, RBO 0.070; split-half r(A,B) 0.96, noise-free ceiling 0.99.
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scores_contrast/_code/contrast_extra.b1ae7ded9451.py ADDED
@@ -0,0 +1,1220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Rank-based, threshold-free and reliability-aware disease-signal metrics for the paired fine-tuning benchmark.
3
+
4
+ CPU only; never imports torch (CUDA hidden). Added 2026-10-02. Every scored unit (one few-pair draw = the draw<j> and
5
+ draw<j>_scsemi5 calls; one pooled 5-fold call; or any score_ft.py call with --design scored) is re-read exactly as
6
+ tools/score_ft.py scored it, and the per-cell-type case-vs-control quantities are rebuilt with the scorer's own
7
+ functions (ft_common / score_ft / evaluate_generated_vs_truth):
8
+
9
+ 1. Spearman r of generated vs observed logFC next to the scorer's Pearson r (same genes = scoring genes detected in
10
+ >= 1 % of the observed cells of the type, minus --exclude-genes; same statistic `mean_cp10k`, also
11
+ `pseudobulk_log1p_cpm`), and Spearman of the bulk broadcast. Reproduction: Pearson r, broadcast r and partial r
12
+ must equal the call's contrast.csv (|diff| <= 1e-9).
13
+ 2. Split-half ceiling (arm-independent): each scored sample's observed cells of each type (T, B, Monocyte, NK) are
14
+ split into halves A / B (5 seeds 20260926..20260930; per sample x type a permutation from
15
+ default_rng([seed, sha256(sample|type)[:8]]); A = first floor(n/2) positions in canonical cell order); the
16
+ `mean_cp10k` logFC of A and of B (same genes, same donor balancing) -> r(A, B) Pearson and Spearman; Spearman-Brown
17
+ full-data reliability 2r/(1+r) and the noise-free ceiling sqrt(2r/(1+r)). On the same footing:
18
+ r(generated, half B) and r(bulk broadcast, half B).
19
+ 3. limma-voom DEG sensitivity on the donor x type pseudobulks the Welch top-50 DEG uses (observed summed counts;
20
+ generated = summed Poisson read-out counts of the generated cells, exactly what score_ft.deg_block feeds the
21
+ Welch test; broadcast = the arm's condition bulk_counts): edgeR TMM + voom + lmFit + eBayes, BH, FDR < 0.05,
22
+ top 50 by |logFC| (EV.top_deg_genes) -> overlap with the observed limma top-50, summed over the scored types.
23
+ Gene filter per side: "nonzero" (primary; = the evaluator's edgeR default) and "filterByExpr" (secondary).
24
+ The existing Welch top-50 overlap is recomputed and must equal the call's contrast.csv and deg_top50_lists.csv.
25
+ 4. CAT curves (Irizarry 2005) at k = 10, 20, 50, 100, 200, 500 on the limma ranking by |moderated t| (primary
26
+ filter): CAT(k) = |obs top-k & pred top-k with the same logFC sign| / k; chance k / (2 G) with G = genes tested on
27
+ both sides (any sign: k / G). RBO_ext (Webber 2010, eq. 32, p = 0.98) of the signed rankings (t descending;
28
+ t ascending reported too). The broadcast is ranked by the limma t of its bulk.
29
+ 5. Chance level of the top-50 overlaps (Welch and limma): sum over types of |obs list| x |pred list| / G
30
+ (hypergeometric mean; G = genes tested on both sides).
31
+
32
+ usage (CPU; run through tools/run_contrast_unit.sh):
33
+ contrast_extra.py --design fewshot --dataset ye2026_sepsis [--draws 0,1,2,3,4] [--threads 4]
34
+ contrast_extra.py --design pooled --dataset ye2026_sepsis
35
+ contrast_extra.py --design scored --dataset ye2026_sepsis --score-dir scores/ye2026_sepsis/cal_budget_20261001/pooled \
36
+ --arms zs__cal_n5,zs__cal_n10,zs__cal_n20,zs__cal_n40 --unit cal_budget_20261001/pooled
37
+ contrast_extra.py --collect # scores_contrast/{fewshot,pooled,learning_curve,scored}_*.csv + reproduction_check.csv
38
+ Giroux: few-pair and pooled units read scores_nosex/ (196 sex-linked genes excluded; the exclusion recorded in the
39
+ call's summary.json is applied); --design scored on giroux2022 requires a call with that exclusion or --exclude-genes.
40
+ Outputs: scores_contrast/<ds>/<unit>/{contrast.csv, ceiling.csv, deg_limma.csv, cat.csv, rbo.csv, headline.csv,
41
+ repro.json, manifest.json, limma/{jobs.csv, limma_status.csv, versions.txt, R.log}}.
42
+ """
43
+ from __future__ import annotations
44
+
45
+ import os
46
+ import sys
47
+
48
+
49
+ def _threads_from_argv(default: int = 4) -> int:
50
+ for i, a in enumerate(sys.argv):
51
+ if a == "--threads" and i + 1 < len(sys.argv):
52
+ return int(sys.argv[i + 1])
53
+ if a.startswith("--threads="):
54
+ return int(a.split("=", 1)[1])
55
+ return default
56
+
57
+
58
+ _THR = str(_threads_from_argv())
59
+ for _k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMBA_NUM_THREADS"):
60
+ os.environ[_k] = _THR
61
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
62
+
63
+ import argparse # noqa: E402
64
+ import hashlib # noqa: E402
65
+ import json # noqa: E402
66
+ import re # noqa: E402
67
+ import shutil # noqa: E402
68
+ import subprocess # noqa: E402
69
+ import time # noqa: E402
70
+ from pathlib import Path # noqa: E402
71
+
72
+ import numpy as np # noqa: E402
73
+ import pandas as pd # noqa: E402
74
+ import scipy.sparse as sp # noqa: E402
75
+ from scipy.stats import rankdata # noqa: E402
76
+
77
+ TOOLS = Path(__file__).resolve().parent
78
+ sys.path.insert(0, str(TOOLS))
79
+ import ft_common as F # noqa: E402
80
+ import score_ft as S # noqa: E402 (module level: argparse/env only; main() is not run)
81
+
82
+ EV = F.EV
83
+ TASK = F.TASK
84
+ SCORES = TASK / "scores"
85
+ NOSEX = TASK / "scores_nosex"
86
+ OUT_ROOT = TASK / "scores_contrast"
87
+ R_SCRIPT = TOOLS / "contrast_extra_limma.R"
88
+ RSCRIPT = Path("/home/sj_server_1/miniforge3/bin/Rscript")
89
+ CODE_FILES = (Path(__file__).resolve(), R_SCRIPT, TOOLS / "ft_common.py", TOOLS / "score_ft.py", F.EV_PATH)
90
+ REMOTE = "spark-0110"
91
+ MIN_FREE_GIB = 40.0
92
+ MAX_THREADS = 14
93
+
94
+ SPLIT_SEEDS = tuple(20260926 + s for s in range(5)) # SLE split-half seeds (sle_broadcast_splithalf.py)
95
+ CAT_KS = (10, 20, 50, 100, 200, 500)
96
+ RBO_P = 0.98
97
+ LIMMA_FILTERS = ("nonzero", "filterByExpr")
98
+ PRIMARY_FILTER = "nonzero"
99
+ STATS = ("mean_cp10k", "pseudobulk_log1p_cpm")
100
+ DATASETS = ("immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
101
+ DISEASE = ("ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
102
+ SOURCE_TREE = {"giroux2022": NOSEX} # Giroux disease metrics without sex-linked genes
103
+ POOLED_CALL = {"ye2026_sepsis": "pooled_deg"} # the sepsis pooled call that carries the DEG score
104
+ SEX_EXCL = TASK / "data/sex_linked_genes/sex_linked_genes_exclude.csv"
105
+ REPRO_TOL = 1e-9
106
+
107
+ ARM_LABEL = {"zs_raw": "Zero-shot, real bulk", "zs__raw": "Zero-shot, real bulk",
108
+ "zs_cal": "Zero-shot + calibration", "zs__cal": "Zero-shot + calibration",
109
+ "scsemi5": "scSemiProfiler, 5 donors", "lora5": "LoRA, 5 donors",
110
+ "real_lora__raw": "LoRA, all training pairs", "real_full__raw": "Full FT, all training pairs",
111
+ "pseudo_full__cal": "sc-only fine-tune (+ calibration)", "pseudo_full__raw": "sc-only fine-tune, real bulk",
112
+ "zs_pseudo": "Zero-shot, sc pseudobulk input (reference)",
113
+ "zs__pseudo": "Zero-shot, sc pseudobulk input (reference)",
114
+ "lora_multik__raw": "LoRA, multi-K", "lora_recipe__raw": "LoRA + recipes",
115
+ "scsemi__raw": "scSemiProfiler, all training pairs (5-fold CV)",
116
+ **{f"lora_n{n}__raw": f"LoRA, {n} pairs + inner-val" for n in (5, 10, 20, 40)},
117
+ **{f"zs__cal_n{n}": f"Zero-shot + calibration (alpha from {n} pairs + inner-val)" for n in (5, 10, 20, 40)},
118
+ **{f"scsemi_n{n}__raw": f"scSemiProfiler, {n} pairs + inner-val" for n in (5, 10, 20, 40)}}
119
+ ROLE = {"lora5": "lora", "real_lora__raw": "lora", "scsemi5": "scsemi", "scsemi__raw": "scsemi",
120
+ "zs_raw": "zs_raw", "zs__raw": "zs_raw", "zs_cal": "zs_cal", "zs__cal": "zs_cal"}
121
+ SCORED: dict = {} # --design scored: {"dir": Path, "arms": tuple, "unit": str}
122
+
123
+
124
+ def log(msg: str) -> None:
125
+ F.log(msg)
126
+
127
+
128
+ # =========================================================================== pure metric functions
129
+ def spearman(a, b) -> float:
130
+ """Spearman rank correlation = Pearson r (EV.pearson) of the average-tie ranks; NaN when degenerate."""
131
+ a = np.asarray(a, np.float64)
132
+ b = np.asarray(b, np.float64)
133
+ if a.shape != b.shape or a.size < 3:
134
+ return float("nan")
135
+ return EV.pearson(rankdata(a), rankdata(b))
136
+
137
+
138
+ def spearman_brown(r: float) -> float:
139
+ """Full-data reliability from a split-half correlation: 2 r / (1 + r) (Spearman 1910; Brown 1910)."""
140
+ if r is None or not np.isfinite(r) or r <= -1:
141
+ return float("nan")
142
+ return 2.0 * r / (1.0 + r)
143
+
144
+
145
+ def noise_free_ceiling(r: float) -> float:
146
+ """Expected r of a noise-free predictor with the full-data observed vector: sqrt(2 r / (1 + r)); NaN if <= 0."""
147
+ sb = spearman_brown(r)
148
+ return float(np.sqrt(sb)) if np.isfinite(sb) and sb > 0 else float("nan")
149
+
150
+
151
+ def prefix_overlaps(short: list, long: list) -> np.ndarray:
152
+ """X_d for d = 1..len(long): |short[:min(d, s)] & long[:d]| (lists without duplicates)."""
153
+ s, l_ = len(short), len(long)
154
+ seen_s, seen_l = set(), set()
155
+ x, out = 0, np.zeros(l_, np.int64)
156
+ for d in range(l_):
157
+ b = long[d]
158
+ if d < s:
159
+ a = short[d]
160
+ if a == b:
161
+ x += 1
162
+ else:
163
+ x += (a in seen_l) + (b in seen_s)
164
+ seen_s.add(a)
165
+ else:
166
+ x += b in seen_s
167
+ seen_l.add(b)
168
+ out[d] = x
169
+ return out
170
+
171
+
172
+ def rbo_ext(list1, list2, p: float = RBO_P) -> float:
173
+ """Extrapolated rank-biased overlap RBO_ext (Webber, Moffat & Zobel 2010, ACM TOIS 28:20, eq. 32; eq. 30 for equal
174
+ lengths). Lists are rankings without duplicates (item 0 = top). With s = |shorter|, l = |longer|, X_d = overlap of
175
+ the depth-d prefixes (the shorter list fully seen beyond s):
176
+ RBO_ext = (1-p)/p * ( sum_{d=1..l} X_d/d p^d + sum_{d=s+1..l} X_s (d-s)/(s d) p^d ) + ((X_l - X_s)/l + X_s/s) p^l.
177
+ NaN when a list is empty."""
178
+ a, b = list(list1), list(list2)
179
+ if len(set(a)) != len(a) or len(set(b)) != len(b):
180
+ raise ValueError("rbo_ext: lists must not contain duplicates")
181
+ if not a or not b:
182
+ return float("nan")
183
+ short, long = (a, b) if len(a) <= len(b) else (b, a)
184
+ s, l_ = len(short), len(long)
185
+ X = prefix_overlaps(short, long).astype(np.float64)
186
+ d = np.arange(1, l_ + 1, dtype=np.float64)
187
+ w = np.power(p, d)
188
+ term1 = float(np.sum(X / d * w))
189
+ xs = X[s - 1]
190
+ dd = d[s:]
191
+ term2 = float(np.sum(xs * (dd - s) / (s * dd) * w[s:])) if l_ > s else 0.0
192
+ xl = X[l_ - 1]
193
+ return (1.0 - p) / p * (term1 + term2) + ((xl - xs) / l_ + xs / s) * p ** l_
194
+
195
+
196
+ def cat_curve(obs_order: np.ndarray, obs_sign: np.ndarray, pred_order: np.ndarray | None, pred_sign: np.ndarray | None,
197
+ ks=CAT_KS) -> list[dict]:
198
+ """Correspondence-at-the-top (Irizarry et al. 2005): for each k the fraction of the observed top-k genes that are in
199
+ the predictor's top-k, with the same sign (cat_same_sign) and regardless of sign (cat_any_sign). Orders are gene
200
+ indices ranked best first; signs are full-length arrays indexed by gene. pred_order None = the predictor's test is
201
+ undefined -> 0 (as the benchmark's top-50 overlap). Denominator = min(k, len(obs_order))."""
202
+ out = []
203
+ for k in ks:
204
+ top_o = np.asarray(obs_order[:k], np.int64)
205
+ kk = int(top_o.size)
206
+ if kk == 0:
207
+ out.append({"k": k, "k_eff": 0, "cat_same_sign": float("nan"), "cat_any_sign": float("nan")})
208
+ continue
209
+ if pred_order is None:
210
+ out.append({"k": k, "k_eff": kk, "cat_same_sign": 0.0, "cat_any_sign": 0.0})
211
+ continue
212
+ top_p = np.asarray(pred_order[:k], np.int64)
213
+ both = np.intersect1d(top_o, top_p, assume_unique=True)
214
+ same = int((obs_sign[both] == pred_sign[both]).sum())
215
+ out.append({"k": k, "k_eff": kk, "cat_same_sign": same / kk, "cat_any_sign": both.size / kk})
216
+ return out
217
+
218
+
219
+ def cat_chance(k: int, G: int) -> tuple[float, float]:
220
+ """Expected CAT(k) of a random ranking over G genes: k / (2 G) with the same-sign requirement (sign a fair coin),
221
+ k / G regardless of sign."""
222
+ if G <= 0:
223
+ return float("nan"), float("nan")
224
+ return min(k, G) / (2.0 * G), min(k, G) / float(G)
225
+
226
+
227
+ def expected_overlap(n: int, m: int, G: int) -> float:
228
+ """Hypergeometric mean of |A & B| for a fixed n-set A and a random m-set B among G genes: n m / G."""
229
+ return float(n) * float(m) / float(G) if G > 0 else float("nan")
230
+
231
+
232
+ def rank_orders(t: np.ndarray) -> dict:
233
+ """Gene-index orders of one limma result (NaN t = not tested): by |t| descending, by t descending, by t ascending
234
+ (stable; ties keep the fixed gene order)."""
235
+ idx = np.flatnonzero(np.isfinite(t))
236
+ tt = t[idx]
237
+ return {"abs": idx[np.argsort(-np.abs(tt), kind="stable")], "up": idx[np.argsort(-tt, kind="stable")],
238
+ "down": idx[np.argsort(tt, kind="stable")], "sign": np.sign(np.nan_to_num(t, nan=0.0)),
239
+ "tested": np.isfinite(t)}
240
+
241
+
242
+ # =========================================================================== file helpers
243
+ def sha256(path: Path) -> str:
244
+ h = hashlib.sha256()
245
+ with open(path, "rb") as fh:
246
+ for block in iter(lambda: fh.read(1 << 24), b""):
247
+ h.update(block)
248
+ return h.hexdigest()
249
+
250
+
251
+ def free_gib(path: Path) -> float:
252
+ st = os.statvfs(path)
253
+ return st.f_bavail * st.f_frsize / 2**30
254
+
255
+
256
+ def resolve_file(path: Path, want_sha: str, fetch_root: Path, fetched: list, receipt: bool) -> Path:
257
+ """The scored file: the local file if present, else a sha-checked copy from server_2 (same absolute path) under
258
+ fetch_root (with its .log receipt next to it when receipt=True, so score_ft.open_arm can check output_sha256)."""
259
+ path = Path(path)
260
+ if path.is_file():
261
+ return path
262
+ rel = path.relative_to(TASK)
263
+ dst = fetch_root / rel
264
+ marker = path.with_suffix(".moved")
265
+ if dst.is_file() and (not receipt or dst.with_suffix(".log").is_file()):
266
+ if sha256(dst) == want_sha:
267
+ if dst not in fetched:
268
+ fetched.append(dst)
269
+ return dst
270
+ dst.unlink()
271
+ size = int(subprocess.run(["ssh", "-n", REMOTE, f"stat -c %s '{path}'"], capture_output=True, text=True,
272
+ check=True).stdout.strip())
273
+ need = size / 2**30 + MIN_FREE_GIB
274
+ fetch_root.mkdir(parents=True, exist_ok=True)
275
+ if free_gib(fetch_root) < need:
276
+ raise SystemExit(f"disk: {free_gib(fetch_root):.1f} GiB free < {need:.1f} GiB needed to fetch {path}")
277
+ dst.parent.mkdir(parents=True, exist_ok=True)
278
+ log(f"fetching {rel} ({size / 2**30:.2f} GiB) from {REMOTE}")
279
+ subprocess.run(["rsync", "-a", "--bwlimit=200000", f"{REMOTE}:{path}", str(dst)], check=True)
280
+ if receipt:
281
+ rec = path.with_suffix(".log")
282
+ if rec.is_file():
283
+ shutil.copy2(rec, dst.with_suffix(".log"))
284
+ else:
285
+ subprocess.run(["rsync", "-a", f"{REMOTE}:{rec}", str(dst.with_suffix(".log"))], check=True)
286
+ fetched.append(dst)
287
+ got = sha256(dst)
288
+ if got != want_sha:
289
+ raise SystemExit(f"{dst}: sha {got[:12]} differs from the scored sha {want_sha[:12]}")
290
+ if marker.is_file() and f"sha {want_sha[:12]}" not in marker.read_text():
291
+ raise SystemExit(f"{marker}: marker sha differs ({marker.read_text().strip()})")
292
+ return dst
293
+
294
+
295
+ def drop_fetched(f: Path) -> None:
296
+ f.unlink(missing_ok=True)
297
+ f.with_suffix(".log").unlink(missing_ok=True)
298
+ log(f"removed fetched copy {f}")
299
+
300
+
301
+ # =========================================================================== unit definition
302
+ def unit_calls(design: str, ds: str, draw: int | None) -> tuple[list[tuple[Path, tuple | None]], dict]:
303
+ """[(call dir, arms or None = all)], notes."""
304
+ tree = SOURCE_TREE.get(ds, SCORES)
305
+ notes = {"source_tree": str(tree)}
306
+ if design == "fewshot":
307
+ base = tree / ds / "fewshot_n5"
308
+ calls = [(base / f"draw{draw}", None)]
309
+ sc = base / f"draw{draw}_scsemi5"
310
+ if (sc / "summary.json").is_file():
311
+ calls.append((sc, None))
312
+ else:
313
+ notes["missing_calls"] = [str(sc)]
314
+ return calls, notes
315
+ if design == "pooled":
316
+ name = POOLED_CALL.get(ds, "pooled")
317
+ if name != "pooled":
318
+ notes["contrast_also_checked_against"] = str(tree / ds / "pooled")
319
+ return [(tree / ds / name, None)], notes
320
+ if design == "scored":
321
+ return [(SCORED["dir"], SCORED["arms"])], notes
322
+ raise ValueError(design)
323
+
324
+
325
+ def unit_dir(design: str, ds: str, draw: int | None) -> Path:
326
+ if design == "scored":
327
+ return OUT_ROOT / ds / SCORED["unit"]
328
+ return OUT_ROOT / ds / (f"fewshot_n5/draw{draw}" if design == "fewshot" else "pooled")
329
+
330
+
331
+ def light_view(ref: dict, deg: dict, donors: list[str]) -> dict:
332
+ """score_ft.make_view's observed side without the embedding: the scored samples' groups and donor x type
333
+ aggregates with exactly the scorer's dtype casts."""
334
+ pos = {d: i for i, d in enumerate(ref["donors"].astype(str))}
335
+ miss = [d for d in donors if d not in pos]
336
+ if miss:
337
+ raise SystemExit(f"donors not in the reference: {miss[:5]}")
338
+ sel = np.asarray([pos[d] for d in donors], dtype=np.int64)
339
+ v = {"donors": np.asarray(donors, dtype=str), "sel": sel, "groups": ref["groups"][sel].astype(str),
340
+ "score_ids": [str(g) for g in ref["score_ids"]]}
341
+ for k in ("n", "sum", "cp10k", "det"):
342
+ v[f"agg_{k}"] = ref[f"agg_{k}"][sel].astype(np.float64 if k != "n" else np.int64)
343
+ v["deg_types"] = tuple(deg["types"])
344
+ v["deg_n"], v["deg_sum"] = deg["n"][sel], deg["sum"][sel]
345
+ return v
346
+
347
+
348
+ def contrast_from_summary(s: dict, v: dict) -> dict:
349
+ cd = s["contrast_definition"]
350
+ if not cd.get("enabled"):
351
+ return {"enabled": False, "reason": cd.get("reason")}
352
+ case, ctrl = np.asarray(cd["case"], bool), np.asarray(cd["ctrl"], bool)
353
+ groups = np.asarray(cd["groups"], dtype=str)
354
+ if case.size != v["donors"].size or ctrl.size != v["donors"].size:
355
+ raise SystemExit("contrast_definition length differs from the scored donors")
356
+ if not (np.array_equal(case, np.isin(groups, cd["case_groups"])) and
357
+ np.array_equal(ctrl, np.isin(groups, cd["control_groups"]))):
358
+ raise SystemExit("contrast_definition case/ctrl differ from its groups and group lists")
359
+ if cd["group_source"] == "features groups" and not np.array_equal(groups, v["groups"]):
360
+ raise SystemExit("contrast groups differ from the reference groups")
361
+ return {"enabled": True, "case": case, "ctrl": ctrl, "groups": groups, "case_groups": cd["case_groups"],
362
+ "control_groups": cd["control_groups"], "n_case_donors": int(case.sum()), "n_control_donors": int(ctrl.sum())}
363
+
364
+
365
+ # =========================================================================== observed cells (split half)
366
+ def observed_cells(spec, ref: dict, man: dict, cache: Path, v: dict) -> dict:
367
+ """All observed QC cells of the scored samples on the scoring genes, in the reference's canonical order
368
+ (F.build_reference: lexsort by (cell key, sample row)), with the reference's frozen observed labels; every input
369
+ sha-checked against reference_manifest.json."""
370
+ feat = F.load_features(spec.features)
371
+ if feat["sha256"] != man["features"]["sha256"]:
372
+ raise SystemExit("features sha differs from the reference's")
373
+ gs = F.gene_sets(feat)
374
+ if not np.array_equal(gs["score_ids"], ref["score_ids"].astype(str)):
375
+ raise SystemExit("scoring genes differ from the reference")
376
+ cells = F.load_cells_datadir(spec, gs)
377
+ if cells is None or cells["inputs_sha256"] != man["cells"]["inputs_sha256"]:
378
+ raise SystemExit("observed cell files differ from the ones the reference was built from")
379
+ table = cells["table"].reset_index(drop=True)
380
+ lab_path = cache / "observed_labels" / "labels" / "labels.parquet"
381
+ if sha256(lab_path) != man["labels"]["sha256"]:
382
+ raise SystemExit(f"{lab_path}: sha differs from the reference manifest")
383
+ lab = pd.read_parquet(lab_path, columns=["cell_index", "celltype_l1_pred"])
384
+ if len(lab) != len(table) or not np.array_equal(lab.cell_index.to_numpy(), np.arange(len(table))):
385
+ raise SystemExit("observed labels are not row-aligned with the observed cells")
386
+ labels = lab.celltype_l1_pred.astype(str).to_numpy()
387
+ keys, _ = F.cell_keys(table)
388
+ srow = np.asarray(cells["sample_row"], np.int64)
389
+ order = np.lexsort((keys, srow))
390
+ srow, labels = srow[order], labels[order]
391
+ sid = feat["sample_ids"]
392
+ want = {d: i for i, d in enumerate(v["donors"])}
393
+ didx = np.asarray([want.get(str(sid[r]), -1) for r in range(sid.size)], np.int64)[srow]
394
+ keep_rows = np.flatnonzero((didx >= 0) & np.isin(labels, F.CONTRAST_TYPES))
395
+ X = cells["X"].tocsr()[order]
396
+ del cells
397
+ X = X[keep_rows][:, gs["score_idx"]].tocsr()
398
+ return {"X": X, "d": didx[keep_rows], "labels": labels[keep_rows],
399
+ "n_cells_scored_all_types": int((didx >= 0).sum()), "inputs_sha256": man["cells"]["inputs_sha256"],
400
+ "labels_sha256": man["labels"]["sha256"]}
401
+
402
+
403
+ def split_half(spec, ref: dict, man: dict, cache: Path, v: dict, contrast: dict, genes: dict) -> dict:
404
+ """Observed mean_cp10k logFC on random halves A / B of every scored sample's cells of each contrast type."""
405
+ t0 = time.monotonic()
406
+ oc = observed_cells(spec, ref, man, cache, v)
407
+ S_ = v["donors"].size
408
+ X, d, lab = oc["X"], oc["d"], oc["labels"]
409
+ # the full-data aggregates rebuilt from these cells must equal the reference cache (the scorer's observed side)
410
+ agg = F.type_aggregates(X, d, lab, S_)
411
+ chk = {"n_equal": bool(np.array_equal(agg["n"], v["agg_n"])),
412
+ "det_equal": bool(np.array_equal(agg["det"], v["agg_det"])),
413
+ "sum_equal_float32": bool(np.array_equal(agg["sum"].astype(np.float32), ref["agg_sum"][v["sel"]])),
414
+ "cp10k_max_abs_diff_float32": float(np.abs(agg["cp10k"].astype(np.float32).astype(np.float64)
415
+ - v["agg_cp10k"]).max())}
416
+ chk["cp10k_equal_float32"] = chk["cp10k_max_abs_diff_float32"] == 0.0
417
+ if not (chk["n_equal"] and chk["det_equal"] and chk["sum_equal_float32"]):
418
+ raise SystemExit(f"observed cells do not rebuild the reference aggregates: {chk}")
419
+ del agg
420
+ Xf = X.astype(np.float64)
421
+ lib = np.asarray(Xf.sum(axis=1)).ravel()
422
+ cp = (sp.diags(np.divide(F.CP10K, lib, out=np.zeros_like(lib), where=lib > 0)) @ Xf).tocsr()
423
+ del Xf, X
424
+ T = len(F.CONTRAST_TYPES)
425
+ tix = np.asarray([F.CONTRAST_TYPES.index(x) for x in lab], np.int64)
426
+ blocks = {}
427
+ for s in range(S_):
428
+ for ti in range(T):
429
+ blocks[(s, ti)] = np.flatnonzero((d == s) & (tix == ti)) # canonical order within the sample
430
+ case, ctrl = contrast["case"], contrast["ctrl"]
431
+ out = {"seeds": list(SPLIT_SEEDS), "check_full_aggregates": chk, "per_seed": [], "halfB": {}}
432
+ G = cp.shape[1]
433
+ for seed in SPLIT_SEEDS:
434
+ inA = np.zeros(d.size, bool)
435
+ for (s, ti), idx in blocks.items():
436
+ n = idx.size
437
+ if n == 0:
438
+ continue
439
+ perm = F.donor_rng(seed, f"{v['donors'][s]}|{F.CONTRAST_TYPES[ti]}").permutation(n)
440
+ inA[idx[np.sort(perm[:n // 2])]] = True
441
+ gid = np.where(inA, 0, 1) * (S_ * T) + d * T + tix
442
+ ind = sp.csr_matrix((np.ones(d.size), (gid, np.arange(d.size))), shape=(2 * S_ * T, d.size))
443
+ sums = (ind @ cp).toarray().reshape(2, S_, T, G)
444
+ nn = np.bincount(gid, minlength=2 * S_ * T).reshape(2, S_, T)
445
+ for ti, t in enumerate(F.CONTRAST_TYPES):
446
+ gm = genes[t]
447
+ la = F.lfc_mean_cp10k(nn[0, :, ti], sums[0, :, ti], case, ctrl)
448
+ lb = F.lfc_mean_cp10k(nn[1, :, ti], sums[1, :, ti], case, ctrl)
449
+ ok = la is not None and lb is not None and gm.sum() >= 3
450
+ out["per_seed"].append({
451
+ "seed": seed, "celltype": t, "n_genes": int(gm.sum()),
452
+ "pearson": EV.pearson(la[gm], lb[gm]) if ok else float("nan"),
453
+ "spearman": spearman(la[gm], lb[gm]) if ok else float("nan"),
454
+ "n_case_donors_A": int((case & (nn[0, :, ti] > 0)).sum()),
455
+ "n_control_donors_A": int((ctrl & (nn[0, :, ti] > 0)).sum()),
456
+ "n_case_donors_B": int((case & (nn[1, :, ti] > 0)).sum()),
457
+ "n_control_donors_B": int((ctrl & (nn[1, :, ti] > 0)).sum()),
458
+ "n_cells_A": int(nn[0, case | ctrl, ti].sum()), "n_cells_B": int(nn[1, case | ctrl, ti].sum())})
459
+ out["halfB"][(seed, t)] = lb
460
+ out["seconds"] = round(time.monotonic() - t0, 1)
461
+ out["n_cells_used"] = int(d.size)
462
+ log(f"split half: {d.size} observed cells of the 4 types, {len(SPLIT_SEEDS)} seeds; mean r(A,B) "
463
+ + ", ".join(f"{F.SHORT_TYPE[t]} {np.nanmean([r['pearson'] for r in out['per_seed'] if r['celltype'] == t]):.3f}"
464
+ for t in F.CONTRAST_TYPES) + f" ({out['seconds']} s; full aggregates rebuilt = cache)")
465
+ return out
466
+
467
+
468
+ # =========================================================================== DEG helpers
469
+ def welch_side(n: np.ndarray, sums: np.ndarray, case: np.ndarray, ctrl: np.ndarray, genes: list) -> dict:
470
+ """F.deg_top's computation (rows with >= 1 cell of the type among case | control; EV.welch_bh_deg;
471
+ EV.top_deg_genes), also returning the tested mask (the BH family)."""
472
+ rows = (np.asarray(n) > 0) & (case | ctrl)
473
+ deg = EV.welch_bh_deg(np.asarray(sums, np.float64)[rows], case[rows]) if rows.any() else None
474
+ top = EV.top_deg_genes(deg, genes, top_n=F.DEG_TOP_N, fdr=F.DEG_FDR)
475
+ return {"top": top, "defined": deg is not None, "tested": deg.tested if deg is not None else np.zeros(len(genes), bool),
476
+ "n_significant": int(deg.significant(F.DEG_FDR).size) if deg is not None else 0}
477
+
478
+
479
+ class LimmaBatch:
480
+ """Collects donor x type count matrices (kept genes) for one Rscript call."""
481
+
482
+ def __init__(self, workdir: Path, n_genes: int):
483
+ self.dir = workdir
484
+ self.dir.mkdir(parents=True, exist_ok=True)
485
+ self.G = n_genes
486
+ self.fh = open(self.dir / "counts.bin", "wb")
487
+ self.offset = 0
488
+ self.jobs, self.meta = [], {}
489
+
490
+ def add(self, key: str, counts: np.ndarray, is_case: np.ndarray) -> dict:
491
+ """counts: samples x genes (the rows the Welch test uses). Samples with zero library are dropped (recorded)."""
492
+ counts = np.asarray(counts, np.float64)
493
+ is_case = np.asarray(is_case, bool)
494
+ lib = counts.sum(1)
495
+ zero = lib <= 0
496
+ counts, is_case = counts[~zero], is_case[~zero]
497
+ info = {"key": key, "n_samples": int(counts.shape[0]), "n_case": int(is_case.sum()),
498
+ "n_control": int((~is_case).sum()), "n_zero_library_dropped": int(zero.sum()),
499
+ "defined": bool(is_case.sum() >= 2 and (~is_case).sum() >= 2)}
500
+ self.meta[key] = info
501
+ if not info["defined"]:
502
+ return info
503
+ assert counts.shape[1] == self.G
504
+ self.fh.write(np.ascontiguousarray(counts, dtype="<f8").tobytes())
505
+ for flt in LIMMA_FILTERS:
506
+ self.jobs.append({"job": f"{key}|{flt}", "offset": self.offset, "n_samples": counts.shape[0],
507
+ "is_case": "".join("1" if c else "0" for c in is_case), "filter": flt})
508
+ self.offset += counts.size
509
+ return info
510
+
511
+ def run(self, threads: int, log_path: Path) -> dict:
512
+ self.fh.close()
513
+ pd.DataFrame(self.jobs, columns=["job", "offset", "n_samples", "is_case", "filter"]).to_csv(
514
+ self.dir / "jobs.csv", index=False)
515
+ (self.dir / "n_genes.txt").write_text(f"{self.G}\n")
516
+ env = dict(os.environ, CUDA_VISIBLE_DEVICES="", OMP_NUM_THREADS=str(threads),
517
+ OPENBLAS_NUM_THREADS=str(threads), MKL_NUM_THREADS=str(threads))
518
+ t0 = time.monotonic()
519
+ res = subprocess.run([str(RSCRIPT), "--vanilla", str(R_SCRIPT), str(self.dir)], env=env, capture_output=True,
520
+ text=True)
521
+ log_path.write_text(res.stdout + "\n--- stderr ---\n" + res.stderr)
522
+ if res.returncode != 0:
523
+ raise SystemExit(f"limma Rscript failed (see {log_path})")
524
+ status = pd.read_csv(self.dir / "limma_status.csv")
525
+ raw = np.fromfile(self.dir / "limma.bin", dtype="<f8")
526
+ if raw.size != len(self.jobs) * self.G * 6:
527
+ raise SystemExit("limma.bin size differs from the job list")
528
+ out = {}
529
+ for i, j in enumerate(self.jobs):
530
+ m = raw[i * self.G * 6:(i + 1) * self.G * 6].reshape(6, self.G)
531
+ out[j["job"]] = {"logFC": m[0], "AveExpr": m[1], "t": m[2], "P": m[3], "q": m[4], "B": m[5],
532
+ "status": str(status.status.iloc[i])}
533
+ bad = status[~status.status.isin(["ok"])]
534
+ log(f"limma: {len(self.jobs)} jobs in {time.monotonic() - t0:.0f} s ({len(bad)} not ok)")
535
+ return {"results": out, "status": status, "seconds": round(time.monotonic() - t0, 1),
536
+ "versions": (self.dir / "versions.txt").read_text().strip().splitlines()}
537
+
538
+
539
+ def limma_top(res: dict | None, genes: list) -> dict:
540
+ """EV.top_deg_genes on a limma result (FDR = adj.P.Val < 0.05 over the tested genes, descending |logFC|, 50)."""
541
+ if res is None or res["status"] != "ok":
542
+ return {"top": [], "defined": False, "tested": np.zeros(len(genes), bool), "n_significant": 0}
543
+ tested = np.isfinite(res["P"])
544
+ deg = EV.DegResult(logfc=np.nan_to_num(res["logFC"], nan=0.0), pvalues=res["P"], qvalues=res["q"], tested=tested,
545
+ backend="limma_voom")
546
+ return {"top": EV.top_deg_genes(deg, genes, top_n=F.DEG_TOP_N, fdr=F.DEG_FDR), "defined": True, "tested": tested,
547
+ "n_significant": int(deg.significant(F.DEG_FDR).size)}
548
+
549
+
550
+ # =========================================================================== one unit
551
+ def run_unit(design: str, ds: str, draw: int | None, a) -> None:
552
+ out = unit_dir(design, ds, draw)
553
+ if (out / "manifest.json").is_file() and not a.force:
554
+ log(f"{out} done already")
555
+ return
556
+ out.mkdir(parents=True, exist_ok=True)
557
+ lock = out / ".in_progress"
558
+ if lock.is_file():
559
+ pid = int(lock.read_text().split()[0])
560
+ if Path(f"/proc/{pid}").exists():
561
+ log(f"{out} is being computed by pid {pid}; skipped")
562
+ return
563
+ lock.write_text(f"{os.getpid()} {F.now()}\n")
564
+ try:
565
+ _run_unit(design, ds, draw, a, out)
566
+ finally:
567
+ lock.unlink(missing_ok=True)
568
+
569
+
570
+ def _isclose(x, y) -> tuple[bool, float]:
571
+ x = float("nan") if x is None or (isinstance(x, float) and np.isnan(x)) else float(x)
572
+ y = float("nan") if y is None or pd.isna(y) else float(y)
573
+ if np.isnan(x) and np.isnan(y):
574
+ return True, 0.0
575
+ if np.isnan(x) or np.isnan(y):
576
+ return False, float("inf")
577
+ return abs(x - y) <= REPRO_TOL, abs(x - y)
578
+
579
+
580
+ def _run_unit(design: str, ds: str, draw: int | None, a, out: Path) -> None:
581
+ t_unit = time.monotonic()
582
+ spec = F.DATASETS[ds]
583
+ calls, notes = unit_calls(design, ds, draw)
584
+ summ, arms_of = {}, {}
585
+ for cdir, arms in calls:
586
+ s = json.loads((cdir / "summary.json").read_text())
587
+ use = tuple(s["arms"]) if arms is None else tuple(arms)
588
+ miss = [x for x in use if x not in s["arms"]]
589
+ if miss:
590
+ raise SystemExit(f"{cdir}: arms {miss} not scored there")
591
+ summ[cdir], arms_of[cdir] = s, use
592
+ first = summ[calls[0][0]]
593
+ donors = [str(x) for x in first["donors"]]
594
+ for cdir, s in summ.items():
595
+ if [str(x) for x in s["donors"]] != donors:
596
+ raise SystemExit(f"{cdir}: scored donors differ from {calls[0][0]}")
597
+ if s["reference"]["reference_sha256"] != first["reference"]["reference_sha256"]:
598
+ raise SystemExit(f"{cdir}: reference sha differs")
599
+ if s["contrast_definition"].get("case") != first["contrast_definition"].get("case") or \
600
+ s["contrast_definition"].get("ctrl") != first["contrast_definition"].get("ctrl"):
601
+ raise SystemExit(f"{cdir}: contrast differs from {calls[0][0]}")
602
+ meta = {"dataset": ds, "design": design, "unit": str(out.relative_to(OUT_ROOT / ds))}
603
+ cache = F.CACHE_ROOT / ds
604
+ ref, man = F.load_reference(cache)
605
+ if man["reference_sha256"] != first["reference"]["reference_sha256"]:
606
+ raise SystemExit(f"{cache}: reference sha differs from the scored one")
607
+ deg_ref = F.load_deg_reference(cache, man, ref)
608
+ v = light_view(ref, deg_ref, donors)
609
+ # ---------------- gene exclusion (Giroux: the scored call's --exclude-genes)
610
+ ex_calls = {json.dumps(s.get("gene_exclusion", {}).get("sha256")) for s in summ.values()}
611
+ if len(ex_calls) != 1:
612
+ raise SystemExit("calls of one unit differ in their gene exclusion")
613
+ gex = first.get("gene_exclusion")
614
+ repro_comparable = True
615
+ excl_path = None
616
+ if gex is not None:
617
+ excl_path = Path(gex["file"])
618
+ if a.exclude_genes is not None and sha256(Path(a.exclude_genes)) != gex["sha256"]:
619
+ raise SystemExit("--exclude-genes differs from the scored call's exclusion")
620
+ elif a.exclude_genes is not None:
621
+ excl_path = Path(a.exclude_genes)
622
+ repro_comparable = False # the scorer's numbers were made without this exclusion
623
+ elif ds == "giroux2022" and not a.allow_sex_genes:
624
+ raise SystemExit("giroux2022: the call has no sex-linked-gene exclusion; pass --exclude-genes "
625
+ f"{SEX_EXCL} (or --allow-sex-genes)")
626
+ gene_excl = None
627
+ if excl_path is not None:
628
+ v["keep"], gene_excl = S.gene_exclusion(excl_path, v["score_ids"])
629
+ if gex is not None and gene_excl["sha256"] != gex["sha256"]:
630
+ raise SystemExit("exclusion file sha differs from the scored call's")
631
+ gene_excl.pop("dropped", None)
632
+ genes_kept = S.keep_genes(v)
633
+ Gk = len(genes_kept)
634
+ contrast = contrast_from_summary(first, v)
635
+ if not contrast["enabled"]:
636
+ manifest = {"schema": "paired_ft_contrast_extra.v1", **meta, "written_utc": F.now(), "skipped": True,
637
+ "reason": f"no case-control contrast ({contrast.get('reason')})", "calls": [str(c) for c, _ in calls]}
638
+ (out / "manifest.json").write_text(json.dumps(manifest, indent=1) + "\n")
639
+ log(f"{out}: no contrast, skipped")
640
+ return
641
+ case, ctrl = contrast["case"], contrast["ctrl"]
642
+ S_ = v["donors"].size
643
+ log(f"{ds} {meta['unit']}: {S_} scored samples ({contrast['n_case_donors']} case / {contrast['n_control_donors']} "
644
+ f"control), {Gk} genes for the disease scores" + (f" ({gene_excl['n_dropped_from_scoring_genes']} excluded)"
645
+ if gene_excl else ""))
646
+ # ---------------- observed side
647
+ genes, obs_lfc = {}, {}
648
+ for ti, t in enumerate(F.CONTRAST_TYPES):
649
+ n_o = v["agg_n"][:, ti]
650
+ det = v["agg_det"][:, ti].sum(0) / max(int(n_o.sum()), 1)
651
+ gm = det >= F.MIN_DETECT_FRAC
652
+ if "keep" in v:
653
+ gm &= v["keep"]
654
+ genes[t] = gm
655
+ obs_lfc[(t, "mean_cp10k")] = F.lfc_mean_cp10k(n_o, v["agg_cp10k"][:, ti], case, ctrl)
656
+ obs_lfc[(t, "pseudobulk_log1p_cpm")] = F.lfc_pseudobulk(n_o, v["agg_sum"][:, ti], case, ctrl)
657
+ obs_deg = S.observed_deg(v, contrast) # the scorer's observed Welch lists
658
+ obs_welch = {t: welch_side(v["deg_n"][:, k], S.keep_cols(v, v["deg_sum"][:, k]), case, ctrl, genes_kept)
659
+ for k, t in enumerate(v["deg_types"])}
660
+ for t in v["deg_types"]:
661
+ if obs_welch[t]["top"] != obs_deg[t]["top"]:
662
+ raise SystemExit(f"{t}: observed Welch list differs between welch_side and score_ft.observed_deg")
663
+ work = OUT_ROOT / "_work" / ds / meta["unit"]
664
+ if work.exists():
665
+ shutil.rmtree(work)
666
+ lb = LimmaBatch(work, Gk)
667
+ for k, t in enumerate(v["deg_types"]):
668
+ rows = (v["deg_n"][:, k] > 0) & (case | ctrl)
669
+ lb.add(f"obs|{t}", S.keep_cols(v, v["deg_sum"][:, k])[rows], case[rows])
670
+ # ---------------- split half (observed only)
671
+ sh = split_half(spec, ref, man, cache, v, contrast, genes)
672
+ # ---------------- arms
673
+ fetched: list[Path] = []
674
+ fetched_all: set = set()
675
+ fetch_root = Path(a.fetch_dir)
676
+ panel_ids = ref["panel_ids"].astype(str)
677
+ score_idx = ref["score_idx"]
678
+ cond_cache: dict = {}
679
+ contrast_rows, half_rows, welch_rows, repro, arm_info = [], [], [], {"arms": {}}, {}
680
+ gen_lfc_store, bcast_store = {}, {}
681
+ pcache = a.pcache
682
+ for cdir, arms in ((c, arms_of[c]) for c, _ in calls):
683
+ s = summ[cdir]
684
+ ccsv = pd.read_csv(cdir / "contrast.csv")
685
+ for name in arms:
686
+ t0 = time.monotonic()
687
+ pa = s["per_arm"][name]
688
+ path = resolve_file(Path(pa["npz"]), pa["npz_sha256"], fetch_root, fetched, receipt=True)
689
+ if str(path).startswith(str(fetch_root)):
690
+ fetched_all.add(str(path))
691
+ arm = S.open_arm(name, path, panel_ids, allow_no_receipt=False)
692
+ if arm["sha256"] != pa["npz_sha256"] or not arm["receipt_verified"]:
693
+ raise SystemExit(f"{name}: NPZ sha / receipt check failed for {path}")
694
+ npos = {n_: i for i, n_ in enumerate(arm["sample_ids"])}
695
+ rws = [np.flatnonzero(arm["bulk_index"] == npos[x]) for x in v["donors"]]
696
+ sel = np.concatenate(rws)
697
+ gen_d = np.repeat(np.arange(S_), [x.size for x in rws])
698
+ if arm["sha256"] not in pcache:
699
+ rates = np.ascontiguousarray(arm["d"]["generated_counts"], dtype=np.float32)
700
+ full = F.PR.poisson_integerise(rates, seed=F.POISSON_SEED, chunk_rows=4096) # whole NPZ, row order
701
+ del rates
702
+ pcache[arm["sha256"]] = full[:, score_idx].tocsr()
703
+ del full
704
+ arm["d"].close()
705
+ Xg = pcache[arm["sha256"]][sel].tocsr()
706
+ gc = pd.read_parquet(cdir / "arms" / name / "generated_cells.parquet", columns=["npz_row", "donor", "label"])
707
+ if not (np.array_equal(gc.npz_row.to_numpy(), sel) and
708
+ np.array_equal(gc.donor.astype(str).to_numpy(), v["donors"][gen_d])):
709
+ raise SystemExit(f"{name}: scored rows differ from {cdir}/arms/{name}/generated_cells.parquet")
710
+ gen_lab = gc.label.astype(str).to_numpy()
711
+ labp = pd.read_parquet(cdir / "arms" / name / "labels" / "labels.parquet", columns=["celltype_l1_pred"])
712
+ if not np.array_equal(labp.celltype_l1_pred.astype(str).to_numpy(), gen_lab):
713
+ raise SystemExit(f"{name}: labels.parquet differs from generated_cells.parquet")
714
+ # condition bulk (broadcast)
715
+ cfb = pa["condition_for_broadcast"]
716
+ cpath = resolve_file(Path(cfb["path"]), cfb["sha256"], fetch_root, fetched, receipt=False)
717
+ if str(cpath).startswith(str(fetch_root)):
718
+ fetched_all.add(str(cpath))
719
+ if cfb["sha256"] not in cond_cache:
720
+ cond = S.load_condition_bulk(str(cpath), cfb["sha256"], v["donors"], ref["score_ids"].astype(str))
721
+ cond_cache[cfb["sha256"]] = {"bulk": cond["bulk"], "path": cfb["path"], "lfc": F.bulk_lfc(cond["bulk"], case, ctrl),
722
+ "label": f"{Path(cfb['path']).name}@{cfb['sha256'][:8]}"}
723
+ cond = cond_cache[cfb["sha256"]]
724
+ bulk, blk = cond["bulk"], cond["lfc"]
725
+ # ---- 1. contrast (Pearson = scorer, Spearman new)
726
+ ga = F.type_aggregates(Xg, gen_d, gen_lab, S_)
727
+ rep = {"contrast_max_abs_diff": 0.0, "contrast_all_equal": True, "n_genes_equal": True}
728
+ for ti, t in enumerate(F.CONTRAST_TYPES):
729
+ gm = genes[t]
730
+ for variant, fn, key in (("mean_cp10k", F.lfc_mean_cp10k, "cp10k"),
731
+ ("pseudobulk_log1p_cpm", F.lfc_pseudobulk, "sum")):
732
+ o = obs_lfc[(t, variant)]
733
+ g = fn(ga["n"][:, ti], ga[key][:, ti], case, ctrl)
734
+ sc = F.contrast_scores(o, g, blk[variant], gm)
735
+ ok = o is not None and gm.sum() >= 3
736
+ row = {"arm": name, "celltype": t, "statistic": variant, "n_genes": sc["n_genes"],
737
+ "pearson_r_generated": sc["r_generated"],
738
+ "spearman_r_generated": spearman(g[gm], o[gm]) if ok and g is not None else float("nan"),
739
+ "pearson_r_broadcast": sc["r_broadcast"],
740
+ "spearman_r_broadcast": spearman(blk[variant][gm], o[gm]) if ok and blk[variant] is not None
741
+ else float("nan"),
742
+ "partial_r_generated_given_broadcast": sc["partial_r_generated_given_broadcast"],
743
+ "r_generated_vs_broadcast": sc["r_generated_vs_broadcast"],
744
+ "condition": cond["label"], "condition_sha256": cfb["sha256"]}
745
+ sr = ccsv[(ccsv.arm == name) & (ccsv.celltype == t) & (ccsv.statistic == variant)]
746
+ if len(sr) != 1:
747
+ raise SystemExit(f"{cdir}/contrast.csv: no unique row for {name} {t} {variant}")
748
+ sr = sr.iloc[0]
749
+ for ours, theirs in (("pearson_r_generated", "r_generated"), ("pearson_r_broadcast", "r_broadcast"),
750
+ ("partial_r_generated_given_broadcast", "partial_r_generated_given_broadcast"),
751
+ ("r_generated_vs_broadcast", "r_generated_vs_broadcast")):
752
+ row[f"{ours}_scorer"] = sr[theirs]
753
+ eq, dif = _isclose(row[ours], sr[theirs])
754
+ rep["contrast_all_equal"] &= eq
755
+ rep["contrast_max_abs_diff"] = max(rep["contrast_max_abs_diff"], dif)
756
+ rep["n_genes_equal"] &= int(sr.n_genes) == row["n_genes"]
757
+ contrast_rows.append(row)
758
+ if variant == "mean_cp10k":
759
+ gen_lfc_store[(name, t)] = g
760
+ # ---- 2. split half: generated and broadcast vs half B
761
+ for t in F.CONTRAST_TYPES:
762
+ gm, g = genes[t], gen_lfc_store[(name, t)]
763
+ for seed in SPLIT_SEEDS:
764
+ hb = sh["halfB"][(seed, t)]
765
+ ok = hb is not None and gm.sum() >= 3
766
+ half_rows.append({"predictor": f"generated:{name}", "arm": name, "celltype": t, "seed": seed,
767
+ "pearson": EV.pearson(g[gm], hb[gm]) if ok and g is not None else float("nan"),
768
+ "spearman": spearman(g[gm], hb[gm]) if ok and g is not None else float("nan")})
769
+ key = (cfb["sha256"], t, seed)
770
+ if key not in bcast_store:
771
+ b = blk["mean_cp10k"]
772
+ bcast_store[key] = {"predictor": f"broadcast:{cond['label']}", "arm": "", "celltype": t,
773
+ "seed": seed, "condition_sha256": cfb["sha256"],
774
+ "pearson": EV.pearson(b[gm], hb[gm]) if ok and b is not None else float("nan"),
775
+ "spearman": spearman(b[gm], hb[gm]) if ok and b is not None else float("nan")}
776
+ # ---- 3. Welch top-50 reproduction (score_ft.deg_block) + tested masks + limma jobs
777
+ drows, block = S.deg_block(v, obs_deg, ga, Xg, gen_d, gen_lab, bulk, contrast)
778
+ extra = tuple(t for t in v["deg_types"] if t not in F.CONTRAST_TYPES)
779
+ gx = F.type_aggregates(Xg, gen_d, gen_lab, S_, types=extra) if extra else None
780
+ lcols = ["celltype", "source", "rank", "gene_id"]
781
+ sl = pd.read_csv(cdir / "arms" / name / "deg_top50_lists.csv", dtype=str)
782
+ ours_l = pd.DataFrame(block["_lists"], columns=lcols)
783
+ rep["welch_lists_equal"] = [tuple(x) for x in ours_l.astype(str).to_numpy()] == \
784
+ [tuple(x) for x in sl[lcols].astype(str).to_numpy()]
785
+ rep["welch_counts_equal"] = True
786
+ dsc = ccsv[(ccsv.arm == name) & (ccsv.statistic == F.DEG_STATISTIC)].set_index("celltype")
787
+ bw = welch_side(np.ones(S_, np.int64), S.keep_cols(v, bulk), case, ctrl, genes_kept)
788
+ for r in drows:
789
+ t = r["celltype"]
790
+ for c in ("top50_overlap", "n_sig_obs", "n_sig_gen", "obs_top_list_size", "gen_top_list_size",
791
+ "top50_overlap_broadcast", "n_sig_broadcast"):
792
+ if int(dsc.loc[t, c]) != int(r[c]):
793
+ rep["welch_counts_equal"] = False
794
+ k = v["deg_types"].index(t)
795
+ if t in F.CONTRAST_TYPES:
796
+ n_g, s_g = ga["n"][:, F.CONTRAST_TYPES.index(t)], ga["sum"][:, F.CONTRAST_TYPES.index(t)]
797
+ else:
798
+ n_g, s_g = gx["n"][:, extra.index(t)], gx["sum"][:, extra.index(t)]
799
+ gw = welch_side(n_g, S.keep_cols(v, s_g), case, ctrl, genes_kept)
800
+ if gw["top"] != [x for x in ours_l[(ours_l.celltype == t) & (ours_l.source == "generated")].gene_id]:
801
+ raise SystemExit(f"{name} {t}: welch_side list differs from score_ft.deg_block")
802
+ ow = obs_welch[t]
803
+ Gg = int((ow["tested"] & gw["tested"]).sum())
804
+ Gb = int((ow["tested"] & bw["tested"]).sum())
805
+ welch_rows.append({"arm": name, "celltype": t, "method": "welch", "deg_scored": ow["defined"],
806
+ "pred_defined": gw["defined"], "overlap": len(set(ow["top"]) & set(gw["top"])),
807
+ "overlap_scorer": int(dsc.loc[t, "top50_overlap"]),
808
+ "obs_list_size": len(ow["top"]), "gen_list_size": len(gw["top"]),
809
+ "n_sig_obs": ow["n_significant"], "n_sig_gen": gw["n_significant"],
810
+ "n_tested_obs": int(ow["tested"].sum()), "n_tested_gen": int(gw["tested"].sum()),
811
+ "G_both": Gg, "chance_overlap": expected_overlap(len(ow["top"]), len(gw["top"]), Gg),
812
+ "broadcast_overlap": len(set(ow["top"]) & set(bw["top"])),
813
+ "broadcast_overlap_scorer": int(dsc.loc[t, "top50_overlap_broadcast"]),
814
+ "broadcast_list_size": len(bw["top"]), "n_sig_broadcast": bw["n_significant"],
815
+ "n_tested_broadcast": int(bw["tested"].sum()), "G_both_broadcast": Gb,
816
+ "broadcast_chance_overlap": expected_overlap(len(ow["top"]), len(bw["top"]), Gb),
817
+ "condition": cond["label"]})
818
+ wr = welch_rows[-1]
819
+ if wr["overlap"] != wr["overlap_scorer"] or wr["broadcast_overlap"] != wr["broadcast_overlap_scorer"]:
820
+ rep["welch_counts_equal"] = False
821
+ rows_ = (n_g > 0) & (case | ctrl)
822
+ lb.add(f"gen:{name}|{t}", S.keep_cols(v, s_g)[rows_], case[rows_])
823
+ ckey = f"bcast:{cfb['sha256'][:16]}"
824
+ if ckey not in lb.meta:
825
+ lb.add(ckey, S.keep_cols(v, bulk)[case | ctrl], case[case | ctrl])
826
+ arm_info[name] = {"call": str(cdir), "npz": pa["npz"], "npz_read_from": str(path), "npz_sha256": arm["sha256"],
827
+ "receipt_verified": arm["receipt_verified"], "condition": cfb["path"],
828
+ "condition_sha256": cfb["sha256"], "condition_label": cond["label"],
829
+ "condition_read_from": str(cpath),
830
+ "condition_key": ckey, "n_generated_cells": int(sel.size),
831
+ "label": ARM_LABEL.get(name, name), "seconds": round(time.monotonic() - t0, 1)}
832
+ rep["pass"] = bool(rep["contrast_all_equal"] and rep["n_genes_equal"] and rep["welch_lists_equal"]
833
+ and rep["welch_counts_equal"])
834
+ repro["arms"][name] = rep
835
+ log(f"{name}: {sel.size} cells; r mean_cp10k "
836
+ + ", ".join(f"{F.SHORT_TYPE[r['celltype']]} {r['pearson_r_generated']:.3f}/{r['spearman_r_generated']:.3f}"
837
+ for r in contrast_rows if r["arm"] == name and r["statistic"] == "mean_cp10k")
838
+ + f" (Pearson/Spearman); repro {'PASS' if rep['pass'] else 'FAIL'} "
839
+ f"(max |d| {rep['contrast_max_abs_diff']:.1e}) ({time.monotonic() - t0:.0f} s)")
840
+ del Xg, ga, gx
841
+ if not (design == "fewshot" and arm["sha256"] in a.shared_shas):
842
+ pcache.pop(arm["sha256"], None)
843
+ if path in fetched and not (design == "fewshot" and path.name.endswith("_all.npz")):
844
+ drop_fetched(path)
845
+ fetched.remove(path)
846
+ for f in [f for f in fetched if f.name.startswith("conditions_")]:
847
+ drop_fetched(f)
848
+ fetched.remove(f)
849
+ # ---------------- extra reproduction: sepsis pooled_deg contrast vs pooled
850
+ if "contrast_also_checked_against" in notes:
851
+ other = pd.read_csv(Path(notes["contrast_also_checked_against"]) / "contrast.csv")
852
+ other = other[other.statistic.isin(STATS)].set_index(["arm", "celltype", "statistic"])
853
+ mx = 0.0
854
+ for r in contrast_rows:
855
+ k = (r["arm"], r["celltype"], r["statistic"])
856
+ if k in other.index:
857
+ for ours, theirs in (("pearson_r_generated", "r_generated"), ("pearson_r_broadcast", "r_broadcast"),
858
+ ("partial_r_generated_given_broadcast", "partial_r_generated_given_broadcast")):
859
+ eq, dif = _isclose(r[ours], other.loc[k, theirs])
860
+ mx = max(mx, dif)
861
+ repro["contrast_vs_other_call"] = {"call": notes["contrast_also_checked_against"], "max_abs_diff": mx,
862
+ "pass": mx <= REPRO_TOL}
863
+ # ---------------- limma
864
+ lim = lb.run(a.threads, out / "limma_R.log")
865
+ (out / "limma").mkdir(exist_ok=True)
866
+ for f in ("jobs.csv", "limma_status.csv", "versions.txt"):
867
+ shutil.copy2(work / f, out / "limma" / f)
868
+ shutil.move(str(out / "limma_R.log"), str(out / "limma" / "R.log"))
869
+ R = lim["results"]
870
+ deg_rows, cat_rows, rbo_rows = list(welch_rows), [], []
871
+ lim_obs = {flt: {t: limma_top(R.get(f"obs|{t}|{flt}"), genes_kept) for t in v["deg_types"]} for flt in LIMMA_FILTERS}
872
+ obs_rank = {t: rank_orders(R[f"obs|{t}|{PRIMARY_FILTER}"]["t"]) if f"obs|{t}|{PRIMARY_FILTER}" in R else None
873
+ for t in v["deg_types"]}
874
+ bc_rank_cache = {}
875
+ for name, info in arm_info.items():
876
+ ck = info["condition_key"]
877
+ for flt in LIMMA_FILTERS:
878
+ bres = limma_top(R.get(f"{ck}|{flt}"), genes_kept)
879
+ for t in v["deg_types"]:
880
+ ol = lim_obs[flt][t]
881
+ gl = limma_top(R.get(f"gen:{name}|{t}|{flt}"), genes_kept)
882
+ Gg = int((ol["tested"] & gl["tested"]).sum())
883
+ Gb = int((ol["tested"] & bres["tested"]).sum())
884
+ deg_rows.append({"arm": name, "celltype": t, "method": f"limma_voom_{flt}", "deg_scored": ol["defined"],
885
+ "pred_defined": gl["defined"], "overlap": len(set(ol["top"]) & set(gl["top"])),
886
+ "overlap_scorer": None, "obs_list_size": len(ol["top"]), "gen_list_size": len(gl["top"]),
887
+ "n_sig_obs": ol["n_significant"], "n_sig_gen": gl["n_significant"],
888
+ "n_tested_obs": int(ol["tested"].sum()), "n_tested_gen": int(gl["tested"].sum()),
889
+ "G_both": Gg, "chance_overlap": expected_overlap(len(ol["top"]), len(gl["top"]), Gg),
890
+ "broadcast_overlap": len(set(ol["top"]) & set(bres["top"])),
891
+ "broadcast_overlap_scorer": None, "broadcast_list_size": len(bres["top"]),
892
+ "n_sig_broadcast": bres["n_significant"], "n_tested_broadcast": int(bres["tested"].sum()),
893
+ "G_both_broadcast": Gb,
894
+ "broadcast_chance_overlap": expected_overlap(len(ol["top"]), len(bres["top"]), Gb),
895
+ "condition": info["condition_label"]})
896
+ # CAT / RBO on the primary limma ranking
897
+ bkey = f"{ck}|{PRIMARY_FILTER}"
898
+ if ck not in bc_rank_cache:
899
+ bc_rank_cache[ck] = rank_orders(R[bkey]["t"]) if bkey in R and R[bkey]["status"] == "ok" else None
900
+ for t in v["deg_types"]:
901
+ orank = obs_rank[t]
902
+ if orank is None or R[f"obs|{t}|{PRIMARY_FILTER}"]["status"] != "ok":
903
+ continue
904
+ gkey = f"gen:{name}|{t}|{PRIMARY_FILTER}"
905
+ grank = rank_orders(R[gkey]["t"]) if gkey in R and R[gkey]["status"] == "ok" else None
906
+ for pname, prank in ((f"generated:{name}", grank), (f"broadcast:{info['condition_label']}",
907
+ bc_rank_cache[ck])):
908
+ G_both = int((orank["tested"] & prank["tested"]).sum()) if prank is not None else 0
909
+ for c in cat_curve(orank["abs"], orank["sign"], None if prank is None else prank["abs"],
910
+ None if prank is None else prank["sign"]):
911
+ cs, ca = cat_chance(c["k"], G_both if prank is not None else int(orank["tested"].sum()))
912
+ cat_rows.append({"arm": name, "predictor": pname, "celltype": t, **c, "chance_same_sign": cs,
913
+ "chance_any_sign": ca, "G_both": G_both, "pred_defined": prank is not None,
914
+ "n_tested_obs": int(orank["tested"].sum()),
915
+ "n_tested_pred": int(prank["tested"].sum()) if prank is not None else 0})
916
+ up = rbo_ext(list(orank["up"]), list(prank["up"]), RBO_P) if prank is not None else 0.0
917
+ dn = rbo_ext(list(orank["down"]), list(prank["down"]), RBO_P) if prank is not None else 0.0
918
+ rbo_rows.append({"arm": name, "predictor": pname, "celltype": t, "p": RBO_P, "rbo_ext_t_desc": up,
919
+ "rbo_ext_t_asc": dn, "rbo_ext_mean_up_down": (up + dn) / 2, "pred_defined": prank is not None,
920
+ "len_obs": int(orank["tested"].sum()),
921
+ "len_pred": int(prank["tested"].sum()) if prank is not None else 0})
922
+ # ---------------- assemble tables
923
+ def prefixed(df: pd.DataFrame) -> pd.DataFrame:
924
+ for k, x in reversed(list(meta.items())):
925
+ df.insert(0, k, x)
926
+ return df
927
+
928
+ cdf = pd.DataFrame(contrast_rows)
929
+ m4 = (cdf.groupby(["arm", "statistic"], sort=False)[[c for c in cdf.columns if c.startswith(("pearson", "spearman",
930
+ "partial", "r_gen"))]]
931
+ .agg(lambda x: float(np.nanmean(x)) if pd.notna(x).any() else float("nan")).reset_index())
932
+ m4["celltype"] = "mean4"
933
+ cdf = pd.concat([cdf, m4], ignore_index=True)
934
+ cdf.insert(3, "label", cdf.arm.map(lambda x: ARM_LABEL.get(x, x)))
935
+ prefixed(cdf).to_csv(out / "contrast.csv", index=False)
936
+ # ceiling.csv: split-half (ceiling) + generated / broadcast vs half B
937
+ ps = pd.DataFrame(sh["per_seed"])
938
+ ps["predictor"], ps["arm"] = "split_half_A_vs_B", ""
939
+ hr = pd.concat([ps, pd.DataFrame(half_rows), pd.DataFrame(list(bcast_store.values()))], ignore_index=True)
940
+ ceil_rows = []
941
+ for (pred, arm_, t), sub in hr.groupby(["predictor", "arm", "celltype"], sort=False):
942
+ sub = sub.set_index("seed").reindex(list(SPLIT_SEEDS))
943
+ r = {"predictor": pred, "arm": arm_, "celltype": t, "n_genes": int(genes[t].sum()),
944
+ "pearson_mean": float(sub.pearson.mean()), "pearson_sd": float(sub.pearson.std(ddof=1)),
945
+ "spearman_mean": float(sub.spearman.mean()), "spearman_sd": float(sub.spearman.std(ddof=1))}
946
+ for sd_ in SPLIT_SEEDS:
947
+ r[f"pearson_s{sd_}"], r[f"spearman_s{sd_}"] = sub.loc[sd_, "pearson"], sub.loc[sd_, "spearman"]
948
+ if pred == "split_half_A_vs_B":
949
+ r.update({"sb_reliability_pearson": spearman_brown(r["pearson_mean"]),
950
+ "noise_free_ceiling_pearson": noise_free_ceiling(r["pearson_mean"]),
951
+ "sb_reliability_spearman": spearman_brown(r["spearman_mean"]),
952
+ "noise_free_ceiling_spearman": noise_free_ceiling(r["spearman_mean"])})
953
+ for c in ("n_case_donors_A", "n_control_donors_A", "n_case_donors_B", "n_control_donors_B"):
954
+ r[f"min_{c}"] = int(sub[c].min())
955
+ r["mean_n_cells_A"], r["mean_n_cells_B"] = float(sub.n_cells_A.mean()), float(sub.n_cells_B.mean())
956
+ if "condition_sha256" in sub.columns and sub.condition_sha256.notna().any():
957
+ r["condition_sha256"] = sub.condition_sha256.dropna().iloc[0]
958
+ ceil_rows.append(r)
959
+ for (pred, arm_), sub in hr.groupby(["predictor", "arm"], sort=False): # mean over the 4 types, per seed
960
+ per_seed = sub.groupby("seed")[["pearson", "spearman"]].mean().reindex(list(SPLIT_SEEDS))
961
+ r = {"predictor": pred, "arm": arm_, "celltype": "mean4",
962
+ "pearson_mean": float(per_seed.pearson.mean()), "pearson_sd": float(per_seed.pearson.std(ddof=1)),
963
+ "spearman_mean": float(per_seed.spearman.mean()), "spearman_sd": float(per_seed.spearman.std(ddof=1))}
964
+ for sd_ in SPLIT_SEEDS:
965
+ r[f"pearson_s{sd_}"], r[f"spearman_s{sd_}"] = per_seed.loc[sd_, "pearson"], per_seed.loc[sd_, "spearman"]
966
+ if pred == "split_half_A_vs_B":
967
+ tt = [x for x in ceil_rows if x["predictor"] == pred]
968
+ for c in ("sb_reliability_pearson", "noise_free_ceiling_pearson", "sb_reliability_spearman",
969
+ "noise_free_ceiling_spearman"):
970
+ vals = [x[c] for x in tt]
971
+ r[c] = float(np.nanmean(vals)) if np.isfinite(vals).any() else float("nan")
972
+ if "condition_sha256" in sub.columns and sub.condition_sha256.notna().any():
973
+ r["condition_sha256"] = sub.condition_sha256.dropna().iloc[0]
974
+ ceil_rows.append(r)
975
+ prefixed(pd.DataFrame(ceil_rows)).to_csv(out / "ceiling.csv", index=False)
976
+ ddf = pd.DataFrame(deg_rows)
977
+ prefixed(ddf).to_csv(out / "deg_limma.csv", index=False)
978
+ cat_df = pd.DataFrame(cat_rows)
979
+ prefixed(cat_df).to_csv(out / "cat.csv", index=False)
980
+ rbo_df = pd.DataFrame(rbo_rows)
981
+ prefixed(rbo_df).to_csv(out / "rbo.csv", index=False)
982
+ # ---------------- headline (one row per arm)
983
+ ceil = pd.DataFrame(ceil_rows)
984
+ sh4 = ceil[(ceil.predictor == "split_half_A_vs_B") & (ceil.celltype == "mean4")].iloc[0]
985
+ heads = []
986
+ for name, info in arm_info.items():
987
+ c4 = cdf[(cdf.arm == name) & (cdf.statistic == "mean_cp10k") & (cdf.celltype == "mean4")].iloc[0]
988
+ gB = ceil[(ceil.predictor == f"generated:{name}") & (ceil.celltype == "mean4")].iloc[0]
989
+ bB = ceil[(ceil.predictor == f"broadcast:{info['condition_label']}") & (ceil.celltype == "mean4")]
990
+ h = {"arm": name, "label": info["label"], "role": ROLE.get(name, "other"), "condition": info["condition_label"],
991
+ "pearson_r": c4.pearson_r_generated, "spearman_r": c4.spearman_r_generated,
992
+ "partial_r": c4.partial_r_generated_given_broadcast,
993
+ "broadcast_pearson_r": c4.pearson_r_broadcast, "broadcast_spearman_r": c4.spearman_r_broadcast,
994
+ "splithalf_r_AB": sh4.pearson_mean, "splithalf_r_AB_sd": sh4.pearson_sd,
995
+ "splithalf_spearman_AB": sh4.spearman_mean,
996
+ "sb_reliability": sh4.sb_reliability_pearson, "noise_free_ceiling": sh4.noise_free_ceiling_pearson,
997
+ "r_generated_vs_halfB": gB.pearson_mean, "r_broadcast_vs_halfB": bB.pearson_mean.iloc[0] if len(bB) else np.nan}
998
+ for meth in ("welch", f"limma_voom_{PRIMARY_FILTER}", "limma_voom_filterByExpr"):
999
+ sub = ddf[(ddf.arm == name) & (ddf.method == meth) & ddf.deg_scored.astype(bool)]
1000
+ tag = {"welch": "welch", f"limma_voom_{PRIMARY_FILTER}": "limma", "limma_voom_filterByExpr": "limma_fbe"}[meth]
1001
+ h[f"{tag}_top50"] = int(sub.overlap.sum())
1002
+ h[f"{tag}_top50_max"] = int(sub.obs_list_size.sum())
1003
+ h[f"{tag}_top50_chance"] = float(sub.chance_overlap.fillna(0).sum())
1004
+ h[f"{tag}_top50_broadcast"] = int(sub.broadcast_overlap.sum())
1005
+ h[f"{tag}_top50_broadcast_chance"] = float(sub.broadcast_chance_overlap.fillna(0).sum())
1006
+ h[f"{tag}_n_sig_obs"] = int(sub.n_sig_obs.sum())
1007
+ h[f"{tag}_n_sig_gen"] = int(sub.n_sig_gen.sum())
1008
+ h[f"{tag}_n_sig_broadcast_per_type"] = int(sub.n_sig_broadcast.iloc[0]) if len(sub) else 0
1009
+ h[f"{tag}_types_scored"] = int(len(sub))
1010
+ for pred, tag in ((f"generated:{name}", ""), (f"broadcast:{info['condition_label']}", "broadcast_")):
1011
+ cs = cat_df[(cat_df.arm == name) & (cat_df.predictor == pred)] if len(cat_df) else cat_df
1012
+ for k in (50, 100):
1013
+ sk = cs[cs.k == k] if len(cs) else cs
1014
+ h[f"{tag}cat{k}"] = float(sk.cat_same_sign.mean()) if len(sk) else np.nan
1015
+ h[f"{tag}cat{k}_chance"] = float(sk.chance_same_sign.mean()) if len(sk) else np.nan
1016
+ rs = rbo_df[(rbo_df.arm == name) & (rbo_df.predictor == pred)] if len(rbo_df) else rbo_df
1017
+ h[f"{tag}rbo"] = float(rs.rbo_ext_t_desc.mean()) if len(rs) else np.nan
1018
+ h[f"{tag}rbo_up_down"] = float(rs.rbo_ext_mean_up_down.mean()) if len(rs) else np.nan
1019
+ h[f"{tag}cat_types"] = int(rs.celltype.nunique()) if len(rs) else 0
1020
+ h["repro_pass"] = repro["arms"][name]["pass"] if repro_comparable else None
1021
+ heads.append(h)
1022
+ hdf = pd.DataFrame(heads)
1023
+ prefixed(hdf).to_csv(out / "headline.csv", index=False)
1024
+ # ---------------- repro + manifest
1025
+ repro["observed_split_half_full_aggregates"] = sh["check_full_aggregates"]
1026
+ repro["comparable_with_scorer"] = repro_comparable
1027
+ repro["all_pass"] = bool(all(r["pass"] for r in repro["arms"].values())
1028
+ and repro.get("contrast_vs_other_call", {}).get("pass", True)) if repro_comparable else None
1029
+ (out / "repro.json").write_text(json.dumps(repro, indent=1, default=float) + "\n")
1030
+ code = a.code_sha
1031
+ manifest = {"schema": "paired_ft_contrast_extra.v1", **meta, "written_utc": F.now(), "command": sys.argv,
1032
+ "threads": a.threads, "donors": list(map(str, v["donors"])), "n_samples": int(S_),
1033
+ "contrast": {k: contrast[k] for k in ("case_groups", "control_groups", "n_case_donors",
1034
+ "n_control_donors")},
1035
+ "calls": {str(c): {"arms": list(arms_of[c]), "summary_sha256": sha256(c / "summary.json"),
1036
+ "contrast_csv_sha256": sha256(c / "contrast.csv")} for c, _ in calls},
1037
+ "notes": notes, "reference_sha256": man["reference_sha256"],
1038
+ "deg_reference": {"source": deg_ref["source"], "sha256": deg_ref["sha256"]},
1039
+ "gene_exclusion": gene_excl, "n_genes_disease_scores": Gk,
1040
+ "genes_per_type": {t: int(genes[t].sum()) for t in F.CONTRAST_TYPES},
1041
+ "arms": arm_info, "observed_cells": {"inputs_sha256": man["cells"]["inputs_sha256"],
1042
+ "labels_sha256": man["labels"]["sha256"],
1043
+ "n_cells_4types_scored": sh["n_cells_used"]},
1044
+ "params": {"split_seeds": list(SPLIT_SEEDS),
1045
+ "split_rule": "per scored sample x contrast type: permutation from default_rng([seed, "
1046
+ "uint64 LE of sha256('<sample>|<type>')[:8]]) of its cells in canonical order; "
1047
+ "half A = first floor(n/2) positions, half B = the rest",
1048
+ "cat_ks": list(CAT_KS), "rbo_p": RBO_P, "limma_filters": list(LIMMA_FILTERS),
1049
+ "primary_filter": PRIMARY_FILTER, "fdr": F.DEG_FDR, "top_n": F.DEG_TOP_N,
1050
+ "min_detect_frac": F.MIN_DETECT_FRAC, "poisson_seed": F.POISSON_SEED,
1051
+ "repro_tol": REPRO_TOL},
1052
+ "limma": {"rscript": str(RSCRIPT), "versions": lim["versions"], "n_jobs": len(lb.jobs),
1053
+ "n_not_ok": int((lim["status"].status != "ok").sum()), "seconds": lim["seconds"],
1054
+ "job_matrices": lb.meta},
1055
+ "repro_all_pass": repro["all_pass"], "split_half_seconds": sh["seconds"],
1056
+ "fetched_from_server2": sorted(fetched_all), "code_sha256": code,
1057
+ "seconds": round(time.monotonic() - t_unit, 1)}
1058
+ (out / "manifest.json").write_text(json.dumps(manifest, indent=1, default=float) + "\n")
1059
+ shutil.rmtree(work, ignore_errors=True)
1060
+ log(f"unit {meta['unit']} of {ds} -> {out} in {manifest['seconds']} s; reproduction "
1061
+ f"{'PASS' if repro['all_pass'] else ('n/a' if repro['all_pass'] is None else 'FAIL')}")
1062
+
1063
+
1064
+ # =========================================================================== collect
1065
+ LC_LORA = {"zs__raw": 0, "zs__cal": 0, "lora_n5__raw": 5, "lora_n10__raw": 10, "lora_n20__raw": 20,
1066
+ "lora_n40__raw": 40, "real_lora__raw": "all"}
1067
+ LC_CAL = {"zs__cal_n5": 5, "zs__cal_n10": 10, "zs__cal_n20": 20, "zs__cal_n40": 40}
1068
+
1069
+
1070
+ def collect() -> None:
1071
+ """Concatenate every unit into scores_contrast/<design>_<table>.csv, fewshot_summary.csv (mean +- SD over draws),
1072
+ learning_curve_*.csv (sepsis pooled LoRA subsets + equal-budget calibration) and reproduction_check.csv."""
1073
+ units = sorted(p.parent for p in OUT_ROOT.glob("*/**/manifest.json")
1074
+ if not any(x.startswith("_") for x in p.relative_to(OUT_ROOT).parts))
1075
+ tabs = {k: [] for k in ("contrast", "ceiling", "deg_limma", "cat", "rbo", "headline")}
1076
+ rep, skipped, runtime = [], [], []
1077
+ for u in units:
1078
+ m = json.loads((u / "manifest.json").read_text())
1079
+ if m.get("skipped"):
1080
+ skipped.append({"dataset": m["dataset"], "unit": m["unit"], "reason": m["reason"]})
1081
+ continue
1082
+ runtime.append({"dataset": m["dataset"], "design": m["design"], "unit": m["unit"], "seconds": m["seconds"],
1083
+ "split_half_seconds": m["split_half_seconds"], "limma_seconds": m["limma"]["seconds"],
1084
+ "n_samples": m["n_samples"], "n_arms": len(m["arms"])})
1085
+ for k in tabs:
1086
+ tabs[k].append(pd.read_csv(u / f"{k}.csv"))
1087
+ r = json.loads((u / "repro.json").read_text())
1088
+ for arm, x in r["arms"].items():
1089
+ rep.append({"dataset": m["dataset"], "design": m["design"], "unit": m["unit"], "arm": arm,
1090
+ "contrast_max_abs_diff": x["contrast_max_abs_diff"], "contrast_all_equal": x["contrast_all_equal"],
1091
+ "n_genes_equal": x["n_genes_equal"], "welch_lists_equal": x["welch_lists_equal"],
1092
+ "welch_counts_equal": x["welch_counts_equal"], "pass": x["pass"],
1093
+ "observed_aggregates_rebuilt": all(r["observed_split_half_full_aggregates"][c] for c in
1094
+ ("n_equal", "det_equal", "sum_equal_float32")),
1095
+ "observed_cp10k_max_abs_diff_float32":
1096
+ r["observed_split_half_full_aggregates"]["cp10k_max_abs_diff_float32"],
1097
+ "other_call_max_abs_diff": r.get("contrast_vs_other_call", {}).get("max_abs_diff")})
1098
+ if not runtime:
1099
+ log("nothing to collect")
1100
+ return
1101
+ cat = {k: pd.concat(v_, ignore_index=True) for k, v_ in tabs.items()}
1102
+
1103
+ def design_of(df):
1104
+ return np.where(df.unit.str.startswith("fewshot_n5"), "fewshot",
1105
+ np.where(df.unit == "pooled", "pooled", "scored"))
1106
+ for k, df in cat.items():
1107
+ df["_d"] = design_of(df)
1108
+ for d, sub in df.groupby("_d"):
1109
+ sub.drop(columns="_d").to_csv(OUT_ROOT / f"{d}_{k}.csv", index=False)
1110
+ pd.DataFrame(rep).to_csv(OUT_ROOT / "reproduction_check.csv", index=False)
1111
+ pd.DataFrame(runtime).to_csv(OUT_ROOT / "run_time.csv", index=False)
1112
+ if skipped:
1113
+ pd.DataFrame(skipped).to_csv(OUT_ROOT / "skipped_units.csv", index=False)
1114
+ h = cat["headline"]
1115
+ few = h[h._d == "fewshot"].drop(columns="_d")
1116
+ if len(few):
1117
+ num = [c for c in few.columns if c not in ("dataset", "design", "unit", "arm", "label", "role", "condition")
1118
+ and pd.api.types.is_numeric_dtype(few[c])]
1119
+ g = few.groupby(["dataset", "arm", "label", "role"], sort=False)
1120
+ summ = g[num].mean().add_suffix("_mean").join(g[num].std(ddof=1).add_suffix("_sd")).join(
1121
+ g.size().rename("n_draws")).reset_index()
1122
+ summ.to_csv(OUT_ROOT / "fewshot_summary.csv", index=False)
1123
+ lc = []
1124
+ for _, r in h[(h.dataset == "ye2026_sepsis") & (h.unit == "pooled") & h.arm.isin(list(LC_LORA))].iterrows():
1125
+ lc.append({**r.drop("_d").to_dict(), "series": "lora" if r.arm not in ("zs__raw", "zs__cal") else r.arm,
1126
+ "pairs": LC_LORA[r.arm]})
1127
+ for _, r in h[(h.dataset == "ye2026_sepsis") & (h.unit == "cal_budget_20261001/pooled")].iterrows():
1128
+ lc.append({**r.drop("_d").to_dict(), "series": "zs_cal_budget", "pairs": LC_CAL.get(r.arm, r.arm)})
1129
+ if lc:
1130
+ pd.DataFrame(lc).to_csv(OUT_ROOT / "learning_curve_headline.csv", index=False)
1131
+ keys = {(x["unit"], x["arm"]) for x in lc}
1132
+ for k in ("contrast", "ceiling", "deg_limma", "cat", "rbo"):
1133
+ df = cat[k]
1134
+ m_ = [(u, a_) in keys for u, a_ in zip(df.unit, df.arm)] if "arm" in df.columns else []
1135
+ sub = df[(df.dataset == "ye2026_sepsis") & np.asarray(m_, bool)].drop(columns="_d")
1136
+ if k == "ceiling": # arm-independent rows (split half, broadcast) of the two units too
1137
+ extra = df[(df.dataset == "ye2026_sepsis") & df.unit.isin(["pooled", "cal_budget_20261001/pooled"])
1138
+ & (df.arm.isna() | (df.arm == ""))].drop(columns="_d")
1139
+ sub = pd.concat([extra, sub], ignore_index=True)
1140
+ sub.to_csv(OUT_ROOT / f"learning_curve_{k}.csv", index=False)
1141
+ log(f"collected {len(runtime)} units; reproduction pass {sum(bool(r['pass']) for r in rep)}/{len(rep)} arms")
1142
+
1143
+
1144
+ # =========================================================================== main
1145
+ def parse(argv=None):
1146
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
1147
+ p.add_argument("--design", choices=["fewshot", "pooled", "scored"])
1148
+ p.add_argument("--dataset", choices=DATASETS)
1149
+ p.add_argument("--draws", default="0,1,2,3,4")
1150
+ p.add_argument("--score-dir", default=None, help="--design scored: a score_ft.py output dir (summary.json)")
1151
+ p.add_argument("--arms", default=None, help="--design scored: comma list of arms scored in --score-dir")
1152
+ p.add_argument("--unit", default=None, help="--design scored: output sub-path under scores_contrast/<dataset>/")
1153
+ p.add_argument("--exclude-genes", default=None, help="CSV with gene_id (score_ft --exclude-genes); only needed "
1154
+ "when the scored call has none (reproduction then n/a)")
1155
+ p.add_argument("--allow-sex-genes", action="store_true", help="giroux2022 without any sex-linked-gene exclusion")
1156
+ p.add_argument("--threads", type=int, default=4)
1157
+ p.add_argument("--fetch-dir", default=None, help="server_2 NPZ copies (default scores_contrast/_fetch_tmp)")
1158
+ p.add_argument("--force", action="store_true")
1159
+ p.add_argument("--collect", action="store_true")
1160
+ return p.parse_args(argv)
1161
+
1162
+
1163
+ def main(argv=None) -> int:
1164
+ a = parse(argv)
1165
+ if a.collect:
1166
+ collect()
1167
+ return 0
1168
+ if not 1 <= a.threads <= MAX_THREADS:
1169
+ raise SystemExit(f"--threads must be 1..{MAX_THREADS}")
1170
+ try:
1171
+ from threadpoolctl import threadpool_limits
1172
+ threadpool_limits(a.threads)
1173
+ except ImportError:
1174
+ pass
1175
+ if a.design is None or a.dataset is None:
1176
+ raise SystemExit("--design and --dataset are required (or --collect)")
1177
+ if a.dataset not in DISEASE and a.design != "scored":
1178
+ raise SystemExit(f"{a.dataset} has no case-control contrast")
1179
+ a.code_sha = {str(p_): sha256(p_) for p_ in CODE_FILES}
1180
+ a.fetch_dir = a.fetch_dir or str(OUT_ROOT / "_fetch_tmp")
1181
+ Path(a.fetch_dir).mkdir(parents=True, exist_ok=True)
1182
+ a.pcache, a.shared_shas = {}, set()
1183
+ code_dir = OUT_ROOT / "_code"
1184
+ code_dir.mkdir(parents=True, exist_ok=True)
1185
+ for p_ in (Path(__file__).resolve(), R_SCRIPT):
1186
+ dst = code_dir / f"{p_.stem}.{a.code_sha[str(p_)][:12]}{p_.suffix}"
1187
+ if not dst.exists():
1188
+ shutil.copy2(p_, dst)
1189
+ if a.design == "scored":
1190
+ if not (a.score_dir and a.arms and a.unit):
1191
+ raise SystemExit("--design scored needs --score-dir, --arms and --unit")
1192
+ unit = Path(a.unit)
1193
+ if unit.is_absolute() or ".." in unit.parts or unit.parts[0] in ("pooled", "fewshot_n5") or unit.name.startswith("_"):
1194
+ raise SystemExit("--unit must be a new relative sub-path (not pooled/ or fewshot_n5/)")
1195
+ SCORED.update({"dir": Path(a.score_dir).resolve(), "arms": tuple(x for x in a.arms.split(",") if x),
1196
+ "unit": str(unit)})
1197
+ run_unit("scored", a.dataset, None, a)
1198
+ elif a.design == "pooled":
1199
+ run_unit("pooled", a.dataset, None, a)
1200
+ else:
1201
+ draws = [int(x) for x in a.draws.split(",") if x.strip()]
1202
+ # shared zero-shot NPZs (zs__raw_all, zs__pseudo_all): one Poisson read-out reused by every draw
1203
+ tree = SOURCE_TREE.get(a.dataset, SCORES)
1204
+ shas = {}
1205
+ for j in draws:
1206
+ s = json.loads((tree / a.dataset / "fewshot_n5" / f"draw{j}" / "summary.json").read_text())
1207
+ for pa in s["per_arm"].values():
1208
+ shas.setdefault(pa["npz_sha256"], set()).add(j)
1209
+ a.shared_shas = {k for k, js in shas.items() if len(js) > 1}
1210
+ for j in draws:
1211
+ run_unit("fewshot", a.dataset, j, a)
1212
+ shared = Path(a.fetch_dir) / "generated" / a.dataset / "fewshot_n5"
1213
+ for f in list(shared.glob("zs__*_all.npz")) if shared.is_dir() else []:
1214
+ drop_fetched(f)
1215
+ assert "torch" not in sys.modules, "torch was imported"
1216
+ return 0
1217
+
1218
+
1219
+ if __name__ == "__main__":
1220
+ raise SystemExit(main())
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/contrast_extra_limma.R ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # edgeR TMM + limma voom + lmFit + eBayes (case vs control) for a batch of donor x cell-type pseudobulk jobs.
2
+ # CPU only. Called by tools/contrast_extra.py (added 2026-10-02); not meant to be run by hand.
3
+ #
4
+ # usage: Rscript contrast_extra_limma.R JOBDIR
5
+ # JOBDIR/n_genes.txt G (number of genes = rows of every matrix, the kept scoring genes in their fixed order)
6
+ # JOBDIR/counts.bin float64 little endian; matrix m starts at double offset `offset` and holds G x n_samples
7
+ # values in column-major order (one column per donor pseudobulk)
8
+ # JOBDIR/jobs.csv job, offset, n_samples, is_case (string of 0/1 per column), filter (nonzero | filterByExpr)
9
+ # Output:
10
+ # JOBDIR/limma.bin per job (jobs.csv order) a float64 G x 6 matrix, column-major:
11
+ # logFC, AveExpr, t, P.Value, adj.P.Val, B (moderated t of coef case - control); NaN = not tested
12
+ # JOBDIR/limma_status.csv job, status, n_tested, n_sig_fdr05, seconds
13
+ # JOBDIR/versions.txt R, limma, edgeR versions
14
+ #
15
+ # Per job: DGEList(counts) -> gene filter on that side's columns only ("nonzero": rowSums > 0, the default gene filter
16
+ # of evaluate_generated_vs_truth.py's edgeR backend; "filterByExpr": edgeR::filterByExpr(y, design)) ->
17
+ # y[keep, , keep.lib.sizes = FALSE] -> calcNormFactors(method = "TMM") -> voom(y, design) -> lmFit -> eBayes ->
18
+ # topTable(coef = 2, number = Inf, sort.by = "none"); design = model.matrix(~ group), group levels (control, case).
19
+ # BH (adj.P.Val) runs over the tested (kept) genes.
20
+ suppressPackageStartupMessages({
21
+ library(limma)
22
+ library(edgeR)
23
+ })
24
+ args <- commandArgs(trailingOnly = TRUE)
25
+ if (length(args) != 1L) stop("usage: Rscript contrast_extra_limma.R JOBDIR")
26
+ jobdir <- args[[1]]
27
+ writeLines(c(R.version.string, paste("limma", as.character(packageVersion("limma"))),
28
+ paste("edgeR", as.character(packageVersion("edgeR")))), file.path(jobdir, "versions.txt"))
29
+ G <- as.integer(readLines(file.path(jobdir, "n_genes.txt"))[[1]])
30
+ jobs <- read.csv(file.path(jobdir, "jobs.csv"), stringsAsFactors = FALSE,
31
+ colClasses = c(job = "character", offset = "numeric", n_samples = "integer",
32
+ is_case = "character", filter = "character"))
33
+ inp <- file(file.path(jobdir, "counts.bin"), "rb")
34
+ out <- file(file.path(jobdir, "limma.bin"), "wb")
35
+ status <- data.frame(job = jobs$job, status = "", n_tested = 0L, n_sig_fdr05 = 0L, seconds = 0,
36
+ stringsAsFactors = FALSE)
37
+ cols <- c("logFC", "AveExpr", "t", "P.Value", "adj.P.Val", "B")
38
+ for (i in seq_len(nrow(jobs))) {
39
+ t0 <- proc.time()[["elapsed"]]
40
+ ns <- jobs$n_samples[i]
41
+ seek(inp, where = jobs$offset[i] * 8, origin = "start", rw = "read")
42
+ x <- readBin(inp, what = "double", n = G * ns, size = 8, endian = "little")
43
+ if (length(x) != G * ns) stop(sprintf("job %s: short read", jobs$job[i]))
44
+ M <- matrix(x, nrow = G, ncol = ns)
45
+ rownames(M) <- as.character(seq_len(G))
46
+ is_case <- as.integer(strsplit(jobs$is_case[i], "")[[1]])
47
+ res <- matrix(NaN, nrow = G, ncol = 6L)
48
+ st <- "ok"
49
+ if (length(is_case) != ns) stop(sprintf("job %s: is_case length %d != %d", jobs$job[i], length(is_case), ns))
50
+ if (sum(is_case == 1L) < 2L || sum(is_case == 0L) < 2L) {
51
+ st <- "undefined_lt2_per_group"
52
+ } else {
53
+ r <- tryCatch({
54
+ grp <- factor(ifelse(is_case == 1L, "case", "control"), levels = c("control", "case"))
55
+ design <- model.matrix(~grp)
56
+ y <- DGEList(counts = M)
57
+ keep <- if (identical(jobs$filter[i], "filterByExpr")) filterByExpr(y, design = design) else rowSums(M) > 0
58
+ if (sum(keep) < 3L) stop("fewer than 3 genes pass the filter")
59
+ y <- y[keep, , keep.lib.sizes = FALSE]
60
+ y <- calcNormFactors(y, method = "TMM")
61
+ v <- voom(y, design, plot = FALSE)
62
+ fit <- eBayes(lmFit(v, design))
63
+ tt <- topTable(fit, coef = 2, number = Inf, sort.by = "none")
64
+ if (!identical(rownames(tt), rownames(M)[keep])) stop("topTable row order differs from the input")
65
+ res[keep, ] <- as.matrix(tt[, cols])
66
+ "ok"
67
+ }, error = function(e) paste0("error: ", conditionMessage(e)))
68
+ st <- r
69
+ }
70
+ writeBin(as.vector(res), out, size = 8, endian = "little")
71
+ status$status[i] <- st
72
+ status$n_tested[i] <- sum(is.finite(res[, 4]))
73
+ status$n_sig_fdr05[i] <- sum(res[, 5] < 0.05, na.rm = TRUE)
74
+ status$seconds[i] <- round(proc.time()[["elapsed"]] - t0, 3)
75
+ }
76
+ close(inp)
77
+ close(out)
78
+ write.csv(status, file.path(jobdir, "limma_status.csv"), row.names = FALSE)
79
+ cat(sprintf("limma jobs: %d (%d ok)\n", nrow(jobs), sum(status$status == "ok")))