junidude14 commited on
Commit
ff847ed
·
verified ·
1 Parent(s): 8fcc889

Archive 4 checkpoints (1-4)

Browse files
paper-releases/20260928/diffusion/data/source_prep/ji2025_chili/code/export_seurat_counts.R ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Export the raw RNA counts (Assay "RNA", slot "counts"; NOT data / scale.data) of the GSE287541
2
+ # author-filtered Seurat object into one 10x-style MatrixMarket library per sequencing library
3
+ # (round x PID_visit, = one GEO GPEX GSM), plus the cell metadata and the feature table.
4
+ # CPU only. Reads the outer-gunzipped copy extracted/GSE287541_seurat.rds (byte-identical inner stream
5
+ # of the acquired .RDS.gz; sha256 of both recorded by the Python 'sources' step).
6
+ #
7
+ # Feature identity: the object carries gene symbols only (36,601 rows). The CellRanger GRCh38-2020-A
8
+ # features.tsv (36,601 Ensembl IDs) is taken from 13 byte-identical GEO copies already extracted in
9
+ # strict_qc_v1 (GSE201534, GSE247707). IDs are assigned only if make.unique(gsub("_","-",symbol)),
10
+ # i.e. exactly what Read10X + CreateSeuratObject do, reproduces the object's rownames in order.
11
+ suppressPackageStartupMessages({library(Seurat); library(SeuratObject); library(Matrix); library(data.table); library(jsonlite)})
12
+ RUN <- "/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/ji2025_chili_v1_20260928"
13
+ FEATURES_2020A <- "/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/extracted/GSE201534/GSE201534_RAW_tar/GSM6066350_ChAd_ChAd_2_Day7_features.tsv.gz"
14
+ OUT <- file.path(RUN, "r_export")
15
+ dir.create(OUT, showWarnings = FALSE)
16
+ stopifnot(!file.exists(file.path(OUT, "EXPORT_SUMMARY.json")))
17
+ data.table::setDTthreads(2)
18
+
19
+ obj <- readRDS(file.path(RUN, "extracted/GSE287541_seurat.rds"))
20
+ stopifnot(identical(Assays(obj), "RNA"))
21
+ counts <- GetAssayData(obj, assay = "RNA", layer = "counts")
22
+ stopifnot(inherits(counts, "dgCMatrix"))
23
+ md <- obj@meta.data
24
+ umap <- Embeddings(obj, "ref.umap")
25
+ obj_version <- as.character(obj@version); obj_reductions <- Reductions(obj)
26
+ rm(obj); invisible(gc()) # drop the log-normalised 'data' slot from memory
27
+ cells <- colnames(counts)
28
+ stopifnot(identical(cells, rownames(md)), !anyDuplicated(cells))
29
+
30
+ # ---- values: finite, positive, integer-valued
31
+ x <- counts@x
32
+ stopifnot(all(is.finite(x)), all(x > 0), all(x == round(x)), max(x) < 2^31)
33
+
34
+ # ---- feature identity
35
+ f <- fread(FEATURES_2020A, header = FALSE, col.names = c("id", "symbol", "type"))
36
+ stopifnot(nrow(f) == nrow(counts), all(f$type == "Gene Expression"), !anyDuplicated(f$id))
37
+ seurat_names <- make.unique(gsub("_", "-", f$symbol))
38
+ feature_order_identical <- identical(seurat_names, rownames(counts))
39
+ stopifnot(feature_order_identical)
40
+ n_underscore <- sum(grepl("_", f$symbol))
41
+ n_dup_symbol <- sum(duplicated(f$symbol))
42
+
43
+ # ---- author per-cell metrics reproduce from the counts slot
44
+ tot <- Matrix::colSums(counts)
45
+ det <- Matrix::colSums(counts > 0)
46
+ mt <- grepl("^MT-", f$symbol)
47
+ pmt <- Matrix::colSums(counts[mt, , drop = FALSE]) / tot * 100
48
+ chk <- list(
49
+ nCount_equals_colsum = isTRUE(all.equal(unname(tot), md$nCount_RNA, tolerance = 0)),
50
+ nFeature_equals_detected = identical(as.integer(unname(det)), as.integer(md$nFeature_RNA)),
51
+ percent_mt_max_abs_diff = max(abs(unname(pmt) - md$percent.mt)),
52
+ nCount_refAssay_equals_nCount = isTRUE(all.equal(md$nCount_refAssay, md$nCount_RNA, tolerance = 0))
53
+ )
54
+ author <- list(n_cells = ncol(counts), min_nFeature = min(det), max_nFeature = max(det), min_nCount = min(tot),
55
+ max_nCount = max(tot), max_percent_mt = max(pmt), cells_lt_200_genes = sum(det < 200),
56
+ cells_lt_500_umi = sum(tot < 500), cells_gt_20pct_mt = sum(pmt > 20), cells_gt_10pct_mt = sum(pmt > 10),
57
+ cells_gt_15pct_mt = sum(pmt > 15))
58
+
59
+ # ---- library key from the cell-name prefix "<round>_<PID_visit>_<barcode>"
60
+ # The middle token embeds patient initials and is not always the PID (e.g. Rd4a_N1131ACV01 = N131V01,
61
+ # Rd4a_N127131ACV00 = N127V00); the library key therefore uses round + meta.data PID_visit, and the
62
+ # name token is kept as provenance. Each (round, name token) must map to exactly one PID_visit and back.
63
+ m <- regmatches(cells, regexec("^(Rd[0-9]+[ab]?)_([A-Za-z0-9]+)_([ACGT]+-1)$", cells))
64
+ ok <- lengths(m) == 4
65
+ stopifnot(all(ok))
66
+ round_ <- vapply(m, `[`, "", 2); name_token <- vapply(m, `[`, "", 3); bc <- vapply(m, `[`, "", 4)
67
+ stopifnot(identical(round_, md$round))
68
+ pidv <- md$PID_visit
69
+ key_name <- paste(round_, name_token); key_meta <- paste(round_, pidv)
70
+ stopifnot(all(tapply(key_meta, key_name, function(v) length(unique(v))) == 1),
71
+ all(tapply(key_name, key_meta, function(v) length(unique(v))) == 1))
72
+ lib <- paste0(round_, "_", pidv)
73
+ libs <- unique(lib)
74
+
75
+ # ---- write features and cell metadata
76
+ fwrite(data.table(f$id, f$symbol, f$type, seurat_names), file.path(OUT, "features.tsv.gz"), sep = "\t", col.names = FALSE)
77
+ meta <- data.table(cell = cells, library_key = lib, round = round_, cell_name_token = name_token, raw_barcode = bc,
78
+ counts_total = unname(tot), counts_detected = as.integer(unname(det)), counts_percent_mt = unname(pmt))
79
+ meta <- cbind(meta, as.data.table(md))
80
+ stopifnot(identical(rownames(umap), cells))
81
+ meta[, `:=`(refUMAP_1 = umap[, 1], refUMAP_2 = umap[, 2])]
82
+ fwrite(meta, file.path(OUT, "cell_metadata.csv.gz"))
83
+
84
+ # ---- per-library MatrixMarket (features x cells, integer, cell-column ordered)
85
+ lib_rows <- list()
86
+ for (L in libs) {
87
+ idx <- which(lib == L)
88
+ sub <- counts[, idx, drop = FALSE]
89
+ d <- file.path(OUT, L); dir.create(d, showWarnings = FALSE)
90
+ mtx <- file.path(d, "matrix.mtx")
91
+ s <- summary(sub) # i, j, x in column-major order
92
+ stopifnot(nrow(s) == length(sub@x), !is.unsorted(s$j))
93
+ writeLines(c("%%MatrixMarket matrix coordinate integer general",
94
+ sprintf("%%metadata_json: {\"source\": \"GSE287541 Seurat RNA@counts\", \"library_key\": \"%s\"}", L),
95
+ sprintf("%d %d %d", nrow(sub), ncol(sub), nrow(s))), mtx)
96
+ fwrite(data.table(i = as.integer(s$i), j = as.integer(s$j), x = as.integer(s$x)), mtx, sep = " ",
97
+ col.names = FALSE, append = TRUE)
98
+ stopifnot(system2("gzip", c("-1", "-f", mtx)) == 0)
99
+ fwrite(data.table(cells[idx]), file.path(d, "barcodes.tsv.gz"), col.names = FALSE)
100
+ lib_rows[[L]] <- data.table(library_key = L, n_cells = length(idx), nnz = nrow(s), total_counts = sum(s$x),
101
+ PID_visit = unique(md$PID_visit[idx]), round = unique(md$round[idx]),
102
+ orig_ident = paste(unique(md$orig.ident[idx]), collapse = "|"),
103
+ cell_name_token = paste(unique(name_token[idx]), collapse = "|"),
104
+ Time = paste(unique(md$Time[idx]), collapse = "|"),
105
+ Person = paste(unique(md$Person.CHILI.ID[idx]), collapse = "|"),
106
+ Group = paste(unique(md$Group[idx]), collapse = "|"),
107
+ Gender = paste(unique(md$Gender[idx]), collapse = "|"),
108
+ Age = paste(unique(md$Age[idx]), collapse = "|"),
109
+ Steroid = paste(unique(md$Steroid_yn[idx]), collapse = "|"),
110
+ Cancer = paste(unique(md$Type.of.cancer[idx]), collapse = "|"),
111
+ min_genes = min(det[idx]), min_umi = min(tot[idx]), max_pct_mt = max(pmt[idx]))
112
+ cat(L, length(idx), nrow(s), "\n")
113
+ }
114
+ libtab <- rbindlist(lib_rows)
115
+ fwrite(libtab, file.path(OUT, "libraries.csv"))
116
+ summ <- list(source_object = file.path(RUN, "extracted/GSE287541_seurat.rds"), seurat_object_version = obj_version,
117
+ assay = "RNA", exported_slot = "counts (raw UMI counts; data and scale.data not exported)",
118
+ n_features = nrow(counts), n_cells = ncol(counts), nnz = length(counts@x), total_counts = sum(counts@x),
119
+ n_libraries = length(libs), feature_reference = FEATURES_2020A,
120
+ feature_identity_rule = "make.unique(gsub('_','-',symbol)) of CellRanger GRCh38-2020-A features.tsv equals Seurat rownames in order",
121
+ feature_order_identical = feature_order_identical, n_symbols_with_underscore = n_underscore,
122
+ n_duplicated_symbols = n_dup_symbol, counts_checks = chk, author_filter_evidence = author,
123
+ meta_columns = colnames(md), reductions = obj_reductions)
124
+ write_json(summ, file.path(OUT, "EXPORT_SUMMARY.json"), auto_unbox = TRUE, pretty = TRUE, digits = NA)
125
+ cat(toJSON(summ[c("n_cells", "nnz", "n_libraries", "feature_order_identical", "counts_checks", "author_filter_evidence")],
126
+ auto_unbox = TRUE, pretty = TRUE), "\n")
paper-releases/20260928/diffusion/data/source_prep/ji2025_chili/code/ji2025_assemble.py ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Assemble the Ji 2025 ChILI paired bulk <-> scRNA fine-tuning files (CPU only).
3
+
4
+ Mirrors plans/.../data/ye2026_sepsis (same file names, keys and semantics; see ye2026_assemble.py). Differences:
5
+ * rows are patient x timepoint pairs; donor_ids = patient, groups = timepoints = GEO time label,
6
+ outcome = ChILI / control;
7
+ * bulk is Salmon estimated read counts (float64, stored unchanged; the deposited table is integer-valued);
8
+ * identity checks are made patient-aware (the same patient's other time points are the natural near-ties),
9
+ use a PC-removal depth adapted to 46 sc libraries, and exclude chrY genes so that they are independent
10
+ of the sex check.
11
+
12
+ Inputs (processing run, produced by ji2025_pipeline.py): pairing/, bulk/GSE287540_salmon_counts/harmonized.h5ad,
13
+ bulk/bulk_source_counts.npz, singlecell/<GSM>/..., r_export/cell_metadata.csv.gz
14
+ Outputs (OUT): features.npz, cells_panel6k.npz, cells_obs.parquet, samples.csv, pairs.csv,
15
+ identity_sex_bulk_all.csv, identity_sex_sc_all.csv, identity_expression.csv, MANIFEST.json
16
+ Retained cells = flag_conservative_review_pass (>=200 genes, >=500 UMIs, <=20 % mito). Identity checks are
17
+ reported, never used to drop rows.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import hashlib
22
+ import json
23
+ import os
24
+ import shutil
25
+ import sys
26
+ from datetime import datetime, timezone
27
+ from pathlib import Path
28
+
29
+ import h5py
30
+ import numpy as np
31
+ import pandas as pd
32
+ import scipy.sparse as sp
33
+ from scipy.stats import rankdata
34
+
35
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
36
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
37
+
38
+ DATALAKE = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc")
39
+ RUN = DATALAKE / "processing/ji2025_chili_v1_20260928"
40
+ REFERENCE = DATALAKE / "processing/strict_qc_v1_20260913/reference"
41
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
42
+ OUT = M8 / "plans/paired_finetune_intradataset_20260927/data/ji2025_chili"
43
+ POSITIONS = M8 / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/gene_positions.npy"
44
+ POSITIONS_SHA = "653ffa45ac519000baa41086c52408009391d6e68cfb218bc6a50d34163fcb24"
45
+ SELECTED = POSITIONS.parent / "selected_genes.csv"
46
+ BULK_H5AD = RUN / "bulk/GSE287540_salmon_counts/harmonized.h5ad"
47
+ TMP = RUN / "assemble_tmp"
48
+ SEX_GENES = ["XIST", "RPS4Y1", "DDX3Y", "UTY", "KDM5D"]
49
+ SEX_IDS = {"XIST": "ENSG00000229807", "RPS4Y1": "ENSG00000129824", "DDX3Y": "ENSG00000067048",
50
+ "UTY": "ENSG00000183878", "KDM5D": "ENSG00000012817"}
51
+ Y_GENES = ["RPS4Y1", "DDX3Y", "UTY", "KDM5D"]
52
+ TOP_N = 2000
53
+ K_PRIMARY = 5 # ~10 % of the 46 sc libraries (Ye: k=10 for 133 sc / 207 bulk)
54
+ RESID_K = (0, 3, 5, 8, 10) # sensitivity
55
+ SPECIMEN_GENES = {"hemoglobin": ["HBB", "HBA1", "HBA2", "HBD"],
56
+ "neutrophil": ["FCGR3B", "CXCR2", "CSF3R", "MMP9", "CAMP", "LTF"],
57
+ "lymphocyte": ["CD3E", "MS4A1", "IL7R"], "monocyte": ["CD14", "LYZ"]}
58
+
59
+
60
+ def sha256_file(path: Path) -> str:
61
+ h = hashlib.sha256()
62
+ with open(path, "rb") as f:
63
+ for block in iter(lambda: f.read(1 << 24), b""):
64
+ h.update(block)
65
+ return h.hexdigest()
66
+
67
+
68
+ def text(values) -> np.ndarray:
69
+ return np.asarray([v.decode() if isinstance(v, bytes) else str(v) for v in values])
70
+
71
+
72
+ def require(ok: bool, msg: str) -> None:
73
+ if not ok:
74
+ raise SystemExit(msg)
75
+
76
+
77
+ def sex_call(xist_cpm: float, y_cpm: float) -> tuple[str, float]:
78
+ """female if log2(XIST+1)-log2(Ysum+1) > 2, male if < -2, else ambiguous (Ye 2026 rule)."""
79
+ score = float(np.log2(xist_cpm + 1) - np.log2(y_cpm + 1))
80
+ return ("female" if score > 2 else "male" if score < -2 else "ambiguous"), score
81
+
82
+
83
+ def spearman_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:
84
+ ra = rankdata(a, axis=1)
85
+ rb = rankdata(b, axis=1)
86
+ ra = (ra - ra.mean(1, keepdims=True)) / ra.std(1, keepdims=True)
87
+ rb = (rb - rb.mean(1, keepdims=True)) / rb.std(1, keepdims=True)
88
+ return ra @ rb.T / a.shape[1]
89
+
90
+
91
+ def pearson_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:
92
+ a = (a - a.mean(1, keepdims=True)) / a.std(1, keepdims=True)
93
+ b = (b - b.mean(1, keepdims=True)) / b.std(1, keepdims=True)
94
+ return a @ b.T / a.shape[1]
95
+
96
+
97
+ def rank_of(scores: np.ndarray, target: int) -> int:
98
+ order = np.argsort(-scores, kind="mergesort")
99
+ return int(np.flatnonzero(order == target)[0]) + 1
100
+
101
+
102
+ def patient_rank(scores: np.ndarray, cand_patient: np.ndarray, own: str) -> tuple[int, str, float]:
103
+ """Collapse candidates to patients by their best score; rank of the own patient, best patient, best score."""
104
+ pats = np.unique(cand_patient)
105
+ best = np.asarray([scores[cand_patient == q].max() for q in pats])
106
+ order = np.argsort(-best, kind="mergesort")
107
+ r = int(np.flatnonzero(pats[order] == own)[0]) + 1 if own in set(pats) else -1
108
+ return r, str(pats[order[0]]), float(best[order[0]])
109
+
110
+
111
+ def auc(pos: np.ndarray, neg: np.ndarray) -> float:
112
+ allv = np.concatenate([pos, neg])
113
+ r = rankdata(allv)
114
+ return float((r[:len(pos)].sum() - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg)))
115
+
116
+
117
+ def main() -> int:
118
+ t0 = datetime.now(timezone.utc)
119
+ require(sha256_file(POSITIONS) == POSITIONS_SHA, "gene_positions.npy sha differs from the final run's")
120
+ positions = np.load(POSITIONS).astype(np.int64)
121
+ canonical = pd.read_csv(REFERENCE / "canonical_genes.tsv", sep="\t", dtype=str)
122
+ gene_ids = canonical.gene_id.to_numpy().astype("U15")
123
+ require(gene_ids.dtype.kind == "U" and all(len(x) == 15 for x in gene_ids), "gene id dtype")
124
+ require(len(gene_ids) == 20097 and canonical.panel_index.astype(int).tolist() == list(range(20097)), "axis")
125
+ selected = pd.read_csv(SELECTED)
126
+ require(np.array_equal(selected.gene_id.to_numpy(), gene_ids[positions]), "panel ids differ from positions")
127
+ sym = canonical.gene_symbol.to_numpy().astype(str)
128
+ chr_y = canonical.chromosome.to_numpy().astype(str) == "chrY"
129
+
130
+ table = pd.read_csv(RUN / "pairing/sc_gex_libraries_with_bulk_match.csv", dtype=str, keep_default_na=False)
131
+ summaries = {g: json.loads((RUN / "singlecell" / g / "summary.json").read_text()) for g in table.sc_gsm}
132
+ bad = [g for g, s in summaries.items() if s["status"] != "PASS"]
133
+ pairs = table[table.paired == "True"].copy()
134
+ quarantined_pairs = sorted(set(bad) & set(pairs.sc_gsm))
135
+ pairs = pairs[~pairs.sc_gsm.isin(bad)].sort_values("bulk_gsm").reset_index(drop=True)
136
+ n = len(pairs)
137
+
138
+ # ---------------- bulk (canonical, harmonized by qc_bulk.harmonize)
139
+ import anndata as ad
140
+ bad_ = ad.read_h5ad(BULK_H5AD)
141
+ bX = np.asarray(bad_.X, dtype=np.float64)
142
+ b_valid = np.asarray(bad_.layers["harmonization_valid"]).astype(bool)
143
+ b_index = bad_.obs_names.to_numpy().astype(str)
144
+ b_gsm = bad_.obs["source_GSM"].astype(str).to_numpy()
145
+ b_patient_raw = bad_.obs["source_subject"].astype(str).to_numpy()
146
+ require(np.array_equal(bad_.var_names.to_numpy().astype(str), gene_ids), "bulk gene order")
147
+ require(str(bad_.uns["units"]) == "salmon_1.10.0_gene_estimated_read_counts_as_deposited", "bulk units")
148
+ del bad_
149
+ b_patient = np.asarray([f"N{int(p[1:]):03d}" for p in b_patient_raw])
150
+ brow = {g: i for i, g in enumerate(b_gsm)}
151
+ require(len(brow) == len(b_gsm), "duplicate bulk GSM")
152
+ inside = bX[b_valid]
153
+ require(np.isfinite(inside).all() and (inside >= 0).all(), "bulk values inside the measured mask must be finite, >=0")
154
+ bulk_fractional = int(np.sum(inside != np.trunc(inside)))
155
+ require(np.isnan(bX[~b_valid]).all(), "bulk values outside the mask must be NaN in the harmonized file")
156
+ bulk_all = np.where(b_valid, bX, 0.0)
157
+
158
+ # ---------------- sc per library: pseudobulk sums and masks for every PASS library
159
+ sc_gsms = [g for g in table.sc_gsm if summaries[g]["status"] == "PASS"]
160
+ tix = table.set_index("sc_gsm")
161
+ sc_patient = tix.loc[sc_gsms, "patient"].to_numpy().astype(str)
162
+ sc_key = tix.loc[sc_gsms, "library_key"].to_numpy().astype(str)
163
+ sc_sum = np.zeros((len(sc_gsms), 20097))
164
+ sc_valid_all = np.zeros((len(sc_gsms), 20097), dtype=bool)
165
+ sc_n = np.zeros(len(sc_gsms), dtype=np.int64)
166
+ sc_n_all = np.zeros(len(sc_gsms), dtype=np.int64)
167
+ for i, g in enumerate(sc_gsms):
168
+ with h5py.File(RUN / "singlecell" / g / "pseudobulk_per_published_sample.h5", "r") as f:
169
+ require(np.array_equal(text(f["gene_id"][:]), gene_ids), f"{g}: gene order")
170
+ require(len(f["sample_id"]) == 1, f"{g}: exactly one sample per library")
171
+ require(f.attrs["units"] == "UMI_counts", f"{g}: units")
172
+ sc_sum[i] = f["qc_review_pass_cells_sum"][0]
173
+ sc_valid_all[i] = f["harmonization_valid"][:].astype(bool)
174
+ sc_n[i] = int(f["n_cells"][1, 0])
175
+ sc_n_all[i] = int(f["n_cells"][0, 0])
176
+ require(np.array_equal(sc_sum[i], np.rint(sc_sum[i])) and (sc_sum[i] >= 0).all(), f"{g}: noninteger sum")
177
+ require((sc_sum[i][~sc_valid_all[i]] == 0).all(), f"{g}: mass outside the measured mask")
178
+ srow = {g: i for i, g in enumerate(sc_gsms)}
179
+
180
+ # ---------------- per-pair feature rows
181
+ bi = np.asarray([brow[g] for g in pairs.bulk_gsm])
182
+ si = np.asarray([srow[g] for g in pairs.sc_gsm])
183
+ require(np.array_equal(b_index[bi], pairs.bulk_title.to_numpy()), "bulk sample id join")
184
+ bulk_raw = bulk_all[bi]
185
+ bulk_valid = b_valid[bi]
186
+ pseudo_raw_sum = sc_sum[si]
187
+ sc_valid = sc_valid_all[si]
188
+ qc_cell_counts = sc_n[si]
189
+
190
+ # ---------------- sex check (source axis; XIST is not protein-coding)
191
+ bsrc = np.load(RUN / "bulk/bulk_source_counts.npz")
192
+ bids = list(bsrc["gene_ids"])
193
+ bcounts = bsrc["counts"]
194
+ bcpm = bcounts / bcounts.sum(1, keepdims=True) * 1e6
195
+ b_src_gsm = list(bsrc["gsm"])
196
+ sex_rows = []
197
+ for g in sc_gsms:
198
+ z = np.load(RUN / "singlecell" / g / "source_axis_pseudobulk.npz")
199
+ fid = list(z["feature_ids"])
200
+ tot = z["qc_pass_sum"][z["rna"]].sum()
201
+ rec = {"sc_gsm": g}
202
+ for gene in SEX_GENES:
203
+ rec["sc_" + gene + "_cpm"] = float(z["qc_pass_sum"][fid.index(SEX_IDS[gene])] / tot * 1e6)
204
+ rec["sc_Ysum_cpm"] = sum(rec["sc_" + x + "_cpm"] for x in Y_GENES)
205
+ rec["sc_sex_call"], rec["sc_sex_score"] = sex_call(rec["sc_XIST_cpm"], rec["sc_Ysum_cpm"])
206
+ sex_rows.append(rec)
207
+ sc_sex = pd.DataFrame(sex_rows).set_index("sc_gsm")
208
+ bulk_sex_rows = []
209
+ for j, g in enumerate(b_src_gsm):
210
+ rec = {"bulk_gsm": g}
211
+ for gene in SEX_GENES:
212
+ rec["bulk_" + gene + "_cpm"] = float(bcpm[j, bids.index(SEX_IDS[gene])])
213
+ rec["bulk_Ysum_cpm"] = sum(rec["bulk_" + x + "_cpm"] for x in Y_GENES)
214
+ rec["bulk_sex_call"], rec["bulk_sex_score"] = sex_call(rec["bulk_XIST_cpm"], rec["bulk_Ysum_cpm"])
215
+ bulk_sex_rows.append(rec)
216
+ bulk_sex = pd.DataFrame(bulk_sex_rows).set_index("bulk_gsm")
217
+
218
+ # ---------------- expression identity
219
+ common = b_valid.all(0) & sc_valid_all.all(0)
220
+ use_genes = common & ~chr_y # chrY excluded: keeps the expression test independent of the sex test
221
+
222
+ def logcpm(m: np.ndarray) -> np.ndarray:
223
+ x = m[:, use_genes]
224
+ return np.log2(x / x.sum(1, keepdims=True) * 1e6 + 1)
225
+
226
+ lb_all, ls_all = logcpm(bulk_all), logcpm(sc_sum)
227
+ use_ids = gene_ids[use_genes]
228
+ # (a) Ye's "as specified" test: Spearman over the top 2,000 genes by mean, raw and modality-centred
229
+ mean_score = 0.5 * (lb_all.mean(0) + ls_all.mean(0))
230
+ top = np.argsort(-mean_score, kind="mergesort")[:TOP_N]
231
+ rho = spearman_matrix(lb_all[bi][:, top], ls_all[:, top])
232
+ rho_rev = spearman_matrix(ls_all[si][:, top], lb_all[:, top])
233
+ cb, cs = lb_all - lb_all.mean(0), ls_all - ls_all.mean(0)
234
+ rho_c = spearman_matrix(cb[bi][:, top], cs[:, top])
235
+ expr = []
236
+ for r in range(n):
237
+ own = si[r]
238
+ order = np.argsort(-rho[r]); order_c = np.argsort(-rho_c[r]); rev = np.argsort(-rho_rev[r])
239
+ expr.append({"sample_id": pairs.sample_id[r], "bulk_gsm": pairs.bulk_gsm[r], "sc_gsm": pairs.sc_gsm[r],
240
+ "rho_own": rho[r, own], "best_sc_gsm": sc_gsms[order[0]], "rho_best": rho[r, order[0]],
241
+ "own_rank_among_sc": rank_of(rho[r], own), "best_is_own": bool(order[0] == own),
242
+ "centred_own_rank_among_sc": rank_of(rho_c[r], own), "centred_best_is_own": bool(order_c[0] == own),
243
+ "reverse_best_bulk_gsm": b_gsm[rev[0]], "reverse_own_rank_among_bulk": rank_of(rho_rev[r], bi[r]),
244
+ "reverse_best_is_own": bool(rev[0] == bi[r])})
245
+ expr = pd.DataFrame(expr)
246
+
247
+ # (b) donor-sensitive residualised test (uses no pairing information): within each modality centre
248
+ # log2(CPM+1), remove the top k sample PCs (computed on expressed genes), keep the 2,000 genes with the
249
+ # highest residual variance in both modalities (rank sum), Pearson bulk x sc.
250
+ expressed = (lb_all.mean(0) > 3) & (ls_all.mean(0) > 1)
251
+ ex = np.flatnonzero(expressed)
252
+
253
+ def resid(x: np.ndarray, k: int) -> np.ndarray:
254
+ xc = x - x.mean(0)
255
+ if k == 0:
256
+ return xc
257
+ u = np.linalg.svd(xc[:, ex], full_matrices=False)[0][:, :k]
258
+ return xc - u @ (u.T @ xc)
259
+
260
+ disc = {}
261
+ fw_primary = None
262
+ for k in RESID_K:
263
+ rb_, rs_ = resid(lb_all, k), resid(ls_all, k)
264
+ vb = np.where(expressed, rb_.var(0), -1.0); vs = np.where(expressed, rs_.var(0), -1.0)
265
+ sel = np.argsort(rankdata(-vb) + rankdata(-vs), kind="mergesort")[:TOP_N]
266
+ full = pearson_matrix(rb_[:, sel], rs_[:, sel]) # all 128 bulks x all 46 sc
267
+ if k == K_PRIMARY:
268
+ fw_primary, sel_primary = full, sel
269
+ cols = {c: [] for c in ("own_rank_bulk_to_sc", "own_rank_sc_to_bulk", "best_sc_gsm", "best_bulk_gsm", "r_own",
270
+ "r_best", "patient_rank_bulk_to_sc", "patient_rank_sc_to_bulk", "best_sc_patient",
271
+ "best_bulk_patient", "r_best_other_patient_sc", "own_tp_best_within_patient_sc",
272
+ "own_tp_best_within_patient_bulk")}
273
+ for r in range(n):
274
+ fwr, bwr = full[bi[r]], full[:, si[r]]
275
+ own_p = pairs.patient[r]
276
+ cols["own_rank_bulk_to_sc"].append(rank_of(fwr, si[r]))
277
+ cols["own_rank_sc_to_bulk"].append(rank_of(bwr, bi[r]))
278
+ cols["best_sc_gsm"].append(sc_gsms[int(np.argmax(fwr))])
279
+ cols["best_bulk_gsm"].append(b_gsm[int(np.argmax(bwr))])
280
+ cols["r_own"].append(float(fwr[si[r]])); cols["r_best"].append(float(fwr.max()))
281
+ pr, pb, _ = patient_rank(fwr, sc_patient, own_p)
282
+ pr2, pb2, _ = patient_rank(bwr, b_patient, own_p)
283
+ cols["patient_rank_bulk_to_sc"].append(pr); cols["patient_rank_sc_to_bulk"].append(pr2)
284
+ cols["best_sc_patient"].append(pb); cols["best_bulk_patient"].append(pb2)
285
+ cols["r_best_other_patient_sc"].append(float(fwr[sc_patient != own_p].max()))
286
+ same = np.flatnonzero(sc_patient == own_p)
287
+ cols["own_tp_best_within_patient_sc"].append(
288
+ bool(fwr[same].argmax() == np.flatnonzero(same == si[r])[0]) if len(same) > 1 else None)
289
+ sameb = np.flatnonzero(b_patient == own_p)
290
+ cols["own_tp_best_within_patient_bulk"].append(
291
+ bool(bwr[sameb].argmax() == np.flatnonzero(sameb == bi[r])[0]) if len(sameb) > 1 else None)
292
+ for c, v in cols.items():
293
+ expr[f"resid_k{k}_{c}"] = v
294
+ # discrimination over ALL bulks / sc libraries whose patient exists in the other modality
295
+ have_sc = np.isin(b_patient, sc_patient)
296
+ top_bulk = [sc_patient[int(np.argmax(full[j]))] == b_patient[j] for j in np.flatnonzero(have_sc)]
297
+ have_b = np.isin(sc_patient, b_patient)
298
+ top_sc = [b_patient[int(np.argmax(full[:, i]))] == sc_patient[i] for i in np.flatnonzero(have_b)]
299
+ chance_b = float(np.mean([np.mean(sc_patient == b_patient[j]) for j in np.flatnonzero(have_sc)]))
300
+ chance_s = float(np.mean([np.mean(b_patient == sc_patient[i]) for i in np.flatnonzero(have_b)]))
301
+ same_mask = b_patient[:, None] == sc_patient[None, :]
302
+ pair_mask = np.zeros_like(same_mask); pair_mask[bi, si] = True
303
+ disc[k] = {"n_genes_selected": int(len(sel)),
304
+ "pairs_own_library_top1_bulk_to_sc": int((np.asarray(cols["own_rank_bulk_to_sc"]) == 1).sum()),
305
+ "pairs_own_library_top1_sc_to_bulk": int((np.asarray(cols["own_rank_sc_to_bulk"]) == 1).sum()),
306
+ "pairs_own_patient_top1_bulk_to_sc": int((np.asarray(cols["patient_rank_bulk_to_sc"]) == 1).sum()),
307
+ "pairs_own_patient_top1_sc_to_bulk": int((np.asarray(cols["patient_rank_sc_to_bulk"]) == 1).sum()),
308
+ "all_bulks_top_sc_same_patient": f"{int(np.sum(top_bulk))}/{len(top_bulk)}",
309
+ "all_bulks_chance_rate": round(chance_b, 4),
310
+ "all_sc_top_bulk_same_patient": f"{int(np.sum(top_sc))}/{len(top_sc)}",
311
+ "all_sc_chance_rate": round(chance_s, 4),
312
+ "auc_same_patient_vs_other_patient_all_bulk_sc_combinations": auc(full[same_mask], full[~same_mask]),
313
+ "median_r_paired": float(np.median(full[pair_mask])),
314
+ "median_r_same_patient_other_timepoint": float(np.median(full[same_mask & ~pair_mask])),
315
+ "median_r_other_patient": float(np.median(full[~same_mask])),
316
+ "p99_r_other_patient": float(np.quantile(full[~same_mask], 0.99)),
317
+ "timepoint_own_best_within_patient_bulk_to_sc":
318
+ f"{sum(v is True for v in cols['own_tp_best_within_patient_sc'])}/"
319
+ f"{sum(v is not None for v in cols['own_tp_best_within_patient_sc'])}",
320
+ "timepoint_own_best_within_patient_sc_to_bulk":
321
+ f"{sum(v is True for v in cols['own_tp_best_within_patient_bulk'])}/"
322
+ f"{sum(v is not None for v in cols['own_tp_best_within_patient_bulk'])}"}
323
+ # full primary correlation matrix (bulk x sc) for audit
324
+ pd.DataFrame(fw_primary, index=b_gsm, columns=sc_gsms).to_csv(RUN / f"identity_resid_k{K_PRIMARY}_bulk_x_sc.csv")
325
+
326
+ # anomaly probe: N127 / N131 libraries (cell names 'N127131AC', 'N1131AC', 'N131NS'; orig.ident '...V01AC')
327
+ probe = {}
328
+ for g in sc_gsms:
329
+ if sc_patient[srow[g]] in ("N127", "N131"):
330
+ col = fw_primary[:, srow[g]]
331
+ o = np.argsort(-col)[:3]
332
+ probe[sc_key[srow[g]]] = {"top_bulk": [(b_index[j], round(float(col[j]), 3)) for j in o],
333
+ "r_bulk_N131_chili_BC": float(col[b_index.tolist().index("N131_chili_BC")])}
334
+ rs5 = resid(ls_all, K_PRIMARY)[:, sel_primary]
335
+ ids_probe = [srow[g] for g in sc_gsms if sc_patient[srow[g]] in ("N127", "N131")]
336
+ probe["sc_sc_residual_pearson"] = {f"{sc_key[a]}~{sc_key[b]}": float(np.corrcoef(rs5[a], rs5[b])[0, 1])
337
+ for x, a in enumerate(ids_probe) for b in ids_probe[x + 1:]}
338
+ other = [float(np.corrcoef(rs5[a], rs5[b])[0, 1]) for a in range(len(sc_gsms)) for b in range(a + 1, len(sc_gsms))
339
+ if sc_patient[a] != sc_patient[b]]
340
+ same_p = [float(np.corrcoef(rs5[a], rs5[b])[0, 1]) for a in range(len(sc_gsms)) for b in range(a + 1, len(sc_gsms))
341
+ if sc_patient[a] == sc_patient[b] and not {sc_patient[a]} & {"N127", "N131"}]
342
+ probe["sc_sc_reference"] = {"different_patients_median": float(np.median(other)), "different_patients_p99": float(np.quantile(other, .99)),
343
+ "same_patient_other_patients_median": float(np.median(same_p)), "same_patient_min": float(np.min(same_p))}
344
+
345
+ # specimen evidence: bulk (PAXgene whole blood) vs sc (PBMC) composition marker CPM on the canonical axis
346
+ spec = {}
347
+ bc_cpm = bulk_all / bulk_all.sum(1, keepdims=True) * 1e6
348
+ sc_cpm = sc_sum / sc_sum.sum(1, keepdims=True) * 1e6
349
+ for grp, genes in SPECIMEN_GENES.items():
350
+ for gname in genes:
351
+ j = np.flatnonzero(sym == gname)
352
+ if len(j) == 1:
353
+ spec[f"{grp}:{gname}"] = {"bulk_median_cpm_paired": float(np.median(bc_cpm[bi, j[0]])),
354
+ "sc_median_cpm_paired": float(np.median(sc_cpm[si, j[0]]))}
355
+ hb = np.isin(sym, SPECIMEN_GENES["hemoglobin"])
356
+ spec["hemoglobin_fraction_of_canonical_bulk_counts_paired"] = {
357
+ "median": float(np.median(bulk_all[bi][:, hb].sum(1) / bulk_all[bi].sum(1))),
358
+ "min": float(np.min(bulk_all[bi][:, hb].sum(1) / bulk_all[bi].sum(1))),
359
+ "max": float(np.max(bulk_all[bi][:, hb].sum(1) / bulk_all[bi].sum(1)))}
360
+ spec["hemoglobin_fraction_of_canonical_sc_counts_paired"] = {
361
+ "median": float(np.median(sc_sum[si][:, hb].sum(1) / sc_sum[si].sum(1)))}
362
+
363
+ # ---------------- cells on the 6k panel (two passes: per-library temp files, then one CSR)
364
+ cm = pd.read_csv(RUN / "r_export/cell_metadata.csv.gz", dtype=str, keep_default_na=False,
365
+ usecols=["cell", "predicted.celltype.l1", "predicted.celltype.l2", "predicted.celltype.l3",
366
+ "predicted.celltype.l2.score", "mapping.score"]).set_index("cell")
367
+ if TMP.exists():
368
+ shutil.rmtree(TMP)
369
+ TMP.mkdir()
370
+ nnz_per, obs_blocks = [], []
371
+ for r in range(n):
372
+ g = pairs.sc_gsm[r]
373
+ h5 = RUN / "singlecell" / g / "canonical.h5ad"
374
+ with h5py.File(h5, "r") as f:
375
+ X = f["X"]
376
+ ncell = len(X["indptr"]) - 1
377
+ full = sp.csr_matrix((X["data"][:], X["indices"][:], X["indptr"][:]), shape=(ncell, 20097))
378
+ o = f["obs"]
379
+ keep = o["flag_conservative_review_pass"][:].astype(bool)
380
+ obs = pd.DataFrame({"cell_index": np.arange(ncell), "barcode": text(o["_index"][:]),
381
+ "raw_gex_total": o["cell_total"][:], "n_genes": o["cell_detected"][:],
382
+ "mito_pct": o["cell_mito_percent"][:],
383
+ "flag_low_total_mad": o["flag_low_total_mad"][:].astype(bool),
384
+ "flag_low_genes_mad": o["flag_low_genes_mad"][:].astype(bool),
385
+ "flag_high_mito_mad": o["flag_high_mito_mad"][:].astype(bool),
386
+ "flag_high_total_review_only": o["flag_high_total_review_only"][:].astype(bool)})
387
+ require(np.array_equal(text(o["sample_id"][:]), np.full(ncell, pairs.sample_id[r])), f"{g}: sample id")
388
+ require(int(keep.sum()) == qc_cell_counts[r], f"{g}: retained-cell count differs from pseudobulk file")
389
+ kept = full[np.flatnonzero(keep)]
390
+ require(np.array_equal(np.asarray(kept.sum(0)).ravel(), pseudo_raw_sum[r]), f"{g}: canonical sum differs")
391
+ sub = kept[:, positions].tocsr()
392
+ sub.sort_indices()
393
+ require(np.array_equal(sub.data, np.rint(sub.data)) and (sub.data >= 0).all() and
394
+ (sub.data.max(initial=0) < 2**31), f"{g}: non-integer or overflowing counts")
395
+ require(np.array_equal(np.asarray(sub.sum(0)).ravel(), pseudo_raw_sum[r, positions]), f"{g}: panel sum")
396
+ np.save(TMP / f"{r:03d}_data.npy", sub.data.astype(np.int32))
397
+ np.save(TMP / f"{r:03d}_indices.npy", sub.indices.astype(np.int32))
398
+ np.save(TMP / f"{r:03d}_indptr.npy", sub.indptr.astype(np.int64))
399
+ sx = np.load(RUN / "singlecell" / g / "cell_sex_gene_counts.npz")
400
+ require(list(sx["genes"]) == SEX_GENES and sx["found"].all(), f"{g}: sex genes")
401
+ obs = obs[keep].reset_index(drop=True)
402
+ obs["cell_total_canonical"] = np.asarray(kept.sum(1)).ravel()
403
+ obs["lib_panel"] = np.asarray(sub.sum(1)).ravel()
404
+ for k, gene in enumerate(SEX_GENES):
405
+ obs[("xist" if gene == "XIST" else "y_" + gene)] = sx["counts"][k][keep]
406
+ obs["y_sum"] = obs[["y_" + x for x in Y_GENES]].sum(1)
407
+ obs.insert(2, "library_id", g)
408
+ obs.insert(3, "sample_id", pairs.sample_id[r])
409
+ obs.insert(4, "donor_id", pairs.patient[r])
410
+ obs.insert(5, "group", pairs.timepoint[r])
411
+ a = cm.reindex(obs.barcode)
412
+ require(a.notna().all().all() and np.array_equal(a.index.to_numpy(), obs.barcode.to_numpy()), f"{g}: author labels")
413
+ obs["author_cell_type"] = a["predicted.celltype.l2"].to_numpy()
414
+ obs["row_sample"] = np.int32(r)
415
+ # extra columns (appended after the Ye 2026 schema)
416
+ obs["author_cell_type_l1"] = a["predicted.celltype.l1"].to_numpy()
417
+ obs["author_cell_type_l3"] = a["predicted.celltype.l3"].to_numpy()
418
+ obs["author_cell_type_l2_score"] = a["predicted.celltype.l2.score"].astype(float).to_numpy()
419
+ obs["author_mapping_score"] = a["mapping.score"].astype(float).to_numpy()
420
+ obs["outcome"] = pairs.outcome[r]
421
+ obs_blocks.append(obs)
422
+ nnz_per.append(sub.nnz)
423
+ print(f"{g} {pairs.sample_id[r]}: {sub.shape[0]} cells, nnz {sub.nnz}", flush=True)
424
+ del full, kept, sub
425
+ total_nnz = int(sum(nnz_per))
426
+ total_cells = int(qc_cell_counts.sum())
427
+ data = np.lib.format.open_memmap(TMP / "all_data.npy", mode="w+", dtype=np.int32, shape=(total_nnz,))
428
+ indices = np.lib.format.open_memmap(TMP / "all_indices.npy", mode="w+", dtype=np.int32, shape=(total_nnz,))
429
+ indptr = np.empty(total_cells + 1, dtype=np.int64)
430
+ indptr[0] = 0
431
+ at, cell_at = 0, 0
432
+ for r in range(n):
433
+ d = np.load(TMP / f"{r:03d}_data.npy"); ix = np.load(TMP / f"{r:03d}_indices.npy")
434
+ ip = np.load(TMP / f"{r:03d}_indptr.npy")
435
+ data[at:at + len(d)] = d
436
+ indices[at:at + len(d)] = ix
437
+ indptr[cell_at + 1:cell_at + len(ip)] = ip[1:] + at
438
+ at += len(d); cell_at += len(ip) - 1
439
+ require(at == total_nnz and cell_at == total_cells, "assembly size")
440
+ cobs = pd.concat(obs_blocks, ignore_index=True)
441
+ row_sample = cobs.row_sample.to_numpy(np.int32)
442
+ require(np.all(np.diff(row_sample) >= 0), "cells must be grouped by row")
443
+ require(np.array_equal(np.bincount(row_sample, minlength=n), qc_cell_counts), "assembled cell counts")
444
+ starts = np.concatenate([[0], np.cumsum(qc_cell_counts)])
445
+ for r in range(n):
446
+ a_, b_ = indptr[starts[r]], indptr[starts[r + 1]]
447
+ s_r = np.bincount(indices[a_:b_], weights=data[a_:b_].astype(np.float64), minlength=len(positions))
448
+ require(np.array_equal(s_r, pseudo_raw_sum[r, positions]), f"row {r}: assembled panel sum differs")
449
+ require(np.all(np.diff(indptr) >= 0) and indptr[-1] == total_nnz, "indptr")
450
+
451
+ # ---------------- write
452
+ OUT.mkdir(parents=True, exist_ok=True)
453
+ S = lambda c: pairs[c].to_numpy().astype(str) # noqa: E731
454
+ meta_arrays = {
455
+ "gene_ids": gene_ids, "sample_ids": S("sample_id"), "donor_ids": S("patient"), "groups": S("timepoint"),
456
+ "timepoints": S("timepoint"), "outcome": S("outcome"),
457
+ "bulk_raw": bulk_raw.astype(np.float64), "pseudo_raw_sum": pseudo_raw_sum.astype(np.float64),
458
+ "bulk_valid": bulk_valid, "sc_valid": sc_valid, "pair_valid": bulk_valid & sc_valid,
459
+ "qc_cell_counts": qc_cell_counts.astype(np.int64),
460
+ "bulk_gsm": S("bulk_gsm"), "sc_gsm": S("sc_gsm"), "sc_title_sample_id": S("PID_visit"),
461
+ "id_match": S("id_match"), "bulk_title": S("bulk_title"), "sc_title": S("sc_title"),
462
+ "bulk_library": S("bulk_library"), "sc_library_key": S("library_key"), "bulk_batch": S("bulk_batch"),
463
+ "sc_round": S("round"), "sex_geo": S("sex_geo_sc"), "age_geo": S("age_geo_sc"),
464
+ "age_geo_bulk": S("age_geo_bulk"), "regimen": S("regimen_sc"), "cancer_type": S("cancer_type"),
465
+ "steroid_bulk": S("steroid_bulk"), "steroid_sc": S("steroid_sc"),
466
+ }
467
+ panel_gene_ids = gene_ids[positions]
468
+ tmp = OUT / "cells_panel6k.npz.tmp"
469
+ with open(tmp, "wb") as h:
470
+ np.savez_compressed(h, data=data, indices=indices, indptr=indptr,
471
+ shape=np.array([total_cells, len(positions)], dtype=np.int64), row_sample=row_sample,
472
+ panel_gene_ids=panel_gene_ids, panel_measured=sc_valid[:, positions])
473
+ os.replace(tmp, OUT / "cells_panel6k.npz")
474
+ cobs.to_parquet(OUT / "cells_obs.parquet", index=False)
475
+ pd.DataFrame({"row": np.arange(n), "sample_id": meta_arrays["sample_ids"], "donor_id": meta_arrays["donor_ids"],
476
+ "group": meta_arrays["groups"], "n_cells": qc_cell_counts}).to_csv(OUT / "samples.csv", index=False)
477
+
478
+ # pairs.csv with identity results
479
+ p = pairs[["sample_id", "bulk_gsm", "sc_gsm", "bulk_title", "sc_title", "id_match", "timepoint", "outcome",
480
+ "sex_geo_sc", "age_geo_sc", "age_geo_bulk", "regimen_sc", "cancer_type", "steroid_bulk", "steroid_sc",
481
+ "bulk_library", "bulk_batch", "library_key", "round", "PID_visit", "bulk_subject_raw",
482
+ "seurat_orig_ident", "metadata_notes"]].copy()
483
+ p.insert(3, "donor_id", pairs.patient.to_numpy())
484
+ p.insert(4, "row", np.arange(n))
485
+ p.insert(8, "group", pairs.timepoint.to_numpy())
486
+ p = p.rename(columns={"sex_geo_sc": "sex_geo", "age_geo_sc": "age_geo", "regimen_sc": "regimen"})
487
+ p["n_cells_library"] = [summaries[g]["n_cells"] for g in p.sc_gsm]
488
+ p["n_cells_retained"] = qc_cell_counts
489
+ for c in ("bulk_XIST_cpm", "bulk_Ysum_cpm", "bulk_sex_score", "bulk_sex_call"):
490
+ p[c] = bulk_sex.loc[p.bulk_gsm, c].to_numpy()
491
+ for c in ("sc_XIST_cpm", "sc_Ysum_cpm", "sc_sex_score", "sc_sex_call"):
492
+ p[c] = sc_sex.loc[p.sc_gsm, c].to_numpy()
493
+ geo = p.sex_geo.str.lower()
494
+ p["sex_concordant"] = (p.bulk_sex_call == p.sc_sex_call) & (p.sc_sex_call == geo)
495
+ p["bulk_possible_mixture"] = ((p.bulk_sex_call == "female") & (p.bulk_Ysum_cpm > 20)) | \
496
+ ((p.bulk_sex_call == "male") & (p.bulk_XIST_cpm > 50))
497
+ e = expr.set_index("bulk_gsm")
498
+ for c in ("rho_own", "rho_best", "own_rank_among_sc", "best_is_own", "best_sc_gsm", "centred_own_rank_among_sc",
499
+ "centred_best_is_own", "reverse_own_rank_among_bulk", "reverse_best_is_own"):
500
+ p["expr_" + c] = e.loc[p.bulk_gsm, c].to_numpy()
501
+ for k in RESID_K:
502
+ for c in ("own_rank_bulk_to_sc", "own_rank_sc_to_bulk", "patient_rank_bulk_to_sc", "patient_rank_sc_to_bulk",
503
+ "best_sc_gsm", "best_sc_patient", "best_bulk_patient", "r_own", "r_best", "r_best_other_patient_sc",
504
+ "own_tp_best_within_patient_sc", "own_tp_best_within_patient_bulk"):
505
+ p[f"expr_resid_k{k}_{c}"] = e.loc[p.bulk_gsm, f"resid_k{k}_{c}"].to_numpy()
506
+ sc_name = dict(zip(table.sc_gsm, table.library_key))
507
+ kp = f"expr_resid_k{K_PRIMARY}_"
508
+
509
+ def verdict(row) -> str:
510
+ """pass: sex concordant AND (residualised, k=K_PRIMARY) own PATIENT ranked 1st in one direction and <=5th in
511
+ the other. fail: sex discordant, or own patient ranked >5th in both directions. Otherwise borderline.
512
+ Patient level because the same patient's other time points are legitimate near-ties."""
513
+ r1, r2 = row[kp + "patient_rank_bulk_to_sc"], row[kp + "patient_rank_sc_to_bulk"]
514
+ issues = []
515
+ if not row.sex_concordant:
516
+ issues.append(f"sex bulk={row.bulk_sex_call} sc={row.sc_sex_call} geo={row.sex_geo.lower()}")
517
+ if min(r1, r2) > 5:
518
+ issues.append(f"expression: own patient rank {r1} (bulk->28 sc patients) and {r2} (sc->61 bulk patients); "
519
+ f"bulk best sc = {sc_name[row[kp + 'best_sc_gsm']]}")
520
+ if issues:
521
+ return "fail: " + "; ".join(issues)
522
+ if min(r1, r2) == 1 and max(r1, r2) <= 5:
523
+ return "pass"
524
+ return f"borderline: own patient rank {r1} (bulk->sc) and {r2} (sc->bulk)"
525
+ p["identity_check"] = p.apply(verdict, axis=1)
526
+ p["identity_pass"] = p.identity_check == "pass"
527
+ notes = []
528
+ for _, row in p.iterrows():
529
+ x = []
530
+ if row.bulk_possible_mixture:
531
+ x.append("bulk has opposite-sex signal (possible minor admixture)")
532
+ if row[kp + "own_tp_best_within_patient_sc"] is False:
533
+ x.append("bulk matches this patient's other sc time point slightly better (time point not resolvable)")
534
+ notes.append("; ".join(x))
535
+ p["identity_notes"] = notes
536
+ p.to_csv(OUT / "pairs.csv", index=False)
537
+ require(np.array_equal(p.bulk_gsm.to_numpy(), meta_arrays["bulk_gsm"]), "pairs/features row order")
538
+ meta_arrays["identity_pass"] = p.identity_pass.to_numpy().astype(bool)
539
+ meta_arrays["identity_check"] = p.identity_check.to_numpy().astype(str)
540
+ meta_arrays["sex_bulk_expr"] = p.bulk_sex_call.to_numpy().astype(str)
541
+ meta_arrays["sex_sc_expr"] = p.sc_sex_call.to_numpy().astype(str)
542
+ tmp = OUT / "features.npz.tmp"
543
+ with open(tmp, "wb") as h:
544
+ np.savez_compressed(h, **meta_arrays)
545
+ os.replace(tmp, OUT / "features.npz")
546
+ bsx = bulk_sex.join(pd.Series(dict(zip(b_gsm, b_index)), name="sample_id"))
547
+ bmeta = pd.read_csv(RUN / "pairing/GSE287540_samples.csv", dtype=str, keep_default_na=False).set_index("gsm")
548
+ bsx["sex_geo"] = bmeta.loc[bsx.index, "ch_Sex"].to_numpy()
549
+ bsx["sex_discordant_with_geo"] = bsx.bulk_sex_call != bsx.sex_geo.str.lower()
550
+ bsx.to_csv(OUT / "identity_sex_bulk_all.csv")
551
+ ssx = sc_sex.join(table.set_index("sc_gsm")[["library_key", "sample_id", "sex_geo_sc", "paired"]])
552
+ ssx["sex_discordant_with_geo"] = ssx.sc_sex_call != ssx.sex_geo_sc.str.lower()
553
+ ssx.to_csv(OUT / "identity_sex_sc_all.csv")
554
+ expr.to_csv(OUT / "identity_expression.csv", index=False)
555
+
556
+ unmatched_sc = table[table.paired != "True"][["sc_gsm", "library_key", "sample_id", "unpaired_reason"]]
557
+ unmatched_bulk = pd.read_csv(RUN / "pairing/bulk_without_sc.csv", dtype=str, keep_default_na=False)
558
+
559
+ checks = {
560
+ "gene_positions_sha256_ok": True,
561
+ "panel_gene_ids_match_selected_genes_csv": True,
562
+ "bulk_finite_nonnegative_inside_mask": True,
563
+ "bulk_fractional_values_inside_mask": bulk_fractional,
564
+ "pseudo_raw_sum_equals_sum_of_retained_cells_full_axis": True,
565
+ "cells_panel_sums_equal_pseudo_raw_sum_positions_exactly": True,
566
+ "cells_per_row_equal_qc_cell_counts": True,
567
+ "no_sc_mass_outside_sc_valid": True,
568
+ "one_sample_id_per_library": True,
569
+ "sex_concordant_pairs": f"{int(p.sex_concordant.sum())}/{n}",
570
+ "sex_discordant_bulk_all": bsx[bsx.sex_discordant_with_geo].sample_id.tolist(),
571
+ "sex_discordant_sc_all": ssx[ssx.sex_discordant_with_geo].library_key.tolist(),
572
+ "expression_best_match_is_own_pair": f"{int(p.expr_best_is_own.sum())}/{n}",
573
+ "expression_best_match_is_own_pair_centred": f"{int(p.expr_centred_best_is_own.sum())}/{n}",
574
+ "expression_reverse_best_match_is_own_pair": f"{int(p.expr_reverse_best_is_own.sum())}/{n}",
575
+ "identity_check_pass": f"{int((p.identity_check == 'pass').sum())}/{n}",
576
+ "identity_check_fail": p[p.identity_check.str.startswith('fail')].sample_id.tolist(),
577
+ "identity_check_borderline": p[p.identity_check.str.startswith('borderline')].sample_id.tolist(),
578
+ }
579
+ manifest = {
580
+ "schema": "ji2025_chili_paired_ft_v1",
581
+ "written_utc": datetime.now(timezone.utc).isoformat(), "started_utc": t0.isoformat(),
582
+ "study": "Ji C et al., Cancer Immunol Immunother 2025 (PMC12049347; NCT04476563); bulk GSE287540, scRNA GSE287541",
583
+ "rows": n, "row_order": "bulk GSM ascending", "patients": int(pairs.patient.nunique()),
584
+ "pairs_by_timepoint": p.timepoint.value_counts().to_dict(), "pairs_by_outcome": p.outcome.value_counts().to_dict(),
585
+ "pairs_by_outcome_timepoint": (p.outcome + "_" + p.timepoint).value_counts().to_dict(),
586
+ "pairs_per_patient": p.donor_id.value_counts().to_dict(),
587
+ "pairs_by_id_match": p.id_match.value_counts().to_dict(),
588
+ "cells": {"n_cells": total_cells, "nnz": total_nnz, "per_row_min": int(qc_cell_counts.min()),
589
+ "per_row_median": float(np.median(qc_cell_counts)), "per_row_max": int(qc_cell_counts.max()),
590
+ "author_filtered_cells_in_paired_libraries": int(sum(summaries[g]["n_cells"] for g in pairs.sc_gsm))},
591
+ "retained_cells_rule": "flag_conservative_review_pass = genes>=200 & UMIs>=500 & mito<=20% (qc_core, ImMicro definition) applied to the author-filtered Seurat cells; MAD flags are review-only columns",
592
+ "features_semantics": {
593
+ "bulk_raw": "Salmon 1.10.0 gene-level estimated read counts (QuantSeq 3' FWD, PAXgene WHOLE BLOOD) on the canonical axis, float64 exactly as deposited (never rounded; the deposited table happens to be integer-valued); 0 where bulk_valid is False",
594
+ "pseudo_raw_sum": "sum of retained cells' UMI counts (Seurat RNA@counts) on the canonical axis; storage 0 where sc_valid is False",
595
+ "bulk_valid": "harmonization_valid from qc_bulk.harmonize (gene in the Salmon table, unique mapping)",
596
+ "sc_valid": "harmonization_valid from qc_singlecell.canonical_export (gene in the CellRanger 2020-A feature table)",
597
+ "pair_valid": "bulk_valid & sc_valid",
598
+ "sample_ids": "<patient>_<timepoint>, e.g. N022_TOL", "donor_ids": "patient (N###, zero-padded)",
599
+ "groups": "= timepoints: GEO time label BC (before ICI), AC (control patients ~12 weeks after ICI start), TOL (time of liver injury), FU1 (follow-up 3-49 d after TOL)",
600
+ "outcome": "GEO group: ChILI or control (ICI-treated, no ChILI)",
601
+ "extra_keys": "timepoints, outcome, bulk_gsm, sc_gsm, sc_title_sample_id (=PID_visit), id_match, bulk_title, sc_title, bulk_library, sc_library_key, bulk_batch, sc_round, sex_geo, age_geo, age_geo_bulk, regimen, cancer_type, steroid_bulk, steroid_sc, identity_pass, identity_check, sex_bulk_expr, sex_sc_expr"},
602
+ "specimen_warning": "The bulk RNA is from PAXgene WHOLE BLOOD (GEO extract protocol and paper methods), not PBMC; the sc data are PBMC (dead-cell removed). Same patient and same visit, different specimen. Whole blood contains neutrophils and reticulocyte globin RNA that PBMC lack.",
603
+ "specimen_evidence_median_cpm": spec,
604
+ "identity": {"sex_rule": "CPM on the source axis (bulk: Salmon table; 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)",
605
+ "genes": f"{int(use_genes.sum())} canonical genes measured in all 128 bulks and all {len(sc_gsms)} sc libraries, chrY excluded; {int(expressed.sum())} 'expressed' (bulk mean log2CPM>3 and sc mean>1)",
606
+ "expression_rule_as_ye": f"Spearman over the top {TOP_N} genes by mean log2(CPM+1), each paired bulk vs all {len(sc_gsms)} sc pseudobulks; centred and reverse variants",
607
+ "expression_residualised_rule": f"within each modality centre log2(CPM+1), remove the top k sample PCs (computed on expressed genes), keep the {TOP_N} genes with the highest residual variance in both modalities (rank sum), Pearson all 128 bulks x all {len(sc_gsms)} sc libraries. Primary k={K_PRIMARY} (~10% of the 46 sc libraries; Ye used 10 for 133/207); sensitivity k={list(RESID_K)}. Uses no pairing information.",
608
+ "verdict_rule": f"pass = sex concordant (bulk, sc, GEO) and at k={K_PRIMARY} the own PATIENT ranked 1st in one direction and <=5th in the other (candidates collapsed to patients by their best r: 28 sc patients, 61 bulk patients); fail = sex discordant or own patient >5th in both directions; else borderline",
609
+ "discrimination_by_k": disc,
610
+ "anomaly_probe_N127_N131": probe,
611
+ "policy": "reported only; no row dropped on identity results; features.npz carries identity_pass / identity_check"},
612
+ "checks": checks,
613
+ "excluded": {"quarantined_sc_libraries_among_pairs": quarantined_pairs,
614
+ "sc_libraries_without_bulk": unmatched_sc.to_dict("records"),
615
+ "bulk_samples_without_sc": unmatched_bulk[["gsm", "Sample_title", "ch_time", "reason"]].to_dict("records")},
616
+ "inputs": {"gene_positions": {"path": str(POSITIONS), "sha256": POSITIONS_SHA},
617
+ "selected_genes": {"path": str(SELECTED), "sha256": sha256_file(SELECTED)},
618
+ "canonical_genes": {"path": str(REFERENCE / "canonical_genes.tsv"), "sha256": sha256_file(REFERENCE / "canonical_genes.tsv")},
619
+ "bulk_harmonized": {"path": str(BULK_H5AD), "sha256": sha256_file(BULK_H5AD)},
620
+ "r_export_summary": json.loads((RUN / "r_export/EXPORT_SUMMARY.json").read_text()),
621
+ "sources": json.loads((RUN / "SOURCES.json").read_text())},
622
+ "code": {name: {"path": str(path), "sha256": sha256_file(path)} for name, path in [
623
+ ("assemble", Path(__file__).resolve()), ("pipeline", RUN / "code/ji2025_pipeline.py"),
624
+ ("export_seurat_counts", RUN / "code/export_seurat_counts.R"), ("run_step", RUN / "code/run_step.sh")] + [
625
+ ("bundle/" + q.name, q) for q in sorted((RUN / "code/strict_qc_v1_code_bundle_v5").glob("*.py"))]},
626
+ "processing_dir": str(RUN),
627
+ }
628
+ manifest["outputs"] = {q.name: {"bytes": q.stat().st_size, "sha256": sha256_file(q)}
629
+ for q in sorted(OUT.iterdir()) if q.is_file() and q.name not in ("MANIFEST.json", "QC_REPORT.md")
630
+ and not q.name.startswith("cells_full")}
631
+ (OUT / "MANIFEST.json").write_text(json.dumps(manifest, indent=1, default=str) + "\n")
632
+ shutil.rmtree(TMP)
633
+ print(json.dumps({"rows": n, "cells": manifest["cells"], "checks": checks, "disc_primary": disc[K_PRIMARY]}, indent=1, default=str))
634
+ return 0
635
+
636
+
637
+ if __name__ == "__main__":
638
+ sys.exit(main())
paper-releases/20260928/diffusion/data/source_prep/ji2025_chili/code/ji2025_full_cells.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """data/ji2025_chili/cells_full.npz via the shared tools/build_full_cells.py, unmodified (CPU only).
3
+
4
+ The shared tool keys library roots by dataset name; rather than editing it (other build agents use it), this
5
+ wrapper imports it, registers this run's singlecell/ directory for 'ji2025_chili' in memory, and calls its main().
6
+ All checks (panel columns equal cells_panel6k.npz; per-row full-axis sums equal pseudo_raw_sum) are the tool's own.
7
+ """
8
+ import importlib.util
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ TOOL = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
13
+ "paired_finetune_intradataset_20260927/tools/build_full_cells.py")
14
+ RUN = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/ji2025_chili_v1_20260928")
15
+
16
+ spec = importlib.util.spec_from_file_location("build_full_cells", TOOL)
17
+ bfc = importlib.util.module_from_spec(spec)
18
+ spec.loader.exec_module(bfc)
19
+ bfc.LIBRARY_ROOT.setdefault("ji2025_chili", RUN / "singlecell")
20
+ if bfc.LIBRARY_ROOT["ji2025_chili"] != RUN / "singlecell":
21
+ raise SystemExit("build_full_cells.py already maps ji2025_chili elsewhere")
22
+ print(f"tool {TOOL} sha256 {bfc.sha(TOOL)}", flush=True)
23
+ sys.exit(bfc.main("ji2025_chili"))
paper-releases/20260928/diffusion/data/source_prep/ji2025_chili/code/ji2025_pipeline.py ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Ji et al. 2025 ChILI (Cancer Immunol Immunother) bulk (GSE287540) + scRNA (GSE287541) 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 code/strict_qc_v1_code_bundle_v5,
7
+ sha256 verified against its MANIFEST), exactly as the Ye 2026 build does:
8
+ * qc_core.scan_mtx (streaming MTX audit; cell flags min_genes 200, min_counts 500,
9
+ max mito 20 %, 5-MAD review-only outliers)
10
+ * qc_genes.GeneMapper (frozen 20,097-gene GENCODE v49 axis, ambiguity/conflict quarantine)
11
+ * qc_singlecell.read_axes / canonical_export (canonical sparse H5AD, measured masks, SUM pseudobulk)
12
+ * qc_bulk.from_assembled / harmonize (bulk canonical matrix, NaN + source_feature_present/harmonization_valid)
13
+ Study-specific glue only: GEO SOFT parsing, the patient x timepoint pairing rule, the Salmon count-table
14
+ parser and the per-library obs. The single-cell MTX libraries come from code/export_seurat_counts.R
15
+ (RNA@counts of the author-filtered GEO Seurat object; see r_export/EXPORT_SUMMARY.json).
16
+
17
+ Subcommands: sources | pairing | bulk | sc
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import gzip
23
+ import json
24
+ import re
25
+ import sys
26
+ import time
27
+ from collections import defaultdict
28
+ from concurrent.futures import ProcessPoolExecutor, as_completed
29
+ from datetime import datetime, timezone
30
+ from pathlib import Path
31
+
32
+ import numpy as np
33
+ import pandas as pd
34
+
35
+ DATALAKE = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc")
36
+ RAW = {"GSE287540": DATALAKE / "datasets/GSE287540", "GSE287541": DATALAKE / "datasets/GSE287541"}
37
+ RUN = DATALAKE / "processing/ji2025_chili_v1_20260928"
38
+ BUNDLE = RUN / "code/strict_qc_v1_code_bundle_v5" # verbatim copy of strict_qc_v1_20260913/code_bundle_v5
39
+ REFERENCE = DATALAKE / "processing/strict_qc_v1_20260913/reference" # frozen; read only
40
+ RECEIPTS = DATALAKE / "acquisition/20260927/manifests/download_receipts.jsonl"
41
+ EXPORT = RUN / "r_export"
42
+ BULK_TABLE = RAW["GSE287540"] / "raw/GSE287540_ChILI_bulk_readcount.tsv.gz"
43
+ SEURAT_GZ = RAW["GSE287541"] / "raw/GSE287541_all_pbmc_combined_filtered_SeuratObj.RDS.gz"
44
+ SEURAT_RDS = RUN / "extracted/GSE287541_seurat.rds"
45
+ sys.path.insert(0, str(BUNDLE))
46
+
47
+ import qc_core # noqa: E402
48
+ import qc_genes # noqa: E402
49
+
50
+ SEX_GENES = {"XIST": "ENSG00000229807", "RPS4Y1": "ENSG00000129824", "DDX3Y": "ENSG00000067048",
51
+ "UTY": "ENSG00000183878", "KDM5D": "ENSG00000012817"}
52
+ COUNT_EVIDENCE = ("GEO GSE287541 author-filtered Seurat object (SeuratObject v4 Assay 'RNA'), slot 'counts': "
53
+ "integer UMI counts from CellRanger multi (GRCh38-2020-A); nCount_RNA/nFeature_RNA/percent.mt "
54
+ "reproduce exactly from this slot; exported per library by code/export_seurat_counts.R")
55
+ UNITS_BULK = "salmon_1.10.0_gene_estimated_read_counts_as_deposited"
56
+ TIMES = ("BC", "AC", "TOL", "FU1", "FU2")
57
+
58
+
59
+ def now() -> str:
60
+ return datetime.now(timezone.utc).isoformat()
61
+
62
+
63
+ def log(event: dict) -> None:
64
+ event = {"t": now(), **event}
65
+ line = json.dumps(event, default=str)
66
+ print(line, flush=True)
67
+ with open(RUN / "events.jsonl", "a") as handle:
68
+ handle.write(line + "\n")
69
+
70
+
71
+ def sha256(path: Path) -> str:
72
+ return qc_core.sha256_file(path)
73
+
74
+
75
+ def verify_bundle() -> dict:
76
+ manifest = json.loads((BUNDLE / "MANIFEST.json").read_text())
77
+ for name, digest in manifest["files"].items():
78
+ if sha256(BUNDLE / name) != digest:
79
+ raise RuntimeError(f"Code bundle file changed: {name}")
80
+ return manifest
81
+
82
+
83
+ def norm_patient(pid: str) -> str:
84
+ """'N87' -> 'N087', 'N064' -> 'N064'; the GEO/Seurat patient IDs are not consistently zero-padded."""
85
+ m = re.fullmatch(r"N(\d+)", pid.strip())
86
+ if not m:
87
+ raise ValueError(f"Unexpected patient ID {pid!r}")
88
+ return f"N{int(m.group(1)):03d}"
89
+
90
+
91
+ # ----------------------------------------------------------------- sources
92
+ def receipts() -> dict:
93
+ out = {}
94
+ for line in open(RECEIPTS):
95
+ rec = json.loads(line)
96
+ out[rec["local_path"]] = rec
97
+ return out
98
+
99
+
100
+ def cmd_sources(_args) -> None:
101
+ """sha256 every acquired file used here against its acquisition receipt; hash the gunzipped RDS copy."""
102
+ verify_bundle()
103
+ known = receipts()
104
+ records = []
105
+ for acc, base in RAW.items():
106
+ for path in sorted(list((base / "raw").glob("*")) + list((base / "metadata").glob("*"))):
107
+ if not path.is_file() or path.name.endswith((".partial", ".tmp")):
108
+ continue
109
+ rec = {"accession": acc, "path": str(path), "bytes": path.stat().st_size, "sha256": sha256(path)}
110
+ receipt = known.get(str(path))
111
+ rec["acquisition_receipt"] = bool(receipt)
112
+ if receipt:
113
+ rec.update(url=receipt["url"], receipt_sha256=receipt["sha256"], receipt_bytes=receipt["bytes"],
114
+ receipt_completed_at=receipt["completed_at"],
115
+ matches_receipt=(receipt["sha256"] == rec["sha256"] and receipt["bytes"] == rec["bytes"]))
116
+ if not rec["matches_receipt"]:
117
+ raise RuntimeError(f"Acquired file differs from its receipt: {path}")
118
+ records.append(rec)
119
+ # The GEO .RDS.gz is gzip around an (internally gzip-compressed) RDS: extracted/ holds the outer-gunzipped stream.
120
+ h = __import__("hashlib").sha256()
121
+ with gzip.open(SEURAT_GZ, "rb") as fh:
122
+ for block in iter(lambda: fh.read(1 << 24), b""):
123
+ h.update(block)
124
+ rds = {"path": str(SEURAT_RDS), "bytes": SEURAT_RDS.stat().st_size, "sha256": sha256(SEURAT_RDS),
125
+ "gunzip_of": str(SEURAT_GZ), "gunzip_stream_sha256": h.hexdigest()}
126
+ rds["identical_to_gunzip_stream"] = rds["sha256"] == rds["gunzip_stream_sha256"]
127
+ if not rds["identical_to_gunzip_stream"]:
128
+ raise RuntimeError("extracted RDS differs from the gunzipped acquired file")
129
+ qc_core._write_json(RUN / "SOURCES.json", {"created_at_utc": now(), "files": records, "extracted_rds": rds,
130
+ "receipts": str(RECEIPTS)})
131
+ log({"stage": "sources", "n_files": len(records), "rds_ok": rds["identical_to_gunzip_stream"],
132
+ "unreceipted": [r["path"] for r in records if not r["acquisition_receipt"]]})
133
+
134
+
135
+ # ----------------------------------------------------------------- pairing
136
+ def parse_soft(path: Path) -> pd.DataFrame:
137
+ samples, cur, section = [], None, None
138
+ with gzip.open(path, "rt", encoding="utf-8") as fh:
139
+ for line in fh:
140
+ line = line.rstrip("\n")
141
+ if line.startswith("^"):
142
+ section = line[1:].split(" = ")[0]
143
+ if section == "SAMPLE":
144
+ cur = defaultdict(list)
145
+ cur["gsm"] = [line.split(" = ")[1]]
146
+ samples.append(cur)
147
+ continue
148
+ if section != "SAMPLE" or not line.startswith("!") or " = " not in line:
149
+ continue
150
+ key, val = line[1:].split(" = ", 1)
151
+ if key == "Sample_characteristics_ch1" and ": " in val:
152
+ k, v = val.split(": ", 1)
153
+ cur["ch_" + k.strip()].append(v.strip())
154
+ else:
155
+ cur[key].append(val)
156
+ return pd.DataFrame([{k: "|".join(v) for k, v in s.items()} for s in samples]).fillna("")
157
+
158
+
159
+ def cmd_pairing(_args) -> None:
160
+ out = RUN / "pairing"
161
+ out.mkdir(parents=True, exist_ok=True)
162
+ bulk = parse_soft(RAW["GSE287540"] / "metadata/GSE287540_family.soft.gz")
163
+ sc = parse_soft(RAW["GSE287541"] / "metadata/GSE287541_family.soft.gz")
164
+ bulk.to_csv(out / "GSE287540_samples.csv", index=False)
165
+ sc.to_csv(out / "GSE287541_samples.csv", index=False)
166
+
167
+ # ---- bulk: GEO title '<subject>_<group>_<time>', library 'Library name: itoxNNNNNN' = count-table column
168
+ m = bulk.Sample_title.str.extract(r"^(N\d+)_(chili|control)_(BC|AC|TOL|FU1|FU2)$")
169
+ if m.isna().any().any():
170
+ raise RuntimeError("Unexpected bulk title format")
171
+ if not ((m[0] == bulk.ch_subject) & (m[1] == bulk.ch_group) & (m[2] == bulk.ch_time)).all():
172
+ raise RuntimeError("Bulk title disagrees with GEO characteristics")
173
+ bulk["bulk_library"] = bulk.Sample_description.str.extract(r"^Library name: (itox\d+)$")[0]
174
+ if bulk.bulk_library.isna().any() or not bulk.bulk_library.is_unique or not bulk.Sample_title.is_unique:
175
+ raise RuntimeError("Bulk library names missing or duplicated")
176
+ bulk["patient"] = bulk.ch_subject.map(norm_patient)
177
+ bulk["key"] = bulk.patient + "_" + bulk.ch_time
178
+ if not bulk.key.is_unique:
179
+ raise RuntimeError("Two bulk samples for one patient x timepoint")
180
+ header = gzip.open(BULK_TABLE, "rt").readline().rstrip("\n").split("\t")[1:]
181
+ if sorted(header) != sorted(bulk.bulk_library):
182
+ raise RuntimeError("Bulk count-table columns differ from GEO library names")
183
+
184
+ # ---- sc: GEO titles '<PID_visit>_<round>_GPEX' (GEX) or '_TCR' (V(D)J); GEX joined to the R export
185
+ t = sc.Sample_title.str.extract(r"^(N\d+V\d+)_(Rd\d[ab]?)_(GPEX|TCR)$")
186
+ if t.isna().any().any() or not (t[0] == sc.ch_subject).all() or not (t[1] == sc.ch_batch).all():
187
+ raise RuntimeError("Unexpected sc title format")
188
+ sc["PID_visit"], sc["round"], sc["library_kind"] = t[0], t[1], t[2]
189
+ sc["library_key"] = sc["round"] + "_" + sc.PID_visit
190
+ gex = sc[sc.library_kind == "GPEX"].copy()
191
+ tcr = sc[sc.library_kind == "TCR"].copy()
192
+ if not gex.library_key.is_unique:
193
+ raise RuntimeError("Duplicate GEX library key")
194
+ libs = pd.read_csv(EXPORT / "libraries.csv", dtype=str, keep_default_na=False)
195
+ if sorted(libs.library_key) != sorted(gex.library_key):
196
+ raise RuntimeError("R-export libraries differ from GEO GEX GSMs")
197
+ gex = gex.merge(libs, on="library_key", how="left", validate="one_to_one", suffixes=("", "_seurat"))
198
+ gex["patient"] = gex.PID_visit.str.extract(r"^(N\d+)V\d+$")[0].map(norm_patient)
199
+ # GEO vs Seurat per-library metadata must agree (Seurat fields are per-cell, one unique value per library).
200
+ seurat_steroid = gex.Steroid.replace({"NA": "NA"})
201
+ agree = {"time": gex.ch_time == gex.Time, "group": gex.ch_group == gex.Group, "sex": gex.ch_Sex == gex.Gender,
202
+ "age": gex.ch_age.astype(float) == gex.Age.astype(float), "steroid": gex.ch_steroid == seurat_steroid,
203
+ "patient": gex.patient == gex.Person.map(norm_patient)}
204
+ gex["geo_vs_seurat_disagree"] = [";".join(k for k, v in agree.items() if not v[i]) for i in range(len(gex))]
205
+ hard = gex.geo_vs_seurat_disagree.str.contains("time|group|sex|patient")
206
+ if hard.any(): # identity fields must agree; age/steroid differences are recorded only
207
+ raise RuntimeError(f"GEO vs Seurat identity metadata disagree: {gex[hard].library_key.tolist()}")
208
+ gex["key"] = gex.patient + "_" + gex.ch_time
209
+ gex["group"] = gex.ch_time # groups = timepoint label
210
+ gex["outcome"] = gex.ch_group.str.lower().map({"chili": "ChILI", "control": "control"})
211
+
212
+ # ---- pairing: same patient AND same timepoint label; must agree on sex, outcome group and ICI regimen
213
+ by_key = bulk.set_index("key")
214
+ rows, used_bulk = [], defaultdict(list)
215
+ for _, g in gex.iterrows():
216
+ rec = {"sc_gsm": g.gsm, "sc_title": g.Sample_title, "library_key": g.library_key, "PID_visit": g.PID_visit,
217
+ "round": g["round"], "patient": g.patient, "timepoint": g.ch_time, "sample_id": g.key,
218
+ "outcome": g.outcome, "sex_geo_sc": g.ch_Sex, "age_geo_sc": g.ch_age, "steroid_sc": g.ch_steroid,
219
+ "regimen_sc": g.ch_treatment, "cancer_type": g.Cancer, "sc_subject_raw": g.ch_subject,
220
+ "seurat_orig_ident": g.orig_ident, "seurat_cell_name_token": g.cell_name_token,
221
+ "n_cells_author": int(g.n_cells), "geo_vs_seurat_disagree": g.geo_vs_seurat_disagree,
222
+ "steroid_seurat": g.Steroid}
223
+ if g.key in by_key.index:
224
+ b = by_key.loc[g.key]
225
+ mism = []
226
+ if b.ch_Sex.lower() != g.ch_Sex.lower():
227
+ mism.append("sex")
228
+ if b.ch_group.lower() != g.ch_group.lower():
229
+ mism.append("outcome_group")
230
+ if b.ch_treatment != g.ch_treatment:
231
+ mism.append("regimen")
232
+ notes = []
233
+ if abs(float(b.ch_age) - float(g.ch_age)) > 0:
234
+ notes.append(f"age bulk {b.ch_age} vs sc {g.ch_age}")
235
+ if b.ch_steroid != g.ch_steroid:
236
+ notes.append(f"steroid bulk {b.ch_steroid} vs sc {g.ch_steroid}")
237
+ if abs(float(b.ch_age) - float(g.ch_age)) > 1:
238
+ mism.append("age_gt_1y")
239
+ rec.update({"bulk_gsm": b.gsm, "bulk_title": b.Sample_title, "bulk_library": b.bulk_library,
240
+ "bulk_subject_raw": b.ch_subject, "bulk_batch": b.ch_batch, "sex_geo_bulk": b.ch_Sex,
241
+ "age_geo_bulk": b.ch_age, "steroid_bulk": b.ch_steroid, "regimen_bulk": b.ch_treatment,
242
+ "id_match": ("exact_subject_id" if b.ch_subject == g.patient else "zero_padding_difference"),
243
+ "metadata_mismatch_fields": ";".join(mism), "metadata_notes": "; ".join(notes)})
244
+ used_bulk[b.gsm].append(g.gsm)
245
+ rows.append(rec)
246
+ table = pd.DataFrame(rows)
247
+ table["candidate"] = table.bulk_gsm.notna()
248
+ multi = {b: s for b, s in used_bulk.items() if len(s) > 1}
249
+ table["sc_libraries_for_this_bulk"] = table.bulk_gsm.map(lambda b: len(used_bulk.get(b, [])) if isinstance(b, str) else 0)
250
+ table["paired"] = table.candidate & (table.metadata_mismatch_fields.fillna("") == "") & (table.sc_libraries_for_this_bulk == 1)
251
+ reasons = []
252
+ for _, r in table.iterrows():
253
+ if r.paired:
254
+ reasons.append("")
255
+ elif not r.candidate:
256
+ have = bulk[bulk.patient == r.patient].ch_time.tolist()
257
+ reasons.append(f"no bulk for {r.patient} at {r.timepoint}; bulk timepoints of this patient: "
258
+ f"{','.join(have) if have else 'none (patient absent from GSE287540)'}")
259
+ elif r.metadata_mismatch_fields:
260
+ reasons.append("metadata mismatch: " + r.metadata_mismatch_fields)
261
+ else:
262
+ reasons.append("bulk matched by >1 sc library")
263
+ table["unpaired_reason"] = reasons
264
+ table.to_csv(out / "sc_gex_libraries_with_bulk_match.csv", index=False)
265
+ paired_bulk = set(table[table.paired].bulk_gsm)
266
+ ub = bulk[~bulk.gsm.isin(paired_bulk)].copy()
267
+ sc_keys = set(gex.key)
268
+ sc_patients = set(gex.patient)
269
+ ub["reason"] = [("sc library exists for this key but pairing was refused" if k in sc_keys else
270
+ f"no sc library at {tp}; sc timepoints of this patient: "
271
+ f"{','.join(sorted(gex[gex.patient == p].ch_time)) if p in sc_patients else 'none (patient absent from GSE287541)'}")
272
+ for k, p, tp in zip(ub.key, ub.patient, ub.ch_time)]
273
+ ub[["gsm", "Sample_title", "bulk_library", "ch_subject", "patient", "ch_group", "ch_time", "ch_Sex", "ch_age",
274
+ "ch_treatment", "ch_steroid", "ch_batch", "reason"]].to_csv(out / "bulk_without_sc.csv", index=False)
275
+ p = table[table.paired]
276
+ summary = {"bulk_gsms": len(bulk), "bulk_subjects": int(bulk.patient.nunique()), "sc_gsms_total": len(sc),
277
+ "sc_gex_gsms": len(gex), "sc_tcr_gsms": len(tcr), "sc_gex_patients": int(gex.patient.nunique()),
278
+ "sc_gex_patient_visits": int(gex.PID_visit.nunique()),
279
+ "tcr_library_keys_equal_gex": sorted(tcr.library_key) == sorted(gex.library_key),
280
+ "pairs_total": int(len(p)), "pairs_patients": int(p.patient.nunique()),
281
+ "pairs_by_timepoint": p.timepoint.value_counts().to_dict(),
282
+ "pairs_by_outcome": p.outcome.value_counts().to_dict(),
283
+ "pairs_by_id_match": p.id_match.value_counts().to_dict(),
284
+ "pairs_per_patient": p.patient.value_counts().value_counts().sort_index().to_dict(),
285
+ "pairs_with_metadata_notes": p[p.metadata_notes != ""][["sample_id", "metadata_notes"]].to_dict("records"),
286
+ "bulk_matched_by_multiple_sc": multi,
287
+ "sc_without_bulk": table[~table.paired][["library_key", "sc_gsm", "sample_id", "unpaired_reason"]].to_dict("records"),
288
+ "bulk_without_sc": int(len(ub)),
289
+ "bulk_without_sc_by_timepoint": ub.ch_time.value_counts().to_dict(),
290
+ "rule": ("Pair = same patient AND same GEO timepoint label. Patient = GEO 'subject' (bulk: 'N064'; sc: the "
291
+ "N### prefix of PID_visit 'N064V01'), zero-padded to 3 digits (bulk writes N87/N96 for N087/N096). "
292
+ "Timepoint = GEO 'time' (BC/AC/TOL/FU1/FU2; for sc also equal to the Seurat per-cell Time). "
293
+ "An accepted pair must also agree on GEO sex, outcome group (chili/control) and ICI regimen, and "
294
+ "age within 1 year (differences recorded); steroid-status differences are recorded, not refused. "
295
+ "A bulk sample may pair with only one sc library. TCR GSMs are separate V(D)J libraries and are not paired.")}
296
+ qc_core._write_json(out / "PAIRING_SUMMARY.json", summary)
297
+ log({"stage": "pairing", **{k: summary[k] for k in ("pairs_total", "pairs_patients", "pairs_by_timepoint", "pairs_by_id_match")}})
298
+
299
+
300
+ # ----------------------------------------------------------------- bulk
301
+ def cmd_bulk(_args) -> None:
302
+ import qc_bulk
303
+ verify_bundle()
304
+ mapper = qc_genes.GeneMapper(REFERENCE)
305
+ meta = pd.read_csv(RUN / "pairing/GSE287540_samples.csv", dtype=str, keep_default_na=False)
306
+ meta["bulk_library"] = meta.Sample_description.str.extract(r"^Library name: (itox\d+)$")[0]
307
+ lib2 = meta.set_index("bulk_library")
308
+ header = qc_bulk.read_original_header(BULK_TABLE)
309
+ frame = qc_bulk.load_table(BULK_TABLE, dtype={header[0]: str})
310
+ ids = frame.iloc[:, 0].astype(str)
311
+ if not ids.is_unique:
312
+ raise RuntimeError("Duplicate gene IDs in bulk table")
313
+ values = qc_bulk.numeric_values(frame.iloc[:, 1:]) # samples x genes, float64, unchanged
314
+ libraries = list(frame.columns[1:])
315
+ records = []
316
+ for s, lib in enumerate(libraries):
317
+ g = lib2.loc[lib]
318
+ v = values[s]
319
+ records.append((g.Sample_title, ids.tolist(), None, v,
320
+ {"GSM": g.gsm, "bulk_library": lib, "subject": g.ch_subject, "time": g.ch_time,
321
+ "group": g.ch_group, "batch": g.ch_batch, "library_total": float(v.sum()),
322
+ "fractional_values": int(np.sum(v != np.trunc(v)))}))
323
+ (RUN / "bulk").mkdir(exist_ok=True)
324
+ np.savez_compressed(RUN / "bulk/bulk_source_counts.npz", gene_ids=ids.to_numpy().astype(str),
325
+ sample_ids=np.asarray([r[0] for r in records]), gsm=np.asarray([r[4]["GSM"] for r in records]),
326
+ library=np.asarray(libraries), counts=values)
327
+ fractional = int(np.sum(values != np.trunc(values)))
328
+ assay = qc_bulk.from_assembled(
329
+ "GSE287540", "GSE287540_salmon_counts", UNITS_BULK, records,
330
+ declared_raw_counts=True, sources=[BULK_TABLE],
331
+ caveats=["GEO/paper: RNA from WHOLE BLOOD in PAXgene tubes (PAXgene Blood RNA Kit), not PBMC; "
332
+ "Lexogen QuantSeq 3' mRNA-Seq FWD (100 ng), NextSeq 2000; Salmon 1.10.0 to GRCh38.p14 / Ensembl 110; "
333
+ "GEO: 'Ensembl gene ID by sample matrix of raw counts'.",
334
+ f"Values are Salmon estimated read counts as deposited; {fractional} of {values.size} values are "
335
+ "fractional (the deposited table is integer-valued); no rounding or other change was applied.",
336
+ "Bulk-to-single-cell pairing is by GEO patient ID and timepoint label; see pairing/."],
337
+ extra={"source_format": "single tab-separated gene x library matrix (library names itoxNNNNNN)",
338
+ "fractional_values": fractional, "n_values": int(values.size)})
339
+ report = qc_bulk.harmonize(assay, mapper, RUN / "bulk" / assay.assay_id)
340
+ log({"stage": "bulk", "status": report["status"], "n_samples": report["n_samples"],
341
+ "raw_count_eligible": report["raw_count_eligible"], "canonical_coverage": report["canonical_coverage"],
342
+ "fractional_values": fractional})
343
+
344
+
345
+ # ----------------------------------------------------------------- single cell
346
+ def process_library(row: dict) -> dict:
347
+ import qc_singlecell as qs
348
+ import scipy.io._fast_matrix_market as fmm
349
+ from scipy.io import mmread
350
+
351
+ fmm.PARALLELISM = 1 # single-threaded MTX reader (host CPU budget)
352
+ qs.COUNT_SOURCE_EVIDENCE["GSE287541"] = COUNT_EVIDENCE # provenance string only
353
+ gsm, key = row["sc_gsm"], row["library_key"]
354
+ lib_dir = EXPORT / key
355
+ out = RUN / "singlecell" / gsm
356
+ out.mkdir(parents=True, exist_ok=True)
357
+ summary_path = out / "summary.json"
358
+ if summary_path.exists() and json.loads(summary_path.read_text()).get("status") == "PASS":
359
+ return json.loads(summary_path.read_text())
360
+ item = {"accession": "GSE287541", "library_id": gsm, "path": str(lib_dir / "matrix.mtx.gz"), "format": "mtx",
361
+ "duplicate_representation": False, "features_path": str(EXPORT / "features.tsv.gz"),
362
+ "barcodes_path": str(lib_dir / "barcodes.tsv.gz")}
363
+ summary = {**item, "library_key": key, "sample_id": row["sample_id"], "status": "RUNNING",
364
+ "output_dir": str(out), "started": now()}
365
+ qc_core._write_json(summary_path, summary)
366
+ t0 = time.time()
367
+ try:
368
+ mapper = qc_genes.GeneMapper(REFERENCE)
369
+ ids, symbols, cells, rna, axes = qs.read_axes(item)
370
+ item["matrix_path"] = axes["matrix_path"]
371
+ mapping = mapper.map_features(ids, symbols)
372
+ mapping_summary = mapper.write_rows(mapping, out / "gene_mapping")
373
+ mito = np.asarray([r["mitochondrial"] for r in mapping])
374
+ n = len(cells)
375
+ if len(set(cells)) != n:
376
+ raise qs.QCError("Duplicate barcodes within library")
377
+ cm = pd.read_csv(EXPORT / "cell_metadata.csv.gz", dtype=str, keep_default_na=False,
378
+ usecols=["cell", "library_key", "raw_barcode", "PID_visit"])
379
+ cm = cm[cm.library_key == key].set_index("cell")
380
+ if list(cm.index) != list(cells):
381
+ raise qs.QCError("Barcode order differs from the exported cell metadata")
382
+ obs = pd.DataFrame({"barcode": cells, "source_barcode": cm.raw_barcode.to_numpy(), "raw_10x_barcode": cm.raw_barcode.to_numpy(),
383
+ "author_cell_id": cells, "library_id": gsm, "donor_id": row["patient"],
384
+ "sample_id": row["sample_id"], "visit_id": row["PID_visit"], "author_retained": "true",
385
+ "mapping_basis": "one 10x library per GEO GPEX GSM; author cell name prefix <round>_<PID_visit>",
386
+ "protocol": "10x_5prime_GEX"})
387
+ obs.to_csv(out / "cell_metadata.csv.gz", index=False, compression="gzip")
388
+ metrics = out / "metrics"
389
+ if (metrics / "qc_summary.json").exists():
390
+ qc = json.loads((metrics / "qc_summary.json").read_text())
391
+ else:
392
+ qc = qc_core.scan_mtx(item["path"], metrics, mito_mask=mito, feature_mask=rna,
393
+ sample_ids=obs.sample_id.to_numpy(), feature_ids=ids,
394
+ feature_symbols=symbols, cell_ids=cells)
395
+ total = np.load(metrics / "cell_total.npy")
396
+ detected = np.load(metrics / "cell_detected.npy")
397
+ mito_pct = np.load(metrics / "cell_mito_percent.npy")
398
+ pd.DataFrame([{"min_genes": g, "min_abundance": 500, "max_mito_percent": m,
399
+ "n_review_pass": int(((detected >= g) & (total >= 500) & (mito_pct <= m)).sum())}
400
+ for g in (100, 200, 500) for m in (10, 20, 30)]).to_csv(out / "threshold_sensitivity.csv", index=False)
401
+ integral = qc["numeric"]["integer_fraction_selected_stored"] == 1
402
+ item["source_sha256"] = qc["input"].get("sha256", "")
403
+ item["canonical_identity_sha256"] = mapper.manifest.get("canonical_identity_sha256", "")
404
+ verified = bool(integral)
405
+ units = "UMI_counts" if verified else "nonnegative_abundance_source_units_unproven"
406
+ export = qs.canonical_export(item, out, mapping, mapper.canonical, obs, rna,
407
+ verified_counts=verified, units=units, full_mapping=True)
408
+ qcpass = np.load(metrics / "flag_conservative_review_pass.npy")
409
+ matrix = mmread(item["path"]).tocsc()
410
+ if matrix.shape != (len(ids), n):
411
+ raise qs.QCError("MTX shape changed")
412
+ all_sum = np.asarray(matrix.sum(axis=1)).ravel()
413
+ pass_sum = np.asarray(matrix[:, np.flatnonzero(qcpass)].sum(axis=1)).ravel()
414
+ if not np.isclose(all_sum[rna].sum(), total.sum(), rtol=1e-12):
415
+ raise qs.QCError("Source-axis sum differs from QC scan")
416
+ np.savez_compressed(out / "source_axis_pseudobulk.npz", feature_ids=np.asarray(ids),
417
+ feature_symbols=np.asarray(symbols), rna=rna, all_cells_sum=all_sum,
418
+ qc_pass_sum=pass_sum, n_cells=n, n_qc_pass=int(qcpass.sum()))
419
+ where = {g: i for i, g in enumerate(ids)}
420
+ sex_rows = [where.get(g, -1) for g in SEX_GENES.values()]
421
+ per_cell = np.zeros((len(SEX_GENES), n), dtype=np.float64)
422
+ csr = matrix.tocsr()
423
+ for k, r in enumerate(sex_rows):
424
+ if r >= 0:
425
+ per_cell[k] = csr[r].toarray().ravel()
426
+ np.savez_compressed(out / "cell_sex_gene_counts.npz", genes=np.asarray(list(SEX_GENES)),
427
+ gene_ids=np.asarray(list(SEX_GENES.values())), found=np.asarray(sex_rows) >= 0,
428
+ counts=per_cell)
429
+ del matrix, csr
430
+ author = {"cells": n, "genes_le_200": int((detected <= 200).sum()), "genes_ge_5000": int((detected >= 5000).sum()),
431
+ "mito_ge_5": int((mito_pct >= 5).sum()), "counts_lt_500": int((total < 500).sum()),
432
+ "min_genes": int(detected.min()), "max_genes": int(detected.max()), "min_counts": float(total.min()),
433
+ "max_mito_pct": float(mito_pct.max())}
434
+ summary.update({"status": "PASS", "n_cells": n, "n_features": len(ids),
435
+ "n_rna_features": int(rna.sum()), "n_qc_review_pass": int(qcpass.sum()),
436
+ "flag_counts": qc["flag_counts"], "numeric": qc["numeric"], "units": units,
437
+ "count_space_verified": verified, "count_provenance": COUNT_EVIDENCE,
438
+ "canonicalcoverage": mapping_summary, "canonical_export": export,
439
+ "author_prefilter_evidence": author, "seconds": round(time.time() - t0, 1),
440
+ "finished": now()})
441
+ except Exception as error: # noqa: BLE001 - recorded, not hidden
442
+ summary.update({"status": "QUARANTINED", "error_type": type(error).__name__, "error": str(error)})
443
+ qc_core._write_json(summary_path, summary)
444
+ return summary
445
+
446
+
447
+ def cmd_sc(args) -> None:
448
+ verify_bundle()
449
+ table = pd.read_csv(RUN / "pairing/sc_gex_libraries_with_bulk_match.csv", dtype=str, keep_default_na=False)
450
+ rows = table.to_dict("records")
451
+ if args.gsm:
452
+ rows = [r for r in rows if r["sc_gsm"] in set(args.gsm.split(","))]
453
+ if args.limit:
454
+ rows = rows[:args.limit]
455
+ log({"stage": "sc", "event": "start", "n_libraries": len(rows), "workers": args.workers})
456
+ done = []
457
+ with ProcessPoolExecutor(max_workers=args.workers, max_tasks_per_child=1) as pool:
458
+ futures = {pool.submit(process_library, r): r["sc_gsm"] for r in rows}
459
+ for future in as_completed(futures):
460
+ s = future.result()
461
+ done.append(s)
462
+ log({"stage": "sc", "library": futures[future], "status": s["status"], "n_cells": s.get("n_cells"),
463
+ "n_qc_review_pass": s.get("n_qc_review_pass"), "seconds": s.get("seconds"), "error": s.get("error")})
464
+ if not args.gsm and not args.limit:
465
+ qc_core._write_json(RUN / "singlecell/SINGLECELL_SUMMARY.json",
466
+ {"created_at_utc": now(), "libraries": sorted(done, key=lambda s: s["library_id"])})
467
+ log({"stage": "sc", "event": "finish", "pass": sum(s["status"] == "PASS" for s in done), "n": len(done)})
468
+
469
+
470
+ def main() -> None:
471
+ parser = argparse.ArgumentParser(description=__doc__)
472
+ sub = parser.add_subparsers(dest="cmd", required=True)
473
+ sub.add_parser("sources")
474
+ sub.add_parser("pairing")
475
+ sub.add_parser("bulk")
476
+ p = sub.add_parser("sc")
477
+ p.add_argument("--workers", type=int, default=3)
478
+ p.add_argument("--limit", type=int, default=0)
479
+ p.add_argument("--gsm", default="", help="comma-separated GSM subset")
480
+ args = parser.parse_args()
481
+ RUN.mkdir(parents=True, exist_ok=True)
482
+ {"sources": cmd_sources, "pairing": cmd_pairing, "bulk": cmd_bulk, "sc": cmd_sc}[args.cmd](args)
483
+
484
+
485
+ if __name__ == "__main__":
486
+ main()