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

Archive 4 checkpoints (1-4)

Browse files
paper-releases/20260928/diffusion/data/protocol/paired_finetune/tools/prepare_dataset.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Folds and condition NPZs for the within-dataset fine-tuning benchmark (CPU only).
3
+
4
+ For one dataset directory (features.npz + samples.csv, see build_immicro_cells.py) this writes
5
+
6
+ folds.csv row, sample_id, donor_id, group, fold (0..K-1), inner_val (bool, per fold column)
7
+ conditions_raw_fixed.npz every row: the separately measured bulk
8
+ conditions_pseudo_fixed.npz every row: the pseudobulk of that row's own cells
9
+ fold{k}/conditions_cal_fixed.npz every row: bulk x gene multiplier alpha fitted on fold k's training rows only
10
+ fold{k}/test_{raw,cal,pseudo}.npz the test rows of fold k, same keys (the sampler input)
11
+
12
+ Folds are donor-level (all rows of one donor share a fold) and stratified by group. Inside each fold's
13
+ training donors, a fixed ~10 % (at least one per group where possible) is marked inner_val: fine-tuning uses
14
+ them only for early stopping; the test donors are never read during training.
15
+
16
+ Condition arithmetic is imported from plans/realbulk_generation_20260922/build_realbulk_conditions.py (cpm,
17
+ gene_multiplier, to_condition_counts, RECIPE_K, DEPTH_ANCHOR), i.e. the fixed-depth policy of the published
18
+ ImMicro arms: K = 1000 and one depth anchor for every sample, so no test donor's single-cell depth or cell count
19
+ enters its own condition. For ImMicro the raw and pseudo NPZs are checked against the published
20
+ conditions_ImMicro_{raw,pseudo}.npz.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import hashlib
26
+ import importlib.util
27
+ import json
28
+ import os
29
+ import sys
30
+ from datetime import datetime, timezone
31
+ from pathlib import Path
32
+
33
+ import numpy as np
34
+ import pandas as pd
35
+
36
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
37
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
38
+
39
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
40
+ TASK = M8 / "plans/paired_finetune_intradataset_20260927"
41
+ BUILDER = M8 / "plans/realbulk_generation_20260922/build_realbulk_conditions.py"
42
+ PUBLISHED_IMMICRO = M8 / "plans/realbulk_generation_20260922/conditions"
43
+ SCHEMA = "pbisc_sdd.ft_intradataset.conditions.v1"
44
+ MIN_CELLS = 200
45
+
46
+ spec = importlib.util.spec_from_file_location("build_realbulk_conditions", BUILDER)
47
+ RB = importlib.util.module_from_spec(spec)
48
+ sys.modules[spec.name] = RB
49
+ spec.loader.exec_module(RB)
50
+
51
+
52
+ def sha256_file(path: Path) -> str:
53
+ h = hashlib.sha256()
54
+ with open(path, "rb") as f:
55
+ for block in iter(lambda: f.read(1 << 24), b""):
56
+ h.update(block)
57
+ return h.hexdigest()
58
+
59
+
60
+ def load(ds_dir: Path) -> dict:
61
+ f = np.load(ds_dir / "features.npz", allow_pickle=False)
62
+ if not (ds_dir / "samples.csv").exists():
63
+ # datasets built by the pairing agent carry sample_ids / donor_ids / groups in features.npz
64
+ pd.DataFrame({"row": np.arange(len(f["donor_ids"])), "sample_id": f["sample_ids"].astype(str),
65
+ "donor_id": f["donor_ids"].astype(str), "group": f["groups"].astype(str),
66
+ "n_cells": f["qc_cell_counts"].astype(np.int64)}).to_csv(ds_dir / "samples.csv", index=False)
67
+ s = pd.read_csv(ds_dir / "samples.csv")
68
+ n = len(s)
69
+ sample_ids = (f["sample_ids"] if "sample_ids" in f.files else f["donor_ids"]).astype(str)
70
+ if not np.array_equal(sample_ids, s["sample_id"].astype(str).to_numpy()):
71
+ raise SystemExit("samples.csv sample_id order differs from features.npz")
72
+ d = {
73
+ "gene_ids": f["gene_ids"].astype(str), "sample_ids": sample_ids,
74
+ "donor_ids": s["donor_id"].astype(str).to_numpy(), "groups": s["group"].astype(str).to_numpy(),
75
+ "bulk_valid": f["bulk_valid"].astype(bool), "sc_valid": f["sc_valid"].astype(bool),
76
+ "n_cells": s["n_cells"].to_numpy(np.int64),
77
+ # rows whose bulk and single cells failed the pairing identity checks are never trained on or tested
78
+ "use": (f["identity_pass"].astype(bool) if "identity_pass" in f.files else np.ones(n, dtype=bool)),
79
+ }
80
+ # the strict-QC protocol's minimum usable cells per sample (PROTOCOL.json qc.minimum_usable_cells_per_sample);
81
+ # every earlier dataset has >= 759 cells per row, so this only affects Imperial's tiny sc samples
82
+ d["use"] = d["use"] & (d["n_cells"] >= MIN_CELLS)
83
+ d["bulk"] = RB.drop_unmeasured_nan(f["bulk_raw"], d["bulk_valid"], "bulk")
84
+ d["pseudo"] = RB.drop_unmeasured_nan(f["pseudo_raw_sum"], d["sc_valid"], "pseudobulk")
85
+ for k in ("bulk", "pseudo", "bulk_valid", "sc_valid"):
86
+ if d[k].shape != (n, 20097):
87
+ raise SystemExit(f"{k} shape {d[k].shape}")
88
+ return d
89
+
90
+
91
+ def make_folds(d: dict, k: int, seed: int, inner_frac: float) -> pd.DataFrame:
92
+ """Donor-level, group-stratified folds; inner-validation donors inside each fold's training part."""
93
+ rng = np.random.default_rng(seed)
94
+ use = d["use"]
95
+ donors = pd.DataFrame({"donor_id": d["donor_ids"][use], "group": d["groups"][use]}).drop_duplicates("donor_id")
96
+ if donors["donor_id"].duplicated().any():
97
+ raise SystemExit("a donor carries two groups")
98
+ fold_of = {}
99
+ offset = 0
100
+ for _, g in donors.groupby("group", sort=True):
101
+ ids = g["donor_id"].to_numpy()
102
+ ids = ids[rng.permutation(len(ids))]
103
+ for i, did in enumerate(ids):
104
+ fold_of[did] = (offset + i) % k # round-robin across groups keeps folds balanced in size
105
+ offset += len(ids)
106
+ out = pd.DataFrame({"row": np.arange(len(d["sample_ids"])), "sample_id": d["sample_ids"],
107
+ "donor_id": d["donor_ids"], "group": d["groups"]})
108
+ out["fold"] = out["donor_id"].map(fold_of).fillna(-1).astype(int)
109
+ out.loc[~use, "fold"] = -1 # excluded rows: fold -1, never training, inner-val or test
110
+ for f in range(k):
111
+ train_donors = donors[donors["donor_id"].map(fold_of) != f]
112
+ inner = []
113
+ for _, g in train_donors.groupby("group", sort=True):
114
+ n_take = int(round(inner_frac * len(g)))
115
+ if n_take == 0 and len(g) >= 4:
116
+ n_take = 1
117
+ ids = g["donor_id"].to_numpy()
118
+ inner.extend(ids[rng.permutation(len(ids))[:n_take]].tolist())
119
+ out[f"inner_val_f{f}"] = out["donor_id"].isin(inner) & (out["fold"] != f) & (out["fold"] >= 0)
120
+ return out
121
+
122
+
123
+ def write_npz(path: Path, d: dict, rows: np.ndarray, counts: np.ndarray, frac: np.ndarray,
124
+ cells_per_bulk: int, arm: str) -> str:
125
+ rows = np.asarray(rows, dtype=np.int64)
126
+ c = counts[rows]
127
+ fr = frac[rows].astype(np.float32)
128
+ if bool((c[fr == 0] != 0).any()):
129
+ raise SystemExit(f"{path.name}: unmeasured coordinate with a non-zero count")
130
+ np.savez(path, schema_version=np.array(SCHEMA), bulk_counts=c, bulk_measurement_fraction=fr,
131
+ output_availability_mask=d["sc_valid"][rows], recipe_k=np.full(len(rows), RB.RECIPE_K, dtype=np.int64),
132
+ cells_per_bulk=np.full(len(rows), int(cells_per_bulk), dtype=np.int64),
133
+ sample_ids=d["sample_ids"][rows], donor_ids=d["donor_ids"][rows], groups=d["groups"][rows],
134
+ gene_ids=d["gene_ids"], donor_n_cells=d["n_cells"][rows], dataset_rows=rows, arm=np.array(arm))
135
+ return sha256_file(path)
136
+
137
+
138
+ def main(argv=None) -> int:
139
+ ap = argparse.ArgumentParser()
140
+ ap.add_argument("--dataset", required=True)
141
+ ap.add_argument("--folds", type=int, default=5)
142
+ ap.add_argument("--seed", type=int, default=20260927)
143
+ ap.add_argument("--inner-frac", type=float, default=0.10)
144
+ ap.add_argument("--cells-per-bulk", type=int, default=1500)
145
+ a = ap.parse_args(argv)
146
+ ds = TASK / "data" / a.dataset
147
+ d = load(ds)
148
+ n = len(d["sample_ids"])
149
+ folds = make_folds(d, a.folds, a.seed, a.inner_frac)
150
+ folds.to_csv(ds / "folds.csv", index=False)
151
+ all_rows = np.arange(n)
152
+ man = {"schema": SCHEMA, "dataset": a.dataset, "written_utc": datetime.now(timezone.utc).isoformat(),
153
+ "features_sha256": sha256_file((ds / "features.npz").resolve()), "seed": a.seed, "folds": a.folds,
154
+ "inner_frac": a.inner_frac, "cells_per_bulk": a.cells_per_bulk, "recipe_k": RB.RECIPE_K,
155
+ "depth_anchor": RB.DEPTH_ANCHOR, "builder": str(BUILDER), "builder_sha256": sha256_file(BUILDER),
156
+ "files": {}, "fold_sizes": {}, "checks": {}}
157
+
158
+ raw = RB.to_condition_counts(d["bulk"], d["bulk_valid"])
159
+ pseudo = RB.to_condition_counts(d["pseudo"], d["sc_valid"])
160
+ man["files"]["conditions_raw_fixed.npz"] = write_npz(ds / "conditions_raw_fixed.npz", d, all_rows, raw,
161
+ d["bulk_valid"], a.cells_per_bulk, "raw")
162
+ man["files"]["conditions_pseudo_fixed.npz"] = write_npz(ds / "conditions_pseudo_fixed.npz", d, all_rows, pseudo,
163
+ d["sc_valid"], a.cells_per_bulk, "pseudo")
164
+ if a.dataset == "immicro":
165
+ for arm, arr in (("raw", raw), ("pseudo", pseudo)):
166
+ pub = np.load(PUBLISHED_IMMICRO / f"conditions_ImMicro_{arm}.npz")
167
+ same = bool(np.array_equal(pub["bulk_counts"], arr)) and bool(
168
+ np.array_equal(pub["sample_ids"].astype(str), d["sample_ids"]))
169
+ man["checks"][f"{arm}_equals_published_fixed"] = same
170
+ if not same:
171
+ raise SystemExit(f"{arm}: differs from the published fixed ImMicro condition")
172
+
173
+ for f in range(a.folds):
174
+ fd = ds / f"fold{f}"
175
+ fd.mkdir(exist_ok=True)
176
+ test = folds.index[folds["fold"] == f].to_numpy()
177
+ inner = folds.index[folds[f"inner_val_f{f}"]].to_numpy()
178
+ train = folds.index[(folds["fold"] != f) & (folds["fold"] >= 0) & ~folds[f"inner_val_f{f}"]].to_numpy()
179
+ # alpha uses all training donors (train + inner-val), never excluded rows
180
+ fit = folds.index[(folds["fold"] != f) & (folds["fold"] >= 0)].to_numpy()
181
+ valid = d["bulk_valid"][fit].all(axis=0) & d["sc_valid"][fit].all(axis=0)
182
+ alpha = RB.gene_multiplier(d["bulk"][fit], d["pseudo"][fit], valid)
183
+ cal = RB.to_condition_counts(RB.cpm(d["bulk"]) * alpha[None, :], d["bulk_valid"])
184
+ man["files"][f"fold{f}/conditions_cal_fixed.npz"] = write_npz(fd / "conditions_cal_fixed.npz", d, all_rows,
185
+ cal, d["bulk_valid"], a.cells_per_bulk, "cal")
186
+ np.save(fd / "alpha.npy", alpha)
187
+ for arm, arr, frac in (("raw", raw, d["bulk_valid"]), ("cal", cal, d["bulk_valid"]),
188
+ ("pseudo", pseudo, d["sc_valid"])):
189
+ man["files"][f"fold{f}/test_{arm}.npz"] = write_npz(fd / f"test_{arm}.npz", d, test, arr, frac,
190
+ a.cells_per_bulk, arm)
191
+ man["fold_sizes"][f] = {"test": int(len(test)), "train": int(len(train)), "inner_val": int(len(inner)),
192
+ "test_groups": folds.loc[test, "group"].value_counts().to_dict(),
193
+ "alpha_genes_estimated": int((alpha != 1.0).sum())}
194
+ (ds / "PREPARE.json").write_text(json.dumps(man, indent=1, default=str))
195
+ print(json.dumps(man["fold_sizes"], indent=1), json.dumps(man["checks"]))
196
+ return 0
197
+
198
+
199
+ if __name__ == "__main__":
200
+ sys.exit(main())
paper-releases/20260928/diffusion/data/protocol/paired_finetune/tools/prepare_fewshot.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Few-pair deployment scenario: n paired donors for fine-tuning, every other donor of the cohort for testing (CPU only).
3
+
4
+ Per draw j (seed = --seed + j), n donors are drawn among the usable rows of data/<dataset>/folds.csv (fold >= 0,
5
+ i.e. identity-passed), stratified by a donor-level stratum (a donor is in the stratum if any of its rows' group
6
+ matches --strata-regex; allocation proportional, at least one donor per stratum). All rows of the chosen donors are
7
+ training pairs; all rows of every other usable donor are test rows. No inner validation: the LoRA is trained for a
8
+ fixed number of steps (the learning curve's early-stopping range for n = 5).
9
+
10
+ Writes data/<dataset>/fewshot_n<n>/
11
+ all_usable_{raw,pseudo}.npz every usable row (zero-shot raw and pseudobulk arms are sampled once and subset)
12
+ draw<j>/train_donors.txt the n training donors
13
+ draw<j>/test_samples.txt test sample_ids (the scorer's --donors list)
14
+ draw<j>/test_cal.npz test rows, bulk x alpha fitted on the n training donors only
15
+ draw<j>/test_raw.npz test rows, raw bulk (the fine-tuned model's input)
16
+ DRAWS.json
17
+ usage: prepare_fewshot.py DATASET --n 5 --draws 5 [--strata-regex REGEX]
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import json
23
+ import os
24
+ import sys
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+
30
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
31
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
32
+ TASK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
33
+ sys.path.insert(0, str(TASK / "tools"))
34
+ import prepare_dataset as PD # noqa: E402 (same loader, condition arithmetic and NPZ writer as the fold benchmark)
35
+
36
+ DEFAULT_STRATA = {"ye2026_sepsis": "sepsis", "imperial_eskd": "positive", "giroux2022": "severe",
37
+ "ji2025_chili": "TOL|FU1"}
38
+
39
+
40
+ def main(argv=None) -> int:
41
+ ap = argparse.ArgumentParser()
42
+ ap.add_argument("dataset")
43
+ ap.add_argument("--n", type=int, default=5)
44
+ ap.add_argument("--draws", type=int, default=5)
45
+ ap.add_argument("--seed", type=int, default=20260928)
46
+ ap.add_argument("--strata-regex", default=None)
47
+ ap.add_argument("--cells-per-bulk", type=int, default=1500)
48
+ a = ap.parse_args(argv)
49
+ ds = TASK / "data" / a.dataset
50
+ d = PD.load(ds)
51
+ folds = pd.read_csv(ds / "folds.csv")
52
+ if not np.array_equal(folds["sample_id"].astype(str).to_numpy(), d["sample_ids"]):
53
+ raise SystemExit("folds.csv rows differ from features.npz")
54
+ usable = folds.index[folds["fold"] >= 0].to_numpy()
55
+ regex = DEFAULT_STRATA.get(a.dataset, "") if a.strata_regex is None else a.strata_regex
56
+ donor_groups = folds.loc[usable].groupby("donor_id")["group"].apply(lambda g: " ".join(map(str, g)))
57
+ stratum = donor_groups.str.contains(regex, regex=True) if regex else pd.Series(True, index=donor_groups.index)
58
+ out = ds / f"fewshot_n{a.n}"
59
+ out.mkdir(exist_ok=True)
60
+ raw = PD.RB.to_condition_counts(d["bulk"], d["bulk_valid"])
61
+ pseudo = PD.RB.to_condition_counts(d["pseudo"], d["sc_valid"])
62
+ man = {"dataset": a.dataset, "n": a.n, "draws": a.draws, "seed": a.seed, "strata_regex": regex,
63
+ "n_usable_rows": int(usable.size), "n_usable_donors": int(donor_groups.size),
64
+ "stratum_sizes": {str(k): int(v) for k, v in stratum.value_counts().items()}, "files": {}, "draw": {}}
65
+ man["files"]["all_usable_raw.npz"] = PD.write_npz(out / "all_usable_raw.npz", d, usable, raw, d["bulk_valid"],
66
+ a.cells_per_bulk, "raw")
67
+ man["files"]["all_usable_pseudo.npz"] = PD.write_npz(out / "all_usable_pseudo.npz", d, usable, pseudo, d["sc_valid"],
68
+ a.cells_per_bulk, "pseudo")
69
+ labels = sorted(set(stratum.tolist()))
70
+ sizes = {s: int((stratum == s).sum()) for s in labels}
71
+ total = sum(sizes.values())
72
+ for j in range(a.draws):
73
+ rng = np.random.default_rng(a.seed + j)
74
+ alloc = {s: max(1, int(np.floor(a.n * sizes[s] / total))) for s in labels}
75
+ while sum(alloc.values()) < a.n:
76
+ s = max(labels, key=lambda s: a.n * sizes[s] / total - alloc[s]); alloc[s] += 1
77
+ while sum(alloc.values()) > a.n:
78
+ s = max((s for s in labels if alloc[s] > 1), key=lambda s: alloc[s]); alloc[s] -= 1
79
+ chosen = []
80
+ for s in labels:
81
+ pool = np.asarray(sorted(stratum.index[stratum == s]))
82
+ chosen += pool[rng.permutation(pool.size)[:alloc[s]]].tolist()
83
+ train = folds.index[folds["donor_id"].astype(str).isin(chosen) & (folds["fold"] >= 0)].to_numpy()
84
+ test = np.setdiff1d(usable, train)
85
+ dd = out / f"draw{j}"
86
+ dd.mkdir(exist_ok=True)
87
+ (dd / "train_donors.txt").write_text("\n".join(chosen) + "\n")
88
+ (dd / "test_samples.txt").write_text("\n".join(d["sample_ids"][test]) + "\n")
89
+ # paired calibration with the same n pairs the LoRA sees: the zero-parameter comparator at equal data budget
90
+ valid = d["bulk_valid"][train].all(axis=0) & d["sc_valid"][train].all(axis=0)
91
+ alpha = PD.RB.gene_multiplier(d["bulk"][train], d["pseudo"][train], valid)
92
+ cal = PD.RB.to_condition_counts(PD.RB.cpm(d["bulk"]) * alpha[None, :], d["bulk_valid"])
93
+ np.save(dd / "alpha.npy", alpha)
94
+ for arm, arr, frac in (("raw", raw, d["bulk_valid"]), ("cal", cal, d["bulk_valid"])):
95
+ man["files"][f"draw{j}/test_{arm}.npz"] = PD.write_npz(dd / f"test_{arm}.npz", d, test, arr, frac,
96
+ a.cells_per_bulk, arm)
97
+ man["draw"][j] = {"train_donors": chosen, "n_train_rows": int(train.size), "n_test_rows": int(test.size),
98
+ "allocation": {str(k): int(v) for k, v in alloc.items()},
99
+ "test_groups": folds.loc[test, "group"].value_counts().to_dict(),
100
+ "alpha_genes_estimated": int((alpha != 1.0).sum())}
101
+ (out / "DRAWS.json").write_text(json.dumps(man, indent=1, default=str))
102
+ print(json.dumps({k: man[k] for k in ("dataset", "n", "n_usable_rows", "n_usable_donors", "stratum_sizes")}))
103
+ for j, v in man["draw"].items():
104
+ print(j, v["train_donors"], v["n_train_rows"], v["n_test_rows"], v["allocation"])
105
+ return 0
106
+
107
+
108
+ if __name__ == "__main__":
109
+ sys.exit(main())
paper-releases/20260928/diffusion/data/source_prep/giroux2022/code/giroux2022_assemble.py ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Assemble the Giroux 2022 COVID-19 paired bulk <-> scRNA fine-tuning files (CPU only).
3
+
4
+ Adapted from the Ye 2026 build (processing/ye2026_sepsis_v1_20260927/code/ye2026_assemble.py); same output
5
+ files, keys and semantics. Study-specific differences:
6
+ * one row = one subject-day (a subject has 2-3 rows); donor_ids = GEO subject, timepoints = GEO day;
7
+ * bulk genes are hg19 annotation symbols (no Ensembl IDs); RPS4Y1 is absent from the bulk table, so the bulk
8
+ Y score uses DDX3Y + UTY + KDM5D (sc keeps the 4-gene Ye score; a 3-gene sc score is reported alongside);
9
+ * the donor-sensitive expression test ranks SUBJECTS (a subject's other visit is the same person), removes
10
+ k = 5 sample PCs per modality (41 sc libraries / 49 bulks; k = 3 and 10 are sensitivity), and leaves chrY
11
+ genes out so that it is independent of the sex check.
12
+
13
+ Inputs (processing run, produced by giroux2022_pipeline.py):
14
+ pairing/sc_libraries_with_bulk_match.csv, pairing/bulk_count_columns.csv,
15
+ bulk/GSE206263_featureCounts/harmonized.h5ad, bulk/bulk_source_counts.npz,
16
+ singlecell/<GSM>/{canonical.h5ad, pseudobulk_per_published_sample.h5, source_axis_pseudobulk.npz,
17
+ cell_sex_gene_counts.npz, summary.json}
18
+ Outputs (OUT):
19
+ features.npz, cells_panel6k.npz, cells_obs.parquet, samples.csv, pairs.csv, identity_sex_bulk_all.csv,
20
+ identity_sex_sc_all.csv, identity_expression.csv, MANIFEST.json (QC_REPORT.md is written by hand)
21
+ Processing-run extras: identity/ (full residual correlation matrices, unpaired-healthy leads).
22
+
23
+ Rows = accepted pairs ordered by bulk GSM. Retained cells = flag_conservative_review_pass (qc_core: >= 200 genes,
24
+ >= 500 UMIs, <= 20 % mito), the ImMicro definition. Identity checks are reported, never used to drop rows.
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import hashlib
29
+ import json
30
+ import os
31
+ import shutil
32
+ import sys
33
+ from datetime import datetime, timezone
34
+ from pathlib import Path
35
+
36
+ import h5py
37
+ import numpy as np
38
+ import pandas as pd
39
+ import scipy.sparse as sp
40
+ from scipy.stats import rankdata
41
+
42
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
43
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
44
+
45
+ DATALAKE = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc")
46
+ RUN = DATALAKE / "processing/giroux2022_v1_20260928"
47
+ REFERENCE = DATALAKE / "processing/strict_qc_v1_20260913/reference"
48
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
49
+ OUT = M8 / "plans/paired_finetune_intradataset_20260927/data/giroux2022"
50
+ POSITIONS = M8 / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/gene_positions.npy"
51
+ POSITIONS_SHA = "653ffa45ac519000baa41086c52408009391d6e68cfb218bc6a50d34163fcb24"
52
+ SELECTED = POSITIONS.parent / "selected_genes.csv"
53
+ TMP = RUN / "assemble_tmp"
54
+ IDENT = RUN / "identity"
55
+ SEX_GENES = ["XIST", "RPS4Y1", "DDX3Y", "UTY", "KDM5D"]
56
+ SEX_IDS = {"XIST": "ENSG00000229807", "RPS4Y1": "ENSG00000129824", "DDX3Y": "ENSG00000067048",
57
+ "UTY": "ENSG00000183878", "KDM5D": "ENSG00000012817"}
58
+ Y_GENES = ["RPS4Y1", "DDX3Y", "UTY", "KDM5D"]
59
+ Y_GENES_BULK = ["DDX3Y", "UTY", "KDM5D"] # RPS4Y1 is not a row of the author bulk table
60
+ TOP_N = 2000
61
+ RESID_K = (5, 3, 10) # k = 5 primary; 3 and 10 sensitivity
62
+ K_PRIMARY = 5
63
+ SUBJ_TOP = 3 # verdict: own subject 1st in one direction and within the top 3 subjects in the other
64
+ ISG_GENES = ["IFI27", "IFI44L", "ISG15", "RSAD2", "IFIT1", "IFIT3", "MX1", "OAS1", "OAS3", "SIGLEC1", "IFI6", "HERC5"]
65
+
66
+
67
+ def sha256_file(path: Path) -> str:
68
+ h = hashlib.sha256()
69
+ with open(path, "rb") as f:
70
+ for block in iter(lambda: f.read(1 << 24), b""):
71
+ h.update(block)
72
+ return h.hexdigest()
73
+
74
+
75
+ def text(values) -> np.ndarray:
76
+ return np.asarray([v.decode() if isinstance(v, bytes) else str(v) for v in values])
77
+
78
+
79
+ def require(ok: bool, msg: str) -> None:
80
+ if not ok:
81
+ raise SystemExit(msg)
82
+
83
+
84
+ def sex_call(xist_cpm: float, y_cpm: float) -> tuple[str, float]:
85
+ """female if log2(XIST+1)-log2(Ysum+1) > 2, male if < -2, else ambiguous (the Ye 2026 rule)."""
86
+ score = float(np.log2(xist_cpm + 1) - np.log2(y_cpm + 1))
87
+ return ("female" if score > 2 else "male" if score < -2 else "ambiguous"), score
88
+
89
+
90
+ def spearman_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:
91
+ ra = rankdata(a, axis=1)
92
+ rb = rankdata(b, axis=1)
93
+ ra = (ra - ra.mean(1, keepdims=True)) / ra.std(1, keepdims=True)
94
+ rb = (rb - rb.mean(1, keepdims=True)) / rb.std(1, keepdims=True)
95
+ return ra @ rb.T / a.shape[1]
96
+
97
+
98
+ def pearson_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:
99
+ a = (a - a.mean(1, keepdims=True)) / a.std(1, keepdims=True)
100
+ b = (b - b.mean(1, keepdims=True)) / b.std(1, keepdims=True)
101
+ return a @ b.T / a.shape[1]
102
+
103
+
104
+ def subject_rank(scores: np.ndarray, subjects: np.ndarray, own: str) -> tuple[int, str, float]:
105
+ """Rank of subject `own` when every subject is scored by its best-matching sample (1 = best)."""
106
+ best = pd.Series(scores).groupby(subjects).max().sort_values(ascending=False, kind="mergesort")
107
+ return int(np.flatnonzero(best.index.to_numpy() == own)[0]) + 1, str(best.index[0]), float(best.iloc[0])
108
+
109
+
110
+ def main() -> int:
111
+ t0 = datetime.now(timezone.utc)
112
+ require(sha256_file(POSITIONS) == POSITIONS_SHA, "gene_positions.npy sha differs from the final run's")
113
+ positions = np.load(POSITIONS).astype(np.int64)
114
+ canonical = pd.read_csv(REFERENCE / "canonical_genes.tsv", sep="\t", dtype=str)
115
+ gene_ids = canonical.gene_id.to_numpy().astype("U15")
116
+ require(gene_ids.dtype.kind == "U" and all(len(x) == 15 for x in gene_ids), "gene id dtype")
117
+ require(len(gene_ids) == 20097 and canonical.panel_index.astype(int).tolist() == list(range(20097)), "axis")
118
+ chr_y = canonical.chromosome.astype(str).isin(["Y", "chrY"]).to_numpy()
119
+ selected = pd.read_csv(SELECTED)
120
+ require(np.array_equal(selected.gene_id.to_numpy(), gene_ids[positions]), "panel ids differ from positions")
121
+
122
+ table = pd.read_csv(RUN / "pairing/sc_libraries_with_bulk_match.csv", dtype=str, keep_default_na=False)
123
+ cols = pd.read_csv(RUN / "pairing/bulk_count_columns.csv", dtype=str, keep_default_na=False)
124
+ summaries = {g: json.loads((RUN / "singlecell" / g / "summary.json").read_text()) for g in table.sc_gsm}
125
+ bad = [g for g, s in summaries.items() if s["status"] != "PASS"]
126
+ pairs = table[table.paired == "True"].copy()
127
+ quarantined_pairs = sorted(set(bad) & set(pairs.sc_gsm))
128
+ pairs = pairs[~pairs.sc_gsm.isin(bad)].sort_values("bulk_gsm").reset_index(drop=True)
129
+ n = len(pairs)
130
+
131
+ # ---------------- bulk (canonical, harmonized by qc_bulk.harmonize)
132
+ import anndata as ad
133
+ bad_ = ad.read_h5ad(RUN / "bulk/GSE206263_featureCounts/harmonized.h5ad")
134
+ bX = np.asarray(bad_.X, dtype=np.float64)
135
+ b_valid = np.asarray(bad_.layers["harmonization_valid"]).astype(bool)
136
+ b_index = bad_.obs_names.to_numpy().astype(str) # author column names
137
+ b_gsm = bad_.obs["source_GSM"].astype(str).to_numpy() # '' for the 6 columns without a GEO GSM
138
+ require(np.array_equal(bad_.var_names.to_numpy().astype(str), gene_ids), "bulk gene order")
139
+ require(str(bad_.uns["units"]) == "featureCounts_raw_gene_counts", "bulk units")
140
+ require(bool(bad_.uns["raw_count_eligible"]), "bulk not raw-count eligible")
141
+ del bad_
142
+ bcol = {c: i for i, c in enumerate(b_index)}
143
+ require(len(bcol) == len(b_index), "duplicate bulk column")
144
+ inside = bX[b_valid]
145
+ require(np.isfinite(inside).all() and (inside >= 0).all() and np.array_equal(inside, np.rint(inside)),
146
+ "bulk values inside the measured mask must be nonnegative integers")
147
+ require(np.isnan(bX[~b_valid]).all(), "bulk values outside the mask must be NaN in the harmonized file")
148
+ bulk_all = np.where(b_valid, bX, 0.0)
149
+ b_subject = cols.set_index("bulk_column").loc[b_index, "subject"].to_numpy()
150
+ b_label = np.asarray([c for c in b_index])
151
+
152
+ # ---------------- sc per library: pseudobulk sums and masks for every PASS library
153
+ sc_gsms = [g for g in table.sc_gsm if summaries[g]["status"] == "PASS"]
154
+ sc_meta = table.set_index("sc_gsm")
155
+ s_subject = sc_meta.loc[sc_gsms, "subject"].to_numpy()
156
+ s_label = sc_meta.loc[sc_gsms, "sample_id"].to_numpy()
157
+ sc_sum = np.zeros((len(sc_gsms), 20097))
158
+ sc_valid_all = np.zeros((len(sc_gsms), 20097), dtype=bool)
159
+ sc_n = np.zeros(len(sc_gsms), dtype=np.int64)
160
+ for i, g in enumerate(sc_gsms):
161
+ with h5py.File(RUN / "singlecell" / g / "pseudobulk_per_published_sample.h5", "r") as f:
162
+ require(np.array_equal(text(f["gene_id"][:]), gene_ids), f"{g}: gene order")
163
+ require(len(f["sample_id"]) == 1, f"{g}: exactly one sample per library")
164
+ require(text(f["sample_id"][:])[0] == s_label[i], f"{g}: sample id")
165
+ require(f.attrs["units"] == "UMI_counts", f"{g}: units")
166
+ sc_sum[i] = f["qc_review_pass_cells_sum"][0]
167
+ sc_valid_all[i] = f["harmonization_valid"][:].astype(bool)
168
+ sc_n[i] = int(f["n_cells"][1, 0])
169
+ require(np.array_equal(sc_sum[i], np.rint(sc_sum[i])) and (sc_sum[i] >= 0).all(), f"{g}: noninteger sum")
170
+ require((sc_sum[i][~sc_valid_all[i]] == 0).all(), f"{g}: mass outside the measured mask")
171
+ srow = {g: i for i, g in enumerate(sc_gsms)}
172
+
173
+ # ---------------- per-pair feature rows
174
+ bi = np.asarray([bcol[c] for c in pairs.bulk_count_column])
175
+ si = np.asarray([srow[g] for g in pairs.sc_gsm])
176
+ require(np.array_equal(b_gsm[bi], pairs.bulk_gsm.to_numpy()), "bulk column -> GSM join")
177
+ require(np.array_equal(b_subject[bi], pairs.subject.to_numpy()), "bulk subject join")
178
+ bulk_raw = bulk_all[bi]
179
+ bulk_valid = b_valid[bi]
180
+ pseudo_raw_sum = sc_sum[si]
181
+ sc_valid = sc_valid_all[si]
182
+ qc_cell_counts = sc_n[si]
183
+
184
+ # ---------------- sex check (source axis; XIST is not protein-coding)
185
+ bsrc = np.load(RUN / "bulk/bulk_source_counts.npz")
186
+ bids = list(bsrc["gene_ids"])
187
+ bcounts = bsrc["counts"]
188
+ require(list(bsrc["sample_ids"]) == list(b_index), "bulk source-axis sample order")
189
+ bcpm = bcounts / bcounts.sum(1, keepdims=True) * 1e6
190
+ sex_rows = []
191
+ for g in sc_gsms:
192
+ z = np.load(RUN / "singlecell" / g / "source_axis_pseudobulk.npz")
193
+ fid = list(z["feature_ids"])
194
+ tot = z["qc_pass_sum"][z["rna"]].sum()
195
+ rec = {"sc_gsm": g}
196
+ for gene in SEX_GENES:
197
+ rec["sc_" + gene + "_cpm"] = float(z["qc_pass_sum"][fid.index(SEX_IDS[gene])] / tot * 1e6)
198
+ rec["sc_Ysum_cpm"] = sum(rec["sc_" + x + "_cpm"] for x in Y_GENES)
199
+ rec["sc_Ysum3_cpm"] = sum(rec["sc_" + x + "_cpm"] for x in Y_GENES_BULK)
200
+ rec["sc_sex_call"], rec["sc_sex_score"] = sex_call(rec["sc_XIST_cpm"], rec["sc_Ysum_cpm"])
201
+ rec["sc_sex_call_3gene"], rec["sc_sex_score_3gene"] = sex_call(rec["sc_XIST_cpm"], rec["sc_Ysum3_cpm"])
202
+ sex_rows.append(rec)
203
+ sc_sex = pd.DataFrame(sex_rows).set_index("sc_gsm")
204
+ bulk_sex_rows = []
205
+ for j, c in enumerate(b_index):
206
+ rec = {"bulk_column": c, "bulk_gsm": b_gsm[j]}
207
+ for gene in SEX_GENES:
208
+ rec["bulk_" + gene + "_cpm"] = float(bcpm[j, bids.index(gene)]) if gene in bids else np.nan
209
+ rec["bulk_Ysum_cpm"] = sum(rec["bulk_" + x + "_cpm"] for x in Y_GENES_BULK)
210
+ rec["bulk_sex_call"], rec["bulk_sex_score"] = sex_call(rec["bulk_XIST_cpm"], rec["bulk_Ysum_cpm"])
211
+ bulk_sex_rows.append(rec)
212
+ bulk_sex = pd.DataFrame(bulk_sex_rows).set_index("bulk_column")
213
+
214
+ # ---------------- expression identity: every bulk column vs every sc pseudobulk (retained cells)
215
+ common = b_valid.all(0) & sc_valid_all.all(0) & ~chr_y
216
+
217
+ def logcpm(m: np.ndarray) -> np.ndarray:
218
+ x = m[:, common]
219
+ return np.log2(x / x.sum(1, keepdims=True) * 1e6 + 1)
220
+
221
+ lb_all, ls_all = logcpm(bulk_all), logcpm(sc_sum)
222
+ mean_score = 0.5 * (lb_all.mean(0) + ls_all.mean(0))
223
+ top = np.argsort(-mean_score, kind="mergesort")[:TOP_N]
224
+ rho = spearman_matrix(lb_all[bi][:, top], ls_all[:, top]) # paired bulks x all sc
225
+ rho_rev = spearman_matrix(ls_all[si][:, top], lb_all[:, top]) # paired sc x all bulks
226
+ cb = lb_all - lb_all.mean(0)
227
+ cs = ls_all - ls_all.mean(0)
228
+ rho_c = spearman_matrix(cb[bi][:, top], cs[:, top]) # modality-centred sensitivity
229
+ rho_c_rev = spearman_matrix(cs[si][:, top], cb[:, top])
230
+ expr = []
231
+ for r in range(n):
232
+ own = si[r]
233
+ order = np.argsort(-rho[r]); order_c = np.argsort(-rho_c[r])
234
+ rev = np.argsort(-rho_rev[r]); rev_c = np.argsort(-rho_c_rev[r])
235
+ expr.append({"sample_id": pairs.sample_id[r], "bulk_gsm": pairs.bulk_gsm[r], "sc_gsm": pairs.sc_gsm[r],
236
+ "rho_own": rho[r, own], "best_sc_gsm": sc_gsms[order[0]], "rho_best": rho[r, order[0]],
237
+ "own_rank_among_sc": int(np.flatnonzero(order == own)[0]) + 1,
238
+ "best_is_own": bool(order[0] == own),
239
+ "rho_second": rho[r, order[1]],
240
+ "centred_rho_own": rho_c[r, own], "centred_best_sc_gsm": sc_gsms[order_c[0]],
241
+ "centred_own_rank_among_sc": int(np.flatnonzero(order_c == own)[0]) + 1,
242
+ "centred_best_is_own": bool(order_c[0] == own),
243
+ "reverse_best_bulk": b_label[rev[0]], "reverse_own_rank_among_bulk": int(np.flatnonzero(rev == bi[r])[0]) + 1,
244
+ "reverse_best_is_own": bool(rev[0] == bi[r]),
245
+ "centred_reverse_best_bulk": b_label[rev_c[0]],
246
+ "centred_reverse_own_rank_among_bulk": int(np.flatnonzero(rev_c == bi[r])[0]) + 1,
247
+ "centred_reverse_best_is_own": bool(rev_c[0] == bi[r])})
248
+ expr = pd.DataFrame(expr)
249
+
250
+ # Residualised donor-identity test (unsupervised w.r.t. pairing): within each modality centre log CPM, remove
251
+ # the top-k sample PCs (computed on expressed genes), keep the 2,000 genes with the highest residual variance
252
+ # in both modalities, Pearson. Ranks are reported per library and per subject (best library of a subject).
253
+ expressed = (lb_all.mean(0) > 3) & (ls_all.mean(0) > 1)
254
+ ex = np.flatnonzero(expressed)
255
+
256
+ def resid(x: np.ndarray, k: int) -> np.ndarray:
257
+ xc = x - x.mean(0)
258
+ u = np.linalg.svd(xc[:, ex], full_matrices=False)[0][:, :k]
259
+ return xc - u @ (u.T @ xc)
260
+
261
+ IDENT.mkdir(exist_ok=True)
262
+ full_fw = {}
263
+ for k in RESID_K:
264
+ rb_, rs_ = resid(lb_all, k), resid(ls_all, k)
265
+ vb = np.where(expressed, rb_.var(0), -1.0); vs = np.where(expressed, rs_.var(0), -1.0)
266
+ sel = np.argsort(rankdata(-vb) + rankdata(-vs), kind="mergesort")[:TOP_N]
267
+ fw_all = pearson_matrix(rb_[:, sel], rs_[:, sel]) # all 49 bulks x all 41 sc
268
+ full_fw[k] = fw_all
269
+ pd.DataFrame(fw_all, index=b_label, columns=[f"{g}|{s}" for g, s in zip(sc_gsms, s_label)]).to_csv(
270
+ IDENT / f"residual_k{k}_pearson_bulk_x_sc.csv")
271
+ fw = fw_all[bi]; bw = fw_all[:, si].T
272
+ c = {x: [] for x in ("lib_b2s", "lib_s2b", "subj_b2s", "subj_s2b", "best_sc", "best_subj_b2s",
273
+ "best_subj_s2b", "r_own", "r_best", "day_b2s", "day_s2b", "n_days")}
274
+ for r in range(n):
275
+ o = np.argsort(-fw[r]); o2 = np.argsort(-bw[r])
276
+ subj = pairs.subject[r]
277
+ c["lib_b2s"].append(int(np.flatnonzero(o == si[r])[0]) + 1)
278
+ c["lib_s2b"].append(int(np.flatnonzero(o2 == bi[r])[0]) + 1)
279
+ rk, best, _ = subject_rank(fw[r], s_subject, subj); c["subj_b2s"].append(rk); c["best_subj_b2s"].append(best)
280
+ rk, best, _ = subject_rank(bw[r], b_subject, subj); c["subj_s2b"].append(rk); c["best_subj_s2b"].append(best)
281
+ c["best_sc"].append(sc_gsms[o[0]]); c["r_own"].append(float(fw[r, si[r]])); c["r_best"].append(float(fw[r, o[0]]))
282
+ # within-subject day check: among this subject's paired libraries / bulks, is the own day the best?
283
+ own_s = np.flatnonzero((s_subject == subj) & np.isin(np.arange(len(sc_gsms)), si))
284
+ own_b = np.flatnonzero((b_subject == subj) & np.isin(np.arange(len(b_index)), bi))
285
+ c["day_b2s"].append(int((fw[r, own_s] > fw[r, si[r]]).sum()) + 1)
286
+ c["day_s2b"].append(int((bw[r, own_b] > bw[r, bi[r]]).sum()) + 1)
287
+ c["n_days"].append(len(own_s))
288
+ for key, name in (("lib_b2s", "own_rank_bulk_to_sc"), ("lib_s2b", "own_rank_sc_to_bulk"),
289
+ ("subj_b2s", "own_subject_rank_bulk_to_sc"), ("subj_s2b", "own_subject_rank_sc_to_bulk"),
290
+ ("best_sc", "best_sc_gsm"), ("best_subj_b2s", "best_subject_bulk_to_sc"),
291
+ ("best_subj_s2b", "best_subject_sc_to_bulk"), ("r_own", "r_own"), ("r_best", "r_best"),
292
+ ("day_b2s", "own_day_rank_within_subject_bulk_to_sc"),
293
+ ("day_s2b", "own_day_rank_within_subject_sc_to_bulk"), ("n_days", "subject_paired_days")):
294
+ expr[f"resid_k{k}_{name}"] = c[key]
295
+
296
+ # Day check on disease-state signal (centred, NOT residualised): within the subject's paired rows only.
297
+ vb = cb.var(0); vs = cs.var(0)
298
+ selc = np.argsort(rankdata(-np.where(expressed, vb, -1)) + rankdata(-np.where(expressed, vs, -1)), kind="mergesort")[:TOP_N]
299
+ cfw = pearson_matrix(cb[:, selc], cs[:, selc])
300
+ dd1, dd2 = [], []
301
+ for r in range(n):
302
+ subj = pairs.subject[r]
303
+ rows_subj = np.flatnonzero(pairs.subject.to_numpy() == subj)
304
+ dd1.append(int((cfw[bi[r], si[rows_subj]] > cfw[bi[r], si[r]]).sum()) + 1)
305
+ dd2.append(int((cfw[bi[rows_subj], si[r]] > cfw[bi[r], si[r]]).sum()) + 1)
306
+ expr["centred_own_day_rank_within_subject_bulk_to_sc"] = dd1
307
+ expr["centred_own_day_rank_within_subject_sc_to_bulk"] = dd2
308
+
309
+ # Interferon-stimulated-gene score (informational day evidence): mean log2(CPM+1) of a fixed ISG set on the
310
+ # canonical axis, per bulk column and per sc library. Early COVID-19 should peak at day 0 in both assays.
311
+ sym = canonical.gene_symbol.astype(str).to_numpy()
312
+ isg_idx = np.flatnonzero(np.isin(sym, ISG_GENES))
313
+ require(len(isg_idx) == len(ISG_GENES), "ISG genes missing from the canonical axis")
314
+ require(bool(b_valid[:, isg_idx].all() and sc_valid_all[:, isg_idx].all()), "ISG genes not measured everywhere")
315
+ isg_b = np.log2(bulk_all[:, isg_idx] / bulk_all.sum(1, keepdims=True) * 1e6 + 1).mean(1)
316
+ isg_s = np.log2(sc_sum[:, isg_idx] / sc_sum.sum(1, keepdims=True) * 1e6 + 1).mean(1)
317
+ expr["isg_score_bulk"] = isg_b[bi]
318
+ expr["isg_score_sc"] = isg_s[si]
319
+ peak_b, peak_s = {}, {}
320
+ for subj in pairs.subject.unique():
321
+ rows_subj = np.flatnonzero(pairs.subject.to_numpy() == subj)
322
+ peak_b[subj] = pairs.day[rows_subj[np.argmax(isg_b[bi[rows_subj]])]]
323
+ peak_s[subj] = pairs.day[rows_subj[np.argmax(isg_s[si[rows_subj]])]]
324
+ expr["isg_peak_day_bulk"] = [peak_b[s] for s in pairs.subject]
325
+ expr["isg_peak_day_sc"] = [peak_s[s] for s in pairs.subject]
326
+
327
+ # Leads only (no pairing): unpaired bulk columns without a GEO GSM vs unpaired sc libraries, primary k.
328
+ fw_all = full_fw[K_PRIMARY]
329
+ unpaired_sc = [i for i in range(len(sc_gsms)) if i not in set(si)]
330
+ no_gsm_cols = [j for j in range(len(b_index)) if b_gsm[j] == ""]
331
+ # positional counterpart: healthy rows of the author sample sheet vs healthy bulk GSMs in GEO order
332
+ sheet = pd.read_csv(RUN / "extracted/GSE206263/bulk_RNA-seq_sample_metadata.tsv", sep="\t", dtype=str, keep_default_na=False)
333
+ sheet_healthy = sheet[sheet.Cohort == "Healthy"].SampleID.tolist()
334
+ geo_b = pd.read_csv(RUN / "pairing/GSE206263_samples.csv", dtype=str, keep_default_na=False).sort_values("gsm")
335
+ geo_healthy = geo_b[geo_b.ch_exposure == "Healthy"].subject.tolist()
336
+ require(len(sheet_healthy) == len(geo_healthy), "healthy counts differ between author sheet and GEO")
337
+ same_position = dict(zip(sheet_healthy, geo_healthy))
338
+ leads = []
339
+ for j in no_gsm_cols:
340
+ o = np.argsort(-fw_all[j])
341
+ best = o[0]
342
+ rev = np.argsort(-fw_all[:, best])
343
+ leads.append({"bulk_column": b_label[j], "bulk_sex_call": bulk_sex.loc[b_label[j], "bulk_sex_call"],
344
+ "best_sc_gsm": sc_gsms[best], "best_sc_sample": s_label[best],
345
+ "best_sc_sex_call": sc_sex.loc[sc_gsms[best], "sc_sex_call"],
346
+ "best_sc_geo_sex": sc_meta.loc[sc_gsms[best], "sc_sex"],
347
+ "best_sc_is_unpaired": bool(best in unpaired_sc), "r_best": float(fw_all[j, best]),
348
+ "r_second": float(fw_all[j, o[1]]), "second_sc_sample": s_label[o[1]],
349
+ "reverse_rank_of_this_bulk_for_best_sc": int(np.flatnonzero(rev == j)[0]) + 1,
350
+ "reverse_best_bulk_for_best_sc": b_label[rev[0]],
351
+ "geo_healthy_subject_at_same_position_in_author_sheet": same_position.get(b_label[j], ""),
352
+ "position_agrees_with_best_sc_subject": same_position.get(b_label[j], "") == s_subject[best]})
353
+ leads = pd.DataFrame(leads)
354
+ leads.to_csv(IDENT / f"leads_bulk_columns_without_gsm_k{K_PRIMARY}.csv", index=False)
355
+
356
+ # ---------------- cells on the 6k panel (two passes: per-library temp files, then one CSR)
357
+ TMP.mkdir(exist_ok=True)
358
+ nnz_per, obs_blocks = [], []
359
+ for r in range(n):
360
+ g = pairs.sc_gsm[r]
361
+ h5 = RUN / "singlecell" / g / "canonical.h5ad"
362
+ with h5py.File(h5, "r") as f:
363
+ X = f["X"]
364
+ ncell = len(X["indptr"]) - 1
365
+ full = sp.csr_matrix((X["data"][:], X["indices"][:], X["indptr"][:]), shape=(ncell, 20097))
366
+ o = f["obs"]
367
+ keep = o["flag_conservative_review_pass"][:].astype(bool)
368
+ obs = pd.DataFrame({"cell_index": np.arange(ncell), "barcode": text(o["_index"][:]),
369
+ "raw_gex_total": o["cell_total"][:], "n_genes": o["cell_detected"][:],
370
+ "mito_pct": o["cell_mito_percent"][:],
371
+ "flag_low_total_mad": o["flag_low_total_mad"][:].astype(bool),
372
+ "flag_low_genes_mad": o["flag_low_genes_mad"][:].astype(bool),
373
+ "flag_high_mito_mad": o["flag_high_mito_mad"][:].astype(bool),
374
+ "flag_high_total_review_only": o["flag_high_total_review_only"][:].astype(bool)})
375
+ require(np.array_equal(text(o["sample_id"][:]), np.full(ncell, pairs.sample_id[r])), f"{g}: sample id")
376
+ require(int(keep.sum()) == qc_cell_counts[r], f"{g}: retained-cell count differs from pseudobulk file")
377
+ kept = full[np.flatnonzero(keep)]
378
+ require(np.array_equal(np.asarray(kept.sum(0)).ravel(), pseudo_raw_sum[r]), f"{g}: canonical sum differs")
379
+ sub = kept[:, positions].tocsr()
380
+ sub.sort_indices()
381
+ require(np.array_equal(sub.data, np.rint(sub.data)) and (sub.data >= 0).all() and
382
+ (sub.data.max(initial=0) < 2**31), f"{g}: non-integer or overflowing counts")
383
+ require(np.array_equal(np.asarray(sub.sum(0)).ravel(), pseudo_raw_sum[r, positions]), f"{g}: panel sum")
384
+ np.save(TMP / f"{r:03d}_data.npy", sub.data.astype(np.int32))
385
+ np.save(TMP / f"{r:03d}_indices.npy", sub.indices.astype(np.int32))
386
+ np.save(TMP / f"{r:03d}_indptr.npy", sub.indptr.astype(np.int64))
387
+ sx = np.load(RUN / "singlecell" / g / "cell_sex_gene_counts.npz")
388
+ require(list(sx["genes"]) == SEX_GENES and sx["found"].all(), f"{g}: sex genes")
389
+ obs = obs[keep].reset_index(drop=True)
390
+ obs["cell_total_canonical"] = np.asarray(kept.sum(1)).ravel()
391
+ obs["lib_panel"] = np.asarray(sub.sum(1)).ravel()
392
+ for k, gene in enumerate(SEX_GENES):
393
+ obs[("xist" if gene == "XIST" else "y_" + gene)] = sx["counts"][k][keep]
394
+ obs["y_sum"] = obs[["y_" + x for x in Y_GENES]].sum(1)
395
+ obs.insert(2, "library_id", g)
396
+ obs.insert(3, "sample_id", pairs.sample_id[r])
397
+ obs.insert(4, "donor_id", pairs.subject[r])
398
+ obs.insert(5, "group", pairs.group[r])
399
+ obs["author_cell_type"] = ""
400
+ obs["row_sample"] = np.int32(r)
401
+ obs_blocks.append(obs)
402
+ nnz_per.append(sub.nnz)
403
+ print(f"{g} {pairs.sample_id[r]}: {sub.shape[0]} cells, nnz {sub.nnz}", flush=True)
404
+ del full, kept, sub
405
+ total_nnz = int(sum(nnz_per))
406
+ total_cells = int(qc_cell_counts.sum())
407
+ data = np.lib.format.open_memmap(TMP / "all_data.npy", mode="w+", dtype=np.int32, shape=(total_nnz,))
408
+ indices = np.lib.format.open_memmap(TMP / "all_indices.npy", mode="w+", dtype=np.int32, shape=(total_nnz,))
409
+ indptr = np.empty(total_cells + 1, dtype=np.int64)
410
+ indptr[0] = 0
411
+ at, cell_at = 0, 0
412
+ for r in range(n):
413
+ d = np.load(TMP / f"{r:03d}_data.npy"); ix = np.load(TMP / f"{r:03d}_indices.npy")
414
+ ip = np.load(TMP / f"{r:03d}_indptr.npy")
415
+ data[at:at + len(d)] = d
416
+ indices[at:at + len(d)] = ix
417
+ indptr[cell_at + 1:cell_at + len(ip)] = ip[1:] + at
418
+ at += len(d); cell_at += len(ip) - 1
419
+ require(at == total_nnz and cell_at == total_cells, "assembly size")
420
+ cobs = pd.concat(obs_blocks, ignore_index=True)
421
+ row_sample = cobs.row_sample.to_numpy(np.int32)
422
+ # Fail-closed re-check on the assembled matrix.
423
+ require(np.all(np.diff(row_sample) >= 0), "cells must be grouped by row")
424
+ require(np.array_equal(np.bincount(row_sample, minlength=n), qc_cell_counts), "assembled cell counts")
425
+ starts = np.concatenate([[0], np.cumsum(qc_cell_counts)])
426
+ for r in range(n):
427
+ a, b = indptr[starts[r]], indptr[starts[r + 1]]
428
+ s_r = np.bincount(indices[a:b], weights=data[a:b].astype(np.float64), minlength=len(positions))
429
+ require(np.array_equal(s_r, pseudo_raw_sum[r, positions]), f"row {r}: assembled panel sum differs")
430
+ require(np.all(np.diff(indptr) >= 0) and indptr[-1] == total_nnz, "indptr")
431
+
432
+ # ---------------- write
433
+ OUT.mkdir(parents=True, exist_ok=True)
434
+ bmeta = pd.read_csv(RUN / "pairing/GSE206263_samples.csv", dtype=str, keep_default_na=False).set_index("gsm")
435
+ meta_arrays = {
436
+ "gene_ids": gene_ids, "sample_ids": pairs.sample_id.to_numpy().astype(str),
437
+ "donor_ids": pairs.subject.to_numpy().astype(str), "groups": pairs.group.to_numpy().astype(str),
438
+ "timepoints": pairs.day.astype(np.int64).to_numpy(),
439
+ "bulk_raw": bulk_raw.astype(np.float64), "pseudo_raw_sum": pseudo_raw_sum.astype(np.float64),
440
+ "bulk_valid": bulk_valid, "sc_valid": sc_valid, "pair_valid": bulk_valid & sc_valid,
441
+ "qc_cell_counts": qc_cell_counts.astype(np.int64),
442
+ "bulk_gsm": pairs.bulk_gsm.to_numpy().astype(str), "sc_gsm": pairs.sc_gsm.to_numpy().astype(str),
443
+ "sc_title_sample_id": pairs.sc_title.to_numpy().astype(str),
444
+ "id_match": np.full(n, "exact_subject_day").astype(str),
445
+ "bulk_count_column": pairs.bulk_count_column.to_numpy().astype(str),
446
+ "sc_author_library": pairs.author_library.to_numpy().astype(str),
447
+ "sex_geo": pairs.sc_sex.to_numpy().astype(str), "age_geo": pairs.sc_age.to_numpy().astype(str),
448
+ "serostatus_geo": pairs.sc_serostatus.to_numpy().astype(str),
449
+ "author_cohort": cols.set_index("bulk_column").loc[pairs.bulk_count_column, "author_cohort"].to_numpy().astype(str),
450
+ }
451
+ require(np.array_equal(bmeta.loc[pairs.bulk_gsm, "ch_serostatus"].to_numpy(), pairs.sc_serostatus.to_numpy()),
452
+ "serostatus differs between bulk and sc GSM")
453
+ panel_gene_ids = gene_ids[positions]
454
+ tmp = OUT / "cells_panel6k.npz.tmp"
455
+ with open(tmp, "wb") as h:
456
+ np.savez_compressed(h, data=data, indices=indices, indptr=indptr,
457
+ shape=np.array([total_cells, len(positions)], dtype=np.int64), row_sample=row_sample,
458
+ panel_gene_ids=panel_gene_ids, panel_measured=sc_valid[:, positions])
459
+ os.replace(tmp, OUT / "cells_panel6k.npz")
460
+ cobs.to_parquet(OUT / "cells_obs.parquet", index=False)
461
+ pd.DataFrame({"row": np.arange(n), "sample_id": meta_arrays["sample_ids"], "donor_id": meta_arrays["donor_ids"],
462
+ "group": meta_arrays["groups"], "n_cells": qc_cell_counts}).to_csv(OUT / "samples.csv", index=False)
463
+
464
+ # pairs.csv with identity results
465
+ p = pairs[["sample_id", "bulk_gsm", "sc_gsm", "subject", "bulk_title", "sc_title", "bulk_count_column",
466
+ "author_library", "group", "day", "sc_sex", "sc_age", "sc_serostatus"]].copy()
467
+ p = p.rename(columns={"subject": "donor_id", "author_library": "sc_author_library", "day": "timepoint",
468
+ "sc_sex": "sex_geo", "sc_age": "age_geo", "sc_serostatus": "serostatus_geo"})
469
+ p.insert(4, "row", np.arange(n))
470
+ p.insert(7, "id_match", "exact_subject_day")
471
+ p["author_cohort"] = meta_arrays["author_cohort"]
472
+ p["n_cells_library"] = [summaries[g]["n_cells"] for g in p.sc_gsm]
473
+ p["n_cells_retained"] = qc_cell_counts
474
+ p["bulk_assigned_counts"] = bcounts[bi].sum(1)
475
+ p["bulk_canonical_counts"] = bulk_raw.sum(1)
476
+ p["sc_retained_umis_canonical"] = pseudo_raw_sum.sum(1)
477
+ for c in ("bulk_XIST_cpm", "bulk_Ysum_cpm", "bulk_sex_score", "bulk_sex_call"):
478
+ p[c] = bulk_sex.loc[p.bulk_count_column, c].to_numpy()
479
+ for c in ("sc_XIST_cpm", "sc_Ysum_cpm", "sc_sex_score", "sc_sex_call", "sc_Ysum3_cpm", "sc_sex_call_3gene"):
480
+ p[c] = sc_sex.loc[p.sc_gsm, c].to_numpy()
481
+ geo = p.sex_geo.str.lower()
482
+ p["sex_concordant"] = (p.bulk_sex_call == p.sc_sex_call) & (p.sc_sex_call == geo)
483
+ p["bulk_possible_mixture"] = ((p.bulk_sex_call == "female") & (p.bulk_Ysum_cpm > 20)) | \
484
+ ((p.bulk_sex_call == "male") & (p.bulk_XIST_cpm > 50))
485
+ e = expr.set_index("bulk_gsm")
486
+ for c in ("rho_own", "rho_best", "own_rank_among_sc", "best_is_own", "best_sc_gsm", "centred_own_rank_among_sc",
487
+ "centred_best_is_own", "reverse_own_rank_among_bulk", "reverse_best_is_own",
488
+ "centred_own_day_rank_within_subject_bulk_to_sc", "centred_own_day_rank_within_subject_sc_to_bulk",
489
+ "isg_score_bulk", "isg_score_sc", "isg_peak_day_bulk", "isg_peak_day_sc"):
490
+ p["expr_" + c] = e.loc[p.bulk_gsm, c].to_numpy()
491
+ for k in RESID_K:
492
+ for c in ("own_rank_bulk_to_sc", "own_rank_sc_to_bulk", "own_subject_rank_bulk_to_sc",
493
+ "own_subject_rank_sc_to_bulk", "best_subject_bulk_to_sc", "best_subject_sc_to_bulk",
494
+ "best_sc_gsm", "r_own", "r_best", "own_day_rank_within_subject_bulk_to_sc",
495
+ "own_day_rank_within_subject_sc_to_bulk", "subject_paired_days"):
496
+ p[f"expr_resid_k{k}_{c}"] = e.loc[p.bulk_gsm, f"resid_k{k}_{c}"].to_numpy()
497
+ kp = K_PRIMARY
498
+
499
+ def day_ranks(row) -> tuple[int, int, int, int]:
500
+ return (row[f"expr_resid_k{kp}_own_day_rank_within_subject_bulk_to_sc"],
501
+ row[f"expr_resid_k{kp}_own_day_rank_within_subject_sc_to_bulk"],
502
+ row.expr_centred_own_day_rank_within_subject_bulk_to_sc,
503
+ row.expr_centred_own_day_rank_within_subject_sc_to_bulk)
504
+
505
+ def verdict(row) -> str:
506
+ """pass: sex concordant AND (residualised, k=5) own SUBJECT ranked 1st in one direction and within the top 3
507
+ subjects in the other AND no day failure. fail: sex discordant, or own subject ranked below 3rd in both
508
+ directions, or a day failure = within the subject's paired rows another day beats the own day in BOTH
509
+ directions on BOTH the residualised (k=5) and the centred expression test. Otherwise borderline.
510
+ (A subject's other visit is the same person, so subjects are ranked for the donor test and days are
511
+ checked separately within the subject.)"""
512
+ r1 = row[f"expr_resid_k{kp}_own_subject_rank_bulk_to_sc"]
513
+ r2 = row[f"expr_resid_k{kp}_own_subject_rank_sc_to_bulk"]
514
+ d1, d2, c1, c2 = day_ranks(row)
515
+ issues = []
516
+ if not row.sex_concordant:
517
+ issues.append(f"sex bulk={row.bulk_sex_call} sc={row.sc_sex_call} geo={row.sex_geo.lower()}")
518
+ if min(r1, r2) > SUBJ_TOP:
519
+ issues.append(f"expression: own subject rank {r1} (bulk->{len(set(s_subject))} sc subjects) and {r2} "
520
+ f"(sc->{len(set(b_subject))} bulk subjects); bulk best subject = "
521
+ f"{row[f'expr_resid_k{kp}_best_subject_bulk_to_sc']}")
522
+ if min(d1, d2, c1, c2) > 1:
523
+ issues.append(f"day: within subject {row.donor_id}, own day {row.timepoint} ranks {d1}/{d2} (residualised "
524
+ f"k={kp}, bulk->sc/sc->bulk) and {c1}/{c2} (centred) among {row[f'expr_resid_k{kp}_subject_paired_days']} "
525
+ f"paired days; ISG peak day bulk={row.expr_isg_peak_day_bulk} sc={row.expr_isg_peak_day_sc}")
526
+ if issues:
527
+ return "fail: " + "; ".join(issues)
528
+ if min(r1, r2) == 1 and max(r1, r2) <= SUBJ_TOP:
529
+ return "pass"
530
+ return f"borderline: own subject rank {r1} (bulk->sc) and {r2} (sc->bulk)"
531
+ p["identity_check"] = p.apply(verdict, axis=1)
532
+ p["identity_pass"] = p.identity_check == "pass"
533
+ notes = []
534
+ for _, row in p.iterrows():
535
+ nt = []
536
+ if row.bulk_possible_mixture:
537
+ nt.append("bulk has opposite-sex signal (possible minor admixture)")
538
+ d1, d2, c1, c2 = day_ranks(row)
539
+ if max(d1, d2, c1, c2) > 1 and min(d1, d2, c1, c2) == 1:
540
+ nt.append(f"within subject, another day beats the own day in some day tests (residualised {d1}/{d2}, "
541
+ f"centred {c1}/{c2}); not a day failure")
542
+ if row.expr_isg_peak_day_bulk != row.expr_isg_peak_day_sc:
543
+ nt.append(f"subject ISG peak day differs between assays (bulk day {row.expr_isg_peak_day_bulk}, "
544
+ f"sc day {row.expr_isg_peak_day_sc})")
545
+ if row.bulk_assigned_counts < 2e6:
546
+ nt.append(f"low-depth bulk ({int(row.bulk_assigned_counts):,} assigned reads)")
547
+ notes.append("; ".join(nt))
548
+ p["identity_notes"] = notes
549
+ p.to_csv(OUT / "pairs.csv", index=False)
550
+ require(np.array_equal(p.bulk_gsm.to_numpy(), meta_arrays["bulk_gsm"]), "pairs/features row order")
551
+ meta_arrays["identity_pass"] = p.identity_pass.to_numpy().astype(bool)
552
+ meta_arrays["identity_check"] = p.identity_check.to_numpy().astype(str)
553
+ meta_arrays["sex_bulk_expr"] = p.bulk_sex_call.to_numpy().astype(str)
554
+ meta_arrays["sex_sc_expr"] = p.sc_sex_call.to_numpy().astype(str)
555
+ tmp = OUT / "features.npz.tmp"
556
+ with open(tmp, "wb") as h:
557
+ np.savez_compressed(h, **meta_arrays)
558
+ os.replace(tmp, OUT / "features.npz")
559
+ bsex_out = bulk_sex.copy()
560
+ bsex_out["subject"] = b_subject
561
+ bsex_out["geo_sex"] = [bmeta.loc[g, "ch_Sex"] if g else "" for g in bsex_out.bulk_gsm]
562
+ bsex_out["paired"] = bsex_out.index.isin(set(p.bulk_count_column))
563
+ bsex_out.to_csv(OUT / "identity_sex_bulk_all.csv")
564
+ sc_sex.join(table.set_index("sc_gsm")[["sample_id", "subject", "sc_sex", "paired"]]).to_csv(OUT / "identity_sex_sc_all.csv")
565
+ expr.to_csv(OUT / "identity_expression.csv", index=False)
566
+
567
+ # unmatched lists
568
+ unmatched_sc = table[table.paired != "True"][["sc_gsm", "sample_id", "group", "pair_status"]]
569
+ unmatched_cols = cols[cols.paired != "True"][["bulk_column", "bulk_gsm", "unpaired_reason"]]
570
+ bulk_no_col = pd.read_csv(RUN / "pairing/bulk_GSM_without_count_column.csv", dtype=str, keep_default_na=False)
571
+ rk = f"expr_resid_k{kp}"
572
+ checks = {
573
+ "gene_positions_sha256_ok": True,
574
+ "panel_gene_ids_match_selected_genes_csv": True,
575
+ "bulk_integer_nonnegative_inside_mask": True,
576
+ "pseudo_raw_sum_equals_sum_of_retained_cells_full_axis": True,
577
+ "cells_panel_sums_equal_pseudo_raw_sum_positions_exactly": True,
578
+ "cells_per_row_equal_qc_cell_counts": True,
579
+ "no_sc_mass_outside_sc_valid": True,
580
+ "one_sample_id_per_library": True,
581
+ "bulk_and_sc_GSM_agree_on_age_sex_group_serostatus": True,
582
+ "sex_concordant_pairs": f"{int(p.sex_concordant.sum())}/{n}",
583
+ "sc_sex_call_4gene_equals_3gene_all_41_libraries": bool((sc_sex.sc_sex_call == sc_sex.sc_sex_call_3gene).all()),
584
+ "expression_best_match_is_own_pair": f"{int(p.expr_best_is_own.sum())}/{n}",
585
+ "expression_best_match_is_own_pair_centred": f"{int(p.expr_centred_best_is_own.sum())}/{n}",
586
+ "expression_reverse_best_match_is_own_pair": f"{int(p.expr_reverse_best_is_own.sum())}/{n}",
587
+ **{f"expression_residualised_k{k}_own_subject_top1_bulk_to_sc": f"{int((p[f'expr_resid_k{k}_own_subject_rank_bulk_to_sc'] == 1).sum())}/{n}" for k in RESID_K},
588
+ **{f"expression_residualised_k{k}_own_subject_top1_sc_to_bulk": f"{int((p[f'expr_resid_k{k}_own_subject_rank_sc_to_bulk'] == 1).sum())}/{n}" for k in RESID_K},
589
+ **{f"expression_residualised_k{k}_own_library_top1_bulk_to_sc": f"{int((p[f'expr_resid_k{k}_own_rank_bulk_to_sc'] == 1).sum())}/{n}" for k in RESID_K},
590
+ f"expression_residualised_k{kp}_own_day_best_within_subject_bulk_to_sc": f"{int((p[f'{rk}_own_day_rank_within_subject_bulk_to_sc'] == 1).sum())}/{n}",
591
+ f"expression_residualised_k{kp}_own_day_best_within_subject_sc_to_bulk": f"{int((p[f'{rk}_own_day_rank_within_subject_sc_to_bulk'] == 1).sum())}/{n}",
592
+ "expression_centred_own_day_best_within_subject_bulk_to_sc": f"{int((p.expr_centred_own_day_rank_within_subject_bulk_to_sc == 1).sum())}/{n}",
593
+ "expression_centred_own_day_best_within_subject_sc_to_bulk": f"{int((p.expr_centred_own_day_rank_within_subject_sc_to_bulk == 1).sum())}/{n}",
594
+ "isg_peak_day_same_in_both_assays_subjects": f"{int((p.drop_duplicates('donor_id').expr_isg_peak_day_bulk == p.drop_duplicates('donor_id').expr_isg_peak_day_sc).sum())}/{p.donor_id.nunique()}",
595
+ "identity_check_pass": f"{int((p.identity_check == 'pass').sum())}/{n}",
596
+ "identity_check_fail": p[p.identity_check.str.startswith('fail')].sample_id.tolist(),
597
+ "identity_check_borderline": p[p.identity_check.str.startswith('borderline')].sample_id.tolist(),
598
+ }
599
+ manifest = {
600
+ "schema": "giroux2022_paired_ft_v1",
601
+ "written_utc": datetime.now(timezone.utc).isoformat(), "started_utc": t0.isoformat(),
602
+ "study": "Giroux NS et al., Sci Rep 2022 (doi 10.1038/s41598-022-15668-8; PMID 35810186); SuperSeries GSE206284; bulk GSE206263, scRNA GSE206283",
603
+ "rows": n, "subjects": int(pairs.subject.nunique()), "row_order": "bulk GSM ascending (subject blocks, day ascending)",
604
+ "pairs_by_group": p.group.value_counts().to_dict(),
605
+ "pairs_by_timepoint": p.timepoint.value_counts().to_dict(),
606
+ "pairs_by_subject": p.groupby("donor_id").timepoint.apply(lambda s: ",".join(s)).to_dict(),
607
+ "pairs_by_id_match": p.id_match.value_counts().to_dict(),
608
+ "cells": {"n_cells": total_cells, "nnz": total_nnz, "per_row_min": int(qc_cell_counts.min()),
609
+ "per_row_median": float(np.median(qc_cell_counts)), "per_row_max": int(qc_cell_counts.max())},
610
+ "retained_cells_rule": "flag_conservative_review_pass = genes>=200 & UMIs>=500 & mito<=20% (qc_core, ImMicro definition); MAD flags are review-only columns",
611
+ "features_semantics": {
612
+ "bulk_raw": "author featureCounts raw gene counts (STAR/hg19) mapped by gene symbol to the canonical axis; 0 where bulk_valid is False (ImMicro file uses NaN there); 3 many-to-one symbol groups summed (bundle policy for verified integer counts)",
613
+ "pseudo_raw_sum": "sum of retained cells' UMI counts on the canonical axis; storage 0 where sc_valid is False",
614
+ "bulk_valid": "harmonization_valid from qc_bulk.harmonize (symbol in the author table maps uniquely to the canonical gene)",
615
+ "sc_valid": "harmonization_valid from qc_singlecell.canonical_export (gene in the 10x features table)",
616
+ "pair_valid": "bulk_valid & sc_valid",
617
+ "sample_ids": "<subject>_d<day>, e.g. 450905_d0",
618
+ "donor_ids": "GEO subject ID (6-hex); a subject has 2-3 rows (days)",
619
+ "timepoints": "GEO sampling day (int64: 0, 7 or 14 among pairs)",
620
+ "groups": "GEO 'exposure' field lower-cased: mild, severe (the paper and the author sample sheet call this group 'moderate'; kept in author_cohort), exposed, healthy; only mild and severe have pairs",
621
+ "extra_keys": "bulk_gsm, sc_gsm, sc_title_sample_id (GEO sc title), id_match, bulk_count_column (author table column), sc_author_library (author library name), sex_geo, age_geo, serostatus_geo (IgG), author_cohort, identity_pass, identity_check, sex_bulk_expr, sex_sc_expr",
622
+ "not_applicable": "Ye 2026 keys infection_source and collection_site have no counterpart here"},
623
+ "identity": {"sex_rule": "CPM on the source axis (bulk: all 26,045 author-table genes; sc: retained cells, all RNA features); score=log2(XIST+1)-log2(Ysum+1); female>2, male<-2, else ambiguous. Bulk Ysum = DDX3Y+UTY+KDM5D (RPS4Y1 is not in the author table); sc Ysum = RPS4Y1+DDX3Y+UTY+KDM5D (3-gene sc call also reported); opposite-sex signal flag: female call with Y CPM>20 or male call with XIST CPM>50 (bulk)",
624
+ "expression_rule": f"log2(CPM+1) over the {int(common.sum())} non-chrY canonical genes measured in all 49 bulk columns and all {len(sc_gsms)} sc libraries; top {TOP_N} by the mean of the bulk-mean and sc-mean log CPM; Spearman of each paired bulk vs all sc pseudobulks; centred sensitivity; reverse vs all 49 bulks",
625
+ "expression_residualised_rule": f"within each modality: centre log2(CPM+1) (same genes), remove the top k sample PCs computed on expressed genes (bulk mean >3 and sc mean >1 log2 CPM), keep the 2000 genes with the highest residual variance in both modalities (rank sum), Pearson over all 49 bulks x all {len(sc_gsms)} sc libraries. k={K_PRIMARY} primary (41 sc libraries and 49 bulks, vs 133/207 with k=10 for Ye 2026), k=3 and k=10 sensitivity. Ranks are reported per library and per subject (each subject scored by its best sample). chrY genes are excluded so the test is independent of the sex check. Uses no pairing information.",
626
+ "verdict_rule": f"pass = sex concordant (bulk, sc, GEO) and residualised k={K_PRIMARY} own subject ranked 1st in one direction and within the top {SUBJ_TOP} subjects in the other and no day failure; fail = sex discordant, or own subject below {SUBJ_TOP} in both directions, or day failure; else borderline",
627
+ "day_check": f"within the subject's paired rows, rank of the own day on the residualised (k={K_PRIMARY}) and on the centred (not residualised; top {TOP_N} genes by centred variance in both modalities) expression correlation, both directions. Day failure = another day of the same subject beats the own day in all four. Added after the subject-level test was seen to be blind to within-subject day swaps (the task requires the same sampling day).",
628
+ "isg_rule": f"informational: mean log2(CPM+1) of {len(ISG_GENES)} ISGs ({', '.join(ISG_GENES)}) per sample; per subject the ISG-peak day in bulk and in sc is reported",
629
+ "policy": "reported only; no row dropped on identity results; features.npz carries identity_pass / identity_check"},
630
+ "checks": checks,
631
+ "excluded": {"quarantined_sc_libraries_among_pairs": quarantined_pairs,
632
+ "sc_libraries_without_pair": unmatched_sc.to_dict("records"),
633
+ "bulk_count_columns_without_pair": unmatched_cols.to_dict("records"),
634
+ "bulk_GSMs_without_author_count_column": bulk_no_col[["gsm", "sample_id", "group"]].to_dict("records")},
635
+ "leads_not_pairs": {"note": f"unpaired author bulk columns that have no GEO GSM vs all sc libraries (residualised k={K_PRIMARY}); a lead is NOT a pair: no published ID links these columns to GEO subjects",
636
+ "rows": leads.to_dict("records")},
637
+ "inputs": {"gene_positions": {"path": str(POSITIONS), "sha256": POSITIONS_SHA},
638
+ "selected_genes": {"path": str(SELECTED), "sha256": sha256_file(SELECTED)},
639
+ "canonical_genes": {"path": str(REFERENCE / "canonical_genes.tsv"), "sha256": sha256_file(REFERENCE / "canonical_genes.tsv")},
640
+ "bulk_harmonized": {"path": str(RUN / "bulk/GSE206263_featureCounts/harmonized.h5ad"),
641
+ "sha256": sha256_file(RUN / "bulk/GSE206263_featureCounts/harmonized.h5ad")},
642
+ "sources": json.loads((RUN / "SOURCES.json").read_text())["files"],
643
+ "external_metadata": json.loads((RUN / "SOURCES.json").read_text())["external_metadata_fetched_20260928"]},
644
+ "code": {name: {"path": str(path), "sha256": sha256_file(path)} for name, path in [
645
+ ("assemble", Path(__file__).resolve()), ("pipeline", RUN / "code/giroux2022_pipeline.py"),
646
+ ("run_step", RUN / "code/run_step.sh")] + [
647
+ ("bundle/" + q.name, q) for q in sorted((RUN / "code/strict_qc_v1_code_bundle_v5").glob("*.py"))]},
648
+ "processing_dir": str(RUN),
649
+ }
650
+ manifest["outputs"] = {q.name: {"bytes": q.stat().st_size, "sha256": sha256_file(q)}
651
+ for q in sorted(OUT.iterdir()) if q.is_file() and q.name in (
652
+ "features.npz", "cells_panel6k.npz", "cells_obs.parquet", "samples.csv", "pairs.csv",
653
+ "identity_sex_bulk_all.csv", "identity_sex_sc_all.csv", "identity_expression.csv")}
654
+ (OUT / "MANIFEST.json").write_text(json.dumps(manifest, indent=1, default=str) + "\n")
655
+ shutil.rmtree(TMP)
656
+ print(json.dumps({"rows": n, "cells": manifest["cells"], "checks": checks}, indent=1, default=str))
657
+ return 0
658
+
659
+
660
+ if __name__ == "__main__":
661
+ sys.exit(main())
paper-releases/20260928/diffusion/data/source_prep/giroux2022/code/giroux2022_full_cells.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """cells_full.npz for giroux2022: tools/build_full_cells.py semantics with bounded memory (CPU only).
3
+
4
+ Uses build_full_cells.read_library (the tool's own reader) for every library and applies the tool's fail-closed
5
+ checks: cells_obs rows == cells_panel6k rows; cells sorted by dataset row; on every row the panel columns equal
6
+ cells_panel6k exactly and the full-axis sums equal features.npz pseudo_raw_sum. Rows are streamed through disk
7
+ memmaps (one library = one row here), so peak memory is one library instead of three copies of the whole matrix.
8
+ Output keys, dtypes and cells_full.BUILD.json fields are those of build_full_cells.py.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import importlib.util
13
+ import json
14
+ import os
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import pandas as pd
20
+ import scipy.sparse as sp
21
+
22
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
23
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
24
+ TOOL = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/tools/build_full_cells.py")
25
+ RUN = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/giroux2022_v1_20260928")
26
+ DS = "giroux2022"
27
+ spec = importlib.util.spec_from_file_location("build_full_cells", TOOL)
28
+ BF = importlib.util.module_from_spec(spec)
29
+ spec.loader.exec_module(BF)
30
+ BF.LIBRARY_ROOT[DS] = RUN / "singlecell"
31
+
32
+
33
+ def main() -> int:
34
+ d = BF.TASK / "data" / DS
35
+ obs = pd.read_parquet(d / "cells_obs.parquet")
36
+ panel = np.load(d / "cells_panel6k.npz", allow_pickle=False)
37
+ feat = np.load(d / "features.npz", allow_pickle=False)
38
+ positions = np.load(BF.POSITIONS).astype(np.int64)
39
+ if len(obs) != int(panel["shape"][0]):
40
+ raise SystemExit("cells_obs rows differ from cells_panel6k rows")
41
+ rs = panel["row_sample"].astype(np.int64)
42
+ if bool((np.diff(rs) < 0).any()):
43
+ raise SystemExit("cells are not sorted by dataset row")
44
+ if not np.array_equal(rs, obs.row_sample.to_numpy(np.int64)):
45
+ raise SystemExit("cells_obs row_sample differs from cells_panel6k row_sample")
46
+ P = sp.csr_matrix((panel["data"], panel["indices"], panel["indptr"]), shape=tuple(panel["shape"]))
47
+ want = np.nan_to_num(feat["pseudo_raw_sum"].astype(np.float64), nan=0.0)
48
+ n_rows = int(rs.max()) + 1
49
+ bounds = np.searchsorted(rs, np.arange(n_rows + 1))
50
+ root = BF.LIBRARY_ROOT[DS]
51
+ parts, total_nnz = [], 0
52
+ tmp = RUN / "full_cells_tmp"
53
+ tmp.mkdir(exist_ok=True)
54
+ bad_panel = bad_sum = 0
55
+ for r in range(n_rows):
56
+ a, b = int(bounds[r]), int(bounds[r + 1])
57
+ sub = obs.iloc[a:b]
58
+ libs = sub.library_id.unique()
59
+ if len(libs) != 1:
60
+ raise SystemExit(f"row {r}: expected one library, found {list(libs)}")
61
+ Xr = BF.read_library(root / str(libs[0]) / "canonical.h5ad", sub["barcode"].astype(str).to_numpy())
62
+ bad_panel += int((Xr[:, positions] != P[a:b]).nnz)
63
+ bad_sum += int(not np.array_equal(np.asarray(Xr.sum(axis=0, dtype=np.float64)).ravel(), want[r]))
64
+ np.save(tmp / f"{r:03d}_data.npy", Xr.data.astype(np.int32))
65
+ np.save(tmp / f"{r:03d}_indices.npy", Xr.indices.astype(np.int32))
66
+ np.save(tmp / f"{r:03d}_indptr.npy", Xr.indptr.astype(np.int64))
67
+ parts.append((Xr.shape[0], Xr.nnz))
68
+ total_nnz += Xr.nnz
69
+ print(f"{libs[0]}: {Xr.shape[0]} cells", flush=True)
70
+ del Xr
71
+ if bad_panel:
72
+ raise SystemExit(f"full-axis cells differ from cells_panel6k on the panel columns ({bad_panel} entries)")
73
+ if bad_sum:
74
+ raise SystemExit(f"per-row full-axis sums differ from pseudo_raw_sum for {bad_sum} rows")
75
+ n_cells = sum(c for c, _ in parts)
76
+ if n_cells != len(obs):
77
+ raise SystemExit("assembled cell count differs")
78
+ data = np.lib.format.open_memmap(tmp / "all_data.npy", mode="w+", dtype=np.int32, shape=(total_nnz,))
79
+ indices = np.lib.format.open_memmap(tmp / "all_indices.npy", mode="w+", dtype=np.int32, shape=(total_nnz,))
80
+ indptr = np.empty(n_cells + 1, dtype=np.int64)
81
+ indptr[0] = 0
82
+ at = cell_at = 0
83
+ for r in range(n_rows):
84
+ dd = np.load(tmp / f"{r:03d}_data.npy"); ix = np.load(tmp / f"{r:03d}_indices.npy")
85
+ ip = np.load(tmp / f"{r:03d}_indptr.npy")
86
+ data[at:at + len(dd)] = dd
87
+ indices[at:at + len(dd)] = ix
88
+ indptr[cell_at + 1:cell_at + len(ip)] = ip[1:] + at
89
+ at += len(dd); cell_at += len(ip) - 1
90
+ if at != total_nnz or cell_at != n_cells or indptr[-1] != total_nnz or bool((np.diff(indptr) < 0).any()):
91
+ raise SystemExit("assembly size / indptr")
92
+ data.flush(); indices.flush()
93
+ out = d / "cells_full.npz"
94
+ part = d / "cells_full.npz.partial"
95
+ with open(part, "wb") as h:
96
+ np.savez(h, data=data, indices=indices, indptr=indptr, shape=np.array([n_cells, 20097], dtype=np.int64),
97
+ row_sample=rs.astype(np.int32))
98
+ os.replace(part, out)
99
+ del data, indices
100
+ # re-open the written file and re-run the row checks on it (fail-closed on the artifact itself)
101
+ z = np.load(out, allow_pickle=False, mmap_mode=None)
102
+ for k, dt in (("data", np.int32), ("indices", np.int32), ("indptr", np.int64), ("shape", np.int64), ("row_sample", np.int32)):
103
+ if z[k].dtype != dt:
104
+ raise SystemExit(f"{k} dtype {z[k].dtype}")
105
+ X = sp.csr_matrix((z["data"], z["indices"], z["indptr"]), shape=tuple(z["shape"]))
106
+ for r in range(n_rows):
107
+ a, b = int(bounds[r]), int(bounds[r + 1])
108
+ Xr = X[a:b]
109
+ if (Xr[:, positions] != P[a:b]).nnz or not np.array_equal(np.asarray(Xr.sum(axis=0, dtype=np.float64)).ravel(), want[r]):
110
+ raise SystemExit(f"row {r}: written cells_full.npz fails the checks")
111
+ del X, z
112
+ for q in tmp.iterdir():
113
+ q.unlink()
114
+ tmp.rmdir()
115
+ info = {"dataset": DS, "n_cells": int(n_cells), "nnz": int(total_nnz), "sha256": BF.sha(out),
116
+ "checks": {"panel_columns_equal_cells_panel6k": True, "row_sums_equal_pseudo_raw_sum": True},
117
+ "builder": "processing/giroux2022_v1_20260928/code/giroux2022_full_cells.py (build_full_cells.read_library, same checks, streamed; re-verified on the written file)"}
118
+ (d / "cells_full.BUILD.json").write_text(json.dumps(info, indent=1))
119
+ print(json.dumps(info))
120
+ return 0
121
+
122
+
123
+ if __name__ == "__main__":
124
+ sys.exit(main())