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/tests/test_extra_metrics.py +215 -0
- paper-releases/pbisc-diffusion/updates/20261001T200638Z-extra-realism-metrics/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/build_archive_request.py +210 -0
- paper-releases/pbisc-diffusion/updates/20261001T200638Z-extra-realism-metrics/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/collect_extra_metrics.py +290 -0
- paper-releases/pbisc-diffusion/updates/20261001T200638Z-extra-realism-metrics/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/extra_metrics.py +849 -0
paper-releases/pbisc-diffusion/updates/20261001T200638Z-extra-realism-metrics/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tests/test_extra_metrics.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synthetic checks of tools/extra_metrics.py (CPU; ~1-2 min, the get_error comparison imports scSemiProfiler).
|
| 2 |
+
|
| 3 |
+
Run: CUDA_VISIBLE_DEVICES= OMP_NUM_THREADS=4 <cxg_corpus python> -m pytest -q tests/test_extra_metrics.py
|
| 4 |
+
|
| 5 |
+
1. Same distribution: C2ST AUC (kNN, RF) ~ 0.5, 1-NN accuracy ~ 0.5, MMD^2 ~ 0, coverage at k = 3 / 5 / 10 near
|
| 6 |
+
Naeem et al.'s E[coverage] (eq. 9), precision high.
|
| 7 |
+
2. Shifted distribution: AUC -> 1, 1-NN -> 1, MMD^2 >> 0, coverage -> 0.
|
| 8 |
+
3. Building blocks equal their definitions (brute-force NN, unbiased MMD^2 by explicit sums, sparse log1p CP10K =
|
| 9 |
+
stage_b_embed.cp10k_log1p, Gram-eigh PCA = sklearn PCA up to signs).
|
| 10 |
+
4. E_N: extra_metrics.get_error_legacy and the production path (Gram PCA + dif_sc) equal scSemiProfiler's own
|
| 11 |
+
utils.get_error on a toy project (run in the frozen scSemiProfiler runtime_env, CPU, same np.random seed).
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import subprocess
|
| 18 |
+
import sys
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 22 |
+
import numpy as np # noqa: E402
|
| 23 |
+
import pytest # noqa: E402
|
| 24 |
+
import scipy.sparse as sp # noqa: E402
|
| 25 |
+
|
| 26 |
+
TASK = Path(__file__).resolve().parents[1]
|
| 27 |
+
sys.path.insert(0, str(TASK / "tools"))
|
| 28 |
+
import extra_metrics as X # noqa: E402
|
| 29 |
+
|
| 30 |
+
SCSEMI_PY = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
|
| 31 |
+
"immicro_scsemi_comparison_20260927/runtime_env/bin/python")
|
| 32 |
+
SCSEMI_VENDOR = TASK / "scsemi/vendor/scSemiProfiler"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@pytest.fixture(scope="module")
|
| 36 |
+
def same():
|
| 37 |
+
rng = np.random.default_rng(0)
|
| 38 |
+
n, d = 2000, 50
|
| 39 |
+
return rng.normal(size=(n, d)).astype(np.float32), rng.normal(size=(n, d)).astype(np.float32)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_same_distribution(same):
|
| 43 |
+
zr, zg = same
|
| 44 |
+
knn = X.c2st_auc(zr, zg, kind="knn", n_jobs=2)["c2st_knn_auc"]
|
| 45 |
+
rf = X.c2st_auc(zr, zg, kind="rf", n_jobs=2)["c2st_rf_auc"]
|
| 46 |
+
nn1 = X.one_nn_loo(zr, zg)
|
| 47 |
+
m = X.median_bandwidth(zr)
|
| 48 |
+
mmd = X.mmd2_unbiased(zr, zg, [0.5 * m, m, 2 * m])
|
| 49 |
+
assert abs(knn - 0.5) < 0.04 and abs(rf - 0.5) < 0.04, (knn, rf)
|
| 50 |
+
assert abs(nn1["nn1_acc"] - 0.5) < 0.04, nn1
|
| 51 |
+
assert np.all(np.abs(mmd) < 2e-3), mmd
|
| 52 |
+
prec = []
|
| 53 |
+
for k in (3, 5, 10):
|
| 54 |
+
r = X.pc_at_k(zr, zg, k)
|
| 55 |
+
exp = X.expected_coverage(len(zr), len(zg), k)
|
| 56 |
+
assert abs(r["coverage"] - exp) < 0.03, (k, r["coverage"], exp)
|
| 57 |
+
assert abs(r["density"] - 1.0) < 0.15 # Naeem lemma 1: E[density] = 1
|
| 58 |
+
prec.append(r["precision"])
|
| 59 |
+
# Kynkaanniemi precision has no closed form; in 50-D it is well below 1 at small k even for identical sets
|
| 60 |
+
assert prec[0] < prec[1] < prec[2] and prec[2] > 0.8, prec
|
| 61 |
+
# Naeem eq. 9 limits: 1 - 1/2^k for M = N -> inf
|
| 62 |
+
assert abs(X.expected_coverage(10**6, 10**6, 3) - (1 - 1 / 8)) < 1e-4
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def test_shifted_distribution(same):
|
| 66 |
+
zr, zg = same
|
| 67 |
+
zs = zg + 3.0
|
| 68 |
+
assert X.c2st_auc(zr, zs, kind="knn", n_jobs=2)["c2st_knn_auc"] > 0.99
|
| 69 |
+
assert X.c2st_auc(zr, zs, kind="rf", n_jobs=2)["c2st_rf_auc"] > 0.99
|
| 70 |
+
assert X.one_nn_loo(zr, zs)["nn1_acc"] > 0.97
|
| 71 |
+
m = X.median_bandwidth(zr)
|
| 72 |
+
assert X.mmd2_unbiased(zr, zs, [m])[0] > 0.1
|
| 73 |
+
assert X.pc_at_k(zr, zs, 10)["coverage"] < 0.05
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def test_building_blocks():
|
| 77 |
+
from scipy.spatial.distance import cdist
|
| 78 |
+
rng = np.random.default_rng(1)
|
| 79 |
+
a, b = rng.normal(size=(300, 7)), rng.normal(size=(250, 7)) + 0.3
|
| 80 |
+
D = cdist(a, b, "sqeuclidean")
|
| 81 |
+
d, i = X.sqdist_min(a, b, max_block=5e3)
|
| 82 |
+
assert np.allclose(d, D.min(1)) and np.array_equal(i, D.argmin(1))
|
| 83 |
+
Daa = cdist(a, a, "sqeuclidean")
|
| 84 |
+
np.fill_diagonal(Daa, np.inf)
|
| 85 |
+
d2, i2 = X.sqdist_min(a, a, exclude_self=True, max_block=5e3)
|
| 86 |
+
assert np.allclose(d2, Daa.min(1)) and np.array_equal(i2, Daa.argmin(1))
|
| 87 |
+
# unbiased MMD^2 by explicit sums
|
| 88 |
+
s = 1.7
|
| 89 |
+
k = lambda u, v: np.exp(-cdist(u, v, "sqeuclidean") / (2 * s * s)) # noqa: E731
|
| 90 |
+
Kxx, Kyy, Kxy = k(a, a), k(b, b), k(a, b)
|
| 91 |
+
n, m = len(a), len(b)
|
| 92 |
+
want = (Kxx.sum() - np.trace(Kxx)) / (n * (n - 1)) + (Kyy.sum() - np.trace(Kyy)) / (m * (m - 1)) - 2 * Kxy.mean()
|
| 93 |
+
assert np.isclose(X.mmd2_unbiased(a, b, [s])[0], want, rtol=1e-9, atol=1e-12)
|
| 94 |
+
# sparse log1p CP10K = stage_b_embed.cp10k_log1p (dense float32), incl. an empty cell
|
| 95 |
+
C = sp.csr_matrix(rng.poisson(0.7, size=(40, 30)).astype(np.float32))
|
| 96 |
+
C[3] = 0
|
| 97 |
+
C.eliminate_zeros()
|
| 98 |
+
assert np.array_equal(X.log1p_cp10k_sparse(C).toarray(), X.F.SB.cp10k_log1p(C))
|
| 99 |
+
# Gram-eigh PCA = sklearn PCA (distances in the embedding equal; components equal up to sign)
|
| 100 |
+
from sklearn.decomposition import PCA
|
| 101 |
+
# well-separated spectrum (low rank + small noise), so the components are identifiable up to sign
|
| 102 |
+
W = rng.normal(size=(3000, 12)) * np.linspace(6, 1, 12)
|
| 103 |
+
Z = sp.csr_matrix(np.maximum(W @ rng.normal(size=(12, 120)) + 0.05 * rng.normal(size=(3000, 120)) + 8, 0)
|
| 104 |
+
.astype(np.float32))
|
| 105 |
+
g = X.Gram(120).add(Z, chunk=700)
|
| 106 |
+
mu, comps = g.pca(12)
|
| 107 |
+
e1 = X.embed(Z, mu, comps, chunk=500)
|
| 108 |
+
e2 = PCA(n_components=12, svd_solver="full").fit_transform(Z.toarray().astype(np.float64))
|
| 109 |
+
assert np.allclose(np.abs(e1), np.abs(e2), rtol=1e-4, atol=1e-3)
|
| 110 |
+
assert np.allclose(cdist(e1[:200], e1[200:400]), cdist(e2[:200], e2[200:400]), rtol=1e-5, atol=1e-3)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# ------------------------------------------------------------------ E_N vs scSemiProfiler's own get_error
|
| 114 |
+
def _toy(rng, P=6, genes=150):
|
| 115 |
+
"""P samples from three 'conditions'; representatives 0 and 3; semis of targets = their rep's cells shifted
|
| 116 |
+
towards the target (what scSemiProfiler outputs, one cell per representative cell)."""
|
| 117 |
+
prof = rng.gamma(0.5, 1.0, size=(3, genes)) + 0.02
|
| 118 |
+
gts, sids = [], []
|
| 119 |
+
for i in range(P):
|
| 120 |
+
n = int(rng.integers(300, 420))
|
| 121 |
+
p = prof[i % 3] * rng.uniform(0.8, 1.2, size=genes)
|
| 122 |
+
lib = rng.integers(800, 2000, size=n)
|
| 123 |
+
c = rng.poisson(p / p.sum() * lib[:, None])
|
| 124 |
+
gts.append(np.log1p(c / c.sum(1, keepdims=True) * 1e4).astype(np.float32))
|
| 125 |
+
sids.append(f"S{i}")
|
| 126 |
+
reps, labels = [0, 3], [0, 0, 0, 1, 1, 1]
|
| 127 |
+
semis = []
|
| 128 |
+
for i in range(P):
|
| 129 |
+
if i in reps:
|
| 130 |
+
semis.append(gts[i])
|
| 131 |
+
else:
|
| 132 |
+
r = gts[reps[labels[i]]]
|
| 133 |
+
semis.append((0.6 * r + 0.4 * gts[i].mean(0)).astype(np.float32))
|
| 134 |
+
return gts, semis, sids, reps, labels
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@pytest.mark.skipif(not SCSEMI_PY.is_file(), reason="scSemiProfiler runtime_env not on this host")
|
| 138 |
+
def test_en_matches_get_error(tmp_path):
|
| 139 |
+
rng = np.random.default_rng(7)
|
| 140 |
+
gts, semis, sids, reps, labels = _toy(rng)
|
| 141 |
+
name = tmp_path / "proj"
|
| 142 |
+
(name / "status").mkdir(parents=True)
|
| 143 |
+
(name / "inferreddata").mkdir()
|
| 144 |
+
(name / "sids.txt").write_text("\n".join(sids) + "\n")
|
| 145 |
+
(name / "status/init_representatives.txt").write_text("\n".join(map(str, reps)) + "\n")
|
| 146 |
+
(name / "status/init_cluster_labels.txt").write_text("\n".join(map(str, labels)) + "\n")
|
| 147 |
+
for i in range(len(sids)):
|
| 148 |
+
if i not in reps:
|
| 149 |
+
np.save(name / "inferreddata" / f"{sids[reps[labels[i]]]}_to_{sids[i]}.npy", semis[i])
|
| 150 |
+
np.save(tmp_path / "X.npy", np.concatenate(gts))
|
| 151 |
+
np.save(tmp_path / "sid.npy", np.repeat(np.asarray(sids), [len(g) for g in gts]))
|
| 152 |
+
seed = 20261001
|
| 153 |
+
script = f"""
|
| 154 |
+
import os, sys, json, numpy as np
|
| 155 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 156 |
+
sys.path.insert(0, {str(SCSEMI_VENDOR)!r})
|
| 157 |
+
import anndata, pandas as pd
|
| 158 |
+
from scSemiProfiler.utils import get_error
|
| 159 |
+
X = np.load({str(tmp_path / 'X.npy')!r}); sid = np.load({str(tmp_path / 'sid.npy')!r})
|
| 160 |
+
anndata.AnnData(X=X, obs=pd.DataFrame({{"sample_ids": sid}}, index=[str(i) for i in range(len(sid))])).write_h5ad({str(tmp_path / 'sc.h5ad')!r})
|
| 161 |
+
np.random.seed({seed})
|
| 162 |
+
ub, lb, se, ne = get_error({str(name)!r}, scpath={str(tmp_path / 'sc.h5ad')!r})
|
| 163 |
+
print("RESULT " + json.dumps({{"ub": float(ub[0]), "lb": float(lb[0]), "semi": float(se[0]), "naive": float(ne[0])}}))
|
| 164 |
+
"""
|
| 165 |
+
env = dict(os.environ, CUDA_VISIBLE_DEVICES="", OMP_NUM_THREADS="2", OPENBLAS_NUM_THREADS="2")
|
| 166 |
+
res = subprocess.run([str(SCSEMI_PY), "-c", script], capture_output=True, text=True, env=env, timeout=900)
|
| 167 |
+
line = [x for x in res.stdout.splitlines() if x.startswith("RESULT ")]
|
| 168 |
+
assert line, res.stdout[-2000:] + res.stderr[-3000:]
|
| 169 |
+
theirs = json.loads(line[0][7:])
|
| 170 |
+
# 1) line-by-line restatement, same global np.random stream
|
| 171 |
+
np.random.seed(seed)
|
| 172 |
+
ours = X.get_error_legacy(gts, semis, reps, labels)
|
| 173 |
+
for k_o, k_t in (("upperbound", "ub"), ("lowerbound", "lb"), ("semierror", "semi"), ("naiveerror", "naive")):
|
| 174 |
+
assert np.isclose(ours[k_o], theirs[k_t], rtol=2e-5), (k_o, ours[k_o], theirs[k_t])
|
| 175 |
+
en_theirs = (theirs["semi"] - theirs["lb"]) / (theirs["ub"] - theirs["lb"])
|
| 176 |
+
assert np.isclose(ours["en_semi"], en_theirs, rtol=1e-4)
|
| 177 |
+
# 2) production path: Gram-eigh PCA-100 on real + generated, dif_sc per sample, same LB split and UB partners
|
| 178 |
+
# as the legacy stream (fed explicitly), representatives at LB -> the same E_N as get_error
|
| 179 |
+
L_g = [sp.csr_matrix(g) for g in gts]
|
| 180 |
+
L_s = [sp.csr_matrix(s) for s in semis]
|
| 181 |
+
gram = X.Gram(gts[0].shape[1])
|
| 182 |
+
for L in L_g + L_s:
|
| 183 |
+
gram.add(L)
|
| 184 |
+
mu, comps = gram.pca(100)
|
| 185 |
+
eg, es = [X.embed(L, mu, comps) for L in L_g], [X.embed(L, mu, comps) for L in L_s]
|
| 186 |
+
np.random.seed(seed)
|
| 187 |
+
Z = np.vstack(eg + es)
|
| 188 |
+
perm = np.arange(len(Z))
|
| 189 |
+
np.random.shuffle(perm) # same draws as np.random.shuffle on the matrix rows
|
| 190 |
+
h = len(Z) // 2
|
| 191 |
+
a, b = Z[perm[:h]], Z[perm[h:]]
|
| 192 |
+
lb = float(np.r_[X.sqdist_min(a, b)[0], X.sqdist_min(b, a)[0]].mean())
|
| 193 |
+
ub = float(np.mean([X.dif_sc(eg[i], eg[np.random.randint(0, len(eg))])["sq"] for i in range(len(eg))]))
|
| 194 |
+
semi = np.mean([lb if i in reps else X.dif_sc(eg[i], es[i])["sq"] for i in range(len(eg))])
|
| 195 |
+
assert np.isclose(lb, theirs["lb"], rtol=2e-5) and np.isclose(ub, theirs["ub"], rtol=2e-5)
|
| 196 |
+
assert np.isclose((semi - lb) / (ub - lb), en_theirs, rtol=1e-4)
|
| 197 |
+
# 3) the production en_from_embeddings arithmetic (no representatives, own rng) on the same embedding
|
| 198 |
+
t = [i for i in range(len(eg)) if i not in reps]
|
| 199 |
+
r = X.en_from_embeddings([eg[i] for i in t], [es[i] for i in t], np.random.default_rng(0), lb_max_queries=None,
|
| 200 |
+
Z_all=Z)
|
| 201 |
+
d = np.asarray([X.dif_sc(eg[i], es[i])["sq"] for i in t])
|
| 202 |
+
assert np.allclose(r["sq"]["dif_i"], d)
|
| 203 |
+
assert np.isclose(r["sq"]["en"], (d.mean() - r["sq"]["lb"]) / (r["sq"]["ub"] - r["sq"]["lb"]))
|
| 204 |
+
# scSemiProfiler's convention (representatives at LB) = ours x n_targets / P, with the same LB / UB
|
| 205 |
+
conv = ((d.sum() + len(reps) * r["sq"]["lb"]) / len(eg) - r["sq"]["lb"]) / (r["sq"]["ub"] - r["sq"]["lb"])
|
| 206 |
+
assert np.isclose(conv, r["sq"]["en"] * len(t) / len(eg))
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def test_lower_bound_estimate_unbiased():
|
| 210 |
+
rng = np.random.default_rng(3)
|
| 211 |
+
Z = rng.normal(size=(6000, 10))
|
| 212 |
+
exact = X.lower_bound(Z, np.random.default_rng(5), None)
|
| 213 |
+
est = X.lower_bound(Z, np.random.default_rng(5), 1500)
|
| 214 |
+
assert exact["exact"] and not est["exact"]
|
| 215 |
+
assert abs(est["sq"] / exact["sq"] - 1) < 0.03
|
paper-releases/pbisc-diffusion/updates/20261001T200638Z-extra-realism-metrics/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/build_archive_request.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Archive-maintenance request for the paired fine-tuning benchmark (PBISC-Diffusion paper, pbisc-diffusion).
|
| 3 |
+
|
| 4 |
+
Follows paper-release-20260928/maintenance/POLICY.md: every payload is listed explicitly (host, exact path, kind,
|
| 5 |
+
state); generated arrays are not payloads but inference locations with their receipts; work that is still running
|
| 6 |
+
(the scSemiProfiler baseline) is registered as running/planned locations only.
|
| 7 |
+
|
| 8 |
+
Payloads (completed): code, documents, figures and their source CSVs, score tables, paired-data manifests and
|
| 9 |
+
small data (features, pairs, folds, splits, cell metadata), the condition NPZs every sampler read, run receipts
|
| 10 |
+
(RUN.json / history.json, which carry every fine-tuned checkpoint's sha256), queues, and the recommended-protocol
|
| 11 |
+
LoRA checkpoints (all-training-donor LoRA per fold, and the 5-pair LoRA per draw) on both hosts.
|
| 12 |
+
Not uploaded (location/provenance only): other fine-tuned checkpoints (sha256 in their RUN.json), the per-cell
|
| 13 |
+
count arrays cells_panel6k.npz / cells_full.npz (sha256 in BUILD.json / MANIFEST.json; rebuilt from the datalake
|
| 14 |
+
processing outputs), generated NPZs.
|
| 15 |
+
usage: build_archive_request.py OUT.json
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import glob
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
import subprocess
|
| 23 |
+
import sys
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
T = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
|
| 27 |
+
DATASETS = ("immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def files(patterns, root=T):
|
| 31 |
+
out = []
|
| 32 |
+
for p in patterns:
|
| 33 |
+
for f in sorted(glob.glob(str(root / p), recursive=True)):
|
| 34 |
+
q = Path(f)
|
| 35 |
+
if q.is_file() and not q.is_symlink() and "__pycache__" not in q.parts and not q.name.endswith((".bak", ".pyc")) \
|
| 36 |
+
and ".bak_" not in q.name:
|
| 37 |
+
out.append(str(q))
|
| 38 |
+
return sorted(set(out))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def remote_files(patterns):
|
| 42 |
+
cmd = "cd %s && for p in %s; do ls -1d $p 2>/dev/null; done; true" % (T, " ".join(patterns))
|
| 43 |
+
res = subprocess.run(["ssh", "-n", "spark-0110", cmd], capture_output=True, text=True, check=True)
|
| 44 |
+
return sorted({str(T / l.strip()) for l in res.stdout.splitlines() if l.strip()})
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def remote_json(path):
|
| 48 |
+
res = subprocess.run(["ssh", "-n", "spark-0110", f"cat '{path}'"], capture_output=True, text=True)
|
| 49 |
+
return json.loads(res.stdout) if res.returncode == 0 and res.stdout.strip() else None
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def main(out: str) -> int:
|
| 53 |
+
assets = []
|
| 54 |
+
|
| 55 |
+
def add(paths, kind, host="server_1", state="completed"):
|
| 56 |
+
for p in paths:
|
| 57 |
+
assets.append({"host": host, "source": p, "kind": kind, "state": state})
|
| 58 |
+
|
| 59 |
+
add(files(["tools/*.py", "tools/*.sh", "tests/*.py", "figures/make_figures.py",
|
| 60 |
+
"scsemi/tools/*.py", "scsemi/tools/*.sh", "scsemi/tests/*.py"]), "code")
|
| 61 |
+
add(files(["README.md", "FEASIBILITY.md", "figures/FIGURES.md", "scsemi/README.md",
|
| 62 |
+
"data/*/QC_REPORT.md"]), "document")
|
| 63 |
+
add(files(["figures/*.png", "figures/*.pdf"]), "figure")
|
| 64 |
+
add(files(["figures/source_data/**/*.csv"]), "table")
|
| 65 |
+
add(files(["scores/*/*/summary.json", "scores/*/*/per_donor.csv", "scores/*/*/contrast.csv", "scores/*/*/README.md",
|
| 66 |
+
"scores/*/fewshot_n5/*/summary.json", "scores/*/fewshot_n5/*/per_donor.csv",
|
| 67 |
+
"scores/*/fewshot_n5/*/contrast.csv", "scores/*/fewshot_n5/*/README.md",
|
| 68 |
+
"scores/*/AGGREGATE.md", "scores/*/aggregate.json",
|
| 69 |
+
"scores/*/fewshot_n5/AGGREGATE.md", "scores/*/fewshot_n5/aggregate.json"]), "table")
|
| 70 |
+
# 2026-10-01: Giroux sex-linked-gene rescoring (scores_nosex, chrY-only sensitivity scores_nochrY) and its gene list
|
| 71 |
+
add(files([f"{d}/{p}" for d in ("scores_nosex", "scores_nochrY")
|
| 72 |
+
for p in ("README.md", "**/summary.json", "**/per_donor.csv", "**/contrast.csv", "**/README.md")]), "table")
|
| 73 |
+
add(files(["data/sex_linked_genes/*.csv", "data/sex_linked_genes/*.md", # BUILD.json is caught by data/*/BUILD.json
|
| 74 |
+
"data/sex_linked_genes/sources/*.txt", "data/sex_linked_genes/sources/README*"]), "metadata")
|
| 75 |
+
# 2026-10-01 LoRA rank sweep (r4/r64) and equal-pair-budget calibration: per-fold and pooled scores + comparison tables
|
| 76 |
+
add(files([f"scores/*/{d}/*/{p}" for d in ("lora_rank_20261001", "cal_budget_20261001")
|
| 77 |
+
for p in ("summary.json", "per_donor.csv", "contrast.csv", "README.md")]), "table")
|
| 78 |
+
add(files(["scores/*/rankcal_20261001.md", "scores/*/rankcal_20261001.json"]), "table")
|
| 79 |
+
# 2026-10-02 extra realism/diversity metrics (classifier AUC, 1-NN, MMD2, scSemiProfiler E_N, k = 3/5/10 P/C)
|
| 80 |
+
add(files(["scores_extra/**/*.csv", "scores_extra/**/*.json", "scores_extra/**/*.md"]), "table")
|
| 81 |
+
add(files(["scores_extra/_code/*.py"]), "code")
|
| 82 |
+
add(files(["logs/extraA_*.log", "logs/extraA_*.jobs", "logs/extraB_*.log", "logs/extraB_*.jobs"]), "log")
|
| 83 |
+
# equal-pair-budget calibration (alpha fitted on each lora_n<n> run's own pairs)
|
| 84 |
+
add(files(["data/*/fold*/alpha_n*.npy"]), "data")
|
| 85 |
+
add(files(["data/*/CAL_BUDGET.json"]), "metadata")
|
| 86 |
+
add(files(["data/*/features.npz", "data/*/cells_obs.parquet", "data/*/fold*/alpha.npy",
|
| 87 |
+
"data/*/fewshot_n5/draw*/alpha.npy"]), "data")
|
| 88 |
+
add(files(["data/*/pairs.csv", "data/*/folds.csv", "data/*/samples.csv", "data/*/identity_*.csv",
|
| 89 |
+
"data/*/pairs_sensitivity_offday.csv", "data/*/MANIFEST.json", "data/*/PREPARE.json",
|
| 90 |
+
"data/*/BUILD.json", "data/*/cells_full.BUILD.json", "data/*/fewshot_n5/DRAWS.json",
|
| 91 |
+
"data/*/fewshot_n5/draw*/*.txt"]), "metadata")
|
| 92 |
+
add(files(["data/*/conditions_*.npz", "data/*/fold*/*.npz", "data/*/fewshot_n5/*.npz",
|
| 93 |
+
"data/*/fewshot_n5/draw*/*.npz"]), "condition")
|
| 94 |
+
add(files(["runs/**/RUN.json", "runs/**/history.json"]), "log")
|
| 95 |
+
# server_2 ran its own copies of the scSemiProfiler queues (some exist only there): keep them as the as-run record
|
| 96 |
+
subprocess.run(["rsync", "-a", f"spark-0110:{T}/scsemi/queues/", f"{T}/scsemi/queues/as_run_server2/",
|
| 97 |
+
"--include=server2_*.txt", "--exclude=*"], check=True)
|
| 98 |
+
add(files(["queues/*.txt", "scsemi/queues/*.txt", "scsemi/queues/as_run_server2/*.txt",
|
| 99 |
+
"scsemi/vendor/compatibility.patch",
|
| 100 |
+
"scsemi/vendor/source_manifest.json"]), "config")
|
| 101 |
+
# recommended protocol weights (LoRA merged into the base weights): server_1 datasets here, Imperial on server_2
|
| 102 |
+
add(files(["runs/*/fold*/real_lora/checkpoint_ft.pt", "runs/*/fewshot_n5/draw*/lora/checkpoint_ft.pt"]), "checkpoint")
|
| 103 |
+
add(remote_files(["runs/imperial_eskd/fold*/real_lora/checkpoint_ft.pt",
|
| 104 |
+
"runs/imperial_eskd/fewshot_n5/draw*/lora/checkpoint_ft.pt"]), "checkpoint", host="server_2")
|
| 105 |
+
add(remote_files(["runs/imperial_eskd/*/*/RUN.json", "runs/imperial_eskd/*/*/history.json",
|
| 106 |
+
"runs/imperial_eskd/fewshot_n5/*/*/RUN.json", "runs/imperial_eskd/fewshot_n5/*/*/history.json"]),
|
| 107 |
+
"log", host="server_2")
|
| 108 |
+
|
| 109 |
+
# ---- inference locations (not payloads) ------------------------------------------------------------------------
|
| 110 |
+
locs = []
|
| 111 |
+
|
| 112 |
+
def receipt_fields(rec: dict | None) -> dict:
|
| 113 |
+
if not rec:
|
| 114 |
+
return {}
|
| 115 |
+
keep = {}
|
| 116 |
+
for k in ("output_sha256", "checkpoint", "checkpoint_sha256", "input_condition_path", "input_condition_sha256",
|
| 117 |
+
"condition_npz", "condition_sha256", "seed", "steps", "generated_counts_rows"):
|
| 118 |
+
if k in rec and not isinstance(rec[k], (dict, list)):
|
| 119 |
+
keep[k] = rec[k]
|
| 120 |
+
if "output_sha256" in keep:
|
| 121 |
+
keep["sha256"] = keep["output_sha256"]
|
| 122 |
+
return keep
|
| 123 |
+
|
| 124 |
+
def loc(host, npz, experiment, cohort, rec=None, state="completed"):
|
| 125 |
+
rpath = npz[:-4] + ".log"
|
| 126 |
+
item = {"host": host, "path": npz, "state": state, "experiment": experiment, "cohort": cohort,
|
| 127 |
+
"artifact_role": "inference_output"}
|
| 128 |
+
if state in ("completed", "final"):
|
| 129 |
+
item["receipt"] = rpath
|
| 130 |
+
item.update(receipt_fields(rec))
|
| 131 |
+
locs.append(item)
|
| 132 |
+
|
| 133 |
+
for ds in DATASETS:
|
| 134 |
+
# present on server_1
|
| 135 |
+
for npz in files([f"generated/{ds}/**/*.npz"]):
|
| 136 |
+
rel = Path(npz).relative_to(T / "generated" / ds)
|
| 137 |
+
rp = Path(npz[:-4] + ".log")
|
| 138 |
+
rec = json.loads(rp.read_text()) if rp.is_file() and rp.stat().st_size else None
|
| 139 |
+
if rec is None:
|
| 140 |
+
continue
|
| 141 |
+
loc("server_1", npz, f"paired_finetune_{rel.parts[0]}", ds, rec)
|
| 142 |
+
# moved to server_2 (sha-verified move; .moved marker kept on server_1)
|
| 143 |
+
for mk in files([f"generated/{ds}/**/*.moved"]):
|
| 144 |
+
npz = mk[:-6] + ".npz"
|
| 145 |
+
rp = Path(mk[:-6] + ".log")
|
| 146 |
+
rec = json.loads(rp.read_text()) if rp.is_file() and rp.stat().st_size else None
|
| 147 |
+
rel = Path(npz).relative_to(T / "generated" / ds)
|
| 148 |
+
item_state = "completed" if rec else "presence_only"
|
| 149 |
+
loc("server_2", npz, f"paired_finetune_{rel.parts[0]}", ds, rec, state=item_state)
|
| 150 |
+
locs[-1]["move_marker_server_1"] = mk
|
| 151 |
+
# Imperial outputs live on server_2
|
| 152 |
+
for npz in remote_files(["generated/imperial_eskd/*/*.npz", "generated/imperial_eskd/fewshot_n5/*/*.npz",
|
| 153 |
+
"generated/imperial_eskd/pooled/*.npz"]):
|
| 154 |
+
rec = remote_json(npz[:-4] + ".log")
|
| 155 |
+
if rec is None:
|
| 156 |
+
continue
|
| 157 |
+
rel = Path(npz).relative_to(T / "generated" / "imperial_eskd")
|
| 158 |
+
loc("server_2", npz, f"paired_finetune_{rel.parts[0]}", "imperial_eskd", rec)
|
| 159 |
+
# scSemiProfiler draws of the other datasets that ran on server_2 (queues server2_*.txt)
|
| 160 |
+
for npz in remote_files([f"generated/{ds}/fewshot_n5/draw*/scsemi5__raw.npz" for ds in DATASETS
|
| 161 |
+
if ds != "imperial_eskd"]):
|
| 162 |
+
rec = remote_json(npz[:-4] + ".log")
|
| 163 |
+
if rec is None:
|
| 164 |
+
continue
|
| 165 |
+
rel = Path(npz).relative_to(T / "generated")
|
| 166 |
+
loc("server_2", npz, "paired_finetune_fewshot_n5", rel.parts[0], rec)
|
| 167 |
+
# scSemiProfiler baseline still running: register in-progress / planned draws by their future output path
|
| 168 |
+
done = {l["path"] for l in locs}
|
| 169 |
+
run_queues = [T / "scsemi" / "queues" / "server1_fewshot_d0first.txt"] + \
|
| 170 |
+
sorted((T / "scsemi" / "queues" / "as_run_server2").glob("server2_*.txt"))
|
| 171 |
+
for qf in run_queues:
|
| 172 |
+
host = "server_1" if qf.name.startswith("server1_") else "server_2"
|
| 173 |
+
for line in qf.read_text().splitlines():
|
| 174 |
+
if not line.startswith("fewshot|"):
|
| 175 |
+
continue
|
| 176 |
+
_, ds, j = line.split("|")[:3]
|
| 177 |
+
npz = str(T / "generated" / ds / "fewshot_n5" / f"draw{j}" / "scsemi5__raw.npz")
|
| 178 |
+
if npz in done:
|
| 179 |
+
continue
|
| 180 |
+
state = "planned"
|
| 181 |
+
locs.append({"host": host, "path": npz, "state": state, "experiment": "paired_finetune_fewshot_n5_scsemiprofiler",
|
| 182 |
+
"cohort": ds, "artifact_role": "inference_output",
|
| 183 |
+
"note": "scSemiProfiler 5-pair baseline queued or running on this host at request time"})
|
| 184 |
+
done.add(npz)
|
| 185 |
+
req = {
|
| 186 |
+
"project_id": "pbisc-diffusion",
|
| 187 |
+
"summary": (
|
| 188 |
+
"Within-dataset paired fine-tuning benchmark of the final 6k 1x E16 model (plans/paired_finetune_intradataset_20260927): "
|
| 189 |
+
"LoRA (recommended protocol), full and condition-encoder fine-tuning, sc-only control, LoRA learning curve, "
|
| 190 |
+
"K-augmentation null, 5-pair deployment scenario, on ImMicro, Ye 2026 sepsis, Imperial ESKD COVID, Giroux 2022 and "
|
| 191 |
+
"Ji 2025 (whole-blood bulk); scores (scANVI composition, precision/coverage, contrast logFC r, top-50 DEG), figures, "
|
| 192 |
+
"paired-data manifests, conditions, run receipts and the recommended-protocol LoRA checkpoints. The scSemiProfiler "
|
| 193 |
+
"5-pair baseline: every finished draw is included as score tables and a completed location; draws not yet "
|
| 194 |
+
"finished at request time (none on 2026-09-30: 25/25 done) are planned locations. Not uploaded: per-cell count "
|
| 195 |
+
"arrays and non-recommended fine-tuned checkpoints (sha256 recorded in BUILD/MANIFEST and RUN.json)."),
|
| 196 |
+
"assets": assets,
|
| 197 |
+
"inference_locations": locs,
|
| 198 |
+
}
|
| 199 |
+
Path(out).write_text(json.dumps(req, indent=1))
|
| 200 |
+
kinds = {}
|
| 201 |
+
for a in assets:
|
| 202 |
+
kinds[(a["host"], a["kind"])] = kinds.get((a["host"], a["kind"]), 0) + 1
|
| 203 |
+
print(json.dumps({"assets": len(assets), "by_host_kind": {f"{h}/{k}": v for (h, k), v in sorted(kinds.items())},
|
| 204 |
+
"locations": len(locs), "location_states": {s: sum(l["state"] == s for l in locs) for s in {l["state"] for l in locs}}},
|
| 205 |
+
indent=1))
|
| 206 |
+
return 0
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
if __name__ == "__main__":
|
| 210 |
+
sys.exit(main(sys.argv[1]))
|
paper-releases/pbisc-diffusion/updates/20261001T200638Z-extra-realism-metrics/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/collect_extra_metrics.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Collect the per-unit outputs of tools/extra_metrics.py into scores_extra/*.csv and scores_extra/TABLES.md.
|
| 3 |
+
|
| 4 |
+
CPU, pandas only (no torch, no CUDA, no heavy imports). usage: collect_extra_metrics.py
|
| 5 |
+
|
| 6 |
+
Files written (scores_extra/):
|
| 7 |
+
{fewshot,pooled}_{metrics,per_donor,en,en_per_sample}.csv every unit's CSV, concatenated
|
| 8 |
+
{fewshot,pooled}_wide.csv one row per unit x set x real_side x mode, with the E_N headline columns
|
| 9 |
+
{fewshot,pooled}_headline.csv per cohort x arm (few-pair: mean, SD, n over draws) of the headline metrics
|
| 10 |
+
{fewshot,pooled}_reproduction_check.csv k = 10 precision / coverage recomputed vs score_ft.py, per unit and set
|
| 11 |
+
run_time.csv seconds per unit (manifest.json)
|
| 12 |
+
TABLES.md headline tables, all-variant tables, LoRA win counts, Kendall tau
|
| 13 |
+
|
| 14 |
+
Headline metric spaces (README.md): classifier AUCs, 1-NN accuracy and MMD^2 from the out-of-sample real side (R2;
|
| 15 |
+
control row = R2 vs R3); precision / coverage at k = 3 / 5 / 10 from the scorer's space (R1; control = R1 vs R2);
|
| 16 |
+
E_N = scSemiProfiler's metric on all cells, squared L2 (control = within-sample half split). E_N is undefined when
|
| 17 |
+
the arm's own upper bound does not exceed its lower bound (UB <= LB): such units are left out of the means (count
|
| 18 |
+
shown as "†n") and rank last in the win counts.
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import json
|
| 23 |
+
from datetime import datetime, timezone
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import pandas as pd
|
| 28 |
+
from scipy.stats import kendalltau
|
| 29 |
+
|
| 30 |
+
TASK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
|
| 31 |
+
OUT = TASK / "scores_extra"
|
| 32 |
+
DATASETS = ("immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
|
| 33 |
+
COHORT = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis", "imperial_eskd": "Imperial", "giroux2022": "Giroux",
|
| 34 |
+
"ji2025_chili": "Ji (whole blood)"}
|
| 35 |
+
CONTROL, CONTROL_OOS = "real_R2", "real_R3"
|
| 36 |
+
LABEL = {"zs_raw": "Zero-shot, real bulk", "zs__raw": "Zero-shot, real bulk",
|
| 37 |
+
"zs_cal": "Zero-shot + calibration", "zs__cal": "Zero-shot + calibration",
|
| 38 |
+
"scsemi5": "scSemiProfiler, 5 donors", "lora5": "LoRA, 5 donors",
|
| 39 |
+
"real_lora__raw": "LoRA, all training pairs", "pseudo_full__cal": "sc-only fine-tune (+ calibration)",
|
| 40 |
+
"zs_pseudo": "Zero-shot, sc pseudobulk input (ref.)", "zs__pseudo": "Zero-shot, sc pseudobulk input (ref.)",
|
| 41 |
+
CONTROL: "Real vs real control (R1 vs R2)", CONTROL_OOS: "Real vs real control (R2 vs R3)", "control": "Real vs real control"}
|
| 42 |
+
ARMS = {"fewshot": ("zs_raw", "zs_cal", "scsemi5", "lora5", "zs_pseudo"),
|
| 43 |
+
"pooled": ("zs__raw", "zs__cal", "pseudo_full__cal", "real_lora__raw", "zs__pseudo")}
|
| 44 |
+
LORA = {"fewshot": "lora5", "pooled": "real_lora__raw"}
|
| 45 |
+
COMPARE = {"fewshot": ("scsemi5", "zs_raw", "zs_cal"), "pooled": ("zs__raw", "zs__cal", "pseudo_full__cal")}
|
| 46 |
+
# (column, short name, direction: +1 higher better, -1 lower better, 0 closer to 0.5 better, space)
|
| 47 |
+
TWO = [("c2st_knn_auc", "AUC kNN", 0), ("c2st_rf_auc", "AUC RF", 0), ("nn1_acc", "1-NN acc", 0),
|
| 48 |
+
("mmd2_bw1", "MMD² (σ=m)", -1), ("mmd2_sum", "MMD² (σ sum)", -1)]
|
| 49 |
+
ENC = [("en_all_sq", "E_N (all cells)", -1), ("en_pc_sq", "E_N (P/C cells)", -1)]
|
| 50 |
+
PC = [(f"{q}_k{k}", f"{q[0].upper()} k{k}", 1) for k in (3, 5, 10) for q in ("precision", "coverage")]
|
| 51 |
+
HEADLINE = [(c, n, s, "R2") for c, n, s in TWO] + [(ENC[0][0], ENC[0][1], -1, "EN")] + [(c, n, s, "R1") for c, n, s in PC]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def now() -> str:
|
| 55 |
+
return datetime.now(timezone.utc).isoformat()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def units(design: str) -> list[Path]:
|
| 59 |
+
glob = "*/fewshot_n5/draw*" if design == "fewshot" else "*/pooled"
|
| 60 |
+
return [d for d in sorted(OUT.glob(glob)) if (d / "manifest.json").is_file()]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def wide(design: str) -> pd.DataFrame:
|
| 64 |
+
us = units(design)
|
| 65 |
+
if not us:
|
| 66 |
+
return pd.DataFrame()
|
| 67 |
+
met = pd.concat([pd.read_csv(d / "metrics.csv") for d in us], ignore_index=True)
|
| 68 |
+
en = pd.concat([pd.read_csv(d / "en.csv") for d in us], ignore_index=True)
|
| 69 |
+
en["bounds_ok"] = en.ub > en.lb
|
| 70 |
+
key = ["dataset", "design", "unit", "set"]
|
| 71 |
+
parts = []
|
| 72 |
+
for val, name in (("en", "en"), ("bounds_ok", "en_ok"), ("dif_mean", "dif"), ("lb", "lb"), ("ub", "ub"),
|
| 73 |
+
("en_reps_at_lb", "en_reps_at_lb")):
|
| 74 |
+
x = en.pivot_table(index=key, columns=["cellset", "distance"], values=val, aggfunc="first")
|
| 75 |
+
x.columns = [f"{name}_{c}_{d}" for c, d in x.columns]
|
| 76 |
+
parts.append(x)
|
| 77 |
+
e = pd.concat(parts, axis=1).reset_index()
|
| 78 |
+
w = met.merge(e, on=key, how="left")
|
| 79 |
+
w.loc[w.real_side == "R2", [c for c in e.columns if c not in key]] = np.nan # E_N: one value per set (R1 rows)
|
| 80 |
+
return w
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def en_rank_value(row, col: str) -> float:
|
| 84 |
+
"""E_N for ranking: +inf when undefined (UB <= LB), the value otherwise."""
|
| 85 |
+
ok = row.get(col.replace("en_", "en_ok_"), True)
|
| 86 |
+
return float(row[col]) if (ok is True or ok == 1.0) else np.inf
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def cell_stats(x: pd.DataFrame, col: str) -> tuple:
|
| 90 |
+
v = x[col].astype(float)
|
| 91 |
+
bad = 0
|
| 92 |
+
if col.startswith("en_") and col.replace("en_", "en_ok_") in x.columns:
|
| 93 |
+
ok = x[col.replace("en_", "en_ok_")].astype(bool)
|
| 94 |
+
bad = int((~ok).sum())
|
| 95 |
+
v = v[ok]
|
| 96 |
+
return (v.mean() if len(v) else np.nan, v.std(ddof=1) if len(v) > 1 else np.nan, len(v), bad)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def fmt(m, sd=np.nan, bad=0, nd=3, show_sd=True) -> str:
|
| 100 |
+
if m is None or (isinstance(m, float) and np.isnan(m)):
|
| 101 |
+
s = "—"
|
| 102 |
+
else:
|
| 103 |
+
s = f"{m:.{nd}f}" if (abs(m) >= 10 ** -nd or m == 0) else f"{m:.1e}"
|
| 104 |
+
if show_sd and not np.isnan(sd):
|
| 105 |
+
s += f" ± {sd:.{nd}f}"
|
| 106 |
+
return s + (f" †{bad}" if bad else "")
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def better(a: float, b: float, sign: int) -> bool:
|
| 110 |
+
return (abs(a - 0.5) < abs(b - 0.5)) if sign == 0 else (a > b if sign > 0 else a < b)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def pick(w: pd.DataFrame, ds: str, s: str, space: str) -> pd.DataFrame:
|
| 114 |
+
"""Rows of one cohort x set in the metric's headline space (no depth matching)."""
|
| 115 |
+
side = "R2" if space == "R2" else "R1"
|
| 116 |
+
if s == "control":
|
| 117 |
+
s = CONTROL_OOS if space == "R2" else CONTROL
|
| 118 |
+
return w[(w.dataset == ds) & (w.set == s) & (w["mode"] == "raw") & (w.real_side == side)]
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def headline(w: pd.DataFrame, design: str) -> tuple[pd.DataFrame, list]:
|
| 122 |
+
rows, lines = [], []
|
| 123 |
+
sd = design == "fewshot"
|
| 124 |
+
lines.append("| cohort | arm | " + " | ".join(n for _, n, _, _ in HEADLINE) + " |")
|
| 125 |
+
lines.append("|---|---|" + "---:|" * len(HEADLINE))
|
| 126 |
+
for ds in DATASETS:
|
| 127 |
+
if not (w.dataset == ds).any():
|
| 128 |
+
continue
|
| 129 |
+
for s in ("control",) + ARMS[design]:
|
| 130 |
+
cells, rec = [], {"dataset": ds, "set": s, "label": LABEL[s]}
|
| 131 |
+
for c, n, _, space in HEADLINE:
|
| 132 |
+
x = pick(w, ds, s, space)
|
| 133 |
+
if x.empty or c not in x.columns:
|
| 134 |
+
cells.append("—")
|
| 135 |
+
continue
|
| 136 |
+
m, v, k, bad = cell_stats(x, c)
|
| 137 |
+
rec.update({c: m, f"{c}_sd": v, f"{c}_n": k, f"{c}_undefined": bad})
|
| 138 |
+
cells.append(fmt(m, v, bad, 4 if c.startswith("mmd") else 3, sd))
|
| 139 |
+
rows.append(rec)
|
| 140 |
+
name = f"**{LABEL[s]}**" if s == LORA[design] else LABEL[s]
|
| 141 |
+
lines.append(f"| {COHORT[ds]} | {name} | " + " | ".join(cells) + " |")
|
| 142 |
+
return pd.DataFrame(rows), lines
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def wins(w: pd.DataFrame, design: str) -> tuple[list, list]:
|
| 146 |
+
cols = HEADLINE + [(ENC[1][0], ENC[1][1], -1, "EN")]
|
| 147 |
+
lines = ["| cohort | LoRA vs | " + " | ".join(n for _, n, _, _ in cols) + " |", "|---|---|" + "---:|" * len(cols)]
|
| 148 |
+
exc = []
|
| 149 |
+
for ds in DATASETS:
|
| 150 |
+
for comp in COMPARE[design]:
|
| 151 |
+
cells, any_ = [], False
|
| 152 |
+
for c, n, sgn, space in cols:
|
| 153 |
+
L = pick(w, ds, LORA[design], space).set_index("unit")
|
| 154 |
+
C = pick(w, ds, comp, space).set_index("unit")
|
| 155 |
+
us = sorted(set(L.index) & set(C.index))
|
| 156 |
+
if not us or c not in L.columns:
|
| 157 |
+
cells.append("—")
|
| 158 |
+
continue
|
| 159 |
+
any_ = True
|
| 160 |
+
if c.startswith("en_"):
|
| 161 |
+
pairs = [(en_rank_value(L.loc[u], c), en_rank_value(C.loc[u], c)) for u in us]
|
| 162 |
+
k = sum(a < b for a, b in pairs)
|
| 163 |
+
tie = sum(a == b for a, b in pairs)
|
| 164 |
+
else:
|
| 165 |
+
pairs = [(float(L.at[u, c]), float(C.at[u, c])) for u in us]
|
| 166 |
+
k = sum(better(a, b, sgn) for a, b in pairs)
|
| 167 |
+
tie = sum(a == b for a, b in pairs)
|
| 168 |
+
tt = f" ({tie} tie)" if tie else ""
|
| 169 |
+
cells.append(f"{k}/{len(us)}{tt}" if design == "fewshot" else ("✓" if k else ("tie" if tie else "✗")))
|
| 170 |
+
if k + tie < len(us):
|
| 171 |
+
exc.append(f"{COHORT[ds]}: LoRA worse than {LABEL[comp]} on {n} in {len(us) - k - tie}/{len(us)} "
|
| 172 |
+
f"{'draws' if design == 'fewshot' else 'pooled call'}{tt}")
|
| 173 |
+
if any_:
|
| 174 |
+
lines.append(f"| {COHORT[ds]} | {LABEL[comp]} | " + " | ".join(cells) + " |")
|
| 175 |
+
return lines, exc
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def taus(w: pd.DataFrame, design: str) -> list:
|
| 179 |
+
"""Kendall tau over the arms (control excluded) of each metric's cohort-mean ranking vs coverage / precision k10."""
|
| 180 |
+
cols = HEADLINE + [(ENC[1][0], ENC[1][1], -1, "EN")]
|
| 181 |
+
lines = ["| cohort | vs | " + " | ".join(n for _, n, _, _ in cols) + " |", "|---|---|" + "---:|" * len(cols)]
|
| 182 |
+
for ds in DATASETS:
|
| 183 |
+
if not (w.dataset == ds).any():
|
| 184 |
+
continue
|
| 185 |
+
score = {}
|
| 186 |
+
for s in ARMS[design]:
|
| 187 |
+
score[s] = {}
|
| 188 |
+
for c, _, sgn, space in cols:
|
| 189 |
+
x = pick(w, ds, s, space)
|
| 190 |
+
if x.empty:
|
| 191 |
+
continue
|
| 192 |
+
if c.startswith("en_"):
|
| 193 |
+
vals = [en_rank_value(r, c) for _, r in x.iterrows()]
|
| 194 |
+
score[s][c] = -np.median(vals) # median: robust to an undefined unit (+inf)
|
| 195 |
+
else:
|
| 196 |
+
m = x[c].astype(float).mean()
|
| 197 |
+
score[s][c] = -abs(m - 0.5) if sgn == 0 else sgn * m
|
| 198 |
+
S = pd.DataFrame(score).T
|
| 199 |
+
for ref in ("coverage_k10", "precision_k10"):
|
| 200 |
+
t = [kendalltau(S[c], S[ref]).statistic if c in S else np.nan for c, _, _, _ in cols]
|
| 201 |
+
lines.append(f"| {COHORT[ds]} | {ref.split('_')[0]} k10 | " + " | ".join(fmt(x, nd=2) for x in t) + " |")
|
| 202 |
+
return lines
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def variant_tables(w: pd.DataFrame, design: str) -> list:
|
| 206 |
+
lines = []
|
| 207 |
+
sd = design == "fewshot"
|
| 208 |
+
for side, mode in (("R1", "raw"), ("R1", "dm"), ("R2", "raw"), ("R2", "dm")):
|
| 209 |
+
sub = w[(w.real_side == side) & (w["mode"] == mode)]
|
| 210 |
+
cols = TWO + ([] if side == "R2" else PC) + (ENC if (side == "R1" and mode == "raw") else [])
|
| 211 |
+
lines += [f"#### real side {side}, {'no depth matching' if mode == 'raw' else 'depth matched'}", "",
|
| 212 |
+
"| cohort | set | " + " | ".join(n for _, n, _ in cols) + " |", "|---|---|" + "---:|" * len(cols)]
|
| 213 |
+
for ds in DATASETS:
|
| 214 |
+
for s in ((CONTROL,) if side == "R1" else (CONTROL_OOS,)) + ARMS[design]:
|
| 215 |
+
x = sub[(sub.dataset == ds) & (sub.set == s)]
|
| 216 |
+
if x.empty:
|
| 217 |
+
continue
|
| 218 |
+
cells = []
|
| 219 |
+
for c, _, _ in cols:
|
| 220 |
+
m, v, _, bad = cell_stats(x, c)
|
| 221 |
+
cells.append(fmt(m, v, bad, 4 if c.startswith("mmd") else 3, sd))
|
| 222 |
+
lines.append(f"| {COHORT[ds]} | {LABEL[s]} | " + " | ".join(cells) + " |")
|
| 223 |
+
lines.append("")
|
| 224 |
+
return lines
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def main() -> int:
|
| 228 |
+
md = ["# Extra realism / diversity metrics: tables", "",
|
| 229 |
+
f"Written by `tools/collect_extra_metrics.py` ({now()}). Definitions, parameters and citations: `README.md`.", "",
|
| 230 |
+
"Headline spaces: AUC (5-fold CV), 1-NN accuracy and MMD² use the **out-of-sample real side R2** (same PCA-50, "
|
| 231 |
+
"generated cells, subsample as the scorer; control row = R2 vs R3); precision (P) / coverage (C) are the "
|
| 232 |
+
"scorer's own (real side R1; control row = R1 vs R2); E_N = scSemiProfiler's normalized error on all cells, "
|
| 233 |
+
"squared L2 (control row = within-sample half split). AUC / 1-NN: 0.5 is ideal. † n = units where E_N is "
|
| 234 |
+
"undefined (the arm's UB ≤ LB), left out of the mean. No depth matching in the headline tables.", ""]
|
| 235 |
+
times = []
|
| 236 |
+
for design in ("fewshot", "pooled"):
|
| 237 |
+
us = units(design)
|
| 238 |
+
if not us:
|
| 239 |
+
continue
|
| 240 |
+
for name in ("metrics", "per_donor", "en", "en_per_sample"):
|
| 241 |
+
pd.concat([pd.read_csv(d / f"{name}.csv") for d in us], ignore_index=True).to_csv(
|
| 242 |
+
OUT / f"{design}_{name}.csv", index=False)
|
| 243 |
+
rep = []
|
| 244 |
+
for d in us:
|
| 245 |
+
r = json.loads((d / "repro.json").read_text())
|
| 246 |
+
m = json.loads((d / "manifest.json").read_text())
|
| 247 |
+
times.append({"dataset": m["dataset"], "design": design, "unit": m["unit"], "n_samples": m["n_samples"],
|
| 248 |
+
"seconds": m["seconds"], "threads": m["threads"]})
|
| 249 |
+
for arm, c in r["arms"].items():
|
| 250 |
+
rep.append({"dataset": m["dataset"], "unit": m["unit"], "set": arm,
|
| 251 |
+
**{k: (x["abs_diff"] if isinstance(x, dict) and "abs_diff" in x else x)
|
| 252 |
+
for k, x in c.items() if k != "npz"}})
|
| 253 |
+
rp = pd.DataFrame(rep)
|
| 254 |
+
rp.to_csv(OUT / f"{design}_reproduction_check.csv", index=False)
|
| 255 |
+
w = wide(design)
|
| 256 |
+
w.to_csv(OUT / f"{design}_wide.csv", index=False)
|
| 257 |
+
title = ("(a) 5-donor few-pair design: mean ± SD over the 5 draws" if design == "fewshot"
|
| 258 |
+
else "(b) 5-fold pooled design: one scoring call over all cross-fitted pairs")
|
| 259 |
+
hl, lines = headline(w, design)
|
| 260 |
+
hl.to_csv(OUT / f"{design}_headline.csv", index=False)
|
| 261 |
+
num = [c for c in rp.columns if c not in ("dataset", "unit", "set", "rows_and_subsample_equal_scorer")]
|
| 262 |
+
same = rp["rows_and_subsample_equal_scorer"].dropna().astype(bool).all() \
|
| 263 |
+
if "rows_and_subsample_equal_scorer" in rp else True
|
| 264 |
+
md += [f"## {title}", "", f"Units: {len(us)}. k = 10 reproduction: max |diff| vs score_ft.py = "
|
| 265 |
+
f"{np.nanmax(rp[num].to_numpy(dtype=float)):.1e} over {len(rp)} unit × set rows (pooled and per donor, "
|
| 266 |
+
f"raw and depth matched); scored rows and P/C subsample identical in every arm: {bool(same)}.", ""]
|
| 267 |
+
md += lines + [""]
|
| 268 |
+
wl, exc = wins(w, design)
|
| 269 |
+
md += [f"### {title}: is LoRA better than each comparator? "
|
| 270 |
+
+ ("(draws where LoRA is better / draws)" if design == "fewshot" else "(✓ better / ✗ not)"), ""] + wl
|
| 271 |
+
md += ["", "Exceptions (LoRA worse; ties are not counted as worse):", ""] + ([f"- {e}" for e in exc] or ["- none"]) + [""]
|
| 272 |
+
md += [f"### {title}: Kendall τ of each metric's arm ranking with the coverage / precision (k = 10) ranking "
|
| 273 |
+
"(arms only; few-pair: means over draws, E_N medians)", ""] + taus(w, design) + [""]
|
| 274 |
+
md += [f"### {title}: every variant (real side R1 / R2, raw / depth matched)", ""] + variant_tables(w, design)
|
| 275 |
+
pd.DataFrame(times).to_csv(OUT / "run_time.csv", index=False)
|
| 276 |
+
if times:
|
| 277 |
+
t = pd.DataFrame(times)
|
| 278 |
+
md += ["## Run time per unit (seconds; server_1 CPU, few-pair 6 threads, pooled 8 threads)", "",
|
| 279 |
+
"| design | cohort | units | samples per unit | mean s | min s | max s |", "|---|---|---:|---:|---:|---:|---:|"]
|
| 280 |
+
for (dz, ds), x in t.groupby(["design", "dataset"], sort=False):
|
| 281 |
+
md.append(f"| {dz} | {COHORT[ds]} | {len(x)} | {int(x.n_samples.median())} | {x.seconds.mean():.0f} | "
|
| 282 |
+
f"{x.seconds.min():.0f} | {x.seconds.max():.0f} |")
|
| 283 |
+
md.append("")
|
| 284 |
+
(OUT / "TABLES.md").write_text("\n".join(md) + "\n")
|
| 285 |
+
print(f"collected -> {OUT / 'TABLES.md'}")
|
| 286 |
+
return 0
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
if __name__ == "__main__":
|
| 290 |
+
raise SystemExit(main())
|
paper-releases/pbisc-diffusion/updates/20261001T200638Z-extra-realism-metrics/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/extra_metrics.py
ADDED
|
@@ -0,0 +1,849 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
CODE_FILES = (Path(__file__).resolve(), TOOLS / "ft_common.py", TOOLS / "score_ft.py", F.SB_PATH)
|
| 77 |
+
OUT_ROOT = TASK / "scores_extra"
|
| 78 |
+
REMOTE = "spark-0110"
|
| 79 |
+
MIN_FREE_GIB = 40.0
|
| 80 |
+
|
| 81 |
+
SEED = 20261001 # every new random stream of this file (CV folds, RF, bandwidth subsample, E_N)
|
| 82 |
+
KS = (3, 5, 10)
|
| 83 |
+
KNN_C2ST_K = 5 # sklearn default, scDiffusion's kNN classifier
|
| 84 |
+
RF_TREES = 300 # scGAN: fully grown trees, max_features = sqrt; 300 instead of 1000 trees (cost)
|
| 85 |
+
CV_FOLDS = 5 # scGAN: five-fold cross-validation, equal real / generated counts
|
| 86 |
+
BW_MULTIPLES = (0.5, 1.0, 2.0) # scGAN: sigma in {m/2, m, 2m}
|
| 87 |
+
BW_MAX_CELLS = 4000 # R1 cells used for the median pairwise distance
|
| 88 |
+
EN_PCS = 100 # scSemiProfiler: PCA to 100 dimensions
|
| 89 |
+
EN_LB_MAX_QUERIES = 20000 # all-cells E_N: LB estimated from this many query cells per direction (index = full half)
|
| 90 |
+
EN_CHUNK = 8192
|
| 91 |
+
|
| 92 |
+
FEW_ARMS = ("zs_raw", "zs_cal", "scsemi5", "lora5", "zs_pseudo")
|
| 93 |
+
POOLED_ARMS = ("zs__raw", "zs__cal", "pseudo_full__cal", "real_lora__raw", "zs__pseudo")
|
| 94 |
+
CONTROL = "real_R2" # R1 vs R2 (P/C cells) / within-sample half split (all cells)
|
| 95 |
+
CONTROL_OOS = "real_R3" # out-of-sample real side: R2' vs R3 (families 1-2)
|
| 96 |
+
ARM_LABEL = {"zs_raw": "Zero-shot, real bulk", "zs__raw": "Zero-shot, real bulk",
|
| 97 |
+
"zs_cal": "Zero-shot + calibration", "zs__cal": "Zero-shot + calibration",
|
| 98 |
+
"scsemi5": "scSemiProfiler, 5 donors", "lora5": "LoRA, 5 donors",
|
| 99 |
+
"real_lora__raw": "LoRA, all training pairs", "pseudo_full__cal": "sc-only fine-tune (+ calibration)",
|
| 100 |
+
"zs_pseudo": "Zero-shot, sc pseudobulk input (reference)",
|
| 101 |
+
"zs__pseudo": "Zero-shot, sc pseudobulk input (reference)",
|
| 102 |
+
CONTROL: "Real vs real control (held-out real cells)",
|
| 103 |
+
CONTROL_OOS: "Real vs real control (out-of-sample: R2 vs R3)"}
|
| 104 |
+
DATASETS = ("immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def log(msg: str) -> None:
|
| 108 |
+
F.log(msg)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
# =========================================================================== pure metric functions
|
| 112 |
+
def sqdist_min(Q: np.ndarray, X: np.ndarray, *, exclude_self: bool = False, max_block: float = 1.5e8) -> tuple:
|
| 113 |
+
"""For every row of Q: the minimum squared L2 distance to the rows of X and its index (brute force, float64,
|
| 114 |
+
chunked BLAS). exclude_self: Q is X and the diagonal is skipped (leave-one-out)."""
|
| 115 |
+
Q = np.ascontiguousarray(Q, dtype=np.float64)
|
| 116 |
+
X = np.ascontiguousarray(X, dtype=np.float64)
|
| 117 |
+
xx = np.einsum("ij,ij->i", X, X)
|
| 118 |
+
qq = np.einsum("ij,ij->i", Q, Q)
|
| 119 |
+
out = np.empty(Q.shape[0])
|
| 120 |
+
arg = np.empty(Q.shape[0], dtype=np.int64)
|
| 121 |
+
chunk = max(16, int(max_block // max(X.shape[0], 1)))
|
| 122 |
+
for s in range(0, Q.shape[0], chunk):
|
| 123 |
+
e = min(s + chunk, Q.shape[0])
|
| 124 |
+
D = qq[s:e, None] + xx[None, :] - 2.0 * (Q[s:e] @ X.T)
|
| 125 |
+
if exclude_self:
|
| 126 |
+
D[np.arange(e - s), np.arange(s, e)] = np.inf
|
| 127 |
+
a = np.argmin(D, axis=1)
|
| 128 |
+
arg[s:e] = a
|
| 129 |
+
out[s:e] = np.maximum(D[np.arange(e - s), a], 0.0)
|
| 130 |
+
return out, arg
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def one_nn_loo(zr: np.ndarray, zg: np.ndarray) -> dict:
|
| 134 |
+
"""Leave-one-out 1-NN two-sample accuracy (Lopez-Paz & Oquab 2017; scLDM eq. 32): pool both sets, predict each
|
| 135 |
+
point's label by its nearest other point; 0.5 = indistinguishable, 1 = separable."""
|
| 136 |
+
Z = np.vstack([zr, zg])
|
| 137 |
+
y = np.r_[np.ones(len(zr), bool), np.zeros(len(zg), bool)]
|
| 138 |
+
_, a = sqdist_min(Z, Z, exclude_self=True)
|
| 139 |
+
ok = y[a] == y
|
| 140 |
+
return {"nn1_acc": float(ok.mean()), "nn1_acc_real": float(ok[y].mean()), "nn1_acc_gen": float(ok[~y].mean())}
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def c2st_auc(zr: np.ndarray, zg: np.ndarray, *, kind: str, seed: int = SEED, n_jobs: int = 1) -> dict:
|
| 144 |
+
"""Classifier two-sample test: stratified 5-fold CV ROC AUC of real (1) vs generated (0); mean and SD over folds."""
|
| 145 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 146 |
+
from sklearn.metrics import roc_auc_score
|
| 147 |
+
from sklearn.model_selection import StratifiedKFold
|
| 148 |
+
from sklearn.neighbors import KNeighborsClassifier
|
| 149 |
+
Z = np.vstack([zr, zg]).astype(np.float32)
|
| 150 |
+
y = np.r_[np.ones(len(zr), np.int8), np.zeros(len(zg), np.int8)]
|
| 151 |
+
aucs = []
|
| 152 |
+
for tr, te in StratifiedKFold(CV_FOLDS, shuffle=True, random_state=seed).split(Z, y):
|
| 153 |
+
if kind == "knn":
|
| 154 |
+
clf = KNeighborsClassifier(n_neighbors=KNN_C2ST_K, n_jobs=n_jobs)
|
| 155 |
+
elif kind == "rf":
|
| 156 |
+
clf = RandomForestClassifier(n_estimators=RF_TREES, max_features="sqrt", n_jobs=n_jobs, random_state=seed)
|
| 157 |
+
else:
|
| 158 |
+
raise ValueError(kind)
|
| 159 |
+
clf.fit(Z[tr], y[tr])
|
| 160 |
+
p = clf.predict_proba(Z[te])[:, list(clf.classes_).index(1)]
|
| 161 |
+
aucs.append(roc_auc_score(y[te], p))
|
| 162 |
+
return {f"c2st_{kind}_auc": float(np.mean(aucs)), f"c2st_{kind}_auc_sd": float(np.std(aucs, ddof=1))}
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def median_bandwidth(z: np.ndarray, *, seed: int = SEED, max_cells: int = BW_MAX_CELLS) -> float:
|
| 166 |
+
"""Median heuristic (Gretton et al. 2012): median pairwise Euclidean distance among (<= max_cells) real cells."""
|
| 167 |
+
rng = np.random.default_rng(seed)
|
| 168 |
+
idx = np.sort(rng.choice(len(z), size=min(max_cells, len(z)), replace=False))
|
| 169 |
+
x = np.asarray(z[idx], np.float64)
|
| 170 |
+
sq = np.einsum("ij,ij->i", x, x)
|
| 171 |
+
D = np.maximum(sq[:, None] + sq[None, :] - 2 * x @ x.T, 0.0)
|
| 172 |
+
iu = np.triu_indices(len(x), 1)
|
| 173 |
+
return float(np.sqrt(np.median(D[iu])))
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _kernel_sums(A: np.ndarray, B: np.ndarray, sigmas, same: bool, max_block: float = 6e7) -> np.ndarray:
|
| 177 |
+
"""sum over pairs of exp(-||a - b||^2 / (2 sigma^2)) for every sigma (diagonal excluded when same)."""
|
| 178 |
+
A = np.ascontiguousarray(A, np.float64)
|
| 179 |
+
B = np.ascontiguousarray(B, np.float64)
|
| 180 |
+
aa, bb = np.einsum("ij,ij->i", A, A), np.einsum("ij,ij->i", B, B)
|
| 181 |
+
g = np.asarray([1.0 / (2.0 * s * s) for s in sigmas])
|
| 182 |
+
tot = np.zeros(len(sigmas))
|
| 183 |
+
chunk = max(16, int(max_block // max(len(B), 1)))
|
| 184 |
+
for s in range(0, len(A), chunk):
|
| 185 |
+
e = min(s + chunk, len(A))
|
| 186 |
+
D = np.maximum(aa[s:e, None] + bb[None, :] - 2.0 * (A[s:e] @ B.T), 0.0)
|
| 187 |
+
for i, gi in enumerate(g):
|
| 188 |
+
K = np.exp(-gi * D)
|
| 189 |
+
if same:
|
| 190 |
+
K[np.arange(e - s), np.arange(s, e)] = 0.0
|
| 191 |
+
tot[i] += K.sum()
|
| 192 |
+
return tot
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def mmd2_unbiased(zr: np.ndarray, zg: np.ndarray, sigmas) -> np.ndarray:
|
| 196 |
+
"""Unbiased MMD^2 (Gretton et al. 2012, eq. 3) with Gaussian RBF k(x, y) = exp(-||x - y||^2 / (2 sigma^2)), one value
|
| 197 |
+
per sigma; the kernel sum over the sigmas (scGAN's multi-scale kernel) is the sum of the per-sigma values."""
|
| 198 |
+
n, m = len(zr), len(zg)
|
| 199 |
+
kxx = _kernel_sums(zr, zr, sigmas, True) / (n * (n - 1))
|
| 200 |
+
kyy = _kernel_sums(zg, zg, sigmas, True) / (m * (m - 1))
|
| 201 |
+
kxy = _kernel_sums(zr, zg, sigmas, False) / (n * m)
|
| 202 |
+
return kxx + kyy - 2.0 * kxy
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def pc_at_k(zr: np.ndarray, zg: np.ndarray, k: int) -> dict:
|
| 206 |
+
"""Kynkaanniemi precision and Naeem coverage / density with k-NN balls of the real set: the scorer's own
|
| 207 |
+
stage_b_embed functions (knn_radius, precision_coverage). density is rescaled from SB's fixed k = 10 to k."""
|
| 208 |
+
radius = F.SB.knn_radius(zr, k)
|
| 209 |
+
r = F.SB.precision_coverage(zr, radius, zg)
|
| 210 |
+
r["density"] = r["density"] * F.K_NN / k
|
| 211 |
+
return r
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def expected_coverage(n_real: int, n_gen: int, k: int) -> float:
|
| 215 |
+
"""Naeem et al. 2020, eq. 9: E[coverage] for identical real and fake distributions."""
|
| 216 |
+
num = np.prod([(n_real - i) for i in range(1, k + 1)], dtype=np.float64)
|
| 217 |
+
den = np.prod([(n_gen + n_real - i) for i in range(1, k + 1)], dtype=np.float64)
|
| 218 |
+
return float(1.0 - num / den)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def two_sample_block(zr: np.ndarray, zg: np.ndarray, sigma_m: float, *, n_jobs: int, rf: bool = True) -> dict:
|
| 222 |
+
out = {}
|
| 223 |
+
out.update(c2st_auc(zr, zg, kind="knn", n_jobs=n_jobs))
|
| 224 |
+
if rf:
|
| 225 |
+
out.update(c2st_auc(zr, zg, kind="rf", n_jobs=n_jobs))
|
| 226 |
+
out.update(one_nn_loo(zr, zg))
|
| 227 |
+
sig = [m * sigma_m for m in BW_MULTIPLES]
|
| 228 |
+
mm = mmd2_unbiased(zr, zg, sig)
|
| 229 |
+
for mult, val in zip(BW_MULTIPLES, mm):
|
| 230 |
+
out[f"mmd2_bw{mult:g}"] = float(val)
|
| 231 |
+
out["mmd2_sum"] = float(mm.sum())
|
| 232 |
+
out["mmd_bandwidth_m"] = float(sigma_m)
|
| 233 |
+
return out
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
# =========================================================================== scSemiProfiler E_N
|
| 237 |
+
def log1p_cp10k_sparse(X: sp.csr_matrix) -> sp.csr_matrix:
|
| 238 |
+
"""SB.cp10k_log1p (per-cell CP10K over the columns, log1p; empty cells stay zero) kept sparse, float32."""
|
| 239 |
+
X = X.tocsr().astype(np.float64)
|
| 240 |
+
lib = np.asarray(X.sum(axis=1)).ravel()
|
| 241 |
+
D = (sp.diags(np.divide(F.CP10K, lib, out=np.zeros_like(lib), where=lib > 0)) @ X).tocsr()
|
| 242 |
+
D.data = np.log1p(D.data)
|
| 243 |
+
return D.astype(np.float32)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class Gram:
|
| 247 |
+
"""Running X^T X, column sums and row count of log1p-CP10K features (float64), for an exact PCA by eigh of the
|
| 248 |
+
covariance (the solver sklearn's PCA calls covariance_eigh; equal to the full-SVD PCA up to component signs)."""
|
| 249 |
+
|
| 250 |
+
def __init__(self, p: int):
|
| 251 |
+
self.G = np.zeros((p, p))
|
| 252 |
+
self.s = np.zeros(p)
|
| 253 |
+
self.n = 0
|
| 254 |
+
|
| 255 |
+
def add(self, L: sp.csr_matrix, chunk: int = EN_CHUNK) -> "Gram":
|
| 256 |
+
for a in range(0, L.shape[0], chunk):
|
| 257 |
+
B = L[a:a + chunk].toarray() # float32 (log1p CP10K)
|
| 258 |
+
self.G += (B.T @ B).astype(np.float64) # sgemm within a chunk, float64 across chunks
|
| 259 |
+
self.s += B.sum(0, dtype=np.float64)
|
| 260 |
+
self.n += B.shape[0]
|
| 261 |
+
return self
|
| 262 |
+
|
| 263 |
+
def __add__(self, other: "Gram") -> "Gram":
|
| 264 |
+
g = Gram(len(self.s))
|
| 265 |
+
g.G, g.s, g.n = self.G + other.G, self.s + other.s, self.n + other.n
|
| 266 |
+
return g
|
| 267 |
+
|
| 268 |
+
def pca(self, n_comp: int = EN_PCS) -> tuple[np.ndarray, np.ndarray]:
|
| 269 |
+
from scipy.linalg import eigh
|
| 270 |
+
p = len(self.s)
|
| 271 |
+
n_comp = int(min(n_comp, p, self.n - 1))
|
| 272 |
+
mu = self.s / self.n
|
| 273 |
+
C = (self.G - self.n * np.outer(mu, mu)) / (self.n - 1)
|
| 274 |
+
w, V = eigh(C, subset_by_index=[p - n_comp, p - 1])
|
| 275 |
+
return mu, np.ascontiguousarray(V[:, ::-1].T) # components x genes, descending variance
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def embed(L: sp.csr_matrix, mu: np.ndarray, comps: np.ndarray, chunk: int = EN_CHUNK) -> np.ndarray:
|
| 279 |
+
"""(x - mu) @ comps.T for sparse features x (dense row chunks, float64 BLAS)."""
|
| 280 |
+
out = np.empty((L.shape[0], comps.shape[0]))
|
| 281 |
+
for a in range(0, L.shape[0], chunk):
|
| 282 |
+
out[a:a + chunk] = (L[a:a + chunk].toarray().astype(np.float64) - mu) @ comps.T
|
| 283 |
+
return out
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def dif_sc(a: np.ndarray, b: np.ndarray) -> dict:
|
| 287 |
+
"""scSemiProfiler eq. 17 with K = 1: mean over the cells of both samples of the distance to the nearest cell of the
|
| 288 |
+
other sample. 'sq' = squared L2 (their code: faiss IndexFlatL2), 'l2' = L2 (their text)."""
|
| 289 |
+
da, _ = sqdist_min(a, b)
|
| 290 |
+
db, _ = sqdist_min(b, a)
|
| 291 |
+
n = len(a) + len(b)
|
| 292 |
+
return {"sq": float((da.sum() + db.sum()) / n), "l2": float((np.sqrt(da).sum() + np.sqrt(db).sum()) / n)}
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def lower_bound(Z: np.ndarray, rng: np.random.Generator, max_queries: int | None) -> dict:
|
| 296 |
+
"""LB: random half split of the whole PCA matrix (real + generated), symmetric 1-NN (their code: shuffle, first
|
| 297 |
+
n//2 rows vs the rest). With max_queries, each direction averages max_queries random query cells of one half
|
| 298 |
+
against the complete other half (an unbiased estimate of the same mean)."""
|
| 299 |
+
perm = rng.permutation(len(Z))
|
| 300 |
+
h = len(Z) // 2
|
| 301 |
+
A, B = Z[perm[:h]], Z[perm[h:]]
|
| 302 |
+
qa = A if (max_queries is None or len(A) <= max_queries) else A[np.sort(rng.choice(len(A), max_queries, replace=False))]
|
| 303 |
+
qb = B if (max_queries is None or len(B) <= max_queries) else B[np.sort(rng.choice(len(B), max_queries, replace=False))]
|
| 304 |
+
da, _ = sqdist_min(qa, B)
|
| 305 |
+
db, _ = sqdist_min(qb, A)
|
| 306 |
+
exact = len(qa) == len(A) and len(qb) == len(B)
|
| 307 |
+
if exact: # their arithmetic: mean over the concatenated distances of both directions
|
| 308 |
+
sq = float((da.sum() + db.sum()) / (len(da) + len(db)))
|
| 309 |
+
l2 = float((np.sqrt(da).sum() + np.sqrt(db).sum()) / (len(da) + len(db)))
|
| 310 |
+
else: # same weights as the exact concatenation (|A| and |B| cells), each direction estimated
|
| 311 |
+
wa, wb = len(A) / (len(A) + len(B)), len(B) / (len(A) + len(B))
|
| 312 |
+
sq = float(wa * da.mean() + wb * db.mean())
|
| 313 |
+
l2 = float(wa * np.sqrt(da).mean() + wb * np.sqrt(db).mean())
|
| 314 |
+
return {"sq": sq, "l2": l2, "exact": exact, "n_queries": [int(len(qa)), int(len(qb))], "n_half": [int(len(A)), int(len(B))]}
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def en_from_embeddings(gts: list, semis: list, rng: np.random.Generator, *, lb_max_queries: int | None,
|
| 318 |
+
Z_all: np.ndarray) -> dict:
|
| 319 |
+
"""E_N for one arm from per-sample embeddings (PCA already fitted on real + generated together).
|
| 320 |
+
UB: per sample i a uniformly random partner j != i (real cells of both), Dif averaged over samples.
|
| 321 |
+
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)."""
|
| 322 |
+
P = len(gts)
|
| 323 |
+
lb = lower_bound(Z_all, rng, lb_max_queries)
|
| 324 |
+
partner = (np.arange(P) + rng.integers(1, P, size=P)) % P if P > 1 else np.zeros(P, int)
|
| 325 |
+
ub_i = [dif_sc(gts[i], gts[partner[i]]) for i in range(P)]
|
| 326 |
+
dif_i = [dif_sc(gts[i], semis[i]) for i in range(P)]
|
| 327 |
+
out = {"lb": lb, "partner": partner.tolist(), "per_sample": []}
|
| 328 |
+
for d in ("sq", "l2"):
|
| 329 |
+
ub = float(np.mean([u[d] for u in ub_i]))
|
| 330 |
+
dif = np.asarray([x[d] for x in dif_i])
|
| 331 |
+
out[d] = {"lb": lb[d], "ub": ub, "dif_mean": float(dif.mean()), "en": float((dif.mean() - lb[d]) / (ub - lb[d])),
|
| 332 |
+
"en_i": ((dif - lb[d]) / (ub - lb[d])).tolist(), "dif_i": dif.tolist()}
|
| 333 |
+
return out
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def get_error_legacy(gts: list, semis: list, representatives: list, cluster_labels: list, n_comp: int = EN_PCS) -> dict:
|
| 337 |
+
"""Line-by-line re-statement of scSemiProfiler utils.get_error for one round (global np.random state, sklearn PCA,
|
| 338 |
+
self-pairing allowed in the UB, representatives at LB, squared L2). Only for the equivalence test."""
|
| 339 |
+
from sklearn.decomposition import PCA
|
| 340 |
+
P = len(gts)
|
| 341 |
+
X = np.concatenate([np.concatenate(gts, 0), np.concatenate(semis, 0)], 0)
|
| 342 |
+
Xr = PCA(n_components=n_comp).fit_transform(X)
|
| 343 |
+
xg, xs, off = [], [], 0
|
| 344 |
+
for g in gts:
|
| 345 |
+
xg.append(Xr[off:off + len(g)])
|
| 346 |
+
off += len(g)
|
| 347 |
+
for s in semis:
|
| 348 |
+
xs.append(Xr[off:off + len(s)])
|
| 349 |
+
off += len(s)
|
| 350 |
+
lbgt = Xr.copy()
|
| 351 |
+
np.random.shuffle(lbgt)
|
| 352 |
+
h = lbgt.shape[0] // 2
|
| 353 |
+
a, b = lbgt[:h], lbgt[h:]
|
| 354 |
+
da, _ = sqdist_min(a, b)
|
| 355 |
+
db, _ = sqdist_min(b, a)
|
| 356 |
+
lb = float(np.r_[da, db].mean())
|
| 357 |
+
ubs = []
|
| 358 |
+
for i in range(P):
|
| 359 |
+
r = np.random.randint(0, P)
|
| 360 |
+
ubs.append(dif_sc(xg[i], xg[r])["sq"])
|
| 361 |
+
ub = float(np.mean(ubs))
|
| 362 |
+
semi = [lb if i in representatives else dif_sc(xg[i], xs[i])["sq"] for i in range(P)]
|
| 363 |
+
naive = [lb if i in representatives else dif_sc(xg[i], xg[representatives[cluster_labels[i]]])["sq"] for i in range(P)]
|
| 364 |
+
return {"upperbound": ub, "lowerbound": lb, "semierror": float(np.mean(semi)), "naiveerror": float(np.mean(naive)),
|
| 365 |
+
"en_semi": (float(np.mean(semi)) - lb) / (ub - lb)}
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
# =========================================================================== unit inputs
|
| 369 |
+
def sha256(path: Path) -> str:
|
| 370 |
+
h = hashlib.sha256()
|
| 371 |
+
with open(path, "rb") as fh:
|
| 372 |
+
for block in iter(lambda: fh.read(1 << 24), b""):
|
| 373 |
+
h.update(block)
|
| 374 |
+
return h.hexdigest()
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def free_gib(path: Path) -> float:
|
| 378 |
+
st = os.statvfs(path)
|
| 379 |
+
return st.f_bavail * st.f_frsize / 2**30
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def resolve_npz(path: Path, want_sha: str, fetch_root: Path, fetched: list) -> Path:
|
| 383 |
+
"""The scored NPZ: the local file if present, else a sha-checked copy from server_2 (same path) under fetch_root,
|
| 384 |
+
with its receipt (.log) next to it so score_ft.open_arm can check output_sha256."""
|
| 385 |
+
path = Path(path)
|
| 386 |
+
if path.is_file():
|
| 387 |
+
return path
|
| 388 |
+
rel = path.relative_to(TASK)
|
| 389 |
+
dst = fetch_root / rel
|
| 390 |
+
marker = path.with_suffix(".moved")
|
| 391 |
+
if dst.is_file() and dst.with_suffix(".log").is_file():
|
| 392 |
+
if sha256(dst) == want_sha:
|
| 393 |
+
return dst
|
| 394 |
+
dst.unlink()
|
| 395 |
+
size = int(subprocess.run(["ssh", "-n", REMOTE, f"stat -c %s '{path}'"], capture_output=True, text=True,
|
| 396 |
+
check=True).stdout.strip())
|
| 397 |
+
need = size / 2**30 + MIN_FREE_GIB
|
| 398 |
+
if free_gib(fetch_root) < need:
|
| 399 |
+
raise SystemExit(f"disk: {free_gib(fetch_root):.1f} GiB free < {need:.1f} GiB needed to fetch {path}")
|
| 400 |
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
| 401 |
+
log(f"fetching {rel} ({size / 2**30:.2f} GiB) from {REMOTE}")
|
| 402 |
+
subprocess.run(["rsync", "-a", "--bwlimit=200000", f"{REMOTE}:{path}", str(dst)], check=True)
|
| 403 |
+
rec = path.with_suffix(".log")
|
| 404 |
+
if rec.is_file():
|
| 405 |
+
shutil.copy2(rec, dst.with_suffix(".log"))
|
| 406 |
+
else:
|
| 407 |
+
subprocess.run(["rsync", "-a", f"{REMOTE}:{rec}", str(dst.with_suffix(".log"))], check=True)
|
| 408 |
+
fetched.append(dst)
|
| 409 |
+
got = sha256(dst)
|
| 410 |
+
if got != want_sha:
|
| 411 |
+
raise SystemExit(f"{dst}: sha {got[:12]} differs from the scored NPZ sha {want_sha[:12]}")
|
| 412 |
+
if marker.is_file():
|
| 413 |
+
txt = marker.read_text()
|
| 414 |
+
if f"sha {want_sha[:12]}" not in txt:
|
| 415 |
+
raise SystemExit(f"{marker}: marker sha differs ({txt.strip()})")
|
| 416 |
+
return dst
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def unit_calls(design: str, ds: str, draw: int | None) -> list[tuple[Path, tuple]]:
|
| 420 |
+
if design == "fewshot":
|
| 421 |
+
base = SCORES / ds / "fewshot_n5"
|
| 422 |
+
return [(base / f"draw{draw}", ("zs_raw", "zs_cal", "lora5", "zs_pseudo")), (base / f"draw{draw}_scsemi5", ("scsemi5",))]
|
| 423 |
+
if design == "pooled":
|
| 424 |
+
return [(SCORES / ds / "pooled", POOLED_ARMS)]
|
| 425 |
+
raise ValueError(design)
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def unit_dir(design: str, ds: str, draw: int | None) -> Path:
|
| 429 |
+
return OUT_ROOT / ds / (f"fewshot_n5/draw{draw}" if design == "fewshot" else "pooled")
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def observed_cells(spec, ref: dict, man: dict, donors: np.ndarray, cache: dict) -> tuple[list, dict]:
|
| 433 |
+
"""All observed QC cells of the scored samples on the scoring genes (counts), per sample in the reference's
|
| 434 |
+
canonical cell order, from the same files the reference was built from (inputs sha-checked against
|
| 435 |
+
reference_manifest.json). cache: per dataset, reused by the draws of one process."""
|
| 436 |
+
if spec.name not in cache:
|
| 437 |
+
cache.clear()
|
| 438 |
+
cache[spec.name] = _observed_all(spec, ref, man)
|
| 439 |
+
X, srow, sid, inputs = cache[spec.name]
|
| 440 |
+
out = []
|
| 441 |
+
for d in donors:
|
| 442 |
+
out.append(X[np.flatnonzero(srow == int(np.flatnonzero(sid == d)[0]))].tocsr())
|
| 443 |
+
n = np.asarray([o.shape[0] for o in out])
|
| 444 |
+
ref_n = ref["n_cells"][[int(np.flatnonzero(ref["donors"].astype(str) == d)[0]) for d in donors]]
|
| 445 |
+
if not np.array_equal(n, ref_n):
|
| 446 |
+
raise SystemExit("observed cell counts per sample differ from the reference")
|
| 447 |
+
return out, {"inputs_sha256": inputs, "n_cells_total": int(n.sum())}
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def _observed_all(spec, ref: dict, man: dict):
|
| 451 |
+
feat = F.load_features(spec.features)
|
| 452 |
+
if feat["sha256"] != man["features"]["sha256"]:
|
| 453 |
+
raise SystemExit("features sha differs from the reference's")
|
| 454 |
+
gs = F.gene_sets(feat)
|
| 455 |
+
if not np.array_equal(gs["score_ids"], ref["score_ids"].astype(str)):
|
| 456 |
+
raise SystemExit("scoring genes differ from the reference")
|
| 457 |
+
cells = F.load_cells_datadir(spec, gs)
|
| 458 |
+
if cells is None or cells["inputs_sha256"] != man["cells"]["inputs_sha256"]:
|
| 459 |
+
raise SystemExit("observed cell files differ from the ones the reference was built from")
|
| 460 |
+
keys, _ = F.cell_keys(cells["table"].reset_index(drop=True))
|
| 461 |
+
srow = np.asarray(cells["sample_row"])
|
| 462 |
+
order = np.lexsort((keys, srow)) # the reference's canonical order (F.build_reference)
|
| 463 |
+
X = cells["X"].tocsr()[order][:, gs["score_idx"]].tocsr().astype(np.float32)
|
| 464 |
+
return X, srow[order], feat["sample_ids"], cells["inputs_sha256"]
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
CODE_SHA256 = {str(p): sha256(p) for p in CODE_FILES} # at import = the code this process runs
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
# =========================================================================== one unit
|
| 471 |
+
def pair_embeddings(v: dict, R: sp.csr_matrix, r_d: np.ndarray, Q: sp.csr_matrix, q_d: np.ndarray,
|
| 472 |
+
zr_raw: np.ndarray | None = None) -> dict:
|
| 473 |
+
"""Real set R and query set Q in the scorer's PCA-50: 'raw' = SB.project; 'dm' = score_ft.depth_matched's own
|
| 474 |
+
steps (SB.depth_match of the pair with a fresh rng(DEPTH_SEED), real set in the 'R1' slot, then SB.project),
|
| 475 |
+
returning the embeddings instead of only their precision/coverage. zr_raw: the view's fitted z1 for R = R1."""
|
| 476 |
+
names = v["donors"]
|
| 477 |
+
thinned, _ = F.SB.depth_match({"R1": R, "Q": Q}, {"R1": names[r_d], "Q": names[q_d]}, list(names),
|
| 478 |
+
np.random.default_rng(F.DEPTH_SEED))
|
| 479 |
+
return {"raw": (zr_raw if zr_raw is not None else F.SB.project(R, v["mean"], v["comps"]),
|
| 480 |
+
F.SB.project(Q, v["mean"], v["comps"])),
|
| 481 |
+
"dm": (F.SB.project(thinned["R1"], v["mean"], v["comps"]), F.SB.project(thinned["Q"], v["mean"], v["comps"]))}
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def per_donor_pc(r1_d, q_d, S_, res) -> tuple:
|
| 485 |
+
nq, n1 = np.bincount(q_d, minlength=S_), np.bincount(r1_d, minlength=S_)
|
| 486 |
+
return (np.bincount(q_d, weights=res["inside"], minlength=S_) / nq,
|
| 487 |
+
np.bincount(r1_d, weights=res["covered"], minlength=S_) / n1)
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def score_set(name: str, v: dict, Q: sp.csr_matrix, q_d: np.ndarray, sigma_m: float, n_jobs: int,
|
| 491 |
+
expect: dict | None, oos: tuple | None) -> tuple[list, pd.DataFrame, dict]:
|
| 492 |
+
"""Families 1, 2, 4 for one query set (an arm's P/C subsample, or R2), raw and depth matched, real side = R1
|
| 493 |
+
(the scorer's space). oos = (R2 counts, R2 donor index, set name): families 1-2 again with R2 as the real side."""
|
| 494 |
+
S_ = v["donors"].size
|
| 495 |
+
E = pair_embeddings(v, v["R1"], v["r1_d"], Q, q_d, zr_raw=v["z1"])
|
| 496 |
+
rows, per, chk = [], {"donor": v["donors"], "set": name}, {}
|
| 497 |
+
for mode, (zr, zg) in E.items():
|
| 498 |
+
t0 = time.monotonic()
|
| 499 |
+
m = {"set": name, "real_side": "R1", "mode": mode, "n_real": int(len(zr)), "n_gen": int(len(zg))}
|
| 500 |
+
for k in KS:
|
| 501 |
+
# k = 10 raw: the view's own radii (score_ft.arm_metrics); every other k / mode: radii recomputed on zr
|
| 502 |
+
res = F.SB.precision_coverage(zr, v["radius"], zg) if (k == F.K_NN and mode == "raw") else pc_at_k(zr, zg, k)
|
| 503 |
+
m[f"precision_k{k}"], m[f"coverage_k{k}"], m[f"density_k{k}"] = res["precision"], res["coverage"], res["density"]
|
| 504 |
+
m[f"expected_coverage_identical_k{k}"] = expected_coverage(len(zr), len(zg), k)
|
| 505 |
+
pp, pc = per_donor_pc(v["r1_d"], q_d, S_, res)
|
| 506 |
+
per[f"precision_k{k}_{mode}"], per[f"coverage_k{k}_{mode}"] = pp, pc
|
| 507 |
+
m.update(two_sample_block(zr, zg, sigma_m, n_jobs=n_jobs))
|
| 508 |
+
m["seconds"] = round(time.monotonic() - t0, 1)
|
| 509 |
+
rows.append(m)
|
| 510 |
+
log(f" {name} [R1 {mode}] P/C k10 {m['precision_k10']:.4f}/{m['coverage_k10']:.4f} k5 {m['precision_k5']:.4f}/"
|
| 511 |
+
f"{m['coverage_k5']:.4f} k3 {m['precision_k3']:.4f}/{m['coverage_k3']:.4f} | AUC knn {m['c2st_knn_auc']:.3f} "
|
| 512 |
+
f"rf {m['c2st_rf_auc']:.3f} | 1-NN {m['nn1_acc']:.3f} | MMD2 {m['mmd2_bw1']:.4f} ({m['seconds']} s)")
|
| 513 |
+
if oos is not None:
|
| 514 |
+
R2, r2_d, oname = oos
|
| 515 |
+
for mode, (zr, zg) in pair_embeddings(v, R2, r2_d, Q, q_d).items():
|
| 516 |
+
t0 = time.monotonic()
|
| 517 |
+
m = {"set": oname, "real_side": "R2", "mode": mode, "n_real": int(len(zr)), "n_gen": int(len(zg))}
|
| 518 |
+
m.update(two_sample_block(zr, zg, sigma_m, n_jobs=n_jobs))
|
| 519 |
+
m["seconds"] = round(time.monotonic() - t0, 1)
|
| 520 |
+
rows.append(m)
|
| 521 |
+
log(f" {oname} [R2 {mode}] AUC knn {m['c2st_knn_auc']:.3f} rf {m['c2st_rf_auc']:.3f} | 1-NN {m['nn1_acc']:.3f} "
|
| 522 |
+
f"| MMD2 {m['mmd2_bw1']:.4f} ({m['seconds']} s)")
|
| 523 |
+
if expect is not None: # reproduction of the scorer's k = 10 values
|
| 524 |
+
for mode, key in (("raw", ""), ("dm", "_depth_matched")):
|
| 525 |
+
mm = next(r for r in rows if r["mode"] == mode)
|
| 526 |
+
for q in ("precision", "coverage"):
|
| 527 |
+
chk[f"{q}{key}"] = {"ours": mm[f"{q}_k10"], "scorer": expect[f"{q}{key}"],
|
| 528 |
+
"abs_diff": abs(mm[f"{q}_k10"] - expect[f"{q}{key}"])}
|
| 529 |
+
if "per_donor" in expect:
|
| 530 |
+
d = np.abs(per[f"{q}_k10_{mode}"] - expect["per_donor"][f"{q}{key}"])
|
| 531 |
+
chk[f"{q}{key}_per_donor_max_abs_diff"] = float(d.max())
|
| 532 |
+
return rows, pd.DataFrame(per), chk
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def run_unit(design: str, ds: str, draw: int | None, a) -> None:
|
| 536 |
+
t_unit = time.monotonic()
|
| 537 |
+
spec = F.DATASETS[ds]
|
| 538 |
+
out = unit_dir(design, ds, draw)
|
| 539 |
+
if (out / "manifest.json").is_file() and not a.force:
|
| 540 |
+
log(f"{out} done already")
|
| 541 |
+
return
|
| 542 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 543 |
+
lock = out / ".in_progress"
|
| 544 |
+
if lock.is_file(): # another process (other stream) is computing this unit: skip unless its pid is gone
|
| 545 |
+
pid = int(lock.read_text().split()[0])
|
| 546 |
+
if Path(f"/proc/{pid}").exists():
|
| 547 |
+
log(f"{out} is being computed by pid {pid}; skipped")
|
| 548 |
+
return
|
| 549 |
+
lock.write_text(f"{os.getpid()} {F.now()}\n")
|
| 550 |
+
try:
|
| 551 |
+
_run_unit(design, ds, draw, a, t_unit, spec, out)
|
| 552 |
+
finally:
|
| 553 |
+
lock.unlink(missing_ok=True)
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def _run_unit(design: str, ds: str, draw: int | None, a, t_unit: float, spec, out: Path) -> None:
|
| 557 |
+
calls = unit_calls(design, ds, draw)
|
| 558 |
+
summ = {}
|
| 559 |
+
for cdir, arms in calls:
|
| 560 |
+
s = json.loads((cdir / "summary.json").read_text())
|
| 561 |
+
miss = [x for x in arms if x not in s["arms"]]
|
| 562 |
+
if miss:
|
| 563 |
+
raise SystemExit(f"{cdir}: arms {miss} not scored there")
|
| 564 |
+
summ[cdir] = s
|
| 565 |
+
first = summ[calls[0][0]]
|
| 566 |
+
donors = [str(x) for x in first["donors"]]
|
| 567 |
+
for cdir, s in summ.items():
|
| 568 |
+
if [str(x) for x in s["donors"]] != donors:
|
| 569 |
+
raise SystemExit(f"{cdir}: scored donors differ from {calls[0][0]}")
|
| 570 |
+
if s["reference"]["reference_sha256"] != first["reference"]["reference_sha256"]:
|
| 571 |
+
raise SystemExit(f"{cdir}: reference sha differs")
|
| 572 |
+
cache = F.CACHE_ROOT / ds
|
| 573 |
+
ref, man = F.load_reference(cache)
|
| 574 |
+
if man["reference_sha256"] != first["reference"]["reference_sha256"]:
|
| 575 |
+
raise SystemExit(f"{cache}: reference sha differs from the scored one")
|
| 576 |
+
log(f"{ds} {design} {'' if draw is None else f'draw{draw} '}: {len(donors)} scored samples; fitting the scorer's view")
|
| 577 |
+
v = S.make_view(ref, donors)
|
| 578 |
+
repro = {"unit": str(out), "pca": {"ours": v["pca"], "scorer": first["reference"]["pca"]},
|
| 579 |
+
"r2_control": {"ours": v["r2_control"], "scorer": first["reference"]["r2_control"]}, "arms": {}}
|
| 580 |
+
S_ = v["donors"].size
|
| 581 |
+
sigma_m = median_bandwidth(v["z1"])
|
| 582 |
+
log(f"bandwidth m (median pairwise distance of R1, PCA-50) = {sigma_m:.4f}")
|
| 583 |
+
rows, per_frames, en_rows, en_ps = [], [], [], []
|
| 584 |
+
fetched: list[Path] = []
|
| 585 |
+
fetch_root = Path(a.fetch_dir)
|
| 586 |
+
|
| 587 |
+
# ---------------- E_N inputs shared by all arms
|
| 588 |
+
rng_c = F.donor_rng
|
| 589 |
+
R1L = log1p_cp10k_sparse(v["R1"])
|
| 590 |
+
gram_r1 = Gram(R1L.shape[1]).add(R1L)
|
| 591 |
+
r1_split = [np.flatnonzero(v["r1_d"] == s) for s in range(S_)]
|
| 592 |
+
obs, obs_info = observed_cells(spec, ref, man, v["donors"], a.obs_cache)
|
| 593 |
+
# out-of-sample real sets from the scorer's donor-keyed permutation (F.reference_split): R1 = perm[:n],
|
| 594 |
+
# R2 = perm[n:2n] (both checked equal to reference.npz), R3 = perm[2n:3n] (fewer cells when the sample is small);
|
| 595 |
+
# the R2-vs-R3 control uses R2' = perm[n:n+m], m = min(n, |R3|), so both sides have the same size per sample.
|
| 596 |
+
r3_blocks, r2b_blocks, r3_d, r2b_d, oos_info = [], [], [], [], {"n_r3": [], "short_samples": []}
|
| 597 |
+
for k in range(S_):
|
| 598 |
+
nk, d = obs[k].shape[0], str(v["donors"][k])
|
| 599 |
+
a1, a2 = F.reference_split(nk, d)
|
| 600 |
+
if (obs[k][a1] != v["R1"][np.flatnonzero(v["r1_d"] == k)]).nnz or \
|
| 601 |
+
(obs[k][a2] != v["R2"][np.flatnonzero(v["r2_d"] == k)]).nnz:
|
| 602 |
+
raise SystemExit(f"{d}: R1 / R2 rebuilt from the observed cells differ from reference.npz")
|
| 603 |
+
perm = F.donor_rng(F.SUB_SEED, d).permutation(nk)
|
| 604 |
+
n = a1.size
|
| 605 |
+
r3 = np.sort(perm[2 * n:3 * n])
|
| 606 |
+
m_ = r3.size
|
| 607 |
+
if m_ < n:
|
| 608 |
+
oos_info["short_samples"].append({"sample": d, "n": int(n), "n_r3": int(m_)})
|
| 609 |
+
r3_blocks.append(obs[k][r3])
|
| 610 |
+
r2b_blocks.append(obs[k][np.sort(perm[n:n + m_])])
|
| 611 |
+
r3_d.append(np.full(m_, k))
|
| 612 |
+
r2b_d.append(np.full(m_, k))
|
| 613 |
+
oos_info["n_r3"].append(int(m_))
|
| 614 |
+
R3, R2b = sp.vstack(r3_blocks, format="csr"), sp.vstack(r2b_blocks, format="csr")
|
| 615 |
+
r3_d, r2b_d = np.concatenate(r3_d), np.concatenate(r2b_d)
|
| 616 |
+
log(f"observed cells: {obs_info['n_cells_total']} in {S_} samples; R1/R2 rebuilt = reference.npz; R3 {R3.shape[0]} "
|
| 617 |
+
f"cells ({len(oos_info['short_samples'])} samples with fewer than n)")
|
| 618 |
+
oos_r2 = (v["R2"], v["r2_d"])
|
| 619 |
+
if not a.no_en_all:
|
| 620 |
+
obsL = [log1p_cp10k_sparse(o) for o in obs]
|
| 621 |
+
gram_obs = Gram(R1L.shape[1])
|
| 622 |
+
for L in obsL:
|
| 623 |
+
gram_obs.add(L)
|
| 624 |
+
del obs
|
| 625 |
+
|
| 626 |
+
def en_unit(set_name: str, cellset: str, gts_L: list, semis_L: list, gram_real: Gram, n_rep_rows: int | None):
|
| 627 |
+
t0 = time.monotonic()
|
| 628 |
+
g = Gram(gts_L[0].shape[1])
|
| 629 |
+
for L in semis_L:
|
| 630 |
+
g.add(L)
|
| 631 |
+
mu, comps = (gram_real + g).pca(EN_PCS)
|
| 632 |
+
gts = [embed(L, mu, comps) for L in gts_L]
|
| 633 |
+
semis = [embed(L, mu, comps) for L in semis_L]
|
| 634 |
+
Z_all = np.vstack(gts + semis)
|
| 635 |
+
rng = np.random.default_rng([SEED, 17 if cellset == "pc" else 29])
|
| 636 |
+
res = en_from_embeddings(gts, semis, rng, Z_all=Z_all,
|
| 637 |
+
lb_max_queries=None if cellset == "pc" else EN_LB_MAX_QUERIES)
|
| 638 |
+
n_test = len(gts)
|
| 639 |
+
for d in ("sq", "l2"):
|
| 640 |
+
r = res[d]
|
| 641 |
+
en_rows.append({"set": set_name, "cellset": cellset, "distance": d, "n_samples": n_test,
|
| 642 |
+
"n_cells_real": int(sum(len(x) for x in gts)), "n_cells_gen": int(sum(len(x) for x in semis)),
|
| 643 |
+
"n_pcs": int(comps.shape[0]), "lb": r["lb"], "ub": r["ub"], "dif_mean": r["dif_mean"],
|
| 644 |
+
"en": r["en"], "lb_exact": res["lb"]["exact"], "lb_queries": res["lb"]["n_queries"],
|
| 645 |
+
"n_representative_rows": n_rep_rows,
|
| 646 |
+
"en_reps_at_lb": (r["en"] * n_test / (n_test + n_rep_rows)) if n_rep_rows else None,
|
| 647 |
+
"seconds": round(time.monotonic() - t0, 1)})
|
| 648 |
+
en_ps.append(pd.DataFrame({"set": set_name, "cellset": cellset, "distance": d, "donor": v["donors"],
|
| 649 |
+
"n_real": [len(x) for x in gts], "n_gen": [len(x) for x in semis],
|
| 650 |
+
"partner": v["donors"][res["partner"]], "dif": r["dif_i"], "en_i": r["en_i"]}))
|
| 651 |
+
log(f" {set_name} E_N[{cellset}] sq {res['sq']['en']:.4f} (LB {res['sq']['lb']:.3f} UB {res['sq']['ub']:.3f} "
|
| 652 |
+
f"Dif {res['sq']['dif_mean']:.3f}) l2 {res['l2']['en']:.4f} ({round(time.monotonic() - t0, 1)} s)")
|
| 653 |
+
|
| 654 |
+
# ---------------- control: R1 vs R2 (the scorer's own)
|
| 655 |
+
expect_r2 = {"precision": first["reference"]["r2_control"]["precision"],
|
| 656 |
+
"coverage": first["reference"]["r2_control"]["coverage"],
|
| 657 |
+
"precision_depth_matched": first["reference"]["r2_control"]["depth_matched"]["precision"],
|
| 658 |
+
"coverage_depth_matched": first["reference"]["r2_control"]["depth_matched"]["coverage"]}
|
| 659 |
+
r, p, chk = score_set(CONTROL, v, v["R2"], v["r2_d"], sigma_m, a.threads, expect_r2, oos=None)
|
| 660 |
+
rows += r
|
| 661 |
+
# out-of-sample control: R2' (real side) vs R3, families 1-2 only
|
| 662 |
+
for mode, (zr, zg) in pair_embeddings(v, R2b, r2b_d, R3, r3_d).items():
|
| 663 |
+
t0 = time.monotonic()
|
| 664 |
+
m = {"set": CONTROL_OOS, "real_side": "R2", "mode": mode, "n_real": int(len(zr)), "n_gen": int(len(zg))}
|
| 665 |
+
m.update(two_sample_block(zr, zg, sigma_m, n_jobs=a.threads))
|
| 666 |
+
m["seconds"] = round(time.monotonic() - t0, 1)
|
| 667 |
+
rows.append(m)
|
| 668 |
+
log(f" {CONTROL_OOS} [R2 {mode}] AUC knn {m['c2st_knn_auc']:.3f} rf {m['c2st_rf_auc']:.3f} | 1-NN "
|
| 669 |
+
f"{m['nn1_acc']:.3f} | MMD2 {m['mmd2_bw1']:.4f} ({m['seconds']} s)")
|
| 670 |
+
per_frames.append(p)
|
| 671 |
+
repro["arms"][CONTROL] = chk
|
| 672 |
+
R2L = log1p_cp10k_sparse(v["R2"])
|
| 673 |
+
en_unit(CONTROL, "pc", [R1L[i] for i in r1_split], [R2L[np.flatnonzero(v["r2_d"] == s)] for s in range(S_)],
|
| 674 |
+
gram_r1, None)
|
| 675 |
+
if not a.no_en_all:
|
| 676 |
+
A_, B_ = [], []
|
| 677 |
+
for s in range(S_):
|
| 678 |
+
perm = rng_c(SEED, v["donors"][s]).permutation(obsL[s].shape[0])
|
| 679 |
+
h = obsL[s].shape[0] // 2
|
| 680 |
+
A_.append(obsL[s][np.sort(perm[:h])])
|
| 681 |
+
B_.append(obsL[s][np.sort(perm[h:])])
|
| 682 |
+
# the PCA basis is the one of all observed cells (A and B together): gram_real = A-part, semis add the B-part
|
| 683 |
+
gA = Gram(R1L.shape[1])
|
| 684 |
+
for L in A_:
|
| 685 |
+
gA.add(L)
|
| 686 |
+
en_unit(CONTROL, "all", A_, B_, gA, None)
|
| 687 |
+
del A_, B_
|
| 688 |
+
|
| 689 |
+
# ---------------- arms
|
| 690 |
+
pcache = a.pcache # Poisson read-outs (scoring genes) by NPZ sha; zs_*_all are reused by later draws
|
| 691 |
+
n_rep_rows = None
|
| 692 |
+
if design == "fewshot":
|
| 693 |
+
dj = json.loads((TASK / "data" / ds / "fewshot_n5" / "DRAWS.json").read_text())["draw"][str(draw)]
|
| 694 |
+
n_rep_rows = int(dj["n_train_rows"])
|
| 695 |
+
panel_ids = ref["panel_ids"].astype(str)
|
| 696 |
+
for cdir, arms in calls:
|
| 697 |
+
s = summ[cdir]
|
| 698 |
+
per_csv = pd.read_csv(cdir / "per_donor.csv")
|
| 699 |
+
for name in arms:
|
| 700 |
+
t0 = time.monotonic()
|
| 701 |
+
pa = s["per_arm"][name]
|
| 702 |
+
path = resolve_npz(Path(pa["npz"]), pa["npz_sha256"], fetch_root, fetched)
|
| 703 |
+
arm = S.open_arm(name, path, panel_ids, allow_no_receipt=False)
|
| 704 |
+
if arm["sha256"] != pa["npz_sha256"] or not arm["receipt_verified"]:
|
| 705 |
+
raise SystemExit(f"{name}: NPZ sha / receipt check failed for {path}")
|
| 706 |
+
npos = {n: i for i, n in enumerate(arm["sample_ids"])}
|
| 707 |
+
rws = [np.flatnonzero(arm["bulk_index"] == npos[x]) for x in v["donors"]]
|
| 708 |
+
sel = np.concatenate(rws)
|
| 709 |
+
gen_d = np.repeat(np.arange(S_), [x.size for x in rws])
|
| 710 |
+
if arm["sha256"] not in pcache:
|
| 711 |
+
rates = np.ascontiguousarray(arm["d"]["generated_counts"], dtype=np.float32)
|
| 712 |
+
full = F.PR.poisson_integerise(rates, seed=F.POISSON_SEED, chunk_rows=4096)
|
| 713 |
+
del rates
|
| 714 |
+
pcache[arm["sha256"]] = full[:, ref["score_idx"]].tocsr()
|
| 715 |
+
del full
|
| 716 |
+
arm["d"].close()
|
| 717 |
+
Xg = pcache[arm["sha256"]][sel].tocsr()
|
| 718 |
+
sub = np.concatenate([np.flatnonzero(gen_d == k)[F.generated_subsample(int((gen_d == k).sum()),
|
| 719 |
+
int(v["n_ref"][k]), v["donors"][k])]
|
| 720 |
+
for k in range(S_)])
|
| 721 |
+
Q, q_d = Xg[sub].tocsr(), gen_d[sub]
|
| 722 |
+
gc = pd.read_parquet(cdir / "arms" / name / "generated_cells.parquet", columns=["npz_row", "in_pc_subsample"])
|
| 723 |
+
same_rows = bool(np.array_equal(gc.npz_row.to_numpy(), sel)
|
| 724 |
+
and np.array_equal(np.flatnonzero(gc.in_pc_subsample.to_numpy()), np.sort(sub)))
|
| 725 |
+
if not same_rows:
|
| 726 |
+
raise SystemExit(f"{name}: scored rows / P/C subsample differ from {cdir}/arms/{name}/generated_cells.parquet")
|
| 727 |
+
pdn = per_csv[per_csv.arm == name].set_index("donor").loc[v["donors"]]
|
| 728 |
+
h = s["headline"][name]
|
| 729 |
+
expect = {"precision": h["precision"], "coverage": h["coverage"], "precision_depth_matched": h["precision_dm"],
|
| 730 |
+
"coverage_depth_matched": h["coverage_dm"],
|
| 731 |
+
"per_donor": {k: pdn[k].to_numpy() for k in ("precision", "coverage", "precision_depth_matched",
|
| 732 |
+
"coverage_depth_matched")}}
|
| 733 |
+
log(f"{name}: {path.name} sha {arm['sha256'][:12]} (receipt verified), {sel.size} scored cells, "
|
| 734 |
+
f"{sub.size} in the P/C subsample (same rows as the scorer)")
|
| 735 |
+
r, p, chk = score_set(name, v, Q, q_d, sigma_m, a.threads, expect, oos=(oos_r2[0], oos_r2[1], name))
|
| 736 |
+
chk["rows_and_subsample_equal_scorer"] = same_rows
|
| 737 |
+
chk["npz"] = {"path": str(path), "scored_path": pa["npz"], "sha256": arm["sha256"]}
|
| 738 |
+
rows += r
|
| 739 |
+
per_frames.append(p)
|
| 740 |
+
repro["arms"][name] = chk
|
| 741 |
+
QL = log1p_cp10k_sparse(Q)
|
| 742 |
+
en_unit(name, "pc", [R1L[i] for i in r1_split], [QL[np.flatnonzero(q_d == k)] for k in range(S_)], gram_r1,
|
| 743 |
+
n_rep_rows if name == "scsemi5" else None)
|
| 744 |
+
if not a.no_en_all:
|
| 745 |
+
XgL = log1p_cp10k_sparse(Xg)
|
| 746 |
+
en_unit(name, "all", obsL, [XgL[np.flatnonzero(gen_d == k)] for k in range(S_)], gram_obs,
|
| 747 |
+
n_rep_rows if name == "scsemi5" else None)
|
| 748 |
+
del XgL
|
| 749 |
+
log(f"{name} done in {time.monotonic() - t0:.0f} s")
|
| 750 |
+
if not (design == "fewshot" and name in ("zs_raw", "zs_pseudo")):
|
| 751 |
+
pcache.pop(arm["sha256"], None) # not reused by another unit
|
| 752 |
+
# ---------------- write
|
| 753 |
+
meta = {"dataset": ds, "design": design, "unit": "pooled" if draw is None else f"draw{draw}"}
|
| 754 |
+
met = pd.DataFrame(rows)
|
| 755 |
+
for k, x in reversed(list(meta.items())):
|
| 756 |
+
met.insert(0, k, x)
|
| 757 |
+
met.insert(3, "label", met["set"].map(ARM_LABEL))
|
| 758 |
+
met.to_csv(out / "metrics.csv", index=False)
|
| 759 |
+
perd = pd.concat(per_frames, ignore_index=True)
|
| 760 |
+
for k, x in reversed(list(meta.items())):
|
| 761 |
+
perd.insert(0, k, x)
|
| 762 |
+
perd.to_csv(out / "per_donor.csv", index=False)
|
| 763 |
+
en = pd.DataFrame(en_rows)
|
| 764 |
+
for k, x in reversed(list(meta.items())):
|
| 765 |
+
en.insert(0, k, x)
|
| 766 |
+
en.to_csv(out / "en.csv", index=False)
|
| 767 |
+
ep = pd.concat(en_ps, ignore_index=True)
|
| 768 |
+
for k, x in reversed(list(meta.items())):
|
| 769 |
+
ep.insert(0, k, x)
|
| 770 |
+
ep.to_csv(out / "en_per_sample.csv", index=False)
|
| 771 |
+
worst = max([c.get("abs_diff", 0.0) for arm in repro["arms"].values() for c in arm.values() if isinstance(c, dict)]
|
| 772 |
+
+ [0.0])
|
| 773 |
+
repro["max_abs_diff_k10_pooled"] = worst
|
| 774 |
+
repro["oos_r3"] = oos_info
|
| 775 |
+
repro["pca_equal"] = repro["pca"]["ours"] == repro["pca"]["scorer"]
|
| 776 |
+
(out / "repro.json").write_text(json.dumps(repro, indent=1, default=float) + "\n")
|
| 777 |
+
code = CODE_SHA256 # hashed when the process started
|
| 778 |
+
manifest = {"schema": "paired_ft_extra_metrics.v1", **meta, "written_utc": F.now(), "command": sys.argv,
|
| 779 |
+
"threads": a.threads, "donors": list(map(str, v["donors"])), "n_samples": int(S_),
|
| 780 |
+
"calls": {str(c): {"arms": list(arms), "summary_sha256": sha256(c / "summary.json")} for c, arms in calls},
|
| 781 |
+
"reference_sha256": man["reference_sha256"], "bandwidth_m": sigma_m,
|
| 782 |
+
"params": {"seed": SEED, "ks": KS, "knn_c2st_k": KNN_C2ST_K, "rf_trees": RF_TREES, "cv_folds": CV_FOLDS,
|
| 783 |
+
"bw_multiples": BW_MULTIPLES, "bw_max_cells": BW_MAX_CELLS, "en_pcs": EN_PCS,
|
| 784 |
+
"en_lb_max_queries_all_cells": EN_LB_MAX_QUERIES, "en_all_cells": not a.no_en_all},
|
| 785 |
+
"n_representative_rows": n_rep_rows, "fetched_from_server2": [str(f) for f in fetched],
|
| 786 |
+
"code_sha256": code, "seconds": round(time.monotonic() - t_unit, 1),
|
| 787 |
+
"max_abs_diff_k10_pooled": worst}
|
| 788 |
+
(out / "manifest.json").write_text(json.dumps(manifest, indent=1, default=float) + "\n")
|
| 789 |
+
log(f"unit {meta['unit']} of {ds} written to {out} in {manifest['seconds']} s (k=10 max |diff| vs scorer {worst:.2e})")
|
| 790 |
+
for f in fetched:
|
| 791 |
+
if f.name.startswith("zs__raw_all") or f.name.startswith("zs__pseudo_all"):
|
| 792 |
+
continue # shared by the draws of the cohort; removed by main after the last draw
|
| 793 |
+
f.unlink(missing_ok=True)
|
| 794 |
+
f.with_suffix(".log").unlink(missing_ok=True)
|
| 795 |
+
log(f"removed fetched copy {f}")
|
| 796 |
+
|
| 797 |
+
|
| 798 |
+
# =========================================================================== collect
|
| 799 |
+
def collect() -> None:
|
| 800 |
+
"""Tables and concatenated CSVs: tools/collect_extra_metrics.py (pandas only)."""
|
| 801 |
+
import collect_extra_metrics as C
|
| 802 |
+
C.main()
|
| 803 |
+
|
| 804 |
+
|
| 805 |
+
def parse(argv=None):
|
| 806 |
+
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 807 |
+
p.add_argument("--design", choices=["fewshot", "pooled"])
|
| 808 |
+
p.add_argument("--dataset", choices=DATASETS)
|
| 809 |
+
p.add_argument("--draws", default="0,1,2,3,4")
|
| 810 |
+
p.add_argument("--threads", type=int, default=7)
|
| 811 |
+
p.add_argument("--fetch-dir", default=None, help="where server_2 NPZ copies go (default: scratch under scores_extra)")
|
| 812 |
+
p.add_argument("--no-en-all", action="store_true", help="skip the all-cells E_N (P/C-cell E_N is always computed)")
|
| 813 |
+
p.add_argument("--force", action="store_true", help="recompute units that already have a manifest")
|
| 814 |
+
p.add_argument("--collect", action="store_true")
|
| 815 |
+
return p.parse_args(argv)
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
def main(argv=None) -> int:
|
| 819 |
+
a = parse(argv)
|
| 820 |
+
if a.collect:
|
| 821 |
+
collect()
|
| 822 |
+
return 0
|
| 823 |
+
if not (1 <= a.threads <= 8):
|
| 824 |
+
raise SystemExit("--threads must be 1..8")
|
| 825 |
+
try:
|
| 826 |
+
from threadpoolctl import threadpool_limits
|
| 827 |
+
threadpool_limits(a.threads)
|
| 828 |
+
except ImportError:
|
| 829 |
+
pass
|
| 830 |
+
if a.design is None or a.dataset is None:
|
| 831 |
+
raise SystemExit("--design and --dataset are required (or --collect)")
|
| 832 |
+
a.fetch_dir = a.fetch_dir or str(OUT_ROOT / "_fetch_tmp")
|
| 833 |
+
Path(a.fetch_dir).mkdir(parents=True, exist_ok=True)
|
| 834 |
+
a.pcache, a.obs_cache = {}, {}
|
| 835 |
+
if a.design == "pooled":
|
| 836 |
+
run_unit("pooled", a.dataset, None, a)
|
| 837 |
+
else:
|
| 838 |
+
for j in [int(x) for x in a.draws.split(",") if x.strip()]:
|
| 839 |
+
run_unit("fewshot", a.dataset, j, a)
|
| 840 |
+
shared = Path(a.fetch_dir) / "generated" / a.dataset / "fewshot_n5"
|
| 841 |
+
for f in list(shared.glob("zs__*_all.npz")) if shared.is_dir() else []:
|
| 842 |
+
f.unlink(missing_ok=True)
|
| 843 |
+
f.with_suffix(".log").unlink(missing_ok=True)
|
| 844 |
+
log(f"removed fetched copy {f}")
|
| 845 |
+
return 0
|
| 846 |
+
|
| 847 |
+
|
| 848 |
+
if __name__ == "__main__":
|
| 849 |
+
raise SystemExit(main())
|