junidude14 commited on
Commit
087b652
·
verified ·
1 Parent(s): 756b86a

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/rescore_excluding_genes.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Re-run earlier score_ft.py calls with --exclude-genes, reusing their frozen scANVI labels (--reuse-labels).
3
+
4
+ CPU only. For every source score dir (e.g. scores/giroux2022/pooled, scores/giroux2022/fewshot_n5/draw0_scsemi5) the
5
+ exact command recorded in its summary.json is replayed through tools/run_unit.sh with only three changes:
6
+ --out <OUT_ROOT>/<path of the source dir below scores/> (new directory; the source is never written)
7
+ --exclude-genes CSV
8
+ --reuse-labels <source dir>
9
+ Optional --arms keeps a subset of the recorded arms. Optional --npz-map OLD=NEW reads generated NPZs (and their
10
+ receipts / condition NPZs) from a copy, e.g. after tools/move_generated.sh moved them to the other host; the condition
11
+ NPZ is then passed with --condition and its sha256 is checked here against the generation metadata.
12
+ An output dir that already has a summary.json is skipped.
13
+
14
+ usage: rescore_excluding_genes.py --exclude CSV --out-root DIR [--arms a,b] [--npz-map OLD=NEW] [--dry-run] SRC_DIR ...
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import hashlib
20
+ import json
21
+ import subprocess
22
+ import sys
23
+ from pathlib import Path
24
+
25
+ import numpy as np
26
+
27
+ T = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
28
+ PY = "/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python"
29
+
30
+
31
+ def sha(p: Path) -> str:
32
+ h = hashlib.sha256()
33
+ with open(p, "rb") as fh:
34
+ for b in iter(lambda: fh.read(1 << 22), b""):
35
+ h.update(b)
36
+ return h.hexdigest()
37
+
38
+
39
+ def remap(path: str, npz_map: tuple[str, str] | None) -> str:
40
+ if npz_map and path.startswith(npz_map[0]):
41
+ return npz_map[1] + path[len(npz_map[0]):]
42
+ return path
43
+
44
+
45
+ def build(src: Path, a) -> tuple[list[str], Path, int]:
46
+ s = json.loads((src / "summary.json").read_text())
47
+ cmd = list(s["command"])
48
+ if Path(cmd[0]).resolve() != (T / "tools" / "score_ft.py").resolve():
49
+ raise SystemExit(f"{src}: recorded command is not tools/score_ft.py: {cmd[0]}")
50
+ out = a.out_root / src.resolve().relative_to((T / "scores").resolve())
51
+ keep_arms = set(a.arms.split(",")) if a.arms else None
52
+ args, i, threads, conds = [], 1, 8, []
53
+ while i < len(cmd):
54
+ k = cmd[i]
55
+ if k in ("--out", "--exclude-genes", "--reuse-labels"):
56
+ i += 2
57
+ continue
58
+ if k == "--threads":
59
+ threads = int(cmd[i + 1])
60
+ if k == "--arm":
61
+ name, _, path = cmd[i + 1].partition("=")
62
+ if keep_arms is not None and name not in keep_arms:
63
+ i += 2
64
+ continue
65
+ new = remap(path, a.npz_map)
66
+ if new != path:
67
+ meta = json.loads(str(np.load(new, allow_pickle=False)["metadata_json"]))
68
+ cpath, csha = meta["input_condition_path"], meta["input_condition_sha256"]
69
+ cnew = remap(cpath, a.npz_map)
70
+ if not Path(cnew).is_file() or sha(Path(cnew)) != csha:
71
+ raise SystemExit(f"{name}: condition copy {cnew} missing or sha differs from the generation metadata")
72
+ conds += ["--condition", f"{name}={cnew}"]
73
+ args += ["--arm", f"{name}={new}"]
74
+ i += 2
75
+ continue
76
+ args.append(k)
77
+ i += 1
78
+ if keep_arms is not None and len([x for x in args if x == "--arm"]) != len(keep_arms):
79
+ raise SystemExit(f"{src}: not every requested arm is in the recorded command")
80
+ args += conds + ["--out", str(out), "--exclude-genes", str(a.exclude), "--reuse-labels", str(src)]
81
+ return args, out, threads
82
+
83
+
84
+ def main() -> int:
85
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
86
+ p.add_argument("--exclude", type=Path, required=True)
87
+ p.add_argument("--out-root", type=Path, required=True)
88
+ p.add_argument("--arms", default=None)
89
+ p.add_argument("--npz-map", default=None, help="OLD_PREFIX=NEW_PREFIX for generated NPZ paths")
90
+ p.add_argument("--dry-run", action="store_true")
91
+ p.add_argument("src", nargs="+", type=Path)
92
+ a = p.parse_args()
93
+ a.npz_map = tuple(a.npz_map.split("=", 1)) if a.npz_map else None
94
+ a.exclude = a.exclude.resolve()
95
+ a.out_root = a.out_root.resolve()
96
+ if a.out_root.resolve() == (T / "scores").resolve():
97
+ raise SystemExit("--out-root must not be scores/ (never overwrite the original scores)")
98
+ rc = 0
99
+ for src in a.src:
100
+ args, out, threads = build(src.resolve(), a)
101
+ if (out / "summary.json").exists():
102
+ print(f"skip (done): {out}")
103
+ continue
104
+ unit = (a.out_root.name + "-" + "-".join(out.relative_to(a.out_root).parts))[-70:]
105
+ line = ["bash", str(T / "tools" / "run_unit.sh"), unit, str(threads), PY, str(T / "tools" / "score_ft.py")] + args
106
+ print(" ".join(line), flush=True)
107
+ if a.dry_run:
108
+ continue
109
+ out.mkdir(parents=True, exist_ok=True)
110
+ r = subprocess.run(line)
111
+ if r.returncode != 0:
112
+ print(f"FAILED rc={r.returncode}: {src}", flush=True)
113
+ rc = 1
114
+ return rc
115
+
116
+
117
+ if __name__ == "__main__":
118
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/run_chain.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Run several queues one after another with one runner (run_queue.sh on server_1, run_queue_s2.sh on server_2); each
3
+ # runner takes one dataset, so a host with queues of two datasets chains them here. A failed queue does not stop the
4
+ # chain; finished steps are skipped by the runners, so a rerun resumes. GPU steps go through ml-run inside the runner.
5
+ # usage: run_chain.sh RUNNER DATASET:QUEUE_NAME [DATASET:QUEUE_NAME ...] (RUNNER = run_queue.sh | run_queue_s2.sh)
6
+ set -uo pipefail
7
+ T=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927
8
+ runner=$1; shift
9
+ [[ -f $T/tools/$runner ]] || { echo "no runner $runner" >&2; exit 2; }
10
+ rc=0
11
+ for spec in "$@"; do
12
+ ds=${spec%%:*}; q=${spec#*:}
13
+ [[ -s $T/queues/$q.txt && -d $T/data/$ds ]] || { echo "bad spec $spec" >&2; rc=1; continue; }
14
+ echo "$(date +%FT%T) chain: $q ($ds) with $runner on $(hostname -s)"
15
+ QUEUE=$T/queues/$q.txt DATASET_DIR=$T/data/$ds bash "$T/tools/$runner" || rc=1
16
+ done
17
+ echo "$(date +%FT%T) chain finished rc=$rc"
18
+ exit $rc
paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/score_arms.sh ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Score a chosen set of finished arms of one dataset into a NEW output dir, leaving the existing
3
+ # scores/<dataset>/{fold<k>,pooled,pooled_deg}/ untouched (score_ft.py rewrites summary.json/per_donor.csv of its --out).
4
+ # Same scorer, same per-dataset contrast arguments (contrast_args.sh), same CPU unit (run_unit.sh, 8 threads) as
5
+ # score_fold.sh / score_pooled.sh. Every arm's metrics depend only on the scored donors (fixed per-donor seeds), so
6
+ # arms scored here line up with the existing per-fold / pooled arms of the same donors. With a contrast (sepsis) the
7
+ # current scorer also writes the top-50 DEG score, i.e. the pooled_deg metrics.
8
+ # Waits until MemAvailable >= 56 GiB (run_unit.sh refuses below). An OUT_DIR that already has summary.json is skipped.
9
+ # usage: score_arms.sh DATASET GEN_DIR OUT_DIR UNIT_NAME ARM [ARM ...] (arm = NPZ basename without .npz)
10
+ set -uo pipefail
11
+ T=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927
12
+ PY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python
13
+ (( $# >= 5 )) || { echo "usage: score_arms.sh DATASET GEN_DIR OUT_DIR UNIT_NAME ARM [ARM ...]" >&2; exit 2; }
14
+ ds=$1; gen=$2; out=$3; name=$4; shift 4
15
+ [[ -s $out/summary.json ]] && { echo "$out already scored; not overwriting"; exit 0; }
16
+ args=()
17
+ for arm in "$@"; do
18
+ npz=$gen/$arm.npz; rec=$gen/$arm.log
19
+ if [[ ! -s $npz ]]; then
20
+ echo "missing $npz$([[ -f $gen/$arm.moved ]] && echo " ($(cat "$gen/$arm.moved"))")" >&2; exit 2
21
+ fi
22
+ grep -q '"output_sha256"' "$rec" 2>/dev/null || { echo "no finished receipt $rec" >&2; exit 2; }
23
+ args+=(--arm "$arm=$npz")
24
+ done
25
+ read -r -a cargs <<< "$(bash "$T/tools/contrast_args.sh" "$ds")"
26
+ until (( $(awk '/MemAvailable/ {print int($2/1048576)}' /proc/meminfo) >= 56 )); do sleep 120; done
27
+ mkdir -p "$out"
28
+ echo "scoring ${#args[@]} arg(s) -> $out"
29
+ bash "$T/tools/run_unit.sh" "$name" 8 "$PY" "$T/tools/score_ft.py" --dataset "$ds" --out "$out" --threads 8 \
30
+ "${args[@]}" "${cargs[@]}"
paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/score_ft.py ADDED
@@ -0,0 +1,827 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Score generated cells of held-out donors against the same donors' observed cells (fine-tuning benchmark).
3
+
4
+ CPU only. Run through tools/run_unit.sh (systemd user unit, CUDA hidden, <= 8 threads).
5
+
6
+ # once per dataset (observed reference cache, ~tens of MB, independent of folds and arms)
7
+ score_ft.py --dataset immicro --build-reference [--cells-source auto|datadir|immicro_h5ad]
8
+
9
+ # score one or more arms on the same donors
10
+ score_ft.py --dataset immicro --out DIR --arm raw=GEN_raw.npz --arm ft_realbulk=GEN_ft.npz
11
+ [--donors HS1,HS2,... | --donors donors.txt] [--threads 8]
12
+ [--groups-csv FILE] [--case-groups A,B] [--control-groups C] [--no-contrast]
13
+ [--condition ARM=COND.npz] [--allow-no-receipt]
14
+
15
+ Donors: default = the sample_ids of the NPZs; then every arm must have exactly the same sample_ids. With --donors,
16
+ every arm must contain all of them (it may hold more, e.g. a zero-shot NPZ over all donors).
17
+
18
+ Per arm (definitions in the README.md written to DIR):
19
+ one Poisson read-out of generated_counts over the WHOLE NPZ (seed 20260916, poisson_integerise), then the scored
20
+ donors' cells; frozen f01common scANVI six-type labels from those integer counts (predict_scanvi.py, CPU);
21
+ composition + L1 + observed LOO null; pseudobulk r + closest-donor top-1 (evaluate_realbulk statistic, among the
22
+ scored donors); precision/coverage/density (PCA-50 + k = 10 balls fitted on the scored donors' observed R1 cells) and
23
+ the depth-matched version; monocyte %; median UMI per cell; per-cell-type group contrast logFC r with the bulk
24
+ broadcast baseline; the benchmark's top-50 DEG overlap per cell type (T, B, Monocyte, NK, DC) and its bulk-broadcast
25
+ analogue (on by default whenever the contrast is on; --no-deg skips it).
26
+ Outputs in DIR: per_donor.csv, summary.json, contrast.csv (when a contrast is defined), README.md,
27
+ arms/<arm>/{labels/, predict_scanvi.log, generated_cells.parquet, deg_top50_lists.csv}.
28
+
29
+ # once per existing reference cache: donor x type aggregates incl. DC for the DEG score (new caches get it built in)
30
+ score_ft.py --dataset ye2026_sepsis --build-deg-reference
31
+
32
+ Optional (added 2026-10-01; without them the scorer behaves exactly as before):
33
+ --exclude-genes CSV genes (column gene_id) dropped from the disease-signal scores only: the group-contrast logFC r,
34
+ its broadcast r and partial r (removed from each type's detected-gene set), and the top-50 DEG
35
+ tests of the observed, generated and broadcast sides (columns removed before the Welch test, so
36
+ log1p-CPM libraries and BH run on the kept genes). Composition, precision/coverage, pseudobulk r
37
+ and depth are unchanged. Used for Giroux, whose severity is confounded with sex.
38
+ --reuse-labels DIR take each arm's frozen scANVI labels from an earlier score_ft.py output DIR (arms/<arm>/labels)
39
+ instead of running predict_scanvi.py; requires the same reference, NPZ sha256 and scored donors.
40
+ """
41
+ from __future__ import annotations
42
+
43
+ import os
44
+
45
+ for _k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMBA_NUM_THREADS"):
46
+ os.environ.setdefault(_k, "8")
47
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
48
+
49
+ import argparse # noqa: E402
50
+ import json # noqa: E402
51
+ import shutil # noqa: E402
52
+ import sys # noqa: E402
53
+ import time # noqa: E402
54
+ from pathlib import Path # noqa: E402
55
+
56
+ import numpy as np # noqa: E402
57
+ import pandas as pd # noqa: E402
58
+ import scipy.sparse as sp # noqa: E402
59
+
60
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
61
+ import ft_common as F # noqa: E402
62
+
63
+ MAX_THREADS = 8
64
+
65
+
66
+ # --------------------------------------------------------------------------- scored-donor view of the reference
67
+ def make_view(ref: dict, donors: list[str]) -> dict:
68
+ """Observed side restricted to the scored donors; PCA-50 + k-NN radii fitted on their R1 cells only."""
69
+ from sklearn.decomposition import PCA
70
+ pos = {d: i for i, d in enumerate(ref["donors"].astype(str))}
71
+ miss = [d for d in donors if d not in pos]
72
+ if miss:
73
+ raise SystemExit(f"donors not in the dataset reference: {miss[:5]}")
74
+ sel = np.asarray([pos[d] for d in donors], dtype=np.int64)
75
+ S = sel.size
76
+ remap = np.full(ref["donors"].size, -1, dtype=np.int64)
77
+ remap[sel] = np.arange(S)
78
+ v = {"donors": np.asarray(donors, dtype=str), "sel": sel, "groups": ref["groups"][sel].astype(str),
79
+ "n_cells": ref["n_cells"][sel], "n_ref": ref["n_ref"][sel], "comp": ref["composition"][sel],
80
+ "pb": ref["pseudobulk"][sel].astype(np.float64)}
81
+ for p in ("r1", "r2"):
82
+ m = remap[ref[f"{p}_donor"]] >= 0
83
+ v[p.upper()] = ref[p][np.flatnonzero(m)].tocsr()
84
+ v[f"{p}_d"] = remap[ref[f"{p}_donor"][m]]
85
+ cm = remap[ref["cell_donor"]] >= 0
86
+ v["cell_lib"], v["cell_d"] = ref["cell_lib"][cm].astype(np.float64), remap[ref["cell_donor"][cm]]
87
+ for k in ("n", "sum", "cp10k", "det"):
88
+ v[f"agg_{k}"] = ref[f"agg_{k}"][sel].astype(np.float64 if k != "n" else np.int64)
89
+ v["score_ids"] = [str(g) for g in ref["score_ids"]]
90
+ if "deg" in ref: # DEG aggregates (F.load_deg_reference), attached by main
91
+ v["deg_types"] = tuple(ref["deg"]["types"])
92
+ v["deg_n"], v["deg_sum"] = ref["deg"]["n"][sel], ref["deg"]["sum"][sel]
93
+ X1 = F.SB.cp10k_log1p(v["R1"])
94
+ ncomp = int(min(F.PCA_DIM, X1.shape[0] - 1, X1.shape[1]))
95
+ pca = PCA(n_components=ncomp, svd_solver="randomized", random_state=F.SUB_SEED).fit(X1)
96
+ v["mean"], v["comps"] = pca.mean_.astype(np.float32), pca.components_.astype(np.float32)
97
+ v["z1"] = ((X1 - v["mean"]) @ v["comps"].T).astype(np.float32)
98
+ v["radius"] = F.SB.knn_radius(v["z1"], F.K_NN)
99
+ v["pca"] = {"n_components": ncomp, "explained_variance_ratio_sum": float(pca.explained_variance_ratio_.sum()),
100
+ "n_fit_cells": int(X1.shape[0])}
101
+ del X1
102
+ z2 = F.SB.project(v["R2"], v["mean"], v["comps"])
103
+ pc2 = F.SB.precision_coverage(v["z1"], v["radius"], z2)
104
+ dm2 = depth_matched(v, v["R2"], v["r2_d"])
105
+ v["r2_control"] = {"precision": pc2["precision"], "coverage": pc2["coverage"], "density": pc2["density"],
106
+ "n_query": int(z2.shape[0]),
107
+ "depth_matched": {k: dm2[k] for k in ("precision", "coverage", "density")}}
108
+ v["obs_lib_median_d"] = np.asarray([np.median(v["cell_lib"][v["cell_d"] == s]) for s in range(S)])
109
+ return v
110
+
111
+
112
+ def depth_matched(v: dict, Q: sp.csr_matrix, q_d: np.ndarray) -> dict:
113
+ """stage_b_embed depth matching, pairwise (R1 vs one query set): per donor and within-donor rank of detected genes,
114
+ both cells are thinned (UMI sampling without replacement) to the smaller detected-gene count; the PCA is the one
115
+ fitted on the un-thinned R1; k = 10 radii are recomputed on the thinned R1. Fresh rng(20260925 + 4) per call."""
116
+ names = v["donors"]
117
+ thinned, summ = F.SB.depth_match({"R1": v["R1"], "Q": Q}, {"R1": names[v["r1_d"]], "Q": names[q_d]}, list(names),
118
+ np.random.default_rng(F.DEPTH_SEED))
119
+ z1 = F.SB.project(thinned["R1"], v["mean"], v["comps"])
120
+ zq = F.SB.project(thinned["Q"], v["mean"], v["comps"])
121
+ radius = F.SB.knn_radius(z1, F.K_NN)
122
+ r = F.SB.precision_coverage(z1, radius, zq)
123
+ r["summary"] = summ
124
+ return r
125
+
126
+
127
+ # --------------------------------------------------------------------------- --exclude-genes (disease-signal scores only)
128
+ def gene_exclusion(path: Path, score_ids: list[str]) -> tuple[np.ndarray, dict]:
129
+ """keep mask over the scoring genes (False = listed in the CSV's gene_id column) and its summary block."""
130
+ g = pd.read_csv(path, dtype=str)
131
+ if "gene_id" not in g.columns:
132
+ raise SystemExit(f"{path}: needs a gene_id column")
133
+ listed = set(g.gene_id.str.strip())
134
+ keep = np.asarray([s not in listed for s in score_ids], dtype=bool)
135
+ sym = dict(zip(g.gene_id, g.symbol)) if "symbol" in g.columns else {}
136
+ dropped = [s for s, k in zip(score_ids, keep) if not k]
137
+ return keep, {"file": str(path), "sha256": F.sha(path), "n_listed": len(listed),
138
+ "n_scoring_genes": len(score_ids), "n_dropped_from_scoring_genes": len(dropped),
139
+ "n_scoring_genes_kept": int(keep.sum()),
140
+ "dropped": [{"gene_id": s, "symbol": sym.get(s, "")} for s in dropped],
141
+ "applies_to": "group contrast (logFC r generated / broadcast / partial: dropped from each type's "
142
+ "detected-gene set) and top-50 DEG (observed, generated and broadcast tests: columns "
143
+ "dropped before log1p CPM, Welch and BH); all other metrics use every scoring gene"}
144
+
145
+
146
+ def keep_cols(v: dict, M: np.ndarray) -> np.ndarray:
147
+ """The scoring-gene columns (last axis) kept by --exclude-genes; M itself when no genes are excluded."""
148
+ return M if "keep" not in v else M[..., v["keep"]]
149
+
150
+
151
+ def keep_genes(v: dict) -> list:
152
+ return v["score_ids"] if "keep" not in v else [g for g, k in zip(v["score_ids"], v["keep"]) if k]
153
+
154
+
155
+ # --------------------------------------------------------------------------- --reuse-labels
156
+ def reused_labels(prev: Path, name: str, arm: dict, ref_sha: str, donors: np.ndarray, sel: np.ndarray,
157
+ gen_d: np.ndarray, work: Path) -> tuple[pd.DataFrame, dict]:
158
+ """Frozen labels of an earlier score_ft.py call on the same NPZ and scored donors (no predict_scanvi.py run).
159
+ The Poisson read-out and the row order depend only on the NPZ and the donor list, so that call labelled exactly
160
+ these cells. Checked: reference sha, NPZ sha256, donor list and order, NPZ rows and donors of its
161
+ generated_cells.parquet, labels row-aligned and equal to the parquet's, annotator model sha."""
162
+ s = json.loads((prev / "summary.json").read_text())
163
+ pa = s.get("per_arm", {}).get(name)
164
+ if pa is None:
165
+ raise SystemExit(f"--reuse-labels {prev}: no arm {name}")
166
+ if s["reference"]["reference_sha256"] != ref_sha:
167
+ raise SystemExit(f"--reuse-labels {prev}: reference sha differs")
168
+ if pa["npz_sha256"] != arm["sha256"]:
169
+ raise SystemExit(f"--reuse-labels {prev}: {name} NPZ sha differs from {arm['path']}")
170
+ if [str(x) for x in s["donors"]] != [str(x) for x in donors]:
171
+ raise SystemExit(f"--reuse-labels {prev}: scored donors differ")
172
+ gc = pd.read_parquet(prev / "arms" / name / "generated_cells.parquet", columns=["npz_row", "donor", "label"])
173
+ if not (np.array_equal(gc.npz_row.to_numpy(), sel) and np.array_equal(gc.donor.astype(str).to_numpy(), donors[gen_d])):
174
+ raise SystemExit(f"--reuse-labels {prev}: {name} generated cells differ (NPZ rows / donors)")
175
+ ldir = prev / "arms" / name / "labels"
176
+ lab = pd.read_parquet(ldir / "labels.parquet")
177
+ if len(lab) != sel.size or not np.array_equal(lab.cell_index.to_numpy(), np.arange(sel.size)) \
178
+ or not np.array_equal(lab.celltype_l1_pred.astype(str).to_numpy(), gc.label.astype(str).to_numpy()):
179
+ raise SystemExit(f"--reuse-labels {prev}: {name} labels are not row-aligned with its generated cells")
180
+ man = json.loads((ldir / "labels.manifest.json").read_text())
181
+ if man["model"]["model_pt_sha256"] != F.ANNOT_MODEL_SHA or pa["annotation"]["model_pt_sha256"] != F.ANNOT_MODEL_SHA:
182
+ raise SystemExit(f"--reuse-labels {prev}: annotator model sha differs from the f01common model")
183
+ (work / "labels").mkdir(parents=True, exist_ok=True)
184
+ for f in ("labels.parquet", "labels.manifest.json"):
185
+ shutil.copy2(ldir / f, work / "labels" / f)
186
+ info = {**pa["annotation"], "reused_from": str(ldir), "reused_labels_sha256": F.sha(ldir / "labels.parquet")}
187
+ F.log(f"{name}: labels reused from {ldir} (no predict_scanvi.py run)")
188
+ return lab, info
189
+
190
+
191
+ # --------------------------------------------------------------------------- contrast definition
192
+ def resolve_contrast(spec: F.DatasetSpec, v: dict, a) -> dict:
193
+ groups = v["groups"].copy()
194
+ source = "features groups"
195
+ if a.groups_csv:
196
+ g = pd.read_csv(a.groups_csv, dtype=str)
197
+ if not {"sample_id", "group"} <= set(g.columns):
198
+ raise SystemExit(f"{a.groups_csv}: needs columns sample_id, group")
199
+ m = g.set_index("sample_id").group.reindex(v["donors"])
200
+ if m.isna().any():
201
+ raise SystemExit(f"{a.groups_csv}: no group for {list(v['donors'][m.isna().to_numpy()][:5])}")
202
+ groups, source = m.astype(str).to_numpy(), f"groups csv {a.groups_csv}"
203
+ if a.no_contrast:
204
+ return {"enabled": False, "reason": "--no-contrast"}
205
+ case = a.case_groups.split(",") if a.case_groups else None
206
+ ctrl = a.control_groups.split(",") if a.control_groups else None
207
+ uniq = sorted(set(groups.tolist()))
208
+ if case is None and ctrl is None:
209
+ if spec.contrast == "none" and not a.groups_csv:
210
+ return {"enabled": False, "reason": f"dataset {spec.name} has no group contrast (use --groups-csv / --case-groups)"}
211
+ ctrl = [g for g in uniq if F.CONTROL_RE.search(g)]
212
+ case = [g for g in uniq if g not in ctrl]
213
+ rule = f"auto: control = groups matching /{F.CONTROL_RE.pattern}/, case = all other groups"
214
+ else:
215
+ if case is None:
216
+ case = [g for g in uniq if g not in ctrl]
217
+ if ctrl is None:
218
+ ctrl = [g for g in uniq if g not in case]
219
+ rule = "explicit --case-groups / --control-groups"
220
+ cm, hm = np.isin(groups, case), np.isin(groups, ctrl)
221
+ if (cm & hm).any():
222
+ raise SystemExit("a group is both case and control")
223
+ out = {"enabled": bool(cm.any() and hm.any()), "rule": rule, "group_source": source, "case_groups": case,
224
+ "control_groups": ctrl, "n_case_donors": int(cm.sum()), "n_control_donors": int(hm.sum()),
225
+ "n_donors_in_neither": int((~cm & ~hm).sum()), "case": cm, "ctrl": hm, "groups": groups}
226
+ if not out["enabled"]:
227
+ out["reason"] = "scored donors do not include both groups"
228
+ return out
229
+
230
+
231
+ # --------------------------------------------------------------------------- one arm
232
+ def open_arm(name: str, path: Path, panel_ids: np.ndarray, allow_no_receipt: bool) -> dict:
233
+ if not path.is_file():
234
+ moved = path.with_suffix(".moved")
235
+ raise SystemExit(f"{name}: {path} missing" + (f" ({moved} says it was moved)" if moved.exists() else ""))
236
+ npz_sha = F.sha(path)
237
+ rec_path = path.with_suffix(".log")
238
+ receipt = None
239
+ if rec_path.is_file() and rec_path.stat().st_size:
240
+ try:
241
+ receipt = json.loads(rec_path.read_text())
242
+ except json.JSONDecodeError:
243
+ receipt = None
244
+ if receipt is None and not allow_no_receipt:
245
+ raise SystemExit(f"{name}: no JSON generation receipt at {rec_path}; --allow-no-receipt to override")
246
+ if receipt is not None and receipt.get("output_sha256") not in (None, npz_sha):
247
+ raise SystemExit(f"{name}: NPZ sha256 differs from its generation receipt (partial or replaced file)")
248
+ d = np.load(path, allow_pickle=False)
249
+ if not np.array_equal(d["gene_ids"].astype(str), panel_ids):
250
+ raise SystemExit(f"{name}: NPZ gene_ids differ from the 6k panel")
251
+ meta = json.loads(str(d["metadata_json"])) if "metadata_json" in d.files else {}
252
+ cond = meta.get("input_condition_path") or (receipt or {}).get("condition_npz")
253
+ return {"name": name, "path": path, "d": d, "sha256": npz_sha, "receipt": receipt,
254
+ "receipt_verified": bool(receipt and receipt.get("output_sha256") == npz_sha),
255
+ "sample_ids": d["sample_ids"].astype(str), "bulk_index": d["bulk_index"].astype(np.int64), "meta": meta,
256
+ "condition": cond, "condition_sha256": meta.get("input_condition_sha256") or (receipt or {}).get("condition_sha256")}
257
+
258
+
259
+ def load_condition_bulk(path: str | None, expect_sha: str | None, donors: np.ndarray, score_ids: np.ndarray) -> dict:
260
+ if not path or not Path(path).is_file():
261
+ raise SystemExit(f"condition NPZ not found: {path} (pass --condition ARM=PATH or --no-contrast)")
262
+ s = F.sha(Path(path))
263
+ if expect_sha and s != expect_sha:
264
+ raise SystemExit(f"{path}: sha differs from the generation metadata")
265
+ z = np.load(path, allow_pickle=False)
266
+ ids = z["sample_ids"].astype(str)
267
+ pos = {x: i for i, x in enumerate(ids)}
268
+ miss = [x for x in donors if x not in pos]
269
+ if miss:
270
+ raise SystemExit(f"{path}: no bulk for {miss[:5]}")
271
+ gpos = {g: i for i, g in enumerate(z["gene_ids"].astype(str))}
272
+ gm = [g for g in score_ids if g not in gpos]
273
+ if gm:
274
+ raise SystemExit(f"{path}: {len(gm)} scoring genes absent")
275
+ bulk = np.asarray(z["bulk_counts"], np.float64)[[pos[x] for x in donors]][:, [gpos[g] for g in score_ids]]
276
+ return {"bulk": bulk, "path": str(path), "sha256": s}
277
+
278
+
279
+ def observed_deg(v: dict, contrast: dict) -> dict:
280
+ """Observed top-50 lists per DEG type (independent of the arm): F.deg_top on the observed donor x type sums."""
281
+ case, ctrl = contrast["case"], contrast["ctrl"]
282
+ out = {}
283
+ for ti, t in enumerate(v["deg_types"]):
284
+ d = F.deg_top(v["deg_n"][:, ti], keep_cols(v, v["deg_sum"][:, ti]), case, ctrl, keep_genes(v))
285
+ d["n_cells"] = int(v["deg_n"][case | ctrl, ti].sum())
286
+ out[t] = d
287
+ return out
288
+
289
+
290
+ def deg_block(v: dict, obs: dict, ga: dict, Xg, gen_d, gen_lab, bulk, contrast: dict) -> tuple[list, dict]:
291
+ """contrast.csv rows (statistic welch_top50_deg) and the summary block of the top-50 DEG overlap of one arm.
292
+ A type is scored when the observed Welch test is defined (>= 2 case and >= 2 control donors with a cell of the
293
+ type); an arm whose generated test is undefined there gets an empty list, i.e. overlap 0 (EV semantics)."""
294
+ t0 = time.monotonic()
295
+ S = v["donors"].size
296
+ case, ctrl = contrast["case"], contrast["ctrl"]
297
+ genes = keep_genes(v)
298
+ extra = tuple(t for t in v["deg_types"] if t not in F.CONTRAST_TYPES)
299
+ gx = F.type_aggregates(Xg, gen_d, gen_lab, S, types=extra) if extra else None
300
+ blk = F.deg_top(np.ones(S, np.int64), keep_cols(v, bulk), case, ctrl, genes) if bulk is not None else None
301
+ rows, per, lists = [], {}, []
302
+ for t in v["deg_types"]:
303
+ if t in F.CONTRAST_TYPES:
304
+ n_g, s_g = ga["n"][:, F.CONTRAST_TYPES.index(t)], keep_cols(v, ga["sum"][:, F.CONTRAST_TYPES.index(t)])
305
+ else:
306
+ n_g, s_g = gx["n"][:, extra.index(t)], keep_cols(v, gx["sum"][:, extra.index(t)])
307
+ od, gd = obs[t], F.deg_top(n_g, s_g, case, ctrl, genes)
308
+ ov = F.deg_overlap(od["top"], gd["top"])
309
+ bo = F.deg_overlap(od["top"], blk["top"]) if blk is not None else {"overlap": None, "jaccard": float("nan")}
310
+ row = {"celltype": t, "statistic": F.DEG_STATISTIC, "n_genes": len(genes), "deg_scored": od["defined"],
311
+ "top50_overlap": ov["overlap"], "top50_jaccard": ov["jaccard"],
312
+ "obs_top_list_size": len(od["top"]), "gen_top_list_size": len(gd["top"]),
313
+ "n_sig_obs": od["n_significant"], "n_sig_gen": gd["n_significant"],
314
+ "top50_overlap_broadcast": bo["overlap"], "top50_jaccard_broadcast": bo["jaccard"],
315
+ "broadcast_top_list_size": len(blk["top"]) if blk is not None else None,
316
+ "n_sig_broadcast": blk["n_significant"] if blk is not None else None,
317
+ "n_case_donors_obs": od["n_case_donors"], "n_control_donors_obs": od["n_control_donors"],
318
+ "n_case_donors_gen": gd["n_case_donors"], "n_control_donors_gen": gd["n_control_donors"],
319
+ "n_cells_obs": od["n_cells"], "n_cells_gen": int(n_g[case | ctrl].sum())}
320
+ rows.append(row)
321
+ per[t] = {k: (None if isinstance(row[k], float) and np.isnan(row[k]) else row[k])
322
+ for k in ("deg_scored", "top50_overlap", "top50_jaccard", "obs_top_list_size", "gen_top_list_size",
323
+ "top50_overlap_broadcast", "top50_jaccard_broadcast", "n_cells_obs", "n_cells_gen")}
324
+ for src, lst in (("observed", od["top"]), ("generated", gd["top"])):
325
+ lists += [{"celltype": t, "source": src, "rank": i + 1, "gene_id": g} for i, g in enumerate(lst)]
326
+ if blk is not None:
327
+ lists += [{"celltype": "all (input bulk)", "source": "broadcast", "rank": i + 1, "gene_id": g}
328
+ for i, g in enumerate(blk["top"])]
329
+ scored = [t for t in v["deg_types"] if obs[t]["defined"]]
330
+ four = [t for t in scored if t in F.CONTRAST_TYPES]
331
+
332
+ def tot(key, ts):
333
+ return None if key == "top50_overlap_broadcast" and blk is None else int(sum(per[t][key] for t in ts))
334
+
335
+ block = {"types_scored": scored,
336
+ "types_not_scored": {t: "observed Welch test undefined (< 2 case or < 2 control donors with a cell)"
337
+ for t in v["deg_types"] if not obs[t]["defined"]},
338
+ "per_type": per, "sum": tot("top50_overlap", scored), "sum_4type": tot("top50_overlap", four),
339
+ "max": tot("obs_top_list_size", scored), "mean": float(np.mean([per[t]["top50_overlap"] for t in scored]))
340
+ if scored else None,
341
+ "sum_broadcast": tot("top50_overlap_broadcast", scored), "sum_broadcast_4type": tot("top50_overlap_broadcast", four),
342
+ "broadcast_n_significant": blk["n_significant"] if blk is not None else None,
343
+ "seconds": round(time.monotonic() - t0, 2), "_lists": lists}
344
+ return rows, block
345
+
346
+
347
+ def arm_metrics(v: dict, Xg: sp.csr_matrix, gen_d: np.ndarray, gen_lab: np.ndarray, gen_pb: np.ndarray,
348
+ bulk: np.ndarray | None, contrast: dict, obs_deg: dict | None = None) -> tuple[pd.DataFrame, dict, list, np.ndarray]:
349
+ """All metrics of one arm from arrays: Xg = Poisson-read counts on the scoring genes (scored donors' cells),
350
+ gen_d = scored-donor index per cell, gen_lab = frozen six-type label per cell, gen_pb = summed generated_counts
351
+ per scored donor on the scoring genes, bulk = condition bulk_counts per scored donor on the scoring genes,
352
+ obs_deg = observed_deg(v, contrast) (None: no top-50 DEG score)."""
353
+ donors = v["donors"]
354
+ S = donors.size
355
+ counts_per = np.bincount(gen_d, minlength=S)
356
+ if (counts_per == 0).any():
357
+ raise SystemExit(f"scored donors without generated cells: {list(donors[counts_per == 0][:5])}")
358
+ # 1. composition
359
+ gc = F.IC.composition(pd.Series(gen_lab), pd.Series(donors[gen_d]), donors).to_numpy()
360
+ oc = v["comp"]
361
+ l1 = F.IC.l1(gc, oc)
362
+ null = F.IC.l1(oc, F.lodo_mean(oc, v["donor_of"])) if S > 1 else np.full(S, np.nan)
363
+ gen_loo = F.IC.l1(F.lodo_mean(gc, v["donor_of"]), oc) if S > 1 else np.full(S, np.nan)
364
+ pair = np.abs(gc[:, None, :] - oc[None, :, :]).sum(-1)
365
+ # 2. pseudobulk agreement + closest donor among the scored donors
366
+ obs = F.IC.ER.cpm_log1p(v["pb"])
367
+ gen = F.IC.ER.cpm_log1p(gen_pb)
368
+ rr = F.IC.retrieval(gen, obs, np.arange(S))
369
+ paired = F.IC.ER.paired_r(gen, obs)
370
+ # 3. precision / coverage (+ depth matched)
371
+ sub = []
372
+ for s in range(S):
373
+ rs = np.flatnonzero(gen_d == s)
374
+ sub.append(rs[F.generated_subsample(rs.size, int(v["n_ref"][s]), donors[s])])
375
+ sub = np.concatenate(sub)
376
+ Q, q_d = Xg[sub].tocsr(), gen_d[sub]
377
+ zq = F.SB.project(Q, v["mean"], v["comps"])
378
+ pc = F.SB.precision_coverage(v["z1"], v["radius"], zq)
379
+ dm = depth_matched(v, Q, q_d)
380
+ nq = np.bincount(q_d, minlength=S)
381
+ n1 = np.bincount(v["r1_d"], minlength=S)
382
+ per_prec = np.bincount(q_d, weights=pc["inside"], minlength=S) / nq
383
+ per_cov = np.bincount(v["r1_d"], weights=pc["covered"], minlength=S) / n1
384
+ per_prec_dm = np.bincount(q_d, weights=dm["inside"], minlength=S) / nq
385
+ per_cov_dm = np.bincount(v["r1_d"], weights=dm["covered"], minlength=S) / n1
386
+ # 4. monocyte %, median UMI per cell (scoring genes)
387
+ mj = F.GATE.index("Monocyte")
388
+ glib = np.asarray(Xg.sum(axis=1)).ravel()
389
+ med_gen = np.asarray([np.median(glib[gen_d == s]) for s in range(S)])
390
+ per = pd.DataFrame({"donor": donors, "group": v["groups"], "n_generated_cells": counts_per,
391
+ "n_observed_cells": v["n_cells"], "n_reference_cells": v["n_ref"]})
392
+ for j, g in enumerate(F.GATE):
393
+ per[f"gen_{g}"] = gc[:, j]
394
+ per[f"obs_{g}"] = oc[:, j]
395
+ per["comp_l1"] = l1
396
+ per["comp_l1_obs_loo_null"] = null
397
+ per["pb_r"] = paired
398
+ per["pb_own_rank"] = rr["rank"]
399
+ per["pb_top1"] = rr["rank"] == 1
400
+ per["precision"] = per_prec
401
+ per["coverage"] = per_cov
402
+ per["precision_depth_matched"] = per_prec_dm
403
+ per["coverage_depth_matched"] = per_cov_dm
404
+ per["mono_pct_gen"] = 100 * gc[:, mj]
405
+ per["mono_pct_obs"] = 100 * oc[:, mj]
406
+ per["median_umi_gen"] = med_gen
407
+ per["median_umi_obs"] = v["obs_lib_median_d"]
408
+ summ = {
409
+ "n_donors": int(S), "n_generated_cells": int(gen_d.size),
410
+ "composition": {"l1_mean": float(l1.mean()), "l1_median": float(np.median(l1)),
411
+ "l1_obs_loo_null_mean": float(np.nanmean(null)) if S > 1 else None,
412
+ "l1_generated_loo_mean_vs_observed_mean": float(np.nanmean(gen_loo)) if S > 1 else None,
413
+ "composition_top1": float((pair.argmin(1) == np.arange(S)).mean()),
414
+ "mean_fraction_generated": dict(zip(F.GATE, gc.mean(0).round(6).tolist())),
415
+ "mean_fraction_observed": dict(zip(F.GATE, oc.mean(0).round(6).tolist()))},
416
+ "pseudobulk": {"n_genes": int(gen.shape[1]), "r_median": float(np.median(paired)), "r_mean": float(paired.mean()),
417
+ "top1": float(rr["top1"]), "n_top1": int((rr["rank"] == 1).sum()),
418
+ "own_rank_median": float(np.median(rr["rank"])), "chance_top1": 1.0 / S},
419
+ "precision_coverage": {"precision": pc["precision"], "coverage": pc["coverage"], "density": pc["density"],
420
+ "n_query": int(zq.shape[0]), "n_reference": int(v["z1"].shape[0])},
421
+ "precision_coverage_depth_matched": {"precision": dm["precision"], "coverage": dm["coverage"], "density": dm["density"],
422
+ "detected_median_before": dm["summary"]["detected_median_before"].to_dict(),
423
+ "detected_median_after": dm["summary"]["detected_median_after"].to_dict()},
424
+ "monocyte_pct": {"generated_mean_over_donors": float(100 * gc[:, mj].mean()),
425
+ "observed_mean_over_donors": float(100 * oc[:, mj].mean()),
426
+ "generated_pooled_cells": float(100 * (gen_lab == "Monocyte").mean())},
427
+ "median_umi_per_cell_scoring_genes": {"generated_pooled": float(np.median(glib)),
428
+ "observed_pooled": float(np.median(v["cell_lib"])),
429
+ "generated_mean_of_donor_medians": float(med_gen.mean()),
430
+ "observed_mean_of_donor_medians": float(v["obs_lib_median_d"].mean())},
431
+ }
432
+ # 5. group contrast
433
+ crow = []
434
+ if contrast.get("enabled"):
435
+ case, ctrl = contrast["case"], contrast["ctrl"]
436
+ ga = F.type_aggregates(Xg, gen_d, gen_lab, S)
437
+ blk = F.bulk_lfc(bulk, case, ctrl) if bulk is not None else {"mean_cp10k": None, "pseudobulk_log1p_cpm": None}
438
+ for ti, t in enumerate(F.CONTRAST_TYPES):
439
+ n_o = v["agg_n"][:, ti]
440
+ det = v["agg_det"][:, ti].sum(0) / max(int(n_o.sum()), 1)
441
+ genes = det >= F.MIN_DETECT_FRAC
442
+ if "keep" in v: # --exclude-genes
443
+ genes &= v["keep"]
444
+ for variant, fn, key in (("mean_cp10k", F.lfc_mean_cp10k, "cp10k"),
445
+ ("pseudobulk_log1p_cpm", F.lfc_pseudobulk, "sum")):
446
+ o = fn(n_o, v[f"agg_{key}"][:, ti], case, ctrl)
447
+ g = fn(ga["n"][:, ti], ga[key][:, ti], case, ctrl)
448
+ row = {"celltype": t, "statistic": variant, **F.contrast_scores(o, g, blk[variant], genes),
449
+ "n_case_donors_obs": int((case & (n_o > 0)).sum()), "n_control_donors_obs": int((ctrl & (n_o > 0)).sum()),
450
+ "n_case_donors_gen": int((case & (ga["n"][:, ti] > 0)).sum()),
451
+ "n_control_donors_gen": int((ctrl & (ga["n"][:, ti] > 0)).sum()),
452
+ "n_cells_obs": int(n_o[case | ctrl].sum()), "n_cells_gen": int(ga["n"][case | ctrl, ti].sum())}
453
+ crow.append(row)
454
+ cdf = pd.DataFrame(crow)
455
+ summ["contrast"] = {}
456
+ for variant, sub_ in cdf.groupby("statistic", sort=False):
457
+ summ["contrast"][variant] = {
458
+ "per_type": {r.celltype: {k: (None if isinstance(r[k], float) and np.isnan(r[k]) else r[k])
459
+ for k in ("r_generated", "r_broadcast", "partial_r_generated_given_broadcast",
460
+ "r_generated_vs_broadcast", "n_genes")} for _, r in sub_.iterrows()},
461
+ "mean_r_generated": float(np.nanmean(sub_.r_generated)) if sub_.r_generated.notna().any() else None,
462
+ "mean_r_broadcast": float(np.nanmean(sub_.r_broadcast)) if sub_.r_broadcast.notna().any() else None,
463
+ "mean_partial_r": float(np.nanmean(sub_.partial_r_generated_given_broadcast))
464
+ if sub_.partial_r_generated_given_broadcast.notna().any() else None}
465
+ if obs_deg is not None:
466
+ drows, summ["deg_top50"] = deg_block(v, obs_deg, ga, Xg, gen_d, gen_lab, bulk, contrast)
467
+ crow += drows
468
+ return per, summ, crow, sub
469
+
470
+
471
+ def score_arm(arm: dict, v: dict, ref: dict, man: dict, spec: F.DatasetSpec, contrast: dict, out: Path, a,
472
+ obs_deg: dict | None = None) -> tuple:
473
+ t0 = time.monotonic()
474
+ name, d = arm["name"], arm["d"]
475
+ donors = v["donors"]
476
+ npos = {n: i for i, n in enumerate(arm["sample_ids"])}
477
+ rows = [np.flatnonzero(arm["bulk_index"] == npos[x]) for x in donors]
478
+ sel = np.concatenate(rows)
479
+ gen_d = np.repeat(np.arange(donors.size), [r.size for r in rows])
480
+ F.log(f"{name}: loading generated_counts ({arm['bulk_index'].size} cells in the NPZ, {sel.size} scored)")
481
+ rates = np.ascontiguousarray(d["generated_counts"], dtype=np.float32)
482
+ full = F.PR.poisson_integerise(rates, seed=F.POISSON_SEED, chunk_rows=4096) # one read-out of the whole NPZ
483
+ nnz_full = int(full.nnz)
484
+ lib_full_median = float(np.median(np.asarray(full.sum(1)).ravel()))
485
+ score_idx = ref["score_idx"]
486
+ gen_pb = np.vstack([rates[r].sum(0) for r in rows]).astype(np.float64)[:, score_idx] # score_generated.py arithmetic
487
+ del rates
488
+ counts = full[sel].tocsr()
489
+ del full
490
+ F.log(f"{name}: Poisson read-out nnz {nnz_full} (whole NPZ), median library {lib_full_median:.0f}; annotating")
491
+ work = out / "arms" / name
492
+ if a.reuse_labels is not None:
493
+ lab, linfo = reused_labels(a.reuse_labels, name, arm, man["reference_sha256"], donors, sel, gen_d, work)
494
+ else:
495
+ lab, linfo = F.run_annotator(counts[:, man["_query_panel_idx"]], list(ref["query_ids"].astype(str)),
496
+ np.asarray([f"{x}|generated" for x in donors[gen_d]], dtype=object), work=work,
497
+ method=name, spec=spec, split="generated", threads=a.threads, annot=a.annot,
498
+ expected_zero_pad=man["gene_sets"]["model_genes_missing_from_query"],
499
+ source_note={"kind": "generated_npz", "readout": "poisson", "seed": F.POISSON_SEED,
500
+ "source_path": str(arm["path"]), "source_sha256": arm["sha256"],
501
+ "poisson_note": "one draw over the whole NPZ, then the scored donors' rows"})
502
+ gen_lab = lab.celltype_l1_pred.astype(str).to_numpy()
503
+ Xg = counts[:, score_idx].tocsr()
504
+ del counts
505
+ bulk, cond = None, None
506
+ if contrast.get("enabled"):
507
+ cpath = a.condition_map.get(name, arm["condition"])
508
+ cond = load_condition_bulk(cpath, arm["condition_sha256"] if cpath == arm["condition"] else None, donors,
509
+ ref["score_ids"].astype(str))
510
+ bulk = cond["bulk"]
511
+ per, summ, crow, sub = arm_metrics(v, Xg, gen_d, gen_lab, gen_pb, bulk, contrast, obs_deg)
512
+ in_sub = np.zeros(sel.size, bool)
513
+ in_sub[sub] = True
514
+ pd.DataFrame({"npz_row": sel, "donor": donors[gen_d], "label": gen_lab,
515
+ "umi_scoring_genes": np.asarray(Xg.sum(axis=1)).ravel().astype(np.float32),
516
+ "in_pc_subsample": in_sub}).to_parquet(work / "generated_cells.parquet", index=False)
517
+ if "deg_top50" in summ:
518
+ pd.DataFrame(summ["deg_top50"].pop("_lists"), columns=["celltype", "source", "rank", "gene_id"]).to_csv(
519
+ work / "deg_top50_lists.csv", index=False)
520
+ per.insert(0, "arm", name)
521
+ for r in crow:
522
+ r["arm"] = name
523
+ summ = {"arm": name, "npz": str(arm["path"]), "npz_sha256": arm["sha256"], "receipt_verified": arm["receipt_verified"],
524
+ "generation": {k: arm["meta"].get(k) for k in ("checkpoint", "checkpoint_sha256", "input_condition_path",
525
+ "input_condition_sha256", "seed", "steps", "support_readout", "weights")},
526
+ "condition_for_broadcast": {k: cond[k] for k in ("path", "sha256")} if cond else None,
527
+ "poisson": {"seed": F.POISSON_SEED, "rule": "whole NPZ, rows in NPZ order", "nnz_whole_npz": nnz_full,
528
+ "median_library_whole_npz_panel": lib_full_median, "n_rows_whole_npz": int(arm["bulk_index"].size)},
529
+ "annotation": {k: linfo[k] for k in ("model_pt_sha256", "zero_padded_model_genes", "label_counts",
530
+ "mean_l2_max_prob", "predict_seconds")}
531
+ | {k: linfo[k] for k in ("reused_from", "reused_labels_sha256") if k in linfo},
532
+ **summ, "seconds": round(time.monotonic() - t0, 1)}
533
+ F.log(f"{name}: L1 {summ['composition']['l1_mean']:.4f} (null {summ['composition']['l1_obs_loo_null_mean']}) "
534
+ f"P/C {summ['precision_coverage']['precision']:.4f}/{summ['precision_coverage']['coverage']:.4f} "
535
+ f"pb r {summ['pseudobulk']['r_median']:.4f} top1 {summ['pseudobulk']['top1']:.3f} "
536
+ f"mono {summ['monocyte_pct']['generated_mean_over_donors']:.1f}% ({summ['seconds']} s)")
537
+ if "deg_top50" in summ:
538
+ dg = summ["deg_top50"]
539
+ F.log(f"{name}: top-50 DEG {dg['sum']}/{dg['max']} ("
540
+ + ", ".join(f"{F.SHORT_TYPE.get(t, t)} {dg['per_type'][t]['top50_overlap']}" for t in dg["types_scored"])
541
+ + f"); broadcast {dg['sum_broadcast']} ({dg['seconds']} s)")
542
+ return per, summ, crow
543
+
544
+
545
+ # --------------------------------------------------------------------------- README
546
+ def readme(spec: F.DatasetSpec, man: dict, v: dict, contrast: dict, summary: dict) -> str:
547
+ c = contrast
548
+ ctext = (f"case groups {c['case_groups']} (n = {c['n_case_donors']}) vs control groups {c['control_groups']} "
549
+ f"(n = {c['n_control_donors']}); rule: {c['rule']}; groups from {c['group_source']}."
550
+ if c.get("enabled") else f"not computed ({c.get('reason')}).")
551
+ dd = summary.get("deg_definition") or {}
552
+ if dd.get("enabled"):
553
+ ns = dd["types_not_scored_observed"]
554
+ dtext = f"""the SLE benchmark's score (`total_top50_overlap` of
555
+ `bulk2sc-paper/scripts/evaluate_generated_vs_truth.py`, Welch backend: the "top-50 DEG 81 / 84" of the final model), run
556
+ with the evaluator's own functions on the same donor x type pseudobulks as the contrast. Per cell type, observed and
557
+ generated separately: donor x type summed counts on all {len(v['score_ids'])} scoring genes (donors of the two groups with
558
+ >= 1 cell of the type) -> `welch_bh_deg` (log1p CPM, two-sided Welch t-test case vs control, Benjamini-Hochberg over the
559
+ genes with a defined p-value; needs >= 2 donors per group) -> `top_deg_genes` (FDR < {F.DEG_FDR:g}, descending |logFC|,
560
+ first {F.DEG_TOP_N}; shorter when fewer genes pass). `top50_overlap` = |observed list & generated list|; `top50_jaccard`
561
+ the evaluator's Jaccard. Summary `sum` = total over the scored types (the quantity reported as 81), `max` = the sum of
562
+ the observed list lengths (the "of 262"), `sum_4type` = T + B + Monocyte + NK. A type is scored when its observed test
563
+ is defined; an arm whose generated test is undefined for a scored type gets overlap 0. Types: {', '.join(dd['types'])}
564
+ (aggregates: {dd['aggregates_source']}){'; not scored: ' + ', '.join(ns) if ns else ''}.
565
+ **Broadcast analogue** (`top50_overlap_broadcast`, as `sle_broadcast.py` `broadcast_input_bulk`; not part of the
566
+ published benchmark): the same test on the arm's condition bulk_counts (scoring genes, the {c.get('n_case_donors')} + {c.get('n_control_donors')}
567
+ donors), one whole-PBMC top-{F.DEG_TOP_N} list, compared with every type's observed list."""
568
+ else:
569
+ dtext = f"not computed ({dd.get('reason', 'contrast off')})."
570
+ return f"""# score_ft.py output: {spec.name}, {v['donors'].size} scored donors
571
+
572
+ Arms: {', '.join(summary['arms'])}. Every arm is scored on the same donors against the same observed reference.
573
+
574
+ ## Inputs and fixed contracts
575
+ - Observed reference: `{man['reference_npz']}` (sha {man['reference_sha256'][:12]}), built from {man['cells']['source']};
576
+ observed cells sum exactly to the features pseudobulk of every donor. Observed labels: {man['labels'].get('source', man['labels'].get('labels_parquet'))}.
577
+ - Generated cells: `generated_counts` read out once with Poisson(seed {F.POISSON_SEED}) over the **whole NPZ in row order**
578
+ (`poisson_readout.poisson_integerise`), then the scored donors' rows. These integer counts are used for labels, embedding,
579
+ depth and the contrast. Pseudobulk uses the summed `generated_counts` (rates), as `score_generated.py`.
580
+ - Labels: frozen f01common scANVI (`predict_scanvi.py`, CPU, zero query epochs), six-type gate {list(F.GATE)}; query genes =
581
+ the 1,006-gene annotation list minus genes the dataset's sc assay did not measure in every sample ({man['gene_sets']['query']} genes).
582
+ - Scoring genes: 6k panel genes measured by both assays in every sample of the dataset ({man['gene_sets']['scoring']} genes).
583
+
584
+ ## Definitions
585
+ 1. **Composition**: fraction of each donor's cells per six-type label (all generated cells; all observed QC cells).
586
+ `comp_l1` = sum over the six labels of |generated - observed| (immicro_common.l1). `comp_l1_obs_loo_null` = L1 of the
587
+ donor's observed composition to the mean of the *other scored donors'* observed compositions. `composition_top1` =
588
+ fraction of donors whose generated composition is closest (L1) to their own observed composition.
589
+ 2. **Pseudobulk**: `pb_r` = Pearson r of CPM-log1p(summed generated_counts) vs CPM-log1p(observed pseudobulk) on the scoring
590
+ genes (evaluate_realbulk.cpm_log1p / paired_r). `pb_top1` = the donor's generated pseudobulk is closest (Pearson) to its own
591
+ observed pseudobulk among the {v['donors'].size} scored donors (immicro_common.retrieval = evaluate_realbulk.top1 arithmetic).
592
+ 3. **Precision / coverage / density** (stage_b_embed.py functions): per-cell CP10K over the scoring genes + log1p; PCA-50
593
+ (randomized, random_state {F.SUB_SEED}) and k = {F.K_NN} real-real k-NN balls fitted on **R1 of the scored donors only**.
594
+ Reference rule (independent of fold and arm): per donor, cells in canonical order ({man['cells']['key_rule']}), one
595
+ permutation from `default_rng([{F.SUB_SEED}, uint64(sha256(donor)[:8])])`; R1 = first n, R2 = next n,
596
+ n = min({F.N_SUB}, n_cells // 2) ({v['n_ref'].sum()} R1 cells here). Generated query: per donor n cells (the donor's R1 size),
597
+ without replacement, `default_rng([{F.GEN_SUB_SEED}, same key])`. Precision = fraction of generated cells inside any R1 ball
598
+ (Kynkaanniemi 2019); coverage = fraction of R1 cells whose ball holds a generated cell; density = Naeem 2020.
599
+ Per-donor precision = that donor's generated cells; per-donor coverage = that donor's R1 cells (the pooled values are
600
+ their n-weighted means; plain means when every donor has {F.N_SUB} reference cells). R2 (held-out real cells of the same donors) is the
601
+ perfect-generator control: precision {v['r2_control']['precision']:.4f}, coverage {v['r2_control']['coverage']:.4f}.
602
+ **Depth matched**: stage_b_embed depth matching run pairwise (R1 vs this arm): per donor and within-donor rank of detected
603
+ genes, both cells are thinned by UMI sampling without replacement to the smaller detected-gene count; PCA kept from
604
+ un-thinned R1, radii recomputed on thinned R1; fresh rng({F.DEPTH_SEED}) per arm. R2 control: precision
605
+ {v['r2_control']['depth_matched']['precision']:.4f}, coverage {v['r2_control']['depth_matched']['coverage']:.4f}.
606
+ 4. **Monocyte %** = 100 x Monocyte fraction (all cells) per donor; **median UMI per cell** = median over cells of the
607
+ Poisson-read (generated) / observed counts summed over the scoring genes (per donor, and pooled).
608
+ 5. **Group contrast** (T, B, Monocyte, NK): {ctext}
609
+ Genes per type = scoring genes detected (count > 0) in >= {100 * F.MIN_DETECT_FRAC:g} % of the scored donors' observed
610
+ cells of that type. Primary statistic `mean_cp10k`: per-cell CP10K over the scoring genes; per donor the mean over its
611
+ cells of the type (donors with >= 1 such cell); group mean = mean over the group's donors (donor-balanced);
612
+ logFC = log2(case mean + 1) - log2(control mean + 1). Secondary `pseudobulk_log1p_cpm`: the SLE benchmark evaluator's
613
+ statistic (donor x type summed counts, log1p CPM over the scoring genes, mean case - mean control;
614
+ evaluate_generated_vs_truth.group_log_fold_change). Both are computed on the generated cells (their frozen labels) and on
615
+ the observed cells; `r_generated` = Pearson r of the two logFC vectors. Broadcast baseline `r_broadcast`: the same
616
+ observed vector against the logFC of the input bulk (condition NPZ `bulk_counts` of the arm, scoring genes, per-donor
617
+ CP10K resp. log1p CPM, group means). `partial_r_generated_given_broadcast`: r of the OLS residuals of observed and
618
+ generated logFC on the bulk logFC (residual_specificity.py).
619
+ 6. **Top-50 DEG overlap** (contrast.csv rows `statistic = {F.DEG_STATISTIC}`; summary `deg_top50`): {dtext}
620
+
621
+ ## Files
622
+ - `per_donor.csv`: one row per arm x donor (all per-donor quantities above).
623
+ - `summary.json`: per arm the donor means / pooled values, provenance (NPZ sha, receipt check, generation metadata,
624
+ Poisson nnz of the whole NPZ, annotation contract), and the reference block (PCA, R2 control).
625
+ - `contrast.csv`: per arm x cell type x statistic (`mean_cp10k`, `pseudobulk_log1p_cpm`: logFC r; `{F.DEG_STATISTIC}`:
626
+ top-50 DEG overlap, T / B / Monocyte / NK / DC; columns of the other kind are empty).
627
+ - `arms/<arm>/labels/` (predict_scanvi.py labels + manifest), `arms/<arm>/generated_cells.parquet` (NPZ row, donor, label,
628
+ UMI on the scoring genes, P/C subsample flag), `arms/<arm>/deg_top50_lists.csv` (observed, generated and broadcast
629
+ top-50 gene lists, Ensembl ids, rank order).
630
+ """
631
+
632
+
633
+ def deg_headline(dg: dict) -> dict:
634
+ """Headline columns of the top-50 DEG score: per scored type, the sum (reported like the SLE 81), its maximum
635
+ (sum of the observed list lengths), the four-contrast-type sum and the broadcast sum."""
636
+ return {**{f"deg_top50_{F.SHORT_TYPE.get(t, t)}": dg["per_type"][t]["top50_overlap"] for t in dg["types_scored"]},
637
+ "deg_top50_sum": dg["sum"], "deg_top50_max": dg["max"], "deg_top50_sum_4type": dg["sum_4type"],
638
+ "deg_top50_sum_broadcast": dg["sum_broadcast"]}
639
+
640
+
641
+ # --------------------------------------------------------------------------- main
642
+ def parse(argv=None):
643
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
644
+ p.add_argument("--dataset", choices=sorted(F.DATASETS), required=True)
645
+ p.add_argument("--build-reference", action="store_true")
646
+ p.add_argument("--build-deg-reference", action="store_true",
647
+ help="add deg_reference.npz (donor x type aggregates incl. DC) to an existing reference cache")
648
+ p.add_argument("--no-deg", action="store_true", help="skip the top-50 DEG overlap (default: on with the contrast)")
649
+ p.add_argument("--cells-source", choices=["auto", "datadir", "immicro_h5ad"], default="auto")
650
+ p.add_argument("--reference", type=Path, default=None, help="reference cache dir (default scoring_cache/<dataset>)")
651
+ p.add_argument("--arm", action="append", default=[], help="NAME=GENERATED_NPZ (repeatable)")
652
+ p.add_argument("--out", type=Path)
653
+ p.add_argument("--donors", default=None, help="comma list or a file with one sample id per line")
654
+ p.add_argument("--groups-csv", default=None)
655
+ p.add_argument("--case-groups", default=None)
656
+ p.add_argument("--control-groups", default=None)
657
+ p.add_argument("--no-contrast", action="store_true")
658
+ p.add_argument("--condition", action="append", default=[], help="ARM=CONDITION_NPZ override for the broadcast")
659
+ p.add_argument("--allow-no-receipt", action="store_true")
660
+ p.add_argument("--annot", type=Path, default=None, help="annotator run dir (default: server_1 run or server_2 mirror)")
661
+ p.add_argument("--threads", type=int, default=8)
662
+ p.add_argument("--exclude-genes", type=Path, default=None,
663
+ help="CSV with a gene_id column: drop these genes from the contrast logFC r / broadcast / partial r "
664
+ "and the top-50 DEG tests (other metrics unchanged)")
665
+ p.add_argument("--reuse-labels", type=Path, default=None,
666
+ help="earlier score_ft.py output dir: reuse its arms/<arm>/labels instead of running predict_scanvi.py")
667
+ return p.parse_args(argv)
668
+
669
+
670
+ def main(argv=None) -> int:
671
+ a = parse(argv)
672
+ t0 = time.monotonic()
673
+ if not 1 <= a.threads <= MAX_THREADS:
674
+ raise SystemExit(f"--threads must be 1..{MAX_THREADS} on the shared hosts")
675
+ try:
676
+ from threadpoolctl import threadpool_limits
677
+ threadpool_limits(a.threads)
678
+ except ImportError:
679
+ pass
680
+ spec = F.DATASETS[a.dataset]
681
+ cache = a.reference or (F.CACHE_ROOT / spec.name)
682
+ a.annot = F.annotator_run(a.annot)
683
+ if a.build_reference:
684
+ F.build_reference(spec, cache, source={"immicro_h5ad": "h5ad"}.get(a.cells_source, a.cells_source),
685
+ threads=a.threads, annot=a.annot)
686
+ return 0
687
+ if a.build_deg_reference:
688
+ F.build_deg_reference(spec, cache)
689
+ return 0
690
+ if not a.arm or a.out is None:
691
+ raise SystemExit("--arm NAME=NPZ (at least one) and --out are required")
692
+ ref, man = F.load_reference(cache)
693
+ if not a.no_deg:
694
+ ref["deg"] = F.load_deg_reference(cache, man, ref)
695
+ panel_ids = ref["panel_ids"].astype(str)
696
+ ppos = {g: i for i, g in enumerate(panel_ids)}
697
+ man["_query_panel_idx"] = np.asarray([ppos[g] for g in ref["query_ids"].astype(str)], dtype=np.int64)
698
+ arms, seen = [], set()
699
+ for s in a.arm:
700
+ name, _, path = s.partition("=")
701
+ if not name or not path or name in seen or not name.replace("_", "").replace("-", "").isalnum():
702
+ raise SystemExit(f"bad or duplicate --arm {s!r} (NAME=PATH, NAME alphanumeric/_/-)")
703
+ seen.add(name)
704
+ arms.append(open_arm(name, Path(path), panel_ids, a.allow_no_receipt))
705
+ a.condition_map = dict(x.split("=", 1) for x in a.condition)
706
+ ref_order = {d: i for i, d in enumerate(ref["donors"].astype(str))}
707
+ if a.donors:
708
+ p = Path(a.donors)
709
+ want = [x.strip().split(",")[0] for x in p.read_text().splitlines() if x.strip()] if p.is_file() else a.donors.split(",")
710
+ for arm in arms:
711
+ miss = sorted(set(want) - set(arm["sample_ids"]))
712
+ if miss:
713
+ raise SystemExit(f"{arm['name']}: NPZ lacks scored donors {miss[:5]}")
714
+ else:
715
+ want = list(arms[0]["sample_ids"])
716
+ for arm in arms[1:]:
717
+ if set(arm["sample_ids"]) != set(want):
718
+ raise SystemExit(f"{arm['name']}: sample_ids differ from {arms[0]['name']}'s; every arm must cover the same donors")
719
+ if len(set(want)) != len(want):
720
+ raise SystemExit("duplicate donors")
721
+ miss = [d for d in want if d not in ref_order]
722
+ if miss:
723
+ raise SystemExit(f"donors not in the {spec.name} reference: {miss[:5]}")
724
+ donors = sorted(want, key=ref_order.get)
725
+ a.out.mkdir(parents=True, exist_ok=True)
726
+ F.log(f"{spec.name}: {len(donors)} scored donors, {len(arms)} arm(s); fitting the observed reference")
727
+ v = make_view(ref, donors)
728
+ gene_excl = None
729
+ if a.exclude_genes is not None:
730
+ v["keep"], gene_excl = gene_exclusion(a.exclude_genes, v["score_ids"])
731
+ F.log(f"--exclude-genes: {gene_excl['n_dropped_from_scoring_genes']} of {gene_excl['n_listed']} listed genes are "
732
+ f"scoring genes; contrast and DEG use {gene_excl['n_scoring_genes_kept']} of {gene_excl['n_scoring_genes']}")
733
+ feat = F.load_features(spec.features) # sample -> donor, for the leave-donor-out composition null
734
+ d_of = dict(zip(feat["sample_ids"].astype(str), feat["donor_ids"].astype(str)))
735
+ v["donor_of"] = np.asarray([d_of[d] for d in v["donors"]], dtype=str)
736
+ contrast = resolve_contrast(spec, v, a)
737
+ F.log(f"reference: R1 {v['z1'].shape[0]} cells, PCA var {v['pca']['explained_variance_ratio_sum']:.3f}, "
738
+ f"R2 control P/C {v['r2_control']['precision']:.4f}/{v['r2_control']['coverage']:.4f}; contrast "
739
+ f"{'on' if contrast.get('enabled') else 'off'}")
740
+ obs_deg, deg_def = None, {"enabled": False}
741
+ if a.no_deg:
742
+ deg_def["reason"] = "--no-deg"
743
+ elif not contrast.get("enabled"):
744
+ deg_def["reason"] = "contrast off"
745
+ else:
746
+ obs_deg = observed_deg(v, contrast)
747
+ deg_def = {
748
+ "enabled": True, "score": "top-50 DEG overlap per cell type (benchmark total_top50_overlap, Welch backend)",
749
+ "source": str(F.EV_PATH), "functions": ["welch_bh_deg", "top_deg_genes", "jaccard"],
750
+ "reproduces": "utility_studies_final6k_20260925/sle top-50 DEG 81 (1,006 genes) / 84 (2,279 genes) = "
751
+ "sum over the six gated types of top50_overlap_count",
752
+ "top_n": F.DEG_TOP_N, "fdr": F.DEG_FDR, "n_genes": len(v["score_ids"]), "types": list(v["deg_types"]),
753
+ "aggregates_source": ref["deg"]["source"], "aggregates_sha256": ref["deg"]["sha256"],
754
+ "aggregates_note": ref["deg"]["note"],
755
+ "types_not_scored_observed": [t for t, d in obs_deg.items() if not d["defined"]],
756
+ "observed": {t: {k: d[k] for k in ("n_significant", "n_tested", "n_case_donors", "n_control_donors", "n_cells")}
757
+ | {"top_list_size": len(d["top"])} for t, d in obs_deg.items()},
758
+ "broadcast": "welch_bh_deg + top_deg_genes on the arm's condition bulk_counts (scoring genes, case|control "
759
+ "donors), one list compared with every type's observed list (sle_broadcast.py broadcast_input_bulk); "
760
+ "not part of the published benchmark"}
761
+ if gene_excl is not None:
762
+ deg_def["n_genes"] = gene_excl["n_scoring_genes_kept"]
763
+ F.log("observed top-50 DEG lists: " + ", ".join(
764
+ f"{F.SHORT_TYPE.get(t, t)} {len(d['top'])} (sig {d['n_significant']}, {d['n_case_donors']}+{d['n_control_donors']} donors, "
765
+ f"{d['n_cells']} cells)" for t, d in obs_deg.items()))
766
+ pers, summs, crows = [], {}, []
767
+ for arm in arms:
768
+ per, summ, crow = score_arm(arm, v, ref, man, spec, contrast, a.out, a, obs_deg)
769
+ pers.append(per)
770
+ summs[arm["name"]] = summ
771
+ crows += crow
772
+ arm["d"].close()
773
+ pd.concat(pers, ignore_index=True).to_csv(a.out / "per_donor.csv", index=False)
774
+ if crows:
775
+ cols = ["arm", "celltype", "statistic"]
776
+ cdf = pd.DataFrame(crows)
777
+ for c in ("top50_overlap", "obs_top_list_size", "gen_top_list_size", "n_sig_obs", "n_sig_gen",
778
+ "top50_overlap_broadcast", "broadcast_top_list_size", "n_sig_broadcast"):
779
+ if c in cdf.columns: # integer counts on the DEG rows, empty on the logFC rows
780
+ cdf[c] = cdf[c].astype("Int64")
781
+ if "deg_scored" in cdf.columns:
782
+ cdf["deg_scored"] = cdf["deg_scored"].astype("boolean")
783
+ cdf[cols + [c for c in cdf.columns if c not in cols]].to_csv(a.out / "contrast.csv", index=False)
784
+ headline = {n: {"comp_l1": s["composition"]["l1_mean"], "comp_l1_obs_loo_null": s["composition"]["l1_obs_loo_null_mean"],
785
+ "precision": s["precision_coverage"]["precision"], "coverage": s["precision_coverage"]["coverage"],
786
+ "precision_dm": s["precision_coverage_depth_matched"]["precision"],
787
+ "coverage_dm": s["precision_coverage_depth_matched"]["coverage"],
788
+ "pb_r_median": s["pseudobulk"]["r_median"], "pb_top1": s["pseudobulk"]["top1"],
789
+ "mono_pct_gen": s["monocyte_pct"]["generated_mean_over_donors"],
790
+ "mono_pct_obs": s["monocyte_pct"]["observed_mean_over_donors"],
791
+ "median_umi_gen": s["median_umi_per_cell_scoring_genes"]["generated_pooled"],
792
+ "median_umi_obs": s["median_umi_per_cell_scoring_genes"]["observed_pooled"],
793
+ **({f"contrast_{k}_r_gen": s["contrast"][k]["mean_r_generated"] for k in s["contrast"]} if "contrast" in s else {}),
794
+ **({f"contrast_{k}_r_broadcast": s["contrast"][k]["mean_r_broadcast"] for k in s["contrast"]} if "contrast" in s else {}),
795
+ **(deg_headline(s["deg_top50"]) if "deg_top50" in s else {}),
796
+ "seconds": s["seconds"]} for n, s in summs.items()}
797
+ code = {str(p): F.sha(p) for p in (Path(__file__).resolve(), Path(F.__file__).resolve(), F.SB_PATH, F.EV_PATH,
798
+ Path(F.IC.__file__).resolve(), F.IC.PREDICT, F.IC.REBUILD / "poisson_readout.py")}
799
+ summary = {"schema": "paired_ft_scores.v1", "dataset": spec.name, "written_utc": F.now(), "command": sys.argv,
800
+ "arms": list(summs), "donors": donors, "n_donors": len(donors),
801
+ "reference": {"cache": str(cache), "reference_sha256": man["reference_sha256"], "features_sha256": man["features"]["sha256"],
802
+ "n_r1_cells": int(v["z1"].shape[0]), "pca": v["pca"], "r2_control": v["r2_control"],
803
+ "observed_l1_loo_null_mean": float(np.mean(F.IC.l1(v["comp"], F.lodo_mean(v["comp"], v["donor_of"])))) if len(donors) > 1 else None},
804
+ "contrast_definition": {k: (x.tolist() if isinstance(x, np.ndarray) else x) for k, x in contrast.items()},
805
+ "deg_definition": deg_def, "headline": headline, "per_arm": summs, "code_sha256": code, "seconds": round(time.monotonic() - t0, 1)}
806
+ note = ""
807
+ if gene_excl is not None:
808
+ summary["gene_exclusion"] = gene_excl
809
+ note += (f"\n## Gene exclusion (--exclude-genes)\n`{gene_excl['file']}` (sha {gene_excl['sha256'][:12]}): "
810
+ f"{gene_excl['n_listed']} genes listed, {gene_excl['n_dropped_from_scoring_genes']} of them scoring genes "
811
+ f"({', '.join(d['symbol'] or d['gene_id'] for d in gene_excl['dropped'])}). Applies to: "
812
+ f"{gene_excl['applies_to']}. Definitions 5 and 6 above therefore run on "
813
+ f"{gene_excl['n_scoring_genes_kept']} of the {gene_excl['n_scoring_genes']} scoring genes.\n")
814
+ if a.reuse_labels is not None:
815
+ summary["labels_reused_from"] = str(a.reuse_labels)
816
+ note += (f"\n## Labels\nFrozen scANVI labels reused from `{a.reuse_labels}` (same reference, NPZ sha256 and scored "
817
+ f"donors; checked per arm); predict_scanvi.py was not run.\n")
818
+ (a.out / "summary.json").write_text(json.dumps(summary, indent=1, default=float) + "\n")
819
+ (a.out / "README.md").write_text(readme(spec, man, v, contrast, summary) + note)
820
+ with pd.option_context("display.width", 250, "display.max_columns", 40):
821
+ print(pd.DataFrame(headline).T.round(4).to_string())
822
+ F.log(f"done in {summary['seconds']} s -> {a.out}")
823
+ return 0
824
+
825
+
826
+ if __name__ == "__main__":
827
+ raise SystemExit(main())