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

Archive 4 checkpoints (1-4)

Browse files
paper-releases/20260928/diffusion/data/calibration/aida_donor_pseudobulk_20097.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6daea5b8cf14cbde306ef5a09295fc2a502258a8b62b753a782b5226af5f90c6
3
+ size 21349852
paper-releases/20260928/diffusion/data/calibration/aifi_donor_pseudobulk_20097.json ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "pbisc_sdd.utility6k.refcal.aifi_donor_pseudobulk.v1",
3
+ "written_utc": "2026-09-25T14:02:30.594368+00:00",
4
+ "tool": {
5
+ "path": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/utility_studies_final6k_20260925/refcal/tools/build_aifi_reference.py",
6
+ "sha256": "445eb5b702c02364568affc963585e4138c0c7109c3497c8a21fea593e152ab3"
7
+ },
8
+ "inputs": {
9
+ "/home/sj_server_1/gblee/datalake/single-cell-RNA-seq-datasets/PBMC-cells/009_A_Human_Immune_Health_Atlas_Human_Immune_Health_Atlas_AIFI_immune_dynamics_across_healthy_age/39832a61-3df1-4f1f-971d-3c2a74539047.h5ad": "0f4224f4b5f30503e73831c6db0c8f93abb0d2b2845c31003815ab6af24c635d",
10
+ "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/aifi_scanvi_rebuild_20260916/reference/cell_selection.parquet": "a92f4559f47226de75c7a43c42f5674bb099fc1b0339e3be50ab146f04f93819",
11
+ "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/aifi_scanvi_rebuild_20260916/reference/stratum_allocation.csv": "aa6f6866095b739fe11ec7c78d12751fb939945b447cf6acc361989bd60b6723",
12
+ "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/aifi_scanvi_rebuild_20260916/reference/panel_presence_20097.csv": "b8e7ed4fb559d3d8ac81b55693b57041e4b6973184445c762df51b8d2330f0b2",
13
+ "/home/sj_server_1/PBISC/immun-pbmc-fm/model_7_no_annotation_sh_hwang/data/e2_full_source/metadata/var.parquet": "64f4e30e17763bef37793e7229edb6caa0a7ffe3f3bfa5a08e1d4ca8ea7ea1dc",
14
+ "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/artifacts/panel_ladder_floor01_1m_20260923/ordered_train_recipes.csv": "7c3aadcc409c685605f0f610a0dcc48b1ee5e126dcd80b427e835d1e598e5a3a"
15
+ },
16
+ "counts_source": "atlas raw/X (integer UMI counts), every cell; atlas X (scaled) unused",
17
+ "gene_join": "unversioned Ensembl id, canonical order; identical to panel_presence_20097.csv",
18
+ "n_cells": 1821725,
19
+ "n_donors": 108,
20
+ "n_atlas_genes": 32357,
21
+ "n_canonical_present": 19642,
22
+ "fraction_of_umis_on_atlas_genes_outside_canonical": {
23
+ "full": 0.06404817219370862,
24
+ "strata_reweighted": 0.06403839949499501,
25
+ "strata_unweighted": 0.06709644806164117
26
+ },
27
+ "cells_per_donor": {
28
+ "min": 6632,
29
+ "median": 16836.5,
30
+ "max": 26131
31
+ },
32
+ "natural_l1_composition_pooled": {
33
+ "B cell": 0.08817576747313673,
34
+ "DC": 0.012782939247142132,
35
+ "Erythrocyte": 0.0008277868503753311,
36
+ "ILC": 0.000463297149679562,
37
+ "Monocyte": 0.18000466590731312,
38
+ "NK cell": 0.0811104859405234,
39
+ "Platelet": 0.0043381959406606375,
40
+ "Progenitor cell": 0.0008376675952737104,
41
+ "T cell": 0.6314591938958953
42
+ },
43
+ "monocyte_fraction_per_donor": {
44
+ "natural_median": 0.173239410796725,
45
+ "natural_q25_q75": [
46
+ 0.13177028794890605,
47
+ 0.21155032055000875
48
+ ],
49
+ "strata_unweighted_median": 0.16178793137045663
50
+ },
51
+ "reference_variant_agreement": {
52
+ "strata_reweighted_vs_full": {
53
+ "pearson_log1p_mean_cpm_present": 0.999994896636385,
54
+ "mean_abs_log1p_diff_present": 0.0036980056267184383
55
+ },
56
+ "strata_unweighted_vs_full": {
57
+ "pearson_log1p_mean_cpm_present": 0.9988645091206474,
58
+ "mean_abs_log1p_diff_present": 0.03355269717904739
59
+ }
60
+ },
61
+ "reference_h5ad_check": {
62
+ "reference_h5ad": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/aifi_scanvi_rebuild_20260916/reference/aifi_reference_20097.h5ad",
63
+ "per_donor_sums_equal_strata_unweighted": true,
64
+ "max_abs_diff": 0.0
65
+ },
66
+ "training_corpus": {
67
+ "file": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/artifacts/panel_ladder_floor01_1m_20260923/ordered_train_recipes.csv",
68
+ "aifi_dataset_ids": [
69
+ "009_A_Human_Immune_Health_Atlas_Human_Immune_Health_Atlas_AIFI_immune_dynamics_across_healthy_age"
70
+ ],
71
+ "aifi_recipes": 378,
72
+ "all_recipes": 8192,
73
+ "aifi_donors_in_recipes": 85,
74
+ "reference_donors_in_recipes": 85,
75
+ "note": "AIFI is part of the model_8 training corpus; the reference therefore stands for (part of) the training distribution, which is the calibration target"
76
+ },
77
+ "output": {
78
+ "path": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/utility_studies_final6k_20260925/refcal/reference/aifi_donor_pseudobulk_20097.npz",
79
+ "sha256": "f7c7223f0dbfffc20c9137a1ec5b6a2436b27de5a5ae6f15d1686918b6baa564",
80
+ "bytes": 20637643
81
+ },
82
+ "elapsed_s": 102.0
83
+ }
paper-releases/20260928/diffusion/data/calibration/aifi_donor_pseudobulk_20097.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f7c7223f0dbfffc20c9137a1ec5b6a2436b27de5a5ae6f15d1686918b6baa564
3
+ size 20637643
paper-releases/20260928/diffusion/data/calibration/tools/refcal/build_aifi_reference.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Per-donor pseudobulks of the AIFI Human Immune Health Atlas at NATURAL composition, canonical 20,097 axis.
3
+
4
+ The external healthy reference for reference-anchored calibration. Every atlas cell is read once from
5
+ ``raw/X`` (integer UMI counts; the atlas ``X`` is scaled and never touched) in row chunks, and summed per
6
+ donor. Atlas genes are joined to the canonical panel on the unversioned Ensembl id, the rule of the
7
+ existing 400K reference (``aifi_scanvi_rebuild_20260916/build_reference.py``); canonical genes absent from
8
+ the atlas carry 0 and are flagged unmeasured by ``present``.
9
+
10
+ Three per-donor sums are written, all from the same pass:
11
+
12
+ sums_full every atlas cell of the donor (natural composition; the primary reference)
13
+ sums_strata_reweighted only the cells of the stratified 400K reference (``cell_selection.parquet``), each
14
+ weighted by n_available / n_selected of its AIFI_L2 x donor stratum
15
+ (``stratum_allocation.csv``): an estimate of sums_full from the subsample
16
+ sums_strata_unweighted those cells unweighted: the over-sampled rare types, to show what ignoring
17
+ natural composition would do
18
+
19
+ Checks: the atlas obs matches the stratum table (n_available per stratum); the selected rows match the
20
+ 400K reference file cell for cell (barcode, donor, label) and, with ``--check-reference``, per-donor sums of the
21
+ reference h5ad equal sums_strata_unweighted on every canonical gene.
22
+
23
+ CPU only; peak memory a few GB. Output: ``reference/aifi_donor_pseudobulk_20097.{npz,json}``.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import json
29
+ import os
30
+ import sys
31
+ import time
32
+ from datetime import datetime, timezone
33
+ from pathlib import Path
34
+
35
+ os.environ.setdefault("CUDA_VISIBLE_DEVICES", "")
36
+ import h5py
37
+ import numpy as np
38
+ import pandas as pd
39
+ import scipy.sparse as sp
40
+
41
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
42
+ import common_refcal as R # noqa: E402
43
+
44
+ SCHEMA = "pbisc_sdd.utility6k.refcal.aifi_donor_pseudobulk.v1"
45
+
46
+
47
+ def _decode(arr: np.ndarray) -> np.ndarray:
48
+ if arr.dtype.kind in ("S", "O"):
49
+ return np.asarray([x.decode() if isinstance(x, bytes) else str(x) for x in arr], dtype=object)
50
+ return arr
51
+
52
+
53
+ def read_col(group: h5py.Group, key: str) -> np.ndarray:
54
+ obj = group[key]
55
+ if isinstance(obj, h5py.Group) and obj.attrs.get("encoding-type") == "categorical":
56
+ cats = _decode(obj["categories"][:])
57
+ codes = obj["codes"][:]
58
+ if (codes < 0).any():
59
+ raise SystemExit(f"obs/{key} has missing values")
60
+ return cats[codes].astype(str)
61
+ return _decode(obj[:]).astype(str)
62
+
63
+
64
+ def log(msg: str) -> None:
65
+ print(f"{datetime.now(timezone.utc).isoformat(timespec='seconds')} {msg}", flush=True)
66
+
67
+
68
+ def main(argv=None) -> int:
69
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
70
+ ap.add_argument("--chunk-rows", type=int, default=20000)
71
+ ap.add_argument("--max-rows", type=int, default=None, help="smoke test only (no output written)")
72
+ ap.add_argument("--check-reference", action="store_true")
73
+ a = ap.parse_args(argv)
74
+ t0 = time.monotonic()
75
+ panel = R.canonical_panel()
76
+ panel_ids = panel["gene_id"].astype(str).to_numpy()
77
+
78
+ with h5py.File(R.ATLAS, "r") as f:
79
+ obs = f["obs"]
80
+ barcodes = read_col(obs, obs.attrs.get("_index", "_index"))
81
+ donor = read_col(obs, "donor_id")
82
+ l1 = read_col(obs, "AIFI_L1")
83
+ l2 = read_col(obs, "AIFI_L2")
84
+ sample_kit = read_col(obs, "sample.sampleKitGuid")
85
+ atlas_genes = read_col(f["raw/var"], f["raw/var"].attrs.get("_index", "_index"))
86
+ grp = f["raw/X"]
87
+ n_rows, n_cols = (int(x) for x in grp.attrs["shape"])
88
+ if n_rows != len(donor) or n_cols != len(atlas_genes):
89
+ raise SystemExit("raw/X shape disagrees with obs / raw/var")
90
+ if len(set(atlas_genes.tolist())) != len(atlas_genes):
91
+ raise SystemExit("atlas Ensembl ids are not unique")
92
+ col_of = {g: i for i, g in enumerate(atlas_genes.tolist())}
93
+ atlas_col = np.asarray([col_of.get(g, -1) for g in panel_ids], dtype=np.int64)
94
+ present = atlas_col >= 0
95
+ log(f"atlas {n_rows:,} cells x {n_cols:,} genes; canonical genes present {int(present.sum()):,}/20,097")
96
+
97
+ # the existing 400K reference's presence table must agree with this join
98
+ pres = pd.read_csv(R.AIFI_PRESENCE)
99
+ if not (np.array_equal(pres["gene_id"].astype(str).to_numpy(), panel_ids)
100
+ and np.array_equal(pres["present_in_atlas"].to_numpy(dtype=bool), present)
101
+ and np.array_equal(pres["atlas_col"].to_numpy(dtype=np.int64)[present], atlas_col[present])):
102
+ raise SystemExit("gene join disagrees with panel_presence_20097.csv")
103
+
104
+ donors = np.asarray(sorted(set(donor.tolist())))
105
+ d_index = {d: i for i, d in enumerate(donors.tolist())}
106
+ dcode = np.asarray([d_index[d] for d in donor.tolist()], dtype=np.int64)
107
+ kits = pd.Series(sample_kit).groupby(donor).nunique()
108
+ if int(kits.max()) != 1:
109
+ raise SystemExit("a donor has more than one sample kit; per-donor pooling would mix samples")
110
+
111
+ # stratified 400K selection and its stratum weights
112
+ sel = pd.read_parquet(R.AIFI_SELECTION)
113
+ strata = pd.read_csv(R.AIFI_STRATA)
114
+ nat = pd.DataFrame({"AIFI_L2": l2, "donor_id": donor}).value_counts().rename("n_atlas").reset_index()
115
+ chk = strata.merge(nat, on=["AIFI_L2", "donor_id"], how="outer")
116
+ if chk["n_atlas"].isna().any() or chk["n_available"].isna().any() or \
117
+ not np.array_equal(chk["n_available"].to_numpy(), chk["n_atlas"].to_numpy()):
118
+ raise SystemExit("stratum_allocation n_available differs from the atlas obs counts")
119
+ rows_sel = sel["atlas_row"].to_numpy(dtype=np.int64)
120
+ if len(np.unique(rows_sel)) != len(rows_sel):
121
+ raise SystemExit("cell_selection atlas_row has duplicates")
122
+ for col_sel, col_atlas in (("barcode", barcodes), ("donor_id", donor), ("AIFI_L2", l2)):
123
+ if not np.array_equal(sel[col_sel].astype(str).to_numpy(), col_atlas[rows_sel]):
124
+ raise SystemExit(f"cell_selection {col_sel} differs from the atlas at atlas_row")
125
+ w_of = strata.set_index(["AIFI_L2", "donor_id"])
126
+ w_of = (w_of["n_available"] / w_of["n_selected"]).to_dict()
127
+ weight = np.zeros(n_rows, dtype=np.float64)
128
+ weight[rows_sel] = [w_of[(x, y)] for x, y in zip(l2[rows_sel], donor[rows_sel])]
129
+ selected = np.zeros(n_rows, dtype=bool)
130
+ selected[rows_sel] = True
131
+ log(f"strata {len(strata):,}; selected {selected.sum():,}; weights {weight[selected].min():.2f}-"
132
+ f"{weight[selected].max():.2f}")
133
+
134
+ n_d = len(donors)
135
+ acc = {k: np.zeros((n_d, n_cols), dtype=np.float64) for k in ("full", "strata_reweighted",
136
+ "strata_unweighted")}
137
+ indptr = grp["indptr"][:].astype(np.int64)
138
+ data_ds, idx_ds = grp["data"], grp["indices"]
139
+ stop_all = n_rows if a.max_rows is None else min(a.max_rows, n_rows)
140
+ n_nonint = 0
141
+ for start in range(0, stop_all, a.chunk_rows):
142
+ stop = min(start + a.chunk_rows, stop_all)
143
+ lo, hi = int(indptr[start]), int(indptr[stop])
144
+ data = np.asarray(data_ds[lo:hi], dtype=np.float64)
145
+ idx = np.asarray(idx_ds[lo:hi], dtype=np.int64)
146
+ n_nonint += int((data != np.rint(data)).sum())
147
+ m = sp.csr_matrix((data, idx, indptr[start:stop + 1] - lo), shape=(stop - start, n_cols))
148
+ r = np.arange(stop - start)
149
+ dc = dcode[start:stop]
150
+ ind = sp.csr_matrix((np.ones(stop - start), (dc, r)), shape=(n_d, stop - start))
151
+ acc["full"] += (ind @ m).toarray()
152
+ s = selected[start:stop]
153
+ if s.any():
154
+ ind_u = sp.csr_matrix((np.ones(int(s.sum())), (dc[s], r[s])), shape=(n_d, stop - start))
155
+ ind_w = sp.csr_matrix((weight[start:stop][s], (dc[s], r[s])), shape=(n_d, stop - start))
156
+ acc["strata_unweighted"] += (ind_u @ m).toarray()
157
+ acc["strata_reweighted"] += (ind_w @ m).toarray()
158
+ if (start // a.chunk_rows) % 10 == 0 or stop == stop_all:
159
+ el = time.monotonic() - t0
160
+ log(f"[stream] rows {stop:,}/{stop_all:,} elapsed {el / 60:.1f} min")
161
+ if n_nonint:
162
+ raise SystemExit(f"raw/X carries {n_nonint} non-integer values")
163
+
164
+ if a.max_rows is not None:
165
+ log("smoke run finished; nothing written")
166
+ return 0
167
+
168
+ # canonical axis: absent genes stay 0
169
+ out = {}
170
+ for k, v in acc.items():
171
+ c = np.zeros((n_d, len(panel_ids)), dtype=np.float64)
172
+ c[:, present] = v[:, atlas_col[present]]
173
+ out[k] = c
174
+ lost = {k: float(1.0 - out[k].sum() / acc[k].sum()) for k in acc}
175
+ n_cells = np.bincount(dcode, minlength=n_d).astype(np.int64)
176
+ l1_cats = np.asarray(sorted(set(l1.tolist())))
177
+ l1_counts = np.stack([np.bincount(dcode[l1 == c], minlength=n_d) for c in l1_cats], axis=1).astype(np.int64)
178
+ l2_cats = np.asarray(sorted(set(l2.tolist())))
179
+ l2_counts = np.stack([np.bincount(dcode[l2 == c], minlength=n_d) for c in l2_cats], axis=1).astype(np.int64)
180
+ sel_l1 = np.stack([np.bincount(dcode[selected & (l1 == c)], minlength=n_d) for c in l1_cats],
181
+ axis=1).astype(np.int64)
182
+
183
+ check_ref = None
184
+ if a.check_reference:
185
+ with h5py.File(R.AIFI_REF_H5AD, "r") as f:
186
+ g = f["X"]
187
+ n_r, n_c = (int(x) for x in g.attrs["shape"])
188
+ ref_panel_index = f["var/panel_index"][:].astype(np.int64)
189
+ ref_donor = read_col(f["obs"], "donor_id")
190
+ ref_row = f["obs/atlas_row"][:].astype(np.int64)
191
+ if not np.array_equal(np.sort(ref_row), np.sort(rows_sel)):
192
+ raise SystemExit("reference h5ad atlas_row set differs from cell_selection.parquet")
193
+ ip = g["indptr"][:].astype(np.int64)
194
+ s_ref = np.zeros((n_d, n_c), dtype=np.float64)
195
+ rc = np.asarray([d_index[d] for d in ref_donor.tolist()], dtype=np.int64)
196
+ for start in range(0, n_r, 50000):
197
+ stop = min(start + 50000, n_r)
198
+ lo, hi = int(ip[start]), int(ip[stop])
199
+ m = sp.csr_matrix((np.asarray(g["data"][lo:hi], dtype=np.float64),
200
+ np.asarray(g["indices"][lo:hi], dtype=np.int64), ip[start:stop + 1] - lo),
201
+ shape=(stop - start, n_c))
202
+ ind = sp.csr_matrix((np.ones(stop - start), (rc[start:stop], np.arange(stop - start))),
203
+ shape=(n_d, stop - start))
204
+ s_ref += (ind @ m).toarray()
205
+ canon = np.zeros((n_d, len(panel_ids)), dtype=np.float64)
206
+ canon[:, ref_panel_index] = s_ref
207
+ equal = bool(np.array_equal(canon, out["strata_unweighted"]))
208
+ check_ref = {"reference_h5ad": str(R.AIFI_REF_H5AD), "per_donor_sums_equal_strata_unweighted": equal,
209
+ "max_abs_diff": float(np.abs(canon - out["strata_unweighted"]).max())}
210
+ if not equal:
211
+ raise SystemExit(f"reference h5ad per-donor sums differ from the selected atlas rows: {check_ref}")
212
+ log(f"reference h5ad check: {check_ref}")
213
+
214
+ R.REF_NPZ.parent.mkdir(parents=True, exist_ok=True)
215
+ np.savez_compressed(
216
+ R.REF_NPZ,
217
+ schema_version=np.asarray(SCHEMA),
218
+ gene_ids=panel_ids.astype(np.str_),
219
+ present=present,
220
+ donor_ids=donors.astype(np.str_),
221
+ n_cells=n_cells,
222
+ sums_full=out["full"],
223
+ sums_strata_reweighted=out["strata_reweighted"],
224
+ sums_strata_unweighted=out["strata_unweighted"],
225
+ l1_categories=l1_cats.astype(np.str_),
226
+ l1_counts=l1_counts,
227
+ l1_counts_selected=sel_l1,
228
+ l2_categories=l2_cats.astype(np.str_),
229
+ l2_counts=l2_counts,
230
+ )
231
+ B = R.realbulk()
232
+ cp = {k: B.cpm(v) for k, v in out.items()}
233
+ mean_cp = {k: v.mean(0) for k, v in cp.items()}
234
+ lg = {k: np.log1p(v) for k, v in mean_cp.items()}
235
+ mono = l1_counts[:, list(l1_cats).index("Monocyte")] / n_cells
236
+ mono_sel = sel_l1[:, list(l1_cats).index("Monocyte")] / sel_l1.sum(1)
237
+ # which AIFI donors are in the model_8 training recipe sample
238
+ rec = pd.read_csv(R.TRAIN_RECIPES, usecols=["dataset_id", "donor_id", "sample_id", "split"])
239
+ aifi_ds = [d for d in rec["dataset_id"].unique() if d.startswith("009_A_Human_Immune_Health_Atlas")]
240
+ in_train = rec[rec["dataset_id"].isin(aifi_ds)]
241
+ rec_json = {
242
+ "schema_version": SCHEMA,
243
+ "written_utc": datetime.now(timezone.utc).isoformat(),
244
+ "tool": {"path": str(Path(__file__).resolve()), "sha256": R.sha256_file(Path(__file__).resolve())},
245
+ "inputs": {str(p): R.sha256_file(p) for p in (R.ATLAS, R.AIFI_SELECTION, R.AIFI_STRATA, R.AIFI_PRESENCE,
246
+ R.behcet_builder().DEFAULT_PANEL, R.TRAIN_RECIPES)},
247
+ "counts_source": "atlas raw/X (integer UMI counts), every cell; atlas X (scaled) unused",
248
+ "gene_join": "unversioned Ensembl id, canonical order; identical to panel_presence_20097.csv",
249
+ "n_cells": int(n_rows), "n_donors": int(n_d), "n_atlas_genes": int(n_cols),
250
+ "n_canonical_present": int(present.sum()),
251
+ "fraction_of_umis_on_atlas_genes_outside_canonical": lost,
252
+ "cells_per_donor": {"min": int(n_cells.min()), "median": float(np.median(n_cells)), "max": int(n_cells.max())},
253
+ "natural_l1_composition_pooled": {c: float(l1_counts[:, i].sum() / n_cells.sum()) for i, c in enumerate(l1_cats)},
254
+ "monocyte_fraction_per_donor": {"natural_median": float(np.median(mono)),
255
+ "natural_q25_q75": [float(np.percentile(mono, 25)), float(np.percentile(mono, 75))],
256
+ "strata_unweighted_median": float(np.median(mono_sel))},
257
+ "reference_variant_agreement": {
258
+ f"{k}_vs_full": {"pearson_log1p_mean_cpm_present": float(np.corrcoef(lg[k][present], lg["full"][present])[0, 1]),
259
+ "mean_abs_log1p_diff_present": float(np.abs(lg[k][present] - lg["full"][present]).mean())}
260
+ for k in ("strata_reweighted", "strata_unweighted")},
261
+ "reference_h5ad_check": check_ref,
262
+ "training_corpus": {
263
+ "file": str(R.TRAIN_RECIPES),
264
+ "aifi_dataset_ids": aifi_ds,
265
+ "aifi_recipes": int(len(in_train)), "all_recipes": int(len(rec)),
266
+ "aifi_donors_in_recipes": int(in_train["donor_id"].nunique()),
267
+ "reference_donors_in_recipes": int(np.isin(donors, in_train["donor_id"].astype(str).unique()).sum()),
268
+ "note": "AIFI is part of the model_8 training corpus; the reference therefore stands for (part of) "
269
+ "the training distribution, which is the calibration target",
270
+ },
271
+ "output": {"path": str(R.REF_NPZ), "sha256": R.sha256_file(R.REF_NPZ), "bytes": R.REF_NPZ.stat().st_size},
272
+ "elapsed_s": round(time.monotonic() - t0, 1),
273
+ }
274
+ R.REF_JSON.write_text(json.dumps(rec_json, indent=1) + "\n")
275
+ log(f"written {R.REF_NPZ} ({R.REF_NPZ.stat().st_size / 1e6:.1f} MB)")
276
+ return 0
277
+
278
+
279
+ if __name__ == "__main__":
280
+ sys.exit(main())