junidude14 commited on
Commit
ac01120
·
verified ·
1 Parent(s): da900ca

Archive 4 checkpoints (1-4)

Browse files
paper-releases/20260928/diffusion/data/calibration/tools/refcal/common_refcal.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared paths and helpers for the reference-anchored calibration (refcal) study.
2
+
3
+ Nothing here types a donor, sample or gene by hand: every list is read from the source file that defines it.
4
+ The estimator is the published one, imported unchanged from
5
+ ``plans/realbulk_generation_20260922/build_realbulk_conditions.py`` (``cpm``, ``gene_multiplier``,
6
+ ``to_condition_counts``, ``load_cohort``, ``calibration_donors``).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import importlib.util
12
+ import json
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+
18
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
19
+ PLANS = M8 / "plans"
20
+ UT = PLANS / "utility_studies_final6k_20260925"
21
+ TASK = UT / "refcal"
22
+ RB_DIR = PLANS / "realbulk_generation_20260922"
23
+ REALBULK_BUILDER = RB_DIR / "build_realbulk_conditions.py"
24
+ BEHCET_BUILDER = PLANS / "behcet_c1q_repro_20260921/tools/build_behcet_conditions.py"
25
+ BEHCET_NPZ = PLANS / "behcet_c1q_repro_20260921/conditions/behcet_donor_conditions.npz"
26
+ BEHCET_MANIFEST = PLANS / "behcet_c1q_repro_20260921/conditions/MANIFEST.json"
27
+ AR_COND = UT / "arunachalam/conditions"
28
+ AR_MANIFEST = AR_COND / "MANIFEST.json"
29
+ CONDMORE = UT / "conditions_more"
30
+ CHECKPOINT = M8 / "runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt"
31
+ CHECKPOINT_SHA = "8c7cd0e83e2bc19fe03dfcbc084919a1e2f61be8cc8bc12f4caf543dfda91633"
32
+ TIER_6K = M8 / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/gene_positions.npy"
33
+ TRAIN_RECIPES = M8 / "artifacts/panel_ladder_floor01_1m_20260923/ordered_train_recipes.csv"
34
+
35
+ ATLAS = Path(
36
+ "/home/sj_server_1/gblee/datalake/single-cell-RNA-seq-datasets/PBMC-cells/"
37
+ "009_A_Human_Immune_Health_Atlas_Human_Immune_Health_Atlas_AIFI_immune_dynamics_across_healthy_age/"
38
+ "39832a61-3df1-4f1f-971d-3c2a74539047.h5ad"
39
+ )
40
+ AIFI_REF_DIR = PLANS / "aifi_scanvi_rebuild_20260916/reference"
41
+ AIFI_REF_H5AD = AIFI_REF_DIR / "aifi_reference_20097.h5ad"
42
+ AIFI_STRATA = AIFI_REF_DIR / "stratum_allocation.csv"
43
+ AIFI_SELECTION = AIFI_REF_DIR / "cell_selection.parquet"
44
+ AIFI_PRESENCE = AIFI_REF_DIR / "panel_presence_20097.csv"
45
+ AIFI_REF_MANIFEST = AIFI_REF_DIR / "REFERENCE_MANIFEST.json"
46
+ REF_NPZ = TASK / "reference/aifi_donor_pseudobulk_20097.npz"
47
+ REF_JSON = TASK / "reference/aifi_donor_pseudobulk_20097.json"
48
+
49
+
50
+ def sha256_file(path: Path, block: int = 1 << 24) -> str:
51
+ h = hashlib.sha256()
52
+ with Path(path).open("rb") as fh:
53
+ for chunk in iter(lambda: fh.read(block), b""):
54
+ h.update(chunk)
55
+ return h.hexdigest()
56
+
57
+
58
+ def load_module(name: str, path: Path):
59
+ """Import a script by path, unchanged (the published builders are not packages)."""
60
+ if name in sys.modules:
61
+ return sys.modules[name]
62
+ spec = importlib.util.spec_from_file_location(name, path)
63
+ mod = importlib.util.module_from_spec(spec)
64
+ sys.modules[spec.name] = mod
65
+ spec.loader.exec_module(mod)
66
+ return mod
67
+
68
+
69
+ def realbulk():
70
+ """The published realbulk builder module (estimator + depth policies)."""
71
+ sys.path.insert(0, str(RB_DIR))
72
+ import build_realbulk_conditions as B # noqa: E402
73
+
74
+ return B
75
+
76
+
77
+ def behcet_builder():
78
+ return load_module("build_behcet_conditions", BEHCET_BUILDER)
79
+
80
+
81
+ def load_npz(path: Path) -> dict:
82
+ with np.load(path, allow_pickle=False) as z:
83
+ return {k: z[k] for k in z.files}
84
+
85
+
86
+ def canonical_panel():
87
+ import pandas as pd
88
+
89
+ bb = behcet_builder()
90
+ panel = pd.read_parquet(bb.DEFAULT_PANEL)
91
+ if len(panel) != 20_097:
92
+ raise SystemExit("canonical panel is not 20,097 genes")
93
+ return panel
94
+
95
+
96
+ def model_panel_ids(panel) -> np.ndarray:
97
+ """The 6,000 model genes of the final checkpoint (tier positions into the canonical axis)."""
98
+ pos = np.load(TIER_6K)
99
+ return panel["gene_id"].astype(str).to_numpy()[pos]
100
+
101
+
102
+ def reference() -> dict:
103
+ """Per-donor AIFI pseudobulks built by build_aifi_reference.py, with the sha recorded in its JSON."""
104
+ rec = json.loads(REF_JSON.read_text())
105
+ if sha256_file(REF_NPZ) != rec["output"]["sha256"]:
106
+ raise SystemExit(f"{REF_NPZ}: sha differs from {REF_JSON}")
107
+ d = load_npz(REF_NPZ)
108
+ d["record"] = rec
109
+ return d
110
+
111
+
112
+ def reference_mean_cpm(ref: dict, variant: str = "full") -> tuple[np.ndarray, np.ndarray]:
113
+ """Mean over donors of per-donor CPM on the canonical axis, and the atlas's measured-gene mask.
114
+
115
+ ``variant``: ``full`` (every atlas cell, natural composition; the primary reference), ``strata_reweighted``
116
+ (the 400K stratified reference, each cell weighted by n_available / n_selected of its AIFI_L2 x donor
117
+ stratum), ``strata_unweighted`` (the 400K stratified reference as sampled, rare types over-represented).
118
+ """
119
+ B = realbulk()
120
+ sums = np.asarray(ref[f"sums_{variant}"], dtype=np.float64)
121
+ present = np.asarray(ref["present"], dtype=bool)
122
+ if bool((sums[:, ~present] != 0).any()):
123
+ raise SystemExit("reference carries mass on genes absent from the atlas")
124
+ return B.cpm(sums).mean(axis=0), present
125
+
126
+
127
+ def refcal_alpha(bulk_anchor: np.ndarray, anchor_valid: np.ndarray, ref_mean: np.ndarray,
128
+ ref_present: np.ndarray) -> tuple[np.ndarray, dict]:
129
+ """The published estimator with the reference mean in place of the paired pseudobulk mean.
130
+
131
+ ``gene_multiplier(bulk, pseudo, valid)`` takes the mean of ``cpm(pseudo)`` over rows. The reference mean
132
+ CPM is passed as that many identical rows; each row already sums to 1e6, so ``cpm`` leaves it unchanged
133
+ and the row mean is exactly the reference mean. ``valid`` = measured in every anchor bulk and present in
134
+ the atlas; ``gene_multiplier`` then requires both means >= 1 CPM, else alpha = 1.
135
+ """
136
+ B = realbulk()
137
+ if bulk_anchor.ndim != 2 or bulk_anchor.shape[0] == 0:
138
+ raise SystemExit("anchor set is empty")
139
+ tiled = np.repeat(np.asarray(ref_mean, dtype=np.float64)[None, :], bulk_anchor.shape[0], axis=0)
140
+ valid = np.asarray(anchor_valid, dtype=bool).all(axis=0) & np.asarray(ref_present, dtype=bool)
141
+ alpha = B.gene_multiplier(np.asarray(bulk_anchor, dtype=np.float64), tiled, valid)
142
+ est = alpha != 1.0
143
+ q = np.quantile(alpha[est], [0.01, 0.05, 0.25, 0.5, 0.75, 0.95, 0.99]) if est.any() else [1.0] * 7
144
+ return alpha, {
145
+ "n_anchor": int(bulk_anchor.shape[0]),
146
+ "n_genes_valid_for_estimation": int(valid.sum()),
147
+ "n_genes_with_alpha_ne_1": int(est.sum()),
148
+ "alpha_quantiles_estimated_genes": dict(zip(["q01", "q05", "q25", "q50", "q75", "q95", "q99"],
149
+ [float(x) for x in q])),
150
+ "log2_alpha_sd_estimated_genes": float(np.std(np.log2(alpha[est]))) if est.any() else 0.0,
151
+ }
152
+
153
+
154
+ def alpha_agreement(a: np.ndarray, b: np.ndarray, subset: np.ndarray | None = None) -> dict:
155
+ """Agreement of two gene-wise multipliers on the genes where both were estimated (alpha != 1)."""
156
+ from scipy.stats import pearsonr, spearmanr
157
+
158
+ shared = (a != 1.0) & (b != 1.0)
159
+ if subset is not None:
160
+ shared &= subset
161
+ if shared.sum() < 3:
162
+ return {"n_shared": int(shared.sum())}
163
+ la, lb = np.log2(a[shared]), np.log2(b[shared])
164
+ return {"n_shared": int(shared.sum()),
165
+ "pearson_log2": float(pearsonr(la, lb)[0]),
166
+ "spearman": float(spearmanr(la, lb)[0]),
167
+ "median_log2_ratio_refcal_over_paired": float(np.median(la - lb)),
168
+ "mad_log2_ratio": float(np.median(np.abs(la - lb - np.median(la - lb))))}
paper-releases/20260928/diffusion/data/calibration/tools/refcal_refs/build_aida_reference.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Per-donor pseudobulks of the Asian Immune Diversity Atlas (AIDA) at NATURAL composition, canonical 20,097 axis.
3
+
4
+ Mirrors ``refcal/tools/build_aifi_reference.py`` (the AIFI reference of refcal):
5
+
6
+ * every atlas cell is read once from ``raw/X`` (integer UMI counts; the atlas ``X`` is normalised and never
7
+ touched) in row chunks and summed per donor;
8
+ * atlas genes are joined to the canonical panel on the unversioned Ensembl id; canonical genes absent from the
9
+ atlas carry 0 and are flagged unmeasured by ``present`` (the atlas's own measured-gene mask);
10
+ * the reference mean used by refcal is the mean over donors of per-donor CPM (``common_refs.reference_mean_cpm``).
11
+
12
+ Healthy donors only: every cell's ``disease`` must be ``normal`` (checked from obs; the run stops otherwise), and
13
+ each donor must carry exactly one sample (``sample_id``), so per-donor pooling never mixes samples.
14
+
15
+ Extra checks, all from source files:
16
+ * the canonical join is compared with the measurement masks of the AIDA shards of the model_8 training corpus
17
+ (the same h5ad, harmonised by the corpus builder), and for the first ``--corpus-check-cells`` cells of one
18
+ corpus shard the corpus counts are compared cell by cell with this join (``source_row_index``);
19
+ * which AIDA donors appear in the run's ordered_train_recipes.csv (AIDA is part of the training corpus).
20
+
21
+ CPU only; peak memory a few GB. Output: ``reference/aida_donor_pseudobulk_20097.{npz,json}``.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import glob
27
+ import json
28
+ import os
29
+ import sys
30
+ import time
31
+ from datetime import datetime, timezone
32
+ from pathlib import Path
33
+
34
+ os.environ.setdefault("CUDA_VISIBLE_DEVICES", "")
35
+ import h5py
36
+ import numpy as np
37
+ import pandas as pd
38
+ import scipy.sparse as sp
39
+
40
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
41
+ import common_refs as CR # noqa: E402
42
+
43
+ RC = CR.RC
44
+ SCHEMA = "pbisc_sdd.utility6k.refcal_refs.aida_donor_pseudobulk.v1"
45
+ DATASET_PREFIX = "006_A_collection_ced320a1" # the AIDA dataset id prefix in the training corpus (dir name of AIDA_H5AD)
46
+
47
+
48
+ def _decode(arr: np.ndarray) -> np.ndarray:
49
+ if arr.dtype.kind in ("S", "O"):
50
+ return np.asarray([x.decode() if isinstance(x, bytes) else str(x) for x in arr], dtype=object)
51
+ return arr
52
+
53
+
54
+ def read_col(group: h5py.Group, key: str) -> np.ndarray:
55
+ obj = group[key]
56
+ if isinstance(obj, h5py.Group) and obj.attrs.get("encoding-type") == "categorical":
57
+ cats = _decode(obj["categories"][:])
58
+ codes = obj["codes"][:]
59
+ if (codes < 0).any():
60
+ raise SystemExit(f"obs/{key} has missing values")
61
+ return cats[codes].astype(str)
62
+ return _decode(obj[:]).astype(str)
63
+
64
+
65
+ def corpus_shards() -> pd.DataFrame:
66
+ ss = pd.read_parquet(CR.E2_INDEX / "metadata/source_shards.parquet")
67
+ ds = CR.AIDA_H5AD.parent.name
68
+ if not ds.startswith(DATASET_PREFIX):
69
+ raise SystemExit("AIDA directory name changed")
70
+ return ss[ss["dataset_id"].astype(str) == ds].reset_index(drop=True)
71
+
72
+
73
+ def resolve_uri(uri: str) -> Path:
74
+ build = json.loads((CR.E2_SOURCE / "BUILD_COMPLETE.json").read_text())
75
+ for scheme, root in (("strict://", CR.E2_SOURCE), ("base://", Path(build["base_source_root"]))):
76
+ if uri.startswith(scheme):
77
+ return root / uri[len(scheme):]
78
+ raise SystemExit(f"unknown URI scheme {uri}")
79
+
80
+
81
+ def main(argv=None) -> int:
82
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
83
+ ap.add_argument("--chunk-rows", type=int, default=20000)
84
+ ap.add_argument("--max-rows", type=int, default=None, help="smoke test only (no output written)")
85
+ ap.add_argument("--corpus-check-cells", type=int, default=5000)
86
+ a = ap.parse_args(argv)
87
+ t0 = time.monotonic()
88
+ panel = RC.canonical_panel()
89
+ panel_ids = panel["gene_id"].astype(str).to_numpy()
90
+ out_npz, out_json = CR.REFERENCES["aida"]["npz"], CR.REFERENCES["aida"]["json"]
91
+
92
+ with h5py.File(CR.AIDA_H5AD, "r") as f:
93
+ obs = f["obs"]
94
+ barcodes = read_col(obs, obs.attrs.get("_index", "_index"))
95
+ donor = read_col(obs, "donor_id")
96
+ sample = read_col(obs, "sample_id")
97
+ disease = read_col(obs, "disease")
98
+ primary = read_col(obs, "is_primary_data")
99
+ l1 = read_col(obs, "Annotation_Level1")
100
+ l2 = read_col(obs, "Annotation_Level2")
101
+ country = read_col(obs, "Country")
102
+ ethnicity = read_col(obs, "self_reported_ethnicity")
103
+ sex = read_col(obs, "sex")
104
+ assay = read_col(obs, "assay")
105
+ atlas_genes = read_col(f["raw/var"], f["raw/var"].attrs.get("_index", "_index"))
106
+ var_genes = read_col(f["var"], f["var"].attrs.get("_index", "_index"))
107
+ filtered = f["var/feature_is_filtered"][:].astype(bool)
108
+ grp = f["raw/X"]
109
+ n_rows, n_cols = (int(x) for x in grp.attrs["shape"])
110
+ if n_rows != len(donor) or n_cols != len(atlas_genes):
111
+ raise SystemExit("raw/X shape disagrees with obs / raw/var")
112
+ if len(set(atlas_genes.tolist())) != len(atlas_genes):
113
+ raise SystemExit("atlas Ensembl ids are not unique")
114
+ if any("." in g for g in atlas_genes.tolist()):
115
+ raise SystemExit("atlas Ensembl ids carry version suffixes; strip them first")
116
+ if not np.array_equal(var_genes, atlas_genes):
117
+ raise SystemExit("var and raw/var gene order differ")
118
+ healthy = sorted(set(disease.tolist()))
119
+ if healthy != ["normal"]:
120
+ raise SystemExit(f"non-healthy cells present ({healthy}); restrict to disease == normal first")
121
+ if sorted(set(primary.tolist())) != ["True"]:
122
+ raise SystemExit("is_primary_data is not True for every cell")
123
+ col_of = {g: i for i, g in enumerate(atlas_genes.tolist())}
124
+ atlas_col = np.asarray([col_of.get(g, -1) for g in panel_ids], dtype=np.int64)
125
+ present = atlas_col >= 0
126
+ log_ = CR.log
127
+ log_(f"atlas {n_rows:,} cells x {n_cols:,} genes; canonical genes present {int(present.sum()):,}/20,097; "
128
+ f"assay {sorted(set(assay.tolist()))}")
129
+
130
+ donors = np.asarray(sorted(set(donor.tolist())))
131
+ d_index = {d: i for i, d in enumerate(donors.tolist())}
132
+ dcode = np.asarray([d_index[d] for d in donor.tolist()], dtype=np.int64)
133
+ per_donor_samples = pd.Series(sample).groupby(donor).nunique()
134
+ if int(per_donor_samples.max()) != 1:
135
+ raise SystemExit("a donor has more than one sample; per-donor pooling would mix samples")
136
+
137
+ n_d = len(donors)
138
+ acc = np.zeros((n_d, n_cols), dtype=np.float64)
139
+ indptr = grp["indptr"][:].astype(np.int64)
140
+ data_ds, idx_ds = grp["data"], grp["indices"]
141
+ stop_all = n_rows if a.max_rows is None else min(a.max_rows, n_rows)
142
+ n_nonint = 0
143
+ n_neg = 0
144
+ for start in range(0, stop_all, a.chunk_rows):
145
+ stop = min(start + a.chunk_rows, stop_all)
146
+ lo, hi = int(indptr[start]), int(indptr[stop])
147
+ data = np.asarray(data_ds[lo:hi], dtype=np.float64)
148
+ idx = np.asarray(idx_ds[lo:hi], dtype=np.int64)
149
+ n_nonint += int((data != np.rint(data)).sum())
150
+ n_neg += int((data < 0).sum())
151
+ m = sp.csr_matrix((data, idx, indptr[start:stop + 1] - lo), shape=(stop - start, n_cols))
152
+ ind = sp.csr_matrix((np.ones(stop - start), (dcode[start:stop], np.arange(stop - start))),
153
+ shape=(n_d, stop - start))
154
+ acc += (ind @ m).toarray()
155
+ if (start // a.chunk_rows) % 10 == 0 or stop == stop_all:
156
+ log_(f"[stream] rows {stop:,}/{stop_all:,} elapsed {(time.monotonic() - t0) / 60:.1f} min")
157
+ if n_nonint or n_neg:
158
+ raise SystemExit(f"raw/X carries {n_nonint} non-integer and {n_neg} negative values")
159
+
160
+ # cell-by-cell comparison with the training corpus harmonisation of the same h5ad (one shard's first cells)
161
+ shards = corpus_shards()
162
+ corpus_masks = {}
163
+ import zarr
164
+ for _, r in shards.iterrows():
165
+ g = zarr.open_group(str(resolve_uri(str(r["count_zarr"]))), mode="r")
166
+ corpus_masks[str(r["shard_id"])] = np.asarray(g["measurement_mask"][:], dtype=bool)
167
+ r0 = shards.iloc[0]
168
+ g0 = zarr.open_group(str(resolve_uri(str(r0["count_zarr"]))), mode="r")
169
+ obs_part = resolve_uri(str(r0["obs_part"]))
170
+ obs_files = sorted(glob.glob(str(obs_part))) if not obs_part.exists() else [str(obs_part)]
171
+ cobs = pd.read_parquet(obs_files[0], columns=["row_index", "source_row_index", "donor_id"])
172
+ ncheck = min(a.corpus_check_cells, len(cobs))
173
+ cip = np.asarray(g0["indptr"][: ncheck + 1], dtype=np.int64)
174
+ cm = sp.csr_matrix((np.asarray(g0["data"][cip[0]:cip[-1]], dtype=np.float64),
175
+ np.asarray(g0["indices"][cip[0]:cip[-1]], dtype=np.int64), cip - cip[0]),
176
+ shape=(ncheck, len(panel_ids)))
177
+ src_rows = cobs["source_row_index"].to_numpy(dtype=np.int64)[:ncheck]
178
+ if not np.array_equal(cobs["row_index"].to_numpy()[:ncheck], np.arange(ncheck)):
179
+ raise SystemExit("corpus obs rows are not in shard row order")
180
+ order = np.argsort(src_rows)
181
+ mine = np.zeros((ncheck, len(panel_ids)), dtype=np.float64)
182
+ for j in order:
183
+ s0 = int(src_rows[j])
184
+ lo, hi = int(indptr[s0]), int(indptr[s0 + 1])
185
+ row = np.zeros(n_cols)
186
+ row[np.asarray(idx_ds[lo:hi], dtype=np.int64)] = np.asarray(data_ds[lo:hi], dtype=np.float64)
187
+ mine[j, present] = row[atlas_col[present]]
188
+ cmask = corpus_masks[str(r0["shard_id"])]
189
+ both = present & cmask
190
+ corpus_check = {
191
+ "shard_id": str(r0["shard_id"]), "cells_compared": int(ncheck),
192
+ "donor_ids_equal": bool(np.array_equal(cobs["donor_id"].astype(str).to_numpy()[:ncheck],
193
+ donor[src_rows])),
194
+ "counts_equal_on_genes_measured_by_both": bool(np.array_equal(cm.toarray()[:, both], mine[:, both])),
195
+ "corpus_mass_on_genes_outside_this_join": float(cm.toarray()[:, ~present].sum()),
196
+ "join_mass_on_genes_unmeasured_in_corpus": float(mine[:, present & ~cmask].sum()),
197
+ }
198
+ log_(f"corpus cell check: {corpus_check}")
199
+
200
+ if a.max_rows is not None:
201
+ log_("smoke run finished; nothing written")
202
+ return 0
203
+
204
+ out = np.zeros((n_d, len(panel_ids)), dtype=np.float64)
205
+ out[:, present] = acc[:, atlas_col[present]]
206
+ lost = float(1.0 - out.sum() / acc.sum())
207
+ n_cells = np.bincount(dcode, minlength=n_d).astype(np.int64)
208
+ l1_cats = np.asarray(sorted(set(l1.tolist())))
209
+ l1_counts = np.stack([np.bincount(dcode[l1 == c], minlength=n_d) for c in l1_cats], axis=1).astype(np.int64)
210
+ l2_cats = np.asarray(sorted(set(l2.tolist())))
211
+ l2_counts = np.stack([np.bincount(dcode[l2 == c], minlength=n_d) for c in l2_cats], axis=1).astype(np.int64)
212
+ first = pd.DataFrame({"donor": donor, "country": country, "ethnicity": ethnicity, "sex": sex}).drop_duplicates("donor")
213
+ first = first.set_index("donor").loc[donors]
214
+ # canonical present genes that CELLxGENE flags feature_is_filtered (kept in raw, dropped from X)
215
+ filt_canon = np.zeros(len(panel_ids), dtype=bool)
216
+ filt_canon[present] = filtered[atlas_col[present]]
217
+ corpus_union = np.any(np.stack(list(corpus_masks.values())), axis=0)
218
+ corpus_inter = np.all(np.stack(list(corpus_masks.values())), axis=0)
219
+
220
+ out_npz.parent.mkdir(parents=True, exist_ok=True)
221
+ np.savez_compressed(
222
+ out_npz,
223
+ schema_version=np.asarray(SCHEMA),
224
+ gene_ids=panel_ids.astype(np.str_),
225
+ present=present,
226
+ donor_ids=donors.astype(np.str_),
227
+ n_cells=n_cells,
228
+ sums_full=out,
229
+ l1_categories=l1_cats.astype(np.str_),
230
+ l1_counts=l1_counts,
231
+ l2_categories=l2_cats.astype(np.str_),
232
+ l2_counts=l2_counts,
233
+ donor_country=first["country"].to_numpy().astype(np.str_),
234
+ donor_ethnicity=first["ethnicity"].to_numpy().astype(np.str_),
235
+ donor_sex=first["sex"].to_numpy().astype(np.str_),
236
+ )
237
+ B = RC.realbulk()
238
+ mono = l2_counts[:, list(l2_cats).index("Monocyte")] / n_cells
239
+ rec = pd.read_csv(RC.TRAIN_RECIPES, usecols=["dataset_id", "donor_id", "sample_id", "split"])
240
+ in_train = rec[rec["dataset_id"].astype(str) == CR.AIDA_H5AD.parent.name]
241
+ si = pd.read_parquet(CR.E2_INDEX / "metadata/sample_index.parquet")
242
+ si_aida = si[si["dataset_id"].astype(str) == CR.AIDA_H5AD.parent.name]
243
+ rec_json = {
244
+ "schema_version": SCHEMA,
245
+ "written_utc": datetime.now(timezone.utc).isoformat(),
246
+ "tool": {"path": str(Path(__file__).resolve()), "sha256": CR.sha256_file(Path(__file__).resolve())},
247
+ "inputs": {str(p): CR.sha256_file(p) for p in (CR.AIDA_H5AD, RC.behcet_builder().DEFAULT_PANEL,
248
+ RC.TRAIN_RECIPES,
249
+ CR.E2_INDEX / "metadata/source_shards.parquet",
250
+ CR.E2_INDEX / "metadata/sample_index.parquet")},
251
+ "counts_source": "atlas raw/X (integer UMI counts), every cell; atlas X (normalised) unused",
252
+ "assay": sorted(set(assay.tolist())),
253
+ "healthy_filter": "every cell has disease == normal (checked; no cell removed); one sample per donor (checked)",
254
+ "gene_join": "unversioned Ensembl id of raw/var, canonical order (mirror of build_aifi_reference.py)",
255
+ "n_cells": int(n_rows), "n_donors": int(n_d), "n_atlas_genes": int(n_cols),
256
+ "n_canonical_present": int(present.sum()),
257
+ "canonical_present_but_feature_is_filtered": int(filt_canon.sum()),
258
+ "canonical_present_but_feature_is_filtered_umi_fraction": float(out[:, filt_canon].sum() / out.sum()),
259
+ "fraction_of_umis_on_atlas_genes_outside_canonical": lost,
260
+ "training_corpus_harmonisation": {
261
+ "aida_corpus_shards": int(len(shards)),
262
+ "corpus_measured_genes_union": int(corpus_union.sum()),
263
+ "corpus_measured_genes_intersection": int(corpus_inter.sum()),
264
+ "join_present_not_in_corpus_union": int((present & ~corpus_union).sum()),
265
+ "corpus_union_not_in_join": int((corpus_union & ~present).sum()),
266
+ "cell_check": corpus_check,
267
+ },
268
+ "cells_per_donor": {"min": int(n_cells.min()), "median": float(np.median(n_cells)), "max": int(n_cells.max())},
269
+ "natural_l1_composition_pooled": {c: float(l1_counts[:, i].sum() / n_cells.sum()) for i, c in enumerate(l1_cats)},
270
+ "natural_l2_composition_pooled": {c: float(l2_counts[:, i].sum() / n_cells.sum()) for i, c in enumerate(l2_cats)},
271
+ "monocyte_fraction_per_donor": {"label": "Annotation_Level2 == Monocyte",
272
+ "natural_median": float(np.median(mono)),
273
+ "natural_q25_q75": [float(np.percentile(mono, 25)), float(np.percentile(mono, 75))]},
274
+ "donors_by_country": first["country"].value_counts().to_dict(),
275
+ "donors_by_ethnicity": first["ethnicity"].value_counts().to_dict(),
276
+ "donors_by_sex": first["sex"].value_counts().to_dict(),
277
+ "training_corpus": {
278
+ "file": str(RC.TRAIN_RECIPES),
279
+ "aida_recipes": int(len(in_train)), "all_recipes": int(len(rec)),
280
+ "aida_donors_in_recipes": int(in_train["donor_id"].nunique()),
281
+ "reference_donors_in_recipes": int(np.isin(donors, in_train["donor_id"].astype(str).unique()).sum()),
282
+ "aida_samples_by_split_in_corpus": si_aida["split"].value_counts().to_dict(),
283
+ "note": "AIDA is part of the model_8 training corpus (like AIFI); every AIDA donor is used here",
284
+ },
285
+ "output": {"path": str(out_npz), "sha256": CR.sha256_file(out_npz), "bytes": out_npz.stat().st_size},
286
+ "elapsed_s": round(time.monotonic() - t0, 1),
287
+ }
288
+ mean_cp = B.cpm(out).mean(0)
289
+ rec_json["reference_mean_cpm_sum"] = float(mean_cp.sum())
290
+ out_json.write_text(json.dumps(rec_json, indent=1, default=str) + "\n")
291
+ log_(f"written {out_npz} ({out_npz.stat().st_size / 1e6:.1f} MB)")
292
+ return 0
293
+
294
+
295
+ if __name__ == "__main__":
296
+ sys.exit(main())
paper-releases/20260928/diffusion/data/calibration/tools/refcal_refs/build_train_reference.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Training-distribution reference for refcal: the average pseudobulk of the cells the final model was trained on.
3
+
4
+ Why not the sufficient-statistics store. ``artifacts/panel_ladder_floor01_1m_20260923/sufficient_statistics``
5
+ holds ``value_sum`` = the sum over 1,048,576 sampled training cells of log1p(counts / cell total * 1e4)
6
+ (``pbisc_sdd.panel_ladder.collect_train_panel_statistics``; ``binding.json``: target_sum 1e4). That is a mean of
7
+ log-normalised values, not a mean of counts, so it cannot give a mean CPM. The reference is therefore built
8
+ from per-sample pseudobulks of raw counts.
9
+
10
+ What is summed. The run trains on the model_7 E2 corpus (``effective_config.json`` -> model7_root; index
11
+ ``data/e2_full_index``, counts in the corpus Zarr shards, canonical 20,097 axis, raw UMI counts). A training
12
+ recipe draws K cells without replacement from one sample's train pool (``E2FullDataModule._recipe_refs_and_pools``)
13
+ and conditions on their summed counts, so a recipe's expected condition is proportional to the sample's pool
14
+ sum. For every train sample the builder sums ALL cells of its train pool (``sample_pools.parquet``): no cell
15
+ cap is needed (33.1 M cells, streamed shard by shard).
16
+
17
+ Reference mean (``common_refs.reference_mean_cpm('train')``):
18
+ CPM_s = the sample's pool sum over the genes its shards measured (``measurement_mask``), scaled to 1e6
19
+ mean_g = sum_s w_s m_sg CPM_sg / sum_s w_s m_sg over samples s that measured gene g (m_sg = 1)
20
+ present = measured by at least one weighted sample; mean renormalised to 1e6 over present genes
21
+ With w_s = 1 for one donor per sample this is exactly the AIFI/AIDA rule (mean over units of per-unit CPM); a
22
+ gene a dataset did not measure is left out of that dataset's contribution instead of entering as zero, which
23
+ is how the model saw it (the loss and the condition carry the measurement mask).
24
+
25
+ Weightings (``variant_names``):
26
+ recipes_epoch1 primary; w_s = number of recipes of sample s in ordered_train_recipes.csv (8,192 recipes
27
+ = train slot 0 = the run's first epoch, checked against EPOCH_SCHEDULE.json)
28
+ recipes_all_epochs w_s = recipes of s over all 16 epochs of EPOCH_SCHEDULE.json (slots + all-cell top-ups)
29
+ cells_all_epochs w_s = sum of K over those recipes (target-cell exposure: every target cell of a recipe is
30
+ trained against that recipe's condition)
31
+ samples_equal w_s = 1 for every train sample (the corpus by sample, ignoring the schedule)
32
+
33
+ Also checked and recorded: the four evaluation cohorts' GEO accessions (read from their provenance files) do not
34
+ occur anywhere in the training corpus manifest, dataset ids or shard paths.
35
+
36
+ CPU only (multiprocessing over shards; peak memory a few GB). Output: ``reference/train_distribution_reference_20097.{npz,json}``.
37
+ """
38
+ from __future__ import annotations
39
+
40
+ import argparse
41
+ import json
42
+ import multiprocessing as mp
43
+ import os
44
+ import re
45
+ import sys
46
+ import time
47
+ from datetime import datetime, timezone
48
+ from pathlib import Path
49
+
50
+ os.environ.setdefault("CUDA_VISIBLE_DEVICES", "")
51
+ import numpy as np
52
+ import pandas as pd
53
+ import pyarrow.parquet as pq
54
+ import scipy.sparse as sp
55
+
56
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
57
+ import common_refs as CR # noqa: E402
58
+
59
+ RC = CR.RC
60
+ SCHEMA = "pbisc_sdd.utility6k.refcal_refs.train_distribution_reference.v1"
61
+ VARIANTS = ("recipes_epoch1", "recipes_all_epochs", "cells_all_epochs", "samples_equal")
62
+ TOPUP_DIR = CR.M8 / "plans/full_recipe_allcells_6k_broad_20260909/topup_v1"
63
+ N_GENES = 20097
64
+ BASE_OBS_DIR = Path(json.loads((CR.E2_SOURCE / "BUILD_COMPLETE.json").read_text())["base_source_root"]) / "metadata/obs_sc.parquet"
65
+
66
+
67
+ def resolve_uri(uri: str) -> Path:
68
+ build = json.loads((CR.E2_SOURCE / "BUILD_COMPLETE.json").read_text())
69
+ for scheme, root in (("strict://", CR.E2_SOURCE), ("base://", Path(build["base_source_root"]))):
70
+ if uri.startswith(scheme):
71
+ return root / uri[len(scheme):]
72
+ raise SystemExit(f"unknown URI scheme {uri}")
73
+
74
+
75
+ # ------------------------------------------------------------------------------------------ schedule and weights
76
+ def schedule() -> dict:
77
+ """Recipe tables of the run and per-sample recipe counts; every link is checked."""
78
+ cfg = json.loads((CR.RUN_DIR / "effective_config.json").read_text())
79
+ if Path(cfg["paths"]["model7_root"]).resolve() != CR.MODEL7.resolve():
80
+ raise SystemExit("run model7_root differs from the E2 corpus used here")
81
+ man = json.loads((CR.PANEL_ARTIFACT / "manifest.json").read_text())
82
+ if CR.sha256_file(RC.TRAIN_RECIPES) != man["provenance"]["ordered_train_recipes_sha256"]:
83
+ raise SystemExit("ordered_train_recipes.csv sha differs from the panel-ladder manifest")
84
+ rec1 = pd.read_csv(RC.TRAIN_RECIPES)
85
+ if int(cfg["data"]["train_recipes"]) != len(rec1):
86
+ raise SystemExit("ordered_train_recipes.csv length differs from the run's train_recipes")
87
+ slot_files = sorted((CR.E2_INDEX / "recipes").glob("train-slot-*.parquet"))
88
+ slots = pd.concat([pd.read_parquet(p) for p in slot_files], ignore_index=True)
89
+ topup = pd.read_csv(TOPUP_DIR / "topup_recipes.csv")
90
+ tman = json.loads((TOPUP_DIR / "manifest.json").read_text())
91
+ if CR.sha256_file(TOPUP_DIR / "topup_recipes.csv") != tman["recipes_sha256"]:
92
+ raise SystemExit("topup_recipes.csv sha differs from its manifest")
93
+ table = pd.concat([slots[["recipe_id", "sample_key", "dataset_id", "k", "split"]],
94
+ topup[["recipe_id", "sample_key", "dataset_id", "k", "split"]]], ignore_index=True)
95
+ if table["recipe_id"].duplicated().any():
96
+ raise SystemExit("duplicate recipe ids across slots and top-ups")
97
+ if set(table["split"].astype(str)) != {"train"}:
98
+ raise SystemExit("a scheduled recipe is not in the train split")
99
+ by_id = table.set_index("recipe_id")
100
+ slot0 = set(pd.read_parquet(slot_files[0])["recipe_id"].astype(str))
101
+ ep = json.loads((CR.RUN_DIR / "EPOCH_SCHEDULE.json").read_text())
102
+ ep_ids = [list(map(str, e["recipe_ids"])) for e in ep]
103
+ all_ids = [r for e in ep_ids for r in e]
104
+ missing = sorted(set(all_ids) - set(by_id.index))
105
+ if missing:
106
+ raise SystemExit(f"{len(missing)} scheduled recipe ids are not in the slot / top-up tables")
107
+ r1 = rec1.set_index("recipe_id")
108
+ joined = by_id.loc[r1.index]
109
+ for col in ("sample_key", "dataset_id", "k"):
110
+ if not np.array_equal(joined[col].astype(str).to_numpy(), r1[col].astype(str).to_numpy()):
111
+ raise SystemExit(f"ordered_train_recipes.csv {col} differs from the slot tables")
112
+ sched = by_id.loc[all_ids]
113
+ chk = {
114
+ "ordered_train_recipes_equal_train_slot_000": set(r1.index.astype(str)) == slot0,
115
+ "ordered_train_recipes_in_epoch1_schedule": float(np.isin(r1.index.astype(str), ep_ids[0]).mean()),
116
+ "epoch1_first_ids_equal_ordered_order": bool(ep_ids[0][:len(rec1)] == r1.index.astype(str).tolist()),
117
+ "epochs": len(ep_ids), "scheduled_recipes_all_epochs": len(all_ids),
118
+ "distinct_scheduled_recipes": len(set(all_ids)),
119
+ "slot_recipes": int(len(slots)), "topup_recipes": int(len(topup)),
120
+ "scheduled_target_cells_all_epochs": int(sched["k"].sum()),
121
+ }
122
+ w = {
123
+ "recipes_epoch1": rec1["sample_key"].astype(str).value_counts(),
124
+ "recipes_all_epochs": sched["sample_key"].astype(str).value_counts(),
125
+ "cells_all_epochs": sched.groupby(sched["sample_key"].astype(str))["k"].sum().astype(float),
126
+ }
127
+ return {"weights": w, "check": chk, "rec1": rec1, "sched": sched,
128
+ "files": [RC.TRAIN_RECIPES, CR.PANEL_ARTIFACT / "manifest.json", CR.RUN_DIR / "effective_config.json",
129
+ CR.RUN_DIR / "EPOCH_SCHEDULE.json", TOPUP_DIR / "topup_recipes.csv", TOPUP_DIR / "manifest.json",
130
+ *slot_files]}
131
+
132
+
133
+ # ------------------------------------------------------------------------------------------ evaluation cohorts
134
+ def evaluation_exclusion() -> dict:
135
+ """GEO accessions of the four evaluation cohorts, read from their provenance files, vs the training corpus."""
136
+ B = RC.realbulk()
137
+ prov = {
138
+ "ImMicro": [B.SOURCES["ImMicro"].with_suffix(".json")],
139
+ "Randolph": [B.SOURCES["Randolph"].parent / "FEATURES_PROVENANCE.json"],
140
+ "Arunachalam": [RC.AR_MANIFEST],
141
+ "Behcet": [RC.BEHCET_MANIFEST, RC.CONDMORE / "MANIFEST.json"],
142
+ }
143
+ acc = {}
144
+ for c, files in prov.items():
145
+ ids = set()
146
+ for p in files:
147
+ ids |= set(re.findall(r"GSE\d+", Path(p).read_text()))
148
+ acc[c] = sorted(ids)
149
+ corpus_text = (CR.E2_SOURCE / "dataset_manifest.json").read_text()
150
+ si = pd.read_parquet(CR.E2_INDEX / "metadata/sample_index.parquet")
151
+ ss = pd.read_parquet(CR.E2_INDEX / "metadata/source_shards.parquet")
152
+ corpus_ids = sorted(set(si["dataset_id"].astype(str)) | set(ss["dataset_id"].astype(str)))
153
+ corpus_paths = " ".join(ss["count_zarr"].astype(str).tolist() + ss["obs_part"].astype(str).tolist())
154
+ corpus_acc = sorted(set(re.findall(r"GSE\d+", corpus_text + " ".join(corpus_ids) + corpus_paths)))
155
+ hits = {c: sorted(set(ids) & set(corpus_acc)) for c, ids in acc.items()}
156
+ # the paired datalake that holds ImMicro/Randolph must not be a corpus source path either
157
+ datalake_root = str(B.DATALAKE.parent)
158
+ return {"evaluation_accessions": acc, "provenance_files": {c: [str(p) for p in f] for c, f in prov.items()},
159
+ "training_corpus_dataset_ids": corpus_ids, "training_corpus_accessions": corpus_acc,
160
+ "hits": hits, "paired_datalake_in_corpus_manifest": datalake_root in corpus_text,
161
+ "none_in_training_corpus": not any(hits.values()) and datalake_root not in corpus_text}
162
+
163
+
164
+ # ------------------------------------------------------------------------------------------ per-shard worker
165
+ def _process_shard(job):
166
+ import zarr
167
+ shard_id, zpath, opath, codes, row_lists, chunk_rows = job
168
+ g = zarr.open_group(str(zpath), mode="r")
169
+ shape = g.attrs.get("shape")
170
+ ip = np.asarray(g["indptr"][:], dtype=np.int64)
171
+ n = len(ip) - 1
172
+ mask = np.asarray(g["measurement_mask"][:], dtype=np.uint8)
173
+ if mask.shape != (N_GENES,) or not np.isin(mask, (0, 1)).all():
174
+ raise RuntimeError(f"{shard_id}: bad measurement_mask")
175
+ rowmap = np.full(n, -1, dtype=np.int64)
176
+ for j, rows in enumerate(row_lists):
177
+ rows = np.asarray(rows, dtype=np.int64)
178
+ if rows.size and (rows.min() < 0 or rows.max() >= n):
179
+ raise RuntimeError(f"{shard_id}: pool rows out of range")
180
+ if (rowmap[rows] >= 0).any():
181
+ raise RuntimeError(f"{shard_id}: a row belongs to two train pools")
182
+ rowmap[rows] = j
183
+ n_local = len(codes)
184
+ acc = np.zeros((n_local, N_GENES), dtype=np.float64)
185
+ nonint = neg = 0
186
+ used = np.flatnonzero(rowmap >= 0)
187
+ for start in range(0, n, chunk_rows):
188
+ stop = min(start + chunk_rows, n)
189
+ rm = rowmap[start:stop]
190
+ if not (rm >= 0).any():
191
+ continue
192
+ lo, hi = int(ip[start]), int(ip[stop])
193
+ data = np.asarray(g["data"][lo:hi], dtype=np.float64)
194
+ idx = np.asarray(g["indices"][lo:hi], dtype=np.int64)
195
+ nonint += int((data != np.rint(data)).sum())
196
+ neg += int((data < 0).sum())
197
+ m = sp.csr_matrix((data, idx, ip[start:stop + 1] - lo), shape=(stop - start, N_GENES))
198
+ keep = np.flatnonzero(rm >= 0)
199
+ ind = sp.csr_matrix((np.ones(keep.size), (rm[keep], keep)), shape=(n_local, stop - start))
200
+ acc += (ind @ m).toarray()
201
+ # cell-type composition, reporting only. The E2 obs is annotation-free; the base corpus obs of the same shard
202
+ # carries the corpus builder's mapped source labels (weak labels). Rows are matched on source_row_index.
203
+ obs = pd.read_parquet(opath, columns=["row_index", "source_row_index"])
204
+ if len(obs) != n or not np.array_equal(obs["row_index"].to_numpy(), np.arange(n)):
205
+ raise RuntimeError(f"{shard_id}: obs rows are not the shard rows in order")
206
+ lab = np.full(n, "unlabelled", dtype=object)
207
+ base_obs = BASE_OBS_DIR / f"{shard_id}.parquet"
208
+ if base_obs.is_file():
209
+ bo = pd.read_parquet(base_obs, columns=["row_index", "source_row_index", "celltype_l1"])
210
+ if len(bo) == n and np.array_equal(bo["source_row_index"].to_numpy(), obs["source_row_index"].to_numpy()):
211
+ lab = bo["celltype_l1"].astype(str).to_numpy()
212
+ l1 = lab[used].astype(str)
213
+ l1_counts = pd.crosstab(rowmap[used], l1)
214
+ return {"shard_id": shard_id, "codes": codes, "acc": acc, "mask": mask, "nonint": nonint, "neg": neg,
215
+ "rows": np.bincount(rowmap[used], minlength=n_local), "l1": l1_counts, "n_rows": n,
216
+ "shape_attr": None if shape is None else list(shape)}
217
+
218
+
219
+ def main(argv=None) -> int:
220
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
221
+ ap.add_argument("--workers", type=int, default=5)
222
+ ap.add_argument("--chunk-rows", type=int, default=20000)
223
+ ap.add_argument("--max-shards", type=int, default=None, help="smoke test only (no output written)")
224
+ a = ap.parse_args(argv)
225
+ t0 = time.monotonic()
226
+ log = CR.log
227
+ out_npz, out_json = CR.REFERENCES["train"]["npz"], CR.REFERENCES["train"]["json"]
228
+ panel = RC.canonical_panel()
229
+ panel_ids = panel["gene_id"].astype(str).to_numpy()
230
+ var = pd.read_parquet(CR.E2_SOURCE / "metadata/var.parquet")
231
+ if not np.array_equal(var["gene_id"].astype(str).to_numpy(), panel_ids):
232
+ raise SystemExit("E2 corpus gene axis is not the canonical panel")
233
+
234
+ S = schedule()
235
+ log(f"schedule: {S['check']}")
236
+ excl = evaluation_exclusion()
237
+ log(f"evaluation cohorts in training corpus: hits {excl['hits']}; none={excl['none_in_training_corpus']}")
238
+ if not excl["none_in_training_corpus"]:
239
+ raise SystemExit("an evaluation cohort accession occurs in the training corpus")
240
+
241
+ si = pd.read_parquet(CR.E2_INDEX / "metadata/sample_index.parquet")
242
+ train = si[si["split"].astype(str) == "train"].sort_values("sample_key").reset_index(drop=True)
243
+ keys = train["sample_key"].astype(str).to_numpy()
244
+ code_of = {k: i for i, k in enumerate(keys)}
245
+ for v, w in S["weights"].items():
246
+ extra = set(w.index) - set(keys)
247
+ if extra:
248
+ raise SystemExit(f"{v}: {len(extra)} weighted samples are not train samples")
249
+ pools = pq.read_table(CR.E2_INDEX / "metadata/sample_pools.parquet").to_pandas()
250
+ pools = pools[pools["sample_key"].astype(str).isin(code_of)]
251
+ ss = pd.read_parquet(CR.E2_INDEX / "metadata/source_shards.parquet").set_index("shard_id")
252
+ jobs = []
253
+ for shard_id, grp in pools.groupby("shard_id", sort=False):
254
+ r = ss.loc[shard_id]
255
+ codes = np.asarray([code_of[k] for k in grp["sample_key"].astype(str)], dtype=np.int64)
256
+ if len(set(codes.tolist())) != len(codes):
257
+ raise SystemExit(f"{shard_id}: a sample has two pool rows in one shard")
258
+ jobs.append((str(shard_id), resolve_uri(str(r["count_zarr"])), resolve_uri(str(r["obs_part"])), codes,
259
+ [np.asarray(x, dtype=np.int64) for x in grp["row_indices"]], a.chunk_rows))
260
+ jobs.sort(key=lambda j: -int(ss.loc[j[0], "n_cells"]))
261
+ if a.max_shards is not None:
262
+ jobs = jobs[-a.max_shards:]
263
+ log(f"train samples {len(keys):,}; pool cells {int(train['n_cells'].sum()):,}; shards {len(jobs)}")
264
+
265
+ n_s = len(keys)
266
+ sums = np.zeros((n_s, N_GENES), dtype=np.float64)
267
+ m_and = np.ones((n_s, N_GENES), dtype=bool)
268
+ m_or = np.zeros((n_s, N_GENES), dtype=bool)
269
+ rows = np.zeros(n_s, dtype=np.int64)
270
+ l1_frames = []
271
+ nonint = neg = 0
272
+ done = 0
273
+ with mp.get_context("fork").Pool(a.workers) as pool:
274
+ for res in pool.imap_unordered(_process_shard, jobs):
275
+ c = res["codes"]
276
+ sums[c] += res["acc"]
277
+ mk = res["mask"].astype(bool)
278
+ m_and[c] &= mk[None, :]
279
+ m_or[c] |= mk[None, :]
280
+ rows[c] += res["rows"]
281
+ nonint += res["nonint"]
282
+ neg += res["neg"]
283
+ l1 = res["l1"]
284
+ l1.index = c[l1.index.to_numpy()]
285
+ l1_frames.append(l1)
286
+ done += 1
287
+ if done % 20 == 0 or done == len(jobs):
288
+ log(f"[shards] {done}/{len(jobs)} elapsed {(time.monotonic() - t0) / 60:.1f} min")
289
+ if nonint or neg:
290
+ raise SystemExit(f"corpus counts carry {nonint} non-integer and {neg} negative values")
291
+ if a.max_shards is not None:
292
+ log("smoke run finished; nothing written")
293
+ return 0
294
+ if not np.array_equal(rows, train["n_cells"].to_numpy(dtype=np.int64)):
295
+ raise SystemExit("summed pool rows differ from sample_index n_cells")
296
+ mixed = (m_and != m_or).any(axis=1)
297
+ # unmeasured-in-any-shard coordinates are dropped from that sample (m_and), which is also its CPM support
298
+ leaked = float(sums[~m_and].sum())
299
+ sums_m = np.where(m_and, sums, 0.0)
300
+ tot = sums_m.sum(axis=1)
301
+ if (tot <= 0).any():
302
+ raise SystemExit("a train sample has zero counts over its measured genes")
303
+ cpm = sums_m / tot[:, None] * 1e6
304
+
305
+ weights = {}
306
+ for v in VARIANTS:
307
+ if v == "samples_equal":
308
+ weights[v] = np.ones(n_s, dtype=np.float64)
309
+ else:
310
+ weights[v] = S["weights"][v].reindex(keys).fillna(0.0).to_numpy(dtype=np.float64)
311
+ mean_cpm = np.zeros((len(VARIANTS), N_GENES))
312
+ present = np.zeros((len(VARIANTS), N_GENES), dtype=bool)
313
+ coverage = np.zeros((len(VARIANTS), N_GENES), dtype=np.float32)
314
+ for i, v in enumerate(VARIANTS):
315
+ w = weights[v]
316
+ num = w @ (cpm * m_and)
317
+ den = w @ m_and.astype(np.float64)
318
+ pres = den > 0
319
+ mu = np.zeros(N_GENES)
320
+ mu[pres] = num[pres] / den[pres]
321
+ mean_cpm[i] = mu / mu.sum() * 1e6
322
+ present[i] = pres
323
+ coverage[i] = den / w.sum()
324
+
325
+ ds_all = train["dataset_id"].astype(str).to_numpy()
326
+ datasets = np.asarray(sorted(set(ds_all.tolist())))
327
+ w1 = weights["recipes_epoch1"]
328
+ ds_mean = np.zeros((len(datasets), N_GENES))
329
+ ds_measured = np.zeros((len(datasets), N_GENES), dtype=bool)
330
+ ds_share = np.zeros((len(VARIANTS), len(datasets)))
331
+ for j, d in enumerate(datasets):
332
+ sel = ds_all == d
333
+ ww = w1[sel] if w1[sel].sum() > 0 else np.ones(int(sel.sum()))
334
+ num = ww @ (cpm[sel] * m_and[sel])
335
+ den = ww @ m_and[sel].astype(np.float64)
336
+ ok = den > 0
337
+ ds_mean[j, ok] = num[ok] / den[ok]
338
+ ds_mean[j] = ds_mean[j] / ds_mean[j].sum() * 1e6
339
+ ds_measured[j] = m_and[sel].any(axis=0)
340
+ for i, v in enumerate(VARIANTS):
341
+ ds_share[i, j] = weights[v][sel].sum() / weights[v].sum()
342
+
343
+ l1 = pd.concat(l1_frames).groupby(level=0).sum().reindex(range(n_s)).fillna(0).astype(np.int64)
344
+ l1_cats = np.asarray(sorted(l1.columns.astype(str)))
345
+ l1 = l1[l1_cats]
346
+ l1_frac = l1.to_numpy() / l1.to_numpy().sum(axis=1, keepdims=True)
347
+
348
+ out_npz.parent.mkdir(parents=True, exist_ok=True)
349
+ np.savez_compressed(
350
+ out_npz,
351
+ schema_version=np.asarray(SCHEMA),
352
+ gene_ids=panel_ids.astype(np.str_),
353
+ variant_names=np.asarray(VARIANTS).astype(np.str_),
354
+ primary_variant=np.asarray(CR.TRAIN_PRIMARY_VARIANT),
355
+ mean_cpm=mean_cpm,
356
+ present=present,
357
+ measured_weight_fraction=coverage,
358
+ sample_keys=keys.astype(np.str_),
359
+ sample_dataset_ids=ds_all.astype(np.str_),
360
+ sample_n_cells=rows,
361
+ sample_total_umis_measured=tot,
362
+ sample_weights=np.stack([weights[v] for v in VARIANTS]),
363
+ sample_measured_genes=m_and.sum(axis=1).astype(np.int64),
364
+ sample_mask_mixed_across_shards=mixed,
365
+ dataset_ids=datasets.astype(np.str_),
366
+ dataset_mean_cpm=ds_mean,
367
+ dataset_measured_any=ds_measured,
368
+ dataset_weight_share=ds_share,
369
+ l1_categories=l1_cats.astype(np.str_),
370
+ sample_l1_counts=l1.to_numpy(),
371
+ )
372
+ lg = {v: np.log1p(mean_cpm[i]) for i, v in enumerate(VARIANTS)}
373
+ both = present.all(axis=0)
374
+ model = np.zeros(N_GENES, dtype=bool)
375
+ model[np.load(RC.TIER_6K)] = True
376
+ p0 = present[0]
377
+ mono_cat = [c for c in l1_cats if "onocyte" in c]
378
+ rec_json = {
379
+ "schema_version": SCHEMA,
380
+ "written_utc": datetime.now(timezone.utc).isoformat(),
381
+ "tool": {"path": str(Path(__file__).resolve()), "sha256": CR.sha256_file(Path(__file__).resolve())},
382
+ "inputs": {str(p): CR.sha256_file(p) for p in [*S["files"], CR.E2_INDEX / "metadata/sample_index.parquet",
383
+ CR.E2_INDEX / "metadata/sample_pools.parquet",
384
+ CR.E2_INDEX / "metadata/source_shards.parquet",
385
+ CR.E2_SOURCE / "metadata/var.parquet",
386
+ CR.E2_SOURCE / "BUILD_COMPLETE.json",
387
+ CR.E2_SOURCE / "dataset_manifest.json"]},
388
+ "corpus": {"e2_source": str(CR.E2_SOURCE), "e2_index": str(CR.E2_INDEX),
389
+ "build": json.loads((CR.E2_SOURCE / "BUILD_COMPLETE.json").read_text()),
390
+ "shards_read": len(jobs), "train_samples": int(n_s), "train_pool_cells": int(rows.sum()),
391
+ "cell_cap_per_sample": None,
392
+ "counts": "raw UMI counts of the corpus Zarr shards, canonical 20,097 axis, every train-pool cell"},
393
+ "value_sum_is_log_scale": {
394
+ "binding": str(CR.PANEL_ARTIFACT / "sufficient_statistics/binding.json"),
395
+ "collector": "pbisc_sdd.panel_ladder.collect_train_panel_statistics: value_sum += sum of log1p(x / cell total * target_sum)",
396
+ "target_sum": json.loads((CR.PANEL_ARTIFACT / "sufficient_statistics/binding.json").read_text())["collection_parameters"]["target_sum"],
397
+ "consequence": "a mean of log-normalised values cannot give a mean CPM; per-sample raw-count pseudobulks used instead"},
398
+ "schedule_check": S["check"],
399
+ "evaluation_cohorts_excluded": excl,
400
+ "variants": list(VARIANTS), "primary_variant": CR.TRAIN_PRIMARY_VARIANT,
401
+ "weighted_samples": {v: int((weights[v] > 0).sum()) for v in VARIANTS},
402
+ "dataset_share_of_weight": {v: {str(d): round(float(ds_share[i, j]), 5) for j, d in enumerate(datasets)
403
+ if ds_share[i, j] > 0} for i, v in enumerate(VARIANTS)},
404
+ "variant_agreement_vs_primary": {
405
+ v: {"pearson_log1p_mean_cpm_all_present": float(np.corrcoef(lg[v][both], lg[VARIANTS[0]][both])[0, 1]),
406
+ "pearson_log1p_mean_cpm_model_genes": float(np.corrcoef(lg[v][both & model], lg[VARIANTS[0]][both & model])[0, 1]),
407
+ "mean_abs_log1p_diff_all_present": float(np.abs(lg[v][both] - lg[VARIANTS[0]][both]).mean())}
408
+ for v in VARIANTS[1:]},
409
+ "measurement": {
410
+ "n_present_primary": int(p0.sum()),
411
+ "n_present_full_weight_primary": int((coverage[0] >= 1 - 1e-12).sum()),
412
+ "n_present_partial_weight_primary": int((p0 & (coverage[0] < 1 - 1e-12)).sum()),
413
+ "n_present_below_half_weight_primary": int((p0 & (coverage[0] < 0.5)).sum()),
414
+ "model_genes_partial_weight_primary": int((model & p0 & (coverage[0] < 1 - 1e-12)).sum()),
415
+ "model_genes_below_half_weight_primary": int((model & p0 & (coverage[0] < 0.5)).sum()),
416
+ "model_genes_not_present": int((model & ~p0).sum()),
417
+ "samples_with_mask_mixed_across_shards": int(mixed.sum()),
418
+ "counts_on_coordinates_dropped_by_and_mask": leaked,
419
+ },
420
+ "composition_celltype_l1_weighted_primary": {str(c): float(w1 @ l1_frac[:, k] / w1.sum()) for k, c in enumerate(l1_cats)},
421
+ "monocyte_fraction_per_sample_primary_weighted_median": (
422
+ float(np.median(np.repeat(l1_frac[:, list(l1_cats).index(mono_cat[0])], w1.astype(np.int64))))
423
+ if mono_cat else None),
424
+ "output": {"path": str(out_npz), "sha256": CR.sha256_file(out_npz), "bytes": out_npz.stat().st_size},
425
+ "elapsed_s": round(time.monotonic() - t0, 1),
426
+ }
427
+ out_json.write_text(json.dumps(rec_json, indent=1, default=str) + "\n")
428
+ log(f"written {out_npz} ({out_npz.stat().st_size / 1e6:.1f} MB)")
429
+ return 0
430
+
431
+
432
+ if __name__ == "__main__":
433
+ sys.exit(main())
paper-releases/20260928/diffusion/data/calibration/tools/refcal_refs/common_refs.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared paths and helpers for the three-reference refcal comparison (AIFI, AIDA, training distribution).
2
+
3
+ The refcal helpers (paths, estimator wiring, alpha agreement) are imported unchanged from
4
+ ``refcal/tools/common_refcal.py``. This module only adds the two new references and one function that returns
5
+ a reference mean CPM vector and its measured-gene mask for any of the three references.
6
+
7
+ Nothing here types a donor, sample, gene or dataset by hand; every list is read from its source file.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+
17
+ TOOLS = Path(__file__).resolve().parent
18
+ TASK = TOOLS.parent
19
+ REFCAL_TOOLS = TASK.parent / "refcal" / "tools"
20
+ sys.path.insert(0, str(REFCAL_TOOLS))
21
+ import common_refcal as RC # noqa: E402 (unchanged refcal module)
22
+
23
+ M8 = RC.M8
24
+ UT = RC.UT
25
+ RUN_DIR = M8 / "runs/f01_6k_1x_seed20260627"
26
+ PANEL_ARTIFACT = M8 / "artifacts/panel_ladder_floor01_1m_20260923"
27
+ MODEL7 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_7_no_annotation_sh_hwang")
28
+ E2_SOURCE = MODEL7 / "data/e2_full_source"
29
+ E2_INDEX = MODEL7 / "data/e2_full_index"
30
+
31
+ AIDA_H5AD = Path(
32
+ "/home/sj_server_1/gblee/datalake/single-cell-RNA-seq-datasets/PBMC-cells/"
33
+ "006_A_collection_ced320a1-29f3-47c1-a735-513c7084d5_AIDA_Asian_Immune_Diversity_Atlas/"
34
+ "9deda9ad-6a71-401e-b909-5263919d85f9.h5ad"
35
+ )
36
+
37
+ REF_DIR = TASK / "reference"
38
+ REFERENCES = {
39
+ "aifi": {"npz": RC.REF_NPZ, "json": RC.REF_JSON},
40
+ "aida": {"npz": REF_DIR / "aida_donor_pseudobulk_20097.npz",
41
+ "json": REF_DIR / "aida_donor_pseudobulk_20097.json"},
42
+ "train": {"npz": REF_DIR / "train_distribution_reference_20097.npz",
43
+ "json": REF_DIR / "train_distribution_reference_20097.json"},
44
+ }
45
+ TRAIN_PRIMARY_VARIANT = "recipes_epoch1"
46
+
47
+ sha256_file = RC.sha256_file
48
+ load_npz = RC.load_npz
49
+
50
+
51
+ def log(msg: str) -> None:
52
+ from datetime import datetime, timezone
53
+ print(f"{datetime.now(timezone.utc).isoformat(timespec='seconds')} {msg}", flush=True)
54
+
55
+
56
+ def load_reference(name: str) -> dict:
57
+ """The reference NPZ with the sha recorded in its JSON checked."""
58
+ paths = REFERENCES[name]
59
+ rec = json.loads(Path(paths["json"]).read_text())
60
+ if sha256_file(paths["npz"]) != rec["output"]["sha256"]:
61
+ raise SystemExit(f"{paths['npz']}: sha differs from {paths['json']}")
62
+ d = load_npz(paths["npz"])
63
+ d["record"] = rec
64
+ d["_name"] = name
65
+ return d
66
+
67
+
68
+ def reference_mean_cpm(name: str, ref: dict | None = None, variant: str | None = None) -> tuple[np.ndarray, np.ndarray]:
69
+ """Reference mean CPM on the canonical axis (sums to 1e6) and the reference's measured-gene mask.
70
+
71
+ aifi, aida mean over donors of per-donor CPM (natural composition, every atlas cell); ``present`` = the
72
+ atlas measured the gene (canonical gene in the atlas's raw/var). For aifi this is exactly
73
+ ``common_refcal.reference_mean_cpm`` (checked).
74
+ train stored by ``build_train_reference.py``: for each gene, the recipe-weighted mean of per-sample
75
+ CPM over the training samples that measured the gene (each sample's CPM over its own measured
76
+ genes), renormalised to 1e6 over ``present`` genes; ``present`` = measured in at least one
77
+ weighted training sample. ``variant`` selects the weighting (primary: recipes of the run's
78
+ ordered_train_recipes.csv).
79
+ """
80
+ ref = load_reference(name) if ref is None else ref
81
+ if name in ("aifi", "aida"):
82
+ B = RC.realbulk()
83
+ sums = np.asarray(ref["sums_full"], dtype=np.float64)
84
+ present = np.asarray(ref["present"], dtype=bool)
85
+ if bool((sums[:, ~present] != 0).any()):
86
+ raise SystemExit(f"{name}: reference carries mass on genes absent from the atlas")
87
+ mean = B.cpm(sums).mean(axis=0)
88
+ if name == "aifi":
89
+ m0, p0 = RC.reference_mean_cpm(ref, "full")
90
+ if not (np.array_equal(m0, mean) and np.array_equal(p0, present)):
91
+ raise SystemExit("aifi reference mean differs from common_refcal.reference_mean_cpm")
92
+ return mean, present
93
+ variant = variant or TRAIN_PRIMARY_VARIANT
94
+ names = [str(x) for x in ref["variant_names"]]
95
+ i = names.index(variant)
96
+ mean = np.asarray(ref["mean_cpm"][i], dtype=np.float64)
97
+ present = np.asarray(ref["present"][i], dtype=bool)
98
+ if bool((mean[~present] != 0).any()) or not np.isclose(mean.sum(), 1e6, rtol=1e-9):
99
+ raise SystemExit("train reference mean is not a CPM vector over its present genes")
100
+ return mean, present
101
+
102
+
103
+ def reference_units(name: str, ref: dict) -> tuple[np.ndarray, list[str]]:
104
+ """Unit-level CPM rows of a reference (donors for the atlases, datasets for train) for figures/diagnostics."""
105
+ B = RC.realbulk()
106
+ if name in ("aifi", "aida"):
107
+ return B.cpm(np.asarray(ref["sums_full"], dtype=np.float64)), [str(x) for x in ref["donor_ids"]]
108
+ return np.asarray(ref["dataset_mean_cpm"], dtype=np.float64), [str(x) for x in ref["dataset_ids"]]