junidude14 commited on
Commit
7b91e6f
·
verified ·
1 Parent(s): c07b9e8

Archive 4 checkpoints (1-4)

Browse files
paper-releases/20260928/diffusion/data/source_prep/ye2026_sepsis/code/ye2026_assemble.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Assemble the Ye 2026 sepsis paired bulk <-> scRNA fine-tuning files (CPU only).
3
+
4
+ Inputs (processing run, produced by ye2026_pipeline.py):
5
+ pairing/sc_gex_libraries_with_bulk_match.csv, bulk/GSE279448_htseq_counts/harmonized.h5ad,
6
+ bulk/bulk_source_counts.npz, singlecell/<GSM>/{canonical.h5ad, pseudobulk_per_published_sample.h5,
7
+ source_axis_pseudobulk.npz, cell_sex_gene_counts.npz, summary.json}
8
+ Outputs (OUT):
9
+ features.npz, cells_panel6k.npz, cells_obs.parquet, samples.csv, pairs.csv,
10
+ identity_sex.csv, identity_expression.csv, MANIFEST.json (QC_REPORT.md is written by hand from these)
11
+
12
+ Rows = accepted bulk<->sc pairs, ordered by bulk GSM. Retained cells = flag_conservative_review_pass
13
+ (qc_core: >=200 genes, >=500 UMIs, <=20 % mito), the ImMicro definition. Identity checks are reported,
14
+ never used to drop rows.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import json
20
+ import os
21
+ import shutil
22
+ import sys
23
+ from datetime import datetime, timezone
24
+ from pathlib import Path
25
+
26
+ import h5py
27
+ import numpy as np
28
+ import pandas as pd
29
+ import scipy.sparse as sp
30
+ from scipy.stats import rankdata
31
+
32
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
33
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
34
+
35
+ DATALAKE = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc")
36
+ RUN = DATALAKE / "processing/ye2026_sepsis_v1_20260927"
37
+ REFERENCE = DATALAKE / "processing/strict_qc_v1_20260913/reference"
38
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
39
+ OUT = M8 / "plans/paired_finetune_intradataset_20260927/data/ye2026_sepsis"
40
+ POSITIONS = M8 / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/gene_positions.npy"
41
+ POSITIONS_SHA = "653ffa45ac519000baa41086c52408009391d6e68cfb218bc6a50d34163fcb24"
42
+ SELECTED = POSITIONS.parent / "selected_genes.csv"
43
+ TMP = RUN / "assemble_tmp"
44
+ SEX_GENES = ["XIST", "RPS4Y1", "DDX3Y", "UTY", "KDM5D"]
45
+ SEX_IDS = {"XIST": "ENSG00000229807", "RPS4Y1": "ENSG00000129824", "DDX3Y": "ENSG00000067048",
46
+ "UTY": "ENSG00000183878", "KDM5D": "ENSG00000012817"}
47
+ Y_GENES = ["RPS4Y1", "DDX3Y", "UTY", "KDM5D"]
48
+ TOP_N = 2000
49
+ RESID_K = (10, 20, 30) # k=10 is the primary residualised test; 20 and 30 are sensitivity
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 text(values) -> np.ndarray:
61
+ return np.asarray([v.decode() if isinstance(v, bytes) else str(v) for v in values])
62
+
63
+
64
+ def require(ok: bool, msg: str) -> None:
65
+ if not ok:
66
+ raise SystemExit(msg)
67
+
68
+
69
+ def sex_call(xist_cpm: float, y_cpm: float) -> tuple[str, float]:
70
+ """female if log2(XIST+1)-log2(Ysum+1) > 2, male if < -2, else ambiguous."""
71
+ score = float(np.log2(xist_cpm + 1) - np.log2(y_cpm + 1))
72
+ return ("female" if score > 2 else "male" if score < -2 else "ambiguous"), score
73
+
74
+
75
+ def spearman_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:
76
+ """Spearman rho between every row of a and every row of b (average ranks)."""
77
+ from scipy.stats import rankdata
78
+ ra = rankdata(a, axis=1)
79
+ rb = rankdata(b, axis=1)
80
+ ra = (ra - ra.mean(1, keepdims=True)) / ra.std(1, keepdims=True)
81
+ rb = (rb - rb.mean(1, keepdims=True)) / rb.std(1, keepdims=True)
82
+ return ra @ rb.T / a.shape[1]
83
+
84
+
85
+ def main() -> int:
86
+ t0 = datetime.now(timezone.utc)
87
+ require(sha256_file(POSITIONS) == POSITIONS_SHA, "gene_positions.npy sha differs from the final run's")
88
+ positions = np.load(POSITIONS).astype(np.int64)
89
+ canonical = pd.read_csv(REFERENCE / "canonical_genes.tsv", sep="\t", dtype=str)
90
+ gene_ids = canonical.gene_id.to_numpy().astype("U15")
91
+ require(gene_ids.dtype.kind == "U" and all(len(x) == 15 for x in gene_ids), "gene id dtype")
92
+ require(len(gene_ids) == 20097 and canonical.panel_index.astype(int).tolist() == list(range(20097)), "axis")
93
+ selected = pd.read_csv(SELECTED)
94
+ require(np.array_equal(selected.gene_id.to_numpy(), gene_ids[positions]), "panel ids differ from positions")
95
+
96
+ table = pd.read_csv(RUN / "pairing/sc_gex_libraries_with_bulk_match.csv", dtype=str, keep_default_na=False)
97
+ summaries = {}
98
+ for gsm in table.sc_gsm:
99
+ s = json.loads((RUN / "singlecell" / gsm / "summary.json").read_text())
100
+ summaries[gsm] = s
101
+ bad = [g for g, s in summaries.items() if s["status"] != "PASS"]
102
+ pairs = table[table.paired == "True"].copy()
103
+ quarantined_pairs = sorted(set(bad) & set(pairs.sc_gsm))
104
+ pairs = pairs[~pairs.sc_gsm.isin(bad)].sort_values("bulk_gsm").reset_index(drop=True)
105
+ n = len(pairs)
106
+
107
+ # ---------------- bulk (canonical, harmonized by qc_bulk.harmonize)
108
+ import anndata as ad
109
+ bad_ = ad.read_h5ad(RUN / "bulk/GSE279448_htseq_counts/harmonized.h5ad")
110
+ bX = np.asarray(bad_.X, dtype=np.float64)
111
+ b_valid = np.asarray(bad_.layers["harmonization_valid"]).astype(bool)
112
+ b_index = bad_.obs_names.to_numpy().astype(str)
113
+ b_gsm = bad_.obs["source_GSM"].astype(str).to_numpy()
114
+ require(np.array_equal(bad_.var_names.to_numpy().astype(str), gene_ids), "bulk gene order")
115
+ require(str(bad_.uns["units"]) == "htseq_count_raw_gene_counts", "bulk units")
116
+ del bad_
117
+ brow = {g: i for i, g in enumerate(b_gsm)}
118
+ require(len(brow) == len(b_gsm), "duplicate bulk GSM")
119
+ inside = bX[b_valid]
120
+ require(np.isfinite(inside).all() and (inside >= 0).all() and np.array_equal(inside, np.rint(inside)),
121
+ "bulk values inside the measured mask must be nonnegative integers")
122
+ require(np.isnan(bX[~b_valid]).all(), "bulk values outside the mask must be NaN in the harmonized file")
123
+ bulk_all = np.where(b_valid, bX, 0.0)
124
+
125
+ # ---------------- sc per library: pseudobulk sums and masks for every PASS library
126
+ sc_gsms = [g for g in table.sc_gsm if summaries[g]["status"] == "PASS"]
127
+ sc_sum = np.zeros((len(sc_gsms), 20097))
128
+ sc_valid_all = np.zeros((len(sc_gsms), 20097), dtype=bool)
129
+ sc_n = np.zeros(len(sc_gsms), dtype=np.int64)
130
+ for i, g in enumerate(sc_gsms):
131
+ with h5py.File(RUN / "singlecell" / g / "pseudobulk_per_published_sample.h5", "r") as f:
132
+ require(np.array_equal(text(f["gene_id"][:]), gene_ids), f"{g}: gene order")
133
+ require(len(f["sample_id"]) == 1, f"{g}: exactly one sample per library")
134
+ require(f.attrs["units"] == "UMI_counts", f"{g}: units")
135
+ sc_sum[i] = f["qc_review_pass_cells_sum"][0]
136
+ sc_valid_all[i] = f["harmonization_valid"][:].astype(bool)
137
+ sc_n[i] = int(f["n_cells"][1, 0])
138
+ require(np.array_equal(sc_sum[i], np.rint(sc_sum[i])) and (sc_sum[i] >= 0).all(), f"{g}: noninteger sum")
139
+ require((sc_sum[i][~sc_valid_all[i]] == 0).all(), f"{g}: mass outside the measured mask")
140
+ srow = {g: i for i, g in enumerate(sc_gsms)}
141
+
142
+ # ---------------- per-pair feature rows
143
+ bi = np.asarray([brow[g] for g in pairs.bulk_gsm])
144
+ si = np.asarray([srow[g] for g in pairs.sc_gsm])
145
+ require(np.array_equal(b_index[bi], pairs.bulk_sample_id.to_numpy()), "bulk sample id join")
146
+ bulk_raw = bulk_all[bi]
147
+ bulk_valid = b_valid[bi]
148
+ pseudo_raw_sum = sc_sum[si]
149
+ sc_valid = sc_valid_all[si]
150
+ qc_cell_counts = sc_n[si]
151
+
152
+ # ---------------- sex check (source axis; XIST is not protein-coding)
153
+ bsrc = np.load(RUN / "bulk/bulk_source_counts.npz")
154
+ bids = list(bsrc["gene_ids"])
155
+ bcounts = bsrc["counts"]
156
+ bcpm = bcounts / bcounts.sum(1, keepdims=True) * 1e6
157
+ b_src_gsm = list(bsrc["gsm"])
158
+ sex_rows = []
159
+ for g in sc_gsms:
160
+ z = np.load(RUN / "singlecell" / g / "source_axis_pseudobulk.npz")
161
+ fid = list(z["feature_ids"])
162
+ tot = z["qc_pass_sum"][z["rna"]].sum()
163
+ rec = {"sc_gsm": g}
164
+ for gene in SEX_GENES:
165
+ rec["sc_" + gene + "_cpm"] = float(z["qc_pass_sum"][fid.index(SEX_IDS[gene])] / tot * 1e6)
166
+ rec["sc_Ysum_cpm"] = sum(rec["sc_" + x + "_cpm"] for x in Y_GENES)
167
+ rec["sc_sex_call"], rec["sc_sex_score"] = sex_call(rec["sc_XIST_cpm"], rec["sc_Ysum_cpm"])
168
+ sex_rows.append(rec)
169
+ sc_sex = pd.DataFrame(sex_rows).set_index("sc_gsm")
170
+ bulk_sex_rows = []
171
+ for j, g in enumerate(b_src_gsm):
172
+ rec = {"bulk_gsm": g}
173
+ for gene in SEX_GENES:
174
+ rec["bulk_" + gene + "_cpm"] = float(bcpm[j, bids.index(SEX_IDS[gene])])
175
+ rec["bulk_Ysum_cpm"] = sum(rec["bulk_" + x + "_cpm"] for x in Y_GENES)
176
+ rec["bulk_sex_call"], rec["bulk_sex_score"] = sex_call(rec["bulk_XIST_cpm"], rec["bulk_Ysum_cpm"])
177
+ bulk_sex_rows.append(rec)
178
+ bulk_sex = pd.DataFrame(bulk_sex_rows).set_index("bulk_gsm")
179
+
180
+ # ---------------- expression identity: every paired bulk vs every sc pseudobulk (retained cells)
181
+ common = b_valid.all(0) & sc_valid_all.all(0)
182
+
183
+ def logcpm(m: np.ndarray) -> np.ndarray:
184
+ x = m[:, common]
185
+ return np.log2(x / x.sum(1, keepdims=True) * 1e6 + 1)
186
+
187
+ lb_all, ls_all = logcpm(bulk_all), logcpm(sc_sum)
188
+ mean_score = 0.5 * (lb_all.mean(0) + ls_all.mean(0))
189
+ top = np.argsort(-mean_score, kind="mergesort")[:TOP_N]
190
+ rho = spearman_matrix(lb_all[bi][:, top], ls_all[:, top]) # paired bulks x all sc
191
+ rho_rev = spearman_matrix(ls_all[si][:, top], lb_all[:, top]) # paired sc x all bulks
192
+ cb = lb_all - lb_all.mean(0)
193
+ cs = ls_all - ls_all.mean(0)
194
+ rho_c = spearman_matrix(cb[bi][:, top], cs[:, top]) # modality-centred sensitivity
195
+ rho_c_rev = spearman_matrix(cs[si][:, top], cb[:, top])
196
+ expr = []
197
+ for r in range(n):
198
+ own = si[r]
199
+ order = np.argsort(-rho[r]); order_c = np.argsort(-rho_c[r])
200
+ rev = np.argsort(-rho_rev[r]); rev_c = np.argsort(-rho_c_rev[r])
201
+ expr.append({"sample_id": pairs.bulk_sample_id[r], "bulk_gsm": pairs.bulk_gsm[r], "sc_gsm": pairs.sc_gsm[r],
202
+ "rho_own": rho[r, own], "best_sc_gsm": sc_gsms[order[0]], "rho_best": rho[r, order[0]],
203
+ "own_rank_among_sc": int(np.flatnonzero(order == own)[0]) + 1,
204
+ "best_is_own": bool(order[0] == own),
205
+ "rho_second": rho[r, order[1]],
206
+ "centred_rho_own": rho_c[r, own], "centred_best_sc_gsm": sc_gsms[order_c[0]],
207
+ "centred_own_rank_among_sc": int(np.flatnonzero(order_c == own)[0]) + 1,
208
+ "centred_best_is_own": bool(order_c[0] == own),
209
+ "reverse_best_bulk_gsm": b_gsm[rev[0]], "reverse_own_rank_among_bulk": int(np.flatnonzero(rev == bi[r])[0]) + 1,
210
+ "reverse_best_is_own": bool(rev[0] == bi[r]),
211
+ "centred_reverse_best_bulk_gsm": b_gsm[rev_c[0]],
212
+ "centred_reverse_own_rank_among_bulk": int(np.flatnonzero(rev_c == bi[r])[0]) + 1,
213
+ "centred_reverse_best_is_own": bool(rev_c[0] == bi[r])})
214
+ expr = pd.DataFrame(expr)
215
+
216
+ # Residualised donor-identity test (unsupervised w.r.t. pairing): within each modality centre log CPM,
217
+ # remove the top-k sample principal components (shared disease-state / composition axes, computed on
218
+ # expressed genes), keep the 2,000 genes with the highest residual variance in both modalities, Pearson.
219
+ expressed = (lb_all.mean(0) > 3) & (ls_all.mean(0) > 1)
220
+ ex = np.flatnonzero(expressed)
221
+
222
+ def resid(x: np.ndarray, k: int) -> np.ndarray:
223
+ xc = x - x.mean(0)
224
+ u = np.linalg.svd(xc[:, ex], full_matrices=False)[0][:, :k]
225
+ return xc - u @ (u.T @ xc)
226
+
227
+ def pearson_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:
228
+ a = (a - a.mean(1, keepdims=True)) / a.std(1, keepdims=True)
229
+ b = (b - b.mean(1, keepdims=True)) / b.std(1, keepdims=True)
230
+ return a @ b.T / a.shape[1]
231
+
232
+ for k in RESID_K:
233
+ rb_, rs_ = resid(lb_all, k), resid(ls_all, k)
234
+ vb = np.where(expressed, rb_.var(0), -1.0); vs = np.where(expressed, rs_.var(0), -1.0)
235
+ sel = np.argsort(rankdata(-vb) + rankdata(-vs), kind="mergesort")[:TOP_N]
236
+ fw = pearson_matrix(rb_[bi][:, sel], rs_[:, sel]); bw = pearson_matrix(rs_[si][:, sel], rb_[:, sel])
237
+ c1, c2, c3, c4, c5 = [], [], [], [], []
238
+ for r in range(n):
239
+ o = np.argsort(-fw[r]); o2 = np.argsort(-bw[r])
240
+ c1.append(int(np.flatnonzero(o == si[r])[0]) + 1); c2.append(int(np.flatnonzero(o2 == bi[r])[0]) + 1)
241
+ c3.append(sc_gsms[o[0]]); c4.append(float(fw[r, si[r]])); c5.append(float(fw[r, o[0]]))
242
+ expr[f"resid_k{k}_own_rank_bulk_to_sc"] = c1
243
+ expr[f"resid_k{k}_own_rank_sc_to_bulk"] = c2
244
+ expr[f"resid_k{k}_best_sc_gsm"] = c3
245
+ expr[f"resid_k{k}_r_own"] = c4
246
+ expr[f"resid_k{k}_r_best"] = c5
247
+
248
+ # ---------------- cells on the 6k panel (two passes: per-library temp files, then one CSR)
249
+ TMP.mkdir(exist_ok=True)
250
+ nnz_per, obs_blocks = [], []
251
+ for r in range(n):
252
+ g = pairs.sc_gsm[r]
253
+ h5 = RUN / "singlecell" / g / "canonical.h5ad"
254
+ with h5py.File(h5, "r") as f:
255
+ X = f["X"]
256
+ ncell = len(X["indptr"]) - 1
257
+ full = sp.csr_matrix((X["data"][:], X["indices"][:], X["indptr"][:]), shape=(ncell, 20097))
258
+ o = f["obs"]
259
+ keep = o["flag_conservative_review_pass"][:].astype(bool)
260
+ obs = pd.DataFrame({"cell_index": np.arange(ncell), "barcode": text(o["_index"][:]),
261
+ "raw_gex_total": o["cell_total"][:], "n_genes": o["cell_detected"][:],
262
+ "mito_pct": o["cell_mito_percent"][:],
263
+ "flag_low_total_mad": o["flag_low_total_mad"][:].astype(bool),
264
+ "flag_low_genes_mad": o["flag_low_genes_mad"][:].astype(bool),
265
+ "flag_high_mito_mad": o["flag_high_mito_mad"][:].astype(bool),
266
+ "flag_high_total_review_only": o["flag_high_total_review_only"][:].astype(bool)})
267
+ require(np.array_equal(text(o["sample_id"][:]), np.full(ncell, pairs.bulk_sample_id[r])), f"{g}: sample id")
268
+ require(int(keep.sum()) == qc_cell_counts[r], f"{g}: retained-cell count differs from pseudobulk file")
269
+ kept = full[np.flatnonzero(keep)]
270
+ require(np.array_equal(np.asarray(kept.sum(0)).ravel(), pseudo_raw_sum[r]), f"{g}: canonical sum differs")
271
+ sub = kept[:, positions].tocsr()
272
+ sub.sort_indices()
273
+ require(np.array_equal(sub.data, np.rint(sub.data)) and (sub.data >= 0).all() and
274
+ (sub.data.max(initial=0) < 2**31), f"{g}: non-integer or overflowing counts")
275
+ require(np.array_equal(np.asarray(sub.sum(0)).ravel(), pseudo_raw_sum[r, positions]), f"{g}: panel sum")
276
+ np.save(TMP / f"{r:03d}_data.npy", sub.data.astype(np.int32))
277
+ np.save(TMP / f"{r:03d}_indices.npy", sub.indices.astype(np.int32))
278
+ np.save(TMP / f"{r:03d}_indptr.npy", sub.indptr.astype(np.int64))
279
+ sx = np.load(RUN / "singlecell" / g / "cell_sex_gene_counts.npz")
280
+ require(list(sx["genes"]) == SEX_GENES and sx["found"].all(), f"{g}: sex genes")
281
+ obs = obs[keep].reset_index(drop=True)
282
+ obs["cell_total_canonical"] = np.asarray(kept.sum(1)).ravel()
283
+ obs["lib_panel"] = np.asarray(sub.sum(1)).ravel()
284
+ for k, gene in enumerate(SEX_GENES):
285
+ obs[("xist" if gene == "XIST" else "y_" + gene)] = sx["counts"][k][keep]
286
+ obs["y_sum"] = obs[["y_" + x for x in Y_GENES]].sum(1)
287
+ obs.insert(2, "library_id", g)
288
+ obs.insert(3, "sample_id", pairs.bulk_sample_id[r])
289
+ obs.insert(4, "donor_id", pairs.bulk_sample_id[r])
290
+ obs.insert(5, "group", pairs.group[r])
291
+ obs["author_cell_type"] = ""
292
+ obs["row_sample"] = np.int32(r)
293
+ obs_blocks.append(obs)
294
+ nnz_per.append(sub.nnz)
295
+ print(f"{g} {pairs.bulk_sample_id[r]}: {sub.shape[0]} cells, nnz {sub.nnz}", flush=True)
296
+ del full, kept, sub
297
+ total_nnz = int(sum(nnz_per))
298
+ total_cells = int(qc_cell_counts.sum())
299
+ data = np.lib.format.open_memmap(TMP / "all_data.npy", mode="w+", dtype=np.int32, shape=(total_nnz,))
300
+ indices = np.lib.format.open_memmap(TMP / "all_indices.npy", mode="w+", dtype=np.int32, shape=(total_nnz,))
301
+ indptr = np.empty(total_cells + 1, dtype=np.int64)
302
+ indptr[0] = 0
303
+ at, cell_at = 0, 0
304
+ for r in range(n):
305
+ d = np.load(TMP / f"{r:03d}_data.npy"); ix = np.load(TMP / f"{r:03d}_indices.npy")
306
+ ip = np.load(TMP / f"{r:03d}_indptr.npy")
307
+ data[at:at + len(d)] = d
308
+ indices[at:at + len(d)] = ix
309
+ indptr[cell_at + 1:cell_at + len(ip)] = ip[1:] + at
310
+ at += len(d); cell_at += len(ip) - 1
311
+ require(at == total_nnz and cell_at == total_cells, "assembly size")
312
+ cobs = pd.concat(obs_blocks, ignore_index=True)
313
+ row_sample = cobs.row_sample.to_numpy(np.int32)
314
+ # Fail-closed re-check on the assembled matrix.
315
+ require(np.all(np.diff(row_sample) >= 0), "cells must be grouped by row")
316
+ require(np.array_equal(np.bincount(row_sample, minlength=n), qc_cell_counts), "assembled cell counts")
317
+ starts = np.concatenate([[0], np.cumsum(qc_cell_counts)])
318
+ for r in range(n):
319
+ a, b = indptr[starts[r]], indptr[starts[r + 1]]
320
+ s_r = np.bincount(indices[a:b], weights=data[a:b].astype(np.float64), minlength=len(positions))
321
+ require(np.array_equal(s_r, pseudo_raw_sum[r, positions]), f"row {r}: assembled panel sum differs")
322
+ require(np.all(np.diff(indptr) >= 0) and indptr[-1] == total_nnz, "indptr")
323
+
324
+ # ---------------- write
325
+ OUT.mkdir(parents=True, exist_ok=True)
326
+ meta_arrays = {
327
+ "gene_ids": gene_ids, "sample_ids": pairs.bulk_sample_id.to_numpy().astype(str),
328
+ "donor_ids": pairs.bulk_sample_id.to_numpy().astype(str), "groups": pairs.group.to_numpy().astype(str),
329
+ "bulk_raw": bulk_raw.astype(np.float64), "pseudo_raw_sum": pseudo_raw_sum.astype(np.float64),
330
+ "bulk_valid": bulk_valid, "sc_valid": sc_valid, "pair_valid": bulk_valid & sc_valid,
331
+ "qc_cell_counts": qc_cell_counts.astype(np.int64),
332
+ "bulk_gsm": pairs.bulk_gsm.to_numpy().astype(str), "sc_gsm": pairs.sc_gsm.to_numpy().astype(str),
333
+ "sc_title_sample_id": pairs.sc_sample_id.to_numpy().astype(str), "id_match": pairs.id_match.to_numpy().astype(str),
334
+ "sex_geo": pairs.sc_gender.to_numpy().astype(str), "age_geo": pairs.sc_age.to_numpy().astype(str),
335
+ "infection_source": pairs["sc_sepsis_infection_source"].to_numpy().astype(str),
336
+ "collection_site": pairs["sc_sample_collection_site"].to_numpy().astype(str),
337
+ }
338
+ panel_gene_ids = gene_ids[positions]
339
+ tmp = OUT / "cells_panel6k.npz.tmp"
340
+ with open(tmp, "wb") as h:
341
+ np.savez_compressed(h, data=data, indices=indices, indptr=indptr,
342
+ shape=np.array([total_cells, len(positions)], dtype=np.int64), row_sample=row_sample,
343
+ panel_gene_ids=panel_gene_ids, panel_measured=sc_valid[:, positions])
344
+ os.replace(tmp, OUT / "cells_panel6k.npz")
345
+ cobs.to_parquet(OUT / "cells_obs.parquet", index=False)
346
+ pd.DataFrame({"row": np.arange(n), "sample_id": meta_arrays["sample_ids"], "donor_id": meta_arrays["donor_ids"],
347
+ "group": meta_arrays["groups"], "n_cells": qc_cell_counts}).to_csv(OUT / "samples.csv", index=False)
348
+
349
+ # pairs.csv with identity results
350
+ p = pairs.rename(columns={"bulk_sample_id": "sample_id"})[
351
+ ["sample_id", "bulk_gsm", "sc_gsm", "bulk_title", "sc_title", "id_match", "group", "sc_gender", "sc_age",
352
+ "sc_sepsis_infection_source", "sc_sample_collection_site"]].copy()
353
+ p.insert(3, "donor_id", p.sample_id)
354
+ p.insert(4, "row", np.arange(n))
355
+ p = p.rename(columns={"sc_gender": "sex_geo", "sc_age": "age_geo", "sc_sepsis_infection_source": "infection_source",
356
+ "sc_sample_collection_site": "collection_site"})
357
+ p["timepoint"] = "none (single sample per donor)"
358
+ p["n_cells_library"] = [summaries[g]["n_cells"] for g in p.sc_gsm]
359
+ p["n_cells_retained"] = qc_cell_counts
360
+ for c in ("bulk_XIST_cpm", "bulk_Ysum_cpm", "bulk_sex_score", "bulk_sex_call"):
361
+ p[c] = bulk_sex.loc[p.bulk_gsm, c].to_numpy()
362
+ for c in ("sc_XIST_cpm", "sc_Ysum_cpm", "sc_sex_score", "sc_sex_call"):
363
+ p[c] = sc_sex.loc[p.sc_gsm, c].to_numpy()
364
+ geo = p.sex_geo.str.lower()
365
+ p["sex_concordant"] = (p.bulk_sex_call == p.sc_sex_call) & (p.sc_sex_call == geo)
366
+ p["bulk_possible_mixture"] = ((p.bulk_sex_call == "female") & (p.bulk_Ysum_cpm > 20)) | \
367
+ ((p.bulk_sex_call == "male") & (p.bulk_XIST_cpm > 50))
368
+ e = expr.set_index("bulk_gsm")
369
+ for c in ("rho_own", "rho_best", "own_rank_among_sc", "best_is_own", "best_sc_gsm", "centred_own_rank_among_sc",
370
+ "centred_best_is_own", "reverse_own_rank_among_bulk", "reverse_best_is_own"):
371
+ p["expr_" + c] = e.loc[p.bulk_gsm, c].to_numpy()
372
+ for k in RESID_K:
373
+ for c in ("own_rank_bulk_to_sc", "own_rank_sc_to_bulk", "best_sc_gsm", "r_own", "r_best"):
374
+ p[f"expr_resid_k{k}_{c}"] = e.loc[p.bulk_gsm, f"resid_k{k}_{c}"].to_numpy()
375
+ sc_name = dict(zip(table.sc_gsm, table.sc_sample_id))
376
+
377
+ def verdict(row) -> str:
378
+ """pass: sex concordant AND residualised (k=10) own pair ranked 1st in one direction and <=5th in the other.
379
+ fail: sex discordant, or own pair ranked >5th in both directions. Otherwise borderline."""
380
+ r1, r2 = row.expr_resid_k10_own_rank_bulk_to_sc, row.expr_resid_k10_own_rank_sc_to_bulk
381
+ issues = []
382
+ if not row.sex_concordant:
383
+ issues.append(f"sex bulk={row.bulk_sex_call} sc={row.sc_sex_call} geo={row.sex_geo.lower()}")
384
+ if min(r1, r2) > 5:
385
+ issues.append(f"expression: own pair rank {r1} (bulk->133 sc) and {r2} (sc->207 bulk); bulk best sc = "
386
+ f"{sc_name[row.expr_resid_k10_best_sc_gsm]} ({row.expr_resid_k10_best_sc_gsm})")
387
+ if issues:
388
+ return "fail: " + "; ".join(issues)
389
+ if min(r1, r2) == 1 and max(r1, r2) <= 5:
390
+ return "pass"
391
+ return f"borderline: own pair rank {r1} (bulk->sc) and {r2} (sc->bulk)"
392
+ p["identity_check"] = p.apply(verdict, axis=1)
393
+ p["identity_pass"] = p.identity_check == "pass"
394
+ p["identity_notes"] = np.where(p.bulk_possible_mixture, "bulk has opposite-sex signal (possible minor admixture)", "")
395
+ p.to_csv(OUT / "pairs.csv", index=False)
396
+ require(np.array_equal(p.bulk_gsm.to_numpy(), meta_arrays["bulk_gsm"]), "pairs/features row order")
397
+ meta_arrays["identity_pass"] = p.identity_pass.to_numpy().astype(bool)
398
+ meta_arrays["identity_check"] = p.identity_check.to_numpy().astype(str)
399
+ meta_arrays["sex_bulk_expr"] = p.bulk_sex_call.to_numpy().astype(str)
400
+ meta_arrays["sex_sc_expr"] = p.sc_sex_call.to_numpy().astype(str)
401
+ tmp = OUT / "features.npz.tmp"
402
+ with open(tmp, "wb") as h:
403
+ np.savez_compressed(h, **meta_arrays)
404
+ os.replace(tmp, OUT / "features.npz")
405
+ bulk_sex.join(pd.Series(dict(zip(b_gsm, b_index)), name="sample_id")).to_csv(OUT / "identity_sex_bulk_all.csv")
406
+ sc_sex.join(table.set_index("sc_gsm")[["sc_sample_id", "sc_gender", "paired"]]).to_csv(OUT / "identity_sex_sc_all.csv")
407
+ expr.to_csv(OUT / "identity_expression.csv", index=False)
408
+
409
+ # unmatched lists
410
+ unmatched_sc = table[table.paired != "True"][["sc_gsm", "sc_sample_id", "group", "id_match"]]
411
+ unmatched_bulk = pd.read_csv(RUN / "pairing/bulk_without_sc.csv", dtype=str)
412
+
413
+ checks = {
414
+ "gene_positions_sha256_ok": True,
415
+ "panel_gene_ids_match_selected_genes_csv": True,
416
+ "bulk_integer_nonnegative_inside_mask": True,
417
+ "pseudo_raw_sum_equals_sum_of_retained_cells_full_axis": True,
418
+ "cells_panel_sums_equal_pseudo_raw_sum_positions_exactly": True,
419
+ "cells_per_row_equal_qc_cell_counts": True,
420
+ "no_sc_mass_outside_sc_valid": True,
421
+ "one_sample_id_per_library": True,
422
+ "sex_concordant_pairs": f"{int(p.sex_concordant.sum())}/{n}",
423
+ "expression_best_match_is_own_pair": f"{int(p.expr_best_is_own.sum())}/{n}",
424
+ "expression_best_match_is_own_pair_centred": f"{int(p.expr_centred_best_is_own.sum())}/{n}",
425
+ "expression_reverse_best_match_is_own_pair": f"{int(p.expr_reverse_best_is_own.sum())}/{n}",
426
+ "expression_residualised_k10_top1_bulk_to_sc": f"{int((p.expr_resid_k10_own_rank_bulk_to_sc == 1).sum())}/{n}",
427
+ "expression_residualised_k10_top1_sc_to_bulk": f"{int((p.expr_resid_k10_own_rank_sc_to_bulk == 1).sum())}/{n}",
428
+ "expression_residualised_k20_top1_bulk_to_sc": f"{int((p.expr_resid_k20_own_rank_bulk_to_sc == 1).sum())}/{n}",
429
+ "expression_residualised_k30_top1_bulk_to_sc": f"{int((p.expr_resid_k30_own_rank_bulk_to_sc == 1).sum())}/{n}",
430
+ "identity_check_pass": f"{int((p.identity_check == 'pass').sum())}/{n}",
431
+ "identity_check_fail": p[p.identity_check.str.startswith('fail')].sample_id.tolist(),
432
+ "identity_check_borderline": p[p.identity_check.str.startswith('borderline')].sample_id.tolist(),
433
+ }
434
+ manifest = {
435
+ "schema": "ye2026_sepsis_paired_ft_v1",
436
+ "written_utc": datetime.now(timezone.utc).isoformat(), "started_utc": t0.isoformat(),
437
+ "study": "Ye Q et al., Nat Immunol 2026 (doi 10.1038/s41590-025-02345-x); bulk GSE279448, scRNA GSE279452",
438
+ "rows": n, "row_order": "bulk GSM ascending", "pairs_by_group": p.group.value_counts().to_dict(),
439
+ "pairs_by_id_match": p.id_match.value_counts().to_dict(),
440
+ "cells": {"n_cells": total_cells, "nnz": total_nnz, "per_row_min": int(qc_cell_counts.min()),
441
+ "per_row_median": float(np.median(qc_cell_counts)), "per_row_max": int(qc_cell_counts.max())},
442
+ "retained_cells_rule": "flag_conservative_review_pass = genes>=200 & UMIs>=500 & mito<=20% (qc_core, ImMicro definition); MAD flags are review-only columns",
443
+ "features_semantics": {
444
+ "bulk_raw": "htseq-count raw gene counts on the canonical axis; 0 where bulk_valid is False (ImMicro file uses NaN there)",
445
+ "pseudo_raw_sum": "sum of retained cells' UMI counts on the canonical axis; storage 0 where sc_valid is False",
446
+ "bulk_valid": "harmonization_valid from qc_bulk.harmonize (gene in the htseq table, unique mapping)",
447
+ "sc_valid": "harmonization_valid from qc_singlecell.canonical_export (gene in the 10x features table)",
448
+ "pair_valid": "bulk_valid & sc_valid", "donor_ids": "= sample_ids (one sample per donor; no time points)",
449
+ "groups": "GEO 'group' field: adult_sepsis, ped_sepsis, adult_HC, adult_ICU_ctrl, ped_HC, ped_ICU_ctrl",
450
+ "extra_keys": "bulk_gsm, sc_gsm, sc_title_sample_id, id_match, sex_geo, age_geo, infection_source, collection_site, identity_pass, identity_check, sex_bulk_expr, sex_sc_expr",
451
+ "timepoints": "not included: GEO has no visit/time field and each sample ID occurs once per series"},
452
+ "identity": {"sex_rule": "CPM on the source axis (bulk: htseq assigned genes; sc: retained cells, all RNA features); score=log2(XIST+1)-log2(RPS4Y1+DDX3Y+UTY+KDM5D+1); female>2, male<-2, else ambiguous; opposite-sex signal flag: female call with Y CPM>20 or male call with XIST CPM>50 (bulk)",
453
+ "expression_rule": f"log2(CPM+1) over the {int(common.sum())} canonical genes measured in all 207 bulks 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 {len(sc_gsms)} sc pseudobulks (retained cells); sensitivity: same after subtracting each modality's per-gene mean; reverse: each paired sc vs all 207 bulks",
454
+ "expression_residualised_rule": "within each modality: centre log2(CPM+1) (same common 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; paired bulk vs all sc and paired sc vs all 207 bulks; k=10 primary, 20/30 sensitivity. Uses no pairing information.",
455
+ "verdict_rule": "pass = sex concordant (bulk, sc, GEO) and residualised k=10 own pair ranked 1st in one direction and <=5th in the other; fail = sex discordant or own pair >5th in both directions; else borderline",
456
+ "policy": "reported only; no row dropped on identity results; features.npz carries identity_pass / identity_check"},
457
+ "checks": checks,
458
+ "excluded": {"quarantined_sc_libraries_among_pairs": quarantined_pairs,
459
+ "sc_libraries_without_bulk": unmatched_sc.to_dict("records"),
460
+ "bulk_samples_without_sc": unmatched_bulk[["gsm", "sample_id", "ch_group"]].to_dict("records")},
461
+ "inputs": {"gene_positions": {"path": str(POSITIONS), "sha256": POSITIONS_SHA},
462
+ "selected_genes": {"path": str(SELECTED), "sha256": sha256_file(SELECTED)},
463
+ "canonical_genes": {"path": str(REFERENCE / "canonical_genes.tsv"), "sha256": sha256_file(REFERENCE / "canonical_genes.tsv")},
464
+ "bulk_harmonized": {"path": str(RUN / "bulk/GSE279448_htseq_counts/harmonized.h5ad"),
465
+ "sha256": sha256_file(RUN / "bulk/GSE279448_htseq_counts/harmonized.h5ad")},
466
+ "sources": json.loads((RUN / "SOURCES.json").read_text())["files"]},
467
+ "code": {name: {"path": str(path), "sha256": sha256_file(path)} for name, path in [
468
+ ("assemble", Path(__file__).resolve()), ("pipeline", RUN / "code/ye2026_pipeline.py"),
469
+ ("run_step", RUN / "code/run_step.sh")] + [
470
+ ("bundle/" + q.name, q) for q in sorted((RUN / "code/strict_qc_v1_code_bundle_v5").glob("*.py"))]},
471
+ "processing_dir": str(RUN),
472
+ }
473
+ manifest["outputs"] = {q.name: {"bytes": q.stat().st_size, "sha256": sha256_file(q)}
474
+ for q in sorted(OUT.iterdir()) if q.is_file() and q.name not in ("MANIFEST.json", "QC_REPORT.md")}
475
+ (OUT / "MANIFEST.json").write_text(json.dumps(manifest, indent=1, default=str) + "\n")
476
+ shutil.rmtree(TMP)
477
+ print(json.dumps({"rows": n, "cells": manifest["cells"], "checks": checks}, indent=1))
478
+ return 0
479
+
480
+
481
+ if __name__ == "__main__":
482
+ sys.exit(main())
paper-releases/20260928/diffusion/data/source_prep/ye2026_sepsis/code/ye2026_findings.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Evidence for study-level findings (CPU only): 10x chemistry, author pre-filtering, sex vs GEO.
3
+
4
+ Writes RUN/FINDINGS.json and merges it into the deliverable MANIFEST.json as "findings".
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import glob
9
+ import gzip
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+ import pandas as pd
16
+
17
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
18
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
19
+
20
+ RUN = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/ye2026_sepsis_v1_20260927")
21
+ OUT = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/data/ye2026_sepsis")
22
+ E = RUN / "extracted/GSE279452"
23
+
24
+ table = pd.read_csv(RUN / "pairing/sc_gex_libraries_with_bulk_match.csv", dtype=str, keep_default_na=False)
25
+ rows = []
26
+ for r in table.itertuples():
27
+ bc = [l.strip() for l in gzip.open(E / r.barcodes_file, "rt")]
28
+ stem = r.barcodes_file.removesuffix(".barcodes.tsv.gz")
29
+ rec = {"sc_gsm": r.sc_gsm, "n_barcodes": len(bc), "first_barcode": bc[0],
30
+ "suffixes": sorted({b.split("-")[1] for b in bc})}
31
+ sid = stem.split("_", 1)[1] # VDJ files sit under separate VDJ GSMs with the same sample ID
32
+ for chain in ("TCR", "BCR"):
33
+ found = sorted(E.glob(f"GSM*_{sid}.{chain}.filtered_contig_annotations.csv.gz"))
34
+ if len(found) != 1:
35
+ raise SystemExit(f"{sid}: expected one {chain} contig file, found {len(found)}")
36
+ vdj = set(pd.read_csv(found[0], usecols=["barcode"]).barcode)
37
+ rec[f"{chain}_cells"] = len(vdj)
38
+ rec[f"{chain}_cells_in_gex"] = len(vdj & set(bc))
39
+ rows.append(rec)
40
+ chem = pd.DataFrame(rows)
41
+ chem["TCR_frac_in_gex"] = chem.TCR_cells_in_gex / chem.TCR_cells.clip(lower=1)
42
+ chem.to_csv(RUN / "chemistry_barcode_evidence.csv", index=False)
43
+
44
+ libs = json.loads((RUN / "singlecell/SINGLECELL_SUMMARY.json").read_text())["libraries"]
45
+ pre = pd.DataFrame([{**s["author_prefilter_evidence"], "sc_gsm": s["library_id"]} for s in libs])
46
+ sx = pd.read_csv(OUT / "identity_sex_sc_all.csv")
47
+ sxb = pd.read_csv(OUT / "identity_sex_bulk_all.csv")
48
+ geo_b = pd.read_csv(RUN / "pairing/GSE279448_samples.csv", dtype=str).set_index("gsm").ch_gender.str.lower()
49
+ sxb["geo"] = sxb.bulk_gsm.map(geo_b)
50
+ feat_md5 = {__import__("hashlib").md5(gzip.open(E / f, "rb").read()).hexdigest() for f in table.features_file}
51
+
52
+ findings = {
53
+ "sc_chemistry": {
54
+ "geo_statement": "GEX GSMs: '10xGenomics Single Cell 3' Library Gel Bead Kit V3.1'; VDJ GSMs: '10xGenomics Single Cell 5' RNA, VDJ Library Gel Bead Kit'",
55
+ "first_barcode_prefix_counts": chem.first_barcode.str[:7].value_counts().to_dict(),
56
+ "barcode_suffixes": sorted({s for x in chem.suffixes for s in x}),
57
+ "tcr_contig_cells_found_among_gex_barcodes": {"median": float(chem.TCR_frac_in_gex.median()),
58
+ "min": float(chem.TCR_frac_in_gex.min()),
59
+ "pooled": float(chem.TCR_cells_in_gex.sum() / chem.TCR_cells.sum())},
60
+ "conclusion": ("GEX barcodes come from the 737K-august-2016 whitelist (every library's sorted first barcode starts "
61
+ "AAACCTG; 3' v3/v3.1 uses the 3M-february-2018 list) and nearly all TCR contig cells are GEX "
62
+ "cells. The GEX was therefore captured in the same 5' GEM reaction as the V(D)J libraries: 10x 5' "
63
+ "gene expression, not 3' v3.1 as the GEO GEX records state."),
64
+ "mtx_header": "cellranger-6.1.1 (MatrixMarket metadata_json)",
65
+ "features_file_identical_across_libraries": len(feat_md5) == 1,
66
+ },
67
+ "author_filtering": {
68
+ "cells_total_133_libraries": int(pre.cells.sum()),
69
+ "cells_below_500_umi": int(pre.counts_lt_500.sum()),
70
+ "cells_at_or_below_200_genes": int(pre.genes_le_200.sum()),
71
+ "cells_at_or_above_20pct_mito": int(pre.mito_ge_20.sum()),
72
+ "cells_at_or_above_2x_median_genes": int(pre.genes_ge_2x_median.sum()),
73
+ "conclusion": ("GEO matrices are Cell Ranger cell-called barcodes (no cell under 500 UMIs) but NOT the authors' "
74
+ "Seurat-filtered set: cells violating the stated MT%<20, genes>200 and genes<2x median rules remain."),
75
+ },
76
+ "sex_vs_geo": {
77
+ "sc_all_libraries_discordant": sx[(sx.sc_sex_call != sx.sc_gender.str.lower())][["sc_gsm", "sc_sample_id", "sc_gender", "sc_sex_call"]].to_dict("records"),
78
+ "bulk_all_samples_discordant_or_ambiguous": sxb[(sxb.bulk_sex_call != sxb.geo)][["bulk_gsm", "sample_id", "geo", "bulk_sex_call", "bulk_XIST_cpm", "bulk_Ysum_cpm"]].to_dict("records"),
79
+ },
80
+ }
81
+ (RUN / "FINDINGS.json").write_text(json.dumps(findings, indent=1, default=str) + "\n")
82
+ manifest = json.loads((OUT / "MANIFEST.json").read_text())
83
+ manifest["findings"] = findings
84
+ manifest["code"]["findings"] = {"path": str(Path(__file__).resolve()),
85
+ "sha256": __import__("hashlib").sha256(Path(__file__).read_bytes()).hexdigest()}
86
+ (OUT / "MANIFEST.json").write_text(json.dumps(manifest, indent=1, default=str) + "\n")
87
+ print(json.dumps(findings, indent=1, default=str))
paper-releases/20260928/diffusion/data/source_prep/ye2026_sepsis/code/ye2026_pipeline.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Ye et al. 2026 sepsis PBMC bulk (GSE279448) + scRNA (GSE279452) processing.
3
+
4
+ CPU only; never imports torch or initializes CUDA.
5
+
6
+ Reuses the frozen ImMicro strict-QC code bundle v5 VERBATIM (copied to
7
+ code/strict_qc_v1_code_bundle_v5, sha256 verified against its MANIFEST):
8
+ * qc_core.extract_archive / scan_mtx (safe extraction, streaming MTX audit,
9
+ cell flags: min_genes 200, min_counts 500, max mito 20 %, 5-MAD outliers)
10
+ * qc_genes.GeneMapper (frozen 20,097-gene GENCODE v49 axis,
11
+ identifier mapping with ambiguity/conflict quarantine)
12
+ * qc_singlecell.read_axes / canonical_export (canonical sparse H5AD,
13
+ measured-gene masks, per-sample SUM pseudobulk of all / review-pass cells)
14
+ * qc_bulk.from_assembled / harmonize (bulk canonical matrix, NaN +
15
+ source_feature_present/harmonization_valid layers)
16
+ Only the study-specific glue (GEO title parsing, htseq parsing, per-library
17
+ obs construction) is new and lives in this file.
18
+
19
+ Subcommands: sources | extract | pairing | bulk | sc
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import gzip
25
+ import hashlib
26
+ import json
27
+ import os
28
+ import re
29
+ import sys
30
+ import time
31
+ from collections import defaultdict
32
+ from concurrent.futures import ProcessPoolExecutor, as_completed
33
+ from datetime import datetime, timezone
34
+ from pathlib import Path
35
+
36
+ import numpy as np
37
+ import pandas as pd
38
+
39
+ DATALAKE = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc")
40
+ RAW = {"GSE279448": DATALAKE / "datasets/GSE279448", "GSE279452": DATALAKE / "datasets/GSE279452"}
41
+ RUN = DATALAKE / "processing/ye2026_sepsis_v1_20260927"
42
+ BUNDLE = RUN / "code/strict_qc_v1_code_bundle_v5" # verbatim copy of strict_qc_v1_20260913/code_bundle_v5
43
+ REFERENCE = DATALAKE / "processing/strict_qc_v1_20260913/reference" # frozen; read only, sha-verified by GeneMapper
44
+ RECEIPTS = DATALAKE / "acquisition/20260927/manifests/download_receipts.jsonl"
45
+ sys.path.insert(0, str(BUNDLE))
46
+
47
+ import qc_core # noqa: E402
48
+ import qc_genes # noqa: E402
49
+
50
+ GROUP_CODES = {"Adult Sepsis": "adult_sepsis", "Pediatric Sepsis": "ped_sepsis",
51
+ "Adult Healthy Control": "adult_HC", "Adult ICU Control": "adult_ICU_ctrl",
52
+ "Pediatric ICU Control": "ped_ICU_ctrl", "Pediatric Healthy Control": "ped_HC"}
53
+ SEX_GENES = {"XIST": "ENSG00000229807", "RPS4Y1": "ENSG00000129824", "DDX3Y": "ENSG00000067048",
54
+ "UTY": "ENSG00000183878", "KDM5D": "ENSG00000012817"}
55
+ META_FIELDS = ["ch_gender", "ch_age", "ch_group", "ch_sepsis infection_source", "ch_sample collection_site"]
56
+ COUNT_EVIDENCE = ("Published per-GSM 10x Cell Ranger feature-barcode MTX (matrix/features/barcodes); "
57
+ "GEO: 10x Single Cell 3' v3.1, 'Cellranger was utilized to calculate the raw counts'")
58
+
59
+
60
+ def now() -> str:
61
+ return datetime.now(timezone.utc).isoformat()
62
+
63
+
64
+ def log(event: dict) -> None:
65
+ event = {"t": now(), **event}
66
+ line = json.dumps(event, default=str)
67
+ print(line, flush=True)
68
+ with open(RUN / "events.jsonl", "a") as handle:
69
+ handle.write(line + "\n")
70
+
71
+
72
+ def sha256(path: Path) -> str:
73
+ return qc_core.sha256_file(path)
74
+
75
+
76
+ def verify_bundle() -> dict:
77
+ manifest = json.loads((BUNDLE / "MANIFEST.json").read_text())
78
+ for name, digest in manifest["files"].items():
79
+ if sha256(BUNDLE / name) != digest:
80
+ raise RuntimeError(f"Code bundle file changed: {name}")
81
+ return manifest
82
+
83
+
84
+ # ----------------------------------------------------------------- sources
85
+ def receipts() -> dict:
86
+ out = {}
87
+ for line in open(RECEIPTS):
88
+ rec = json.loads(line)
89
+ out[rec["local_path"]] = rec
90
+ return out
91
+
92
+
93
+ def cmd_sources(_args) -> None:
94
+ """sha256 every acquired Ye 2026 file used here and compare with the acquisition receipt."""
95
+ verify_bundle()
96
+ known = receipts()
97
+ records = []
98
+ for acc, base in RAW.items():
99
+ for path in sorted(list((base / "raw").glob("*")) + list((base / "metadata").glob("*"))):
100
+ if not path.is_file() or path.name.endswith((".partial", ".tmp")):
101
+ continue
102
+ rec = {"accession": acc, "path": str(path), "bytes": path.stat().st_size, "sha256": sha256(path)}
103
+ receipt = known.get(str(path))
104
+ rec["acquisition_receipt"] = bool(receipt)
105
+ if receipt:
106
+ rec.update(url=receipt["url"], receipt_sha256=receipt["sha256"], receipt_bytes=receipt["bytes"],
107
+ receipt_completed_at=receipt["completed_at"],
108
+ matches_receipt=(receipt["sha256"] == rec["sha256"] and receipt["bytes"] == rec["bytes"]))
109
+ if not rec["matches_receipt"]:
110
+ raise RuntimeError(f"Acquired file differs from its receipt: {path}")
111
+ records.append(rec)
112
+ qc_core._write_json(RUN / "SOURCES.json", {"created_at_utc": now(), "files": records,
113
+ "acquisition": "paired-datasets-20260927.service (read only; not modified)",
114
+ "receipts": str(RECEIPTS)})
115
+ log({"stage": "sources", "n_files": len(records),
116
+ "unreceipted": [r["path"] for r in records if not r["acquisition_receipt"]]})
117
+
118
+
119
+ # ----------------------------------------------------------------- extract
120
+ def cmd_extract(args) -> None:
121
+ for acc, base in RAW.items():
122
+ if args.acc and acc != args.acc:
123
+ continue
124
+ tar = base / "raw" / f"{acc}_RAW.tar"
125
+ receipt = receipts().get(str(tar))
126
+ if not receipt:
127
+ raise RuntimeError(f"No completed acquisition receipt yet for {tar}")
128
+ if tar.stat().st_size != receipt["bytes"] or sha256(tar) != receipt["sha256"]:
129
+ raise RuntimeError(f"Tar differs from acquisition receipt: {tar}")
130
+ dest = RUN / "extracted" / acc
131
+ receipt = qc_core.extract_archive(tar, dest, RUN / "extracted" / f"{acc}.extraction_receipt.json",
132
+ disk_floor_bytes=50 * 1024**3)
133
+ log({"stage": "extract", "accession": acc, "members": receipt["member_count"], "complete": receipt["complete"]})
134
+
135
+
136
+ # ----------------------------------------------------------------- pairing
137
+ def parse_soft(path: Path) -> pd.DataFrame:
138
+ samples, cur, section = [], None, None
139
+ with gzip.open(path, "rt", encoding="utf-8") as fh:
140
+ for line in fh:
141
+ line = line.rstrip("\n")
142
+ if line.startswith("^"):
143
+ section = line[1:].split(" = ")[0]
144
+ if section == "SAMPLE":
145
+ cur = defaultdict(list)
146
+ cur["gsm"] = [line.split(" = ")[1]]
147
+ samples.append(cur)
148
+ continue
149
+ if section != "SAMPLE" or not line.startswith("!") or " = " not in line:
150
+ continue
151
+ key, val = line[1:].split(" = ", 1)
152
+ if key == "Sample_characteristics_ch1" and ": " in val:
153
+ k, v = val.split(": ", 1)
154
+ cur["ch_" + k.strip()].append(v.strip())
155
+ else:
156
+ cur[key].append(val)
157
+ return pd.DataFrame([{k: "|".join(v) for k, v in s.items()} for s in samples]).fillna("")
158
+
159
+
160
+ def cmd_pairing(_args) -> None:
161
+ out = RUN / "pairing"
162
+ out.mkdir(parents=True, exist_ok=True)
163
+ bulk = parse_soft(RAW["GSE279448"] / "metadata/GSE279448_family.soft.gz")
164
+ sc = parse_soft(RAW["GSE279452"] / "metadata/GSE279452_family.soft.gz")
165
+ bulk.to_csv(out / "GSE279448_samples.csv", index=False)
166
+ sc.to_csv(out / "GSE279452_samples.csv", index=False)
167
+ if not bulk.Sample_title.str.match(r"^bulkRNA \S+$").all():
168
+ raise RuntimeError("Unexpected bulk title format")
169
+ bulk["sample_id"] = bulk.Sample_title.str.removeprefix("bulkRNA ")
170
+ files = sc.filter(like="Sample_supplementary_file").apply(lambda r: "|".join(r), axis=1)
171
+ sc["library_kind"] = np.where(files.str.contains(r"matrix\.mtx"), "GEX_3prime_v3.1_MTX",
172
+ np.where(files.str.contains("contig_annotations"), "VDJ_5prime_contigs", "other"))
173
+ if (sc.library_kind == "other").any():
174
+ raise RuntimeError("Unclassified scRNA GSM")
175
+ sc["sample_id"] = sc.Sample_title.str.removeprefix("scRNA ").str.removesuffix(" (VDJ)")
176
+ gex = sc[sc.library_kind == "GEX_3prime_v3.1_MTX"].copy()
177
+ vdj = sc[sc.library_kind == "VDJ_5prime_contigs"].copy()
178
+ for name, frame in (("bulk", bulk), ("gex", gex)):
179
+ if not frame.sample_id.is_unique:
180
+ raise RuntimeError(f"Duplicate {name} sample IDs")
181
+ if not frame.sample_id.str.upper().is_unique:
182
+ raise RuntimeError(f"Case-insensitive duplicate {name} sample IDs")
183
+ for kind in ("barcodes", "features", "matrix"):
184
+ gex[kind + "_file"] = files[gex.index].str.extract(r"(GSM\d+_[^|/]+\." + kind + r"\.(?:tsv|mtx)\.gz)")[0]
185
+ if gex[["barcodes_file", "features_file", "matrix_file"]].isna().any().any():
186
+ raise RuntimeError("GEX GSM missing one of barcodes/features/matrix")
187
+
188
+ def normalized(sid: str) -> str:
189
+ # Case-fold, and insert the 'S' patient-type letter if a source-prefixed ID lacks it.
190
+ m = re.fullmatch(r"(?i)(abd|res|skin|uri|cns)-(\d+)", sid)
191
+ return (m.group(1) + "-S" + m.group(2)).upper() if m else sid.upper()
192
+
193
+ bulk_by_exact = dict(zip(bulk.sample_id, bulk.index))
194
+ bulk_by_case = dict(zip(bulk.sample_id.str.upper(), bulk.index))
195
+ bulk_by_norm = dict(zip(bulk.sample_id.map(normalized), bulk.index))
196
+ rows, used_bulk = [], set()
197
+ for i, g in gex.iterrows():
198
+ sid = g.sample_id
199
+ if sid in bulk_by_exact:
200
+ j, how = bulk_by_exact[sid], "exact_title"
201
+ elif sid.upper() in bulk_by_case:
202
+ j, how = bulk_by_case[sid.upper()], "case_only_title_difference"
203
+ elif normalized(sid) in bulk_by_norm:
204
+ j, how = bulk_by_norm[normalized(sid)], "missing_S_letter_in_sc_title"
205
+ else:
206
+ j, how = None, "no_bulk"
207
+ rec = {"sc_gsm": g.gsm, "sc_title": g.Sample_title, "sc_sample_id": sid, "id_match": how}
208
+ if j is not None:
209
+ b = bulk.loc[j]
210
+ if b.gsm in used_bulk:
211
+ raise RuntimeError(f"Bulk {b.gsm} matched twice")
212
+ used_bulk.add(b.gsm)
213
+ mismatch = [f for f in META_FIELDS if b[f] != g[f]]
214
+ rec.update({"bulk_gsm": b.gsm, "bulk_title": b.Sample_title, "bulk_sample_id": b.sample_id,
215
+ "metadata_mismatch_fields": ";".join(mismatch)})
216
+ for f in META_FIELDS:
217
+ rec["sc_" + f[3:].replace(" ", "_")] = g[f]
218
+ for kind in ("barcodes_file", "features_file", "matrix_file"):
219
+ rec[kind] = g[kind]
220
+ rows.append(rec)
221
+ table = pd.DataFrame(rows)
222
+ table["paired"] = table.bulk_gsm.notna() & (table.metadata_mismatch_fields.fillna("") == "")
223
+ # Canonical sample ID for the pair = bulk title ID (the complete, correctly cased form).
224
+ table["pair_sample_id"] = np.where(table.paired, table.bulk_sample_id, "")
225
+ table["group"] = table.sc_group.map(GROUP_CODES)
226
+ table.to_csv(out / "sc_gex_libraries_with_bulk_match.csv", index=False)
227
+ unmatched_bulk = bulk[~bulk.gsm.isin(used_bulk)][["gsm", "Sample_title", "sample_id"] + META_FIELDS]
228
+ unmatched_bulk.to_csv(out / "bulk_without_sc.csv", index=False)
229
+ vdj_check = sorted(set(vdj.sample_id) ^ set(gex.sample_id))
230
+ summary = {"bulk_gsms": len(bulk), "sc_gsms_total": len(sc), "sc_gex_gsms": len(gex), "sc_vdj_gsms": len(vdj),
231
+ "vdj_sample_ids_equal_gex_sample_ids": not vdj_check,
232
+ "pairs_by_id_match": table[table.paired].id_match.value_counts().to_dict(),
233
+ "pairs_total": int(table.paired.sum()),
234
+ "pairs_by_group": table[table.paired].group.value_counts().to_dict(),
235
+ "sc_without_bulk": table[~table.paired].sc_sample_id.tolist(),
236
+ "sc_without_bulk_by_group": table[~table.paired].group.value_counts().to_dict(),
237
+ "bulk_without_sc": len(unmatched_bulk),
238
+ "bulk_without_sc_by_group": unmatched_bulk.ch_group.map(GROUP_CODES).value_counts().to_dict(),
239
+ "metadata_mismatches_among_matches": int((table.metadata_mismatch_fields.fillna("") != "").sum()),
240
+ "timepoints": "none: every sample ID occurs once per series; GEO has no visit/time field",
241
+ "rule": ("sc GEX GSM title 'scRNA <ID>' joined to bulk title 'bulkRNA <ID>': exact ID first, then "
242
+ "case-insensitive, then source-prefixed IDs with the missing 'S' patient-type letter restored; "
243
+ "every accepted match must also agree on GEO sex, age, group, infection source and "
244
+ "collection site. VDJ GSMs are separate 5' VDJ libraries and are not paired.")}
245
+ qc_core._write_json(out / "PAIRING_SUMMARY.json", summary)
246
+ log({"stage": "pairing", **{k: summary[k] for k in ("pairs_total", "pairs_by_id_match", "pairs_by_group")}})
247
+
248
+
249
+ # ----------------------------------------------------------------- bulk
250
+ def parse_htseq(path: Path):
251
+ sample, gsm = qc_bulk_sample_label(path)
252
+ frame = pd.read_csv(path, sep="\t", header=None, dtype={0: str}, keep_default_na=False)
253
+ if frame.shape[1] != 2:
254
+ raise ValueError(f"htseq table must have two columns: {path}")
255
+ ids = frame[0].astype(str)
256
+ counters = ids.str.startswith("__").to_numpy()
257
+ values = pd.to_numeric(frame[1], errors="raise").to_numpy(dtype=np.float64)
258
+ if not ids[~counters].is_unique:
259
+ raise ValueError(f"Duplicate gene IDs in htseq table: {path}")
260
+ meta = {"GSM": gsm, "file": str(path)}
261
+ for gid, value in zip(ids[counters], values[counters]):
262
+ meta["htseq" + gid] = float(value)
263
+ assigned = float(values[~counters].sum())
264
+ meta["htseq_assigned_gene_total"] = assigned
265
+ meta["htseq_no_feature_fraction_of_assigned_plus_nofeature_plus_ambiguous"] = (
266
+ meta.get("htseq__no_feature", 0.0) / (assigned + meta.get("htseq__no_feature", 0.0) + meta.get("htseq__ambiguous", 0.0)))
267
+ return sample, ids[~counters].tolist(), None, values[~counters], meta
268
+
269
+
270
+ def qc_bulk_sample_label(path: Path):
271
+ import qc_bulk
272
+ return qc_bulk.sample_file_label(path, ".htseq.results")
273
+
274
+
275
+ def cmd_bulk(_args) -> None:
276
+ import qc_bulk
277
+ verify_bundle()
278
+ mapper = qc_genes.GeneMapper(REFERENCE)
279
+ paths = sorted((RUN / "extracted/GSE279448").glob("GSM*.htseq.results.gz"))
280
+ if len(paths) != 207:
281
+ raise RuntimeError(f"Expected 207 htseq files, found {len(paths)}")
282
+ records = [parse_htseq(p) for p in paths]
283
+ # Keep a source-axis copy (needed for non-protein-coding XIST in sex checks).
284
+ ids0 = records[0][1]
285
+ same_axis = all(r[1] == ids0 for r in records)
286
+ if not same_axis:
287
+ raise RuntimeError("htseq feature axes differ between samples")
288
+ (RUN / "bulk").mkdir(exist_ok=True)
289
+ np.savez_compressed(RUN / "bulk/bulk_source_counts.npz",
290
+ gene_ids=np.asarray(ids0), sample_ids=np.asarray([r[0] for r in records]),
291
+ gsm=np.asarray([r[4]["GSM"] for r in records]),
292
+ counts=np.vstack([r[3] for r in records]))
293
+ pd.DataFrame([{"sample_id": r[0], **r[4]} for r in records]).to_csv(RUN / "bulk/htseq_counters.csv", index=False)
294
+ assay = qc_bulk.from_assembled(
295
+ "GSE279448", "GSE279448_htseq_counts", "htseq_count_raw_gene_counts", records,
296
+ declared_raw_counts=True, sources=paths,
297
+ caveats=["GEO: PBMC total RNA (Trizol), 'standard Illumina protocols', NovaSeq 6000, HISAT2 2.0.4 to GRCh38, htseq-count; "
298
+ "library kit, polyA/rRNA-depletion and htseq strandedness option are not stated.",
299
+ "Five htseq '__' counter rows are kept in sample metadata, not in expression.",
300
+ "Bulk-to-single-cell pairing is by published GEO sample titles; see pairing/."],
301
+ extra={"source_format": "htseq-count two-column per-GSM tables", "identical_feature_axis_all_samples": same_axis})
302
+ report = qc_bulk.harmonize(assay, mapper, RUN / "bulk" / assay.assay_id)
303
+ log({"stage": "bulk", "status": report["status"], "n_samples": report["n_samples"],
304
+ "raw_count_eligible": report["raw_count_eligible"], "canonical_coverage": report["canonical_coverage"]})
305
+
306
+
307
+ # ----------------------------------------------------------------- single cell
308
+ def process_library(row: dict) -> dict:
309
+ import qc_singlecell as qs
310
+ import scipy.io._fast_matrix_market as fmm
311
+ from scipy.io import mmread
312
+
313
+ fmm.PARALLELISM = 1 # single-threaded MTX reader (host CPU budget)
314
+
315
+ qs.COUNT_SOURCE_EVIDENCE["GSE279452"] = COUNT_EVIDENCE # provenance string only
316
+ gsm, sid = row["sc_gsm"], row["sc_sample_id"]
317
+ base = RUN / "extracted/GSE279452"
318
+ out = RUN / "singlecell" / gsm
319
+ out.mkdir(parents=True, exist_ok=True)
320
+ summary_path = out / "summary.json"
321
+ if summary_path.exists() and json.loads(summary_path.read_text()).get("status") == "PASS":
322
+ return json.loads(summary_path.read_text())
323
+ item = {"accession": "GSE279452", "library_id": gsm, "path": str(base / row["matrix_file"]), "format": "mtx",
324
+ "duplicate_representation": False, "features_path": str(base / row["features_file"]),
325
+ "barcodes_path": str(base / row["barcodes_file"])}
326
+ summary = {**item, "sample_id_sc_title": sid, "status": "RUNNING", "output_dir": str(out), "started": now()}
327
+ qc_core._write_json(summary_path, summary)
328
+ t0 = time.time()
329
+ try:
330
+ mapper = qc_genes.GeneMapper(REFERENCE)
331
+ ids, symbols, cells, rna, axes = qs.read_axes(item)
332
+ item["matrix_path"] = axes["matrix_path"]
333
+ mapping = mapper.map_features(ids, symbols)
334
+ mapping_summary = mapper.write_rows(mapping, out / "gene_mapping")
335
+ mito = np.asarray([r["mitochondrial"] for r in mapping])
336
+ n = len(cells)
337
+ if len(set(cells)) != n:
338
+ raise qs.QCError("Duplicate barcodes within library")
339
+ pair_sid = row.get("pair_sample_id") or sid
340
+ obs = pd.DataFrame({"barcode": cells, "source_barcode": cells, "raw_10x_barcode": cells,
341
+ "author_cell_id": "", "library_id": gsm, "donor_id": pair_sid, "sample_id": pair_sid,
342
+ "visit_id": "", "author_retained": "unknown",
343
+ "mapping_basis": "one 10x library per GEO GSM; sample ID from GEO title",
344
+ "protocol": "10x_3prime_v3.1"})
345
+ obs.to_csv(out / "cell_metadata.csv.gz", index=False, compression="gzip")
346
+ metrics = out / "metrics"
347
+ if (metrics / "qc_summary.json").exists():
348
+ qc = json.loads((metrics / "qc_summary.json").read_text())
349
+ else:
350
+ qc = qc_core.scan_mtx(item["path"], metrics, mito_mask=mito, feature_mask=rna,
351
+ sample_ids=obs.sample_id.to_numpy(), feature_ids=ids,
352
+ feature_symbols=symbols, cell_ids=cells)
353
+ total = np.load(metrics / "cell_total.npy")
354
+ detected = np.load(metrics / "cell_detected.npy")
355
+ mito_pct = np.load(metrics / "cell_mito_percent.npy")
356
+ pd.DataFrame([{"min_genes": g, "min_abundance": 500, "max_mito_percent": m,
357
+ "n_review_pass": int(((detected >= g) & (total >= 500) & (mito_pct <= m)).sum())}
358
+ for g in (100, 200, 500) for m in (10, 20, 30)]).to_csv(out / "threshold_sensitivity.csv", index=False)
359
+ integral = qc["numeric"]["integer_fraction_selected_stored"] == 1
360
+ item["source_sha256"] = qc["input"].get("sha256", "")
361
+ item["canonical_identity_sha256"] = mapper.manifest.get("canonical_identity_sha256", "")
362
+ verified = bool(integral)
363
+ units = "UMI_counts" if verified else "nonnegative_abundance_source_units_unproven"
364
+ export = qs.canonical_export(item, out, mapping, mapper.canonical, obs, rna,
365
+ verified_counts=verified, units=units, full_mapping=True)
366
+ # Source-axis sums (all RNA features, incl. non-protein-coding XIST) for identity checks.
367
+ qcpass = np.load(metrics / "flag_conservative_review_pass.npy")
368
+ matrix = mmread(item["path"]).tocsc()
369
+ if matrix.shape != (len(ids), n):
370
+ raise qs.QCError("MTX shape changed")
371
+ all_sum = np.asarray(matrix.sum(axis=1)).ravel()
372
+ pass_sum = np.asarray(matrix[:, np.flatnonzero(qcpass)].sum(axis=1)).ravel()
373
+ if not np.isclose(all_sum[rna].sum(), total.sum(), rtol=1e-12):
374
+ raise qs.QCError("Source-axis sum differs from QC scan")
375
+ np.savez_compressed(out / "source_axis_pseudobulk.npz", feature_ids=np.asarray(ids),
376
+ feature_symbols=np.asarray(symbols), rna=rna, all_cells_sum=all_sum,
377
+ qc_pass_sum=pass_sum, n_cells=n, n_qc_pass=int(qcpass.sum()))
378
+ # Per-cell source counts of sex genes (XIST is not on the protein-coding canonical axis).
379
+ where = {g: i for i, g in enumerate(ids)}
380
+ sex_rows = [where.get(g, -1) for g in SEX_GENES.values()]
381
+ per_cell = np.zeros((len(SEX_GENES), n), dtype=np.float64)
382
+ csr = matrix.tocsr()
383
+ for k, r in enumerate(sex_rows):
384
+ if r >= 0:
385
+ per_cell[k] = csr[r].toarray().ravel()
386
+ np.savez_compressed(out / "cell_sex_gene_counts.npz", genes=np.asarray(list(SEX_GENES)),
387
+ gene_ids=np.asarray(list(SEX_GENES.values())), found=np.asarray(sex_rows) >= 0,
388
+ counts=per_cell)
389
+ del matrix, csr
390
+ # Author pre-filtering evidence (GEO: Seurat MT% < 20, genes > 200, genes < 2 x median).
391
+ median_genes = float(np.median(detected))
392
+ author = {"cells": n, "genes_le_200": int((detected <= 200).sum()), "mito_ge_20": int((mito_pct >= 20).sum()),
393
+ "genes_ge_2x_median": int((detected >= 2 * median_genes).sum()), "median_genes": median_genes,
394
+ "counts_lt_500": int((total < 500).sum()), "min_genes": int(detected.min()),
395
+ "max_mito_pct": float(mito_pct.max())}
396
+ summary.update({"status": "PASS", "n_cells": n, "n_features": len(ids),
397
+ "n_rna_features": int(rna.sum()), "n_qc_review_pass": int(qcpass.sum()),
398
+ "flag_counts": qc["flag_counts"], "numeric": qc["numeric"], "units": units,
399
+ "count_space_verified": verified, "count_provenance": COUNT_EVIDENCE,
400
+ "canonicalcoverage": mapping_summary, "canonical_export": export,
401
+ "author_prefilter_evidence": author, "seconds": round(time.time() - t0, 1),
402
+ "finished": now()})
403
+ except Exception as error: # noqa: BLE001 - recorded, not hidden
404
+ summary.update({"status": "QUARANTINED", "error_type": type(error).__name__, "error": str(error)})
405
+ qc_core._write_json(summary_path, summary)
406
+ return summary
407
+
408
+
409
+ def cmd_sc(args) -> None:
410
+ verify_bundle()
411
+ table = pd.read_csv(RUN / "pairing/sc_gex_libraries_with_bulk_match.csv", dtype=str, keep_default_na=False)
412
+ rows = table.to_dict("records")
413
+ if args.only_paired:
414
+ rows = [r for r in rows if r["paired"] == "True"]
415
+ if args.gsm:
416
+ rows = [r for r in rows if r["sc_gsm"] in set(args.gsm.split(","))]
417
+ if args.limit:
418
+ rows = rows[:args.limit]
419
+ log({"stage": "sc", "event": "start", "n_libraries": len(rows), "workers": args.workers})
420
+ done = []
421
+ with ProcessPoolExecutor(max_workers=args.workers, max_tasks_per_child=1) as pool:
422
+ futures = {pool.submit(process_library, r): r["sc_gsm"] for r in rows}
423
+ for future in as_completed(futures):
424
+ s = future.result()
425
+ done.append(s)
426
+ log({"stage": "sc", "library": futures[future], "status": s["status"], "n_cells": s.get("n_cells"),
427
+ "n_qc_review_pass": s.get("n_qc_review_pass"), "seconds": s.get("seconds"), "error": s.get("error")})
428
+ if not args.gsm and not args.limit:
429
+ qc_core._write_json(RUN / "singlecell/SINGLECELL_SUMMARY.json",
430
+ {"created_at_utc": now(), "libraries": sorted(done, key=lambda s: s["library_id"])})
431
+ log({"stage": "sc", "event": "finish", "pass": sum(s["status"] == "PASS" for s in done), "n": len(done)})
432
+
433
+
434
+ def main() -> None:
435
+ parser = argparse.ArgumentParser(description=__doc__)
436
+ sub = parser.add_subparsers(dest="cmd", required=True)
437
+ sub.add_parser("sources")
438
+ p = sub.add_parser("extract")
439
+ p.add_argument("--acc", default="")
440
+ sub.add_parser("pairing")
441
+ sub.add_parser("bulk")
442
+ p = sub.add_parser("sc")
443
+ p.add_argument("--workers", type=int, default=3)
444
+ p.add_argument("--limit", type=int, default=0)
445
+ p.add_argument("--only-paired", action="store_true")
446
+ p.add_argument("--gsm", default="", help="comma-separated GSM subset")
447
+ args = parser.parse_args()
448
+ RUN.mkdir(parents=True, exist_ok=True)
449
+ {"sources": cmd_sources, "extract": cmd_extract, "pairing": cmd_pairing, "bulk": cmd_bulk, "sc": cmd_sc}[args.cmd](args)
450
+
451
+
452
+ if __name__ == "__main__":
453
+ main()
paper-releases/20260928/diffusion/data/source_provenance/giroux2022/FINDINGS.json ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sc_chemistry": {
3
+ "geo_statement": "10X Genomics Single Cell 5' v1 chemistry; Cell Ranger count; assembly hg19",
4
+ "cellranger_version_from_mtx_header": [
5
+ "3.1.0"
6
+ ],
7
+ "first_sorted_barcode_prefix_counts": {
8
+ "AAACCTG": 41
9
+ },
10
+ "barcode_suffixes": [
11
+ "1"
12
+ ],
13
+ "features_table": "32,738 genes (Cell Ranger refdata hg19 1.2.0 style Ensembl IDs), identical content in all 41 libraries",
14
+ "conclusion": "consistent with GEO: every library's barcodes come from the 737K-august-2016 list (first sorted barcode AAACCTG), which 5' v1 uses; no contradiction found"
15
+ },
16
+ "author_filtering": {
17
+ "geo_statement": "Seurat: cells with > 5% mitochondrial reads or > 2,500 genes removed",
18
+ "cells_all_41_libraries": 472830,
19
+ "cells_paired_26_libraries": 284224,
20
+ "min_umis_any_cell": 500.0,
21
+ "min_genes_any_cell": 50,
22
+ "paired_cells_mito_gt_5pct": 88613,
23
+ "paired_cells_genes_gt_2500": 13168,
24
+ "paired_cells_author_rule_would_keep": 183798,
25
+ "paired_cells_retained_imMicro_rule": 276615,
26
+ "conclusion": "GEO matrices are Cell Ranger filtered barcodes with a 500-UMI floor, NOT the authors' Seurat-filtered cells; the ImMicro rule (>=200 genes, >=500 UMIs, <=20% mito) is used as for ImMicro and Ye 2026"
27
+ },
28
+ "bulk_gene_filtering": {
29
+ "author_table_rows": 26045,
30
+ "rows_matching_RPL_or_RPS_or_starting_MT_or_MRP": 0,
31
+ "canonical_genes_matching_pattern": 276,
32
+ "canonical_genes_lost": 275,
33
+ "only_measured_pattern_gene": [
34
+ "MRPL58"
35
+ ],
36
+ "panel6k_genes_lost_to_this_filter": 121,
37
+ "sc_umi_fraction_in_lost_genes_paired_rows": {
38
+ "median": 0.3573427675868265,
39
+ "min": 0.2169805649672231,
40
+ "max": 0.4196018126068366
41
+ },
42
+ "chrY_rows_present": [
43
+ "DDX3Y",
44
+ "UTY",
45
+ "KDM5D",
46
+ "EIF1AY",
47
+ "USP9Y",
48
+ "ZFY"
49
+ ],
50
+ "conclusion": "The author featureCounts table has no gene whose symbol contains RPL or RPS or starts with MT (ribosomal proteins, MRPL/MRPS, mitochondrial genes and e.g. MTOR were removed by name before deposit; ICT1 = MRPL58 survived under its old symbol). These genes are bulk_valid=False, not zero. Bulk library totals therefore exclude ~36% of the mass that the sc pseudobulk carries on the same genes; compare depth / CPM only on pair_valid genes."
51
+ },
52
+ "bulk_depth": {
53
+ "assigned_reads_per_column": {
54
+ "min": 652157.0,
55
+ "median": 13477519.0,
56
+ "max": 29189295.0
57
+ },
58
+ "low_depth_columns_lt_2M": [
59
+ "7085CA-0",
60
+ "180E1A-0"
61
+ ]
62
+ },
63
+ "pairing": {
64
+ "bulk_gsms": 71,
65
+ "bulk_subjects_geo": 29,
66
+ "bulk_count_table_columns": 49,
67
+ "bulk_count_table_subjects": 22,
68
+ "bulk_columns_matched_to_GSM": 43,
69
+ "bulk_columns_without_GSM": [
70
+ "77DA77",
71
+ "22CBD6",
72
+ "4F2EAD",
73
+ "F8FF1A",
74
+ "56E219",
75
+ "3F05F3-14"
76
+ ],
77
+ "bulk_GSMs_without_count_column": 28,
78
+ "bulk_GSMs_without_count_column_by_group": {
79
+ "exposed": 20,
80
+ "healthy": 5,
81
+ "mild": 2,
82
+ "severe": 1
83
+ },
84
+ "sc_gsms": 41,
85
+ "sc_subjects": 18,
86
+ "geo_level_subject_day_matches": 39,
87
+ "geo_level_subject_day_matches_by_group": {
88
+ "mild": 15,
89
+ "severe": 13,
90
+ "exposed": 6,
91
+ "healthy": 5
92
+ },
93
+ "geo_level_subjects": 18,
94
+ "pairs_total": 26,
95
+ "pairs_subjects": 10,
96
+ "pairs_by_group": {
97
+ "mild": 13,
98
+ "severe": 13
99
+ },
100
+ "pairs_by_day": {
101
+ "0": 10,
102
+ "14": 9,
103
+ "7": 7
104
+ },
105
+ "sc_by_pair_status": {
106
+ "paired": 26,
107
+ "bulk_GSM_has_no_column_in_author_count_table": 13,
108
+ "no_bulk_GSM_for_this_subject_day": 2
109
+ },
110
+ "sc_unpaired": [
111
+ {
112
+ "sc_gsm": "GSM6249237",
113
+ "sample_id": "450905_d7",
114
+ "group": "mild",
115
+ "pair_status": "bulk_GSM_has_no_column_in_author_count_table"
116
+ },
117
+ {
118
+ "sc_gsm": "GSM6249239",
119
+ "sample_id": "7768E4_d2",
120
+ "group": "exposed",
121
+ "pair_status": "no_bulk_GSM_for_this_subject_day"
122
+ },
123
+ {
124
+ "sc_gsm": "GSM6249240",
125
+ "sample_id": "7768E4_d14",
126
+ "group": "exposed",
127
+ "pair_status": "bulk_GSM_has_no_column_in_author_count_table"
128
+ },
129
+ {
130
+ "sc_gsm": "GSM6249241",
131
+ "sample_id": "7768E4_d28",
132
+ "group": "exposed",
133
+ "pair_status": "no_bulk_GSM_for_this_subject_day"
134
+ },
135
+ {
136
+ "sc_gsm": "GSM6249243",
137
+ "sample_id": "0B943B_d3",
138
+ "group": "mild",
139
+ "pair_status": "bulk_GSM_has_no_column_in_author_count_table"
140
+ },
141
+ {
142
+ "sc_gsm": "GSM6249262",
143
+ "sample_id": "61BBAD_d0",
144
+ "group": "exposed",
145
+ "pair_status": "bulk_GSM_has_no_column_in_author_count_table"
146
+ },
147
+ {
148
+ "sc_gsm": "GSM6249263",
149
+ "sample_id": "61BBAD_d7",
150
+ "group": "exposed",
151
+ "pair_status": "bulk_GSM_has_no_column_in_author_count_table"
152
+ },
153
+ {
154
+ "sc_gsm": "GSM6249264",
155
+ "sample_id": "61BBAD_d14",
156
+ "group": "exposed",
157
+ "pair_status": "bulk_GSM_has_no_column_in_author_count_table"
158
+ },
159
+ {
160
+ "sc_gsm": "GSM6249267",
161
+ "sample_id": "80A16A_d0",
162
+ "group": "exposed",
163
+ "pair_status": "bulk_GSM_has_no_column_in_author_count_table"
164
+ },
165
+ {
166
+ "sc_gsm": "GSM6249268",
167
+ "sample_id": "80A16A_d14",
168
+ "group": "exposed",
169
+ "pair_status": "bulk_GSM_has_no_column_in_author_count_table"
170
+ },
171
+ {
172
+ "sc_gsm": "GSM6249272",
173
+ "sample_id": "E0FA1E_dNA",
174
+ "group": "healthy",
175
+ "pair_status": "bulk_GSM_has_no_column_in_author_count_table"
176
+ },
177
+ {
178
+ "sc_gsm": "GSM6249273",
179
+ "sample_id": "3F3322_dNA",
180
+ "group": "healthy",
181
+ "pair_status": "bulk_GSM_has_no_column_in_author_count_table"
182
+ },
183
+ {
184
+ "sc_gsm": "GSM6249274",
185
+ "sample_id": "94D44E_dNA",
186
+ "group": "healthy",
187
+ "pair_status": "bulk_GSM_has_no_column_in_author_count_table"
188
+ },
189
+ {
190
+ "sc_gsm": "GSM6249275",
191
+ "sample_id": "52BA23_dNA",
192
+ "group": "healthy",
193
+ "pair_status": "bulk_GSM_has_no_column_in_author_count_table"
194
+ },
195
+ {
196
+ "sc_gsm": "GSM6249276",
197
+ "sample_id": "655A91_dNA",
198
+ "group": "healthy",
199
+ "pair_status": "bulk_GSM_has_no_column_in_author_count_table"
200
+ }
201
+ ],
202
+ "author_cohort_vs_geo_exposure": {
203
+ "0BF51C": {
204
+ "author_cohort": "Moderate",
205
+ "geo_exposure": "Severe"
206
+ },
207
+ "0E1F8E": {
208
+ "author_cohort": "Moderate",
209
+ "geo_exposure": "Severe"
210
+ },
211
+ "180E1A": {
212
+ "author_cohort": "Moderate",
213
+ "geo_exposure": "Severe"
214
+ },
215
+ "3F05F3": {
216
+ "author_cohort": "Moderate",
217
+ "geo_exposure": "Severe"
218
+ },
219
+ "40067F": {
220
+ "author_cohort": "Moderate",
221
+ "geo_exposure": "Severe"
222
+ },
223
+ "82CCF5": {
224
+ "author_cohort": "Moderate",
225
+ "geo_exposure": "Severe"
226
+ },
227
+ "B85D75": {
228
+ "author_cohort": "Moderate",
229
+ "geo_exposure": "Severe"
230
+ }
231
+ },
232
+ "rule": "A pair is one sc GEX GSM and one bulk GSM with the same GEO subject ID and the same GEO sampling day (title '<subject>, <day>, <group>, <serostatus>' = characteristics subject/time); both GSMs must agree on GEO age, sex, exposure group and serostatus; and the bulk GSM must have a column in the author featureCounts table (column '<subject>-<day>' for infected/exposed subjects, '<subject>' for healthy). No expression, age-sex or row-order matching is used to create a pair."
233
+ },
234
+ "healthy_leads": [
235
+ {
236
+ "bulk_column": "77DA77",
237
+ "bulk_sex_call": "female",
238
+ "best_sc_gsm": "GSM6249272",
239
+ "best_sc_sample": "E0FA1E_dNA",
240
+ "best_sc_sex_call": "female",
241
+ "best_sc_geo_sex": "FEMALE",
242
+ "best_sc_is_unpaired": true,
243
+ "r_best": 0.420464334761289,
244
+ "r_second": 0.2496083989065373,
245
+ "second_sc_sample": "180E1A_d0",
246
+ "reverse_rank_of_this_bulk_for_best_sc": 1,
247
+ "reverse_best_bulk_for_best_sc": "77DA77",
248
+ "geo_healthy_subject_at_same_position_in_author_sheet": "E0FA1E",
249
+ "position_agrees_with_best_sc_subject": true
250
+ },
251
+ {
252
+ "bulk_column": "22CBD6",
253
+ "bulk_sex_call": "female",
254
+ "best_sc_gsm": "GSM6249273",
255
+ "best_sc_sample": "3F3322_dNA",
256
+ "best_sc_sex_call": "female",
257
+ "best_sc_geo_sex": "FEMALE",
258
+ "best_sc_is_unpaired": true,
259
+ "r_best": 0.5237721652596927,
260
+ "r_second": 0.2329536291433593,
261
+ "second_sc_sample": "2AD75E_d14",
262
+ "reverse_rank_of_this_bulk_for_best_sc": 1,
263
+ "reverse_best_bulk_for_best_sc": "22CBD6",
264
+ "geo_healthy_subject_at_same_position_in_author_sheet": "3F3322",
265
+ "position_agrees_with_best_sc_subject": true
266
+ },
267
+ {
268
+ "bulk_column": "4F2EAD",
269
+ "bulk_sex_call": "female",
270
+ "best_sc_gsm": "GSM6249274",
271
+ "best_sc_sample": "94D44E_dNA",
272
+ "best_sc_sex_call": "female",
273
+ "best_sc_geo_sex": "FEMALE",
274
+ "best_sc_is_unpaired": true,
275
+ "r_best": 0.5762409562275047,
276
+ "r_second": 0.2055064434130179,
277
+ "second_sc_sample": "450905_d0",
278
+ "reverse_rank_of_this_bulk_for_best_sc": 1,
279
+ "reverse_best_bulk_for_best_sc": "4F2EAD",
280
+ "geo_healthy_subject_at_same_position_in_author_sheet": "94D44E",
281
+ "position_agrees_with_best_sc_subject": true
282
+ },
283
+ {
284
+ "bulk_column": "F8FF1A",
285
+ "bulk_sex_call": "male",
286
+ "best_sc_gsm": "GSM6249275",
287
+ "best_sc_sample": "52BA23_dNA",
288
+ "best_sc_sex_call": "male",
289
+ "best_sc_geo_sex": "MALE",
290
+ "best_sc_is_unpaired": true,
291
+ "r_best": 0.6572060268667277,
292
+ "r_second": 0.2232559108831267,
293
+ "second_sc_sample": "61BBAD_d14",
294
+ "reverse_rank_of_this_bulk_for_best_sc": 1,
295
+ "reverse_best_bulk_for_best_sc": "F8FF1A",
296
+ "geo_healthy_subject_at_same_position_in_author_sheet": "52BA23",
297
+ "position_agrees_with_best_sc_subject": true
298
+ },
299
+ {
300
+ "bulk_column": "56E219",
301
+ "bulk_sex_call": "female",
302
+ "best_sc_gsm": "GSM6249276",
303
+ "best_sc_sample": "655A91_dNA",
304
+ "best_sc_sex_call": "female",
305
+ "best_sc_geo_sex": "FEMALE",
306
+ "best_sc_is_unpaired": true,
307
+ "r_best": 0.709301480946846,
308
+ "r_second": 0.3301510549216415,
309
+ "second_sc_sample": "80A16A_d0",
310
+ "reverse_rank_of_this_bulk_for_best_sc": 1,
311
+ "reverse_best_bulk_for_best_sc": "56E219",
312
+ "geo_healthy_subject_at_same_position_in_author_sheet": "655A91",
313
+ "position_agrees_with_best_sc_subject": true
314
+ },
315
+ {
316
+ "bulk_column": "3F05F3-14",
317
+ "bulk_sex_call": "male",
318
+ "best_sc_gsm": "GSM6249243",
319
+ "best_sc_sample": "0B943B_d3",
320
+ "best_sc_sex_call": "male",
321
+ "best_sc_geo_sex": "MALE",
322
+ "best_sc_is_unpaired": true,
323
+ "r_best": 0.2104487949476911,
324
+ "r_second": 0.1687903603213745,
325
+ "second_sc_sample": "82CCF5_d0",
326
+ "reverse_rank_of_this_bulk_for_best_sc": 5,
327
+ "reverse_best_bulk_for_best_sc": "2AD75E-7",
328
+ "geo_healthy_subject_at_same_position_in_author_sheet": NaN,
329
+ "position_agrees_with_best_sc_subject": false
330
+ }
331
+ ]
332
+ }