junidude14 commited on
Commit
df753c4
·
verified ·
1 Parent(s): ffb9da7

Archive 4 checkpoints (1-4)

Browse files
paper-releases/20260928/diffusion/data/protocol/paired_finetune/tools/build_full_cells.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Full-axis (20,097-gene) counts of the retained cells, in cells_panel6k.npz row order (CPU only).
3
+
4
+ Recipe conditions (a pseudobulk of K sampled cells, as in pretraining) need every canonical gene: the conditioner
5
+ normalises by the full-axis total and its scalars (detected fraction, log mean/SD, top-1 % share) span all genes.
6
+ This reads each retained cell from its library's canonical.h5ad by obs index (barcode), in the order of
7
+ data/<dataset>/cells_obs.parquet, and writes data/<dataset>/cells_full.npz (CSR int32).
8
+
9
+ Checks (fail-closed): the panel columns equal cells_panel6k.npz exactly, and each row's cells sum to
10
+ features.npz pseudo_raw_sum on the full axis.
11
+ usage: build_full_cells.py DATASET
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ import h5py
22
+ import numpy as np
23
+ import pandas as pd
24
+ import scipy.sparse as sp
25
+
26
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
27
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
28
+ TASK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
29
+ POSITIONS = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/gene_positions.npy")
30
+ LIBRARY_ROOT = {
31
+ "immicro": Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/singlecell/GSE314416"),
32
+ "ye2026_sepsis": Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/ye2026_sepsis_v1_20260927/singlecell"),
33
+ "giroux2022": Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/giroux2022_v1_20260928/singlecell"),
34
+ }
35
+
36
+
37
+ def sha(p: Path) -> str:
38
+ h = hashlib.sha256()
39
+ with open(p, "rb") as f:
40
+ for b in iter(lambda: f.read(1 << 24), b""):
41
+ h.update(b)
42
+ return h.hexdigest()
43
+
44
+
45
+ def read_library(h5: Path, barcodes: np.ndarray) -> sp.csr_matrix:
46
+ with h5py.File(h5, "r") as f:
47
+ g = f["X"]
48
+ indptr, indices, data = g["indptr"][:], g["indices"][:], g["data"][:]
49
+ n_genes = int(f["var/_index"].shape[0])
50
+ obs_index = np.asarray([x.decode() if isinstance(x, bytes) else str(x) for x in f["obs/_index"][:]])
51
+ pos = pd.Series(np.arange(obs_index.size), index=obs_index)
52
+ if pos.index.duplicated().any():
53
+ raise SystemExit(f"{h5}: duplicate obs index")
54
+ rows = pos.reindex(barcodes)
55
+ if rows.isna().any():
56
+ raise SystemExit(f"{h5}: {int(rows.isna().sum())} barcodes not found")
57
+ full = sp.csr_matrix((data, indices, indptr), shape=(indptr.size - 1, n_genes))
58
+ sub = full[rows.to_numpy(np.int64)]
59
+ if sub.nnz and not np.array_equal(sub.data, np.round(sub.data)):
60
+ raise SystemExit(f"{h5}: non-integer counts")
61
+ return sub.astype(np.int32).tocsr()
62
+
63
+
64
+ def main(ds: str) -> int:
65
+ d = TASK / "data" / ds
66
+ obs = pd.read_parquet(d / "cells_obs.parquet")
67
+ panel = np.load(d / "cells_panel6k.npz", allow_pickle=False)
68
+ feat = np.load(d / "features.npz", allow_pickle=False)
69
+ positions = np.load(POSITIONS).astype(np.int64)
70
+ if len(obs) != int(panel["shape"][0]):
71
+ raise SystemExit("cells_obs rows differ from cells_panel6k rows")
72
+ root = LIBRARY_ROOT[ds]
73
+ parts, order = [], []
74
+ for lib, sub in obs.groupby("library_id", sort=True):
75
+ m = read_library(root / str(lib) / "canonical.h5ad", sub["barcode"].astype(str).to_numpy())
76
+ parts.append(m)
77
+ order.append(sub.index.to_numpy())
78
+ print(f"{lib}: {m.shape[0]} cells", flush=True)
79
+ X = sp.vstack(parts, format="csr")
80
+ inv = np.empty(len(obs), dtype=np.int64)
81
+ inv[np.concatenate(order)] = np.arange(len(obs))
82
+ X = X[inv].tocsr() # back to cells_panel6k order
83
+ P = sp.csr_matrix((panel["data"], panel["indices"], panel["indptr"]), shape=tuple(panel["shape"]))
84
+ rs = panel["row_sample"].astype(np.int64)
85
+ if bool((np.diff(rs) < 0).any()):
86
+ raise SystemExit("cells are not sorted by dataset row")
87
+ want = np.nan_to_num(feat["pseudo_raw_sum"].astype(np.float64), nan=0.0)
88
+ bounds = np.searchsorted(rs, np.arange(int(rs.max()) + 2))
89
+ bad_panel = bad_sum = 0
90
+ for r in range(int(rs.max()) + 1): # row by row keeps peak memory at one donor's cells
91
+ a, b = int(bounds[r]), int(bounds[r + 1])
92
+ Xr = X[a:b]
93
+ bad_panel += int((Xr[:, positions] != P[a:b]).nnz)
94
+ bad_sum += int(not np.array_equal(np.asarray(Xr.sum(axis=0, dtype=np.float64)).ravel(), want[r]))
95
+ if bad_panel:
96
+ raise SystemExit(f"full-axis cells differ from cells_panel6k on the panel columns ({bad_panel} entries)")
97
+ if bad_sum:
98
+ raise SystemExit(f"per-row full-axis sums differ from pseudo_raw_sum for {bad_sum} rows")
99
+ out = d / "cells_full.npz"
100
+ np.savez(out, data=X.data.astype(np.int32), indices=X.indices.astype(np.int32), indptr=X.indptr.astype(np.int64),
101
+ shape=np.array(X.shape, dtype=np.int64), row_sample=rs.astype(np.int32))
102
+ info = {"dataset": ds, "n_cells": int(X.shape[0]), "nnz": int(X.nnz), "sha256": sha(out),
103
+ "checks": {"panel_columns_equal_cells_panel6k": True, "row_sums_equal_pseudo_raw_sum": True}}
104
+ (d / "cells_full.BUILD.json").write_text(json.dumps(info, indent=1))
105
+ print(json.dumps(info))
106
+ return 0
107
+
108
+
109
+ if __name__ == "__main__":
110
+ sys.exit(main(sys.argv[1]))
paper-releases/20260928/diffusion/data/protocol/paired_finetune/tools/build_immicro_cells.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ImMicro fine-tuning cells: the 107 baseline donors' retained cells on the model's 6,000-gene panel.
3
+
4
+ Cells are exactly the ones the ImMicro utility study kept (observed_cells.parquet, kind == 'baseline',
5
+ flag_conservative_review_pass), read from the 54 canonical per-library h5ad files by their row index.
6
+ Columns follow the checkpoint's gene_positions (indices into the canonical 20,097 axis).
7
+
8
+ Outputs (data/immicro/):
9
+ cells_panel6k.npz CSR int32 counts [n_cells, 6000], row_sample (index into features.npz rows),
10
+ panel_gene_ids, panel_measured (sc_valid[:, positions])
11
+ cells_obs.parquet the observed_cells rows in the same order
12
+ samples.csv row, sample_id, donor_id, group (pool), n_cells
13
+ features.npz symlink to the ImMicro features file (bulk_raw, pseudo_raw_sum, masks)
14
+ BUILD.json sources, sha256, checks
15
+
16
+ Check (fail-closed): per donor, the summed panel counts equal features.npz pseudo_raw_sum[:, positions]
17
+ exactly, and cell counts equal qc_cell_counts. CPU only.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import hashlib
22
+ import json
23
+ import os
24
+ import sys
25
+ from datetime import datetime, timezone
26
+ from pathlib import Path
27
+
28
+ import h5py
29
+ import numpy as np
30
+ import pandas as pd
31
+ import scipy.sparse as sp
32
+
33
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
34
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
35
+
36
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
37
+ TASK = M8 / "plans/paired_finetune_intradataset_20260927"
38
+ OUT = TASK / "data/immicro"
39
+ FEATURES = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/analyses/offset_sample_size_20260914/features.npz")
40
+ SC_DIR = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/singlecell/GSE314416")
41
+ OBSERVED = M8 / "plans/utility_studies_final6k_20260925/immicro/out/observed_cells.parquet"
42
+ POSITIONS = M8 / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/gene_positions.npy"
43
+ POSITIONS_SHA = "653ffa45ac519000baa41086c52408009391d6e68cfb218bc6a50d34163fcb24"
44
+
45
+
46
+ def sha256_file(path: Path) -> str:
47
+ h = hashlib.sha256()
48
+ with open(path, "rb") as f:
49
+ for block in iter(lambda: f.read(1 << 24), b""):
50
+ h.update(block)
51
+ return h.hexdigest()
52
+
53
+
54
+ def read_rows(h5: Path, barcodes: np.ndarray, positions: np.ndarray) -> sp.csr_matrix:
55
+ """Cells (by obs index = barcode, as build_observed.py keys them) of the canonical CSR X, panel columns only."""
56
+ with h5py.File(h5, "r") as f:
57
+ g = f["X"]
58
+ indptr = g["indptr"][:]
59
+ n_genes = int(f["var/_index"].shape[0])
60
+ data = g["data"][:]
61
+ indices = g["indices"][:]
62
+ obs_index = np.asarray([x.decode() if isinstance(x, bytes) else str(x) for x in f["obs/_index"][:]])
63
+ pos = pd.Series(np.arange(len(obs_index)), index=obs_index)
64
+ if pos.index.duplicated().any():
65
+ raise SystemExit(f"{h5}: duplicate obs index")
66
+ rows = pos.reindex(barcodes)
67
+ if rows.isna().any():
68
+ raise SystemExit(f"{h5}: {int(rows.isna().sum())} barcodes not found")
69
+ rows = rows.to_numpy(np.int64)
70
+ full = sp.csr_matrix((data, indices, indptr), shape=(len(indptr) - 1, n_genes))
71
+ sub = full[rows][:, positions]
72
+ if sub.nnz and not np.array_equal(sub.data, np.round(sub.data)):
73
+ raise SystemExit(f"{h5}: non-integer counts")
74
+ return sub.astype(np.int32)
75
+
76
+
77
+ def main() -> int:
78
+ if sha256_file(POSITIONS) != POSITIONS_SHA:
79
+ raise SystemExit("gene_positions.npy sha differs from the final run's")
80
+ positions = np.load(POSITIONS).astype(np.int64)
81
+ feat = np.load(FEATURES, allow_pickle=False)
82
+ donors = feat["donor_ids"].astype(str)
83
+ gene_ids = feat["gene_ids"].astype(str)
84
+ row_of = {d: i for i, d in enumerate(donors)}
85
+
86
+ obs = pd.read_parquet(OBSERVED)
87
+ obs = obs[obs["kind"] == "baseline"].copy()
88
+ missing = sorted(set(obs["donor_id"]) - set(donors))
89
+ if missing:
90
+ raise SystemExit(f"baseline donors absent from features.npz: {missing[:5]}")
91
+ obs["row_sample"] = obs["donor_id"].map(row_of).astype(np.int32)
92
+ # deterministic order: donor row, then library, then row index inside the library
93
+ obs = obs.sort_values(["row_sample", "library_id", "cell_index"], kind="mergesort").reset_index(drop=True)
94
+
95
+ blocks, block_obs = [], []
96
+ for lib, sub in obs.groupby("library_id", sort=True):
97
+ h5 = SC_DIR / lib / "canonical.h5ad"
98
+ m = read_rows(h5, sub["barcode"].astype(str).to_numpy(), positions)
99
+ blocks.append(m)
100
+ block_obs.append(sub)
101
+ print(f"{lib}: {m.shape[0]} cells", flush=True)
102
+ X = sp.vstack(blocks, format="csr")
103
+ cobs = pd.concat(block_obs, ignore_index=True)
104
+ order = np.lexsort((cobs["cell_index"].to_numpy(), cobs["library_id"].to_numpy(), cobs["row_sample"].to_numpy()))
105
+ X = X[order]
106
+ cobs = cobs.iloc[order].reset_index(drop=True)
107
+ row_sample = cobs["row_sample"].to_numpy(np.int32)
108
+
109
+ # fail-closed checks against the features file
110
+ ind = sp.csr_matrix((np.ones(len(row_sample)), (row_sample, np.arange(len(row_sample)))),
111
+ shape=(len(donors), len(row_sample)))
112
+ sums = np.asarray((ind @ X.astype(np.float64)).todense())
113
+ want = np.nan_to_num(feat["pseudo_raw_sum"][:, positions].astype(np.float64), nan=0.0)
114
+ if not np.array_equal(sums, want):
115
+ bad = int((sums != want).any(axis=1).sum())
116
+ raise SystemExit(f"per-donor panel sums differ from pseudo_raw_sum for {bad} donors")
117
+ counts = np.bincount(row_sample, minlength=len(donors))
118
+ if not np.array_equal(counts, feat["qc_cell_counts"].astype(np.int64)):
119
+ raise SystemExit("per-donor cell counts differ from qc_cell_counts")
120
+
121
+ OUT.mkdir(parents=True, exist_ok=True)
122
+ panel_measured = feat["sc_valid"][:, positions].astype(bool)
123
+ np.savez(OUT / "cells_panel6k.npz", data=X.data.astype(np.int32), indices=X.indices.astype(np.int32),
124
+ indptr=X.indptr.astype(np.int64), shape=np.array(X.shape, dtype=np.int64), row_sample=row_sample,
125
+ panel_gene_ids=gene_ids[positions], panel_measured=panel_measured)
126
+ cobs.drop(columns=["row_sample"]).assign(row_sample=row_sample).to_parquet(OUT / "cells_obs.parquet", index=False)
127
+ pd.DataFrame({"row": np.arange(len(donors)), "sample_id": donors, "donor_id": donors,
128
+ "group": feat["pools"].astype(str), "n_cells": counts}).to_csv(OUT / "samples.csv", index=False)
129
+ link = OUT / "features.npz"
130
+ if link.is_symlink() or link.exists():
131
+ link.unlink()
132
+ link.symlink_to(FEATURES)
133
+ build = {
134
+ "written_utc": datetime.now(timezone.utc).isoformat(),
135
+ "features": str(FEATURES), "features_sha256": sha256_file(FEATURES),
136
+ "observed_cells": str(OBSERVED), "observed_cells_sha256": sha256_file(OBSERVED),
137
+ "gene_positions": str(POSITIONS), "gene_positions_sha256": POSITIONS_SHA,
138
+ "n_cells": int(X.shape[0]), "nnz": int(X.nnz), "n_samples": int(len(donors)),
139
+ "cells_per_sample": {"min": int(counts.min()), "median": float(np.median(counts)), "max": int(counts.max())},
140
+ "checks": {"panel_sums_equal_pseudo_raw_sum": True, "cell_counts_equal_qc_cell_counts": True},
141
+ "cells_panel6k_sha256": sha256_file(OUT / "cells_panel6k.npz"),
142
+ }
143
+ (OUT / "BUILD.json").write_text(json.dumps(build, indent=1))
144
+ print(json.dumps(build, indent=1))
145
+ return 0
146
+
147
+
148
+ if __name__ == "__main__":
149
+ sys.exit(main())
paper-releases/20260928/diffusion/data/protocol/paired_finetune/tools/build_realbulk_conditions.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Condition NPZs that let one frozen model be driven by separately measured bulk.
3
+
4
+ Every earlier paired-cohort experiment stopped at the condition vector: it showed that raw clinical bulk
5
+ lands far from the pseudobulk the model was trained on, and that a ten-pair gene-wise multiplier removes
6
+ most of that distance. No cells were ever generated from a corrected bulk. This script writes the inputs
7
+ that close that gap, as three arms per cohort that differ **only** in the expression vector handed to the
8
+ conditioner:
9
+
10
+ raw the separately measured bulk, exactly as the assay reports it
11
+ cal the same bulk after the published ten-pair gene-wise multiplier, fitted with the donor's whole
12
+ group held out, so no evaluated donor contributes to its own correction
13
+ pseudo the pseudobulk of that donor's own single cells -- the input distribution the model was trained
14
+ on, and therefore the ceiling this cohort can reach
15
+
16
+ Sources (read, never rewritten):
17
+ ImMicro analyses/offset_sample_size_20260914/features.npz 107 healthy donors, 7 pools
18
+ Randolph analyses/offset_two_cohort_20260915/paired_features/Randolph.npz 89 donors x NI/IAV, 15 day groups
19
+
20
+ Depth policy follows the published calibration experiments: both modalities enter the model at K=1000 cells
21
+ and one fixed depth anchor, so the two depth scalars of the conditioner agree and the arms differ only in
22
+ expression shape. This is a fixed-depth condition experiment; it does not reconstruct a donor's true
23
+ sequencing depth.
24
+
25
+ Usage:
26
+ build_realbulk_conditions.py --cohort ImMicro --out-dir <dir> [--cells-per-bulk 1500] [--n-calibration 10]
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import argparse
31
+ import hashlib
32
+ import json
33
+ import sys
34
+ from datetime import datetime, timezone
35
+ from pathlib import Path
36
+
37
+ import numpy as np
38
+
39
+ DATALAKE = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/analyses")
40
+ SOURCES = {
41
+ "ImMicro": DATALAKE / "offset_sample_size_20260914/features.npz",
42
+ "Randolph": DATALAKE / "offset_two_cohort_20260915/paired_features/Randolph.npz",
43
+ }
44
+ # the anchor the published two-cohort and affine-calibration experiments used for both assays
45
+ DEPTH_ANCHOR = 3869.603120208939
46
+ RECIPE_K = 1000
47
+ SCHEMA = "pbisc_sdd.realbulk_conditions.v1"
48
+ NATIVE_SCHEMA = "pbisc_sdd.realbulk_conditions.native_depth.v1"
49
+ ARMS = ("raw", "cal", "pseudo")
50
+
51
+
52
+ class InputError(RuntimeError):
53
+ """A cohort cannot be assembled without inventing data."""
54
+
55
+
56
+ def sha256_file(path: Path) -> str:
57
+ h = hashlib.sha256()
58
+ with open(path, "rb") as f:
59
+ for block in iter(lambda: f.read(1 << 24), b""):
60
+ h.update(block)
61
+ return h.hexdigest()
62
+
63
+
64
+ def cpm(x: np.ndarray) -> np.ndarray:
65
+ """Rows to a fixed relative-expression scale of 1e6."""
66
+ x = np.asarray(x, dtype=np.float64)
67
+ total = x.sum(axis=1, keepdims=True)
68
+ if not np.isfinite(x).all() or (x < 0).any():
69
+ raise InputError("expression contains negative or non-finite values")
70
+ if (total <= 0).any():
71
+ raise InputError("an expression row sums to zero")
72
+ return x / total * 1e6
73
+
74
+
75
+ def drop_unmeasured_nan(x: np.ndarray, valid: np.ndarray, label: str) -> np.ndarray:
76
+ """Both sources mark an unmeasured coordinate with NaN. Turn those into zeros, and only those.
77
+
78
+ A NaN inside the measured support would be a real defect in the source, so it is refused rather than
79
+ silently filled.
80
+ """
81
+ x = np.asarray(x, dtype=np.float64)
82
+ nan = np.isnan(x)
83
+ inside = int((nan & valid).sum())
84
+ if inside:
85
+ raise InputError(f"{label}: {inside} NaN values inside the measured support")
86
+ out = np.where(nan, 0.0, x)
87
+ if not np.isfinite(out).all():
88
+ raise InputError(f"{label}: non-finite values remain after clearing unmeasured coordinates")
89
+ return out
90
+
91
+
92
+ def load_cohort(name: str) -> dict:
93
+ """Canonical 20,097-gene bulk, pseudobulk, assay supports and grouping for one cohort."""
94
+ path = SOURCES[name]
95
+ if not path.is_file():
96
+ raise InputError(f"source missing: {path}")
97
+ d = np.load(path, allow_pickle=False)
98
+ if name == "ImMicro":
99
+ out = {
100
+ "gene_ids": d["gene_ids"].astype(str),
101
+ "sample_ids": d["donor_ids"].astype(str),
102
+ "donor_ids": d["donor_ids"].astype(str),
103
+ "groups": d["pools"].astype(str),
104
+ "conditions": np.array(["baseline"] * len(d["donor_ids"]), dtype=np.str_),
105
+ "bulk": np.asarray(d["bulk_raw"], dtype=np.float64),
106
+ "pseudo": np.asarray(d["pseudo_raw_sum"], dtype=np.float64),
107
+ "bulk_valid": np.asarray(d["bulk_valid"], dtype=bool),
108
+ "sc_valid": np.asarray(d["sc_valid"], dtype=bool),
109
+ "n_cells": np.asarray(d["qc_cell_counts"], dtype=np.int64),
110
+ }
111
+ elif name == "Randolph":
112
+ n = int(d["bulk_original_units_canonical"].shape[0])
113
+ out = {
114
+ "gene_ids": d["gene_ids"].astype(str),
115
+ "sample_ids": d["sample_ids"].astype(str),
116
+ "donor_ids": d["donor_ids"].astype(str),
117
+ "groups": d["cv_groups"].astype(str),
118
+ "conditions": d["conditions"].astype(str),
119
+ "bulk": np.asarray(d["bulk_original_units_canonical"], dtype=np.float64),
120
+ "pseudo": np.asarray(d["pseudo_raw_UMI_canonical"], dtype=np.float64),
121
+ "bulk_valid": np.asarray(d["bulk_valid"], dtype=bool),
122
+ # the Randolph pseudobulk support is one fixed vector for the whole study
123
+ "sc_valid": np.repeat(np.asarray(d["pseudo_valid"], dtype=bool)[None, :], n, axis=0),
124
+ "n_cells": np.full(n, -1, dtype=np.int64),
125
+ }
126
+ else:
127
+ raise InputError(f"unknown cohort {name}")
128
+ out["source_path"] = path
129
+ out["source_sha256"] = sha256_file(path)
130
+ n, g = out["bulk"].shape
131
+ for key in ("pseudo", "bulk_valid", "sc_valid"):
132
+ if out[key].shape != (n, g):
133
+ raise InputError(f"{name}: {key} has shape {out[key].shape}, expected {(n, g)}")
134
+ for key in ("sample_ids", "donor_ids", "groups", "conditions"):
135
+ if out[key].shape != (n,):
136
+ raise InputError(f"{name}: {key} has shape {out[key].shape}, expected {(n,)}")
137
+ if g != 20097:
138
+ raise InputError(f"{name}: expected the canonical 20,097-gene axis, got {g}")
139
+ out["bulk"] = drop_unmeasured_nan(out["bulk"], out["bulk_valid"], f"{name} bulk")
140
+ out["pseudo"] = drop_unmeasured_nan(out["pseudo"], out["sc_valid"], f"{name} pseudobulk")
141
+ return out
142
+
143
+
144
+ def gene_multiplier(bulk: np.ndarray, pseudo: np.ndarray, valid: np.ndarray) -> np.ndarray:
145
+ """The published estimator: alpha_g = mean(P_g) / mean(B_g) over the calibration donors.
146
+
147
+ Both sides are on the 1e6 relative scale. The ratio is only estimated where both training means reach
148
+ 1 unit; elsewhere alpha stays 1, because a ratio of two values near zero carries no information. The
149
+ genes left at 1 are a real limitation of this estimator, not a neutral choice.
150
+ """
151
+ if bulk.shape != pseudo.shape or bulk.ndim != 2:
152
+ raise InputError("calibration bulk and pseudobulk must share a 2-D shape")
153
+ if bulk.shape[0] == 0:
154
+ raise InputError("no calibration donors")
155
+ b = cpm(bulk).mean(axis=0)
156
+ p = cpm(pseudo).mean(axis=0)
157
+ alpha = np.ones_like(b)
158
+ usable = valid & (b >= 1.0) & (p >= 1.0)
159
+ alpha[usable] = p[usable] / b[usable]
160
+ return alpha
161
+
162
+
163
+ def calibration_donors(groups: np.ndarray, held_out: str, n_calibration: int, seed: int) -> np.ndarray:
164
+ """Row indices of the calibration donors, all from groups other than the held-out one."""
165
+ pool = np.flatnonzero(groups != held_out)
166
+ if pool.size < n_calibration:
167
+ raise InputError(f"group {held_out}: only {pool.size} donors outside it, need {n_calibration}")
168
+ rng = np.random.default_rng(seed)
169
+ return np.sort(rng.choice(pool, size=n_calibration, replace=False))
170
+
171
+
172
+ def calibrated_bulk(data: dict, n_calibration: int, seed: int) -> tuple[np.ndarray, dict]:
173
+ """Apply a group-held-out ten-pair multiplier to every sample."""
174
+ bulk, pseudo = data["bulk"], data["pseudo"]
175
+ groups = data["groups"]
176
+ out = np.zeros_like(bulk)
177
+ record: dict[str, dict] = {}
178
+ for gi, group in enumerate(sorted(set(groups.tolist()))):
179
+ rows = np.flatnonzero(groups == group)
180
+ cal = calibration_donors(groups, group, n_calibration, seed + gi)
181
+ # a gene is usable for calibration only where both assays measured it in every calibration donor
182
+ valid = data["bulk_valid"][cal].all(axis=0) & data["sc_valid"][cal].all(axis=0)
183
+ alpha = gene_multiplier(bulk[cal], pseudo[cal], valid)
184
+ out[rows] = cpm(bulk[rows]) * alpha[None, :]
185
+ record[group] = {
186
+ "n_evaluated": int(rows.size),
187
+ "calibration_rows": cal.tolist(),
188
+ "calibration_samples": data["sample_ids"][cal].tolist(),
189
+ "n_genes_with_estimated_alpha": int((alpha != 1.0).sum()),
190
+ "alpha_median": float(np.median(alpha[alpha != 1.0])) if (alpha != 1.0).any() else 1.0,
191
+ }
192
+ return out, record
193
+
194
+
195
+ def to_condition_counts(expression: np.ndarray, measured: np.ndarray,
196
+ totals: np.ndarray | None = None) -> np.ndarray:
197
+ """A count vector per sample, zero wherever the assay did not measure.
198
+
199
+ With ``totals`` omitted every sample enters at one fixed depth, which is the policy the published
200
+ calibration experiments used so that the conditioner's two depth scalars agree between assays. With
201
+ ``totals`` given, each sample keeps that depth instead: this is how the SLE benchmark conditions are
202
+ built, and it is the only way to ask whether standardizing depth is what removes donor identity.
203
+ """
204
+ x = np.where(measured, np.asarray(expression, dtype=np.float64), 0.0)
205
+ if totals is None:
206
+ return cpm(x) / 1e6 * (RECIPE_K * DEPTH_ANCHOR)
207
+ totals = np.asarray(totals, dtype=np.float64).reshape(-1, 1)
208
+ if totals.shape[0] != x.shape[0] or not np.isfinite(totals).all() or (totals <= 0).any():
209
+ raise InputError("native totals must be one positive finite value per sample")
210
+ return cpm(x) / 1e6 * totals
211
+
212
+
213
+ def build(cohort: str, out_dir: Path, cells_per_bulk: int, n_calibration: int, seed: int,
214
+ depth_policy: str = "fixed") -> int:
215
+ data = load_cohort(cohort)
216
+ out_dir.mkdir(parents=True, exist_ok=True)
217
+ cal_bulk, cal_record = calibrated_bulk(data, n_calibration, seed)
218
+ n = data["bulk"].shape[0]
219
+ # the generated cells must live in the space the observed cells live in, for every arm
220
+ output_mask = data["sc_valid"]
221
+ expression = {"raw": data["bulk"], "cal": cal_bulk, "pseudo": data["pseudo"]}
222
+ measured = {"raw": data["bulk_valid"], "cal": data["bulk_valid"], "pseudo": data["sc_valid"]}
223
+ if depth_policy == "native":
224
+ # the donor's own sequencing depth and cell count, as the SLE benchmark conditions carry them.
225
+ # For the bulk arms this borrows the depth of that donor's single cells, which a bulk-only cohort
226
+ # would not know; it is a diagnostic of what depth standardization costs, not a deployable recipe.
227
+ totals = data["pseudo"].sum(axis=1)
228
+ k_vector = data["n_cells"].astype(np.int64)
229
+ if bool((k_vector <= 0).any()):
230
+ raise InputError(f"{cohort}: native depth needs a positive cell count for every sample")
231
+ else:
232
+ totals = None
233
+ k_vector = np.full(n, RECIPE_K, dtype=np.int64)
234
+
235
+ manifest = {
236
+ "schema_version": SCHEMA if depth_policy == "fixed" else NATIVE_SCHEMA,
237
+ "cohort": cohort,
238
+ "depth_policy": depth_policy,
239
+ "source": str(data["source_path"]),
240
+ "source_sha256": data["source_sha256"],
241
+ "n_samples": int(n),
242
+ "n_donors": int(len(set(data["donor_ids"].tolist()))),
243
+ "groups": sorted(set(data["groups"].tolist())),
244
+ "recipe_k": RECIPE_K if depth_policy == "fixed" else "per-sample observed cell count",
245
+ "depth_anchor": DEPTH_ANCHOR if depth_policy == "fixed" else "per-sample observed pseudobulk total",
246
+ "cells_per_bulk": int(cells_per_bulk),
247
+ "n_calibration_pairs": int(n_calibration),
248
+ "calibration_seed": int(seed),
249
+ "calibration_per_group": cal_record,
250
+ "arms": {},
251
+ "written_utc": datetime.now(timezone.utc).isoformat(),
252
+ }
253
+ for arm in ARMS:
254
+ counts = to_condition_counts(expression[arm], measured[arm], totals)
255
+ frac = measured[arm].astype(np.float32)
256
+ if bool((counts[frac == 0] != 0).any()):
257
+ raise InputError(f"{cohort}/{arm}: an unmeasured coordinate carries a non-zero count")
258
+ suffix = "" if depth_policy == "fixed" else f"_{depth_policy}"
259
+ path = out_dir / f"conditions_{cohort}_{arm}{suffix}.npz"
260
+ np.savez(
261
+ path,
262
+ schema_version=np.array(SCHEMA),
263
+ bulk_counts=counts,
264
+ bulk_measurement_fraction=frac,
265
+ output_availability_mask=output_mask,
266
+ recipe_k=k_vector,
267
+ cells_per_bulk=np.full(n, int(cells_per_bulk), dtype=np.int64),
268
+ sample_ids=data["sample_ids"],
269
+ donor_ids=data["donor_ids"],
270
+ conditions=data["conditions"],
271
+ groups=data["groups"],
272
+ gene_ids=data["gene_ids"],
273
+ donor_n_cells=data["n_cells"],
274
+ arm=np.array(arm),
275
+ )
276
+ manifest["arms"][arm] = {
277
+ "path": str(path),
278
+ "sha256": sha256_file(path),
279
+ "n_measured_genes_median": int(np.median(measured[arm].sum(axis=1))),
280
+ "detected_fraction_median": float(np.median((counts > 0).mean(axis=1))),
281
+ }
282
+ print(f"[{cohort}] {arm:6s} -> {path.name} "
283
+ f"measured {manifest['arms'][arm]['n_measured_genes_median']:5d} genes "
284
+ f"detected {manifest['arms'][arm]['detected_fraction_median']:.3f}")
285
+ suffix = "" if depth_policy == "fixed" else f"_{depth_policy}"
286
+ (out_dir / f"MANIFEST_{cohort}{suffix}.json").write_text(json.dumps(manifest, indent=2))
287
+ print(f"[{cohort}] manifest written: {out_dir / f'MANIFEST_{cohort}{suffix}.json'}")
288
+ return 0
289
+
290
+
291
+ def main(argv=None) -> int:
292
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
293
+ p.add_argument("--cohort", choices=sorted(SOURCES), required=True)
294
+ p.add_argument("--out-dir", type=Path, required=True)
295
+ p.add_argument("--cells-per-bulk", type=int, default=1500)
296
+ p.add_argument("--n-calibration", type=int, default=10)
297
+ p.add_argument("--seed", type=int, default=20260922)
298
+ p.add_argument(
299
+ "--depth-policy",
300
+ choices=("fixed", "native"),
301
+ default="fixed",
302
+ help="fixed: one depth and K=1000 for every sample (the published calibration policy). "
303
+ "native: the donor's own pseudobulk total and cell count, as the SLE conditions use.",
304
+ )
305
+ a = p.parse_args(argv)
306
+ if a.cells_per_bulk <= 0 or a.n_calibration <= 0:
307
+ raise SystemExit("cells-per-bulk and n-calibration must be positive")
308
+ return build(a.cohort, a.out_dir, a.cells_per_bulk, a.n_calibration, a.seed, a.depth_policy)
309
+
310
+
311
+ if __name__ == "__main__":
312
+ sys.exit(main())
paper-releases/20260928/diffusion/data/protocol/paired_finetune/tools/ft_common.py ADDED
@@ -0,0 +1,720 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared code of the fine-tuning benchmark scorer (tools/score_ft.py). CPU only; never imports torch.
2
+
3
+ Every statistic is imported from the published tools and not retyped:
4
+ IC utility_studies_final6k_20260925/immicro/tools/immicro_common.py
5
+ composition, composition L1, leave-one-out cohort mean, closest-donor retrieval,
6
+ IC.ER = realbulk_generation_20260922/evaluate_realbulk.py (cpm_log1p, paired_r)
7
+ SB utility_studies_final6k_20260925/umap/cell_immicro_5arm/tools/stage_b_embed.py
8
+ cp10k_log1p, project, knn_radius, precision_coverage, depth_match (thin_to_detected)
9
+ PR aifi_scanvi_rebuild_20260916/poisson_readout.py poisson_integerise
10
+ EV bulk2sc-paper/scripts/evaluate_generated_vs_truth.py log1p_cpm, group_log_fold_change, pearson,
11
+ welch_bh_deg + top_deg_genes + jaccard (the benchmark's top-50 DEG overlap, Welch backend)
12
+
13
+ New here (and only here): the dataset adapters, the observed reference cache, the donor-keyed subsample rule,
14
+ the per-cell-type contrast (mean CP10K) and its bulk-broadcast baseline, the donor x type DEG aggregates
15
+ (deg_reference.npz, adds DC to the four contrast types) and the row selection that feeds EV's DEG test.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import importlib.util
21
+ import json
22
+ import os
23
+ import re
24
+ import subprocess
25
+ import sys
26
+ import time
27
+ from dataclasses import dataclass
28
+ from datetime import datetime, timezone
29
+ from pathlib import Path
30
+
31
+ import numpy as np
32
+ import pandas as pd
33
+ import scipy.sparse as sp
34
+
35
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
36
+ TASK = M8 / "plans/paired_finetune_intradataset_20260927"
37
+ UTIL = M8 / "plans/utility_studies_final6k_20260925"
38
+ CACHE_ROOT = TASK / "scoring_cache"
39
+
40
+ sys.path.insert(0, str(UTIL / "immicro/tools"))
41
+ import immicro_common as IC # noqa: E402
42
+
43
+
44
+ def _load_module(name: str, path: Path):
45
+ if name in sys.modules:
46
+ return sys.modules[name]
47
+ spec = importlib.util.spec_from_file_location(name, path)
48
+ mod = importlib.util.module_from_spec(spec)
49
+ sys.modules[name] = mod
50
+ spec.loader.exec_module(mod) # module level of both files: constants + imports only
51
+ return mod
52
+
53
+
54
+ SB_PATH = UTIL / "umap/cell_immicro_5arm/tools/stage_b_embed.py"
55
+ EV_PATH = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/bulk2sc-paper/scripts/evaluate_generated_vs_truth.py")
56
+ SB = _load_module("stage_b_embed_5arm", SB_PATH)
57
+ EV = _load_module("evaluate_generated_vs_truth", EV_PATH)
58
+ PR = SB.PR
59
+
60
+ GATE = tuple(IC.GATE)
61
+ CONTRAST_TYPES = ("T cell", "B cell", "Monocyte", "NK cell")
62
+ POISSON_SEED = int(SB.POISSON_SEED) # 20260916, one read-out per generated cell
63
+ SUB_SEED = int(SB.SUB_SEED) # 20260925
64
+ GEN_SUB_SEED = SUB_SEED + 1 # stage_b_embed: generated subsample stream
65
+ DEPTH_SEED = SUB_SEED + 4 # stage_b_embed: depth-matching stream
66
+ N_SUB = int(SB.N_SUB) # 150 cells per donor
67
+ K_NN = int(SB.K_NN) # 10
68
+ CP10K = float(SB.CP10K)
69
+ PCA_DIM = 50
70
+ MIN_DETECT_FRAC = 0.01
71
+ CONTROL_RE = re.compile(r"(?i)(control|healthy|^hc$|^hv$|^ctrl|normal)")
72
+ ANNOT_MODEL_SHA = "bf3655899e5abee435340fc008656c4a17342da0f30b70cfd43de8e9223e1930" # f01common scANVI model.pt
73
+ ANNOT_RUNS = (IC.ANNOT_RUN, UTIL / "immicro/annotator_mirror/aifi_scanvi_f01common_v1") # server_1, server_2 mirror
74
+ assert POISSON_SEED == IC.SEED
75
+
76
+
77
+ def log(msg: str) -> None:
78
+ print(f"{datetime.now().strftime('%H:%M:%S')} {msg}", flush=True)
79
+
80
+
81
+ def sha(path: Path) -> str:
82
+ return IC.sha256_file(path)
83
+
84
+
85
+ def now() -> str:
86
+ return datetime.now(timezone.utc).isoformat()
87
+
88
+
89
+ # --------------------------------------------------------------------------- datasets
90
+ @dataclass(frozen=True)
91
+ class DatasetSpec:
92
+ name: str
93
+ data_dir: Path
94
+ features: Path
95
+ dataset_id: str
96
+ batch_prefix: str
97
+ labels: str # "immicro_frozen": the published frozen labels; "predict": label the observed cells here
98
+ contrast: str # "none" | "auto" (control = groups matching CONTROL_RE, case = every other group)
99
+
100
+
101
+ DATASETS = {
102
+ "immicro": DatasetSpec("immicro", TASK / "data/immicro", IC.FEATURES, "GSE314416_ImMicro", IC.BATCH_PREFIX,
103
+ "immicro_frozen", "none"),
104
+ "ye2026_sepsis": DatasetSpec("ye2026_sepsis", TASK / "data/ye2026_sepsis", TASK / "data/ye2026_sepsis/features.npz",
105
+ "Ye2026_sepsis", "Ye2026_sepsis_", "predict", "auto"),
106
+ # added 2026-09-28, built the same way as ye2026_sepsis (observed cells labelled by the frozen annotator)
107
+ "imperial_eskd": DatasetSpec("imperial_eskd", TASK / "data/imperial_eskd", TASK / "data/imperial_eskd/features.npz",
108
+ "Imperial_eskd", "Imperial_eskd_", "predict", "auto"),
109
+ "giroux2022": DatasetSpec("giroux2022", TASK / "data/giroux2022", TASK / "data/giroux2022/features.npz",
110
+ "Giroux2022", "Giroux2022_", "predict", "auto"),
111
+ "ji2025_chili": DatasetSpec("ji2025_chili", TASK / "data/ji2025_chili", TASK / "data/ji2025_chili/features.npz",
112
+ "Ji2025_chili", "Ji2025_chili_", "predict", "auto"),
113
+ }
114
+
115
+
116
+ def load_features(path: Path) -> dict:
117
+ """features.npz of one paired dataset: sample order, groups, canonical gene axis, masks, observed pseudobulk."""
118
+ path = Path(path)
119
+ if not path.is_file():
120
+ raise SystemExit(f"features file missing: {path}")
121
+ f = np.load(path, allow_pickle=False)
122
+ keys = set(f.files)
123
+
124
+ def pick(*names, required=True):
125
+ for n in names:
126
+ if n in keys:
127
+ return n
128
+ if required:
129
+ raise SystemExit(f"{path}: none of {names} present (keys: {sorted(keys)})")
130
+ return None
131
+
132
+ sid = pick("sample_ids", "donor_ids")
133
+ did = pick("donor_ids", "sample_ids")
134
+ gk = pick("groups", "pools", required=False)
135
+ pk = pick("pseudo_raw_sum", "pseudo_raw_UMI_canonical", "pseudo")
136
+ out = {"path": str(path), "sha256": sha(path), "keys": {"sample_ids": sid, "donor_ids": did, "groups": gk, "pseudo": pk},
137
+ "sample_ids": f[sid].astype(str), "donor_ids": f[did].astype(str), "gene_ids": f["gene_ids"].astype(str),
138
+ "bulk_valid": np.asarray(f["bulk_valid"], bool), "sc_valid": np.asarray(f["sc_valid"], bool),
139
+ "pseudo": np.asarray(f[pk], np.float64)}
140
+ n = out["sample_ids"].size
141
+ out["groups"] = f[gk].astype(str) if gk else np.full(n, "", dtype=object).astype(str)
142
+ if len(set(out["sample_ids"])) != n:
143
+ raise SystemExit(f"{path}: sample ids are not unique")
144
+ # longitudinal datasets (Imperial, Giroux, Ji) carry several samples per donor: the scored unit is the sample;
145
+ # the composition null then leaves out every sample of the scored sample's donor (lodo_mean)
146
+ out["multi_sample_donors"] = len(set(out["donor_ids"])) != n
147
+ for k in ("bulk_valid", "sc_valid", "pseudo"):
148
+ if out[k].shape != (n, out["gene_ids"].size):
149
+ raise SystemExit(f"{path}: {k} shape {out[k].shape}")
150
+ return out
151
+
152
+
153
+ def gene_sets(feat: dict) -> dict:
154
+ """Panel (6k, NPZ order), scoring genes, annotation query genes -- all read from their source files.
155
+
156
+ scoring genes = panel genes both assays measured in every sample of the dataset (bulk_valid.all & sc_valid.all):
157
+ evaluate_realbulk.py's rule; used for pseudobulk r, precision/coverage, depth and the contrast.
158
+ query genes = the 1,006-gene annotation list minus genes the dataset's sc assay did not measure in every sample
159
+ (for ImMicro this is exactly the published observed query, observed_query_genes.txt).
160
+ """
161
+ panel_ids = np.asarray(IC.load_panel6k().gene_id.astype(str).to_numpy(), dtype=str)
162
+ cpos = {g: i for i, g in enumerate(feat["gene_ids"])}
163
+ miss = [g for g in panel_ids if g not in cpos]
164
+ if miss:
165
+ raise SystemExit(f"{len(miss)} panel genes absent from the features gene axis (e.g. {miss[:3]})")
166
+ panel_canon = np.asarray([cpos[g] for g in panel_ids], dtype=np.int64)
167
+ measured = feat["bulk_valid"].all(0)[panel_canon] & feat["sc_valid"].all(0)[panel_canon]
168
+ score_idx = np.flatnonzero(measured)
169
+ annot = IC.load_annotation_list()
170
+ dropped = [g for g in annot if g not in cpos or not feat["sc_valid"][:, cpos[g]].all()]
171
+ query = [g for g in annot if g not in set(dropped)]
172
+ ppos = {g: i for i, g in enumerate(panel_ids)}
173
+ qmiss = [g for g in query if g not in ppos]
174
+ if qmiss:
175
+ raise SystemExit(f"{len(qmiss)} annotation genes absent from the 6k panel (e.g. {qmiss[:3]})")
176
+ model_genes = [str(x) for x in pd.read_csv(annotator_run() / "genes.csv").gene_id]
177
+ return {"panel_ids": panel_ids, "panel_canon": panel_canon, "score_idx": score_idx, "score_ids": panel_ids[score_idx],
178
+ "score_canon": panel_canon[score_idx], "query_ids": query,
179
+ "query_panel_idx": np.asarray([ppos[g] for g in query], dtype=np.int64), "dropped_annotation_genes": dropped,
180
+ "model_genes_missing_from_query": int(len(set(model_genes) - set(query)))}
181
+
182
+
183
+ def annotator_run(explicit: Path | None = None) -> Path:
184
+ for cand in ([Path(explicit)] if explicit else list(ANNOT_RUNS)):
185
+ if (cand / "scanvi_model/model.pt").is_file():
186
+ return cand
187
+ raise SystemExit(f"frozen annotator not found in {ANNOT_RUNS}")
188
+
189
+
190
+ # --------------------------------------------------------------------------- observed cells
191
+ def cell_keys(table: pd.DataFrame) -> tuple[np.ndarray, str]:
192
+ """Stable per-cell key (the within-donor canonical order). Falls back to file order."""
193
+ for cols in (("library_id", "barcode"), ("sample_id", "barcode"), ("barcode",), ("cell_id",), ("obs_name",)):
194
+ if all(c in table.columns for c in cols):
195
+ k = table[list(cols)].astype(str).agg("|".join, axis=1).to_numpy() if len(cols) > 1 else table[cols[0]].astype(str).to_numpy()
196
+ if len(set(k)) == len(k):
197
+ return k.astype(str), "+".join(cols)
198
+ return np.char.mod("%012d", np.arange(len(table))).astype(str), "file order"
199
+
200
+
201
+ def load_cells_datadir(spec: DatasetSpec, gs: dict) -> dict | None:
202
+ """data/<dataset>/cells_panel6k.npz + cells_obs.parquet (coordinator's layout); None when absent."""
203
+ npz, obs = spec.data_dir / "cells_panel6k.npz", spec.data_dir / "cells_obs.parquet"
204
+ if not (npz.is_file() and obs.is_file()):
205
+ return None
206
+ z = np.load(npz, allow_pickle=False)
207
+ if not np.array_equal(z["panel_gene_ids"].astype(str), gs["panel_ids"]):
208
+ raise SystemExit(f"{npz}: panel_gene_ids differ from the 6k panel file")
209
+ X = sp.csr_matrix((z["data"], z["indices"], z["indptr"]), shape=tuple(int(x) for x in z["shape"]))
210
+ table = pd.read_parquet(obs)
211
+ rs = np.asarray(z["row_sample"], dtype=np.int64)
212
+ if len(table) != X.shape[0] or rs.size != X.shape[0]:
213
+ raise SystemExit(f"{npz}: {X.shape[0]} rows, {len(table)} obs rows, {rs.size} row_sample")
214
+ return {"X": X, "sample_row": rs, "table": table, "source": f"datadir:{spec.data_dir}",
215
+ "inputs_sha256": {str(npz): sha(npz), str(obs): sha(obs)}}
216
+
217
+
218
+ def load_cells_immicro_h5ad(feat: dict, gs: dict, donors: list[str] | None = None) -> dict:
219
+ """ImMicro baseline cells (observed_cells.parquet kind == 'baseline') read from the canonical per-library h5ads
220
+ by barcode, exactly as umap/cell_immicro/tools/stage_a_real_and_inputs.py does; panel columns only."""
221
+ import anndata as ad
222
+ cells = pd.read_parquet(IC.TASK / "out/observed_cells.parquet")
223
+ base = cells[cells.kind == "baseline"]
224
+ if donors is not None:
225
+ base = base[base.donor_id.isin(donors)]
226
+ row_of = {s: i for i, s in enumerate(feat["sample_ids"])}
227
+ blocks, tabs, shas = [], [], {}
228
+ for lib, sub in base.groupby("library_id", sort=True):
229
+ path = IC.SC_DIR / lib / "canonical.h5ad"
230
+ A = ad.read_h5ad(path)
231
+ if not np.array_equal(A.var_names.astype(str).to_numpy(), feat["gene_ids"]):
232
+ raise SystemExit(f"{lib}: gene axis differs from features.npz")
233
+ pos = pd.Series(np.arange(A.n_obs), index=A.obs_names.astype(str))
234
+ r = pos.reindex(sub.barcode.to_numpy())
235
+ if r.isna().any():
236
+ raise SystemExit(f"{lib}: {int(r.isna().sum())} barcodes missing")
237
+ X = A.X.tocsr() if sp.issparse(A.X) else sp.csr_matrix(A.X)
238
+ Xs = X[r.to_numpy(dtype=np.int64)]
239
+ if not np.allclose(np.asarray(Xs.sum(axis=1)).ravel(), sub.cell_total_canonical.to_numpy()):
240
+ raise SystemExit(f"{lib}: canonical totals differ from observed_cells.parquet")
241
+ Xp = Xs[:, gs["panel_canon"]].tocsr()
242
+ if Xp.nnz and not np.array_equal(Xp.data, np.round(Xp.data)):
243
+ raise SystemExit(f"{lib}: non-integer counts")
244
+ blocks.append(Xp.astype(np.int32))
245
+ tabs.append(sub)
246
+ shas[str(path)] = f"size={path.stat().st_size}"
247
+ del A, X, Xs
248
+ X = sp.vstack(blocks, format="csr")
249
+ table = pd.concat(tabs, ignore_index=True)
250
+ return {"X": X, "sample_row": table.donor_id.map(row_of).to_numpy(np.int64), "table": table,
251
+ "source": f"immicro_h5ad:{IC.SC_DIR}", "inputs_sha256": {str(IC.TASK / 'out/observed_cells.parquet'):
252
+ sha(IC.TASK / "out/observed_cells.parquet"), **shas}}
253
+
254
+
255
+ def immicro_frozen_labels(table: pd.DataFrame) -> tuple[np.ndarray, dict]:
256
+ """The published frozen f01common labels of the observed ImMicro cells, joined on observed cell_index."""
257
+ ldir = IC.TASK / "labels/observed_immicro"
258
+ man = json.loads((ldir / "labels.manifest.json").read_text())
259
+ if man["model"]["model_pt_sha256"] != ANNOT_MODEL_SHA:
260
+ raise SystemExit("observed ImMicro labels were not made with the f01common annotator")
261
+ lab = pd.read_parquet(ldir / "labels.parquet", columns=["cell_index", "celltype_l1_pred"]).set_index("cell_index")
262
+ out = lab.celltype_l1_pred.reindex(table.cell_index.to_numpy())
263
+ if out.isna().any():
264
+ raise SystemExit(f"{int(out.isna().sum())} observed cells without a frozen label")
265
+ info = {"source": str(ldir / "labels.parquet"), "sha256": sha(ldir / "labels.parquet"),
266
+ "model_pt_sha256": man["model"]["model_pt_sha256"],
267
+ "zero_padded_model_genes": man["gene_space"]["model_genes_missing_from_query_zero_padded"]}
268
+ return out.astype(str).to_numpy(), info
269
+
270
+
271
+ # --------------------------------------------------------------------------- frozen annotation (predict_scanvi.py)
272
+ def run_annotator(counts_query: sp.csr_matrix, query_ids: list[str], sample_key: np.ndarray, *, work: Path, method: str,
273
+ spec: DatasetSpec, split: str, threads: int, annot: Path, expected_zero_pad: int,
274
+ source_note: dict) -> tuple[pd.DataFrame, dict]:
275
+ """Label integer cells with the frozen f01common scANVI exactly as score_generated.py does (CPU, zero query
276
+ epochs, batch_key = prefix + sample key). Keeps labels.parquet + manifest, deletes the query h5ad and the
277
+ probability tables."""
278
+ import anndata as ad
279
+ work.mkdir(parents=True, exist_ok=True)
280
+ q = counts_query.astype(np.float32).tocsr()
281
+ q.eliminate_zeros()
282
+ obs = pd.DataFrame({"cell_index": np.arange(q.shape[0]), "sample_id": np.asarray(sample_key, dtype=object),
283
+ "source": method})
284
+ obs["batch_key"] = pd.Categorical([f"{spec.batch_prefix}{s}" for s in obs.sample_id])
285
+ obs["aifi_l2_train"] = pd.Categorical(["Unknown"] * len(obs), categories=["Unknown"])
286
+ obs.index = pd.Index([f"{method}:{i}" for i in range(len(obs))])
287
+ qa = ad.AnnData(X=q, obs=obs, var=pd.DataFrame(index=pd.Index(query_ids, name="gene_id")))
288
+ qa.layers["counts"] = qa.X.copy()
289
+ qa.uns["query_build"] = {"set": method, **source_note}
290
+ qpath = work / "query.h5ad"
291
+ qa.write_h5ad(qpath)
292
+ del qa, q
293
+ lab_dir = work / "labels"
294
+ cmd = [str(IC.SCANVI_PY), "-u", str(IC.PREDICT), "--model-dir", str(annot / "scanvi_model"), "--query", str(qpath),
295
+ "--out-dir", str(lab_dir), "--method-name", method, "--dataset-id", spec.dataset_id, "--split", split,
296
+ "--sample-id-col", "sample_id", "--batch-key-col", "batch_key", "--batch-prefix", spec.batch_prefix,
297
+ "--seed", str(POISSON_SEED), "--device", "cpu", "--num-threads", str(threads), "--eval-batch-size", "2048",
298
+ "--allow-missing-genes"]
299
+ env = dict(os.environ, CUDA_VISIBLE_DEVICES="", PYTHONNOUSERSITE="1", OMP_NUM_THREADS=str(threads),
300
+ MKL_NUM_THREADS=str(threads), OPENBLAS_NUM_THREADS=str(threads))
301
+ t0 = time.monotonic()
302
+ res = subprocess.run(cmd, env=env, capture_output=True, text=True)
303
+ (work / "predict_scanvi.log").write_text(res.stdout + "\n--- stderr ---\n" + res.stderr)
304
+ qpath.unlink(missing_ok=True)
305
+ for extra in ("soft_probabilities_l2.parquet", "probabilities_l1.parquet"):
306
+ (lab_dir / extra).unlink(missing_ok=True)
307
+ if res.returncode != 0:
308
+ raise SystemExit(f"predict_scanvi.py failed (see {work / 'predict_scanvi.log'})")
309
+ man = json.loads((lab_dir / "labels.manifest.json").read_text())
310
+ if man["model"]["model_pt_sha256"] != ANNOT_MODEL_SHA:
311
+ raise SystemExit("annotator model sha differs from the f01common model")
312
+ zp = man["gene_space"]["model_genes_missing_from_query_zero_padded"]
313
+ if zp != expected_zero_pad:
314
+ raise SystemExit(f"annotation contract differs: {zp} zero-padded model genes, expected {expected_zero_pad}")
315
+ lab = pd.read_parquet(lab_dir / "labels.parquet")
316
+ if len(lab) != len(sample_key) or not np.array_equal(lab.cell_index.to_numpy(), np.arange(len(sample_key))):
317
+ raise SystemExit("labels are not row-aligned with the query cells")
318
+ extra = sorted(set(lab.celltype_l1_pred.astype(str)) - set(GATE))
319
+ if extra:
320
+ raise SystemExit(f"labels outside the six-type gate: {extra}")
321
+ info = {"labels_parquet": str(lab_dir / "labels.parquet"), "model_pt_sha256": man["model"]["model_pt_sha256"],
322
+ "zero_padded_model_genes": zp, "label_counts": man["label_counts"]["celltype_l1_pred"],
323
+ "mean_l2_max_prob": man["confidence"]["mean_l2_max_prob"], "predict_seconds": round(time.monotonic() - t0, 1),
324
+ "command": cmd[2:]}
325
+ return lab, info
326
+
327
+
328
+ # --------------------------------------------------------------------------- donor-keyed subsample rule
329
+ def donor_rng(seed: int, donor: str) -> np.random.Generator:
330
+ """A stream that depends only on (seed, donor id): the same donor draws the same cells in every fold and arm."""
331
+ key = int.from_bytes(hashlib.sha256(str(donor).encode()).digest()[:8], "little")
332
+ return np.random.default_rng([int(seed), key])
333
+
334
+
335
+ def reference_split(n_cells: int, donor: str, n_sub: int = N_SUB) -> tuple[np.ndarray, np.ndarray]:
336
+ """Positions (in the donor's canonical cell order) of R1 (PCA / k-NN reference) and R2 (held-out real control):
337
+ one permutation from donor_rng(SUB_SEED, donor); R1 = first n, R2 = next n, n = min(150, n_cells // 2)."""
338
+ n = min(int(n_sub), int(n_cells) // 2)
339
+ if n < 1:
340
+ raise SystemExit(f"{donor}: {n_cells} observed cells, cannot draw a reference")
341
+ perm = donor_rng(SUB_SEED, donor).permutation(int(n_cells))
342
+ return np.sort(perm[:n]), np.sort(perm[n:2 * n])
343
+
344
+
345
+ def generated_subsample(n_gen: int, n_ref: int, donor: str) -> np.ndarray:
346
+ """Positions (in the donor's NPZ cell order) of the generated cells embedded for precision/coverage: n_ref cells
347
+ (the donor's R1 size) drawn without replacement with donor_rng(SUB_SEED + 1, donor)."""
348
+ if n_gen < n_ref:
349
+ raise SystemExit(f"{donor}: {n_gen} generated cells, fewer than the {n_ref} reference cells")
350
+ return np.sort(donor_rng(GEN_SUB_SEED, donor).choice(int(n_gen), size=int(n_ref), replace=False))
351
+
352
+
353
+ # --------------------------------------------------------------------------- per donor x cell type aggregates
354
+ def type_aggregates(X: sp.csr_matrix, donor_idx: np.ndarray, labels: np.ndarray, n_donors: int,
355
+ types=CONTRAST_TYPES) -> dict:
356
+ """Per (donor, type) on the columns of X: cell count, summed counts, summed per-cell CP10K (library = the columns
357
+ of X; a cell with no counts contributes zeros, as SB.cp10k_log1p) and the number of cells with count > 0."""
358
+ X = X.tocsr().astype(np.float64)
359
+ lib = np.asarray(X.sum(axis=1)).ravel()
360
+ cp = (sp.diags(np.divide(CP10K, lib, out=np.zeros_like(lib), where=lib > 0)) @ X).tocsr()
361
+ det = X.copy()
362
+ det.data = (det.data > 0).astype(np.float64)
363
+ T, G = len(types), X.shape[1]
364
+ out = {"n": np.zeros((n_donors, T), np.int64), "sum": np.zeros((n_donors, T, G)), "cp10k": np.zeros((n_donors, T, G)),
365
+ "det": np.zeros((n_donors, T, G))}
366
+ labels = np.asarray(labels).astype(str)
367
+ donor_idx = np.asarray(donor_idx, np.int64)
368
+ for ti, t in enumerate(types):
369
+ m = np.flatnonzero(labels == t)
370
+ if m.size == 0:
371
+ continue
372
+ ind = sp.csr_matrix((np.ones(m.size), (donor_idx[m], np.arange(m.size))), shape=(n_donors, m.size))
373
+ out["n"][:, ti] = np.bincount(donor_idx[m], minlength=n_donors)
374
+ out["sum"][:, ti] = (ind @ X[m]).toarray()
375
+ out["cp10k"][:, ti] = (ind @ cp[m]).toarray()
376
+ out["det"][:, ti] = (ind @ det[m]).toarray()
377
+ return out
378
+
379
+
380
+ def lfc_mean_cp10k(n: np.ndarray, cp_sum: np.ndarray, case: np.ndarray, ctrl: np.ndarray) -> np.ndarray | None:
381
+ """Primary contrast statistic: log2(mean CP10K + 1) of case minus control. The group mean is donor-balanced: the
382
+ mean over the group's donors (those with >= 1 cell of the type) of the donor's mean per-cell CP10K."""
383
+ have = n > 0
384
+ c, h = case & have, ctrl & have
385
+ if c.sum() < 1 or h.sum() < 1:
386
+ return None
387
+ mc = (cp_sum[c] / n[c, None]).mean(0)
388
+ mh = (cp_sum[h] / n[h, None]).mean(0)
389
+ return np.log2(mc + 1.0) - np.log2(mh + 1.0)
390
+
391
+
392
+ def lfc_pseudobulk(n: np.ndarray, counts_sum: np.ndarray, case: np.ndarray, ctrl: np.ndarray) -> np.ndarray | None:
393
+ """Secondary: the SLE benchmark evaluator's statistic (EV.group_log_fold_change): donor x type pseudobulk,
394
+ log1p(CPM) with library = all columns, mean(case) - mean(control), natural log."""
395
+ rows = (n > 0) & (case | ctrl)
396
+ if rows.sum() == 0:
397
+ return None
398
+ return EV.group_log_fold_change(counts_sum[rows], case[rows])
399
+
400
+
401
+ def bulk_lfc(bulk: np.ndarray, case: np.ndarray, ctrl: np.ndarray) -> dict:
402
+ """Broadcast baseline from the input bulk (condition NPZ bulk_counts on the scoring genes), both statistics."""
403
+ lib = bulk.sum(1, keepdims=True)
404
+ if (lib <= 0).any():
405
+ raise SystemExit("a condition bulk has no counts on the scoring genes")
406
+ cp = bulk / lib * CP10K
407
+ prim = np.log2(cp[case].mean(0) + 1.0) - np.log2(cp[ctrl].mean(0) + 1.0) if case.any() and ctrl.any() else None
408
+ rows = case | ctrl
409
+ sec = EV.group_log_fold_change(bulk[rows], case[rows]) if rows.any() else None
410
+ return {"mean_cp10k": prim, "pseudobulk_log1p_cpm": sec}
411
+
412
+
413
+ def resid(y, x):
414
+ """OLS residual of y on [1, x] (sle_broadcast/scripts/residual_specificity.py)."""
415
+ X = np.column_stack([np.ones_like(x), x])
416
+ beta, *_ = np.linalg.lstsq(X, y, rcond=None)
417
+ return y - X @ beta
418
+
419
+
420
+ def contrast_scores(obs_lfc, gen_lfc, blk_lfc, genes: np.ndarray) -> dict:
421
+ """Pearson r of generated vs observed logFC, of broadcast vs observed, and the partial r of generated with
422
+ observed given the broadcast (OLS residuals, as residual_specificity.py)."""
423
+ out = {"n_genes": int(genes.sum()), "r_generated": float("nan"), "r_broadcast": float("nan"),
424
+ "partial_r_generated_given_broadcast": float("nan"), "r_generated_vs_broadcast": float("nan")}
425
+ if obs_lfc is None or genes.sum() < 3:
426
+ return out
427
+ o = obs_lfc[genes]
428
+ if gen_lfc is not None:
429
+ out["r_generated"] = EV.pearson(gen_lfc[genes], o)
430
+ if blk_lfc is not None:
431
+ out["r_broadcast"] = EV.pearson(blk_lfc[genes], o)
432
+ if gen_lfc is not None and blk_lfc is not None:
433
+ b = blk_lfc[genes]
434
+ out["partial_r_generated_given_broadcast"] = EV.pearson(resid(o, b), resid(gen_lfc[genes], b))
435
+ out["r_generated_vs_broadcast"] = EV.pearson(gen_lfc[genes], b)
436
+ return out
437
+
438
+
439
+ # --------------------------------------------------------------------------- top-50 DEG overlap (benchmark score)
440
+ # The SLE benchmark's "top-50 DEG" (total_top50_overlap of evaluate_generated_vs_truth.py, Welch backend; the 81 / 84
441
+ # of utility_studies_final6k_20260925/sle) and its bulk-broadcast analogue (sle_broadcast/scripts/sle_broadcast.py,
442
+ # "broadcast_input_bulk"). The statistic is EV's own functions; only the donor-row selection is written here.
443
+ DEG_TYPES = CONTRAST_TYPES + ("DC",)
444
+ DEG_TOP_N = int(EV.DEFAULT_TOP_N) # 50
445
+ DEG_FDR = float(EV.DEFAULT_FDR) # 0.05
446
+ DEG_STATISTIC = "welch_top50_deg" # contrast.csv rows of this score
447
+ DEG_REF_NPZ = "deg_reference.npz"
448
+ DEG_REF_MANIFEST = "deg_reference_manifest.json"
449
+ SHORT_TYPE = {"T cell": "T", "B cell": "B", "Monocyte": "Mono", "NK cell": "NK", "DC": "DC", "Other": "Other"}
450
+ assert DEG_TYPES[:len(CONTRAST_TYPES)] == CONTRAST_TYPES and DEG_TOP_N == 50 and DEG_FDR == 0.05
451
+
452
+
453
+ def deg_top(n: np.ndarray, counts_sum: np.ndarray, case: np.ndarray, ctrl: np.ndarray, genes) -> dict:
454
+ """One side's top-50 list for one cell type, as evaluate_generated_vs_truth.evaluate (its _deg + top_deg_genes):
455
+ rows = the donor x type pseudobulks with >= 1 cell of the type (EV.aggregate_pseudobulk keeps only those), limited
456
+ to case | control donors; EV.welch_bh_deg (log1p CPM over the given columns, two-sided Welch, BH over the genes with
457
+ a defined p-value; None unless both arms have >= 2 such donors); EV.top_deg_genes (FDR < 0.05, descending |logFC|,
458
+ first 50, fewer when fewer are significant)."""
459
+ n, case, ctrl = np.asarray(n), np.asarray(case, bool), np.asarray(ctrl, bool)
460
+ rows = (n > 0) & (case | ctrl)
461
+ deg = EV.welch_bh_deg(np.asarray(counts_sum, np.float64)[rows], case[rows]) if rows.any() else None
462
+ return {"top": EV.top_deg_genes(deg, genes, top_n=DEG_TOP_N, fdr=DEG_FDR), "defined": deg is not None,
463
+ "n_significant": int(deg.significant(DEG_FDR).size) if deg is not None else 0,
464
+ "n_tested": int(deg.tested.sum()) if deg is not None else 0,
465
+ "n_case_donors": int((rows & case).sum()), "n_control_donors": int((rows & ctrl).sum())}
466
+
467
+
468
+ def deg_overlap(ref_top: list, other_top: list) -> dict:
469
+ """EV's per-type top50_overlap_count (|intersection|) and top50_jaccard (EV.jaccard; NaN for two empty lists)."""
470
+ return {"overlap": len(set(ref_top) & set(other_top)), "jaccard": EV.jaccard(ref_top, other_top)}
471
+
472
+
473
+ def write_deg_reference(out_dir: Path, man: dict, n: np.ndarray, sums: np.ndarray, check: dict) -> dict:
474
+ """deg_reference.npz: per scored-reference donor x DEG_TYPES cell count and summed counts on the scoring genes
475
+ (observed cells, observed labels), bound to reference.npz by its sha256. Written atomically."""
476
+ out_dir = Path(out_dir)
477
+ npz = out_dir / DEG_REF_NPZ
478
+ tmp = out_dir / (DEG_REF_NPZ[:-4] + ".tmp.npz")
479
+ np.savez_compressed(tmp, deg_types=np.asarray(DEG_TYPES), deg_n=np.asarray(n, np.int64),
480
+ deg_sum=np.asarray(sums, np.float64), reference_sha256=np.asarray(man["reference_sha256"]))
481
+ os.replace(tmp, npz)
482
+ dman = {"schema": "paired_ft_deg_reference.v1", "dataset": man["dataset"], "written_utc": now(),
483
+ "deg_reference_npz": str(npz), "sha256": sha(npz), "reference_sha256": man["reference_sha256"],
484
+ "types": list(DEG_TYPES), "n_cells": dict(zip(DEG_TYPES, np.asarray(n).sum(0).tolist())),
485
+ "donors_with_cells": dict(zip(DEG_TYPES, (np.asarray(n) > 0).sum(0).tolist())), "checks": check}
486
+ (out_dir / DEG_REF_MANIFEST).write_text(json.dumps(dman, indent=1, default=str) + "\n")
487
+ log(f"DEG reference: {npz} ({', '.join(f'{t} {c}' for t, c in dman['n_cells'].items())} cells)")
488
+ return dman
489
+
490
+
491
+ def build_deg_reference(spec: DatasetSpec, cache_dir: Path) -> dict:
492
+ """deg_reference.npz for an existing reference cache, from the same observed cells and the same observed labels
493
+ (no re-annotation). Fail-closed: features / cells inputs / labels must be the ones in reference_manifest.json,
494
+ and the four contrast types must equal the reference's agg_n / agg_sum exactly."""
495
+ cache_dir = Path(cache_dir)
496
+ ref, man = load_reference(cache_dir)
497
+ feat = load_features(spec.features)
498
+ if feat["sha256"] != man["features"]["sha256"]:
499
+ raise SystemExit(f"{spec.features}: sha differs from the one the reference was built from")
500
+ gs = gene_sets(feat)
501
+ if not np.array_equal(gs["score_ids"], ref["score_ids"].astype(str)):
502
+ raise SystemExit("scoring genes differ from the reference")
503
+ if man["cells"]["source"].startswith("datadir:"):
504
+ cells = load_cells_datadir(spec, gs)
505
+ if cells is None or cells["inputs_sha256"] != man["cells"]["inputs_sha256"]:
506
+ raise SystemExit(f"{spec.data_dir}: observed cell files differ from the ones the reference was built from")
507
+ elif spec.name == "immicro":
508
+ cells = load_cells_immicro_h5ad(feat, gs)
509
+ else:
510
+ raise SystemExit(f"unknown cells source {man['cells']['source']}")
511
+ table = cells["table"].reset_index(drop=True)
512
+ if spec.labels == "immicro_frozen":
513
+ labels, info = immicro_frozen_labels(table)
514
+ if info["sha256"] != man["labels"]["sha256"]:
515
+ raise SystemExit("frozen ImMicro labels differ from the reference's")
516
+ else:
517
+ lab_path = cache_dir / "observed_labels" / "labels" / "labels.parquet"
518
+ if sha(lab_path) != man["labels"]["sha256"]:
519
+ raise SystemExit(f"{lab_path}: sha differs from the reference manifest")
520
+ lab = pd.read_parquet(lab_path, columns=["cell_index", "celltype_l1_pred"])
521
+ if len(lab) != len(table) or not np.array_equal(lab.cell_index.to_numpy(), np.arange(len(table))):
522
+ raise SystemExit("observed labels are not row-aligned with the observed cells")
523
+ labels = lab.celltype_l1_pred.astype(str).to_numpy()
524
+ srow = cells["sample_row"]
525
+ D = feat["sample_ids"].size
526
+ have = np.bincount(srow, minlength=D) > 0
527
+ donors = feat["sample_ids"][have]
528
+ if not np.array_equal(donors, ref["donors"].astype(str)):
529
+ raise SystemExit("donor order differs from the reference")
530
+ remap = np.full(D, -1)
531
+ remap[np.flatnonzero(have)] = np.arange(donors.size)
532
+ Xs = cells["X"].tocsr()[:, gs["score_idx"]].tocsr()
533
+ del cells
534
+ agg = type_aggregates(Xs, remap[srow], np.asarray(labels, dtype=str), donors.size, types=DEG_TYPES)
535
+ k = len(CONTRAST_TYPES)
536
+ same = bool(np.array_equal(agg["n"][:, :k], ref["agg_n"])
537
+ and np.array_equal(agg["sum"][:, :k].astype(np.float32), ref["agg_sum"]))
538
+ if not same:
539
+ raise SystemExit("recomputed contrast-type aggregates differ from reference.npz (cells or labels misaligned)")
540
+ return write_deg_reference(cache_dir, man, agg["n"], agg["sum"],
541
+ {"contrast_types_equal_reference_agg": same, "built_from": "existing cache"})
542
+
543
+
544
+ def load_deg_reference(cache_dir: Path, man: dict, ref: dict) -> dict:
545
+ """DEG aggregates for scoring: deg_reference.npz when present (fail-closed on a stale file), else the four
546
+ contrast types from reference.npz (then DC is not scored)."""
547
+ npz, mpath = Path(cache_dir) / DEG_REF_NPZ, Path(cache_dir) / DEG_REF_MANIFEST
548
+ if not npz.is_file():
549
+ return {"types": CONTRAST_TYPES, "n": ref["agg_n"].astype(np.int64), "sum": ref["agg_sum"].astype(np.float64),
550
+ "source": "reference.npz agg_n / agg_sum (four contrast types)", "sha256": None,
551
+ "note": f"no {DEG_REF_NPZ} in {cache_dir}: DC not scored "
552
+ f"(score_ft.py --dataset {man['dataset']} --build-deg-reference adds it)"}
553
+ dman = json.loads(mpath.read_text())
554
+ s = sha(npz)
555
+ z = np.load(npz, allow_pickle=False)
556
+ if s != dman["sha256"] or dman["reference_sha256"] != man["reference_sha256"] \
557
+ or str(z["reference_sha256"]) != man["reference_sha256"]:
558
+ raise SystemExit(f"{npz} does not belong to the current reference.npz (rebuild with --build-deg-reference)")
559
+ return {"types": tuple(z["deg_types"].astype(str)), "n": z["deg_n"].astype(np.int64),
560
+ "sum": z["deg_sum"].astype(np.float64), "source": str(npz), "sha256": s, "note": None}
561
+
562
+
563
+ # --------------------------------------------------------------------------- reference cache
564
+ def build_reference(spec: DatasetSpec, out_dir: Path, *, source: str = "auto", threads: int = 8,
565
+ annot: Path | None = None, check_donors: int = 3) -> dict:
566
+ """Per-dataset observed reference: everything the scorer needs from the observed cells, independent of fold/arm.
567
+
568
+ Stored: donor order/groups, n cells, observed six-type composition, observed pseudobulk on the scoring genes,
569
+ R1/R2 reference cells (counts on the scoring genes, donor-keyed rule), per-cell library on the scoring genes,
570
+ and per donor x contrast-type aggregates (n, summed counts, summed CP10K, detection counts)."""
571
+ t0 = time.monotonic()
572
+ out_dir.mkdir(parents=True, exist_ok=True)
573
+ feat = load_features(spec.features)
574
+ gs = gene_sets(feat)
575
+ annot = annotator_run(annot)
576
+ cells = None
577
+ checks: dict = {}
578
+ if source in ("auto", "datadir"):
579
+ cells = load_cells_datadir(spec, gs)
580
+ if cells is None and source == "datadir":
581
+ raise SystemExit(f"{spec.data_dir}: cells_panel6k.npz / cells_obs.parquet missing")
582
+ if cells is None:
583
+ if spec.name != "immicro":
584
+ raise SystemExit(f"{spec.data_dir}: no observed cells (cells_panel6k.npz + cells_obs.parquet)")
585
+ log("reading ImMicro observed cells from the canonical h5ad libraries")
586
+ cells = load_cells_immicro_h5ad(feat, gs)
587
+ elif spec.name == "immicro" and check_donors > 0 and IC.SC_DIR.is_dir():
588
+ pick = list(feat["sample_ids"][np.linspace(0, feat["sample_ids"].size - 1, check_donors).astype(int)])
589
+ log(f"checking {cells['source']} against the canonical h5ads for {pick}")
590
+ ref = load_cells_immicro_h5ad(feat, gs, pick)
591
+ a_keys, _ = cell_keys(ref["table"])
592
+ m = np.isin(cells["sample_row"], [int(np.flatnonzero(feat["sample_ids"] == d)[0]) for d in pick])
593
+ b_keys, _ = cell_keys(cells["table"].loc[m].reset_index(drop=True))
594
+ oa, ob = np.argsort(a_keys, kind="stable"), np.argsort(b_keys, kind="stable")
595
+ same = np.array_equal(a_keys[oa], b_keys[ob]) and (ref["X"][oa] != cells["X"][np.flatnonzero(m)][ob]).nnz == 0
596
+ checks["datadir_equals_h5ad_for_donors"] = {"donors": pick, "equal": bool(same)}
597
+ if not same:
598
+ raise SystemExit(f"{cells['source']} differs from the canonical h5ads for {pick}")
599
+ X = cells["X"].tocsr()
600
+ srow = cells["sample_row"]
601
+ table = cells["table"].reset_index(drop=True)
602
+ if spec.labels == "immicro_frozen":
603
+ labels, label_info = immicro_frozen_labels(table)
604
+ else:
605
+ lab_path = out_dir / "observed_labels" / "labels" / "labels.parquet"
606
+ log(f"labelling {X.shape[0]} observed cells with the frozen annotator")
607
+ lab, label_info = run_annotator(X[:, gs["query_panel_idx"]], gs["query_ids"], feat["sample_ids"][srow],
608
+ work=out_dir / "observed_labels", method=f"observed_{spec.name}", spec=spec,
609
+ split="observed", threads=threads, annot=annot,
610
+ expected_zero_pad=gs["model_genes_missing_from_query"],
611
+ source_note={"kind": "real_counts", "readout": "real_counts", "seed": None,
612
+ "source": cells["source"]})
613
+ labels = lab.celltype_l1_pred.astype(str).to_numpy()
614
+ label_info["sha256"] = sha(lab_path)
615
+ labels = np.asarray(labels, dtype=str)
616
+ keys, key_rule = cell_keys(table)
617
+ order = np.lexsort((keys, srow))
618
+ X, srow, labels, keys = X[order], srow[order], labels[order], keys[order]
619
+ # fail-closed: every sample's summed panel counts equal the features pseudobulk exactly
620
+ D = feat["sample_ids"].size
621
+ have = np.bincount(srow, minlength=D) > 0
622
+ ind = sp.csr_matrix((np.ones(srow.size), (srow, np.arange(srow.size))), shape=(D, srow.size))
623
+ sums = (ind @ X.astype(np.float64)).toarray()
624
+ want = np.nan_to_num(feat["pseudo"][:, gs["panel_canon"]], nan=0.0)
625
+ bad = np.flatnonzero(have & (sums != want).any(1))
626
+ checks["panel_sums_equal_features_pseudobulk"] = {"n_samples_checked": int(have.sum()), "n_mismatch": int(bad.size)}
627
+ if bad.size:
628
+ raise SystemExit(f"observed cells do not sum to the features pseudobulk for {bad.size} samples, e.g. "
629
+ f"{feat['sample_ids'][bad[:3]].tolist()}")
630
+ donors_idx = np.flatnonzero(have)
631
+ donors = feat["sample_ids"][donors_idx]
632
+ remap = np.full(D, -1)
633
+ remap[donors_idx] = np.arange(donors_idx.size)
634
+ didx = remap[srow]
635
+ S = donors.size
636
+ Xs = X[:, gs["score_idx"]].tocsr()
637
+ del X
638
+ lib = np.asarray(Xs.sum(axis=1)).ravel()
639
+ n_cells = np.bincount(didx, minlength=S)
640
+ comp = IC.composition(pd.Series(labels), pd.Series(donors[didx]), donors).to_numpy()
641
+ starts = np.r_[0, np.cumsum(n_cells)[:-1]]
642
+ r1, r2, n_ref = [], [], np.zeros(S, np.int64)
643
+ for s in range(S):
644
+ a, b = reference_split(n_cells[s], donors[s])
645
+ r1.append(starts[s] + a)
646
+ r2.append(starts[s] + b)
647
+ n_ref[s] = a.size
648
+ r1, r2 = np.concatenate(r1), np.concatenate(r2)
649
+ agg = type_aggregates(Xs, didx, labels, S)
650
+ pb = feat["pseudo"][donors_idx][:, gs["score_canon"]]
651
+ if not np.isfinite(pb).all():
652
+ raise SystemExit("features pseudobulk has non-finite values on the scoring genes")
653
+
654
+ def pack(prefix, M):
655
+ M = M.tocsr()
656
+ return {f"{prefix}_data": M.data.astype(np.int32), f"{prefix}_indices": M.indices.astype(np.int32),
657
+ f"{prefix}_indptr": M.indptr.astype(np.int64), f"{prefix}_shape": np.asarray(M.shape, np.int64)}
658
+
659
+ arrays = {"donors": donors.astype(str), "groups": feat["groups"][donors_idx].astype(str), "n_cells": n_cells,
660
+ "composition": comp, "pseudobulk": pb, "score_ids": gs["score_ids"], "score_idx": gs["score_idx"],
661
+ "panel_ids": gs["panel_ids"], "query_ids": np.asarray(gs["query_ids"]),
662
+ **pack("r1", Xs[r1]), "r1_donor": didx[r1], "r1_label": labels[r1], "r1_key": keys[r1],
663
+ **pack("r2", Xs[r2]), "r2_donor": didx[r2], "r2_label": labels[r2], "r2_key": keys[r2],
664
+ "n_ref": n_ref, "cell_lib": lib.astype(np.float32), "cell_donor": didx.astype(np.int32),
665
+ "cell_mono": (labels == "Monocyte"),
666
+ "agg_types": np.asarray(CONTRAST_TYPES), "agg_n": agg["n"], "agg_sum": agg["sum"].astype(np.float32),
667
+ "agg_cp10k": agg["cp10k"].astype(np.float32), "agg_det": agg["det"].astype(np.int32)}
668
+ npz = out_dir / "reference.npz"
669
+ np.savez_compressed(npz, **arrays)
670
+ man = {"schema": "paired_ft_scoring_reference.v1", "dataset": spec.name, "written_utc": now(),
671
+ "reference_npz": str(npz), "reference_sha256": sha(npz), "reference_bytes": npz.stat().st_size,
672
+ "features": {"path": feat["path"], "sha256": feat["sha256"], "keys": feat["keys"]},
673
+ "cells": {"source": cells["source"], "inputs_sha256": cells["inputs_sha256"], "n_cells": int(lib.size),
674
+ "key_rule": key_rule},
675
+ "labels": label_info, "annotator_run": str(annot),
676
+ "n_donors": int(S), "samples_without_cells": feat["sample_ids"][~have].tolist(),
677
+ "gene_sets": {"panel": int(gs["panel_ids"].size), "scoring": int(gs["score_idx"].size),
678
+ "query": len(gs["query_ids"]), "dropped_annotation_genes": gs["dropped_annotation_genes"],
679
+ "model_genes_missing_from_query": gs["model_genes_missing_from_query"]},
680
+ "reference_rule": {"n_sub": N_SUB, "seed": SUB_SEED, "rule": "per donor: canonical order = sort by cell key; "
681
+ "permutation from default_rng([20260925, sha256(donor)[:8] as uint64 LE]); R1 = first "
682
+ "min(150, n//2), R2 = next same number"},
683
+ "n_ref": {"min": int(n_ref.min()), "median": float(np.median(n_ref)), "total": int(n_ref.sum())},
684
+ "checks": checks, "seconds": round(time.monotonic() - t0, 1)}
685
+ (out_dir / "reference_manifest.json").write_text(json.dumps(man, indent=1, default=str) + "\n")
686
+ log(f"reference: {S} donors, {lib.size} cells, R1 {r1.size}, {npz.stat().st_size / 2**20:.1f} MiB, {man['seconds']} s")
687
+ extra = type_aggregates(Xs, didx, labels, S, types=DEG_TYPES[len(CONTRAST_TYPES):])
688
+ write_deg_reference(out_dir, man, np.concatenate([agg["n"], extra["n"]], axis=1),
689
+ np.concatenate([agg["sum"], extra["sum"]], axis=1),
690
+ {"contrast_types_equal_reference_agg": True, "built_from": "build_reference"})
691
+ return man
692
+
693
+
694
+ def load_reference(cache_dir: Path) -> tuple[dict, dict]:
695
+ man_path = cache_dir / "reference_manifest.json"
696
+ if not man_path.is_file():
697
+ raise SystemExit(f"no reference at {cache_dir}; run score_ft.py --dataset NAME --build-reference first")
698
+ man = json.loads(man_path.read_text())
699
+ npz = cache_dir / "reference.npz"
700
+ if sha(npz) != man["reference_sha256"]:
701
+ raise SystemExit(f"{npz}: sha differs from its manifest")
702
+ z = np.load(npz, allow_pickle=False)
703
+ ref = {k: z[k] for k in z.files}
704
+ for p in ("r1", "r2"):
705
+ ref[p] = sp.csr_matrix((ref.pop(f"{p}_data"), ref.pop(f"{p}_indices"), ref.pop(f"{p}_indptr")),
706
+ shape=tuple(int(x) for x in ref.pop(f"{p}_shape")))
707
+ return ref, man
708
+
709
+
710
+ def lodo_mean(frac: np.ndarray, donor_of: np.ndarray) -> np.ndarray:
711
+ """Leave-donor-out cohort mean: for sample i, the mean over samples of other donors. Equals the leave-one-out
712
+ mean (immicro_common.loo_mean) when every donor has one sample."""
713
+ frac = np.asarray(frac, dtype=np.float64)
714
+ donor_of = np.asarray(donor_of).astype(str)
715
+ out = np.full_like(frac, np.nan)
716
+ for i in range(frac.shape[0]):
717
+ m = donor_of != donor_of[i]
718
+ if m.any():
719
+ out[i] = frac[m].mean(axis=0)
720
+ return out