junidude14 commited on
Commit
b976701
·
verified ·
1 Parent(s): c9009bb

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/tools/contrast_extra.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_tables.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Compact tables of scores_contrast (CPU, pandas only; reads the collected CSVs written by contrast_extra.py --collect).
3
+
4
+ Writes scores_contrast/TABLES.md and scores_contrast/compact_{fewshot,pooled,learning_curve}.csv: per cohort and design,
5
+ for the arms LoRA, scSemiProfiler, zero-shot raw, zero-shot + calibration and the real-bulk broadcast: Pearson r,
6
+ Spearman r (mean of T/B/Mono/NK, statistic mean_cp10k), split-half ceiling (r(A,B) and the noise-free ceiling
7
+ sqrt(2r/(1+r))), r vs half B, Welch and limma-voom top-50 DEG overlap (sum over scored types) with their chance levels,
8
+ CAT(50), CAT(100) (same sign, mean over scored types) and RBO_ext (t descending, p = 0.98). Few-pair rows are means over
9
+ the 5 draws (SD in the CSV). Added 2026-10-02.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+
18
+ OUT = Path(__file__).resolve().parents[1] / "scores_contrast"
19
+ COHORT = {"ye2026_sepsis": "Sepsis", "imperial_eskd": "Imperial ESKD COVID", "giroux2022": "Giroux (sex-linked genes excluded)",
20
+ "ji2025_chili": "Ji ChILI (whole-blood bulk)"}
21
+ ROLE_ORDER = ["lora", "scsemi", "zs_raw", "zs_cal", "broadcast"]
22
+ ROLE_LABEL = {"lora": "LoRA", "scsemi": "scSemiProfiler", "zs_raw": "zero-shot raw", "zs_cal": "zero-shot + cal",
23
+ "broadcast": "broadcast (real bulk)"}
24
+ GEN_COLS = {"pearson_r": "pearson", "spearman_r": "spearman", "r_generated_vs_halfB": "r_vs_halfB",
25
+ "welch_top50": "welch50", "welch_top50_chance": "welch50_chance", "limma_top50": "limma50",
26
+ "limma_top50_chance": "limma50_chance", "limma_fbe_top50": "limma50_fbe", "cat50": "cat50", "cat100": "cat100",
27
+ "cat50_chance": "cat50_chance", "rbo": "rbo", "limma_n_sig_gen": "limma_nsig_pred",
28
+ "welch_n_sig_gen": "welch_nsig_pred"}
29
+ BC_COLS = {"broadcast_pearson_r": "pearson", "broadcast_spearman_r": "spearman", "r_broadcast_vs_halfB": "r_vs_halfB",
30
+ "welch_top50_broadcast": "welch50", "welch_top50_broadcast_chance": "welch50_chance",
31
+ "limma_top50_broadcast": "limma50", "limma_top50_broadcast_chance": "limma50_chance",
32
+ "limma_fbe_top50_broadcast": "limma50_fbe", "broadcast_cat50": "cat50", "broadcast_cat100": "cat100",
33
+ "broadcast_cat50_chance": "cat50_chance", "broadcast_rbo": "rbo",
34
+ "limma_n_sig_broadcast_per_type": "limma_nsig_pred", "welch_n_sig_broadcast_per_type": "welch_nsig_pred"}
35
+ UNIT_COLS = {"splithalf_r_AB": "ceiling_rAB", "noise_free_ceiling": "ceiling_noise_free", "welch_top50_max": "welch50_max",
36
+ "limma_top50_max": "limma50_max", "limma_n_sig_obs": "limma_nsig_obs", "welch_n_sig_obs": "welch_nsig_obs"}
37
+
38
+
39
+ def rows_for(h: pd.DataFrame) -> pd.DataFrame:
40
+ """One row per unit x role (LoRA / scSemi / zs raw / zs cal, plus the broadcast of the LoRA arm's raw-bulk condition)."""
41
+ out = []
42
+ for (ds, unit), sub in h.groupby(["dataset", "unit"], sort=False):
43
+ base = {"dataset": ds, "unit": unit}
44
+ for _, r in sub[sub.role.isin(ROLE_ORDER[:4])].iterrows():
45
+ out.append({**base, "role": r.role, "arm": r.arm, **{v: r[k] for k, v in GEN_COLS.items()},
46
+ **{v: r[k] for k, v in UNIT_COLS.items()}})
47
+ lora = sub[sub.role == "lora"]
48
+ if len(lora):
49
+ r = lora.iloc[0]
50
+ out.append({**base, "role": "broadcast", "arm": f"broadcast[{r.condition}]",
51
+ **{v: r[k] for k, v in BC_COLS.items()}, **{v: r[k] for k, v in UNIT_COLS.items()}})
52
+ return pd.DataFrame(out)
53
+
54
+
55
+ def fmt(x, nd=2):
56
+ return "–" if x is None or (isinstance(x, float) and np.isnan(x)) else f"{x:.{nd}f}"
57
+
58
+
59
+ def md_table(df: pd.DataFrame, few: bool) -> str:
60
+ hdr = ("| cohort | arm | Pearson r | Spearman r | split-half r(A,B) / noise-free ceiling | r vs half B | "
61
+ "Welch top-50 (chance) | limma top-50 (chance) | CAT50 / CAT100 (chance@50) | RBO |")
62
+ lines = [hdr, "|" + "---|" * 10]
63
+ for ds in COHORT:
64
+ sub = df[df.dataset == ds]
65
+ if not len(sub):
66
+ continue
67
+ for role in ROLE_ORDER:
68
+ s = sub[sub.role == role]
69
+ if not len(s):
70
+ why = ("not computed: no scSemiProfiler arm in this design (5-fold CV / equal-budget calls do not "
71
+ "exist yet)" if role == "scsemi" else "not computed: no such arm")
72
+ lines.append(f"| {COHORT[ds]} | {ROLE_LABEL[role]} | {why} |||||||| |")
73
+ continue
74
+ m = s.mean(numeric_only=True)
75
+ sd = s.std(numeric_only=True, ddof=1) if few and len(s) > 1 else None
76
+
77
+ def pm(c, nd=2):
78
+ return fmt(m[c], nd) + (f" ± {fmt(sd[c], nd)}" if sd is not None else "")
79
+ lines.append(
80
+ f"| {COHORT[ds]} | {ROLE_LABEL[role]} | {pm('pearson')} | {pm('spearman')} | "
81
+ f"{fmt(m['ceiling_rAB'])} / {fmt(m['ceiling_noise_free'])} | {fmt(m['r_vs_halfB'])} | "
82
+ f"{fmt(m['welch50'], 1)} ({fmt(m['welch50_chance'], 2)}) of {fmt(m['welch50_max'], 0 if not few else 1)} | "
83
+ f"{fmt(m['limma50'], 1)} ({fmt(m['limma50_chance'], 2)}) of {fmt(m['limma50_max'], 0 if not few else 1)} | "
84
+ f"{fmt(m['cat50'], 3)} / {fmt(m['cat100'], 3)} ({fmt(m['cat50_chance'], 3)}) | {fmt(m['rbo'], 3)} |")
85
+ return "\n".join(lines)
86
+
87
+
88
+ def main() -> int:
89
+ parts = ["# scores_contrast: compact tables\n",
90
+ "Generated by `tools/contrast_extra_tables.py` from the collected CSVs. Means over T/B/Mono/NK (r) or over "
91
+ "the scored DEG types T/B/Mono/NK/DC (CAT, RBO); top-50 = sum over the scored types, 'of N' = sum of the "
92
+ "observed list lengths; chance = hypergeometric mean. Broadcast = the raw real-bulk condition of the LoRA "
93
+ "arm. Few-pair: mean ± SD over 5 draws (other columns: means).\n"]
94
+ for design, fn, few in (("fewshot", "fewshot_headline.csv", True), ("pooled", "pooled_headline.csv", False)):
95
+ p = OUT / fn
96
+ if not p.is_file():
97
+ continue
98
+ df = rows_for(pd.read_csv(p))
99
+ df.to_csv(OUT / f"compact_{design}.csv", index=False)
100
+ parts.append(f"\n## {'Few-pair (5 donors, 5 draws)' if few else '5-fold pooled'}\n\n" + md_table(df, few) + "\n")
101
+ p = OUT / "learning_curve_headline.csv"
102
+ if p.is_file():
103
+ lc = pd.read_csv(p)
104
+ keep = ["series", "pairs", "arm", "pearson_r", "spearman_r", "partial_r", "broadcast_pearson_r",
105
+ "broadcast_spearman_r", "splithalf_r_AB", "noise_free_ceiling", "r_generated_vs_halfB",
106
+ "welch_top50", "welch_top50_chance", "welch_top50_max", "limma_top50", "limma_top50_chance",
107
+ "limma_top50_max", "cat50", "cat100", "cat50_chance", "rbo", "broadcast_cat50", "broadcast_rbo"]
108
+ lc = lc[keep]
109
+ order = {"zs__raw": 0, "zs__cal": 1, "lora": 2, "zs_cal_budget": 3}
110
+ lc = lc.assign(_s=lc.series.map(order), _n=pd.to_numeric(lc.pairs, errors="coerce").fillna(1e9)) \
111
+ .sort_values(["_s", "_n"]).drop(columns=["_s", "_n"])
112
+ lc.to_csv(OUT / "compact_learning_curve.csv", index=False)
113
+ lines = ["| series | pairs | arm | Pearson | Spearman | Welch top-50 (chance) | limma top-50 (chance) | "
114
+ "CAT50 / CAT100 | RBO |", "|" + "---|" * 9]
115
+ for _, r in lc.iterrows():
116
+ lines.append(f"| {r.series} | {r.pairs} | {r.arm} | {fmt(r.pearson_r)} | {fmt(r.spearman_r)} | "
117
+ f"{int(r.welch_top50)} ({fmt(r.welch_top50_chance)}) of {int(r.welch_top50_max)} | "
118
+ f"{int(r.limma_top50)} ({fmt(r.limma_top50_chance)}) of {int(r.limma_top50_max)} | "
119
+ f"{fmt(r.cat50, 3)} / {fmt(r.cat100, 3)} | {fmt(r.rbo, 3)} |")
120
+ r0 = lc.iloc[0]
121
+ lines.append(f"\nBroadcast (real bulk): Pearson {fmt(lc[lc.arm == 'real_lora__raw'].broadcast_pearson_r.iloc[0]) if (lc.arm == 'real_lora__raw').any() else '–'}, "
122
+ f"CAT50 {fmt(lc[lc.arm == 'real_lora__raw'].broadcast_cat50.iloc[0], 3) if (lc.arm == 'real_lora__raw').any() else '–'}, "
123
+ f"RBO {fmt(lc[lc.arm == 'real_lora__raw'].broadcast_rbo.iloc[0], 3) if (lc.arm == 'real_lora__raw').any() else '–'}; "
124
+ f"split-half r(A,B) {fmt(r0.splithalf_r_AB)}, noise-free ceiling {fmt(r0.noise_free_ceiling)}.")
125
+ parts.append("\n## Sepsis learning curve (pooled, 82 samples)\n\n" + "\n".join(lines) + "\n")
126
+ (OUT / "TABLES.md").write_text("\n".join(parts))
127
+ print((OUT / "TABLES.md").read_text())
128
+ return 0
129
+
130
+
131
+ if __name__ == "__main__":
132
+ 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/run_contrast_unit.sh ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Run a list of tools/contrast_extra.py jobs (CPU only) in one transient systemd user unit on server_1 (added 2026-10-02).
3
+ # MemoryMax MEM, MemorySwapMax 0, CPUQuota THREADS x 100 %, Nice 10, CUDA hidden, no bytecode written, no restart.
4
+ # Refuses to start unless MemAvailable - 32 GiB > MEM (host rule: keep a 32 GiB floor above the job's peak).
5
+ # Does not wait. Log: scores_contrast/_logs/NAME_<stamp>.log; launches are appended to scores_contrast/_logs/units.tsv.
6
+ # Jobs run one after another; a failed job is logged ("JOB_EXIT <rc> ...") and the next job starts.
7
+ # usage: run_contrast_unit.sh NAME THREADS MEM_GIB JOBFILE
8
+ # JOBFILE: one contrast_extra.py argument line per row, e.g. "--design fewshot --dataset ji2025_chili --draws 0,1,2,3,4"
9
+ set -uo pipefail
10
+ export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
11
+ export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=$XDG_RUNTIME_DIR/bus}"
12
+ TASK=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927
13
+ PY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python
14
+ name=$1; thr=$2; mem=$3; jobs=$4
15
+ (( thr >= 1 && thr <= 14 )) || { echo "THREADS must be 1..14" >&2; exit 2; }
16
+ [[ $mem =~ ^[0-9]+$ ]] || { echo "MEM_GIB must be an integer (GiB)" >&2; exit 2; }
17
+ [[ -s $jobs ]] || { echo "no job file $jobs" >&2; exit 2; }
18
+ avail=$(awk '/MemAvailable/ {print int($2/1048576)}' /proc/meminfo)
19
+ (( avail - 32 > mem )) || { echo "MemAvailable ${avail} GiB - 32 <= ${mem} GiB; not starting $name" >&2; exit 3; }
20
+ logs=$TASK/scores_contrast/_logs
21
+ mkdir -p "$logs"
22
+ stamp=$(date +%Y%m%dT%H%M%S)
23
+ unit=contrast-${name}-${stamp}
24
+ log=$logs/${name}_${stamp}.log
25
+ cp "$jobs" "$logs/${name}_${stamp}.jobs"
26
+ echo -e "$(date -Is)\tstart\t$unit\t$(hostname -s)\tMemAvailable=${avail}GiB\tthreads=$thr\tmem=${mem}G\t$jobs" >> "$logs/units.tsv"
27
+ systemd-run --user --unit="$unit" --working-directory="$TASK" \
28
+ -p MemoryMax="${mem}G" -p MemorySwapMax=0 -p CPUQuota=$((thr * 100))% -p Nice=10 \
29
+ -p StandardOutput=append:"$log" -p StandardError=append:"$log" \
30
+ --setenv=CUDA_VISIBLE_DEVICES= --setenv=PYTHONNOUSERSITE=1 --setenv=PYTHONDONTWRITEBYTECODE=1 \
31
+ --setenv=PYTHONUNBUFFERED=1 --setenv=OMP_NUM_THREADS="$thr" --setenv=OPENBLAS_NUM_THREADS="$thr" \
32
+ --setenv=MKL_NUM_THREADS="$thr" --setenv=NUMBA_NUM_THREADS="$thr" \
33
+ /bin/bash -c 'while IFS= read -r line; do [[ -z $line || $line == \#* ]] && continue; t0=$(date +%s);
34
+ echo "JOB_START $(date -Is) $line"; [[ $line == *--threads* ]] || line="$line --threads '"$thr"'";
35
+ /usr/bin/time -v '"$PY"' tools/contrast_extra.py $line;
36
+ echo "JOB_EXIT $? $(( $(date +%s) - t0 ))s $line"; done < '"$logs/${name}_${stamp}.jobs"'; echo UNIT_EXIT 0' >/dev/null
37
+ echo "unit=$unit log=$log"
paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/sample_lockwait.sh ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Sample base-model zero-shot sets by queuing on the shared GPU lock (2026-10-02).
3
+ #
4
+ # Same sampler, checkpoint and flags as plans/utility_studies_final6k_20260925/tools/sample_queue.sh. The only
5
+ # difference: it does not poll gpu_usable.sh every 120 s. When another queue runs GPU steps back to back (gaps of
6
+ # ~4 s between its ml-run jobs), that poll almost never sees the lock free. Here ml-run blocks on
7
+ # /run/user/1000/ml-gpu0.lock (flock --exclusive) and takes the GPU at the next release, so no two CUDA jobs ever
8
+ # overlap and the other queue simply waits for this one. Before each step: memory guard active, MemAvailable >= 32 GiB,
9
+ # thermal gate. Queue lines: "sample|TAG|base|CONDITION_NPZ|SEED|OUTPUT_NPZ" (run_queue.sh format; base model only).
10
+ # env: QUEUE (required)
11
+ set -uo pipefail
12
+ export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
13
+ M8=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion
14
+ TASK=$M8/plans/paired_finetune_intradataset_20260927
15
+ CKPT=$M8/runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt
16
+ CKPT_SHA=8c7cd0e83e2bc19fe03dfcbc084919a1e2f61be8cc8bc12f4caf543dfda91633
17
+ PY=/home/sj_server_1/miniforge3/envs/b2sc-cu130/bin/python
18
+ QUEUE="${QUEUE:?QUEUE}"
19
+ LOG=$TASK/logs/sample_lockwait_$(basename "$QUEUE" .txt)_$(date +%Y%m%dT%H%M%S).log
20
+ log() { echo "$(date +%FT%T) $*" | tee -a "$LOG"; }
21
+ got=$(sha256sum "$CKPT" | cut -d' ' -f1)
22
+ [[ "$got" == "$CKPT_SHA" ]] || { log "ABORT: checkpoint sha ${got:0:12} != ${CKPT_SHA:0:12}"; exit 1; }
23
+ n_fail=0
24
+ while IFS='|' read -r kind tag ck cond seed out; do
25
+ [[ -z "${kind// }" || "$kind" == \#* ]] && continue
26
+ [[ "$kind" == sample && "$ck" == base ]] || { log "skip non-base line: $kind|$tag"; continue; }
27
+ rec=${out%.npz}.log; err=${out%.npz}.err
28
+ if [[ -s "$rec" && -s "$out" ]]; then log "$tag already sampled; skipped"; continue; fi
29
+ systemctl --user is-active --quiet ml-memory-guard.service || { log "ABORT: memory guard inactive"; exit 1; }
30
+ avail=$(awk '/MemAvailable/ {print int($2 / 1048576)}' /proc/meminfo)
31
+ (( avail >= 32 )) || { log "ABORT: MemAvailable ${avail} GiB < 32"; exit 1; }
32
+ until verdict=$(bash "$M8/plans/floor01_campaign_20260923/tools/thermal_guard.sh"); do sleep 60; done
33
+ mkdir -p "$(dirname "$out")"
34
+ log "--- $tag seed=$seed ($verdict; MemAvailable ${avail} GiB; waiting on the GPU lock)"
35
+ if "$HOME/.local/bin/ml-run" /usr/bin/env CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
36
+ PYTHONPATH="$M8/src" OMP_NUM_THREADS=4 "$PY" -u "$M8/scripts/sample_sdd_standalone.py" \
37
+ --checkpoint "$CKPT" --condition-npz "$cond" --output "$out" --weights ema --batch-size 256 \
38
+ --steps 50 --seed "$seed" --device cuda --conditioner-source embedded \
39
+ --active-logit-threshold 0.0 --support-readout bernoulli > "$rec" 2> "$err"; then
40
+ log "$tag done: $(python3 -c "import json;d=json.load(open('$rec'));print('rows', d.get('generated_counts_rows','?'), 'zero_frac %.4f' % d.get('generated_zero_fraction',-1), d.get('output_sha256','')[:12])" 2>/dev/null)"
41
+ else
42
+ n_fail=$((n_fail+1)); log "WARN: $tag failed (see $err)"; rm -f "$rec"
43
+ fi
44
+ done < "$QUEUE"
45
+ log "finished: failed=$n_fail"
46
+ (( n_fail == 0 ))