junidude14 commited on
Commit
de7281d
·
verified ·
1 Parent(s): 267e72b

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261001T200638Z-extra-realism-metrics/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/logs/extraA_20261002T000131.jobs ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ --design fewshot --dataset giroux2022 --draws 0,1,2,3,4 --threads 6
2
+ --design fewshot --dataset ji2025_chili --draws 0,1,2,3,4 --threads 6
3
+ --design pooled --dataset giroux2022 --threads 8
4
+ --design pooled --dataset ji2025_chili --threads 8
5
+ --design fewshot --dataset immicro --draws 0,1,2,3,4 --threads 6
6
+ --design pooled --dataset immicro --threads 8
7
+ --design pooled --dataset ye2026_sepsis --threads 8
8
+ --design pooled --dataset imperial_eskd --threads 8
paper-releases/pbisc-diffusion/updates/20261001T200638Z-extra-realism-metrics/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scores_extra/_code/extra_metrics_v1_ca3804cffbaa.py ADDED
@@ -0,0 +1,978 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reviewer-expected realism / diversity metrics for the paired fine-tuning benchmark (CPU only; never imports torch).
3
+
4
+ Added 2026-10-01. Every scored unit (one few-pair draw, or one pooled 5-fold call) is re-read exactly as tools/score_ft.py
5
+ scored it, and four metric families are added next to the existing precision/coverage:
6
+
7
+ 1. classifier two-sample tests (real vs generated): kNN (k = 5) and random-forest 5-fold cross-validated ROC AUC
8
+ (scGAN / scDiffusion style) and the leave-one-out 1-NN accuracy (scLDM; Lopez-Paz & Oquab 2017);
9
+ 2. MMD^2 (unbiased, Gaussian RBF; median-heuristic bandwidth and the fixed multiples 0.5 / 1 / 2, plus their sum);
10
+ 3. scSemiProfiler's normalized error E_N (Wang et al. 2024, Methods eq. 17-18; get_error in vendor utils.py);
11
+ 4. precision / coverage at k = 3 and 5 next to k = 10 (k = 10 re-computed first and checked against score_ft.py).
12
+
13
+ Families 1, 2 and 4 use exactly the scorer's embedding and cells: score_ft.make_view (PCA-50 fitted on the scored
14
+ donors' R1 cells), the scorer's whole-NPZ Poisson read-out (seed 20260916), its donor-keyed generated subsample
15
+ (F.generated_subsample) and its pairwise depth matching (F.SB.depth_match with a fresh rng(20260929)). They are
16
+ reported both without ("raw", the deck's headline precision/coverage) and with depth matching ("dm"). The
17
+ real-vs-real control is the scorer's own: held-out real cells R2 of the same donors, same n per donor.
18
+
19
+ E_N follows scSemiProfiler's own space instead: per arm, log1p CP10K -> PCA-100 fitted on real and generated cells
20
+ together; Dif_sc = symmetric 1-NN distance (eq. 17); lower bound = random half split of the whole PCA matrix; upper
21
+ bound = random pairs of different real samples. Distances: squared L2 as their code computes them (faiss
22
+ IndexFlatL2), and plain L2 as the paper's text writes them. Two cell sets:
23
+ "all": every observed QC cell of each scored sample vs all of its generated cells (their setting);
24
+ control = a random within-sample half split of the observed cells (half A as 'real', half B as 'generated').
25
+ "pc": the precision/coverage cells (R1 vs the generated subsample, n per donor equal); control = R1 vs R2.
26
+ Representatives: scSemiProfiler sets a representative's error to the lower bound. Our scored samples never include a
27
+ representative (the 5 training donors of a few-pair draw are not scored in any arm), so no sample is set to LB; for
28
+ scsemi5 the table also gives the value that convention would produce (E_N x n_test / (n_test + n_representative_rows)).
29
+
30
+ usage (CPU; run through tools/run_extra_unit.sh):
31
+ extra_metrics.py --design fewshot --dataset giroux2022 --draws 0,1,2,3,4 [--threads 7] [--no-en-all]
32
+ extra_metrics.py --design pooled --dataset giroux2022
33
+ extra_metrics.py --collect # scores_extra/*.csv + TABLES.md from every unit written so far
34
+ Outputs: scores_extra/<dataset>/<fewshot_n5/draw<j> | pooled>/{metrics.csv, per_donor.csv, en.csv, en_per_sample.csv,
35
+ repro.json, manifest.json}.
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import os
40
+ import sys
41
+
42
+
43
+ def _threads_from_argv(default: int = 7) -> int:
44
+ for i, a in enumerate(sys.argv):
45
+ if a == "--threads" and i + 1 < len(sys.argv):
46
+ return int(sys.argv[i + 1])
47
+ if a.startswith("--threads="):
48
+ return int(a.split("=", 1)[1])
49
+ return default
50
+
51
+
52
+ _THR = str(_threads_from_argv())
53
+ for _k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMBA_NUM_THREADS"):
54
+ os.environ[_k] = _THR
55
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
56
+
57
+ import argparse # noqa: E402
58
+ import hashlib # noqa: E402
59
+ import json # noqa: E402
60
+ import shutil # noqa: E402
61
+ import subprocess # noqa: E402
62
+ import time # noqa: E402
63
+ from pathlib import Path # noqa: E402
64
+
65
+ import numpy as np # noqa: E402
66
+ import pandas as pd # noqa: E402
67
+ import scipy.sparse as sp # noqa: E402
68
+
69
+ TOOLS = Path(__file__).resolve().parent
70
+ sys.path.insert(0, str(TOOLS))
71
+ import ft_common as F # noqa: E402
72
+ import score_ft as S # noqa: E402 (module level: argparse/env only; main() is not run)
73
+
74
+ TASK = F.TASK
75
+ SCORES = TASK / "scores"
76
+ OUT_ROOT = TASK / "scores_extra"
77
+ REMOTE = "spark-0110"
78
+ MIN_FREE_GIB = 40.0
79
+
80
+ SEED = 20261001 # every new random stream of this file (CV folds, RF, bandwidth subsample, E_N)
81
+ KS = (3, 5, 10)
82
+ KNN_C2ST_K = 5 # sklearn default, scDiffusion's kNN classifier
83
+ RF_TREES = 300 # scGAN: fully grown trees, max_features = sqrt; 300 instead of 1000 trees (cost)
84
+ CV_FOLDS = 5 # scGAN: five-fold cross-validation, equal real / generated counts
85
+ BW_MULTIPLES = (0.5, 1.0, 2.0) # scGAN: sigma in {m/2, m, 2m}
86
+ BW_MAX_CELLS = 4000 # R1 cells used for the median pairwise distance
87
+ EN_PCS = 100 # scSemiProfiler: PCA to 100 dimensions
88
+ EN_LB_MAX_QUERIES = 20000 # all-cells E_N: LB estimated from this many query cells per direction (index = full half)
89
+ EN_CHUNK = 8192
90
+
91
+ FEW_ARMS = ("zs_raw", "zs_cal", "scsemi5", "lora5", "zs_pseudo")
92
+ POOLED_ARMS = ("zs__raw", "zs__cal", "pseudo_full__cal", "real_lora__raw", "zs__pseudo")
93
+ CONTROL = "real_R2" # R1 vs R2 (P/C cells) / within-sample half split (all cells)
94
+ CONTROL_OOS = "real_R3" # out-of-sample real side: R2' vs R3 (families 1-2)
95
+ ARM_LABEL = {"zs_raw": "Zero-shot, real bulk", "zs__raw": "Zero-shot, real bulk",
96
+ "zs_cal": "Zero-shot + calibration", "zs__cal": "Zero-shot + calibration",
97
+ "scsemi5": "scSemiProfiler, 5 donors", "lora5": "LoRA, 5 donors",
98
+ "real_lora__raw": "LoRA, all training pairs", "pseudo_full__cal": "sc-only fine-tune (+ calibration)",
99
+ "zs_pseudo": "Zero-shot, sc pseudobulk input (reference)",
100
+ "zs__pseudo": "Zero-shot, sc pseudobulk input (reference)",
101
+ CONTROL: "Real vs real control (held-out real cells)",
102
+ CONTROL_OOS: "Real vs real control (out-of-sample: R2 vs R3)"}
103
+ DATASETS = ("immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
104
+
105
+
106
+ def log(msg: str) -> None:
107
+ F.log(msg)
108
+
109
+
110
+ # =========================================================================== pure metric functions
111
+ def sqdist_min(Q: np.ndarray, X: np.ndarray, *, exclude_self: bool = False, max_block: float = 1.5e8) -> tuple:
112
+ """For every row of Q: the minimum squared L2 distance to the rows of X and its index (brute force, float64,
113
+ chunked BLAS). exclude_self: Q is X and the diagonal is skipped (leave-one-out)."""
114
+ Q = np.ascontiguousarray(Q, dtype=np.float64)
115
+ X = np.ascontiguousarray(X, dtype=np.float64)
116
+ xx = np.einsum("ij,ij->i", X, X)
117
+ qq = np.einsum("ij,ij->i", Q, Q)
118
+ out = np.empty(Q.shape[0])
119
+ arg = np.empty(Q.shape[0], dtype=np.int64)
120
+ chunk = max(16, int(max_block // max(X.shape[0], 1)))
121
+ for s in range(0, Q.shape[0], chunk):
122
+ e = min(s + chunk, Q.shape[0])
123
+ D = qq[s:e, None] + xx[None, :] - 2.0 * (Q[s:e] @ X.T)
124
+ if exclude_self:
125
+ D[np.arange(e - s), np.arange(s, e)] = np.inf
126
+ a = np.argmin(D, axis=1)
127
+ arg[s:e] = a
128
+ out[s:e] = np.maximum(D[np.arange(e - s), a], 0.0)
129
+ return out, arg
130
+
131
+
132
+ def one_nn_loo(zr: np.ndarray, zg: np.ndarray) -> dict:
133
+ """Leave-one-out 1-NN two-sample accuracy (Lopez-Paz & Oquab 2017; scLDM eq. 32): pool both sets, predict each
134
+ point's label by its nearest other point; 0.5 = indistinguishable, 1 = separable."""
135
+ Z = np.vstack([zr, zg])
136
+ y = np.r_[np.ones(len(zr), bool), np.zeros(len(zg), bool)]
137
+ _, a = sqdist_min(Z, Z, exclude_self=True)
138
+ ok = y[a] == y
139
+ return {"nn1_acc": float(ok.mean()), "nn1_acc_real": float(ok[y].mean()), "nn1_acc_gen": float(ok[~y].mean())}
140
+
141
+
142
+ def c2st_auc(zr: np.ndarray, zg: np.ndarray, *, kind: str, seed: int = SEED, n_jobs: int = 1) -> dict:
143
+ """Classifier two-sample test: stratified 5-fold CV ROC AUC of real (1) vs generated (0); mean and SD over folds."""
144
+ from sklearn.ensemble import RandomForestClassifier
145
+ from sklearn.metrics import roc_auc_score
146
+ from sklearn.model_selection import StratifiedKFold
147
+ from sklearn.neighbors import KNeighborsClassifier
148
+ Z = np.vstack([zr, zg]).astype(np.float32)
149
+ y = np.r_[np.ones(len(zr), np.int8), np.zeros(len(zg), np.int8)]
150
+ aucs = []
151
+ for tr, te in StratifiedKFold(CV_FOLDS, shuffle=True, random_state=seed).split(Z, y):
152
+ if kind == "knn":
153
+ clf = KNeighborsClassifier(n_neighbors=KNN_C2ST_K, n_jobs=n_jobs)
154
+ elif kind == "rf":
155
+ clf = RandomForestClassifier(n_estimators=RF_TREES, max_features="sqrt", n_jobs=n_jobs, random_state=seed)
156
+ else:
157
+ raise ValueError(kind)
158
+ clf.fit(Z[tr], y[tr])
159
+ p = clf.predict_proba(Z[te])[:, list(clf.classes_).index(1)]
160
+ aucs.append(roc_auc_score(y[te], p))
161
+ return {f"c2st_{kind}_auc": float(np.mean(aucs)), f"c2st_{kind}_auc_sd": float(np.std(aucs, ddof=1))}
162
+
163
+
164
+ def median_bandwidth(z: np.ndarray, *, seed: int = SEED, max_cells: int = BW_MAX_CELLS) -> float:
165
+ """Median heuristic (Gretton et al. 2012): median pairwise Euclidean distance among (<= max_cells) real cells."""
166
+ rng = np.random.default_rng(seed)
167
+ idx = np.sort(rng.choice(len(z), size=min(max_cells, len(z)), replace=False))
168
+ x = np.asarray(z[idx], np.float64)
169
+ sq = np.einsum("ij,ij->i", x, x)
170
+ D = np.maximum(sq[:, None] + sq[None, :] - 2 * x @ x.T, 0.0)
171
+ iu = np.triu_indices(len(x), 1)
172
+ return float(np.sqrt(np.median(D[iu])))
173
+
174
+
175
+ def _kernel_sums(A: np.ndarray, B: np.ndarray, sigmas, same: bool, max_block: float = 6e7) -> np.ndarray:
176
+ """sum over pairs of exp(-||a - b||^2 / (2 sigma^2)) for every sigma (diagonal excluded when same)."""
177
+ A = np.ascontiguousarray(A, np.float64)
178
+ B = np.ascontiguousarray(B, np.float64)
179
+ aa, bb = np.einsum("ij,ij->i", A, A), np.einsum("ij,ij->i", B, B)
180
+ g = np.asarray([1.0 / (2.0 * s * s) for s in sigmas])
181
+ tot = np.zeros(len(sigmas))
182
+ chunk = max(16, int(max_block // max(len(B), 1)))
183
+ for s in range(0, len(A), chunk):
184
+ e = min(s + chunk, len(A))
185
+ D = np.maximum(aa[s:e, None] + bb[None, :] - 2.0 * (A[s:e] @ B.T), 0.0)
186
+ for i, gi in enumerate(g):
187
+ K = np.exp(-gi * D)
188
+ if same:
189
+ K[np.arange(e - s), np.arange(s, e)] = 0.0
190
+ tot[i] += K.sum()
191
+ return tot
192
+
193
+
194
+ def mmd2_unbiased(zr: np.ndarray, zg: np.ndarray, sigmas) -> np.ndarray:
195
+ """Unbiased MMD^2 (Gretton et al. 2012, eq. 3) with Gaussian RBF k(x, y) = exp(-||x - y||^2 / (2 sigma^2)), one value
196
+ per sigma; the kernel sum over the sigmas (scGAN's multi-scale kernel) is the sum of the per-sigma values."""
197
+ n, m = len(zr), len(zg)
198
+ kxx = _kernel_sums(zr, zr, sigmas, True) / (n * (n - 1))
199
+ kyy = _kernel_sums(zg, zg, sigmas, True) / (m * (m - 1))
200
+ kxy = _kernel_sums(zr, zg, sigmas, False) / (n * m)
201
+ return kxx + kyy - 2.0 * kxy
202
+
203
+
204
+ def pc_at_k(zr: np.ndarray, zg: np.ndarray, k: int) -> dict:
205
+ """Kynkaanniemi precision and Naeem coverage / density with k-NN balls of the real set: the scorer's own
206
+ stage_b_embed functions (knn_radius, precision_coverage). density is rescaled from SB's fixed k = 10 to k."""
207
+ radius = F.SB.knn_radius(zr, k)
208
+ r = F.SB.precision_coverage(zr, radius, zg)
209
+ r["density"] = r["density"] * F.K_NN / k
210
+ return r
211
+
212
+
213
+ def expected_coverage(n_real: int, n_gen: int, k: int) -> float:
214
+ """Naeem et al. 2020, eq. 9: E[coverage] for identical real and fake distributions."""
215
+ num = np.prod([(n_real - i) for i in range(1, k + 1)], dtype=np.float64)
216
+ den = np.prod([(n_gen + n_real - i) for i in range(1, k + 1)], dtype=np.float64)
217
+ return float(1.0 - num / den)
218
+
219
+
220
+ def two_sample_block(zr: np.ndarray, zg: np.ndarray, sigma_m: float, *, n_jobs: int, rf: bool = True) -> dict:
221
+ out = {}
222
+ out.update(c2st_auc(zr, zg, kind="knn", n_jobs=n_jobs))
223
+ if rf:
224
+ out.update(c2st_auc(zr, zg, kind="rf", n_jobs=n_jobs))
225
+ out.update(one_nn_loo(zr, zg))
226
+ sig = [m * sigma_m for m in BW_MULTIPLES]
227
+ mm = mmd2_unbiased(zr, zg, sig)
228
+ for mult, val in zip(BW_MULTIPLES, mm):
229
+ out[f"mmd2_bw{mult:g}"] = float(val)
230
+ out["mmd2_sum"] = float(mm.sum())
231
+ out["mmd_bandwidth_m"] = float(sigma_m)
232
+ return out
233
+
234
+
235
+ # =========================================================================== scSemiProfiler E_N
236
+ def log1p_cp10k_sparse(X: sp.csr_matrix) -> sp.csr_matrix:
237
+ """SB.cp10k_log1p (per-cell CP10K over the columns, log1p; empty cells stay zero) kept sparse, float32."""
238
+ X = X.tocsr().astype(np.float64)
239
+ lib = np.asarray(X.sum(axis=1)).ravel()
240
+ D = (sp.diags(np.divide(F.CP10K, lib, out=np.zeros_like(lib), where=lib > 0)) @ X).tocsr()
241
+ D.data = np.log1p(D.data)
242
+ return D.astype(np.float32)
243
+
244
+
245
+ class Gram:
246
+ """Running X^T X, column sums and row count of log1p-CP10K features (float64), for an exact PCA by eigh of the
247
+ covariance (the solver sklearn's PCA calls covariance_eigh; equal to the full-SVD PCA up to component signs)."""
248
+
249
+ def __init__(self, p: int):
250
+ self.G = np.zeros((p, p))
251
+ self.s = np.zeros(p)
252
+ self.n = 0
253
+
254
+ def add(self, L: sp.csr_matrix, chunk: int = EN_CHUNK) -> "Gram":
255
+ for a in range(0, L.shape[0], chunk):
256
+ B = L[a:a + chunk].toarray() # float32 (log1p CP10K)
257
+ self.G += (B.T @ B).astype(np.float64) # sgemm within a chunk, float64 across chunks
258
+ self.s += B.sum(0, dtype=np.float64)
259
+ self.n += B.shape[0]
260
+ return self
261
+
262
+ def __add__(self, other: "Gram") -> "Gram":
263
+ g = Gram(len(self.s))
264
+ g.G, g.s, g.n = self.G + other.G, self.s + other.s, self.n + other.n
265
+ return g
266
+
267
+ def pca(self, n_comp: int = EN_PCS) -> tuple[np.ndarray, np.ndarray]:
268
+ from scipy.linalg import eigh
269
+ p = len(self.s)
270
+ n_comp = int(min(n_comp, p, self.n - 1))
271
+ mu = self.s / self.n
272
+ C = (self.G - self.n * np.outer(mu, mu)) / (self.n - 1)
273
+ w, V = eigh(C, subset_by_index=[p - n_comp, p - 1])
274
+ return mu, np.ascontiguousarray(V[:, ::-1].T) # components x genes, descending variance
275
+
276
+
277
+ def embed(L: sp.csr_matrix, mu: np.ndarray, comps: np.ndarray, chunk: int = EN_CHUNK) -> np.ndarray:
278
+ """(x - mu) @ comps.T for sparse features x (dense row chunks, float64 BLAS)."""
279
+ out = np.empty((L.shape[0], comps.shape[0]))
280
+ for a in range(0, L.shape[0], chunk):
281
+ out[a:a + chunk] = (L[a:a + chunk].toarray().astype(np.float64) - mu) @ comps.T
282
+ return out
283
+
284
+
285
+ def dif_sc(a: np.ndarray, b: np.ndarray) -> dict:
286
+ """scSemiProfiler eq. 17 with K = 1: mean over the cells of both samples of the distance to the nearest cell of the
287
+ other sample. 'sq' = squared L2 (their code: faiss IndexFlatL2), 'l2' = L2 (their text)."""
288
+ da, _ = sqdist_min(a, b)
289
+ db, _ = sqdist_min(b, a)
290
+ n = len(a) + len(b)
291
+ return {"sq": float((da.sum() + db.sum()) / n), "l2": float((np.sqrt(da).sum() + np.sqrt(db).sum()) / n)}
292
+
293
+
294
+ def lower_bound(Z: np.ndarray, rng: np.random.Generator, max_queries: int | None) -> dict:
295
+ """LB: random half split of the whole PCA matrix (real + generated), symmetric 1-NN (their code: shuffle, first
296
+ n//2 rows vs the rest). With max_queries, each direction averages max_queries random query cells of one half
297
+ against the complete other half (an unbiased estimate of the same mean)."""
298
+ perm = rng.permutation(len(Z))
299
+ h = len(Z) // 2
300
+ A, B = Z[perm[:h]], Z[perm[h:]]
301
+ qa = A if (max_queries is None or len(A) <= max_queries) else A[np.sort(rng.choice(len(A), max_queries, replace=False))]
302
+ qb = B if (max_queries is None or len(B) <= max_queries) else B[np.sort(rng.choice(len(B), max_queries, replace=False))]
303
+ da, _ = sqdist_min(qa, B)
304
+ db, _ = sqdist_min(qb, A)
305
+ exact = len(qa) == len(A) and len(qb) == len(B)
306
+ if exact: # their arithmetic: mean over the concatenated distances of both directions
307
+ sq = float((da.sum() + db.sum()) / (len(da) + len(db)))
308
+ l2 = float((np.sqrt(da).sum() + np.sqrt(db).sum()) / (len(da) + len(db)))
309
+ else: # same weights as the exact concatenation (|A| and |B| cells), each direction estimated
310
+ wa, wb = len(A) / (len(A) + len(B)), len(B) / (len(A) + len(B))
311
+ sq = float(wa * da.mean() + wb * db.mean())
312
+ l2 = float(wa * np.sqrt(da).mean() + wb * np.sqrt(db).mean())
313
+ return {"sq": sq, "l2": l2, "exact": exact, "n_queries": [int(len(qa)), int(len(qb))], "n_half": [int(len(A)), int(len(B))]}
314
+
315
+
316
+ def en_from_embeddings(gts: list, semis: list, rng: np.random.Generator, *, lb_max_queries: int | None,
317
+ Z_all: np.ndarray) -> dict:
318
+ """E_N for one arm from per-sample embeddings (PCA already fitted on real + generated together).
319
+ UB: per sample i a uniformly random partner j != i (real cells of both), Dif averaged over samples.
320
+ Dif_i: real vs generated of sample i. E_N = (mean_i Dif_i - LB) / (UB - LB) (eq. 18); per sample (Dif_i - LB) / (UB - LB)."""
321
+ P = len(gts)
322
+ lb = lower_bound(Z_all, rng, lb_max_queries)
323
+ partner = (np.arange(P) + rng.integers(1, P, size=P)) % P if P > 1 else np.zeros(P, int)
324
+ ub_i = [dif_sc(gts[i], gts[partner[i]]) for i in range(P)]
325
+ dif_i = [dif_sc(gts[i], semis[i]) for i in range(P)]
326
+ out = {"lb": lb, "partner": partner.tolist(), "per_sample": []}
327
+ for d in ("sq", "l2"):
328
+ ub = float(np.mean([u[d] for u in ub_i]))
329
+ dif = np.asarray([x[d] for x in dif_i])
330
+ out[d] = {"lb": lb[d], "ub": ub, "dif_mean": float(dif.mean()), "en": float((dif.mean() - lb[d]) / (ub - lb[d])),
331
+ "en_i": ((dif - lb[d]) / (ub - lb[d])).tolist(), "dif_i": dif.tolist()}
332
+ return out
333
+
334
+
335
+ def get_error_legacy(gts: list, semis: list, representatives: list, cluster_labels: list, n_comp: int = EN_PCS) -> dict:
336
+ """Line-by-line re-statement of scSemiProfiler utils.get_error for one round (global np.random state, sklearn PCA,
337
+ self-pairing allowed in the UB, representatives at LB, squared L2). Only for the equivalence test."""
338
+ from sklearn.decomposition import PCA
339
+ P = len(gts)
340
+ X = np.concatenate([np.concatenate(gts, 0), np.concatenate(semis, 0)], 0)
341
+ Xr = PCA(n_components=n_comp).fit_transform(X)
342
+ xg, xs, off = [], [], 0
343
+ for g in gts:
344
+ xg.append(Xr[off:off + len(g)])
345
+ off += len(g)
346
+ for s in semis:
347
+ xs.append(Xr[off:off + len(s)])
348
+ off += len(s)
349
+ lbgt = Xr.copy()
350
+ np.random.shuffle(lbgt)
351
+ h = lbgt.shape[0] // 2
352
+ a, b = lbgt[:h], lbgt[h:]
353
+ da, _ = sqdist_min(a, b)
354
+ db, _ = sqdist_min(b, a)
355
+ lb = float(np.r_[da, db].mean())
356
+ ubs = []
357
+ for i in range(P):
358
+ r = np.random.randint(0, P)
359
+ ubs.append(dif_sc(xg[i], xg[r])["sq"])
360
+ ub = float(np.mean(ubs))
361
+ semi = [lb if i in representatives else dif_sc(xg[i], xs[i])["sq"] for i in range(P)]
362
+ naive = [lb if i in representatives else dif_sc(xg[i], xg[representatives[cluster_labels[i]]])["sq"] for i in range(P)]
363
+ return {"upperbound": ub, "lowerbound": lb, "semierror": float(np.mean(semi)), "naiveerror": float(np.mean(naive)),
364
+ "en_semi": (float(np.mean(semi)) - lb) / (ub - lb)}
365
+
366
+
367
+ # =========================================================================== unit inputs
368
+ def sha256(path: Path) -> str:
369
+ h = hashlib.sha256()
370
+ with open(path, "rb") as fh:
371
+ for block in iter(lambda: fh.read(1 << 24), b""):
372
+ h.update(block)
373
+ return h.hexdigest()
374
+
375
+
376
+ def free_gib(path: Path) -> float:
377
+ st = os.statvfs(path)
378
+ return st.f_bavail * st.f_frsize / 2**30
379
+
380
+
381
+ def resolve_npz(path: Path, want_sha: str, fetch_root: Path, fetched: list) -> Path:
382
+ """The scored NPZ: the local file if present, else a sha-checked copy from server_2 (same path) under fetch_root,
383
+ with its receipt (.log) next to it so score_ft.open_arm can check output_sha256."""
384
+ path = Path(path)
385
+ if path.is_file():
386
+ return path
387
+ rel = path.relative_to(TASK)
388
+ dst = fetch_root / rel
389
+ marker = path.with_suffix(".moved")
390
+ if dst.is_file() and dst.with_suffix(".log").is_file():
391
+ if sha256(dst) == want_sha:
392
+ return dst
393
+ dst.unlink()
394
+ size = int(subprocess.run(["ssh", "-n", REMOTE, f"stat -c %s '{path}'"], capture_output=True, text=True,
395
+ check=True).stdout.strip())
396
+ need = size / 2**30 + MIN_FREE_GIB
397
+ if free_gib(fetch_root) < need:
398
+ raise SystemExit(f"disk: {free_gib(fetch_root):.1f} GiB free < {need:.1f} GiB needed to fetch {path}")
399
+ dst.parent.mkdir(parents=True, exist_ok=True)
400
+ log(f"fetching {rel} ({size / 2**30:.2f} GiB) from {REMOTE}")
401
+ subprocess.run(["rsync", "-a", "--bwlimit=200000", f"{REMOTE}:{path}", str(dst)], check=True)
402
+ rec = path.with_suffix(".log")
403
+ if rec.is_file():
404
+ shutil.copy2(rec, dst.with_suffix(".log"))
405
+ else:
406
+ subprocess.run(["rsync", "-a", f"{REMOTE}:{rec}", str(dst.with_suffix(".log"))], check=True)
407
+ fetched.append(dst)
408
+ got = sha256(dst)
409
+ if got != want_sha:
410
+ raise SystemExit(f"{dst}: sha {got[:12]} differs from the scored NPZ sha {want_sha[:12]}")
411
+ if marker.is_file():
412
+ txt = marker.read_text()
413
+ if f"sha {want_sha[:12]}" not in txt:
414
+ raise SystemExit(f"{marker}: marker sha differs ({txt.strip()})")
415
+ return dst
416
+
417
+
418
+ def unit_calls(design: str, ds: str, draw: int | None) -> list[tuple[Path, tuple]]:
419
+ if design == "fewshot":
420
+ base = SCORES / ds / "fewshot_n5"
421
+ return [(base / f"draw{draw}", ("zs_raw", "zs_cal", "lora5", "zs_pseudo")), (base / f"draw{draw}_scsemi5", ("scsemi5",))]
422
+ if design == "pooled":
423
+ return [(SCORES / ds / "pooled", POOLED_ARMS)]
424
+ raise ValueError(design)
425
+
426
+
427
+ def unit_dir(design: str, ds: str, draw: int | None) -> Path:
428
+ return OUT_ROOT / ds / (f"fewshot_n5/draw{draw}" if design == "fewshot" else "pooled")
429
+
430
+
431
+ def observed_cells(spec, ref: dict, man: dict, donors: np.ndarray, cache: dict) -> tuple[list, dict]:
432
+ """All observed QC cells of the scored samples on the scoring genes (counts), per sample in the reference's
433
+ canonical cell order, from the same files the reference was built from (inputs sha-checked against
434
+ reference_manifest.json). cache: per dataset, reused by the draws of one process."""
435
+ if spec.name not in cache:
436
+ cache.clear()
437
+ cache[spec.name] = _observed_all(spec, ref, man)
438
+ X, srow, sid, inputs = cache[spec.name]
439
+ out = []
440
+ for d in donors:
441
+ out.append(X[np.flatnonzero(srow == int(np.flatnonzero(sid == d)[0]))].tocsr())
442
+ n = np.asarray([o.shape[0] for o in out])
443
+ ref_n = ref["n_cells"][[int(np.flatnonzero(ref["donors"].astype(str) == d)[0]) for d in donors]]
444
+ if not np.array_equal(n, ref_n):
445
+ raise SystemExit("observed cell counts per sample differ from the reference")
446
+ return out, {"inputs_sha256": inputs, "n_cells_total": int(n.sum())}
447
+
448
+
449
+ def _observed_all(spec, ref: dict, man: dict):
450
+ feat = F.load_features(spec.features)
451
+ if feat["sha256"] != man["features"]["sha256"]:
452
+ raise SystemExit("features sha differs from the reference's")
453
+ gs = F.gene_sets(feat)
454
+ if not np.array_equal(gs["score_ids"], ref["score_ids"].astype(str)):
455
+ raise SystemExit("scoring genes differ from the reference")
456
+ cells = F.load_cells_datadir(spec, gs)
457
+ if cells is None or cells["inputs_sha256"] != man["cells"]["inputs_sha256"]:
458
+ raise SystemExit("observed cell files differ from the ones the reference was built from")
459
+ keys, _ = F.cell_keys(cells["table"].reset_index(drop=True))
460
+ srow = np.asarray(cells["sample_row"])
461
+ order = np.lexsort((keys, srow)) # the reference's canonical order (F.build_reference)
462
+ X = cells["X"].tocsr()[order][:, gs["score_idx"]].tocsr().astype(np.float32)
463
+ return X, srow[order], feat["sample_ids"], cells["inputs_sha256"]
464
+
465
+
466
+ # =========================================================================== one unit
467
+ def pair_embeddings(v: dict, R: sp.csr_matrix, r_d: np.ndarray, Q: sp.csr_matrix, q_d: np.ndarray,
468
+ zr_raw: np.ndarray | None = None) -> dict:
469
+ """Real set R and query set Q in the scorer's PCA-50: 'raw' = SB.project; 'dm' = score_ft.depth_matched's own
470
+ steps (SB.depth_match of the pair with a fresh rng(DEPTH_SEED), real set in the 'R1' slot, then SB.project),
471
+ returning the embeddings instead of only their precision/coverage. zr_raw: the view's fitted z1 for R = R1."""
472
+ names = v["donors"]
473
+ thinned, _ = F.SB.depth_match({"R1": R, "Q": Q}, {"R1": names[r_d], "Q": names[q_d]}, list(names),
474
+ np.random.default_rng(F.DEPTH_SEED))
475
+ return {"raw": (zr_raw if zr_raw is not None else F.SB.project(R, v["mean"], v["comps"]),
476
+ F.SB.project(Q, v["mean"], v["comps"])),
477
+ "dm": (F.SB.project(thinned["R1"], v["mean"], v["comps"]), F.SB.project(thinned["Q"], v["mean"], v["comps"]))}
478
+
479
+
480
+ def per_donor_pc(r1_d, q_d, S_, res) -> tuple:
481
+ nq, n1 = np.bincount(q_d, minlength=S_), np.bincount(r1_d, minlength=S_)
482
+ return (np.bincount(q_d, weights=res["inside"], minlength=S_) / nq,
483
+ np.bincount(r1_d, weights=res["covered"], minlength=S_) / n1)
484
+
485
+
486
+ def score_set(name: str, v: dict, Q: sp.csr_matrix, q_d: np.ndarray, sigma_m: float, n_jobs: int,
487
+ expect: dict | None, oos: tuple | None) -> tuple[list, pd.DataFrame, dict]:
488
+ """Families 1, 2, 4 for one query set (an arm's P/C subsample, or R2), raw and depth matched, real side = R1
489
+ (the scorer's space). oos = (R2 counts, R2 donor index, set name): families 1-2 again with R2 as the real side."""
490
+ S_ = v["donors"].size
491
+ E = pair_embeddings(v, v["R1"], v["r1_d"], Q, q_d, zr_raw=v["z1"])
492
+ rows, per, chk = [], {"donor": v["donors"], "set": name}, {}
493
+ for mode, (zr, zg) in E.items():
494
+ t0 = time.monotonic()
495
+ m = {"set": name, "real_side": "R1", "mode": mode, "n_real": int(len(zr)), "n_gen": int(len(zg))}
496
+ for k in KS:
497
+ # k = 10 raw: the view's own radii (score_ft.arm_metrics); every other k / mode: radii recomputed on zr
498
+ res = F.SB.precision_coverage(zr, v["radius"], zg) if (k == F.K_NN and mode == "raw") else pc_at_k(zr, zg, k)
499
+ m[f"precision_k{k}"], m[f"coverage_k{k}"], m[f"density_k{k}"] = res["precision"], res["coverage"], res["density"]
500
+ m[f"expected_coverage_identical_k{k}"] = expected_coverage(len(zr), len(zg), k)
501
+ pp, pc = per_donor_pc(v["r1_d"], q_d, S_, res)
502
+ per[f"precision_k{k}_{mode}"], per[f"coverage_k{k}_{mode}"] = pp, pc
503
+ m.update(two_sample_block(zr, zg, sigma_m, n_jobs=n_jobs))
504
+ m["seconds"] = round(time.monotonic() - t0, 1)
505
+ rows.append(m)
506
+ log(f" {name} [R1 {mode}] P/C k10 {m['precision_k10']:.4f}/{m['coverage_k10']:.4f} k5 {m['precision_k5']:.4f}/"
507
+ f"{m['coverage_k5']:.4f} k3 {m['precision_k3']:.4f}/{m['coverage_k3']:.4f} | AUC knn {m['c2st_knn_auc']:.3f} "
508
+ f"rf {m['c2st_rf_auc']:.3f} | 1-NN {m['nn1_acc']:.3f} | MMD2 {m['mmd2_bw1']:.4f} ({m['seconds']} s)")
509
+ if oos is not None:
510
+ R2, r2_d, oname = oos
511
+ for mode, (zr, zg) in pair_embeddings(v, R2, r2_d, Q, q_d).items():
512
+ t0 = time.monotonic()
513
+ m = {"set": oname, "real_side": "R2", "mode": mode, "n_real": int(len(zr)), "n_gen": int(len(zg))}
514
+ m.update(two_sample_block(zr, zg, sigma_m, n_jobs=n_jobs))
515
+ m["seconds"] = round(time.monotonic() - t0, 1)
516
+ rows.append(m)
517
+ log(f" {oname} [R2 {mode}] AUC knn {m['c2st_knn_auc']:.3f} rf {m['c2st_rf_auc']:.3f} | 1-NN {m['nn1_acc']:.3f} "
518
+ f"| MMD2 {m['mmd2_bw1']:.4f} ({m['seconds']} s)")
519
+ if expect is not None: # reproduction of the scorer's k = 10 values
520
+ for mode, key in (("raw", ""), ("dm", "_depth_matched")):
521
+ mm = next(r for r in rows if r["mode"] == mode)
522
+ for q in ("precision", "coverage"):
523
+ chk[f"{q}{key}"] = {"ours": mm[f"{q}_k10"], "scorer": expect[f"{q}{key}"],
524
+ "abs_diff": abs(mm[f"{q}_k10"] - expect[f"{q}{key}"])}
525
+ if "per_donor" in expect:
526
+ d = np.abs(per[f"{q}_k10_{mode}"] - expect["per_donor"][f"{q}{key}"])
527
+ chk[f"{q}{key}_per_donor_max_abs_diff"] = float(d.max())
528
+ return rows, pd.DataFrame(per), chk
529
+
530
+
531
+ def run_unit(design: str, ds: str, draw: int | None, a) -> None:
532
+ t_unit = time.monotonic()
533
+ spec = F.DATASETS[ds]
534
+ out = unit_dir(design, ds, draw)
535
+ if (out / "manifest.json").is_file() and not a.force:
536
+ log(f"{out} done already")
537
+ return
538
+ out.mkdir(parents=True, exist_ok=True)
539
+ calls = unit_calls(design, ds, draw)
540
+ summ = {}
541
+ for cdir, arms in calls:
542
+ s = json.loads((cdir / "summary.json").read_text())
543
+ miss = [x for x in arms if x not in s["arms"]]
544
+ if miss:
545
+ raise SystemExit(f"{cdir}: arms {miss} not scored there")
546
+ summ[cdir] = s
547
+ first = summ[calls[0][0]]
548
+ donors = [str(x) for x in first["donors"]]
549
+ for cdir, s in summ.items():
550
+ if [str(x) for x in s["donors"]] != donors:
551
+ raise SystemExit(f"{cdir}: scored donors differ from {calls[0][0]}")
552
+ if s["reference"]["reference_sha256"] != first["reference"]["reference_sha256"]:
553
+ raise SystemExit(f"{cdir}: reference sha differs")
554
+ cache = F.CACHE_ROOT / ds
555
+ ref, man = F.load_reference(cache)
556
+ if man["reference_sha256"] != first["reference"]["reference_sha256"]:
557
+ raise SystemExit(f"{cache}: reference sha differs from the scored one")
558
+ log(f"{ds} {design} {'' if draw is None else f'draw{draw} '}: {len(donors)} scored samples; fitting the scorer's view")
559
+ v = S.make_view(ref, donors)
560
+ repro = {"unit": str(out), "pca": {"ours": v["pca"], "scorer": first["reference"]["pca"]},
561
+ "r2_control": {"ours": v["r2_control"], "scorer": first["reference"]["r2_control"]}, "arms": {}}
562
+ S_ = v["donors"].size
563
+ sigma_m = median_bandwidth(v["z1"])
564
+ log(f"bandwidth m (median pairwise distance of R1, PCA-50) = {sigma_m:.4f}")
565
+ rows, per_frames, en_rows, en_ps = [], [], [], []
566
+ fetched: list[Path] = []
567
+ fetch_root = Path(a.fetch_dir)
568
+
569
+ # ---------------- E_N inputs shared by all arms
570
+ rng_c = F.donor_rng
571
+ R1L = log1p_cp10k_sparse(v["R1"])
572
+ gram_r1 = Gram(R1L.shape[1]).add(R1L)
573
+ r1_split = [np.flatnonzero(v["r1_d"] == s) for s in range(S_)]
574
+ obs, obs_info = observed_cells(spec, ref, man, v["donors"], a.obs_cache)
575
+ # out-of-sample real sets from the scorer's donor-keyed permutation (F.reference_split): R1 = perm[:n],
576
+ # R2 = perm[n:2n] (both checked equal to reference.npz), R3 = perm[2n:3n] (fewer cells when the sample is small);
577
+ # the R2-vs-R3 control uses R2' = perm[n:n+m], m = min(n, |R3|), so both sides have the same size per sample.
578
+ r3_blocks, r2b_blocks, r3_d, r2b_d, oos_info = [], [], [], [], {"n_r3": [], "short_samples": []}
579
+ for k in range(S_):
580
+ nk, d = obs[k].shape[0], str(v["donors"][k])
581
+ a1, a2 = F.reference_split(nk, d)
582
+ if (obs[k][a1] != v["R1"][np.flatnonzero(v["r1_d"] == k)]).nnz or \
583
+ (obs[k][a2] != v["R2"][np.flatnonzero(v["r2_d"] == k)]).nnz:
584
+ raise SystemExit(f"{d}: R1 / R2 rebuilt from the observed cells differ from reference.npz")
585
+ perm = F.donor_rng(F.SUB_SEED, d).permutation(nk)
586
+ n = a1.size
587
+ r3 = np.sort(perm[2 * n:3 * n])
588
+ m_ = r3.size
589
+ if m_ < n:
590
+ oos_info["short_samples"].append({"sample": d, "n": int(n), "n_r3": int(m_)})
591
+ r3_blocks.append(obs[k][r3])
592
+ r2b_blocks.append(obs[k][np.sort(perm[n:n + m_])])
593
+ r3_d.append(np.full(m_, k))
594
+ r2b_d.append(np.full(m_, k))
595
+ oos_info["n_r3"].append(int(m_))
596
+ R3, R2b = sp.vstack(r3_blocks, format="csr"), sp.vstack(r2b_blocks, format="csr")
597
+ r3_d, r2b_d = np.concatenate(r3_d), np.concatenate(r2b_d)
598
+ log(f"observed cells: {obs_info['n_cells_total']} in {S_} samples; R1/R2 rebuilt = reference.npz; R3 {R3.shape[0]} "
599
+ f"cells ({len(oos_info['short_samples'])} samples with fewer than n)")
600
+ oos_r2 = (v["R2"], v["r2_d"])
601
+ if not a.no_en_all:
602
+ obsL = [log1p_cp10k_sparse(o) for o in obs]
603
+ gram_obs = Gram(R1L.shape[1])
604
+ for L in obsL:
605
+ gram_obs.add(L)
606
+ del obs
607
+
608
+ def en_unit(set_name: str, cellset: str, gts_L: list, semis_L: list, gram_real: Gram, n_rep_rows: int | None):
609
+ t0 = time.monotonic()
610
+ g = Gram(gts_L[0].shape[1])
611
+ for L in semis_L:
612
+ g.add(L)
613
+ mu, comps = (gram_real + g).pca(EN_PCS)
614
+ gts = [embed(L, mu, comps) for L in gts_L]
615
+ semis = [embed(L, mu, comps) for L in semis_L]
616
+ Z_all = np.vstack(gts + semis)
617
+ rng = np.random.default_rng([SEED, 17 if cellset == "pc" else 29])
618
+ res = en_from_embeddings(gts, semis, rng, Z_all=Z_all,
619
+ lb_max_queries=None if cellset == "pc" else EN_LB_MAX_QUERIES)
620
+ n_test = len(gts)
621
+ for d in ("sq", "l2"):
622
+ r = res[d]
623
+ en_rows.append({"set": set_name, "cellset": cellset, "distance": d, "n_samples": n_test,
624
+ "n_cells_real": int(sum(len(x) for x in gts)), "n_cells_gen": int(sum(len(x) for x in semis)),
625
+ "n_pcs": int(comps.shape[0]), "lb": r["lb"], "ub": r["ub"], "dif_mean": r["dif_mean"],
626
+ "en": r["en"], "lb_exact": res["lb"]["exact"], "lb_queries": res["lb"]["n_queries"],
627
+ "n_representative_rows": n_rep_rows,
628
+ "en_reps_at_lb": (r["en"] * n_test / (n_test + n_rep_rows)) if n_rep_rows else None,
629
+ "seconds": round(time.monotonic() - t0, 1)})
630
+ en_ps.append(pd.DataFrame({"set": set_name, "cellset": cellset, "distance": d, "donor": v["donors"],
631
+ "n_real": [len(x) for x in gts], "n_gen": [len(x) for x in semis],
632
+ "partner": v["donors"][res["partner"]], "dif": r["dif_i"], "en_i": r["en_i"]}))
633
+ log(f" {set_name} E_N[{cellset}] sq {res['sq']['en']:.4f} (LB {res['sq']['lb']:.3f} UB {res['sq']['ub']:.3f} "
634
+ f"Dif {res['sq']['dif_mean']:.3f}) l2 {res['l2']['en']:.4f} ({round(time.monotonic() - t0, 1)} s)")
635
+
636
+ # ---------------- control: R1 vs R2 (the scorer's own)
637
+ expect_r2 = {"precision": first["reference"]["r2_control"]["precision"],
638
+ "coverage": first["reference"]["r2_control"]["coverage"],
639
+ "precision_depth_matched": first["reference"]["r2_control"]["depth_matched"]["precision"],
640
+ "coverage_depth_matched": first["reference"]["r2_control"]["depth_matched"]["coverage"]}
641
+ r, p, chk = score_set(CONTROL, v, v["R2"], v["r2_d"], sigma_m, a.threads, expect_r2, oos=None)
642
+ rows += r
643
+ # out-of-sample control: R2' (real side) vs R3, families 1-2 only
644
+ for mode, (zr, zg) in pair_embeddings(v, R2b, r2b_d, R3, r3_d).items():
645
+ t0 = time.monotonic()
646
+ m = {"set": CONTROL_OOS, "real_side": "R2", "mode": mode, "n_real": int(len(zr)), "n_gen": int(len(zg))}
647
+ m.update(two_sample_block(zr, zg, sigma_m, n_jobs=a.threads))
648
+ m["seconds"] = round(time.monotonic() - t0, 1)
649
+ rows.append(m)
650
+ log(f" {CONTROL_OOS} [R2 {mode}] AUC knn {m['c2st_knn_auc']:.3f} rf {m['c2st_rf_auc']:.3f} | 1-NN "
651
+ f"{m['nn1_acc']:.3f} | MMD2 {m['mmd2_bw1']:.4f} ({m['seconds']} s)")
652
+ per_frames.append(p)
653
+ repro["arms"][CONTROL] = chk
654
+ R2L = log1p_cp10k_sparse(v["R2"])
655
+ en_unit(CONTROL, "pc", [R1L[i] for i in r1_split], [R2L[np.flatnonzero(v["r2_d"] == s)] for s in range(S_)],
656
+ gram_r1, None)
657
+ if not a.no_en_all:
658
+ A_, B_ = [], []
659
+ for s in range(S_):
660
+ perm = rng_c(SEED, v["donors"][s]).permutation(obsL[s].shape[0])
661
+ h = obsL[s].shape[0] // 2
662
+ A_.append(obsL[s][np.sort(perm[:h])])
663
+ B_.append(obsL[s][np.sort(perm[h:])])
664
+ # the PCA basis is the one of all observed cells (A and B together): gram_real = A-part, semis add the B-part
665
+ gA = Gram(R1L.shape[1])
666
+ for L in A_:
667
+ gA.add(L)
668
+ en_unit(CONTROL, "all", A_, B_, gA, None)
669
+ del A_, B_
670
+
671
+ # ---------------- arms
672
+ pcache = a.pcache # Poisson read-outs (scoring genes) by NPZ sha; zs_*_all are reused by later draws
673
+ n_rep_rows = None
674
+ if design == "fewshot":
675
+ dj = json.loads((TASK / "data" / ds / "fewshot_n5" / "DRAWS.json").read_text())["draw"][str(draw)]
676
+ n_rep_rows = int(dj["n_train_rows"])
677
+ panel_ids = ref["panel_ids"].astype(str)
678
+ for cdir, arms in calls:
679
+ s = summ[cdir]
680
+ per_csv = pd.read_csv(cdir / "per_donor.csv")
681
+ for name in arms:
682
+ t0 = time.monotonic()
683
+ pa = s["per_arm"][name]
684
+ path = resolve_npz(Path(pa["npz"]), pa["npz_sha256"], fetch_root, fetched)
685
+ arm = S.open_arm(name, path, panel_ids, allow_no_receipt=False)
686
+ if arm["sha256"] != pa["npz_sha256"] or not arm["receipt_verified"]:
687
+ raise SystemExit(f"{name}: NPZ sha / receipt check failed for {path}")
688
+ npos = {n: i for i, n in enumerate(arm["sample_ids"])}
689
+ rws = [np.flatnonzero(arm["bulk_index"] == npos[x]) for x in v["donors"]]
690
+ sel = np.concatenate(rws)
691
+ gen_d = np.repeat(np.arange(S_), [x.size for x in rws])
692
+ if arm["sha256"] not in pcache:
693
+ rates = np.ascontiguousarray(arm["d"]["generated_counts"], dtype=np.float32)
694
+ full = F.PR.poisson_integerise(rates, seed=F.POISSON_SEED, chunk_rows=4096)
695
+ del rates
696
+ pcache[arm["sha256"]] = full[:, ref["score_idx"]].tocsr()
697
+ del full
698
+ arm["d"].close()
699
+ Xg = pcache[arm["sha256"]][sel].tocsr()
700
+ sub = np.concatenate([np.flatnonzero(gen_d == k)[F.generated_subsample(int((gen_d == k).sum()),
701
+ int(v["n_ref"][k]), v["donors"][k])]
702
+ for k in range(S_)])
703
+ Q, q_d = Xg[sub].tocsr(), gen_d[sub]
704
+ gc = pd.read_parquet(cdir / "arms" / name / "generated_cells.parquet", columns=["npz_row", "in_pc_subsample"])
705
+ same_rows = bool(np.array_equal(gc.npz_row.to_numpy(), sel)
706
+ and np.array_equal(np.flatnonzero(gc.in_pc_subsample.to_numpy()), np.sort(sub)))
707
+ if not same_rows:
708
+ raise SystemExit(f"{name}: scored rows / P/C subsample differ from {cdir}/arms/{name}/generated_cells.parquet")
709
+ pdn = per_csv[per_csv.arm == name].set_index("donor").loc[v["donors"]]
710
+ h = s["headline"][name]
711
+ expect = {"precision": h["precision"], "coverage": h["coverage"], "precision_depth_matched": h["precision_dm"],
712
+ "coverage_depth_matched": h["coverage_dm"],
713
+ "per_donor": {k: pdn[k].to_numpy() for k in ("precision", "coverage", "precision_depth_matched",
714
+ "coverage_depth_matched")}}
715
+ log(f"{name}: {path.name} sha {arm['sha256'][:12]} (receipt verified), {sel.size} scored cells, "
716
+ f"{sub.size} in the P/C subsample (same rows as the scorer)")
717
+ r, p, chk = score_set(name, v, Q, q_d, sigma_m, a.threads, expect, oos=(oos_r2[0], oos_r2[1], name))
718
+ chk["rows_and_subsample_equal_scorer"] = same_rows
719
+ chk["npz"] = {"path": str(path), "scored_path": pa["npz"], "sha256": arm["sha256"]}
720
+ rows += r
721
+ per_frames.append(p)
722
+ repro["arms"][name] = chk
723
+ QL = log1p_cp10k_sparse(Q)
724
+ en_unit(name, "pc", [R1L[i] for i in r1_split], [QL[np.flatnonzero(q_d == k)] for k in range(S_)], gram_r1,
725
+ n_rep_rows if name == "scsemi5" else None)
726
+ if not a.no_en_all:
727
+ XgL = log1p_cp10k_sparse(Xg)
728
+ en_unit(name, "all", obsL, [XgL[np.flatnonzero(gen_d == k)] for k in range(S_)], gram_obs,
729
+ n_rep_rows if name == "scsemi5" else None)
730
+ del XgL
731
+ log(f"{name} done in {time.monotonic() - t0:.0f} s")
732
+ if not (design == "fewshot" and name in ("zs_raw", "zs_pseudo")):
733
+ pcache.pop(arm["sha256"], None) # not reused by another unit
734
+ # ---------------- write
735
+ meta = {"dataset": ds, "design": design, "unit": "pooled" if draw is None else f"draw{draw}"}
736
+ met = pd.DataFrame(rows)
737
+ for k, x in reversed(list(meta.items())):
738
+ met.insert(0, k, x)
739
+ met.insert(3, "label", met["set"].map(ARM_LABEL))
740
+ met.to_csv(out / "metrics.csv", index=False)
741
+ perd = pd.concat(per_frames, ignore_index=True)
742
+ for k, x in reversed(list(meta.items())):
743
+ perd.insert(0, k, x)
744
+ perd.to_csv(out / "per_donor.csv", index=False)
745
+ en = pd.DataFrame(en_rows)
746
+ for k, x in reversed(list(meta.items())):
747
+ en.insert(0, k, x)
748
+ en.to_csv(out / "en.csv", index=False)
749
+ ep = pd.concat(en_ps, ignore_index=True)
750
+ for k, x in reversed(list(meta.items())):
751
+ ep.insert(0, k, x)
752
+ ep.to_csv(out / "en_per_sample.csv", index=False)
753
+ worst = max([c.get("abs_diff", 0.0) for arm in repro["arms"].values() for c in arm.values() if isinstance(c, dict)]
754
+ + [0.0])
755
+ repro["max_abs_diff_k10_pooled"] = worst
756
+ repro["oos_r3"] = oos_info
757
+ repro["pca_equal"] = repro["pca"]["ours"] == repro["pca"]["scorer"]
758
+ (out / "repro.json").write_text(json.dumps(repro, indent=1, default=float) + "\n")
759
+ code = {str(p): sha256(p) for p in (Path(__file__).resolve(), TOOLS / "ft_common.py", TOOLS / "score_ft.py", F.SB_PATH)}
760
+ manifest = {"schema": "paired_ft_extra_metrics.v1", **meta, "written_utc": F.now(), "command": sys.argv,
761
+ "threads": a.threads, "donors": list(map(str, v["donors"])), "n_samples": int(S_),
762
+ "calls": {str(c): {"arms": list(arms), "summary_sha256": sha256(c / "summary.json")} for c, arms in calls},
763
+ "reference_sha256": man["reference_sha256"], "bandwidth_m": sigma_m,
764
+ "params": {"seed": SEED, "ks": KS, "knn_c2st_k": KNN_C2ST_K, "rf_trees": RF_TREES, "cv_folds": CV_FOLDS,
765
+ "bw_multiples": BW_MULTIPLES, "bw_max_cells": BW_MAX_CELLS, "en_pcs": EN_PCS,
766
+ "en_lb_max_queries_all_cells": EN_LB_MAX_QUERIES, "en_all_cells": not a.no_en_all},
767
+ "n_representative_rows": n_rep_rows, "fetched_from_server2": [str(f) for f in fetched],
768
+ "code_sha256": code, "seconds": round(time.monotonic() - t_unit, 1),
769
+ "max_abs_diff_k10_pooled": worst}
770
+ (out / "manifest.json").write_text(json.dumps(manifest, indent=1, default=float) + "\n")
771
+ log(f"unit {meta['unit']} of {ds} written to {out} in {manifest['seconds']} s (k=10 max |diff| vs scorer {worst:.2e})")
772
+ for f in fetched:
773
+ if f.name.startswith("zs__raw_all") or f.name.startswith("zs__pseudo_all"):
774
+ continue # shared by the draws of the cohort; removed by main after the last draw
775
+ f.unlink(missing_ok=True)
776
+ f.with_suffix(".log").unlink(missing_ok=True)
777
+ log(f"removed fetched copy {f}")
778
+
779
+
780
+ # =========================================================================== collect
781
+ COHORT = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis", "imperial_eskd": "Imperial", "giroux2022": "Giroux",
782
+ "ji2025_chili": "Ji (whole blood)"}
783
+ # headline columns: (column in metrics.csv / en.csv, short name, better direction: +1 higher, -1 lower, 0 closer to 0.5)
784
+ HEAD = [("c2st_knn_auc", "AUC kNN", 0), ("c2st_rf_auc", "AUC RF", 0), ("nn1_acc", "1-NN acc", 0),
785
+ ("mmd2_bw1", "MMD² (σ=m)", -1), ("mmd2_sum", "MMD² (sum)", -1), ("en_all_sq", "E_N all", -1),
786
+ ("en_pc_sq", "E_N P/C cells", -1),
787
+ ("precision_k3", "P k3", 1), ("coverage_k3", "C k3", 1), ("precision_k5", "P k5", 1), ("coverage_k5", "C k5", 1),
788
+ ("precision_k10", "P k10", 1), ("coverage_k10", "C k10", 1)]
789
+ LORA = {"fewshot": "lora5", "pooled": "real_lora__raw"}
790
+ COMPARE = {"fewshot": ("scsemi5", "zs_raw", "zs_cal"), "pooled": ("zs__raw", "zs__cal", "pseudo_full__cal")}
791
+ ORDER = {"fewshot": (CONTROL, CONTROL_OOS, "zs_raw", "zs_cal", "scsemi5", "lora5", "zs_pseudo"),
792
+ "pooled": (CONTROL, CONTROL_OOS, "zs__raw", "zs__cal", "pseudo_full__cal", "real_lora__raw", "zs__pseudo")}
793
+ SIDES = (("R1", "raw", "scorer space: real side = R1 (the PCA-50 fit cells), no depth matching = the deck's precision/coverage"),
794
+ ("R1", "dm", "scorer space: real side = R1, depth matched"),
795
+ ("R2", "raw", "out-of-sample real side = R2 (same PCA-50, generated cells and subsample), no depth matching"),
796
+ ("R2", "dm", "out-of-sample real side = R2, depth matched"))
797
+
798
+
799
+ def _wide(design: str) -> pd.DataFrame:
800
+ """One row per unit x set x mode: metrics.csv joined with the E_N headline (squared L2, both cell sets)."""
801
+ glob = "*/fewshot_n5/draw*" if design == "fewshot" else "*/pooled"
802
+ mets, ens = [], []
803
+ for d in sorted(OUT_ROOT.glob(glob)):
804
+ if (d / "manifest.json").is_file():
805
+ mets.append(pd.read_csv(d / "metrics.csv"))
806
+ ens.append(pd.read_csv(d / "en.csv"))
807
+ if not mets:
808
+ return pd.DataFrame()
809
+ met, en = pd.concat(mets, ignore_index=True), pd.concat(ens, ignore_index=True)
810
+ key = ["dataset", "design", "unit", "set"]
811
+ met = met[~((met.real_side == "R2") & (met.set == CONTROL))]
812
+ e = en.pivot_table(index=key, columns=["cellset", "distance"], values="en", aggfunc="first")
813
+ e.columns = [f"en_{c}_{d}" for c, d in e.columns]
814
+ r = en[en.cellset == "all"].pivot_table(index=key, columns="distance", values="en_reps_at_lb", aggfunc="first")
815
+ r.columns = [f"en_all_{d}_reps_at_lb" for d in r.columns]
816
+ out = met.merge(e.reset_index(), on=key, how="left").merge(r.reset_index(), on=key, how="left")
817
+ out.loc[out.real_side == "R2", [c for c in out.columns if c.startswith("en_")]] = np.nan # E_N: one value per set
818
+ return out
819
+
820
+
821
+ def _fmt(x, sd=None, nd=3):
822
+ if x is None or (isinstance(x, float) and np.isnan(x)):
823
+ return "—"
824
+ s = f"{x:.{nd}f}" if abs(x) >= 10 ** -nd or x == 0 else f"{x:.1e}"
825
+ return s + (f" ± {sd:.{nd}f}" if sd is not None and not np.isnan(sd) else "")
826
+
827
+
828
+ def _better(a: float, b: float, sign: int) -> bool:
829
+ return (abs(a - 0.5) < abs(b - 0.5)) if sign == 0 else (a > b if sign > 0 else a < b)
830
+
831
+
832
+ def collect() -> None:
833
+ """Concatenate every unit's CSVs into scores_extra/{fewshot,pooled}_*.csv and write TABLES.md (means over the
834
+ 5 draws for the few-pair design, single pooled calls for the 5-fold design; LoRA-vs-arm win counts per draw)."""
835
+ from scipy.stats import kendalltau
836
+ lines = ["# Extra realism / diversity metrics: tables", "",
837
+ f"Written by `tools/extra_metrics.py --collect` ({F.now()}). Definitions: `README.md`.", ""]
838
+ for design in ("fewshot", "pooled"):
839
+ glob = "*/fewshot_n5/draw*" if design == "fewshot" else "*/pooled"
840
+ for name in ("metrics", "per_donor", "en", "en_per_sample"):
841
+ parts = [pd.read_csv(d / f"{name}.csv") for d in sorted(OUT_ROOT.glob(glob)) if (d / "manifest.json").is_file()]
842
+ if parts:
843
+ pd.concat(parts, ignore_index=True).to_csv(OUT_ROOT / f"{design}_{name}.csv", index=False)
844
+ rep = [json.loads((d / "repro.json").read_text()) | {"unit_dir": str(d)} for d in sorted(OUT_ROOT.glob(glob))
845
+ if (d / "manifest.json").is_file()]
846
+ if rep:
847
+ rows = []
848
+ for r in rep:
849
+ for arm, c in r["arms"].items():
850
+ rows.append({"unit_dir": r["unit_dir"], "set": arm,
851
+ **{k: (x["abs_diff"] if isinstance(x, dict) and "abs_diff" in x else x)
852
+ for k, x in c.items() if k != "npz"}})
853
+ pd.DataFrame(rows).to_csv(OUT_ROOT / f"{design}_reproduction_check.csv", index=False)
854
+ w = _wide(design)
855
+ if w.empty:
856
+ continue
857
+ w.to_csv(OUT_ROOT / f"{design}_wide.csv", index=False)
858
+ title = "(a) 5-donor few-pair design (mean ± SD over 5 draws)" if design == "fewshot" else \
859
+ "(b) 5-fold pooled design (one call over all pairs)"
860
+ for side, mode, desc in SIDES:
861
+ sub = w[(w["mode"] == mode) & (w["real_side"] == side)]
862
+ lines += [f"## {title}; {desc}", ""]
863
+ cols = [c for c in HEAD if c[0] in sub.columns and sub[c[0]].notna().any()]
864
+ lines.append("| cohort | arm | n units | " + " | ".join(c[1] for c in cols) + " |")
865
+ lines.append("|---|---|---:|" + "---:|" * len(cols))
866
+ for ds in DATASETS:
867
+ for arm in ORDER[design]:
868
+ x = sub[(sub.dataset == ds) & (sub.set == arm)]
869
+ if x.empty:
870
+ continue
871
+ vals = []
872
+ for c, _, _ in cols:
873
+ col = x[c].astype(float)
874
+ vals.append(_fmt(col.mean(), col.std(ddof=1) if design == "fewshot" and len(col) > 1 else None,
875
+ 4 if c.startswith("mmd") else 3))
876
+ lines.append(f"| {COHORT[ds]} | {ARM_LABEL.get(arm, arm)} | {len(x)} | " + " | ".join(vals) + " |")
877
+ lines.append("")
878
+ for side in ("R1", "R2"):
879
+ _wins_and_tau(lines, w, design, title, side, kendalltau)
880
+ (OUT_ROOT / "TABLES.md").write_text("\n".join(lines) + "\n")
881
+ log(f"collected -> {OUT_ROOT}/TABLES.md")
882
+
883
+
884
+ def _wins_and_tau(lines: list, w: pd.DataFrame, design: str, title: str, side: str, kendalltau) -> None:
885
+ # LoRA vs every comparator, per metric (no depth matching)
886
+ sub = w[(w["mode"] == "raw") & (w["real_side"] == side)]
887
+ lines += [f"### {title}: does LoRA beat each comparator? (real side {side}, no depth matching; "
888
+ + ("draws where LoRA is better / draws compared" if design == "fewshot" else "pooled call: ✓ / ✗")
889
+ + "; AUC and 1-NN: closer to 0.5 is better)", ""]
890
+ cols = [c for c in HEAD if c[0] in sub.columns and sub[c[0]].notna().any()]
891
+ lines.append("| cohort | LoRA vs | " + " | ".join(c[1] for c in cols) + " |")
892
+ lines.append("|---|---|" + "---:|" * len(cols))
893
+ excepts = []
894
+ for ds in DATASETS:
895
+ L = sub[(sub.dataset == ds) & (sub.set == LORA[design])].set_index("unit")
896
+ if L.empty:
897
+ continue
898
+ for comp in COMPARE[design]:
899
+ Cm = sub[(sub.dataset == ds) & (sub.set == comp)].set_index("unit")
900
+ units = sorted(set(L.index) & set(Cm.index))
901
+ if not units:
902
+ continue
903
+ cells = []
904
+ for c, short, sign in cols:
905
+ wins = sum(_better(float(L.at[u, c]), float(Cm.at[u, c]), sign) for u in units)
906
+ cells.append(f"{wins}/{len(units)}" if design == "fewshot" else ("✓" if wins else "✗"))
907
+ if wins < len(units):
908
+ excepts.append(f"{COHORT[ds]}: LoRA not better than {ARM_LABEL[comp]} on {short} in "
909
+ f"{len(units) - wins}/{len(units)} unit(s)")
910
+ lines.append(f"| {COHORT[ds]} | {ARM_LABEL[comp]} | " + " | ".join(cells) + " |")
911
+ lines += ["", "Exceptions (LoRA not better):", ""] + [f"- {e}" for e in excepts] + [""]
912
+ # agreement of each metric's arm ranking with coverage (k = 10) and precision (k = 10), per cohort (means)
913
+ lines += [f"### {title}: Kendall τ between each metric's arm ranking and the coverage / precision (k = 10) "
914
+ "ranking (arms only, control excluded; mean over units per cohort; AUC / 1-NN ranked by |x - 0.5|)", ""]
915
+ lines.append("| cohort | vs | " + " | ".join(c[1] for c in cols) + " |")
916
+ lines.append("|---|---|" + "---:|" * len(cols))
917
+ for ds in DATASETS:
918
+ x = sub[(sub.dataset == ds) & ~sub.set.isin([CONTROL, CONTROL_OOS])].groupby("set")[[c[0] for c in cols]].mean()
919
+ if side == "R2": # P/C exists only on the R1 side: take the scorer's k = 10 values from the R1 rows
920
+ pr = w[(w.dataset == ds) & (w["mode"] == "raw") & (w.real_side == "R1")].groupby("set")[
921
+ ["coverage_k10", "precision_k10"]].mean()
922
+ x = x.drop(columns=[c for c in ("coverage_k10", "precision_k10") if c in x.columns]).join(pr)
923
+ if len(x) < 3:
924
+ continue
925
+
926
+ def score(c, sign):
927
+ return -(x[c] - 0.5).abs() if sign == 0 else x[c] * sign
928
+ for ref_c in ("coverage_k10", "precision_k10"):
929
+ taus = [kendalltau(score(c, s), x[ref_c]).statistic for c, _, s in cols]
930
+ lines.append(f"| {COHORT[ds]} | {ref_c.split('_')[0]} | " + " | ".join(_fmt(t, nd=2) for t in taus) + " |")
931
+ lines.append("")
932
+
933
+
934
+ def parse(argv=None):
935
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
936
+ p.add_argument("--design", choices=["fewshot", "pooled"])
937
+ p.add_argument("--dataset", choices=DATASETS)
938
+ p.add_argument("--draws", default="0,1,2,3,4")
939
+ p.add_argument("--threads", type=int, default=7)
940
+ p.add_argument("--fetch-dir", default=None, help="where server_2 NPZ copies go (default: scratch under scores_extra)")
941
+ p.add_argument("--no-en-all", action="store_true", help="skip the all-cells E_N (P/C-cell E_N is always computed)")
942
+ p.add_argument("--force", action="store_true", help="recompute units that already have a manifest")
943
+ p.add_argument("--collect", action="store_true")
944
+ return p.parse_args(argv)
945
+
946
+
947
+ def main(argv=None) -> int:
948
+ a = parse(argv)
949
+ if a.collect:
950
+ collect()
951
+ return 0
952
+ if not (1 <= a.threads <= 8):
953
+ raise SystemExit("--threads must be 1..8")
954
+ try:
955
+ from threadpoolctl import threadpool_limits
956
+ threadpool_limits(a.threads)
957
+ except ImportError:
958
+ pass
959
+ if a.design is None or a.dataset is None:
960
+ raise SystemExit("--design and --dataset are required (or --collect)")
961
+ a.fetch_dir = a.fetch_dir or str(OUT_ROOT / "_fetch_tmp")
962
+ Path(a.fetch_dir).mkdir(parents=True, exist_ok=True)
963
+ a.pcache, a.obs_cache = {}, {}
964
+ if a.design == "pooled":
965
+ run_unit("pooled", a.dataset, None, a)
966
+ else:
967
+ for j in [int(x) for x in a.draws.split(",") if x.strip()]:
968
+ run_unit("fewshot", a.dataset, j, a)
969
+ shared = Path(a.fetch_dir) / "generated" / a.dataset / "fewshot_n5"
970
+ for f in list(shared.glob("zs__*_all.npz")) if shared.is_dir() else []:
971
+ f.unlink(missing_ok=True)
972
+ f.with_suffix(".log").unlink(missing_ok=True)
973
+ log(f"removed fetched copy {f}")
974
+ return 0
975
+
976
+
977
+ if __name__ == "__main__":
978
+ raise SystemExit(main())
paper-releases/pbisc-diffusion/updates/20261001T200638Z-extra-realism-metrics/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scores_extra/_code/extra_metrics_v2_b65e022452d8.py ADDED
@@ -0,0 +1,983 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reviewer-expected realism / diversity metrics for the paired fine-tuning benchmark (CPU only; never imports torch).
3
+
4
+ Added 2026-10-01. Every scored unit (one few-pair draw, or one pooled 5-fold call) is re-read exactly as tools/score_ft.py
5
+ scored it, and four metric families are added next to the existing precision/coverage:
6
+
7
+ 1. classifier two-sample tests (real vs generated): kNN (k = 5) and random-forest 5-fold cross-validated ROC AUC
8
+ (scGAN / scDiffusion style) and the leave-one-out 1-NN accuracy (scLDM; Lopez-Paz & Oquab 2017);
9
+ 2. MMD^2 (unbiased, Gaussian RBF; median-heuristic bandwidth and the fixed multiples 0.5 / 1 / 2, plus their sum);
10
+ 3. scSemiProfiler's normalized error E_N (Wang et al. 2024, Methods eq. 17-18; get_error in vendor utils.py);
11
+ 4. precision / coverage at k = 3 and 5 next to k = 10 (k = 10 re-computed first and checked against score_ft.py).
12
+
13
+ Families 1, 2 and 4 use exactly the scorer's embedding and cells: score_ft.make_view (PCA-50 fitted on the scored
14
+ donors' R1 cells), the scorer's whole-NPZ Poisson read-out (seed 20260916), its donor-keyed generated subsample
15
+ (F.generated_subsample) and its pairwise depth matching (F.SB.depth_match with a fresh rng(20260929)). They are
16
+ reported both without ("raw", the deck's headline precision/coverage) and with depth matching ("dm"). The
17
+ real-vs-real control is the scorer's own: held-out real cells R2 of the same donors, same n per donor.
18
+
19
+ E_N follows scSemiProfiler's own space instead: per arm, log1p CP10K -> PCA-100 fitted on real and generated cells
20
+ together; Dif_sc = symmetric 1-NN distance (eq. 17); lower bound = random half split of the whole PCA matrix; upper
21
+ bound = random pairs of different real samples. Distances: squared L2 as their code computes them (faiss
22
+ IndexFlatL2), and plain L2 as the paper's text writes them. Two cell sets:
23
+ "all": every observed QC cell of each scored sample vs all of its generated cells (their setting);
24
+ control = a random within-sample half split of the observed cells (half A as 'real', half B as 'generated').
25
+ "pc": the precision/coverage cells (R1 vs the generated subsample, n per donor equal); control = R1 vs R2.
26
+ Representatives: scSemiProfiler sets a representative's error to the lower bound. Our scored samples never include a
27
+ representative (the 5 training donors of a few-pair draw are not scored in any arm), so no sample is set to LB; for
28
+ scsemi5 the table also gives the value that convention would produce (E_N x n_test / (n_test + n_representative_rows)).
29
+
30
+ usage (CPU; run through tools/run_extra_unit.sh):
31
+ extra_metrics.py --design fewshot --dataset giroux2022 --draws 0,1,2,3,4 [--threads 7] [--no-en-all]
32
+ extra_metrics.py --design pooled --dataset giroux2022
33
+ extra_metrics.py --collect # scores_extra/*.csv + TABLES.md from every unit written so far
34
+ Outputs: scores_extra/<dataset>/<fewshot_n5/draw<j> | pooled>/{metrics.csv, per_donor.csv, en.csv, en_per_sample.csv,
35
+ repro.json, manifest.json}.
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import os
40
+ import sys
41
+
42
+
43
+ def _threads_from_argv(default: int = 7) -> int:
44
+ for i, a in enumerate(sys.argv):
45
+ if a == "--threads" and i + 1 < len(sys.argv):
46
+ return int(sys.argv[i + 1])
47
+ if a.startswith("--threads="):
48
+ return int(a.split("=", 1)[1])
49
+ return default
50
+
51
+
52
+ _THR = str(_threads_from_argv())
53
+ for _k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMBA_NUM_THREADS"):
54
+ os.environ[_k] = _THR
55
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
56
+
57
+ import argparse # noqa: E402
58
+ import hashlib # noqa: E402
59
+ import json # noqa: E402
60
+ import shutil # noqa: E402
61
+ import subprocess # noqa: E402
62
+ import time # noqa: E402
63
+ from pathlib import Path # noqa: E402
64
+
65
+ import numpy as np # noqa: E402
66
+ import pandas as pd # noqa: E402
67
+ import scipy.sparse as sp # noqa: E402
68
+
69
+ TOOLS = Path(__file__).resolve().parent
70
+ sys.path.insert(0, str(TOOLS))
71
+ import ft_common as F # noqa: E402
72
+ import score_ft as S # noqa: E402 (module level: argparse/env only; main() is not run)
73
+
74
+ TASK = F.TASK
75
+ SCORES = TASK / "scores"
76
+ OUT_ROOT = TASK / "scores_extra"
77
+ REMOTE = "spark-0110"
78
+ MIN_FREE_GIB = 40.0
79
+
80
+ SEED = 20261001 # every new random stream of this file (CV folds, RF, bandwidth subsample, E_N)
81
+ KS = (3, 5, 10)
82
+ KNN_C2ST_K = 5 # sklearn default, scDiffusion's kNN classifier
83
+ RF_TREES = 300 # scGAN: fully grown trees, max_features = sqrt; 300 instead of 1000 trees (cost)
84
+ CV_FOLDS = 5 # scGAN: five-fold cross-validation, equal real / generated counts
85
+ BW_MULTIPLES = (0.5, 1.0, 2.0) # scGAN: sigma in {m/2, m, 2m}
86
+ BW_MAX_CELLS = 4000 # R1 cells used for the median pairwise distance
87
+ EN_PCS = 100 # scSemiProfiler: PCA to 100 dimensions
88
+ EN_LB_MAX_QUERIES = 20000 # all-cells E_N: LB estimated from this many query cells per direction (index = full half)
89
+ EN_CHUNK = 8192
90
+
91
+ FEW_ARMS = ("zs_raw", "zs_cal", "scsemi5", "lora5", "zs_pseudo")
92
+ POOLED_ARMS = ("zs__raw", "zs__cal", "pseudo_full__cal", "real_lora__raw", "zs__pseudo")
93
+ CONTROL = "real_R2" # R1 vs R2 (P/C cells) / within-sample half split (all cells)
94
+ CONTROL_OOS = "real_R3" # out-of-sample real side: R2' vs R3 (families 1-2)
95
+ ARM_LABEL = {"zs_raw": "Zero-shot, real bulk", "zs__raw": "Zero-shot, real bulk",
96
+ "zs_cal": "Zero-shot + calibration", "zs__cal": "Zero-shot + calibration",
97
+ "scsemi5": "scSemiProfiler, 5 donors", "lora5": "LoRA, 5 donors",
98
+ "real_lora__raw": "LoRA, all training pairs", "pseudo_full__cal": "sc-only fine-tune (+ calibration)",
99
+ "zs_pseudo": "Zero-shot, sc pseudobulk input (reference)",
100
+ "zs__pseudo": "Zero-shot, sc pseudobulk input (reference)",
101
+ CONTROL: "Real vs real control (held-out real cells)",
102
+ CONTROL_OOS: "Real vs real control (out-of-sample: R2 vs R3)"}
103
+ DATASETS = ("immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
104
+
105
+
106
+ def log(msg: str) -> None:
107
+ F.log(msg)
108
+
109
+
110
+ # =========================================================================== pure metric functions
111
+ def sqdist_min(Q: np.ndarray, X: np.ndarray, *, exclude_self: bool = False, max_block: float = 1.5e8) -> tuple:
112
+ """For every row of Q: the minimum squared L2 distance to the rows of X and its index (brute force, float64,
113
+ chunked BLAS). exclude_self: Q is X and the diagonal is skipped (leave-one-out)."""
114
+ Q = np.ascontiguousarray(Q, dtype=np.float64)
115
+ X = np.ascontiguousarray(X, dtype=np.float64)
116
+ xx = np.einsum("ij,ij->i", X, X)
117
+ qq = np.einsum("ij,ij->i", Q, Q)
118
+ out = np.empty(Q.shape[0])
119
+ arg = np.empty(Q.shape[0], dtype=np.int64)
120
+ chunk = max(16, int(max_block // max(X.shape[0], 1)))
121
+ for s in range(0, Q.shape[0], chunk):
122
+ e = min(s + chunk, Q.shape[0])
123
+ D = qq[s:e, None] + xx[None, :] - 2.0 * (Q[s:e] @ X.T)
124
+ if exclude_self:
125
+ D[np.arange(e - s), np.arange(s, e)] = np.inf
126
+ a = np.argmin(D, axis=1)
127
+ arg[s:e] = a
128
+ out[s:e] = np.maximum(D[np.arange(e - s), a], 0.0)
129
+ return out, arg
130
+
131
+
132
+ def one_nn_loo(zr: np.ndarray, zg: np.ndarray) -> dict:
133
+ """Leave-one-out 1-NN two-sample accuracy (Lopez-Paz & Oquab 2017; scLDM eq. 32): pool both sets, predict each
134
+ point's label by its nearest other point; 0.5 = indistinguishable, 1 = separable."""
135
+ Z = np.vstack([zr, zg])
136
+ y = np.r_[np.ones(len(zr), bool), np.zeros(len(zg), bool)]
137
+ _, a = sqdist_min(Z, Z, exclude_self=True)
138
+ ok = y[a] == y
139
+ return {"nn1_acc": float(ok.mean()), "nn1_acc_real": float(ok[y].mean()), "nn1_acc_gen": float(ok[~y].mean())}
140
+
141
+
142
+ def c2st_auc(zr: np.ndarray, zg: np.ndarray, *, kind: str, seed: int = SEED, n_jobs: int = 1) -> dict:
143
+ """Classifier two-sample test: stratified 5-fold CV ROC AUC of real (1) vs generated (0); mean and SD over folds."""
144
+ from sklearn.ensemble import RandomForestClassifier
145
+ from sklearn.metrics import roc_auc_score
146
+ from sklearn.model_selection import StratifiedKFold
147
+ from sklearn.neighbors import KNeighborsClassifier
148
+ Z = np.vstack([zr, zg]).astype(np.float32)
149
+ y = np.r_[np.ones(len(zr), np.int8), np.zeros(len(zg), np.int8)]
150
+ aucs = []
151
+ for tr, te in StratifiedKFold(CV_FOLDS, shuffle=True, random_state=seed).split(Z, y):
152
+ if kind == "knn":
153
+ clf = KNeighborsClassifier(n_neighbors=KNN_C2ST_K, n_jobs=n_jobs)
154
+ elif kind == "rf":
155
+ clf = RandomForestClassifier(n_estimators=RF_TREES, max_features="sqrt", n_jobs=n_jobs, random_state=seed)
156
+ else:
157
+ raise ValueError(kind)
158
+ clf.fit(Z[tr], y[tr])
159
+ p = clf.predict_proba(Z[te])[:, list(clf.classes_).index(1)]
160
+ aucs.append(roc_auc_score(y[te], p))
161
+ return {f"c2st_{kind}_auc": float(np.mean(aucs)), f"c2st_{kind}_auc_sd": float(np.std(aucs, ddof=1))}
162
+
163
+
164
+ def median_bandwidth(z: np.ndarray, *, seed: int = SEED, max_cells: int = BW_MAX_CELLS) -> float:
165
+ """Median heuristic (Gretton et al. 2012): median pairwise Euclidean distance among (<= max_cells) real cells."""
166
+ rng = np.random.default_rng(seed)
167
+ idx = np.sort(rng.choice(len(z), size=min(max_cells, len(z)), replace=False))
168
+ x = np.asarray(z[idx], np.float64)
169
+ sq = np.einsum("ij,ij->i", x, x)
170
+ D = np.maximum(sq[:, None] + sq[None, :] - 2 * x @ x.T, 0.0)
171
+ iu = np.triu_indices(len(x), 1)
172
+ return float(np.sqrt(np.median(D[iu])))
173
+
174
+
175
+ def _kernel_sums(A: np.ndarray, B: np.ndarray, sigmas, same: bool, max_block: float = 6e7) -> np.ndarray:
176
+ """sum over pairs of exp(-||a - b||^2 / (2 sigma^2)) for every sigma (diagonal excluded when same)."""
177
+ A = np.ascontiguousarray(A, np.float64)
178
+ B = np.ascontiguousarray(B, np.float64)
179
+ aa, bb = np.einsum("ij,ij->i", A, A), np.einsum("ij,ij->i", B, B)
180
+ g = np.asarray([1.0 / (2.0 * s * s) for s in sigmas])
181
+ tot = np.zeros(len(sigmas))
182
+ chunk = max(16, int(max_block // max(len(B), 1)))
183
+ for s in range(0, len(A), chunk):
184
+ e = min(s + chunk, len(A))
185
+ D = np.maximum(aa[s:e, None] + bb[None, :] - 2.0 * (A[s:e] @ B.T), 0.0)
186
+ for i, gi in enumerate(g):
187
+ K = np.exp(-gi * D)
188
+ if same:
189
+ K[np.arange(e - s), np.arange(s, e)] = 0.0
190
+ tot[i] += K.sum()
191
+ return tot
192
+
193
+
194
+ def mmd2_unbiased(zr: np.ndarray, zg: np.ndarray, sigmas) -> np.ndarray:
195
+ """Unbiased MMD^2 (Gretton et al. 2012, eq. 3) with Gaussian RBF k(x, y) = exp(-||x - y||^2 / (2 sigma^2)), one value
196
+ per sigma; the kernel sum over the sigmas (scGAN's multi-scale kernel) is the sum of the per-sigma values."""
197
+ n, m = len(zr), len(zg)
198
+ kxx = _kernel_sums(zr, zr, sigmas, True) / (n * (n - 1))
199
+ kyy = _kernel_sums(zg, zg, sigmas, True) / (m * (m - 1))
200
+ kxy = _kernel_sums(zr, zg, sigmas, False) / (n * m)
201
+ return kxx + kyy - 2.0 * kxy
202
+
203
+
204
+ def pc_at_k(zr: np.ndarray, zg: np.ndarray, k: int) -> dict:
205
+ """Kynkaanniemi precision and Naeem coverage / density with k-NN balls of the real set: the scorer's own
206
+ stage_b_embed functions (knn_radius, precision_coverage). density is rescaled from SB's fixed k = 10 to k."""
207
+ radius = F.SB.knn_radius(zr, k)
208
+ r = F.SB.precision_coverage(zr, radius, zg)
209
+ r["density"] = r["density"] * F.K_NN / k
210
+ return r
211
+
212
+
213
+ def expected_coverage(n_real: int, n_gen: int, k: int) -> float:
214
+ """Naeem et al. 2020, eq. 9: E[coverage] for identical real and fake distributions."""
215
+ num = np.prod([(n_real - i) for i in range(1, k + 1)], dtype=np.float64)
216
+ den = np.prod([(n_gen + n_real - i) for i in range(1, k + 1)], dtype=np.float64)
217
+ return float(1.0 - num / den)
218
+
219
+
220
+ def two_sample_block(zr: np.ndarray, zg: np.ndarray, sigma_m: float, *, n_jobs: int, rf: bool = True) -> dict:
221
+ out = {}
222
+ out.update(c2st_auc(zr, zg, kind="knn", n_jobs=n_jobs))
223
+ if rf:
224
+ out.update(c2st_auc(zr, zg, kind="rf", n_jobs=n_jobs))
225
+ out.update(one_nn_loo(zr, zg))
226
+ sig = [m * sigma_m for m in BW_MULTIPLES]
227
+ mm = mmd2_unbiased(zr, zg, sig)
228
+ for mult, val in zip(BW_MULTIPLES, mm):
229
+ out[f"mmd2_bw{mult:g}"] = float(val)
230
+ out["mmd2_sum"] = float(mm.sum())
231
+ out["mmd_bandwidth_m"] = float(sigma_m)
232
+ return out
233
+
234
+
235
+ # =========================================================================== scSemiProfiler E_N
236
+ def log1p_cp10k_sparse(X: sp.csr_matrix) -> sp.csr_matrix:
237
+ """SB.cp10k_log1p (per-cell CP10K over the columns, log1p; empty cells stay zero) kept sparse, float32."""
238
+ X = X.tocsr().astype(np.float64)
239
+ lib = np.asarray(X.sum(axis=1)).ravel()
240
+ D = (sp.diags(np.divide(F.CP10K, lib, out=np.zeros_like(lib), where=lib > 0)) @ X).tocsr()
241
+ D.data = np.log1p(D.data)
242
+ return D.astype(np.float32)
243
+
244
+
245
+ class Gram:
246
+ """Running X^T X, column sums and row count of log1p-CP10K features (float64), for an exact PCA by eigh of the
247
+ covariance (the solver sklearn's PCA calls covariance_eigh; equal to the full-SVD PCA up to component signs)."""
248
+
249
+ def __init__(self, p: int):
250
+ self.G = np.zeros((p, p))
251
+ self.s = np.zeros(p)
252
+ self.n = 0
253
+
254
+ def add(self, L: sp.csr_matrix, chunk: int = EN_CHUNK) -> "Gram":
255
+ for a in range(0, L.shape[0], chunk):
256
+ B = L[a:a + chunk].toarray() # float32 (log1p CP10K)
257
+ self.G += (B.T @ B).astype(np.float64) # sgemm within a chunk, float64 across chunks
258
+ self.s += B.sum(0, dtype=np.float64)
259
+ self.n += B.shape[0]
260
+ return self
261
+
262
+ def __add__(self, other: "Gram") -> "Gram":
263
+ g = Gram(len(self.s))
264
+ g.G, g.s, g.n = self.G + other.G, self.s + other.s, self.n + other.n
265
+ return g
266
+
267
+ def pca(self, n_comp: int = EN_PCS) -> tuple[np.ndarray, np.ndarray]:
268
+ from scipy.linalg import eigh
269
+ p = len(self.s)
270
+ n_comp = int(min(n_comp, p, self.n - 1))
271
+ mu = self.s / self.n
272
+ C = (self.G - self.n * np.outer(mu, mu)) / (self.n - 1)
273
+ w, V = eigh(C, subset_by_index=[p - n_comp, p - 1])
274
+ return mu, np.ascontiguousarray(V[:, ::-1].T) # components x genes, descending variance
275
+
276
+
277
+ def embed(L: sp.csr_matrix, mu: np.ndarray, comps: np.ndarray, chunk: int = EN_CHUNK) -> np.ndarray:
278
+ """(x - mu) @ comps.T for sparse features x (dense row chunks, float64 BLAS)."""
279
+ out = np.empty((L.shape[0], comps.shape[0]))
280
+ for a in range(0, L.shape[0], chunk):
281
+ out[a:a + chunk] = (L[a:a + chunk].toarray().astype(np.float64) - mu) @ comps.T
282
+ return out
283
+
284
+
285
+ def dif_sc(a: np.ndarray, b: np.ndarray) -> dict:
286
+ """scSemiProfiler eq. 17 with K = 1: mean over the cells of both samples of the distance to the nearest cell of the
287
+ other sample. 'sq' = squared L2 (their code: faiss IndexFlatL2), 'l2' = L2 (their text)."""
288
+ da, _ = sqdist_min(a, b)
289
+ db, _ = sqdist_min(b, a)
290
+ n = len(a) + len(b)
291
+ return {"sq": float((da.sum() + db.sum()) / n), "l2": float((np.sqrt(da).sum() + np.sqrt(db).sum()) / n)}
292
+
293
+
294
+ def lower_bound(Z: np.ndarray, rng: np.random.Generator, max_queries: int | None) -> dict:
295
+ """LB: random half split of the whole PCA matrix (real + generated), symmetric 1-NN (their code: shuffle, first
296
+ n//2 rows vs the rest). With max_queries, each direction averages max_queries random query cells of one half
297
+ against the complete other half (an unbiased estimate of the same mean)."""
298
+ perm = rng.permutation(len(Z))
299
+ h = len(Z) // 2
300
+ A, B = Z[perm[:h]], Z[perm[h:]]
301
+ qa = A if (max_queries is None or len(A) <= max_queries) else A[np.sort(rng.choice(len(A), max_queries, replace=False))]
302
+ qb = B if (max_queries is None or len(B) <= max_queries) else B[np.sort(rng.choice(len(B), max_queries, replace=False))]
303
+ da, _ = sqdist_min(qa, B)
304
+ db, _ = sqdist_min(qb, A)
305
+ exact = len(qa) == len(A) and len(qb) == len(B)
306
+ if exact: # their arithmetic: mean over the concatenated distances of both directions
307
+ sq = float((da.sum() + db.sum()) / (len(da) + len(db)))
308
+ l2 = float((np.sqrt(da).sum() + np.sqrt(db).sum()) / (len(da) + len(db)))
309
+ else: # same weights as the exact concatenation (|A| and |B| cells), each direction estimated
310
+ wa, wb = len(A) / (len(A) + len(B)), len(B) / (len(A) + len(B))
311
+ sq = float(wa * da.mean() + wb * db.mean())
312
+ l2 = float(wa * np.sqrt(da).mean() + wb * np.sqrt(db).mean())
313
+ return {"sq": sq, "l2": l2, "exact": exact, "n_queries": [int(len(qa)), int(len(qb))], "n_half": [int(len(A)), int(len(B))]}
314
+
315
+
316
+ def en_from_embeddings(gts: list, semis: list, rng: np.random.Generator, *, lb_max_queries: int | None,
317
+ Z_all: np.ndarray) -> dict:
318
+ """E_N for one arm from per-sample embeddings (PCA already fitted on real + generated together).
319
+ UB: per sample i a uniformly random partner j != i (real cells of both), Dif averaged over samples.
320
+ Dif_i: real vs generated of sample i. E_N = (mean_i Dif_i - LB) / (UB - LB) (eq. 18); per sample (Dif_i - LB) / (UB - LB)."""
321
+ P = len(gts)
322
+ lb = lower_bound(Z_all, rng, lb_max_queries)
323
+ partner = (np.arange(P) + rng.integers(1, P, size=P)) % P if P > 1 else np.zeros(P, int)
324
+ ub_i = [dif_sc(gts[i], gts[partner[i]]) for i in range(P)]
325
+ dif_i = [dif_sc(gts[i], semis[i]) for i in range(P)]
326
+ out = {"lb": lb, "partner": partner.tolist(), "per_sample": []}
327
+ for d in ("sq", "l2"):
328
+ ub = float(np.mean([u[d] for u in ub_i]))
329
+ dif = np.asarray([x[d] for x in dif_i])
330
+ out[d] = {"lb": lb[d], "ub": ub, "dif_mean": float(dif.mean()), "en": float((dif.mean() - lb[d]) / (ub - lb[d])),
331
+ "en_i": ((dif - lb[d]) / (ub - lb[d])).tolist(), "dif_i": dif.tolist()}
332
+ return out
333
+
334
+
335
+ def get_error_legacy(gts: list, semis: list, representatives: list, cluster_labels: list, n_comp: int = EN_PCS) -> dict:
336
+ """Line-by-line re-statement of scSemiProfiler utils.get_error for one round (global np.random state, sklearn PCA,
337
+ self-pairing allowed in the UB, representatives at LB, squared L2). Only for the equivalence test."""
338
+ from sklearn.decomposition import PCA
339
+ P = len(gts)
340
+ X = np.concatenate([np.concatenate(gts, 0), np.concatenate(semis, 0)], 0)
341
+ Xr = PCA(n_components=n_comp).fit_transform(X)
342
+ xg, xs, off = [], [], 0
343
+ for g in gts:
344
+ xg.append(Xr[off:off + len(g)])
345
+ off += len(g)
346
+ for s in semis:
347
+ xs.append(Xr[off:off + len(s)])
348
+ off += len(s)
349
+ lbgt = Xr.copy()
350
+ np.random.shuffle(lbgt)
351
+ h = lbgt.shape[0] // 2
352
+ a, b = lbgt[:h], lbgt[h:]
353
+ da, _ = sqdist_min(a, b)
354
+ db, _ = sqdist_min(b, a)
355
+ lb = float(np.r_[da, db].mean())
356
+ ubs = []
357
+ for i in range(P):
358
+ r = np.random.randint(0, P)
359
+ ubs.append(dif_sc(xg[i], xg[r])["sq"])
360
+ ub = float(np.mean(ubs))
361
+ semi = [lb if i in representatives else dif_sc(xg[i], xs[i])["sq"] for i in range(P)]
362
+ naive = [lb if i in representatives else dif_sc(xg[i], xg[representatives[cluster_labels[i]]])["sq"] for i in range(P)]
363
+ return {"upperbound": ub, "lowerbound": lb, "semierror": float(np.mean(semi)), "naiveerror": float(np.mean(naive)),
364
+ "en_semi": (float(np.mean(semi)) - lb) / (ub - lb)}
365
+
366
+
367
+ # =========================================================================== unit inputs
368
+ def sha256(path: Path) -> str:
369
+ h = hashlib.sha256()
370
+ with open(path, "rb") as fh:
371
+ for block in iter(lambda: fh.read(1 << 24), b""):
372
+ h.update(block)
373
+ return h.hexdigest()
374
+
375
+
376
+ def free_gib(path: Path) -> float:
377
+ st = os.statvfs(path)
378
+ return st.f_bavail * st.f_frsize / 2**30
379
+
380
+
381
+ def resolve_npz(path: Path, want_sha: str, fetch_root: Path, fetched: list) -> Path:
382
+ """The scored NPZ: the local file if present, else a sha-checked copy from server_2 (same path) under fetch_root,
383
+ with its receipt (.log) next to it so score_ft.open_arm can check output_sha256."""
384
+ path = Path(path)
385
+ if path.is_file():
386
+ return path
387
+ rel = path.relative_to(TASK)
388
+ dst = fetch_root / rel
389
+ marker = path.with_suffix(".moved")
390
+ if dst.is_file() and dst.with_suffix(".log").is_file():
391
+ if sha256(dst) == want_sha:
392
+ return dst
393
+ dst.unlink()
394
+ size = int(subprocess.run(["ssh", "-n", REMOTE, f"stat -c %s '{path}'"], capture_output=True, text=True,
395
+ check=True).stdout.strip())
396
+ need = size / 2**30 + MIN_FREE_GIB
397
+ if free_gib(fetch_root) < need:
398
+ raise SystemExit(f"disk: {free_gib(fetch_root):.1f} GiB free < {need:.1f} GiB needed to fetch {path}")
399
+ dst.parent.mkdir(parents=True, exist_ok=True)
400
+ log(f"fetching {rel} ({size / 2**30:.2f} GiB) from {REMOTE}")
401
+ subprocess.run(["rsync", "-a", "--bwlimit=200000", f"{REMOTE}:{path}", str(dst)], check=True)
402
+ rec = path.with_suffix(".log")
403
+ if rec.is_file():
404
+ shutil.copy2(rec, dst.with_suffix(".log"))
405
+ else:
406
+ subprocess.run(["rsync", "-a", f"{REMOTE}:{rec}", str(dst.with_suffix(".log"))], check=True)
407
+ fetched.append(dst)
408
+ got = sha256(dst)
409
+ if got != want_sha:
410
+ raise SystemExit(f"{dst}: sha {got[:12]} differs from the scored NPZ sha {want_sha[:12]}")
411
+ if marker.is_file():
412
+ txt = marker.read_text()
413
+ if f"sha {want_sha[:12]}" not in txt:
414
+ raise SystemExit(f"{marker}: marker sha differs ({txt.strip()})")
415
+ return dst
416
+
417
+
418
+ def unit_calls(design: str, ds: str, draw: int | None) -> list[tuple[Path, tuple]]:
419
+ if design == "fewshot":
420
+ base = SCORES / ds / "fewshot_n5"
421
+ return [(base / f"draw{draw}", ("zs_raw", "zs_cal", "lora5", "zs_pseudo")), (base / f"draw{draw}_scsemi5", ("scsemi5",))]
422
+ if design == "pooled":
423
+ return [(SCORES / ds / "pooled", POOLED_ARMS)]
424
+ raise ValueError(design)
425
+
426
+
427
+ def unit_dir(design: str, ds: str, draw: int | None) -> Path:
428
+ return OUT_ROOT / ds / (f"fewshot_n5/draw{draw}" if design == "fewshot" else "pooled")
429
+
430
+
431
+ def observed_cells(spec, ref: dict, man: dict, donors: np.ndarray, cache: dict) -> tuple[list, dict]:
432
+ """All observed QC cells of the scored samples on the scoring genes (counts), per sample in the reference's
433
+ canonical cell order, from the same files the reference was built from (inputs sha-checked against
434
+ reference_manifest.json). cache: per dataset, reused by the draws of one process."""
435
+ if spec.name not in cache:
436
+ cache.clear()
437
+ cache[spec.name] = _observed_all(spec, ref, man)
438
+ X, srow, sid, inputs = cache[spec.name]
439
+ out = []
440
+ for d in donors:
441
+ out.append(X[np.flatnonzero(srow == int(np.flatnonzero(sid == d)[0]))].tocsr())
442
+ n = np.asarray([o.shape[0] for o in out])
443
+ ref_n = ref["n_cells"][[int(np.flatnonzero(ref["donors"].astype(str) == d)[0]) for d in donors]]
444
+ if not np.array_equal(n, ref_n):
445
+ raise SystemExit("observed cell counts per sample differ from the reference")
446
+ return out, {"inputs_sha256": inputs, "n_cells_total": int(n.sum())}
447
+
448
+
449
+ def _observed_all(spec, ref: dict, man: dict):
450
+ feat = F.load_features(spec.features)
451
+ if feat["sha256"] != man["features"]["sha256"]:
452
+ raise SystemExit("features sha differs from the reference's")
453
+ gs = F.gene_sets(feat)
454
+ if not np.array_equal(gs["score_ids"], ref["score_ids"].astype(str)):
455
+ raise SystemExit("scoring genes differ from the reference")
456
+ cells = F.load_cells_datadir(spec, gs)
457
+ if cells is None or cells["inputs_sha256"] != man["cells"]["inputs_sha256"]:
458
+ raise SystemExit("observed cell files differ from the ones the reference was built from")
459
+ keys, _ = F.cell_keys(cells["table"].reset_index(drop=True))
460
+ srow = np.asarray(cells["sample_row"])
461
+ order = np.lexsort((keys, srow)) # the reference's canonical order (F.build_reference)
462
+ X = cells["X"].tocsr()[order][:, gs["score_idx"]].tocsr().astype(np.float32)
463
+ return X, srow[order], feat["sample_ids"], cells["inputs_sha256"]
464
+
465
+
466
+ # =========================================================================== one unit
467
+ def pair_embeddings(v: dict, R: sp.csr_matrix, r_d: np.ndarray, Q: sp.csr_matrix, q_d: np.ndarray,
468
+ zr_raw: np.ndarray | None = None) -> dict:
469
+ """Real set R and query set Q in the scorer's PCA-50: 'raw' = SB.project; 'dm' = score_ft.depth_matched's own
470
+ steps (SB.depth_match of the pair with a fresh rng(DEPTH_SEED), real set in the 'R1' slot, then SB.project),
471
+ returning the embeddings instead of only their precision/coverage. zr_raw: the view's fitted z1 for R = R1."""
472
+ names = v["donors"]
473
+ thinned, _ = F.SB.depth_match({"R1": R, "Q": Q}, {"R1": names[r_d], "Q": names[q_d]}, list(names),
474
+ np.random.default_rng(F.DEPTH_SEED))
475
+ return {"raw": (zr_raw if zr_raw is not None else F.SB.project(R, v["mean"], v["comps"]),
476
+ F.SB.project(Q, v["mean"], v["comps"])),
477
+ "dm": (F.SB.project(thinned["R1"], v["mean"], v["comps"]), F.SB.project(thinned["Q"], v["mean"], v["comps"]))}
478
+
479
+
480
+ def per_donor_pc(r1_d, q_d, S_, res) -> tuple:
481
+ nq, n1 = np.bincount(q_d, minlength=S_), np.bincount(r1_d, minlength=S_)
482
+ return (np.bincount(q_d, weights=res["inside"], minlength=S_) / nq,
483
+ np.bincount(r1_d, weights=res["covered"], minlength=S_) / n1)
484
+
485
+
486
+ def score_set(name: str, v: dict, Q: sp.csr_matrix, q_d: np.ndarray, sigma_m: float, n_jobs: int,
487
+ expect: dict | None, oos: tuple | None) -> tuple[list, pd.DataFrame, dict]:
488
+ """Families 1, 2, 4 for one query set (an arm's P/C subsample, or R2), raw and depth matched, real side = R1
489
+ (the scorer's space). oos = (R2 counts, R2 donor index, set name): families 1-2 again with R2 as the real side."""
490
+ S_ = v["donors"].size
491
+ E = pair_embeddings(v, v["R1"], v["r1_d"], Q, q_d, zr_raw=v["z1"])
492
+ rows, per, chk = [], {"donor": v["donors"], "set": name}, {}
493
+ for mode, (zr, zg) in E.items():
494
+ t0 = time.monotonic()
495
+ m = {"set": name, "real_side": "R1", "mode": mode, "n_real": int(len(zr)), "n_gen": int(len(zg))}
496
+ for k in KS:
497
+ # k = 10 raw: the view's own radii (score_ft.arm_metrics); every other k / mode: radii recomputed on zr
498
+ res = F.SB.precision_coverage(zr, v["radius"], zg) if (k == F.K_NN and mode == "raw") else pc_at_k(zr, zg, k)
499
+ m[f"precision_k{k}"], m[f"coverage_k{k}"], m[f"density_k{k}"] = res["precision"], res["coverage"], res["density"]
500
+ m[f"expected_coverage_identical_k{k}"] = expected_coverage(len(zr), len(zg), k)
501
+ pp, pc = per_donor_pc(v["r1_d"], q_d, S_, res)
502
+ per[f"precision_k{k}_{mode}"], per[f"coverage_k{k}_{mode}"] = pp, pc
503
+ m.update(two_sample_block(zr, zg, sigma_m, n_jobs=n_jobs))
504
+ m["seconds"] = round(time.monotonic() - t0, 1)
505
+ rows.append(m)
506
+ log(f" {name} [R1 {mode}] P/C k10 {m['precision_k10']:.4f}/{m['coverage_k10']:.4f} k5 {m['precision_k5']:.4f}/"
507
+ f"{m['coverage_k5']:.4f} k3 {m['precision_k3']:.4f}/{m['coverage_k3']:.4f} | AUC knn {m['c2st_knn_auc']:.3f} "
508
+ f"rf {m['c2st_rf_auc']:.3f} | 1-NN {m['nn1_acc']:.3f} | MMD2 {m['mmd2_bw1']:.4f} ({m['seconds']} s)")
509
+ if oos is not None:
510
+ R2, r2_d, oname = oos
511
+ for mode, (zr, zg) in pair_embeddings(v, R2, r2_d, Q, q_d).items():
512
+ t0 = time.monotonic()
513
+ m = {"set": oname, "real_side": "R2", "mode": mode, "n_real": int(len(zr)), "n_gen": int(len(zg))}
514
+ m.update(two_sample_block(zr, zg, sigma_m, n_jobs=n_jobs))
515
+ m["seconds"] = round(time.monotonic() - t0, 1)
516
+ rows.append(m)
517
+ log(f" {oname} [R2 {mode}] AUC knn {m['c2st_knn_auc']:.3f} rf {m['c2st_rf_auc']:.3f} | 1-NN {m['nn1_acc']:.3f} "
518
+ f"| MMD2 {m['mmd2_bw1']:.4f} ({m['seconds']} s)")
519
+ if expect is not None: # reproduction of the scorer's k = 10 values
520
+ for mode, key in (("raw", ""), ("dm", "_depth_matched")):
521
+ mm = next(r for r in rows if r["mode"] == mode)
522
+ for q in ("precision", "coverage"):
523
+ chk[f"{q}{key}"] = {"ours": mm[f"{q}_k10"], "scorer": expect[f"{q}{key}"],
524
+ "abs_diff": abs(mm[f"{q}_k10"] - expect[f"{q}{key}"])}
525
+ if "per_donor" in expect:
526
+ d = np.abs(per[f"{q}_k10_{mode}"] - expect["per_donor"][f"{q}{key}"])
527
+ chk[f"{q}{key}_per_donor_max_abs_diff"] = float(d.max())
528
+ return rows, pd.DataFrame(per), chk
529
+
530
+
531
+ def run_unit(design: str, ds: str, draw: int | None, a) -> None:
532
+ t_unit = time.monotonic()
533
+ spec = F.DATASETS[ds]
534
+ out = unit_dir(design, ds, draw)
535
+ if (out / "manifest.json").is_file() and not a.force:
536
+ log(f"{out} done already")
537
+ return
538
+ out.mkdir(parents=True, exist_ok=True)
539
+ calls = unit_calls(design, ds, draw)
540
+ summ = {}
541
+ for cdir, arms in calls:
542
+ s = json.loads((cdir / "summary.json").read_text())
543
+ miss = [x for x in arms if x not in s["arms"]]
544
+ if miss:
545
+ raise SystemExit(f"{cdir}: arms {miss} not scored there")
546
+ summ[cdir] = s
547
+ first = summ[calls[0][0]]
548
+ donors = [str(x) for x in first["donors"]]
549
+ for cdir, s in summ.items():
550
+ if [str(x) for x in s["donors"]] != donors:
551
+ raise SystemExit(f"{cdir}: scored donors differ from {calls[0][0]}")
552
+ if s["reference"]["reference_sha256"] != first["reference"]["reference_sha256"]:
553
+ raise SystemExit(f"{cdir}: reference sha differs")
554
+ cache = F.CACHE_ROOT / ds
555
+ ref, man = F.load_reference(cache)
556
+ if man["reference_sha256"] != first["reference"]["reference_sha256"]:
557
+ raise SystemExit(f"{cache}: reference sha differs from the scored one")
558
+ log(f"{ds} {design} {'' if draw is None else f'draw{draw} '}: {len(donors)} scored samples; fitting the scorer's view")
559
+ v = S.make_view(ref, donors)
560
+ repro = {"unit": str(out), "pca": {"ours": v["pca"], "scorer": first["reference"]["pca"]},
561
+ "r2_control": {"ours": v["r2_control"], "scorer": first["reference"]["r2_control"]}, "arms": {}}
562
+ S_ = v["donors"].size
563
+ sigma_m = median_bandwidth(v["z1"])
564
+ log(f"bandwidth m (median pairwise distance of R1, PCA-50) = {sigma_m:.4f}")
565
+ rows, per_frames, en_rows, en_ps = [], [], [], []
566
+ fetched: list[Path] = []
567
+ fetch_root = Path(a.fetch_dir)
568
+
569
+ # ---------------- E_N inputs shared by all arms
570
+ rng_c = F.donor_rng
571
+ R1L = log1p_cp10k_sparse(v["R1"])
572
+ gram_r1 = Gram(R1L.shape[1]).add(R1L)
573
+ r1_split = [np.flatnonzero(v["r1_d"] == s) for s in range(S_)]
574
+ obs, obs_info = observed_cells(spec, ref, man, v["donors"], a.obs_cache)
575
+ # out-of-sample real sets from the scorer's donor-keyed permutation (F.reference_split): R1 = perm[:n],
576
+ # R2 = perm[n:2n] (both checked equal to reference.npz), R3 = perm[2n:3n] (fewer cells when the sample is small);
577
+ # the R2-vs-R3 control uses R2' = perm[n:n+m], m = min(n, |R3|), so both sides have the same size per sample.
578
+ r3_blocks, r2b_blocks, r3_d, r2b_d, oos_info = [], [], [], [], {"n_r3": [], "short_samples": []}
579
+ for k in range(S_):
580
+ nk, d = obs[k].shape[0], str(v["donors"][k])
581
+ a1, a2 = F.reference_split(nk, d)
582
+ if (obs[k][a1] != v["R1"][np.flatnonzero(v["r1_d"] == k)]).nnz or \
583
+ (obs[k][a2] != v["R2"][np.flatnonzero(v["r2_d"] == k)]).nnz:
584
+ raise SystemExit(f"{d}: R1 / R2 rebuilt from the observed cells differ from reference.npz")
585
+ perm = F.donor_rng(F.SUB_SEED, d).permutation(nk)
586
+ n = a1.size
587
+ r3 = np.sort(perm[2 * n:3 * n])
588
+ m_ = r3.size
589
+ if m_ < n:
590
+ oos_info["short_samples"].append({"sample": d, "n": int(n), "n_r3": int(m_)})
591
+ r3_blocks.append(obs[k][r3])
592
+ r2b_blocks.append(obs[k][np.sort(perm[n:n + m_])])
593
+ r3_d.append(np.full(m_, k))
594
+ r2b_d.append(np.full(m_, k))
595
+ oos_info["n_r3"].append(int(m_))
596
+ R3, R2b = sp.vstack(r3_blocks, format="csr"), sp.vstack(r2b_blocks, format="csr")
597
+ r3_d, r2b_d = np.concatenate(r3_d), np.concatenate(r2b_d)
598
+ log(f"observed cells: {obs_info['n_cells_total']} in {S_} samples; R1/R2 rebuilt = reference.npz; R3 {R3.shape[0]} "
599
+ f"cells ({len(oos_info['short_samples'])} samples with fewer than n)")
600
+ oos_r2 = (v["R2"], v["r2_d"])
601
+ if not a.no_en_all:
602
+ obsL = [log1p_cp10k_sparse(o) for o in obs]
603
+ gram_obs = Gram(R1L.shape[1])
604
+ for L in obsL:
605
+ gram_obs.add(L)
606
+ del obs
607
+
608
+ def en_unit(set_name: str, cellset: str, gts_L: list, semis_L: list, gram_real: Gram, n_rep_rows: int | None):
609
+ t0 = time.monotonic()
610
+ g = Gram(gts_L[0].shape[1])
611
+ for L in semis_L:
612
+ g.add(L)
613
+ mu, comps = (gram_real + g).pca(EN_PCS)
614
+ gts = [embed(L, mu, comps) for L in gts_L]
615
+ semis = [embed(L, mu, comps) for L in semis_L]
616
+ Z_all = np.vstack(gts + semis)
617
+ rng = np.random.default_rng([SEED, 17 if cellset == "pc" else 29])
618
+ res = en_from_embeddings(gts, semis, rng, Z_all=Z_all,
619
+ lb_max_queries=None if cellset == "pc" else EN_LB_MAX_QUERIES)
620
+ n_test = len(gts)
621
+ for d in ("sq", "l2"):
622
+ r = res[d]
623
+ en_rows.append({"set": set_name, "cellset": cellset, "distance": d, "n_samples": n_test,
624
+ "n_cells_real": int(sum(len(x) for x in gts)), "n_cells_gen": int(sum(len(x) for x in semis)),
625
+ "n_pcs": int(comps.shape[0]), "lb": r["lb"], "ub": r["ub"], "dif_mean": r["dif_mean"],
626
+ "en": r["en"], "lb_exact": res["lb"]["exact"], "lb_queries": res["lb"]["n_queries"],
627
+ "n_representative_rows": n_rep_rows,
628
+ "en_reps_at_lb": (r["en"] * n_test / (n_test + n_rep_rows)) if n_rep_rows else None,
629
+ "seconds": round(time.monotonic() - t0, 1)})
630
+ en_ps.append(pd.DataFrame({"set": set_name, "cellset": cellset, "distance": d, "donor": v["donors"],
631
+ "n_real": [len(x) for x in gts], "n_gen": [len(x) for x in semis],
632
+ "partner": v["donors"][res["partner"]], "dif": r["dif_i"], "en_i": r["en_i"]}))
633
+ log(f" {set_name} E_N[{cellset}] sq {res['sq']['en']:.4f} (LB {res['sq']['lb']:.3f} UB {res['sq']['ub']:.3f} "
634
+ f"Dif {res['sq']['dif_mean']:.3f}) l2 {res['l2']['en']:.4f} ({round(time.monotonic() - t0, 1)} s)")
635
+
636
+ # ---------------- control: R1 vs R2 (the scorer's own)
637
+ expect_r2 = {"precision": first["reference"]["r2_control"]["precision"],
638
+ "coverage": first["reference"]["r2_control"]["coverage"],
639
+ "precision_depth_matched": first["reference"]["r2_control"]["depth_matched"]["precision"],
640
+ "coverage_depth_matched": first["reference"]["r2_control"]["depth_matched"]["coverage"]}
641
+ r, p, chk = score_set(CONTROL, v, v["R2"], v["r2_d"], sigma_m, a.threads, expect_r2, oos=None)
642
+ rows += r
643
+ # out-of-sample control: R2' (real side) vs R3, families 1-2 only
644
+ for mode, (zr, zg) in pair_embeddings(v, R2b, r2b_d, R3, r3_d).items():
645
+ t0 = time.monotonic()
646
+ m = {"set": CONTROL_OOS, "real_side": "R2", "mode": mode, "n_real": int(len(zr)), "n_gen": int(len(zg))}
647
+ m.update(two_sample_block(zr, zg, sigma_m, n_jobs=a.threads))
648
+ m["seconds"] = round(time.monotonic() - t0, 1)
649
+ rows.append(m)
650
+ log(f" {CONTROL_OOS} [R2 {mode}] AUC knn {m['c2st_knn_auc']:.3f} rf {m['c2st_rf_auc']:.3f} | 1-NN "
651
+ f"{m['nn1_acc']:.3f} | MMD2 {m['mmd2_bw1']:.4f} ({m['seconds']} s)")
652
+ per_frames.append(p)
653
+ repro["arms"][CONTROL] = chk
654
+ R2L = log1p_cp10k_sparse(v["R2"])
655
+ en_unit(CONTROL, "pc", [R1L[i] for i in r1_split], [R2L[np.flatnonzero(v["r2_d"] == s)] for s in range(S_)],
656
+ gram_r1, None)
657
+ if not a.no_en_all:
658
+ A_, B_ = [], []
659
+ for s in range(S_):
660
+ perm = rng_c(SEED, v["donors"][s]).permutation(obsL[s].shape[0])
661
+ h = obsL[s].shape[0] // 2
662
+ A_.append(obsL[s][np.sort(perm[:h])])
663
+ B_.append(obsL[s][np.sort(perm[h:])])
664
+ # the PCA basis is the one of all observed cells (A and B together): gram_real = A-part, semis add the B-part
665
+ gA = Gram(R1L.shape[1])
666
+ for L in A_:
667
+ gA.add(L)
668
+ en_unit(CONTROL, "all", A_, B_, gA, None)
669
+ del A_, B_
670
+
671
+ # ---------------- arms
672
+ pcache = a.pcache # Poisson read-outs (scoring genes) by NPZ sha; zs_*_all are reused by later draws
673
+ n_rep_rows = None
674
+ if design == "fewshot":
675
+ dj = json.loads((TASK / "data" / ds / "fewshot_n5" / "DRAWS.json").read_text())["draw"][str(draw)]
676
+ n_rep_rows = int(dj["n_train_rows"])
677
+ panel_ids = ref["panel_ids"].astype(str)
678
+ for cdir, arms in calls:
679
+ s = summ[cdir]
680
+ per_csv = pd.read_csv(cdir / "per_donor.csv")
681
+ for name in arms:
682
+ t0 = time.monotonic()
683
+ pa = s["per_arm"][name]
684
+ path = resolve_npz(Path(pa["npz"]), pa["npz_sha256"], fetch_root, fetched)
685
+ arm = S.open_arm(name, path, panel_ids, allow_no_receipt=False)
686
+ if arm["sha256"] != pa["npz_sha256"] or not arm["receipt_verified"]:
687
+ raise SystemExit(f"{name}: NPZ sha / receipt check failed for {path}")
688
+ npos = {n: i for i, n in enumerate(arm["sample_ids"])}
689
+ rws = [np.flatnonzero(arm["bulk_index"] == npos[x]) for x in v["donors"]]
690
+ sel = np.concatenate(rws)
691
+ gen_d = np.repeat(np.arange(S_), [x.size for x in rws])
692
+ if arm["sha256"] not in pcache:
693
+ rates = np.ascontiguousarray(arm["d"]["generated_counts"], dtype=np.float32)
694
+ full = F.PR.poisson_integerise(rates, seed=F.POISSON_SEED, chunk_rows=4096)
695
+ del rates
696
+ pcache[arm["sha256"]] = full[:, ref["score_idx"]].tocsr()
697
+ del full
698
+ arm["d"].close()
699
+ Xg = pcache[arm["sha256"]][sel].tocsr()
700
+ sub = np.concatenate([np.flatnonzero(gen_d == k)[F.generated_subsample(int((gen_d == k).sum()),
701
+ int(v["n_ref"][k]), v["donors"][k])]
702
+ for k in range(S_)])
703
+ Q, q_d = Xg[sub].tocsr(), gen_d[sub]
704
+ gc = pd.read_parquet(cdir / "arms" / name / "generated_cells.parquet", columns=["npz_row", "in_pc_subsample"])
705
+ same_rows = bool(np.array_equal(gc.npz_row.to_numpy(), sel)
706
+ and np.array_equal(np.flatnonzero(gc.in_pc_subsample.to_numpy()), np.sort(sub)))
707
+ if not same_rows:
708
+ raise SystemExit(f"{name}: scored rows / P/C subsample differ from {cdir}/arms/{name}/generated_cells.parquet")
709
+ pdn = per_csv[per_csv.arm == name].set_index("donor").loc[v["donors"]]
710
+ h = s["headline"][name]
711
+ expect = {"precision": h["precision"], "coverage": h["coverage"], "precision_depth_matched": h["precision_dm"],
712
+ "coverage_depth_matched": h["coverage_dm"],
713
+ "per_donor": {k: pdn[k].to_numpy() for k in ("precision", "coverage", "precision_depth_matched",
714
+ "coverage_depth_matched")}}
715
+ log(f"{name}: {path.name} sha {arm['sha256'][:12]} (receipt verified), {sel.size} scored cells, "
716
+ f"{sub.size} in the P/C subsample (same rows as the scorer)")
717
+ r, p, chk = score_set(name, v, Q, q_d, sigma_m, a.threads, expect, oos=(oos_r2[0], oos_r2[1], name))
718
+ chk["rows_and_subsample_equal_scorer"] = same_rows
719
+ chk["npz"] = {"path": str(path), "scored_path": pa["npz"], "sha256": arm["sha256"]}
720
+ rows += r
721
+ per_frames.append(p)
722
+ repro["arms"][name] = chk
723
+ QL = log1p_cp10k_sparse(Q)
724
+ en_unit(name, "pc", [R1L[i] for i in r1_split], [QL[np.flatnonzero(q_d == k)] for k in range(S_)], gram_r1,
725
+ n_rep_rows if name == "scsemi5" else None)
726
+ if not a.no_en_all:
727
+ XgL = log1p_cp10k_sparse(Xg)
728
+ en_unit(name, "all", obsL, [XgL[np.flatnonzero(gen_d == k)] for k in range(S_)], gram_obs,
729
+ n_rep_rows if name == "scsemi5" else None)
730
+ del XgL
731
+ log(f"{name} done in {time.monotonic() - t0:.0f} s")
732
+ if not (design == "fewshot" and name in ("zs_raw", "zs_pseudo")):
733
+ pcache.pop(arm["sha256"], None) # not reused by another unit
734
+ # ---------------- write
735
+ meta = {"dataset": ds, "design": design, "unit": "pooled" if draw is None else f"draw{draw}"}
736
+ met = pd.DataFrame(rows)
737
+ for k, x in reversed(list(meta.items())):
738
+ met.insert(0, k, x)
739
+ met.insert(3, "label", met["set"].map(ARM_LABEL))
740
+ met.to_csv(out / "metrics.csv", index=False)
741
+ perd = pd.concat(per_frames, ignore_index=True)
742
+ for k, x in reversed(list(meta.items())):
743
+ perd.insert(0, k, x)
744
+ perd.to_csv(out / "per_donor.csv", index=False)
745
+ en = pd.DataFrame(en_rows)
746
+ for k, x in reversed(list(meta.items())):
747
+ en.insert(0, k, x)
748
+ en.to_csv(out / "en.csv", index=False)
749
+ ep = pd.concat(en_ps, ignore_index=True)
750
+ for k, x in reversed(list(meta.items())):
751
+ ep.insert(0, k, x)
752
+ ep.to_csv(out / "en_per_sample.csv", index=False)
753
+ worst = max([c.get("abs_diff", 0.0) for arm in repro["arms"].values() for c in arm.values() if isinstance(c, dict)]
754
+ + [0.0])
755
+ repro["max_abs_diff_k10_pooled"] = worst
756
+ repro["oos_r3"] = oos_info
757
+ repro["pca_equal"] = repro["pca"]["ours"] == repro["pca"]["scorer"]
758
+ (out / "repro.json").write_text(json.dumps(repro, indent=1, default=float) + "\n")
759
+ code = {str(p): sha256(p) for p in (Path(__file__).resolve(), TOOLS / "ft_common.py", TOOLS / "score_ft.py", F.SB_PATH)}
760
+ manifest = {"schema": "paired_ft_extra_metrics.v1", **meta, "written_utc": F.now(), "command": sys.argv,
761
+ "threads": a.threads, "donors": list(map(str, v["donors"])), "n_samples": int(S_),
762
+ "calls": {str(c): {"arms": list(arms), "summary_sha256": sha256(c / "summary.json")} for c, arms in calls},
763
+ "reference_sha256": man["reference_sha256"], "bandwidth_m": sigma_m,
764
+ "params": {"seed": SEED, "ks": KS, "knn_c2st_k": KNN_C2ST_K, "rf_trees": RF_TREES, "cv_folds": CV_FOLDS,
765
+ "bw_multiples": BW_MULTIPLES, "bw_max_cells": BW_MAX_CELLS, "en_pcs": EN_PCS,
766
+ "en_lb_max_queries_all_cells": EN_LB_MAX_QUERIES, "en_all_cells": not a.no_en_all},
767
+ "n_representative_rows": n_rep_rows, "fetched_from_server2": [str(f) for f in fetched],
768
+ "code_sha256": code, "seconds": round(time.monotonic() - t_unit, 1),
769
+ "max_abs_diff_k10_pooled": worst}
770
+ (out / "manifest.json").write_text(json.dumps(manifest, indent=1, default=float) + "\n")
771
+ log(f"unit {meta['unit']} of {ds} written to {out} in {manifest['seconds']} s (k=10 max |diff| vs scorer {worst:.2e})")
772
+ for f in fetched:
773
+ if f.name.startswith("zs__raw_all") or f.name.startswith("zs__pseudo_all"):
774
+ continue # shared by the draws of the cohort; removed by main after the last draw
775
+ f.unlink(missing_ok=True)
776
+ f.with_suffix(".log").unlink(missing_ok=True)
777
+ log(f"removed fetched copy {f}")
778
+
779
+
780
+ # =========================================================================== collect
781
+ COHORT = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis", "imperial_eskd": "Imperial", "giroux2022": "Giroux",
782
+ "ji2025_chili": "Ji (whole blood)"}
783
+ # headline columns: (column in metrics.csv / en.csv, short name, better direction: +1 higher, -1 lower, 0 closer to 0.5)
784
+ HEAD = [("c2st_knn_auc", "AUC kNN", 0), ("c2st_rf_auc", "AUC RF", 0), ("nn1_acc", "1-NN acc", 0),
785
+ ("mmd2_bw1", "MMD² (σ=m)", -1), ("mmd2_sum", "MMD² (sum)", -1), ("en_all_sq", "E_N all", -1),
786
+ ("en_pc_sq", "E_N P/C cells", -1),
787
+ ("precision_k3", "P k3", 1), ("coverage_k3", "C k3", 1), ("precision_k5", "P k5", 1), ("coverage_k5", "C k5", 1),
788
+ ("precision_k10", "P k10", 1), ("coverage_k10", "C k10", 1)]
789
+ LORA = {"fewshot": "lora5", "pooled": "real_lora__raw"}
790
+ COMPARE = {"fewshot": ("scsemi5", "zs_raw", "zs_cal"), "pooled": ("zs__raw", "zs__cal", "pseudo_full__cal")}
791
+ ORDER = {"fewshot": (CONTROL, CONTROL_OOS, "zs_raw", "zs_cal", "scsemi5", "lora5", "zs_pseudo"),
792
+ "pooled": (CONTROL, CONTROL_OOS, "zs__raw", "zs__cal", "pseudo_full__cal", "real_lora__raw", "zs__pseudo")}
793
+ SIDES = (("R1", "raw", "scorer space: real side = R1 (the PCA-50 fit cells), no depth matching = the deck's precision/coverage"),
794
+ ("R1", "dm", "scorer space: real side = R1, depth matched"),
795
+ ("R2", "raw", "out-of-sample real side = R2 (same PCA-50, generated cells and subsample), no depth matching"),
796
+ ("R2", "dm", "out-of-sample real side = R2, depth matched"))
797
+
798
+
799
+ def _wide(design: str) -> pd.DataFrame:
800
+ """One row per unit x set x mode: metrics.csv joined with the E_N headline (squared L2, both cell sets)."""
801
+ glob = "*/fewshot_n5/draw*" if design == "fewshot" else "*/pooled"
802
+ mets, ens = [], []
803
+ for d in sorted(OUT_ROOT.glob(glob)):
804
+ if (d / "manifest.json").is_file():
805
+ mets.append(pd.read_csv(d / "metrics.csv"))
806
+ ens.append(pd.read_csv(d / "en.csv"))
807
+ if not mets:
808
+ return pd.DataFrame()
809
+ met, en = pd.concat(mets, ignore_index=True), pd.concat(ens, ignore_index=True)
810
+ key = ["dataset", "design", "unit", "set"]
811
+ met = met[~((met.real_side == "R2") & (met.set == CONTROL))]
812
+ e = en.pivot_table(index=key, columns=["cellset", "distance"], values="en", aggfunc="first")
813
+ e.columns = [f"en_{c}_{d}" for c, d in e.columns]
814
+ r = en[en.cellset == "all"].pivot_table(index=key, columns="distance", values="en_reps_at_lb", aggfunc="first")
815
+ r.columns = [f"en_all_{d}_reps_at_lb" for d in r.columns]
816
+ for q in ("dif_mean", "lb", "ub"):
817
+ x = en[en.distance == "sq"].pivot_table(index=key, columns="cellset", values=q, aggfunc="first")
818
+ x.columns = [f"{q}_{c}_sq" for c in x.columns]
819
+ r = r.join(x, how="outer") if len(r) else x
820
+ out = met.merge(e.reset_index(), on=key, how="left").merge(r.reset_index(), on=key, how="left")
821
+ out.loc[out.real_side == "R2", [c for c in out.columns if c.startswith("en_")]] = np.nan # E_N: one value per set
822
+ return out
823
+
824
+
825
+ def _fmt(x, sd=None, nd=3):
826
+ if x is None or (isinstance(x, float) and np.isnan(x)):
827
+ return "—"
828
+ s = f"{x:.{nd}f}" if abs(x) >= 10 ** -nd or x == 0 else f"{x:.1e}"
829
+ return s + (f" ± {sd:.{nd}f}" if sd is not None and not np.isnan(sd) else "")
830
+
831
+
832
+ def _better(a: float, b: float, sign: int) -> bool:
833
+ return (abs(a - 0.5) < abs(b - 0.5)) if sign == 0 else (a > b if sign > 0 else a < b)
834
+
835
+
836
+ def collect() -> None:
837
+ """Concatenate every unit's CSVs into scores_extra/{fewshot,pooled}_*.csv and write TABLES.md (means over the
838
+ 5 draws for the few-pair design, single pooled calls for the 5-fold design; LoRA-vs-arm win counts per draw)."""
839
+ from scipy.stats import kendalltau
840
+ lines = ["# Extra realism / diversity metrics: tables", "",
841
+ f"Written by `tools/extra_metrics.py --collect` ({F.now()}). Definitions: `README.md`.", ""]
842
+ for design in ("fewshot", "pooled"):
843
+ glob = "*/fewshot_n5/draw*" if design == "fewshot" else "*/pooled"
844
+ for name in ("metrics", "per_donor", "en", "en_per_sample"):
845
+ parts = [pd.read_csv(d / f"{name}.csv") for d in sorted(OUT_ROOT.glob(glob)) if (d / "manifest.json").is_file()]
846
+ if parts:
847
+ pd.concat(parts, ignore_index=True).to_csv(OUT_ROOT / f"{design}_{name}.csv", index=False)
848
+ rep = [json.loads((d / "repro.json").read_text()) | {"unit_dir": str(d)} for d in sorted(OUT_ROOT.glob(glob))
849
+ if (d / "manifest.json").is_file()]
850
+ if rep:
851
+ rows = []
852
+ for r in rep:
853
+ for arm, c in r["arms"].items():
854
+ rows.append({"unit_dir": r["unit_dir"], "set": arm,
855
+ **{k: (x["abs_diff"] if isinstance(x, dict) and "abs_diff" in x else x)
856
+ for k, x in c.items() if k != "npz"}})
857
+ pd.DataFrame(rows).to_csv(OUT_ROOT / f"{design}_reproduction_check.csv", index=False)
858
+ w = _wide(design)
859
+ if w.empty:
860
+ continue
861
+ w.to_csv(OUT_ROOT / f"{design}_wide.csv", index=False)
862
+ title = "(a) 5-donor few-pair design (mean ± SD over 5 draws)" if design == "fewshot" else \
863
+ "(b) 5-fold pooled design (one call over all pairs)"
864
+ for side, mode, desc in SIDES:
865
+ sub = w[(w["mode"] == mode) & (w["real_side"] == side)]
866
+ lines += [f"## {title}; {desc}", ""]
867
+ cols = [c for c in HEAD if c[0] in sub.columns and sub[c[0]].notna().any()
868
+ and not (mode == "dm" and c[0].startswith("en_"))] # E_N has no depth-matched version
869
+ lines.append("| cohort | arm | n units | " + " | ".join(c[1] for c in cols) + " |")
870
+ lines.append("|---|---|---:|" + "---:|" * len(cols))
871
+ for ds in DATASETS:
872
+ for arm in ORDER[design]:
873
+ x = sub[(sub.dataset == ds) & (sub.set == arm)]
874
+ if x.empty:
875
+ continue
876
+ vals = []
877
+ for c, _, _ in cols:
878
+ col = x[c].astype(float)
879
+ vals.append(_fmt(col.mean(), col.std(ddof=1) if design == "fewshot" and len(col) > 1 else None,
880
+ 4 if c.startswith("mmd") else 3))
881
+ lines.append(f"| {COHORT[ds]} | {ARM_LABEL.get(arm, arm)} | {len(x)} | " + " | ".join(vals) + " |")
882
+ lines.append("")
883
+ for side in ("R1", "R2"):
884
+ _wins_and_tau(lines, w, design, title, side, kendalltau)
885
+ (OUT_ROOT / "TABLES.md").write_text("\n".join(lines) + "\n")
886
+ log(f"collected -> {OUT_ROOT}/TABLES.md")
887
+
888
+
889
+ def _wins_and_tau(lines: list, w: pd.DataFrame, design: str, title: str, side: str, kendalltau) -> None:
890
+ # LoRA vs every comparator, per metric (no depth matching)
891
+ sub = w[(w["mode"] == "raw") & (w["real_side"] == side)]
892
+ lines += [f"### {title}: does LoRA beat each comparator? (real side {side}, no depth matching; "
893
+ + ("draws where LoRA is better / draws compared" if design == "fewshot" else "pooled call: ✓ / ✗")
894
+ + "; AUC and 1-NN: closer to 0.5 is better)", ""]
895
+ cols = [c for c in HEAD if c[0] in sub.columns and sub[c[0]].notna().any()]
896
+ lines.append("| cohort | LoRA vs | " + " | ".join(c[1] for c in cols) + " |")
897
+ lines.append("|---|---|" + "---:|" * len(cols))
898
+ excepts = []
899
+ for ds in DATASETS:
900
+ L = sub[(sub.dataset == ds) & (sub.set == LORA[design])].set_index("unit")
901
+ if L.empty:
902
+ continue
903
+ for comp in COMPARE[design]:
904
+ Cm = sub[(sub.dataset == ds) & (sub.set == comp)].set_index("unit")
905
+ units = sorted(set(L.index) & set(Cm.index))
906
+ if not units:
907
+ continue
908
+ cells = []
909
+ for c, short, sign in cols:
910
+ wins = sum(_better(float(L.at[u, c]), float(Cm.at[u, c]), sign) for u in units)
911
+ cells.append(f"{wins}/{len(units)}" if design == "fewshot" else ("✓" if wins else "✗"))
912
+ if wins < len(units):
913
+ excepts.append(f"{COHORT[ds]}: LoRA not better than {ARM_LABEL[comp]} on {short} in "
914
+ f"{len(units) - wins}/{len(units)} unit(s)")
915
+ lines.append(f"| {COHORT[ds]} | {ARM_LABEL[comp]} | " + " | ".join(cells) + " |")
916
+ lines += ["", "Exceptions (LoRA not better):", ""] + [f"- {e}" for e in excepts] + [""]
917
+ # agreement of each metric's arm ranking with coverage (k = 10) and precision (k = 10), per cohort (means)
918
+ lines += [f"### {title}: Kendall τ between each metric's arm ranking and the coverage / precision (k = 10) "
919
+ "ranking (arms only, control excluded; mean over units per cohort; AUC / 1-NN ranked by |x - 0.5|)", ""]
920
+ lines.append("| cohort | vs | " + " | ".join(c[1] for c in cols) + " |")
921
+ lines.append("|---|---|" + "---:|" * len(cols))
922
+ for ds in DATASETS:
923
+ x = sub[(sub.dataset == ds) & ~sub.set.isin([CONTROL, CONTROL_OOS])].groupby("set")[[c[0] for c in cols]].mean()
924
+ if side == "R2": # P/C exists only on the R1 side: take the scorer's k = 10 values from the R1 rows
925
+ pr = w[(w.dataset == ds) & (w["mode"] == "raw") & (w.real_side == "R1")].groupby("set")[
926
+ ["coverage_k10", "precision_k10"]].mean()
927
+ x = x.drop(columns=[c for c in ("coverage_k10", "precision_k10") if c in x.columns]).join(pr)
928
+ if len(x) < 3:
929
+ continue
930
+
931
+ def score(c, sign):
932
+ return -(x[c] - 0.5).abs() if sign == 0 else x[c] * sign
933
+ for ref_c in ("coverage_k10", "precision_k10"):
934
+ taus = [kendalltau(score(c, s), x[ref_c]).statistic for c, _, s in cols]
935
+ lines.append(f"| {COHORT[ds]} | {ref_c.split('_')[0]} | " + " | ".join(_fmt(t, nd=2) for t in taus) + " |")
936
+ lines.append("")
937
+
938
+
939
+ def parse(argv=None):
940
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
941
+ p.add_argument("--design", choices=["fewshot", "pooled"])
942
+ p.add_argument("--dataset", choices=DATASETS)
943
+ p.add_argument("--draws", default="0,1,2,3,4")
944
+ p.add_argument("--threads", type=int, default=7)
945
+ p.add_argument("--fetch-dir", default=None, help="where server_2 NPZ copies go (default: scratch under scores_extra)")
946
+ p.add_argument("--no-en-all", action="store_true", help="skip the all-cells E_N (P/C-cell E_N is always computed)")
947
+ p.add_argument("--force", action="store_true", help="recompute units that already have a manifest")
948
+ p.add_argument("--collect", action="store_true")
949
+ return p.parse_args(argv)
950
+
951
+
952
+ def main(argv=None) -> int:
953
+ a = parse(argv)
954
+ if a.collect:
955
+ collect()
956
+ return 0
957
+ if not (1 <= a.threads <= 8):
958
+ raise SystemExit("--threads must be 1..8")
959
+ try:
960
+ from threadpoolctl import threadpool_limits
961
+ threadpool_limits(a.threads)
962
+ except ImportError:
963
+ pass
964
+ if a.design is None or a.dataset is None:
965
+ raise SystemExit("--design and --dataset are required (or --collect)")
966
+ a.fetch_dir = a.fetch_dir or str(OUT_ROOT / "_fetch_tmp")
967
+ Path(a.fetch_dir).mkdir(parents=True, exist_ok=True)
968
+ a.pcache, a.obs_cache = {}, {}
969
+ if a.design == "pooled":
970
+ run_unit("pooled", a.dataset, None, a)
971
+ else:
972
+ for j in [int(x) for x in a.draws.split(",") if x.strip()]:
973
+ run_unit("fewshot", a.dataset, j, a)
974
+ shared = Path(a.fetch_dir) / "generated" / a.dataset / "fewshot_n5"
975
+ for f in list(shared.glob("zs__*_all.npz")) if shared.is_dir() else []:
976
+ f.unlink(missing_ok=True)
977
+ f.with_suffix(".log").unlink(missing_ok=True)
978
+ log(f"removed fetched copy {f}")
979
+ return 0
980
+
981
+
982
+ if __name__ == "__main__":
983
+ raise SystemExit(main())
paper-releases/pbisc-diffusion/updates/20261001T200638Z-extra-realism-metrics/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scores_extra/_code/extra_metrics_v3_4e69c029476c.py ADDED
@@ -0,0 +1,997 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reviewer-expected realism / diversity metrics for the paired fine-tuning benchmark (CPU only; never imports torch).
3
+
4
+ Added 2026-10-01. Every scored unit (one few-pair draw, or one pooled 5-fold call) is re-read exactly as tools/score_ft.py
5
+ scored it, and four metric families are added next to the existing precision/coverage:
6
+
7
+ 1. classifier two-sample tests (real vs generated): kNN (k = 5) and random-forest 5-fold cross-validated ROC AUC
8
+ (scGAN / scDiffusion style) and the leave-one-out 1-NN accuracy (scLDM; Lopez-Paz & Oquab 2017);
9
+ 2. MMD^2 (unbiased, Gaussian RBF; median-heuristic bandwidth and the fixed multiples 0.5 / 1 / 2, plus their sum);
10
+ 3. scSemiProfiler's normalized error E_N (Wang et al. 2024, Methods eq. 17-18; get_error in vendor utils.py);
11
+ 4. precision / coverage at k = 3 and 5 next to k = 10 (k = 10 re-computed first and checked against score_ft.py).
12
+
13
+ Families 1, 2 and 4 use exactly the scorer's embedding and cells: score_ft.make_view (PCA-50 fitted on the scored
14
+ donors' R1 cells), the scorer's whole-NPZ Poisson read-out (seed 20260916), its donor-keyed generated subsample
15
+ (F.generated_subsample) and its pairwise depth matching (F.SB.depth_match with a fresh rng(20260929)). They are
16
+ reported both without ("raw", the deck's headline precision/coverage) and with depth matching ("dm"). The
17
+ real-vs-real control is the scorer's own: held-out real cells R2 of the same donors, same n per donor.
18
+
19
+ E_N follows scSemiProfiler's own space instead: per arm, log1p CP10K -> PCA-100 fitted on real and generated cells
20
+ together; Dif_sc = symmetric 1-NN distance (eq. 17); lower bound = random half split of the whole PCA matrix; upper
21
+ bound = random pairs of different real samples. Distances: squared L2 as their code computes them (faiss
22
+ IndexFlatL2), and plain L2 as the paper's text writes them. Two cell sets:
23
+ "all": every observed QC cell of each scored sample vs all of its generated cells (their setting);
24
+ control = a random within-sample half split of the observed cells (half A as 'real', half B as 'generated').
25
+ "pc": the precision/coverage cells (R1 vs the generated subsample, n per donor equal); control = R1 vs R2.
26
+ Representatives: scSemiProfiler sets a representative's error to the lower bound. Our scored samples never include a
27
+ representative (the 5 training donors of a few-pair draw are not scored in any arm), so no sample is set to LB; for
28
+ scsemi5 the table also gives the value that convention would produce (E_N x n_test / (n_test + n_representative_rows)).
29
+
30
+ usage (CPU; run through tools/run_extra_unit.sh):
31
+ extra_metrics.py --design fewshot --dataset giroux2022 --draws 0,1,2,3,4 [--threads 7] [--no-en-all]
32
+ extra_metrics.py --design pooled --dataset giroux2022
33
+ extra_metrics.py --collect # scores_extra/*.csv + TABLES.md from every unit written so far
34
+ Outputs: scores_extra/<dataset>/<fewshot_n5/draw<j> | pooled>/{metrics.csv, per_donor.csv, en.csv, en_per_sample.csv,
35
+ repro.json, manifest.json}.
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import os
40
+ import sys
41
+
42
+
43
+ def _threads_from_argv(default: int = 7) -> int:
44
+ for i, a in enumerate(sys.argv):
45
+ if a == "--threads" and i + 1 < len(sys.argv):
46
+ return int(sys.argv[i + 1])
47
+ if a.startswith("--threads="):
48
+ return int(a.split("=", 1)[1])
49
+ return default
50
+
51
+
52
+ _THR = str(_threads_from_argv())
53
+ for _k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMBA_NUM_THREADS"):
54
+ os.environ[_k] = _THR
55
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
56
+
57
+ import argparse # noqa: E402
58
+ import hashlib # noqa: E402
59
+ import json # noqa: E402
60
+ import shutil # noqa: E402
61
+ import subprocess # noqa: E402
62
+ import time # noqa: E402
63
+ from pathlib import Path # noqa: E402
64
+
65
+ import numpy as np # noqa: E402
66
+ import pandas as pd # noqa: E402
67
+ import scipy.sparse as sp # noqa: E402
68
+
69
+ TOOLS = Path(__file__).resolve().parent
70
+ sys.path.insert(0, str(TOOLS))
71
+ import ft_common as F # noqa: E402
72
+ import score_ft as S # noqa: E402 (module level: argparse/env only; main() is not run)
73
+
74
+ TASK = F.TASK
75
+ SCORES = TASK / "scores"
76
+ OUT_ROOT = TASK / "scores_extra"
77
+ REMOTE = "spark-0110"
78
+ MIN_FREE_GIB = 40.0
79
+
80
+ SEED = 20261001 # every new random stream of this file (CV folds, RF, bandwidth subsample, E_N)
81
+ KS = (3, 5, 10)
82
+ KNN_C2ST_K = 5 # sklearn default, scDiffusion's kNN classifier
83
+ RF_TREES = 300 # scGAN: fully grown trees, max_features = sqrt; 300 instead of 1000 trees (cost)
84
+ CV_FOLDS = 5 # scGAN: five-fold cross-validation, equal real / generated counts
85
+ BW_MULTIPLES = (0.5, 1.0, 2.0) # scGAN: sigma in {m/2, m, 2m}
86
+ BW_MAX_CELLS = 4000 # R1 cells used for the median pairwise distance
87
+ EN_PCS = 100 # scSemiProfiler: PCA to 100 dimensions
88
+ EN_LB_MAX_QUERIES = 20000 # all-cells E_N: LB estimated from this many query cells per direction (index = full half)
89
+ EN_CHUNK = 8192
90
+
91
+ FEW_ARMS = ("zs_raw", "zs_cal", "scsemi5", "lora5", "zs_pseudo")
92
+ POOLED_ARMS = ("zs__raw", "zs__cal", "pseudo_full__cal", "real_lora__raw", "zs__pseudo")
93
+ CONTROL = "real_R2" # R1 vs R2 (P/C cells) / within-sample half split (all cells)
94
+ CONTROL_OOS = "real_R3" # out-of-sample real side: R2' vs R3 (families 1-2)
95
+ ARM_LABEL = {"zs_raw": "Zero-shot, real bulk", "zs__raw": "Zero-shot, real bulk",
96
+ "zs_cal": "Zero-shot + calibration", "zs__cal": "Zero-shot + calibration",
97
+ "scsemi5": "scSemiProfiler, 5 donors", "lora5": "LoRA, 5 donors",
98
+ "real_lora__raw": "LoRA, all training pairs", "pseudo_full__cal": "sc-only fine-tune (+ calibration)",
99
+ "zs_pseudo": "Zero-shot, sc pseudobulk input (reference)",
100
+ "zs__pseudo": "Zero-shot, sc pseudobulk input (reference)",
101
+ CONTROL: "Real vs real control (held-out real cells)",
102
+ CONTROL_OOS: "Real vs real control (out-of-sample: R2 vs R3)"}
103
+ DATASETS = ("immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
104
+
105
+
106
+ def log(msg: str) -> None:
107
+ F.log(msg)
108
+
109
+
110
+ # =========================================================================== pure metric functions
111
+ def sqdist_min(Q: np.ndarray, X: np.ndarray, *, exclude_self: bool = False, max_block: float = 1.5e8) -> tuple:
112
+ """For every row of Q: the minimum squared L2 distance to the rows of X and its index (brute force, float64,
113
+ chunked BLAS). exclude_self: Q is X and the diagonal is skipped (leave-one-out)."""
114
+ Q = np.ascontiguousarray(Q, dtype=np.float64)
115
+ X = np.ascontiguousarray(X, dtype=np.float64)
116
+ xx = np.einsum("ij,ij->i", X, X)
117
+ qq = np.einsum("ij,ij->i", Q, Q)
118
+ out = np.empty(Q.shape[0])
119
+ arg = np.empty(Q.shape[0], dtype=np.int64)
120
+ chunk = max(16, int(max_block // max(X.shape[0], 1)))
121
+ for s in range(0, Q.shape[0], chunk):
122
+ e = min(s + chunk, Q.shape[0])
123
+ D = qq[s:e, None] + xx[None, :] - 2.0 * (Q[s:e] @ X.T)
124
+ if exclude_self:
125
+ D[np.arange(e - s), np.arange(s, e)] = np.inf
126
+ a = np.argmin(D, axis=1)
127
+ arg[s:e] = a
128
+ out[s:e] = np.maximum(D[np.arange(e - s), a], 0.0)
129
+ return out, arg
130
+
131
+
132
+ def one_nn_loo(zr: np.ndarray, zg: np.ndarray) -> dict:
133
+ """Leave-one-out 1-NN two-sample accuracy (Lopez-Paz & Oquab 2017; scLDM eq. 32): pool both sets, predict each
134
+ point's label by its nearest other point; 0.5 = indistinguishable, 1 = separable."""
135
+ Z = np.vstack([zr, zg])
136
+ y = np.r_[np.ones(len(zr), bool), np.zeros(len(zg), bool)]
137
+ _, a = sqdist_min(Z, Z, exclude_self=True)
138
+ ok = y[a] == y
139
+ return {"nn1_acc": float(ok.mean()), "nn1_acc_real": float(ok[y].mean()), "nn1_acc_gen": float(ok[~y].mean())}
140
+
141
+
142
+ def c2st_auc(zr: np.ndarray, zg: np.ndarray, *, kind: str, seed: int = SEED, n_jobs: int = 1) -> dict:
143
+ """Classifier two-sample test: stratified 5-fold CV ROC AUC of real (1) vs generated (0); mean and SD over folds."""
144
+ from sklearn.ensemble import RandomForestClassifier
145
+ from sklearn.metrics import roc_auc_score
146
+ from sklearn.model_selection import StratifiedKFold
147
+ from sklearn.neighbors import KNeighborsClassifier
148
+ Z = np.vstack([zr, zg]).astype(np.float32)
149
+ y = np.r_[np.ones(len(zr), np.int8), np.zeros(len(zg), np.int8)]
150
+ aucs = []
151
+ for tr, te in StratifiedKFold(CV_FOLDS, shuffle=True, random_state=seed).split(Z, y):
152
+ if kind == "knn":
153
+ clf = KNeighborsClassifier(n_neighbors=KNN_C2ST_K, n_jobs=n_jobs)
154
+ elif kind == "rf":
155
+ clf = RandomForestClassifier(n_estimators=RF_TREES, max_features="sqrt", n_jobs=n_jobs, random_state=seed)
156
+ else:
157
+ raise ValueError(kind)
158
+ clf.fit(Z[tr], y[tr])
159
+ p = clf.predict_proba(Z[te])[:, list(clf.classes_).index(1)]
160
+ aucs.append(roc_auc_score(y[te], p))
161
+ return {f"c2st_{kind}_auc": float(np.mean(aucs)), f"c2st_{kind}_auc_sd": float(np.std(aucs, ddof=1))}
162
+
163
+
164
+ def median_bandwidth(z: np.ndarray, *, seed: int = SEED, max_cells: int = BW_MAX_CELLS) -> float:
165
+ """Median heuristic (Gretton et al. 2012): median pairwise Euclidean distance among (<= max_cells) real cells."""
166
+ rng = np.random.default_rng(seed)
167
+ idx = np.sort(rng.choice(len(z), size=min(max_cells, len(z)), replace=False))
168
+ x = np.asarray(z[idx], np.float64)
169
+ sq = np.einsum("ij,ij->i", x, x)
170
+ D = np.maximum(sq[:, None] + sq[None, :] - 2 * x @ x.T, 0.0)
171
+ iu = np.triu_indices(len(x), 1)
172
+ return float(np.sqrt(np.median(D[iu])))
173
+
174
+
175
+ def _kernel_sums(A: np.ndarray, B: np.ndarray, sigmas, same: bool, max_block: float = 6e7) -> np.ndarray:
176
+ """sum over pairs of exp(-||a - b||^2 / (2 sigma^2)) for every sigma (diagonal excluded when same)."""
177
+ A = np.ascontiguousarray(A, np.float64)
178
+ B = np.ascontiguousarray(B, np.float64)
179
+ aa, bb = np.einsum("ij,ij->i", A, A), np.einsum("ij,ij->i", B, B)
180
+ g = np.asarray([1.0 / (2.0 * s * s) for s in sigmas])
181
+ tot = np.zeros(len(sigmas))
182
+ chunk = max(16, int(max_block // max(len(B), 1)))
183
+ for s in range(0, len(A), chunk):
184
+ e = min(s + chunk, len(A))
185
+ D = np.maximum(aa[s:e, None] + bb[None, :] - 2.0 * (A[s:e] @ B.T), 0.0)
186
+ for i, gi in enumerate(g):
187
+ K = np.exp(-gi * D)
188
+ if same:
189
+ K[np.arange(e - s), np.arange(s, e)] = 0.0
190
+ tot[i] += K.sum()
191
+ return tot
192
+
193
+
194
+ def mmd2_unbiased(zr: np.ndarray, zg: np.ndarray, sigmas) -> np.ndarray:
195
+ """Unbiased MMD^2 (Gretton et al. 2012, eq. 3) with Gaussian RBF k(x, y) = exp(-||x - y||^2 / (2 sigma^2)), one value
196
+ per sigma; the kernel sum over the sigmas (scGAN's multi-scale kernel) is the sum of the per-sigma values."""
197
+ n, m = len(zr), len(zg)
198
+ kxx = _kernel_sums(zr, zr, sigmas, True) / (n * (n - 1))
199
+ kyy = _kernel_sums(zg, zg, sigmas, True) / (m * (m - 1))
200
+ kxy = _kernel_sums(zr, zg, sigmas, False) / (n * m)
201
+ return kxx + kyy - 2.0 * kxy
202
+
203
+
204
+ def pc_at_k(zr: np.ndarray, zg: np.ndarray, k: int) -> dict:
205
+ """Kynkaanniemi precision and Naeem coverage / density with k-NN balls of the real set: the scorer's own
206
+ stage_b_embed functions (knn_radius, precision_coverage). density is rescaled from SB's fixed k = 10 to k."""
207
+ radius = F.SB.knn_radius(zr, k)
208
+ r = F.SB.precision_coverage(zr, radius, zg)
209
+ r["density"] = r["density"] * F.K_NN / k
210
+ return r
211
+
212
+
213
+ def expected_coverage(n_real: int, n_gen: int, k: int) -> float:
214
+ """Naeem et al. 2020, eq. 9: E[coverage] for identical real and fake distributions."""
215
+ num = np.prod([(n_real - i) for i in range(1, k + 1)], dtype=np.float64)
216
+ den = np.prod([(n_gen + n_real - i) for i in range(1, k + 1)], dtype=np.float64)
217
+ return float(1.0 - num / den)
218
+
219
+
220
+ def two_sample_block(zr: np.ndarray, zg: np.ndarray, sigma_m: float, *, n_jobs: int, rf: bool = True) -> dict:
221
+ out = {}
222
+ out.update(c2st_auc(zr, zg, kind="knn", n_jobs=n_jobs))
223
+ if rf:
224
+ out.update(c2st_auc(zr, zg, kind="rf", n_jobs=n_jobs))
225
+ out.update(one_nn_loo(zr, zg))
226
+ sig = [m * sigma_m for m in BW_MULTIPLES]
227
+ mm = mmd2_unbiased(zr, zg, sig)
228
+ for mult, val in zip(BW_MULTIPLES, mm):
229
+ out[f"mmd2_bw{mult:g}"] = float(val)
230
+ out["mmd2_sum"] = float(mm.sum())
231
+ out["mmd_bandwidth_m"] = float(sigma_m)
232
+ return out
233
+
234
+
235
+ # =========================================================================== scSemiProfiler E_N
236
+ def log1p_cp10k_sparse(X: sp.csr_matrix) -> sp.csr_matrix:
237
+ """SB.cp10k_log1p (per-cell CP10K over the columns, log1p; empty cells stay zero) kept sparse, float32."""
238
+ X = X.tocsr().astype(np.float64)
239
+ lib = np.asarray(X.sum(axis=1)).ravel()
240
+ D = (sp.diags(np.divide(F.CP10K, lib, out=np.zeros_like(lib), where=lib > 0)) @ X).tocsr()
241
+ D.data = np.log1p(D.data)
242
+ return D.astype(np.float32)
243
+
244
+
245
+ class Gram:
246
+ """Running X^T X, column sums and row count of log1p-CP10K features (float64), for an exact PCA by eigh of the
247
+ covariance (the solver sklearn's PCA calls covariance_eigh; equal to the full-SVD PCA up to component signs)."""
248
+
249
+ def __init__(self, p: int):
250
+ self.G = np.zeros((p, p))
251
+ self.s = np.zeros(p)
252
+ self.n = 0
253
+
254
+ def add(self, L: sp.csr_matrix, chunk: int = EN_CHUNK) -> "Gram":
255
+ for a in range(0, L.shape[0], chunk):
256
+ B = L[a:a + chunk].toarray() # float32 (log1p CP10K)
257
+ self.G += (B.T @ B).astype(np.float64) # sgemm within a chunk, float64 across chunks
258
+ self.s += B.sum(0, dtype=np.float64)
259
+ self.n += B.shape[0]
260
+ return self
261
+
262
+ def __add__(self, other: "Gram") -> "Gram":
263
+ g = Gram(len(self.s))
264
+ g.G, g.s, g.n = self.G + other.G, self.s + other.s, self.n + other.n
265
+ return g
266
+
267
+ def pca(self, n_comp: int = EN_PCS) -> tuple[np.ndarray, np.ndarray]:
268
+ from scipy.linalg import eigh
269
+ p = len(self.s)
270
+ n_comp = int(min(n_comp, p, self.n - 1))
271
+ mu = self.s / self.n
272
+ C = (self.G - self.n * np.outer(mu, mu)) / (self.n - 1)
273
+ w, V = eigh(C, subset_by_index=[p - n_comp, p - 1])
274
+ return mu, np.ascontiguousarray(V[:, ::-1].T) # components x genes, descending variance
275
+
276
+
277
+ def embed(L: sp.csr_matrix, mu: np.ndarray, comps: np.ndarray, chunk: int = EN_CHUNK) -> np.ndarray:
278
+ """(x - mu) @ comps.T for sparse features x (dense row chunks, float64 BLAS)."""
279
+ out = np.empty((L.shape[0], comps.shape[0]))
280
+ for a in range(0, L.shape[0], chunk):
281
+ out[a:a + chunk] = (L[a:a + chunk].toarray().astype(np.float64) - mu) @ comps.T
282
+ return out
283
+
284
+
285
+ def dif_sc(a: np.ndarray, b: np.ndarray) -> dict:
286
+ """scSemiProfiler eq. 17 with K = 1: mean over the cells of both samples of the distance to the nearest cell of the
287
+ other sample. 'sq' = squared L2 (their code: faiss IndexFlatL2), 'l2' = L2 (their text)."""
288
+ da, _ = sqdist_min(a, b)
289
+ db, _ = sqdist_min(b, a)
290
+ n = len(a) + len(b)
291
+ return {"sq": float((da.sum() + db.sum()) / n), "l2": float((np.sqrt(da).sum() + np.sqrt(db).sum()) / n)}
292
+
293
+
294
+ def lower_bound(Z: np.ndarray, rng: np.random.Generator, max_queries: int | None) -> dict:
295
+ """LB: random half split of the whole PCA matrix (real + generated), symmetric 1-NN (their code: shuffle, first
296
+ n//2 rows vs the rest). With max_queries, each direction averages max_queries random query cells of one half
297
+ against the complete other half (an unbiased estimate of the same mean)."""
298
+ perm = rng.permutation(len(Z))
299
+ h = len(Z) // 2
300
+ A, B = Z[perm[:h]], Z[perm[h:]]
301
+ qa = A if (max_queries is None or len(A) <= max_queries) else A[np.sort(rng.choice(len(A), max_queries, replace=False))]
302
+ qb = B if (max_queries is None or len(B) <= max_queries) else B[np.sort(rng.choice(len(B), max_queries, replace=False))]
303
+ da, _ = sqdist_min(qa, B)
304
+ db, _ = sqdist_min(qb, A)
305
+ exact = len(qa) == len(A) and len(qb) == len(B)
306
+ if exact: # their arithmetic: mean over the concatenated distances of both directions
307
+ sq = float((da.sum() + db.sum()) / (len(da) + len(db)))
308
+ l2 = float((np.sqrt(da).sum() + np.sqrt(db).sum()) / (len(da) + len(db)))
309
+ else: # same weights as the exact concatenation (|A| and |B| cells), each direction estimated
310
+ wa, wb = len(A) / (len(A) + len(B)), len(B) / (len(A) + len(B))
311
+ sq = float(wa * da.mean() + wb * db.mean())
312
+ l2 = float(wa * np.sqrt(da).mean() + wb * np.sqrt(db).mean())
313
+ return {"sq": sq, "l2": l2, "exact": exact, "n_queries": [int(len(qa)), int(len(qb))], "n_half": [int(len(A)), int(len(B))]}
314
+
315
+
316
+ def en_from_embeddings(gts: list, semis: list, rng: np.random.Generator, *, lb_max_queries: int | None,
317
+ Z_all: np.ndarray) -> dict:
318
+ """E_N for one arm from per-sample embeddings (PCA already fitted on real + generated together).
319
+ UB: per sample i a uniformly random partner j != i (real cells of both), Dif averaged over samples.
320
+ Dif_i: real vs generated of sample i. E_N = (mean_i Dif_i - LB) / (UB - LB) (eq. 18); per sample (Dif_i - LB) / (UB - LB)."""
321
+ P = len(gts)
322
+ lb = lower_bound(Z_all, rng, lb_max_queries)
323
+ partner = (np.arange(P) + rng.integers(1, P, size=P)) % P if P > 1 else np.zeros(P, int)
324
+ ub_i = [dif_sc(gts[i], gts[partner[i]]) for i in range(P)]
325
+ dif_i = [dif_sc(gts[i], semis[i]) for i in range(P)]
326
+ out = {"lb": lb, "partner": partner.tolist(), "per_sample": []}
327
+ for d in ("sq", "l2"):
328
+ ub = float(np.mean([u[d] for u in ub_i]))
329
+ dif = np.asarray([x[d] for x in dif_i])
330
+ out[d] = {"lb": lb[d], "ub": ub, "dif_mean": float(dif.mean()), "en": float((dif.mean() - lb[d]) / (ub - lb[d])),
331
+ "en_i": ((dif - lb[d]) / (ub - lb[d])).tolist(), "dif_i": dif.tolist()}
332
+ return out
333
+
334
+
335
+ def get_error_legacy(gts: list, semis: list, representatives: list, cluster_labels: list, n_comp: int = EN_PCS) -> dict:
336
+ """Line-by-line re-statement of scSemiProfiler utils.get_error for one round (global np.random state, sklearn PCA,
337
+ self-pairing allowed in the UB, representatives at LB, squared L2). Only for the equivalence test."""
338
+ from sklearn.decomposition import PCA
339
+ P = len(gts)
340
+ X = np.concatenate([np.concatenate(gts, 0), np.concatenate(semis, 0)], 0)
341
+ Xr = PCA(n_components=n_comp).fit_transform(X)
342
+ xg, xs, off = [], [], 0
343
+ for g in gts:
344
+ xg.append(Xr[off:off + len(g)])
345
+ off += len(g)
346
+ for s in semis:
347
+ xs.append(Xr[off:off + len(s)])
348
+ off += len(s)
349
+ lbgt = Xr.copy()
350
+ np.random.shuffle(lbgt)
351
+ h = lbgt.shape[0] // 2
352
+ a, b = lbgt[:h], lbgt[h:]
353
+ da, _ = sqdist_min(a, b)
354
+ db, _ = sqdist_min(b, a)
355
+ lb = float(np.r_[da, db].mean())
356
+ ubs = []
357
+ for i in range(P):
358
+ r = np.random.randint(0, P)
359
+ ubs.append(dif_sc(xg[i], xg[r])["sq"])
360
+ ub = float(np.mean(ubs))
361
+ semi = [lb if i in representatives else dif_sc(xg[i], xs[i])["sq"] for i in range(P)]
362
+ naive = [lb if i in representatives else dif_sc(xg[i], xg[representatives[cluster_labels[i]]])["sq"] for i in range(P)]
363
+ return {"upperbound": ub, "lowerbound": lb, "semierror": float(np.mean(semi)), "naiveerror": float(np.mean(naive)),
364
+ "en_semi": (float(np.mean(semi)) - lb) / (ub - lb)}
365
+
366
+
367
+ # =========================================================================== unit inputs
368
+ def sha256(path: Path) -> str:
369
+ h = hashlib.sha256()
370
+ with open(path, "rb") as fh:
371
+ for block in iter(lambda: fh.read(1 << 24), b""):
372
+ h.update(block)
373
+ return h.hexdigest()
374
+
375
+
376
+ def free_gib(path: Path) -> float:
377
+ st = os.statvfs(path)
378
+ return st.f_bavail * st.f_frsize / 2**30
379
+
380
+
381
+ def resolve_npz(path: Path, want_sha: str, fetch_root: Path, fetched: list) -> Path:
382
+ """The scored NPZ: the local file if present, else a sha-checked copy from server_2 (same path) under fetch_root,
383
+ with its receipt (.log) next to it so score_ft.open_arm can check output_sha256."""
384
+ path = Path(path)
385
+ if path.is_file():
386
+ return path
387
+ rel = path.relative_to(TASK)
388
+ dst = fetch_root / rel
389
+ marker = path.with_suffix(".moved")
390
+ if dst.is_file() and dst.with_suffix(".log").is_file():
391
+ if sha256(dst) == want_sha:
392
+ return dst
393
+ dst.unlink()
394
+ size = int(subprocess.run(["ssh", "-n", REMOTE, f"stat -c %s '{path}'"], capture_output=True, text=True,
395
+ check=True).stdout.strip())
396
+ need = size / 2**30 + MIN_FREE_GIB
397
+ if free_gib(fetch_root) < need:
398
+ raise SystemExit(f"disk: {free_gib(fetch_root):.1f} GiB free < {need:.1f} GiB needed to fetch {path}")
399
+ dst.parent.mkdir(parents=True, exist_ok=True)
400
+ log(f"fetching {rel} ({size / 2**30:.2f} GiB) from {REMOTE}")
401
+ subprocess.run(["rsync", "-a", "--bwlimit=200000", f"{REMOTE}:{path}", str(dst)], check=True)
402
+ rec = path.with_suffix(".log")
403
+ if rec.is_file():
404
+ shutil.copy2(rec, dst.with_suffix(".log"))
405
+ else:
406
+ subprocess.run(["rsync", "-a", f"{REMOTE}:{rec}", str(dst.with_suffix(".log"))], check=True)
407
+ fetched.append(dst)
408
+ got = sha256(dst)
409
+ if got != want_sha:
410
+ raise SystemExit(f"{dst}: sha {got[:12]} differs from the scored NPZ sha {want_sha[:12]}")
411
+ if marker.is_file():
412
+ txt = marker.read_text()
413
+ if f"sha {want_sha[:12]}" not in txt:
414
+ raise SystemExit(f"{marker}: marker sha differs ({txt.strip()})")
415
+ return dst
416
+
417
+
418
+ def unit_calls(design: str, ds: str, draw: int | None) -> list[tuple[Path, tuple]]:
419
+ if design == "fewshot":
420
+ base = SCORES / ds / "fewshot_n5"
421
+ return [(base / f"draw{draw}", ("zs_raw", "zs_cal", "lora5", "zs_pseudo")), (base / f"draw{draw}_scsemi5", ("scsemi5",))]
422
+ if design == "pooled":
423
+ return [(SCORES / ds / "pooled", POOLED_ARMS)]
424
+ raise ValueError(design)
425
+
426
+
427
+ def unit_dir(design: str, ds: str, draw: int | None) -> Path:
428
+ return OUT_ROOT / ds / (f"fewshot_n5/draw{draw}" if design == "fewshot" else "pooled")
429
+
430
+
431
+ def observed_cells(spec, ref: dict, man: dict, donors: np.ndarray, cache: dict) -> tuple[list, dict]:
432
+ """All observed QC cells of the scored samples on the scoring genes (counts), per sample in the reference's
433
+ canonical cell order, from the same files the reference was built from (inputs sha-checked against
434
+ reference_manifest.json). cache: per dataset, reused by the draws of one process."""
435
+ if spec.name not in cache:
436
+ cache.clear()
437
+ cache[spec.name] = _observed_all(spec, ref, man)
438
+ X, srow, sid, inputs = cache[spec.name]
439
+ out = []
440
+ for d in donors:
441
+ out.append(X[np.flatnonzero(srow == int(np.flatnonzero(sid == d)[0]))].tocsr())
442
+ n = np.asarray([o.shape[0] for o in out])
443
+ ref_n = ref["n_cells"][[int(np.flatnonzero(ref["donors"].astype(str) == d)[0]) for d in donors]]
444
+ if not np.array_equal(n, ref_n):
445
+ raise SystemExit("observed cell counts per sample differ from the reference")
446
+ return out, {"inputs_sha256": inputs, "n_cells_total": int(n.sum())}
447
+
448
+
449
+ def _observed_all(spec, ref: dict, man: dict):
450
+ feat = F.load_features(spec.features)
451
+ if feat["sha256"] != man["features"]["sha256"]:
452
+ raise SystemExit("features sha differs from the reference's")
453
+ gs = F.gene_sets(feat)
454
+ if not np.array_equal(gs["score_ids"], ref["score_ids"].astype(str)):
455
+ raise SystemExit("scoring genes differ from the reference")
456
+ cells = F.load_cells_datadir(spec, gs)
457
+ if cells is None or cells["inputs_sha256"] != man["cells"]["inputs_sha256"]:
458
+ raise SystemExit("observed cell files differ from the ones the reference was built from")
459
+ keys, _ = F.cell_keys(cells["table"].reset_index(drop=True))
460
+ srow = np.asarray(cells["sample_row"])
461
+ order = np.lexsort((keys, srow)) # the reference's canonical order (F.build_reference)
462
+ X = cells["X"].tocsr()[order][:, gs["score_idx"]].tocsr().astype(np.float32)
463
+ return X, srow[order], feat["sample_ids"], cells["inputs_sha256"]
464
+
465
+
466
+ # =========================================================================== one unit
467
+ def pair_embeddings(v: dict, R: sp.csr_matrix, r_d: np.ndarray, Q: sp.csr_matrix, q_d: np.ndarray,
468
+ zr_raw: np.ndarray | None = None) -> dict:
469
+ """Real set R and query set Q in the scorer's PCA-50: 'raw' = SB.project; 'dm' = score_ft.depth_matched's own
470
+ steps (SB.depth_match of the pair with a fresh rng(DEPTH_SEED), real set in the 'R1' slot, then SB.project),
471
+ returning the embeddings instead of only their precision/coverage. zr_raw: the view's fitted z1 for R = R1."""
472
+ names = v["donors"]
473
+ thinned, _ = F.SB.depth_match({"R1": R, "Q": Q}, {"R1": names[r_d], "Q": names[q_d]}, list(names),
474
+ np.random.default_rng(F.DEPTH_SEED))
475
+ return {"raw": (zr_raw if zr_raw is not None else F.SB.project(R, v["mean"], v["comps"]),
476
+ F.SB.project(Q, v["mean"], v["comps"])),
477
+ "dm": (F.SB.project(thinned["R1"], v["mean"], v["comps"]), F.SB.project(thinned["Q"], v["mean"], v["comps"]))}
478
+
479
+
480
+ def per_donor_pc(r1_d, q_d, S_, res) -> tuple:
481
+ nq, n1 = np.bincount(q_d, minlength=S_), np.bincount(r1_d, minlength=S_)
482
+ return (np.bincount(q_d, weights=res["inside"], minlength=S_) / nq,
483
+ np.bincount(r1_d, weights=res["covered"], minlength=S_) / n1)
484
+
485
+
486
+ def score_set(name: str, v: dict, Q: sp.csr_matrix, q_d: np.ndarray, sigma_m: float, n_jobs: int,
487
+ expect: dict | None, oos: tuple | None) -> tuple[list, pd.DataFrame, dict]:
488
+ """Families 1, 2, 4 for one query set (an arm's P/C subsample, or R2), raw and depth matched, real side = R1
489
+ (the scorer's space). oos = (R2 counts, R2 donor index, set name): families 1-2 again with R2 as the real side."""
490
+ S_ = v["donors"].size
491
+ E = pair_embeddings(v, v["R1"], v["r1_d"], Q, q_d, zr_raw=v["z1"])
492
+ rows, per, chk = [], {"donor": v["donors"], "set": name}, {}
493
+ for mode, (zr, zg) in E.items():
494
+ t0 = time.monotonic()
495
+ m = {"set": name, "real_side": "R1", "mode": mode, "n_real": int(len(zr)), "n_gen": int(len(zg))}
496
+ for k in KS:
497
+ # k = 10 raw: the view's own radii (score_ft.arm_metrics); every other k / mode: radii recomputed on zr
498
+ res = F.SB.precision_coverage(zr, v["radius"], zg) if (k == F.K_NN and mode == "raw") else pc_at_k(zr, zg, k)
499
+ m[f"precision_k{k}"], m[f"coverage_k{k}"], m[f"density_k{k}"] = res["precision"], res["coverage"], res["density"]
500
+ m[f"expected_coverage_identical_k{k}"] = expected_coverage(len(zr), len(zg), k)
501
+ pp, pc = per_donor_pc(v["r1_d"], q_d, S_, res)
502
+ per[f"precision_k{k}_{mode}"], per[f"coverage_k{k}_{mode}"] = pp, pc
503
+ m.update(two_sample_block(zr, zg, sigma_m, n_jobs=n_jobs))
504
+ m["seconds"] = round(time.monotonic() - t0, 1)
505
+ rows.append(m)
506
+ log(f" {name} [R1 {mode}] P/C k10 {m['precision_k10']:.4f}/{m['coverage_k10']:.4f} k5 {m['precision_k5']:.4f}/"
507
+ f"{m['coverage_k5']:.4f} k3 {m['precision_k3']:.4f}/{m['coverage_k3']:.4f} | AUC knn {m['c2st_knn_auc']:.3f} "
508
+ f"rf {m['c2st_rf_auc']:.3f} | 1-NN {m['nn1_acc']:.3f} | MMD2 {m['mmd2_bw1']:.4f} ({m['seconds']} s)")
509
+ if oos is not None:
510
+ R2, r2_d, oname = oos
511
+ for mode, (zr, zg) in pair_embeddings(v, R2, r2_d, Q, q_d).items():
512
+ t0 = time.monotonic()
513
+ m = {"set": oname, "real_side": "R2", "mode": mode, "n_real": int(len(zr)), "n_gen": int(len(zg))}
514
+ m.update(two_sample_block(zr, zg, sigma_m, n_jobs=n_jobs))
515
+ m["seconds"] = round(time.monotonic() - t0, 1)
516
+ rows.append(m)
517
+ log(f" {oname} [R2 {mode}] AUC knn {m['c2st_knn_auc']:.3f} rf {m['c2st_rf_auc']:.3f} | 1-NN {m['nn1_acc']:.3f} "
518
+ f"| MMD2 {m['mmd2_bw1']:.4f} ({m['seconds']} s)")
519
+ if expect is not None: # reproduction of the scorer's k = 10 values
520
+ for mode, key in (("raw", ""), ("dm", "_depth_matched")):
521
+ mm = next(r for r in rows if r["mode"] == mode)
522
+ for q in ("precision", "coverage"):
523
+ chk[f"{q}{key}"] = {"ours": mm[f"{q}_k10"], "scorer": expect[f"{q}{key}"],
524
+ "abs_diff": abs(mm[f"{q}_k10"] - expect[f"{q}{key}"])}
525
+ if "per_donor" in expect:
526
+ d = np.abs(per[f"{q}_k10_{mode}"] - expect["per_donor"][f"{q}{key}"])
527
+ chk[f"{q}{key}_per_donor_max_abs_diff"] = float(d.max())
528
+ return rows, pd.DataFrame(per), chk
529
+
530
+
531
+ def run_unit(design: str, ds: str, draw: int | None, a) -> None:
532
+ t_unit = time.monotonic()
533
+ spec = F.DATASETS[ds]
534
+ out = unit_dir(design, ds, draw)
535
+ if (out / "manifest.json").is_file() and not a.force:
536
+ log(f"{out} done already")
537
+ return
538
+ out.mkdir(parents=True, exist_ok=True)
539
+ lock = out / ".in_progress"
540
+ if lock.is_file(): # another process (other stream) is computing this unit: skip unless its pid is gone
541
+ pid = int(lock.read_text().split()[0])
542
+ if Path(f"/proc/{pid}").exists():
543
+ log(f"{out} is being computed by pid {pid}; skipped")
544
+ return
545
+ lock.write_text(f"{os.getpid()} {F.now()}\n")
546
+ try:
547
+ _run_unit(design, ds, draw, a, t_unit, spec, out)
548
+ finally:
549
+ lock.unlink(missing_ok=True)
550
+
551
+
552
+ def _run_unit(design: str, ds: str, draw: int | None, a, t_unit: float, spec, out: Path) -> None:
553
+ calls = unit_calls(design, ds, draw)
554
+ summ = {}
555
+ for cdir, arms in calls:
556
+ s = json.loads((cdir / "summary.json").read_text())
557
+ miss = [x for x in arms if x not in s["arms"]]
558
+ if miss:
559
+ raise SystemExit(f"{cdir}: arms {miss} not scored there")
560
+ summ[cdir] = s
561
+ first = summ[calls[0][0]]
562
+ donors = [str(x) for x in first["donors"]]
563
+ for cdir, s in summ.items():
564
+ if [str(x) for x in s["donors"]] != donors:
565
+ raise SystemExit(f"{cdir}: scored donors differ from {calls[0][0]}")
566
+ if s["reference"]["reference_sha256"] != first["reference"]["reference_sha256"]:
567
+ raise SystemExit(f"{cdir}: reference sha differs")
568
+ cache = F.CACHE_ROOT / ds
569
+ ref, man = F.load_reference(cache)
570
+ if man["reference_sha256"] != first["reference"]["reference_sha256"]:
571
+ raise SystemExit(f"{cache}: reference sha differs from the scored one")
572
+ log(f"{ds} {design} {'' if draw is None else f'draw{draw} '}: {len(donors)} scored samples; fitting the scorer's view")
573
+ v = S.make_view(ref, donors)
574
+ repro = {"unit": str(out), "pca": {"ours": v["pca"], "scorer": first["reference"]["pca"]},
575
+ "r2_control": {"ours": v["r2_control"], "scorer": first["reference"]["r2_control"]}, "arms": {}}
576
+ S_ = v["donors"].size
577
+ sigma_m = median_bandwidth(v["z1"])
578
+ log(f"bandwidth m (median pairwise distance of R1, PCA-50) = {sigma_m:.4f}")
579
+ rows, per_frames, en_rows, en_ps = [], [], [], []
580
+ fetched: list[Path] = []
581
+ fetch_root = Path(a.fetch_dir)
582
+
583
+ # ---------------- E_N inputs shared by all arms
584
+ rng_c = F.donor_rng
585
+ R1L = log1p_cp10k_sparse(v["R1"])
586
+ gram_r1 = Gram(R1L.shape[1]).add(R1L)
587
+ r1_split = [np.flatnonzero(v["r1_d"] == s) for s in range(S_)]
588
+ obs, obs_info = observed_cells(spec, ref, man, v["donors"], a.obs_cache)
589
+ # out-of-sample real sets from the scorer's donor-keyed permutation (F.reference_split): R1 = perm[:n],
590
+ # R2 = perm[n:2n] (both checked equal to reference.npz), R3 = perm[2n:3n] (fewer cells when the sample is small);
591
+ # the R2-vs-R3 control uses R2' = perm[n:n+m], m = min(n, |R3|), so both sides have the same size per sample.
592
+ r3_blocks, r2b_blocks, r3_d, r2b_d, oos_info = [], [], [], [], {"n_r3": [], "short_samples": []}
593
+ for k in range(S_):
594
+ nk, d = obs[k].shape[0], str(v["donors"][k])
595
+ a1, a2 = F.reference_split(nk, d)
596
+ if (obs[k][a1] != v["R1"][np.flatnonzero(v["r1_d"] == k)]).nnz or \
597
+ (obs[k][a2] != v["R2"][np.flatnonzero(v["r2_d"] == k)]).nnz:
598
+ raise SystemExit(f"{d}: R1 / R2 rebuilt from the observed cells differ from reference.npz")
599
+ perm = F.donor_rng(F.SUB_SEED, d).permutation(nk)
600
+ n = a1.size
601
+ r3 = np.sort(perm[2 * n:3 * n])
602
+ m_ = r3.size
603
+ if m_ < n:
604
+ oos_info["short_samples"].append({"sample": d, "n": int(n), "n_r3": int(m_)})
605
+ r3_blocks.append(obs[k][r3])
606
+ r2b_blocks.append(obs[k][np.sort(perm[n:n + m_])])
607
+ r3_d.append(np.full(m_, k))
608
+ r2b_d.append(np.full(m_, k))
609
+ oos_info["n_r3"].append(int(m_))
610
+ R3, R2b = sp.vstack(r3_blocks, format="csr"), sp.vstack(r2b_blocks, format="csr")
611
+ r3_d, r2b_d = np.concatenate(r3_d), np.concatenate(r2b_d)
612
+ log(f"observed cells: {obs_info['n_cells_total']} in {S_} samples; R1/R2 rebuilt = reference.npz; R3 {R3.shape[0]} "
613
+ f"cells ({len(oos_info['short_samples'])} samples with fewer than n)")
614
+ oos_r2 = (v["R2"], v["r2_d"])
615
+ if not a.no_en_all:
616
+ obsL = [log1p_cp10k_sparse(o) for o in obs]
617
+ gram_obs = Gram(R1L.shape[1])
618
+ for L in obsL:
619
+ gram_obs.add(L)
620
+ del obs
621
+
622
+ def en_unit(set_name: str, cellset: str, gts_L: list, semis_L: list, gram_real: Gram, n_rep_rows: int | None):
623
+ t0 = time.monotonic()
624
+ g = Gram(gts_L[0].shape[1])
625
+ for L in semis_L:
626
+ g.add(L)
627
+ mu, comps = (gram_real + g).pca(EN_PCS)
628
+ gts = [embed(L, mu, comps) for L in gts_L]
629
+ semis = [embed(L, mu, comps) for L in semis_L]
630
+ Z_all = np.vstack(gts + semis)
631
+ rng = np.random.default_rng([SEED, 17 if cellset == "pc" else 29])
632
+ res = en_from_embeddings(gts, semis, rng, Z_all=Z_all,
633
+ lb_max_queries=None if cellset == "pc" else EN_LB_MAX_QUERIES)
634
+ n_test = len(gts)
635
+ for d in ("sq", "l2"):
636
+ r = res[d]
637
+ en_rows.append({"set": set_name, "cellset": cellset, "distance": d, "n_samples": n_test,
638
+ "n_cells_real": int(sum(len(x) for x in gts)), "n_cells_gen": int(sum(len(x) for x in semis)),
639
+ "n_pcs": int(comps.shape[0]), "lb": r["lb"], "ub": r["ub"], "dif_mean": r["dif_mean"],
640
+ "en": r["en"], "lb_exact": res["lb"]["exact"], "lb_queries": res["lb"]["n_queries"],
641
+ "n_representative_rows": n_rep_rows,
642
+ "en_reps_at_lb": (r["en"] * n_test / (n_test + n_rep_rows)) if n_rep_rows else None,
643
+ "seconds": round(time.monotonic() - t0, 1)})
644
+ en_ps.append(pd.DataFrame({"set": set_name, "cellset": cellset, "distance": d, "donor": v["donors"],
645
+ "n_real": [len(x) for x in gts], "n_gen": [len(x) for x in semis],
646
+ "partner": v["donors"][res["partner"]], "dif": r["dif_i"], "en_i": r["en_i"]}))
647
+ log(f" {set_name} E_N[{cellset}] sq {res['sq']['en']:.4f} (LB {res['sq']['lb']:.3f} UB {res['sq']['ub']:.3f} "
648
+ f"Dif {res['sq']['dif_mean']:.3f}) l2 {res['l2']['en']:.4f} ({round(time.monotonic() - t0, 1)} s)")
649
+
650
+ # ---------------- control: R1 vs R2 (the scorer's own)
651
+ expect_r2 = {"precision": first["reference"]["r2_control"]["precision"],
652
+ "coverage": first["reference"]["r2_control"]["coverage"],
653
+ "precision_depth_matched": first["reference"]["r2_control"]["depth_matched"]["precision"],
654
+ "coverage_depth_matched": first["reference"]["r2_control"]["depth_matched"]["coverage"]}
655
+ r, p, chk = score_set(CONTROL, v, v["R2"], v["r2_d"], sigma_m, a.threads, expect_r2, oos=None)
656
+ rows += r
657
+ # out-of-sample control: R2' (real side) vs R3, families 1-2 only
658
+ for mode, (zr, zg) in pair_embeddings(v, R2b, r2b_d, R3, r3_d).items():
659
+ t0 = time.monotonic()
660
+ m = {"set": CONTROL_OOS, "real_side": "R2", "mode": mode, "n_real": int(len(zr)), "n_gen": int(len(zg))}
661
+ m.update(two_sample_block(zr, zg, sigma_m, n_jobs=a.threads))
662
+ m["seconds"] = round(time.monotonic() - t0, 1)
663
+ rows.append(m)
664
+ log(f" {CONTROL_OOS} [R2 {mode}] AUC knn {m['c2st_knn_auc']:.3f} rf {m['c2st_rf_auc']:.3f} | 1-NN "
665
+ f"{m['nn1_acc']:.3f} | MMD2 {m['mmd2_bw1']:.4f} ({m['seconds']} s)")
666
+ per_frames.append(p)
667
+ repro["arms"][CONTROL] = chk
668
+ R2L = log1p_cp10k_sparse(v["R2"])
669
+ en_unit(CONTROL, "pc", [R1L[i] for i in r1_split], [R2L[np.flatnonzero(v["r2_d"] == s)] for s in range(S_)],
670
+ gram_r1, None)
671
+ if not a.no_en_all:
672
+ A_, B_ = [], []
673
+ for s in range(S_):
674
+ perm = rng_c(SEED, v["donors"][s]).permutation(obsL[s].shape[0])
675
+ h = obsL[s].shape[0] // 2
676
+ A_.append(obsL[s][np.sort(perm[:h])])
677
+ B_.append(obsL[s][np.sort(perm[h:])])
678
+ # the PCA basis is the one of all observed cells (A and B together): gram_real = A-part, semis add the B-part
679
+ gA = Gram(R1L.shape[1])
680
+ for L in A_:
681
+ gA.add(L)
682
+ en_unit(CONTROL, "all", A_, B_, gA, None)
683
+ del A_, B_
684
+
685
+ # ---------------- arms
686
+ pcache = a.pcache # Poisson read-outs (scoring genes) by NPZ sha; zs_*_all are reused by later draws
687
+ n_rep_rows = None
688
+ if design == "fewshot":
689
+ dj = json.loads((TASK / "data" / ds / "fewshot_n5" / "DRAWS.json").read_text())["draw"][str(draw)]
690
+ n_rep_rows = int(dj["n_train_rows"])
691
+ panel_ids = ref["panel_ids"].astype(str)
692
+ for cdir, arms in calls:
693
+ s = summ[cdir]
694
+ per_csv = pd.read_csv(cdir / "per_donor.csv")
695
+ for name in arms:
696
+ t0 = time.monotonic()
697
+ pa = s["per_arm"][name]
698
+ path = resolve_npz(Path(pa["npz"]), pa["npz_sha256"], fetch_root, fetched)
699
+ arm = S.open_arm(name, path, panel_ids, allow_no_receipt=False)
700
+ if arm["sha256"] != pa["npz_sha256"] or not arm["receipt_verified"]:
701
+ raise SystemExit(f"{name}: NPZ sha / receipt check failed for {path}")
702
+ npos = {n: i for i, n in enumerate(arm["sample_ids"])}
703
+ rws = [np.flatnonzero(arm["bulk_index"] == npos[x]) for x in v["donors"]]
704
+ sel = np.concatenate(rws)
705
+ gen_d = np.repeat(np.arange(S_), [x.size for x in rws])
706
+ if arm["sha256"] not in pcache:
707
+ rates = np.ascontiguousarray(arm["d"]["generated_counts"], dtype=np.float32)
708
+ full = F.PR.poisson_integerise(rates, seed=F.POISSON_SEED, chunk_rows=4096)
709
+ del rates
710
+ pcache[arm["sha256"]] = full[:, ref["score_idx"]].tocsr()
711
+ del full
712
+ arm["d"].close()
713
+ Xg = pcache[arm["sha256"]][sel].tocsr()
714
+ sub = np.concatenate([np.flatnonzero(gen_d == k)[F.generated_subsample(int((gen_d == k).sum()),
715
+ int(v["n_ref"][k]), v["donors"][k])]
716
+ for k in range(S_)])
717
+ Q, q_d = Xg[sub].tocsr(), gen_d[sub]
718
+ gc = pd.read_parquet(cdir / "arms" / name / "generated_cells.parquet", columns=["npz_row", "in_pc_subsample"])
719
+ same_rows = bool(np.array_equal(gc.npz_row.to_numpy(), sel)
720
+ and np.array_equal(np.flatnonzero(gc.in_pc_subsample.to_numpy()), np.sort(sub)))
721
+ if not same_rows:
722
+ raise SystemExit(f"{name}: scored rows / P/C subsample differ from {cdir}/arms/{name}/generated_cells.parquet")
723
+ pdn = per_csv[per_csv.arm == name].set_index("donor").loc[v["donors"]]
724
+ h = s["headline"][name]
725
+ expect = {"precision": h["precision"], "coverage": h["coverage"], "precision_depth_matched": h["precision_dm"],
726
+ "coverage_depth_matched": h["coverage_dm"],
727
+ "per_donor": {k: pdn[k].to_numpy() for k in ("precision", "coverage", "precision_depth_matched",
728
+ "coverage_depth_matched")}}
729
+ log(f"{name}: {path.name} sha {arm['sha256'][:12]} (receipt verified), {sel.size} scored cells, "
730
+ f"{sub.size} in the P/C subsample (same rows as the scorer)")
731
+ r, p, chk = score_set(name, v, Q, q_d, sigma_m, a.threads, expect, oos=(oos_r2[0], oos_r2[1], name))
732
+ chk["rows_and_subsample_equal_scorer"] = same_rows
733
+ chk["npz"] = {"path": str(path), "scored_path": pa["npz"], "sha256": arm["sha256"]}
734
+ rows += r
735
+ per_frames.append(p)
736
+ repro["arms"][name] = chk
737
+ QL = log1p_cp10k_sparse(Q)
738
+ en_unit(name, "pc", [R1L[i] for i in r1_split], [QL[np.flatnonzero(q_d == k)] for k in range(S_)], gram_r1,
739
+ n_rep_rows if name == "scsemi5" else None)
740
+ if not a.no_en_all:
741
+ XgL = log1p_cp10k_sparse(Xg)
742
+ en_unit(name, "all", obsL, [XgL[np.flatnonzero(gen_d == k)] for k in range(S_)], gram_obs,
743
+ n_rep_rows if name == "scsemi5" else None)
744
+ del XgL
745
+ log(f"{name} done in {time.monotonic() - t0:.0f} s")
746
+ if not (design == "fewshot" and name in ("zs_raw", "zs_pseudo")):
747
+ pcache.pop(arm["sha256"], None) # not reused by another unit
748
+ # ---------------- write
749
+ meta = {"dataset": ds, "design": design, "unit": "pooled" if draw is None else f"draw{draw}"}
750
+ met = pd.DataFrame(rows)
751
+ for k, x in reversed(list(meta.items())):
752
+ met.insert(0, k, x)
753
+ met.insert(3, "label", met["set"].map(ARM_LABEL))
754
+ met.to_csv(out / "metrics.csv", index=False)
755
+ perd = pd.concat(per_frames, ignore_index=True)
756
+ for k, x in reversed(list(meta.items())):
757
+ perd.insert(0, k, x)
758
+ perd.to_csv(out / "per_donor.csv", index=False)
759
+ en = pd.DataFrame(en_rows)
760
+ for k, x in reversed(list(meta.items())):
761
+ en.insert(0, k, x)
762
+ en.to_csv(out / "en.csv", index=False)
763
+ ep = pd.concat(en_ps, ignore_index=True)
764
+ for k, x in reversed(list(meta.items())):
765
+ ep.insert(0, k, x)
766
+ ep.to_csv(out / "en_per_sample.csv", index=False)
767
+ worst = max([c.get("abs_diff", 0.0) for arm in repro["arms"].values() for c in arm.values() if isinstance(c, dict)]
768
+ + [0.0])
769
+ repro["max_abs_diff_k10_pooled"] = worst
770
+ repro["oos_r3"] = oos_info
771
+ repro["pca_equal"] = repro["pca"]["ours"] == repro["pca"]["scorer"]
772
+ (out / "repro.json").write_text(json.dumps(repro, indent=1, default=float) + "\n")
773
+ code = {str(p): sha256(p) for p in (Path(__file__).resolve(), TOOLS / "ft_common.py", TOOLS / "score_ft.py", F.SB_PATH)}
774
+ manifest = {"schema": "paired_ft_extra_metrics.v1", **meta, "written_utc": F.now(), "command": sys.argv,
775
+ "threads": a.threads, "donors": list(map(str, v["donors"])), "n_samples": int(S_),
776
+ "calls": {str(c): {"arms": list(arms), "summary_sha256": sha256(c / "summary.json")} for c, arms in calls},
777
+ "reference_sha256": man["reference_sha256"], "bandwidth_m": sigma_m,
778
+ "params": {"seed": SEED, "ks": KS, "knn_c2st_k": KNN_C2ST_K, "rf_trees": RF_TREES, "cv_folds": CV_FOLDS,
779
+ "bw_multiples": BW_MULTIPLES, "bw_max_cells": BW_MAX_CELLS, "en_pcs": EN_PCS,
780
+ "en_lb_max_queries_all_cells": EN_LB_MAX_QUERIES, "en_all_cells": not a.no_en_all},
781
+ "n_representative_rows": n_rep_rows, "fetched_from_server2": [str(f) for f in fetched],
782
+ "code_sha256": code, "seconds": round(time.monotonic() - t_unit, 1),
783
+ "max_abs_diff_k10_pooled": worst}
784
+ (out / "manifest.json").write_text(json.dumps(manifest, indent=1, default=float) + "\n")
785
+ log(f"unit {meta['unit']} of {ds} written to {out} in {manifest['seconds']} s (k=10 max |diff| vs scorer {worst:.2e})")
786
+ for f in fetched:
787
+ if f.name.startswith("zs__raw_all") or f.name.startswith("zs__pseudo_all"):
788
+ continue # shared by the draws of the cohort; removed by main after the last draw
789
+ f.unlink(missing_ok=True)
790
+ f.with_suffix(".log").unlink(missing_ok=True)
791
+ log(f"removed fetched copy {f}")
792
+
793
+
794
+ # =========================================================================== collect
795
+ COHORT = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis", "imperial_eskd": "Imperial", "giroux2022": "Giroux",
796
+ "ji2025_chili": "Ji (whole blood)"}
797
+ # headline columns: (column in metrics.csv / en.csv, short name, better direction: +1 higher, -1 lower, 0 closer to 0.5)
798
+ HEAD = [("c2st_knn_auc", "AUC kNN", 0), ("c2st_rf_auc", "AUC RF", 0), ("nn1_acc", "1-NN acc", 0),
799
+ ("mmd2_bw1", "MMD² (σ=m)", -1), ("mmd2_sum", "MMD² (sum)", -1), ("en_all_sq", "E_N all", -1),
800
+ ("en_pc_sq", "E_N P/C cells", -1),
801
+ ("precision_k3", "P k3", 1), ("coverage_k3", "C k3", 1), ("precision_k5", "P k5", 1), ("coverage_k5", "C k5", 1),
802
+ ("precision_k10", "P k10", 1), ("coverage_k10", "C k10", 1)]
803
+ LORA = {"fewshot": "lora5", "pooled": "real_lora__raw"}
804
+ COMPARE = {"fewshot": ("scsemi5", "zs_raw", "zs_cal"), "pooled": ("zs__raw", "zs__cal", "pseudo_full__cal")}
805
+ ORDER = {"fewshot": (CONTROL, CONTROL_OOS, "zs_raw", "zs_cal", "scsemi5", "lora5", "zs_pseudo"),
806
+ "pooled": (CONTROL, CONTROL_OOS, "zs__raw", "zs__cal", "pseudo_full__cal", "real_lora__raw", "zs__pseudo")}
807
+ SIDES = (("R1", "raw", "scorer space: real side = R1 (the PCA-50 fit cells), no depth matching = the deck's precision/coverage"),
808
+ ("R1", "dm", "scorer space: real side = R1, depth matched"),
809
+ ("R2", "raw", "out-of-sample real side = R2 (same PCA-50, generated cells and subsample), no depth matching"),
810
+ ("R2", "dm", "out-of-sample real side = R2, depth matched"))
811
+
812
+
813
+ def _wide(design: str) -> pd.DataFrame:
814
+ """One row per unit x set x mode: metrics.csv joined with the E_N headline (squared L2, both cell sets)."""
815
+ glob = "*/fewshot_n5/draw*" if design == "fewshot" else "*/pooled"
816
+ mets, ens = [], []
817
+ for d in sorted(OUT_ROOT.glob(glob)):
818
+ if (d / "manifest.json").is_file():
819
+ mets.append(pd.read_csv(d / "metrics.csv"))
820
+ ens.append(pd.read_csv(d / "en.csv"))
821
+ if not mets:
822
+ return pd.DataFrame()
823
+ met, en = pd.concat(mets, ignore_index=True), pd.concat(ens, ignore_index=True)
824
+ key = ["dataset", "design", "unit", "set"]
825
+ met = met[~((met.real_side == "R2") & (met.set == CONTROL))]
826
+ e = en.pivot_table(index=key, columns=["cellset", "distance"], values="en", aggfunc="first")
827
+ e.columns = [f"en_{c}_{d}" for c, d in e.columns]
828
+ r = en[en.cellset == "all"].pivot_table(index=key, columns="distance", values="en_reps_at_lb", aggfunc="first")
829
+ r.columns = [f"en_all_{d}_reps_at_lb" for d in r.columns]
830
+ for q in ("dif_mean", "lb", "ub"):
831
+ x = en[en.distance == "sq"].pivot_table(index=key, columns="cellset", values=q, aggfunc="first")
832
+ x.columns = [f"{q}_{c}_sq" for c in x.columns]
833
+ r = r.join(x, how="outer") if len(r) else x
834
+ out = met.merge(e.reset_index(), on=key, how="left").merge(r.reset_index(), on=key, how="left")
835
+ out.loc[out.real_side == "R2", [c for c in out.columns if c.startswith("en_")]] = np.nan # E_N: one value per set
836
+ return out
837
+
838
+
839
+ def _fmt(x, sd=None, nd=3):
840
+ if x is None or (isinstance(x, float) and np.isnan(x)):
841
+ return "—"
842
+ s = f"{x:.{nd}f}" if abs(x) >= 10 ** -nd or x == 0 else f"{x:.1e}"
843
+ return s + (f" ± {sd:.{nd}f}" if sd is not None and not np.isnan(sd) else "")
844
+
845
+
846
+ def _better(a: float, b: float, sign: int) -> bool:
847
+ return (abs(a - 0.5) < abs(b - 0.5)) if sign == 0 else (a > b if sign > 0 else a < b)
848
+
849
+
850
+ def collect() -> None:
851
+ """Concatenate every unit's CSVs into scores_extra/{fewshot,pooled}_*.csv and write TABLES.md (means over the
852
+ 5 draws for the few-pair design, single pooled calls for the 5-fold design; LoRA-vs-arm win counts per draw)."""
853
+ from scipy.stats import kendalltau
854
+ lines = ["# Extra realism / diversity metrics: tables", "",
855
+ f"Written by `tools/extra_metrics.py --collect` ({F.now()}). Definitions: `README.md`.", ""]
856
+ for design in ("fewshot", "pooled"):
857
+ glob = "*/fewshot_n5/draw*" if design == "fewshot" else "*/pooled"
858
+ for name in ("metrics", "per_donor", "en", "en_per_sample"):
859
+ parts = [pd.read_csv(d / f"{name}.csv") for d in sorted(OUT_ROOT.glob(glob)) if (d / "manifest.json").is_file()]
860
+ if parts:
861
+ pd.concat(parts, ignore_index=True).to_csv(OUT_ROOT / f"{design}_{name}.csv", index=False)
862
+ rep = [json.loads((d / "repro.json").read_text()) | {"unit_dir": str(d)} for d in sorted(OUT_ROOT.glob(glob))
863
+ if (d / "manifest.json").is_file()]
864
+ if rep:
865
+ rows = []
866
+ for r in rep:
867
+ for arm, c in r["arms"].items():
868
+ rows.append({"unit_dir": r["unit_dir"], "set": arm,
869
+ **{k: (x["abs_diff"] if isinstance(x, dict) and "abs_diff" in x else x)
870
+ for k, x in c.items() if k != "npz"}})
871
+ pd.DataFrame(rows).to_csv(OUT_ROOT / f"{design}_reproduction_check.csv", index=False)
872
+ w = _wide(design)
873
+ if w.empty:
874
+ continue
875
+ w.to_csv(OUT_ROOT / f"{design}_wide.csv", index=False)
876
+ title = "(a) 5-donor few-pair design (mean ± SD over 5 draws)" if design == "fewshot" else \
877
+ "(b) 5-fold pooled design (one call over all pairs)"
878
+ for side, mode, desc in SIDES:
879
+ sub = w[(w["mode"] == mode) & (w["real_side"] == side)]
880
+ lines += [f"## {title}; {desc}", ""]
881
+ cols = [c for c in HEAD if c[0] in sub.columns and sub[c[0]].notna().any()
882
+ and not (mode == "dm" and c[0].startswith("en_"))] # E_N has no depth-matched version
883
+ lines.append("| cohort | arm | n units | " + " | ".join(c[1] for c in cols) + " |")
884
+ lines.append("|---|---|---:|" + "---:|" * len(cols))
885
+ for ds in DATASETS:
886
+ for arm in ORDER[design]:
887
+ x = sub[(sub.dataset == ds) & (sub.set == arm)]
888
+ if x.empty:
889
+ continue
890
+ vals = []
891
+ for c, _, _ in cols:
892
+ col = x[c].astype(float)
893
+ vals.append(_fmt(col.mean(), col.std(ddof=1) if design == "fewshot" and len(col) > 1 else None,
894
+ 4 if c.startswith("mmd") else 3))
895
+ lines.append(f"| {COHORT[ds]} | {ARM_LABEL.get(arm, arm)} | {len(x)} | " + " | ".join(vals) + " |")
896
+ lines.append("")
897
+ for side in ("R1", "R2"):
898
+ _wins_and_tau(lines, w, design, title, side, kendalltau)
899
+ (OUT_ROOT / "TABLES.md").write_text("\n".join(lines) + "\n")
900
+ log(f"collected -> {OUT_ROOT}/TABLES.md")
901
+
902
+
903
+ def _wins_and_tau(lines: list, w: pd.DataFrame, design: str, title: str, side: str, kendalltau) -> None:
904
+ # LoRA vs every comparator, per metric (no depth matching)
905
+ sub = w[(w["mode"] == "raw") & (w["real_side"] == side)]
906
+ lines += [f"### {title}: does LoRA beat each comparator? (real side {side}, no depth matching; "
907
+ + ("draws where LoRA is better / draws compared" if design == "fewshot" else "pooled call: ✓ / ✗")
908
+ + "; AUC and 1-NN: closer to 0.5 is better)", ""]
909
+ cols = [c for c in HEAD if c[0] in sub.columns and sub[c[0]].notna().any()]
910
+ lines.append("| cohort | LoRA vs | " + " | ".join(c[1] for c in cols) + " |")
911
+ lines.append("|---|---|" + "---:|" * len(cols))
912
+ excepts = []
913
+ for ds in DATASETS:
914
+ L = sub[(sub.dataset == ds) & (sub.set == LORA[design])].set_index("unit")
915
+ if L.empty:
916
+ continue
917
+ for comp in COMPARE[design]:
918
+ Cm = sub[(sub.dataset == ds) & (sub.set == comp)].set_index("unit")
919
+ units = sorted(set(L.index) & set(Cm.index))
920
+ if not units:
921
+ continue
922
+ cells = []
923
+ for c, short, sign in cols:
924
+ wins = sum(_better(float(L.at[u, c]), float(Cm.at[u, c]), sign) for u in units)
925
+ cells.append(f"{wins}/{len(units)}" if design == "fewshot" else ("✓" if wins else "✗"))
926
+ if wins < len(units):
927
+ excepts.append(f"{COHORT[ds]}: LoRA not better than {ARM_LABEL[comp]} on {short} in "
928
+ f"{len(units) - wins}/{len(units)} unit(s)")
929
+ lines.append(f"| {COHORT[ds]} | {ARM_LABEL[comp]} | " + " | ".join(cells) + " |")
930
+ lines += ["", "Exceptions (LoRA not better):", ""] + [f"- {e}" for e in excepts] + [""]
931
+ # agreement of each metric's arm ranking with coverage (k = 10) and precision (k = 10), per cohort (means)
932
+ lines += [f"### {title}: Kendall τ between each metric's arm ranking and the coverage / precision (k = 10) "
933
+ "ranking (arms only, control excluded; mean over units per cohort; AUC / 1-NN ranked by |x - 0.5|)", ""]
934
+ lines.append("| cohort | vs | " + " | ".join(c[1] for c in cols) + " |")
935
+ lines.append("|---|---|" + "---:|" * len(cols))
936
+ for ds in DATASETS:
937
+ x = sub[(sub.dataset == ds) & ~sub.set.isin([CONTROL, CONTROL_OOS])].groupby("set")[[c[0] for c in cols]].mean()
938
+ if side == "R2": # P/C exists only on the R1 side: take the scorer's k = 10 values from the R1 rows
939
+ pr = w[(w.dataset == ds) & (w["mode"] == "raw") & (w.real_side == "R1")].groupby("set")[
940
+ ["coverage_k10", "precision_k10"]].mean()
941
+ x = x.drop(columns=[c for c in ("coverage_k10", "precision_k10") if c in x.columns]).join(pr)
942
+ if len(x) < 3:
943
+ continue
944
+
945
+ def score(c, sign):
946
+ return -(x[c] - 0.5).abs() if sign == 0 else x[c] * sign
947
+ for ref_c in ("coverage_k10", "precision_k10"):
948
+ taus = [kendalltau(score(c, s), x[ref_c]).statistic for c, _, s in cols]
949
+ lines.append(f"| {COHORT[ds]} | {ref_c.split('_')[0]} | " + " | ".join(_fmt(t, nd=2) for t in taus) + " |")
950
+ lines.append("")
951
+
952
+
953
+ def parse(argv=None):
954
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
955
+ p.add_argument("--design", choices=["fewshot", "pooled"])
956
+ p.add_argument("--dataset", choices=DATASETS)
957
+ p.add_argument("--draws", default="0,1,2,3,4")
958
+ p.add_argument("--threads", type=int, default=7)
959
+ p.add_argument("--fetch-dir", default=None, help="where server_2 NPZ copies go (default: scratch under scores_extra)")
960
+ p.add_argument("--no-en-all", action="store_true", help="skip the all-cells E_N (P/C-cell E_N is always computed)")
961
+ p.add_argument("--force", action="store_true", help="recompute units that already have a manifest")
962
+ p.add_argument("--collect", action="store_true")
963
+ return p.parse_args(argv)
964
+
965
+
966
+ def main(argv=None) -> int:
967
+ a = parse(argv)
968
+ if a.collect:
969
+ collect()
970
+ return 0
971
+ if not (1 <= a.threads <= 8):
972
+ raise SystemExit("--threads must be 1..8")
973
+ try:
974
+ from threadpoolctl import threadpool_limits
975
+ threadpool_limits(a.threads)
976
+ except ImportError:
977
+ pass
978
+ if a.design is None or a.dataset is None:
979
+ raise SystemExit("--design and --dataset are required (or --collect)")
980
+ a.fetch_dir = a.fetch_dir or str(OUT_ROOT / "_fetch_tmp")
981
+ Path(a.fetch_dir).mkdir(parents=True, exist_ok=True)
982
+ a.pcache, a.obs_cache = {}, {}
983
+ if a.design == "pooled":
984
+ run_unit("pooled", a.dataset, None, a)
985
+ else:
986
+ for j in [int(x) for x in a.draws.split(",") if x.strip()]:
987
+ run_unit("fewshot", a.dataset, j, a)
988
+ shared = Path(a.fetch_dir) / "generated" / a.dataset / "fewshot_n5"
989
+ for f in list(shared.glob("zs__*_all.npz")) if shared.is_dir() else []:
990
+ f.unlink(missing_ok=True)
991
+ f.with_suffix(".log").unlink(missing_ok=True)
992
+ log(f"removed fetched copy {f}")
993
+ return 0
994
+
995
+
996
+ if __name__ == "__main__":
997
+ raise SystemExit(main())