junidude14 commited on
Commit
114a98e
·
verified ·
1 Parent(s): cb56dd6

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/59703cc49f583b6b/run_step.sh ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Run one CPU-only Liu 2021 step as a bounded transient systemd user unit (never GPU work).
3
+ # Limits: MemoryMax 40G (MemoryHigh 38G), no swap, <= 8 CPUs, nice 10, idle IO, positive OOM score, no restart,
4
+ # CUDA hidden, <= 8 BLAS/OpenMP threads. Before launching it waits until /proc/meminfo MemAvailable >= 80 GiB
5
+ # (other jobs share this host; a GPU training job stops itself below 32 GiB and the guard acts below 18 GiB).
6
+ # Usage: run_step.sh <step> [args]
7
+ # step: rds (R export) | assemble | findings | prepare | <pipeline subcommand: sources|pairing|bulk|sc|...>
8
+ set -euo pipefail
9
+ RUN=/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/liu2021_v1_20261002
10
+ PY=/home/sj_server_1/miniforge3/envs/scanvi/bin/python
11
+ RS=/home/sj_server_1/miniforge3/envs/r_env/bin/Rscript
12
+ PREP_PY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python
13
+ PREP=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/tools/prepare_dataset.py
14
+ step="$1"; shift || true
15
+ tag="$step"
16
+ case "$step" in
17
+ rds) cmd=("$RS" "$RUN/code/liu2021_rds_export.R" "$@") ;;
18
+ assemble) cmd=("$PY" "$RUN/code/liu2021_assemble.py" "$@") ;;
19
+ findings) cmd=("$PY" "$RUN/code/liu2021_findings.py" "$@") ;;
20
+ sanity) cmd=("$PY" "$RUN/code/liu2021_sanity.py" "$@") ;;
21
+ htosens) cmd=("$PY" "$RUN/code/liu2021_hto_sensitivity.py" "$@") ;;
22
+ finalize) cmd=("$PY" "$RUN/code/liu2021_finalize.py" "$@") ;;
23
+ fullcells) cmd=("$PY" "$RUN/code/liu2021_full_cells.py" "$@") ;;
24
+ prepare) cmd=("$PREP_PY" "$PREP" --dataset liu2021 "$@") ;;
25
+ *) cmd=("$PY" "$RUN/code/liu2021_pipeline.py" "$step" "$@") ;;
26
+ esac
27
+ systemctl --user is-active --quiet ml-memory-guard.service || { echo "ml-memory-guard not active; refusing" >&2; exit 3; }
28
+ need_kib=$((80 * 1024 * 1024))
29
+ for _ in $(seq 1 240); do
30
+ avail=$(awk '/^MemAvailable:/{print $2}' /proc/meminfo)
31
+ if [ "$avail" -ge "$need_kib" ]; then break; fi
32
+ echo "$(date -Is) MemAvailable $((avail / 1024 / 1024)) GiB < 80 GiB; waiting" >> "$RUN/logs/${tag}.log"
33
+ sleep 60
34
+ done
35
+ avail=$(awk '/^MemAvailable:/{print $2}' /proc/meminfo)
36
+ [ "$avail" -ge "$need_kib" ] || { echo "MemAvailable stayed below 80 GiB; not launching" >&2; exit 4; }
37
+ echo "$(date -Is) launch $step MemAvailable $((avail / 1024 / 1024)) GiB" >> "$RUN/logs/${tag}.log"
38
+ unit="liu-${tag}-$(date +%H%M%S)"
39
+ exec systemd-run --user --wait --collect --quiet --unit="$unit" --slice=app.slice \
40
+ -p MemoryHigh=38G -p MemoryMax=40G -p MemorySwapMax=0 -p CPUQuota=800% \
41
+ -p OOMPolicy=kill -p OOMScoreAdjust=500 -p Nice=10 -p IOSchedulingClass=idle \
42
+ --working-directory="$RUN" \
43
+ -E CUDA_VISIBLE_DEVICES= -E OMP_NUM_THREADS=8 -E OPENBLAS_NUM_THREADS=8 -E MKL_NUM_THREADS=8 \
44
+ -E NUMEXPR_NUM_THREADS=8 -E PYTHONDONTWRITEBYTECODE=1 -E PYTHONUNBUFFERED=1 \
45
+ -p StandardOutput="append:$RUN/logs/${tag}.log" -p StandardError="append:$RUN/logs/${tag}.log" \
46
+ "${cmd[@]}"
paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/7f3e5772147e5dda/liu2021_rds_export.R ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env Rscript
2
+ # Liu et al., Cell 2021 (GSE161918): export the author Seurat object's RNA gene-expression counts and the full cell
3
+ # metadata, unchanged, for the Python strict-QC pipeline (CPU only; no GPU, no Seurat computation).
4
+ #
5
+ # Input : datasets/GSE161918/raw/GSE161918_AllBatches_SeuratObj.rds.gz (GEO supplementary file; a gzip of a
6
+ # gzip-compressed RDS, so it is read through gzcon(gzfile()) without writing a decompressed copy).
7
+ # Output: processing/liu2021_v1_20261002/rds_export/
8
+ # STRUCTURE.json object class/version, assays and slot dimensions, metadata column summary, checks
9
+ # cell_metadata.csv.gz object@meta.data with the cell name as column `cell` (all columns, unchanged)
10
+ # rna_genes.txt RNA assay rownames (counts slot), in order
11
+ # rna_cells.txt RNA assay colnames (counts slot), in order (== rownames(meta.data), checked)
12
+ # rna_counts_p.int32 / rna_counts_i.int32 / rna_counts_x.int32
13
+ # the dgCMatrix (genes x cells, CSC) arrays of the RNA counts slot, little endian;
14
+ # as a cells x genes matrix these are CSR (indptr = p, indices = i, data = x).
15
+ # x is written as int32 only after checking every value is a non-negative integer < 2^31.
16
+ # rna_meta_features.csv.gz RNA assay meta.features (if any columns)
17
+ # other_assay_features.json feature names of every non-RNA assay (ADT/HTO), recorded only
18
+ args <- commandArgs(trailingOnly = TRUE)
19
+ src <- "/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/datasets/GSE161918/raw/GSE161918_AllBatches_SeuratObj.rds.gz"
20
+ out <- "/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/liu2021_v1_20261002/rds_export"
21
+ if (Sys.getenv("CUDA_VISIBLE_DEVICES", unset = "unset") != "") stop("run with CUDA_VISIBLE_DEVICES=''")
22
+ suppressPackageStartupMessages({
23
+ library(Matrix)
24
+ library(SeuratObject)
25
+ library(jsonlite)
26
+ library(data.table)
27
+ })
28
+ setDTthreads(as.integer(Sys.getenv("OMP_NUM_THREADS", "4")))
29
+ dir.create(out, showWarnings = FALSE, recursive = TRUE)
30
+ t0 <- Sys.time()
31
+ msg <- function(...) cat(format(Sys.time(), "%H:%M:%S"), ..., "\n", sep = " ")
32
+
33
+ msg("reading", src)
34
+ con <- gzcon(gzfile(src, "rb"))
35
+ obj <- readRDS(con)
36
+ close(con)
37
+ msg("read done; class", class(obj)[1], "; mem", format(object.size(obj), units = "GB"))
38
+ gc()
39
+
40
+ info <- list(source = src, read_seconds = as.numeric(difftime(Sys.time(), t0, units = "secs")),
41
+ class = class(obj), r_version = R.version.string,
42
+ seuratobject_package = as.character(packageVersion("SeuratObject")))
43
+ info$object_version <- tryCatch(as.character(obj@version), error = function(e) NA)
44
+ info$project_name <- tryCatch(obj@project.name, error = function(e) NA)
45
+ info$assays <- list()
46
+ for (a in names(obj@assays)) {
47
+ A <- obj@assays[[a]]
48
+ rec <- list(class = class(A)[1])
49
+ for (s in c("counts", "data", "scale.data")) {
50
+ v <- tryCatch(slot(A, s), error = function(e) NULL)
51
+ if (!is.null(v)) rec[[s]] <- list(class = class(v)[1], dim = dim(v))
52
+ }
53
+ rec$key <- tryCatch(A@key, error = function(e) NA)
54
+ rec$meta_features_columns <- tryCatch(colnames(A@meta.features), error = function(e) NULL)
55
+ info$assays[[a]] <- rec
56
+ }
57
+ info$active_assay <- tryCatch(obj@active.assay, error = function(e) NA)
58
+ info$reductions <- names(obj@reductions)
59
+ info$graphs <- tryCatch(names(obj@graphs), error = function(e) NULL)
60
+ info$misc_names <- tryCatch(names(obj@misc), error = function(e) NULL)
61
+ info$commands <- tryCatch(names(obj@commands), error = function(e) NULL)
62
+ md <- obj@meta.data
63
+ info$n_cells_meta <- nrow(md)
64
+ info$meta_columns <- lapply(md, function(col) {
65
+ u <- unique(col)
66
+ list(class = class(col)[1], n_unique = length(u), n_na = sum(is.na(col)),
67
+ values = if (length(u) <= 60) as.character(sort(u, na.last = TRUE)) else as.character(head(u, 8)))
68
+ })
69
+ msg("meta.data", nrow(md), "x", ncol(md))
70
+ fwrite(cbind(data.table(cell = rownames(md)), as.data.table(md)), file.path(out, "cell_metadata.csv.gz"))
71
+
72
+ # ---------------- RNA counts slot
73
+ rna <- obj@assays[["RNA"]]
74
+ m <- slot(rna, "counts")
75
+ stopifnot(inherits(m, "dgCMatrix"))
76
+ stopifnot(identical(colnames(m), rownames(md)))
77
+ x <- m@x
78
+ chk <- list(nnz = length(x), dim = dim(m), x_min = min(x), x_max = max(x),
79
+ x_all_integer = all(x == round(x)), x_any_zero_stored = any(x == 0),
80
+ x_all_finite = all(is.finite(x)))
81
+ msg("counts", paste(dim(m), collapse = " x "), "nnz", length(x), "integer", chk$x_all_integer)
82
+ stopifnot(chk$x_all_finite, chk$x_min >= 0, chk$x_all_integer, chk$x_max < 2^31)
83
+ # consistency with the author metadata columns (when present)
84
+ ncount <- Matrix::colSums(m)
85
+ nfeat <- diff(m@p)
86
+ if ("nCount_RNA" %in% colnames(md)) {
87
+ chk$nCount_RNA_equals_colSums <- isTRUE(all(md$nCount_RNA == ncount))
88
+ chk$nCount_RNA_max_abs_diff <- max(abs(md$nCount_RNA - ncount))
89
+ }
90
+ if ("nFeature_RNA" %in% colnames(md)) {
91
+ chk$nFeature_RNA_equals_stored_entries <- isTRUE(all(md$nFeature_RNA == nfeat))
92
+ chk$nFeature_RNA_max_abs_diff <- max(abs(md$nFeature_RNA - nfeat))
93
+ }
94
+ chk$gene_names_unique <- !anyDuplicated(rownames(m))
95
+ chk$cell_names_unique <- !anyDuplicated(colnames(m))
96
+ info$rna_counts_checks <- chk
97
+ writeLines(rownames(m), file.path(out, "rna_genes.txt"))
98
+ writeLines(colnames(m), file.path(out, "rna_cells.txt"))
99
+ w <- function(v, name) {
100
+ f <- file(file.path(out, name), "wb")
101
+ writeBin(v, f, size = 4L, endian = "little")
102
+ close(f)
103
+ }
104
+ w(as.integer(m@p), "rna_counts_p.int32")
105
+ w(as.integer(m@i), "rna_counts_i.int32")
106
+ w(as.integer(x), "rna_counts_x.int32")
107
+ rm(x)
108
+ mf <- rna@meta.features
109
+ if (ncol(mf) > 0) fwrite(cbind(data.table(feature = rownames(mf)), as.data.table(mf)), file.path(out, "rna_meta_features.csv.gz"))
110
+ # the normalised data slot is NOT exported; record whether it differs from counts (it should: log-normalised)
111
+ d <- tryCatch(slot(rna, "data"), error = function(e) NULL)
112
+ if (!is.null(d) && inherits(d, "dgCMatrix")) {
113
+ info$rna_data_slot <- list(dim = dim(d), nnz = length(d@x), identical_to_counts = identical(d@x, m@x),
114
+ x_max = max(d@x), x_all_integer = all(d@x == round(d@x)))
115
+ }
116
+ rm(d, m)
117
+ gc()
118
+ other <- list()
119
+ for (a in setdiff(names(obj@assays), "RNA")) {
120
+ A <- obj@assays[[a]]
121
+ other[[a]] <- rownames(A)
122
+ }
123
+ write_json(other, file.path(out, "other_assay_features.json"), auto_unbox = TRUE)
124
+ info$seconds_total <- as.numeric(difftime(Sys.time(), t0, units = "secs"))
125
+ write_json(info, file.path(out, "STRUCTURE.json"), auto_unbox = TRUE, pretty = TRUE, digits = NA, null = "null", na = "null")
126
+ msg("done in", round(info$seconds_total), "s")
paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/8e68b8329137c8ad/liu2021_pipeline.py ADDED
@@ -0,0 +1,690 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Liu et al., Cell 2021 (GSE161918, NIH COVID-19 CITE-seq): PBMC bulk RNA-seq + PBMC CITE-seq GEX processing.
3
+
4
+ CPU only; never imports torch or initializes CUDA.
5
+
6
+ Reuses the frozen strict-QC code bundle v5 VERBATIM (copied to code/strict_qc_v1_code_bundle_v5, sha256 verified
7
+ against its MANIFEST), exactly as the Giroux 2022 / Imperial ESKD / Ye 2026 builds:
8
+ * qc_genes.GeneMapper frozen 20,097-gene GENCODE v49 axis; ID-first mapping with
9
+ ambiguity/conflict quarantine
10
+ * qc_core.scan_h5 per-sample streaming audit and cell flags (min genes 200,
11
+ min counts 500, max mito 20 %, 5-MAD review flags)
12
+ * qc_singlecell.read_axes/canonical_export canonical sparse H5AD, measured masks, SUM pseudobulk
13
+ * qc_bulk.BulkInput/harmonize bulk canonical matrix with NaN + presence/valid layers
14
+ Study-specific glue only (this file):
15
+ * the single cells come from the authors' Seurat object (GEO GSE161918_AllBatches_SeuratObj.rds.gz), exported
16
+ unchanged by code/liu2021_rds_export.R (RNA counts slot + full meta.data). Each author sample (author
17
+ `sample_id` = batch + subject + timepoint) is cut out of the pooled object into a small per-sample source H5AD
18
+ (raw X, same values) so the bundle runs per library, exactly as for Imperial ESKD;
19
+ * cells kept for a sample: unsorted fraction only (author `Sorted` == "N"; the bulk is unsorted PBMC, while the
20
+ sorted fractions are FACS-enriched B/T/monocyte/innate (batch 1) or non-naive T/B (batches 2-3) cells), author
21
+ HTO demultiplexing singlets only (`HTO_classification.global` == "Singlet"; HTO "Doublet" and "Negative" cells
22
+ are dropped), demuxlet singlets only (`DROPLET.TYPE` == "SNG");
23
+ * the Seurat RNA rownames are make.unique() of the Cell Ranger hg19-1.2.0 symbols with '_' -> '-' (Seurat feature
24
+ naming). They equal, position by position, that reference's genes table (reference_crosswalk/, proof in
25
+ CROSSWALK.json), so Ensembl IDs are restored positionally and the bundle maps by ID with the original 10x
26
+ symbol as the checked secondary field (the Giroux / Imperial semantics);
27
+ * pairing: author bulk count-table column <-> GEO bulk GSM (title) <-> sc author sample by subject + timepoint.
28
+
29
+ Subcommands: sources | pairing | bulk | sc
30
+ """
31
+ from __future__ import annotations
32
+
33
+ import argparse
34
+ import csv
35
+ import gzip
36
+ import json
37
+ import os
38
+ import re
39
+ import shutil
40
+ import sys
41
+ import time
42
+ from collections import defaultdict
43
+ from concurrent.futures import ProcessPoolExecutor, as_completed
44
+ from datetime import datetime, timezone
45
+ from pathlib import Path
46
+
47
+ import numpy as np
48
+ import pandas as pd
49
+
50
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
51
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
52
+
53
+ DATALAKE = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc")
54
+ GEO = DATALAKE / "datasets/GSE161918"
55
+ RDS = GEO / "raw/GSE161918_AllBatches_SeuratObj.rds.gz"
56
+ SOFT = GEO / "metadata/GSE161918_family.soft.gz"
57
+ BULK_TABLES = {"B1_bulkRNAseq_countmtx.csv": GEO / "raw/GSE161918_B1bulkRNAseq_countmtx.csv.gz",
58
+ "B2_B3_bulkRNAseq_countmtx.csv": GEO / "raw/GSE161918_B2GSE161918_B3bulkRNAseq_countmtx.csv.gz"}
59
+ PAIRMAPS = DATALAKE / "analyses/paired_inventory_20260927/new_pairmaps"
60
+ HTO_META = PAIRMAPS / "GSE161918_allbatches.HTOandTimepointMetadata.csv.gz" # GEO suppl. file, cached copy (read only)
61
+ RUN = DATALAKE / "processing/liu2021_v1_20261002"
62
+ EXPORT = RUN / "rds_export"
63
+ BUNDLE = RUN / "code/strict_qc_v1_code_bundle_v5" # verbatim copy of strict_qc_v1_20260913/code_bundle_v5
64
+ REFERENCE = DATALAKE / "processing/strict_qc_v1_20260913/reference" # frozen; read only, sha-verified
65
+ RECEIPTS = DATALAKE / "acquisition/20260927/manifests/download_receipts.jsonl"
66
+ # Cell Ranger hg19-1.2.0 genes table (32,738 genes): GEO GSE206283 per-GSM filtered_feature_bc_matrix, extracted and
67
+ # receipt-verified by the Giroux 2022 build (all 41 copies identical); copied here unchanged.
68
+ CROSSWALK_SRC = DATALAKE / ("processing/giroux2022_v1_20260928/extracted/GSE206283/GSM6249265/"
69
+ "scRNA_59-0_filtered_feature_bc_matrix/features.tsv.gz")
70
+ CROSSWALK = RUN / "reference_crosswalk/cellranger_hg19-1.2.0_features__from_GSE206283_GSM6249265.tsv.gz"
71
+ ACCESSION = "GSE161918"
72
+ sys.path.insert(0, str(BUNDLE))
73
+
74
+ import qc_core # noqa: E402
75
+ import qc_genes # noqa: E402
76
+
77
+ SEX_GENES = {"XIST": "ENSG00000229807", "RPS4Y1": "ENSG00000129824", "DDX3Y": "ENSG00000067048",
78
+ "UTY": "ENSG00000183878", "KDM5D": "ENSG00000012817"}
79
+ COUNT_EVIDENCE = ("GSE161918 author Seurat object (Seurat 3.1.0) RNA assay counts slot: Cell Ranger 3.1.0 UMI counts, "
80
+ "hg19-1.2.0 reference, 10x 5' Next GEM v1.1 CITE-seq gene-expression library. Every stored value "
81
+ "is a positive integer; per cell the column sum equals the author nCount_RNA and the stored-entry "
82
+ "count equals nFeature_RNA (checked in R and again per cell here); the data slot is log-normalised "
83
+ "and is NOT used.")
84
+ # Sample-level clinical fields of the author metadata (must be constant within an author sample).
85
+ SAMPLE_LEVEL = ["Batch", "Donor", "Subject", "Timepoint", "Class", "Age", "Gender", "Ward", "Status", "symptom_type",
86
+ "hospital_days", "day_from_symptom_onset_to_hospitalization", "number_of_days_hospitalized",
87
+ "computed_ethnicity", "ever_admitted_to_icu", "severity", "days_of_symptoms_onset", "condition",
88
+ "outcome", "DDimer", "CRP", "material_type", "sample_bsi_id", "sample_alt_id", "sample_label", "batch",
89
+ "days_since_hospitalized", "days_since_onset", "severity.outcome", "PC1", "PC1_cat", "cond_group",
90
+ "onset_group", "intubation_vent", "PC1_onset_group", "sample_name", "Sorted", "BatchSort"]
91
+ CELL_COLUMNS = ["cell", "Batch", "BatchSort", "Sorted", "Donor", "Subject", "Timepoint", "sample_id", "sample_name",
92
+ "Sample", "BARCODE", "barcodeBatch", "HTO_classification.global", "hash.ID", "autoHashcalls",
93
+ "HTO_maxID", "DROPLET.TYPE", "SNG.BEST.GUESS", "Pool", "nCount_RNA", "nFeature_RNA", "percent.mito",
94
+ "celltypeQC", "coursecelltype", "mergedcelltype", "WCTcoursecelltype", "WCTmergedcelltype",
95
+ "adjustedcelltype"]
96
+ # GEO series design (read from the soft file and asserted below): CHI014 = technical control in every batch;
97
+ # HDML_bc / HDVO_bc = buffy-coat freezing test; SHD8 = excluded by the authors (lymphoma-like B cells).
98
+ # Per the task, technical controls (CHI*, HD_*) are excluded from pairs; they stay in the identity null pool.
99
+ CONTROL_COLUMN = re.compile(r"^(CHI-?014(_B\d)?|HD_(ML|VO)_(bc|PBMC))$")
100
+ CONTROL_SC_SUBJECT = re.compile(r"^(CHI014|HD(ML|VO)_(bc|PBMC))$")
101
+
102
+
103
+ def now() -> str:
104
+ return datetime.now(timezone.utc).isoformat()
105
+
106
+
107
+ def log(event: dict) -> None:
108
+ line = json.dumps({"t": now(), **event}, default=str)
109
+ print(line, flush=True)
110
+ with open(RUN / "events.jsonl", "a") as handle:
111
+ handle.write(line + "\n")
112
+
113
+
114
+ def sha256(path: Path) -> str:
115
+ return qc_core.sha256_file(path)
116
+
117
+
118
+ def require(ok: bool, msg: str) -> None:
119
+ if not ok:
120
+ raise RuntimeError(msg)
121
+
122
+
123
+ def verify_bundle() -> dict:
124
+ manifest = json.loads((BUNDLE / "MANIFEST.json").read_text())
125
+ for name, digest in manifest["files"].items():
126
+ if sha256(BUNDLE / name) != digest:
127
+ raise RuntimeError(f"Code bundle file changed: {name}")
128
+ return manifest
129
+
130
+
131
+ def make_unique(names: list[str]) -> list[str]:
132
+ """R base::make.unique(sep='.'), as Seurat applies to duplicated 10x feature names."""
133
+ seen, counter, out = set(), {}, []
134
+ for name in names:
135
+ if name not in seen:
136
+ out.append(name)
137
+ seen.add(name)
138
+ counter[name] = 0
139
+ continue
140
+ k = counter[name] + 1
141
+ while f"{name}.{k}" in seen:
142
+ k += 1
143
+ counter[name] = k
144
+ out.append(f"{name}.{k}")
145
+ seen.add(f"{name}.{k}")
146
+ return out
147
+
148
+
149
+ def restored_feature_axis() -> tuple[list[str], list[str], dict]:
150
+ """(ids, symbols) for the Seurat RNA rows: Ensembl IDs and 10x symbols of the hg19-1.2.0 table, by position."""
151
+ rows = [line.rstrip("\n").split("\t") for line in gzip.open(CROSSWALK, "rt")]
152
+ ids, symbols, types = [r[0] for r in rows], [r[1] for r in rows], sorted({r[2] for r in rows})
153
+ seurat = [line.rstrip("\n") for line in open(EXPORT / "rna_genes.txt")]
154
+ expected = make_unique([s.replace("_", "-") for s in symbols])
155
+ mismatch = [i for i, (a, b) in enumerate(zip(expected, seurat)) if a != b]
156
+ require(len(seurat) == len(ids) and not mismatch, f"Seurat rownames differ from hg19-1.2.0 order at {mismatch[:5]}")
157
+ require(len(set(ids)) == len(ids) and all(re.fullmatch(r"ENSG\d{11}", i) for i in ids), "crosswalk IDs")
158
+ require(types == ["Gene Expression"], f"unexpected feature types {types}")
159
+ renamed = [{"position": i, "seurat_name": seurat[i], "tenx_symbol": symbols[i], "ensembl_id": ids[i]}
160
+ for i in range(len(ids)) if seurat[i] != symbols[i]]
161
+ proof = {"features": len(ids), "feature_types": types, "positions_compared": len(ids),
162
+ "rule": ("Seurat CreateSeuratObject feature names = make.unique(10x symbol with '_' replaced by '-'); "
163
+ "this equals rna_genes.txt (the counts-slot rownames) at every position, so the Ensembl ID of "
164
+ "row i is the hg19-1.2.0 genes-table ID of row i"),
165
+ "ordered_match_after_underscore_and_make_unique": True,
166
+ "renamed_positions": renamed}
167
+ return ids, symbols, proof
168
+
169
+
170
+ # ----------------------------------------------------------------- sources
171
+ def receipts() -> dict:
172
+ out = {}
173
+ for line in open(RECEIPTS):
174
+ rec = json.loads(line)
175
+ out[rec["local_path"]] = rec
176
+ return out
177
+
178
+
179
+ def cmd_sources(_args) -> None:
180
+ verify_bundle()
181
+ known = receipts()
182
+ records = []
183
+ for path in [RDS, *BULK_TABLES.values(), SOFT]:
184
+ rec = {"path": str(path), "bytes": path.stat().st_size, "sha256": sha256(path)}
185
+ receipt = known.get(str(path))
186
+ rec["acquisition_receipt"] = bool(receipt)
187
+ require(bool(receipt), f"no acquisition receipt for {path}")
188
+ rec.update(url=receipt["url"], receipt_sha256=receipt["sha256"], receipt_bytes=receipt["bytes"],
189
+ receipt_completed_at=receipt["completed_at"],
190
+ matches_receipt=receipt["sha256"] == rec["sha256"] and receipt["bytes"] == rec["bytes"])
191
+ require(rec["matches_receipt"], f"acquired file differs from its receipt: {path}")
192
+ records.append(rec)
193
+ pm = json.loads((PAIRMAPS / "summary.json").read_text())
194
+ liu = [s for s in pm["studies"] if s["study"] == "liu_covid"][0]
195
+ hto = {"path": str(HTO_META), "bytes": HTO_META.stat().st_size, "sha256": sha256(HTO_META),
196
+ "url": liu["hto_source_url"],
197
+ "summary_json_sha256": pm["source_sha256"].get(str(HTO_META), ""),
198
+ "note": "GEO supplementary file cached by the 2026-09-27 pairing audit (read only); used only as an "
199
+ "independent cross-check of the Seurat object's (subject, hashtag) -> timepoint / sorted labels"}
200
+ hto["matches_summary_json"] = hto["sha256"] == hto["summary_json_sha256"]
201
+ structure = json.loads((EXPORT / "STRUCTURE.json").read_text())
202
+ chk = structure["rna_counts_checks"]
203
+ require(chk["x_all_integer"] and chk["x_min"] >= 1 and chk["nCount_RNA_equals_colSums"] and
204
+ chk["nFeature_RNA_equals_stored_entries"] and chk["gene_names_unique"] and chk["cell_names_unique"],
205
+ "R export checks failed")
206
+ export = [{"path": str(p), "bytes": p.stat().st_size, "sha256": sha256(p)} for p in sorted(EXPORT.iterdir())
207
+ if p.is_file()]
208
+ # reference crosswalk: copy the hg19-1.2.0 genes table unchanged and prove the positional identity
209
+ CROSSWALK.parent.mkdir(exist_ok=True)
210
+ if not CROSSWALK.exists():
211
+ shutil.copyfile(CROSSWALK_SRC, CROSSWALK)
212
+ require(sha256(CROSSWALK) == sha256(CROSSWALK_SRC), "crosswalk copy differs from its source")
213
+ _, _, proof = restored_feature_axis()
214
+ gsrc = json.loads((DATALAKE / "processing/giroux2022_v1_20260928/SOURCES.json").read_text())["files"]
215
+ tar = [f for f in gsrc if f["path"].endswith("GSE206283_RAW.tar")][0]
216
+ proof.update({"file": {"path": str(CROSSWALK), "sha256": sha256(CROSSWALK), "bytes": CROSSWALK.stat().st_size},
217
+ "copied_from": str(CROSSWALK_SRC),
218
+ "origin": {"geo_archive": tar["path"], "url": tar.get("url", ""), "sha256": tar["sha256"],
219
+ "matches_receipt": tar.get("matches_receipt"),
220
+ "note": "Giroux 2022 GEO per-GSM Cell Ranger 3.1.0 hg19 matrices; all 41 features.tsv "
221
+ "copies are byte-identical (Giroux FINDINGS sc_chemistry)"},
222
+ "paper_statement": "GEO GSE161918 data processing: 'Genome_build: hg19 (cellranger version 1.2.0)'; "
223
+ "mapping CellRanger 3.1.0",
224
+ "created_utc": now()})
225
+ qc_core._write_json(RUN / "reference_crosswalk/CROSSWALK.json", proof)
226
+ qc_core._write_json(RUN / "SOURCES.json", {
227
+ "created_at_utc": now(), "files": records, "hto_metadata": hto, "rds_export": export,
228
+ "rds_export_code": {"path": str(RUN / "code/liu2021_rds_export.R"), "sha256": sha256(RUN / "code/liu2021_rds_export.R")},
229
+ "rds_structure_checks": chk, "crosswalk": str(RUN / "reference_crosswalk/CROSSWALK.json"),
230
+ "acquisition": "paired-datasets-20260927 acquisition (read only; not modified)", "receipts": str(RECEIPTS)})
231
+ log({"stage": "sources", "n_files": len(records), "hto_matches_summary": hto["matches_summary_json"],
232
+ "crosswalk_positions": proof["positions_compared"], "renamed": len(proof["renamed_positions"])})
233
+
234
+
235
+ # ----------------------------------------------------------------- pairing
236
+ def parse_soft(path: Path) -> pd.DataFrame:
237
+ samples, cur, section, series = [], None, None, defaultdict(list)
238
+ with gzip.open(path, "rt", encoding="utf-8") as fh:
239
+ for line in fh:
240
+ line = line.rstrip("\n")
241
+ if line.startswith("^"):
242
+ section = line[1:].split(" = ")[0]
243
+ if section == "SAMPLE":
244
+ cur = defaultdict(list)
245
+ cur["gsm"] = [line.split(" = ")[1]]
246
+ samples.append(cur)
247
+ continue
248
+ if not line.startswith("!") or " = " not in line:
249
+ continue
250
+ key, val = line[1:].split(" = ", 1)
251
+ if section == "SERIES":
252
+ series[key].append(val)
253
+ if section != "SAMPLE":
254
+ continue
255
+ if key == "Sample_characteristics_ch1" and ": " in val:
256
+ k, v = val.split(": ", 1)
257
+ cur["ch_" + k.strip()].append(v.strip())
258
+ else:
259
+ cur[key].append(val)
260
+ frame = pd.DataFrame([{k: "|".join(v) for k, v in s.items()} for s in samples]).fillna("")
261
+ frame.attrs["series"] = {k: "|".join(v) for k, v in series.items()}
262
+ return frame
263
+
264
+
265
+ BULK_TITLE = re.compile(r"^Batch ?(\d) bulk ?RNAseq (\S+)\s*$")
266
+
267
+
268
+ def geo_timepoint(label: str) -> str:
269
+ m = re.fullmatch(r"Timepoint (\d)", label)
270
+ return f"T{m.group(1)}" if m else ("HC" if label.startswith("Healthy Control") else label)
271
+
272
+
273
+ def read_bulk_header(path: Path) -> list[str]:
274
+ with gzip.open(path, "rt", newline="") as handle:
275
+ header = next(csv.reader(handle))
276
+ require(len(set(header)) == len(header) and all(h.strip() for h in header), f"bad bulk header {path}")
277
+ require(header[0] == "V2", f"unexpected first header field {header[0]!r} in {path}")
278
+ return header[1:]
279
+
280
+
281
+ def read_cells() -> pd.DataFrame:
282
+ cells = pd.read_csv(EXPORT / "cell_metadata.csv.gz", dtype=str, keep_default_na=False)
283
+ order = [line.rstrip("\n") for line in open(EXPORT / "rna_cells.txt")]
284
+ require(cells.cell.tolist() == order, "meta.data rows differ from the counts-slot column order")
285
+ cells.insert(0, "col_index", np.arange(len(cells), dtype=np.int64))
286
+ return cells
287
+
288
+
289
+ def cmd_pairing(_args) -> None:
290
+ out = RUN / "pairing"
291
+ out.mkdir(parents=True, exist_ok=True)
292
+ soft = parse_soft(SOFT)
293
+ design = soft.attrs["series"]["Series_overall_design"]
294
+ for token in ("CHI014", "SHD8", "HDML_bc", "HDVO_bc"):
295
+ require(token in design, f"GEO series design no longer mentions {token}")
296
+ soft.to_csv(out / "GSE161918_samples.csv", index=False)
297
+ bulk = soft[soft.Sample_title.str.contains("bulk", case=False)].copy()
298
+ parsed = bulk.Sample_title.str.extract(BULK_TITLE)
299
+ require(parsed.notna().all().all(), f"unparsed bulk titles {bulk.Sample_title[parsed.isna().any(axis=1)].tolist()}")
300
+ bulk["geo_batch"], bulk["title_name"] = "B" + parsed[0], parsed[1]
301
+ bulk["table_file"] = bulk.Sample_description.str.split("|").str[-1]
302
+ require(bulk.table_file.isin(list(BULK_TABLES)).all(), "bulk GSM description does not name a count table")
303
+ bulk["geo_timepoint"] = bulk.ch_timepoint.map(geo_timepoint)
304
+ require((bulk.Sample_source_name_ch1 == "Peripheral Blood Mononuclear Cells").all(), "bulk source is not PBMC")
305
+ require((bulk["ch_unsorted or sorted t/b cells"] == "Unsorted").all(), "a bulk GSM is not unsorted")
306
+ # ---- author count-table columns -> GSM
307
+ cols = []
308
+ for table, path in BULK_TABLES.items():
309
+ for c in read_bulk_header(path):
310
+ cols.append({"bulk_column": c, "table_file": table})
311
+ cols = pd.DataFrame(cols)
312
+ require(cols.bulk_column.is_unique, "a column name appears in both bulk tables")
313
+ # a leading 'P' before an HGR subject is a typo (GEO GSM4929238 title 'HGR0000074', HTO metadata HGR0000074 T0)
314
+ cols["column_key"] = cols.bulk_column.str.replace(r"^P(HGR\d+_T\d)$", r"\1", regex=True)
315
+ cols["column_correction"] = np.where(cols.column_key != cols.bulk_column,
316
+ "leading 'P' removed (typo; GEO title and HTO metadata name the subject without it)", "")
317
+ tp = cols.column_key.str.extract(r"^(.+)_(T\d)$")
318
+ cols["subject"] = tp[0].fillna(cols.column_key)
319
+ cols["column_timepoint"] = tp[1].fillna("")
320
+ gsm_of = {}
321
+ for i, c in cols.iterrows():
322
+ cand = bulk[(bulk.table_file == c.table_file) &
323
+ ((bulk.title_name == c.column_key) | (bulk.title_name == c.subject))]
324
+ require(len(cand) == 1, f"bulk column {c.bulk_column}: {len(cand)} candidate GSMs")
325
+ gsm_of[i] = cand.index[0]
326
+ cols["bulk_gsm"] = [bulk.loc[gsm_of[i], "gsm"] for i in cols.index]
327
+ require(cols.bulk_gsm.is_unique and set(cols.bulk_gsm) == set(bulk.gsm), "bulk column <-> GSM is not 1:1")
328
+ b = bulk.set_index("gsm")
329
+ cols["bulk_title"] = cols.bulk_gsm.map(b.Sample_title)
330
+ cols["geo_batch"] = cols.bulk_gsm.map(b.geo_batch)
331
+ cols["geo_timepoint_characteristic"] = cols.bulk_gsm.map(b.ch_timepoint)
332
+ cols["geo_timepoint"] = cols.bulk_gsm.map(b.geo_timepoint)
333
+ cols["timepoint"] = np.where(cols.column_timepoint != "", cols.column_timepoint, cols.geo_timepoint)
334
+ cols["timepoint_conflict"] = np.where((cols.column_timepoint != "") & (cols.column_timepoint != cols.geo_timepoint),
335
+ "column name " + cols.column_timepoint + " vs GEO characteristic '" +
336
+ cols.geo_timepoint_characteristic + "'", "")
337
+ cols["kind"] = np.where(cols.bulk_column.str.fullmatch(CONTROL_COLUMN.pattern), "technical_control",
338
+ np.where(cols.geo_timepoint_characteristic.str.contains("excluded"), "author_excluded",
339
+ np.where(cols.timepoint == "HC", "HC", "COVID")))
340
+ # ---- single cells (author Seurat object)
341
+ cells = read_cells()
342
+ cells["selected"] = ((cells.Sorted == "N") & (cells["HTO_classification.global"] == "Singlet") &
343
+ (cells["DROPLET.TYPE"] == "SNG"))
344
+ keep_cols = ["col_index", *CELL_COLUMNS, "selected"]
345
+ cells[keep_cols].to_parquet(out / "sc_cell_obs.parquet", index=False)
346
+ # independent cross-check against GEO's HTO/timepoint metadata: (batch, donor_hashtag) -> timepoint (and sorted, B1)
347
+ hto = pd.read_csv(HTO_META, dtype=str, keep_default_na=False).rename(columns={"Unnamed: 0": "row"})
348
+ hto["key"] = hto.Batch + "|" + hto.x
349
+ require(hto.key.is_unique, "HTO metadata keys not unique")
350
+ hk = hto.set_index("key")
351
+ ck = cells.Batch + "|" + cells.Donor + "_" + cells.autoHashcalls
352
+ found = ck.isin(hk.index)
353
+ tp_ok = found & (ck.map(hk.Timepoint) == cells.Timepoint)
354
+ b1 = cells.Batch == "B1"
355
+ sort_ok = ~b1 | (ck.map(hk.Sorted) == cells.Sorted)
356
+ hto_check = {
357
+ "cells": int(len(cells)), "cells_key_found": int(found.sum()),
358
+ "timepoint_agrees": int(tp_ok.sum()), "timepoint_agrees_selected": int((tp_ok & cells.selected).sum()),
359
+ "batch1_sorted_agrees": int((sort_ok & b1 & found).sum()), "batch1_cells": int(b1.sum()),
360
+ "selected_cells": int(cells.selected.sum()),
361
+ "selected_key_not_found": cells.loc[cells.selected & ~found, "Donor"].value_counts().to_dict(),
362
+ "selected_timepoint_disagrees": (cells.loc[cells.selected & found & ~tp_ok, "sample_id"].value_counts().to_dict()),
363
+ "key": "Batch + '|' + Donor + '_' + autoHashcalls (the hashtag that defines the author Sample)"}
364
+ # ---- sc samples (author sample_id; every sample-level field must be constant within the unsorted fraction)
365
+ uns = cells[cells.Sorted == "N"]
366
+ grouped = uns.groupby("sample_id", sort=True)
367
+ varying = {c: int((grouped[c].nunique() > 1).sum()) for c in SAMPLE_LEVEL if c in uns}
368
+ require(sum(v for k, v in varying.items()) == 0, f"sample-level fields vary within a sample: {varying}")
369
+ sc = grouped[[c for c in SAMPLE_LEVEL if c in uns]].first()
370
+ allc = cells.groupby("sample_id")
371
+ sc["n_cells_object"] = allc.size()
372
+ sc["n_sorted_dropped"] = allc.Sorted.agg(lambda s: int((s == "Y").sum()))
373
+ sc["n_unsorted"] = grouped.size()
374
+ for lab in ("Singlet", "Doublet", "Negative"):
375
+ sc[f"n_unsorted_hto_{lab.lower()}"] = grouped["HTO_classification.global"].agg(lambda s, lab=lab: int((s == lab).sum()))
376
+ sc["n_unsorted_not_demuxlet_singlet"] = grouped["DROPLET.TYPE"].agg(lambda s: int((s != "SNG").sum()))
377
+ sc["n_selected"] = grouped.selected.sum().astype(int)
378
+ sc["hashtags"] = grouped.autoHashcalls.agg(lambda s: "|".join(sorted(set(s))))
379
+ sc = sc.reset_index().rename(columns={"sample_id": "sc_sample"})
380
+ require((sc.sample_name == sc.Subject + "_" + sc.Timepoint).all(), "sample_name != Subject_Timepoint")
381
+ sc["kind"] = np.where(sc.Subject.str.fullmatch(CONTROL_SC_SUBJECT.pattern), "technical_control", sc.Class)
382
+ sc.to_csv(out / "sc_samples.csv", index=False)
383
+ # ---- pairs: same subject and same timepoint, controls excluded
384
+ pairable_b = cols[cols.kind.isin(["HC", "COVID"])]
385
+ pairable_s = sc[sc.kind.isin(["HC", "COVID"])]
386
+ m = pairable_s.merge(pairable_b, left_on=["Subject", "Timepoint"], right_on=["subject", "timepoint"], how="inner",
387
+ suffixes=("", "_bulk"))
388
+ require(m.sc_sample.is_unique and m.bulk_column.is_unique, "a pair is not 1:1")
389
+ require((m.Class == np.where(m.timepoint == "HC", "HC", "COVID")).all(), "sc Class differs from the bulk GEO label")
390
+ require((m.Batch == m.geo_batch).all(), "sc batch differs from the bulk GSM batch")
391
+ m["id_match"] = np.where(m.column_correction != "", "subject_timepoint; bulk column name corrected",
392
+ np.where(m.timepoint_conflict != "", "subject_timepoint; GEO bulk timepoint characteristic differs",
393
+ "exact_subject_timepoint"))
394
+ m["sample_id"] = m.Subject + "_" + m.Timepoint
395
+ m = m.sort_values("bulk_gsm").reset_index(drop=True)
396
+ m.to_csv(out / "pairs_primary.csv", index=False)
397
+ paired_sc, paired_b = set(m.sc_sample), set(m.bulk_column)
398
+
399
+ def sc_reason(r) -> str:
400
+ if r.kind == "technical_control":
401
+ return "technical control (CHI014 / HD buffy-coat test donor); excluded by task rule"
402
+ hit = cols[(cols.subject == r.Subject)]
403
+ return "no bulk column for this subject and timepoint" + (
404
+ f" (subject bulk timepoints: {','.join(hit.timepoint)})" if len(hit) else "")
405
+ sc_un = sc[~sc.sc_sample.isin(paired_sc)].copy()
406
+ sc_un["reason"] = sc_un.apply(sc_reason, axis=1) if len(sc_un) else []
407
+ sc_un.to_csv(out / "sc_without_bulk.csv", index=False)
408
+
409
+ def b_reason(r) -> str:
410
+ if r.kind == "technical_control":
411
+ return "technical control column (CHI014 / HD buffy-coat test); excluded by task rule"
412
+ if r.kind == "author_excluded":
413
+ n = int((cells.Subject == r.subject).sum())
414
+ return f"GEO: '{r.geo_timepoint_characteristic}'; the author Seurat object holds {n} cells of this subject"
415
+ return "no sc sample with this subject and timepoint"
416
+ cols["paired"] = cols.bulk_column.isin(paired_b)
417
+ cols["unpaired_reason"] = [("" if p else b_reason(r)) for p, (_, r) in zip(cols.paired, cols.iterrows())]
418
+ cols.to_csv(out / "bulk_count_columns.csv", index=False)
419
+ summary = {
420
+ "bulk_gsms": int(len(bulk)), "bulk_columns": int(len(cols)),
421
+ "bulk_columns_by_table": cols.table_file.value_counts().to_dict(),
422
+ "bulk_columns_by_kind": cols.kind.value_counts().to_dict(),
423
+ "bulk_column_corrections": cols[cols.column_correction != ""][["bulk_column", "column_key", "bulk_gsm", "bulk_title"]].to_dict("records"),
424
+ "bulk_timepoint_conflicts": cols[cols.timepoint_conflict != ""][["bulk_column", "bulk_gsm", "bulk_title", "timepoint_conflict"]].to_dict("records"),
425
+ "bulk_material": "GEO source 'Peripheral Blood Mononuclear Cells', characteristic 'Unsorted' for all 73 bulk GSMs",
426
+ "sc_cells_object": int(len(cells)), "sc_cells_unsorted": int((cells.Sorted == "N").sum()),
427
+ "sc_cells_selected": int(cells.selected.sum()),
428
+ "sc_cells_by_batchsort_hto": pd.crosstab(cells.BatchSort, cells["HTO_classification.global"]).to_dict(),
429
+ "sc_droplet_type": cells["DROPLET.TYPE"].value_counts().to_dict(),
430
+ "sc_samples_unsorted": int(len(sc)), "sc_samples_by_kind": sc.kind.value_counts().to_dict(),
431
+ "hto_metadata_cross_check": hto_check,
432
+ "pairs_total": int(len(m)), "pairs_subjects": int(m.Subject.nunique()),
433
+ "pairs_by_group": m.Class.value_counts().to_dict(), "pairs_by_timepoint": m.Timepoint.value_counts().to_dict(),
434
+ "pairs_by_batch": m.Batch.value_counts().to_dict(), "pairs_by_id_match": m.id_match.value_counts().to_dict(),
435
+ "subjects_by_group": m.groupby("Class").Subject.nunique().to_dict(),
436
+ "sc_without_bulk": sc_un[["sc_sample", "kind", "reason"]].to_dict("records"),
437
+ "bulk_without_sc": cols[~cols.paired][["bulk_column", "bulk_gsm", "kind", "unpaired_reason"]].to_dict("records"),
438
+ "rule": ("A pair is one author bulk count-table column and one author sc sample (unsorted fraction) with the "
439
+ "same subject and the same timepoint label (T0-T3, or HC). Bulk column <-> GEO GSM by the GEO title "
440
+ "name within the same count table (1:1, all 73). Column subject/timepoint from the column name "
441
+ "(one typo corrected: PHGR0000074_T0); the sc subject/timepoint are the author metadata Subject and "
442
+ "Timepoint (hashtag-defined; cross-checked against the GEO HTO/timepoint table). Technical controls "
443
+ "(CHI014, HD_ML/HD_VO) are not paired. No expression, age-sex or order matching creates a pair."),
444
+ }
445
+ qc_core._write_json(out / "PAIRING_SUMMARY.json", json.loads(json.dumps(summary, default=lambda x: x.item() if hasattr(x, "item") else str(x))))
446
+ log({"stage": "pairing", **{k: summary[k] for k in ("pairs_total", "pairs_subjects", "pairs_by_group",
447
+ "pairs_by_timepoint", "pairs_by_id_match")},
448
+ "hto_check": {k: hto_check[k] for k in ("selected_cells", "timepoint_agrees_selected")}})
449
+
450
+
451
+ # ----------------------------------------------------------------- bulk
452
+ def read_bulk_table(path: Path):
453
+ header = read_bulk_header(path)
454
+ ids, rows = [], []
455
+ with gzip.open(path, "rt", newline="") as handle:
456
+ reader = csv.reader(handle)
457
+ next(reader)
458
+ for line_number, fields in enumerate(reader, start=2):
459
+ if len(fields) != len(header) + 1:
460
+ raise ValueError(f"{path.name} line {line_number}: expected symbol + {len(header)} values")
461
+ ids.append(fields[0])
462
+ rows.append([float(x) for x in fields[1:]]) # float() raises on any non-numeric token
463
+ return header, ids, np.asarray(rows, dtype=np.float64)
464
+
465
+
466
+ def cmd_bulk(_args) -> None:
467
+ import qc_bulk
468
+ verify_bundle()
469
+ mapper = qc_genes.GeneMapper(REFERENCE)
470
+ parts = [read_bulk_table(p) for p in BULK_TABLES.values()]
471
+ ids = parts[0][1]
472
+ require(all(p[1] == ids for p in parts), "the two bulk tables have different gene rows")
473
+ require(len(set(ids)) == len(ids), "duplicate gene symbols in the bulk table")
474
+ require(not any(i.startswith("__") for i in ids), "htseq counter rows present")
475
+ samples = [c for p in parts for c in p[0]]
476
+ values = np.concatenate([p[2] for p in parts], axis=1).T.copy() # samples x genes
477
+ require(np.isfinite(values).all() and (values >= 0).all() and np.array_equal(values, np.rint(values)),
478
+ "bulk values must be nonnegative integers")
479
+ cols = pd.read_csv(RUN / "pairing/bulk_count_columns.csv", dtype=str, keep_default_na=False).set_index("bulk_column")
480
+ require(list(cols.index) == samples, "bulk column order differs from pairing")
481
+ (RUN / "bulk").mkdir(exist_ok=True)
482
+ np.savez_compressed(RUN / "bulk/bulk_source_counts.npz", gene_ids=np.asarray(ids), sample_ids=np.asarray(samples),
483
+ gsm=np.asarray([cols.loc[s, "bulk_gsm"] for s in samples]), counts=values)
484
+ meta = [{"bulk_column": s, "GSM": cols.loc[s, "bulk_gsm"], "subject": cols.loc[s, "subject"],
485
+ "timepoint": cols.loc[s, "timepoint"], "table_file": cols.loc[s, "table_file"], "kind": cols.loc[s, "kind"],
486
+ "assigned_gene_total": float(values[j].sum())} for j, s in enumerate(samples)]
487
+ assay = qc_bulk.BulkInput(
488
+ ACCESSION, "GSE161918_htseq", "htseq_count_raw_gene_counts", ids, samples, values,
489
+ symbols=None, present=None, declared_raw_counts=True, sources=list(BULK_TABLES.values()), sample_metadata=meta,
490
+ caveats=["GEO: PBMC (100,000 cells per sample, unsorted) in Trizol, miRNeasy micro kit, Illumina TruSeq library, "
491
+ "STAR alignment, htseq-count 0.9.1 with the UCSC hg19 annotation; strandedness option not stated.",
492
+ "Two author tables (batch 1; batches 2+3) with identical 55,765 gene-symbol rows, concatenated by "
493
+ "column (23 + 50 = 73 columns = 73 GEO bulk GSMs). Genes are UCSC hg19 symbols (no Ensembl IDs), "
494
+ "mapped to the canonical axis by symbol only. htseq '__' counter rows are not in the tables.",
495
+ "Technical-control columns (CHI-014, CHI014_B2/B3, HD_ML/HD_VO bc/PBMC) and the author-excluded "
496
+ "SHD8 are harmonised but never paired; see pairing/."],
497
+ extra={"source_format": "CSV (gzip), header 'V2' + sample names, rows = gene symbol + integer values",
498
+ "source_gene_rows": len(ids)})
499
+ report = qc_bulk.harmonize(assay, mapper, RUN / "bulk" / assay.assay_id)
500
+ log({"stage": "bulk", "status": report["status"], "n_samples": report["n_samples"],
501
+ "raw_count_eligible": report["raw_count_eligible"], "canonical_coverage": report["canonical_coverage"],
502
+ "duplicate_target_groups_summed": report["duplicate_target_groups_summed_counts"]})
503
+
504
+
505
+ # ----------------------------------------------------------------- single cell
506
+ def write_source_h5ad(path: Path, X, barcodes: np.ndarray, ids: list[str], symbols: list[str]) -> None:
507
+ """Minimal AnnData H5AD holding one author sample's cells unchanged (int32 UMI counts as exported)."""
508
+ import h5py
509
+ import qc_singlecell as qs
510
+ tmp = path.with_suffix(".partial")
511
+ with h5py.File(tmp, "w") as h:
512
+ h.attrs["encoding-type"], h.attrs["encoding-version"] = "anndata", "0.1.0"
513
+ x = h.create_group("X")
514
+ x.attrs["encoding-type"], x.attrs["encoding-version"] = "csr_matrix", "0.1.0"
515
+ x.attrs["shape"] = [X.shape[0], X.shape[1]]
516
+ x.create_dataset("data", data=X.data)
517
+ x.create_dataset("indices", data=X.indices.astype(np.int32))
518
+ x.create_dataset("indptr", data=X.indptr.astype(np.int64))
519
+ qs._h5_dataframe(h, "obs", {}, np.asarray(barcodes, dtype=object))
520
+ qs._h5_dataframe(h, "var", {"gene_symbols": np.asarray(symbols, dtype=object)}, np.asarray(ids, dtype=object))
521
+ for name in ("obsm", "varm", "obsp", "varp", "layers", "uns"):
522
+ g = h.create_group(name)
523
+ g.attrs["encoding-type"], g.attrs["encoding-version"] = "dict", "0.1.0"
524
+ os.replace(tmp, path)
525
+
526
+
527
+ def export_arrays():
528
+ p = np.fromfile(EXPORT / "rna_counts_p.int32", dtype="<i4").astype(np.int64)
529
+ i = np.memmap(EXPORT / "rna_counts_i.int32", dtype="<i4", mode="r")
530
+ x = np.memmap(EXPORT / "rna_counts_x.int32", dtype="<i4", mode="r")
531
+ require(len(i) == len(x) == p[-1] and p[0] == 0 and bool((np.diff(p) >= 0).all()), "exported CSR arrays")
532
+ return p, i, x
533
+
534
+
535
+ def process_sample(sample: str) -> dict:
536
+ import scipy.sparse as sp
537
+ import qc_singlecell as qs
538
+
539
+ qs.COUNT_SOURCE_EVIDENCE[ACCESSION] = COUNT_EVIDENCE # provenance string only
540
+ out = RUN / "singlecell" / sample
541
+ out.mkdir(parents=True, exist_ok=True)
542
+ summary_path = out / "summary.json"
543
+ if summary_path.exists() and json.loads(summary_path.read_text()).get("status") == "PASS":
544
+ return json.loads(summary_path.read_text())
545
+ summary = {"accession": ACCESSION, "library_id": sample, "status": "RUNNING", "output_dir": str(out),
546
+ "started": now(), "source": str(RDS)}
547
+ qc_core._write_json(summary_path, summary)
548
+ t0 = time.time()
549
+ try:
550
+ axis = json.loads((RUN / "singlecell/feature_axis.json").read_text())
551
+ ids, symbols = axis["ids"], axis["symbols"]
552
+ n_var = len(ids)
553
+ mapper = qc_genes.GeneMapper(REFERENCE)
554
+ mapping = mapper.map_features(ids, symbols)
555
+ mito = np.asarray([r["mitochondrial"] for r in mapping])
556
+ obs_all = pd.read_parquet(RUN / "pairing/sc_cell_obs.parquet", filters=[("sample_id", "==", sample)])
557
+ so = obs_all[obs_all.selected].sort_values("col_index")
558
+ require(len(so) > 0, f"{sample}: no selected cells")
559
+ p, ind, val = export_arrays()
560
+ cols = so.col_index.to_numpy(np.int64)
561
+ starts, stops = p[cols], p[cols + 1]
562
+ lengths = stops - starts
563
+ gather = np.concatenate([np.arange(a, b, dtype=np.int64) for a, b in zip(starts, stops)])
564
+ indptr = np.concatenate([[0], np.cumsum(lengths)]).astype(np.int64)
565
+ M = sp.csr_matrix((np.asarray(val[gather]), np.asarray(ind[gather]), indptr), shape=(len(so), n_var))
566
+ M.sort_indices()
567
+ require(np.array_equal(M.data, np.rint(M.data)) and (M.data > 0).all(), f"{sample}: non-integer or non-positive stored values")
568
+ row_sum = np.asarray(M.sum(axis=1, dtype=np.float64)).ravel()
569
+ require(np.array_equal(row_sum, so.nCount_RNA.astype(float).to_numpy()), f"{sample}: row sums differ from nCount_RNA")
570
+ require(np.array_equal(np.diff(M.indptr), so.nFeature_RNA.astype(np.int64).to_numpy()), f"{sample}: stored entries differ from nFeature_RNA")
571
+ src = out / "source_subset.h5ad"
572
+ barcodes = so.cell.to_numpy()
573
+ write_source_h5ad(src, M, barcodes, ids, symbols)
574
+ item = {"accession": ACCESSION, "library_id": sample, "path": str(src), "format": "h5",
575
+ "duplicate_representation": False, "matrix_path": "X"}
576
+ rid, rsym, cells, rna, axes = qs.read_axes(item)
577
+ require(list(rid) == ids and list(rsym) == symbols and np.array_equal(cells, barcodes), f"{sample}: axes changed")
578
+ cell_obs = pd.DataFrame({
579
+ "barcode": barcodes, "source_barcode": barcodes, "raw_10x_barcode": so.BARCODE.to_numpy(),
580
+ "author_cell_id": barcodes, "library_id": sample, "donor_id": so.Subject.to_numpy(),
581
+ "sample_id": sample, "visit_id": so.Timepoint.to_numpy(), "author_retained": "true",
582
+ "mapping_basis": ("author Seurat object: demuxlet SNP subject + hashtag (autoHashcalls) timepoint; unsorted "
583
+ "fraction (Sorted == N); HTO_classification.global == Singlet; DROPLET.TYPE == SNG"),
584
+ "protocol": "10x_5prime_NextGEM_v1.1_CITE-seq_GEX", "author_hashtag": so.autoHashcalls.to_numpy(),
585
+ "author_batch": so.Batch.to_numpy()})
586
+ cell_obs.to_csv(out / "cell_metadata.csv.gz", index=False, compression="gzip")
587
+ metrics = out / "metrics"
588
+ if (metrics / "qc_summary.json").exists():
589
+ shutil.rmtree(metrics) # an interrupted earlier attempt; the scan refuses to overwrite
590
+ qc = qc_core.scan_h5(src, metrics, matrix_path="X", mito_mask=mito, feature_mask=rna,
591
+ sample_ids=cell_obs.sample_id.to_numpy())
592
+ total = np.load(metrics / "cell_total.npy")
593
+ detected = np.load(metrics / "cell_detected.npy")
594
+ mito_pct = np.load(metrics / "cell_mito_percent.npy")
595
+ require(np.array_equal(total, row_sum), f"{sample}: qc cell_total differs from row sums")
596
+ pd.DataFrame([{"min_genes": g, "min_abundance": 500, "max_mito_percent": mm,
597
+ "n_review_pass": int(((detected >= g) & (total >= 500) & (mito_pct <= mm)).sum())}
598
+ for g in (100, 200, 500) for mm in (10, 20, 30)]).to_csv(out / "threshold_sensitivity.csv", index=False)
599
+ integral = qc["numeric"]["integer_fraction_selected_stored"] == 1
600
+ item["source_sha256"] = qc["input"].get("sha256", "")
601
+ item["canonical_identity_sha256"] = mapper.manifest.get("canonical_identity_sha256", "")
602
+ verified = bool(integral)
603
+ units = "UMI_counts" if verified else "nonnegative_abundance_source_units_unproven"
604
+ export = qs.canonical_export(item, out, mapping, mapper.canonical, cell_obs, rna,
605
+ verified_counts=verified, units=units, full_mapping=True)
606
+ qcpass = np.load(metrics / "flag_conservative_review_pass.npy")
607
+ all_sum = np.asarray(M.sum(axis=0, dtype=np.float64)).ravel()
608
+ pass_sum = np.asarray(M[np.flatnonzero(qcpass)].sum(axis=0, dtype=np.float64)).ravel()
609
+ np.savez_compressed(out / "source_axis_pseudobulk.npz", feature_ids=np.asarray(ids),
610
+ feature_symbols=np.asarray(symbols), rna=rna, all_cells_sum=all_sum,
611
+ qc_pass_sum=pass_sum, n_cells=len(so), n_qc_pass=int(qcpass.sum()))
612
+ where = {g: k for k, g in enumerate(ids)}
613
+ sex_rows = [where.get(g, -1) for g in SEX_GENES.values()]
614
+ Mc = M.tocsc()
615
+ per_cell = np.zeros((len(SEX_GENES), len(so)), dtype=np.float64)
616
+ for k, r in enumerate(sex_rows):
617
+ if r >= 0:
618
+ per_cell[k] = Mc[:, r].toarray().ravel()
619
+ np.savez_compressed(out / "cell_sex_gene_counts.npz", genes=np.asarray(list(SEX_GENES)),
620
+ gene_ids=np.asarray(list(SEX_GENES.values())), found=np.asarray(sex_rows) >= 0,
621
+ counts=per_cell)
622
+ author_mito = so["percent.mito"].astype(float).to_numpy()
623
+ summary.update({
624
+ "status": "PASS", "n_cells": int(len(so)), "n_features": n_var, "n_rna_features": int(rna.sum()),
625
+ "n_qc_review_pass": int(qcpass.sum()), "flag_counts": qc["flag_counts"], "numeric": qc["numeric"],
626
+ "units": units, "count_space_verified": verified, "count_provenance": COUNT_EVIDENCE,
627
+ "canonical_export": export,
628
+ "author_checks": {"row_sum_equals_nCount_RNA": True, "stored_entries_equal_nFeature_RNA": True,
629
+ "n_obs_sample_all": int(len(obs_all)), "n_selected": int(len(so)),
630
+ "author_percent_mito_max": float(author_mito.max()),
631
+ "mito_pct_vs_author_percent_mito_x100_max_abs_diff": float(np.max(np.abs(mito_pct - 100 * author_mito))),
632
+ "min_nFeature_RNA": int(detected.min()), "min_nCount_RNA": float(total.min()),
633
+ "median_nCount_RNA": float(np.median(total)), "median_nFeature_RNA": float(np.median(detected)),
634
+ "source_subset_sha256": item["source_sha256"]},
635
+ "seconds": round(time.time() - t0, 1), "finished": now()})
636
+ src.unlink() # reproducible from rds_export; its sha is recorded above
637
+ del M, Mc
638
+ except Exception as error: # noqa: BLE001 - recorded, not hidden
639
+ summary.update({"status": "QUARANTINED", "error_type": type(error).__name__, "error": str(error)})
640
+ qc_core._write_json(summary_path, summary)
641
+ return summary
642
+
643
+
644
+ def cmd_sc(args) -> None:
645
+ verify_bundle()
646
+ ids, symbols, proof = restored_feature_axis()
647
+ (RUN / "singlecell").mkdir(exist_ok=True)
648
+ seurat = [line.rstrip("\n") for line in open(EXPORT / "rna_genes.txt")]
649
+ qc_core._write_json(RUN / "singlecell/feature_axis.json", {"seurat_rownames": seurat, "ids": ids, "symbols": symbols})
650
+ mapper = qc_genes.GeneMapper(REFERENCE)
651
+ mapping = mapper.map_features(ids, symbols)
652
+ mapping_summary = mapper.write_rows(mapping, RUN / "singlecell/gene_mapping")
653
+ sc = pd.read_csv(RUN / "pairing/sc_samples.csv", dtype=str, keep_default_na=False)
654
+ samples = sc.sc_sample.tolist()
655
+ if args.sample:
656
+ want = set(args.sample.split(","))
657
+ samples = [s for s in samples if s in want]
658
+ log({"stage": "sc", "event": "start", "samples": len(samples), "workers": args.workers,
659
+ "mapping": {k: mapping_summary[k] for k in ("unique_canonical_features_present", "status_counts")}})
660
+ done = []
661
+ with ProcessPoolExecutor(max_workers=args.workers) as pool:
662
+ futures = {pool.submit(process_sample, s): s for s in samples}
663
+ for future in as_completed(futures):
664
+ s = future.result()
665
+ done.append(s)
666
+ log({"stage": "sc", "library": futures[future], "status": s["status"], "n_cells": s.get("n_cells"),
667
+ "n_qc_review_pass": s.get("n_qc_review_pass"), "seconds": s.get("seconds"), "error": s.get("error")})
668
+ if not args.sample:
669
+ qc_core._write_json(RUN / "singlecell/SINGLECELL_SUMMARY.json",
670
+ {"created_at_utc": now(), "gene_mapping": mapping_summary,
671
+ "libraries": sorted(done, key=lambda s: s["library_id"])})
672
+ log({"stage": "sc", "event": "finish", "pass": sum(s["status"] == "PASS" for s in done), "n": len(done)})
673
+
674
+
675
+ def main() -> None:
676
+ parser = argparse.ArgumentParser(description=__doc__)
677
+ sub = parser.add_subparsers(dest="cmd", required=True)
678
+ sub.add_parser("sources")
679
+ sub.add_parser("pairing")
680
+ sub.add_parser("bulk")
681
+ p = sub.add_parser("sc")
682
+ p.add_argument("--workers", type=int, default=6)
683
+ p.add_argument("--sample", default="", help="comma-separated sample subset (smoke test)")
684
+ args = parser.parse_args()
685
+ RUN.mkdir(parents=True, exist_ok=True)
686
+ {"sources": cmd_sources, "pairing": cmd_pairing, "bulk": cmd_bulk, "sc": cmd_sc}[args.cmd](args)
687
+
688
+
689
+ if __name__ == "__main__":
690
+ main()
paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/bfebe0cd9337a2da/liu2021_sanity.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Sanity checks for the Liu 2021 build, computed the same way for giroux2022 and ye2026_sepsis (CPU only).
3
+
4
+ For every usable row (folds.csv fold >= 0): Pearson r between log1p(CPM) of the bulk and log1p(CPM) of the sc
5
+ pseudobulk (retained cells), over that row's pair_valid genes, CPM taken over the same pair_valid genes in both
6
+ assays. Also retained cells per row and UMIs per retained cell. Writes processing/.../SANITY.json.
7
+ """
8
+ from __future__ import annotations
9
+
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
+ TASK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
20
+ RUN = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/liu2021_v1_20261002")
21
+ DATASETS = ["liu2021", "giroux2022", "ye2026_sepsis", "imperial_eskd"]
22
+
23
+
24
+ def summarise(v: np.ndarray) -> dict:
25
+ v = np.asarray(v, dtype=float)
26
+ return {"n": int(v.size), "median": float(np.median(v)), "min": float(v.min()), "max": float(v.max()),
27
+ "q25": float(np.quantile(v, 0.25)), "q75": float(np.quantile(v, 0.75))}
28
+
29
+
30
+ def main() -> None:
31
+ out = {"definition": ("per usable row (folds.csv fold >= 0): Pearson r of log1p(CPM) bulk vs log1p(CPM) sc "
32
+ "pseudobulk (pseudo_raw_sum, retained cells) over the row's pair_valid genes; CPM over the "
33
+ "same pair_valid genes in both assays; NaN bulk outside bulk_valid is never used"),
34
+ "datasets": {}}
35
+ for ds in DATASETS:
36
+ d = TASK / "data" / ds
37
+ f = np.load(d / "features.npz", allow_pickle=False)
38
+ folds = pd.read_csv(d / "folds.csv")
39
+ if not np.array_equal(folds.sample_id.astype(str).to_numpy(), f["sample_ids"].astype(str)):
40
+ raise SystemExit(f"{ds}: folds.csv order differs from features.npz")
41
+ use = folds.fold.to_numpy() >= 0
42
+ rs, umi_med = [], []
43
+ for r in np.flatnonzero(use):
44
+ pv = f["pair_valid"][r].astype(bool)
45
+ b = f["bulk_raw"][r][pv].astype(float)
46
+ s = f["pseudo_raw_sum"][r][pv].astype(float)
47
+ if not (np.isfinite(b).all() and np.isfinite(s).all()):
48
+ raise SystemExit(f"{ds} row {r}: non-finite value on pair_valid genes")
49
+ lb = np.log1p(b / b.sum() * 1e6)
50
+ ls = np.log1p(s / s.sum() * 1e6)
51
+ rs.append(float(np.corrcoef(lb, ls)[0, 1]))
52
+ obs = pd.read_parquet(d / "cells_obs.parquet", columns=["row_sample", "raw_gex_total", "cell_total_canonical"])
53
+ per_row = obs.groupby("row_sample").raw_gex_total.median()
54
+ cells = f["qc_cell_counts"][use]
55
+ rec = {"rows": int(len(use)), "usable_rows": int(use.sum()),
56
+ "pearson_log1p_cpm_bulk_vs_pseudobulk": summarise(rs),
57
+ "pair_valid_genes_per_row": summarise(f["pair_valid"][use].sum(1)),
58
+ "retained_cells_per_usable_row": summarise(cells),
59
+ "retained_cells_total_usable_rows": int(cells.sum()),
60
+ "umi_per_cell_source_median_all_cells_usable_rows": float(np.median(obs.raw_gex_total[np.isin(obs.row_sample, np.flatnonzero(use))])),
61
+ "umi_per_cell_canonical_median_all_cells_usable_rows": float(np.median(obs.cell_total_canonical[np.isin(obs.row_sample, np.flatnonzero(use))])),
62
+ "umi_per_cell_source_median_of_row_medians": float(np.median(per_row.loc[np.flatnonzero(use)]))}
63
+ if ds == "liu2021":
64
+ rec["per_row"] = pd.DataFrame({"sample_id": f["sample_ids"][use].astype(str), "batch": f["batch"][use].astype(str),
65
+ "r": rs, "cells": cells,
66
+ "umi_median": per_row.loc[np.flatnonzero(use)].to_numpy()}).round(4).to_dict("records")
67
+ byb = pd.DataFrame(rec["per_row"]).groupby("batch")
68
+ rec["by_batch"] = {b: {"rows": int(len(g)), "r_median": float(g.r.median()), "cells_median": float(g.cells.median()),
69
+ "umi_median_of_row_medians": float(g.umi_median.median())} for b, g in byb}
70
+ out["datasets"][ds] = rec
71
+ print(ds, json.dumps({k: v for k, v in rec.items() if k not in ("per_row",)}, default=float))
72
+ (RUN / "SANITY.json").write_text(json.dumps(out, indent=1, default=float) + "\n")
73
+
74
+
75
+ if __name__ == "__main__":
76
+ main()