Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/9f09c3778e1ee97c/qc_singlecell.py +667 -0
- paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/cacc70e2bf7a0b8c/strict_qc_driver.py +207 -0
- paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/eee279f6185909b7/qc_validate_outputs.py +191 -0
- paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/README.md +124 -0
paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/9f09c3778e1ee97c/qc_singlecell.py
ADDED
|
@@ -0,0 +1,667 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Organize single-cell files, audit numbers and identities, export sparse H5AD.
|
| 2 |
+
|
| 3 |
+
No biological inference is performed. Original cells are retained; thresholds
|
| 4 |
+
are reversible annotations. Published metadata is joined on explicit keys.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from collections import Counter
|
| 9 |
+
import csv
|
| 10 |
+
import gc
|
| 11 |
+
import gzip
|
| 12 |
+
import hashlib
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import re
|
| 17 |
+
from typing import Iterator
|
| 18 |
+
|
| 19 |
+
import h5py
|
| 20 |
+
import numpy as np
|
| 21 |
+
import pandas as pd
|
| 22 |
+
from scipy import sparse
|
| 23 |
+
from scipy.io import mmread
|
| 24 |
+
|
| 25 |
+
from qc_core import QCError, _h5_column, _h5_index, _strings, _text_open, _write_json, scan_h5, scan_mtx, sha256_file
|
| 26 |
+
from qc_genes import GeneMapper
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
SC_ACCESSIONS = {"GSE132044", "GSE155673", "GSE161610", "GSE162632", "GSE198616",
|
| 30 |
+
"GSE201534", "GSE246937", "GSE247707", "GSE253173", "GSE314416"}
|
| 31 |
+
MAX_MTX_ALLOCATION_ESTIMATE = 4 * 1024**3
|
| 32 |
+
COUNT_SOURCE_EVIDENCE = {
|
| 33 |
+
"GSE132044": "Published protocol benchmark pbmc_hg38_count_matrix; read/UMI units kept separate by published barcode protocol",
|
| 34 |
+
"GSE155673": "Published 10x covXX RNA matrix/features/barcodes companions",
|
| 35 |
+
"GSE161610": "Published 10x PB patient feature-barcode count matrices",
|
| 36 |
+
"GSE162632": "Published Bx-cx-10X expression count matrices",
|
| 37 |
+
"GSE198616": "Published 10x PBMC/monocyte feature-barcode expression count matrices",
|
| 38 |
+
"GSE201534": "Published 10x filtered_feature_bc_matrix.h5 with independent MTX representation",
|
| 39 |
+
"GSE246937": "Published 10x pooled feature-barcode matrices; antibody features excluded from RNA counts",
|
| 40 |
+
"GSE247707": "Published 10x PBMC_Pooled feature-barcode matrix; author-filtering status separate",
|
| 41 |
+
"GSE314416": "Published GEX.h5 10x gene-expression counts; separate ADT files omitted",
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _stem(path: Path) -> str:
|
| 46 |
+
return re.sub(r"(?:_?count_?)?matrix\.mtx(?:\.gz)?$", "", path.name, flags=re.I).rstrip("_")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def discover_libraries(root: Path, runroot: Path) -> list[dict]:
|
| 50 |
+
"""Find expression sources; prefer 10x H5 when matching MTX also exists."""
|
| 51 |
+
libraries = []
|
| 52 |
+
for accession in sorted(SC_ACCESSIONS):
|
| 53 |
+
paths = sorted({p for base in (root / "datasets" / accession / "raw", runroot / "extracted" / accession)
|
| 54 |
+
if base.exists() for p in base.rglob("*") if p.is_file()})
|
| 55 |
+
h5_sources = [p for p in paths if p.suffix.lower() in (".h5", ".h5ad") and "_adt" not in p.name.lower()]
|
| 56 |
+
h5_gsm = {re.search(r"GSM\d+", str(p)).group() for p in h5_sources if re.search(r"GSM\d+", str(p))}
|
| 57 |
+
for path in paths:
|
| 58 |
+
is_mtx = bool(re.search(r"matrix\.mtx(?:\.gz)?$", path.name, re.I))
|
| 59 |
+
if path not in h5_sources and not is_mtx:
|
| 60 |
+
continue
|
| 61 |
+
if (accession == "GSE247707" and "pbmc" not in path.name.lower()) or (accession == "GSE161610" and re.search(r"(?:_|/)LN\d", str(path))):
|
| 62 |
+
continue
|
| 63 |
+
match = re.search(r"GSM\d+", str(path))
|
| 64 |
+
library = match.group() if match else (_stem(path) if is_mtx else path.stem)
|
| 65 |
+
if not library:
|
| 66 |
+
library = path.parent.name
|
| 67 |
+
item = {"accession": accession, "library_id": library, "path": str(path),
|
| 68 |
+
"format": "mtx" if is_mtx else "h5", "duplicate_representation": bool(is_mtx and match and library in h5_gsm)}
|
| 69 |
+
if is_mtx:
|
| 70 |
+
prefix = _stem(path)
|
| 71 |
+
siblings = list(path.parent.iterdir())
|
| 72 |
+
feature_names = [(prefix + "_" if prefix else "") + part + suffix
|
| 73 |
+
for part in ("features", "genes", "gene") for suffix in (".tsv.gz", ".tsv")]
|
| 74 |
+
barcode_names = [(prefix + "_" if prefix else "") + part + suffix
|
| 75 |
+
for part in ("barcodes", "cell", "cells") for suffix in (".tsv.gz", ".tsv")]
|
| 76 |
+
feature = next((p for p in siblings if p.name.lower() in [n.lower() for n in feature_names]), None)
|
| 77 |
+
barcode = next((p for p in siblings if p.name.lower() in [n.lower() for n in barcode_names]), None)
|
| 78 |
+
if accession == "GSE155673":
|
| 79 |
+
feature = root / "datasets/GSE155673/raw/GSE155673_features.tsv.gz"
|
| 80 |
+
if accession == "GSE132044":
|
| 81 |
+
feature = root / "datasets/GSE132044/raw/GSE132044_pbmc_hg38_gene.tsv.gz"
|
| 82 |
+
barcode = root / "datasets/GSE132044/raw/GSE132044_pbmc_hg38_cell.tsv.gz"
|
| 83 |
+
item["features_path"] = str(feature) if feature else ""
|
| 84 |
+
item["barcodes_path"] = str(barcode) if barcode else ""
|
| 85 |
+
libraries.append(item)
|
| 86 |
+
return sorted(libraries, key=lambda item: (item["duplicate_representation"], item["accession"], item["library_id"]))
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def read_axes(item: dict) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, dict]:
|
| 90 |
+
path = Path(item["path"])
|
| 91 |
+
if item["format"] == "mtx":
|
| 92 |
+
if not item["features_path"] or not item["barcodes_path"]:
|
| 93 |
+
raise QCError("Missing paired feature or barcode file")
|
| 94 |
+
with _text_open(item["features_path"]) as handle:
|
| 95 |
+
rows = [line.rstrip("\n\r").split("\t") for line in handle if line.strip()]
|
| 96 |
+
ids = [row[0] for row in rows]
|
| 97 |
+
symbols = [row[1] if len(row) > 1 else row[0] for row in rows]
|
| 98 |
+
if item["accession"] == "GSE132044":
|
| 99 |
+
ids = [value.split("_", 1)[0] for value in ids]
|
| 100 |
+
symbols = [row[0].split("_", 1)[1] if "_" in row[0] else row[0] for row in rows]
|
| 101 |
+
rna = np.asarray([len(row) < 3 or row[2] == "Gene Expression" for row in rows])
|
| 102 |
+
with _text_open(item["barcodes_path"]) as handle:
|
| 103 |
+
cells = [line.rstrip("\n\r").split("\t")[0] for line in handle if line.strip()]
|
| 104 |
+
return np.asarray(ids), np.asarray(symbols), np.asarray(cells), rna, {"matrix_path": None, "source": "feature/barcode companion files"}
|
| 105 |
+
with h5py.File(path, "r", rdcc_nbytes=256 * 1024**2) as handle:
|
| 106 |
+
if "matrix" in handle:
|
| 107 |
+
matrix = handle["matrix"]
|
| 108 |
+
features = matrix["features"]
|
| 109 |
+
ids = _strings(features["id"])
|
| 110 |
+
symbols = _strings(features["name"]) if "name" in features else ids
|
| 111 |
+
rna = _strings(features["feature_type"]) == "Gene Expression" if "feature_type" in features else np.ones(len(ids), bool)
|
| 112 |
+
cells = _strings(matrix["barcodes"])
|
| 113 |
+
return ids, symbols, cells, rna, {"matrix_path": "matrix", "source": "10x H5 embedded axes"}
|
| 114 |
+
matrix_path = item.get("matrix_path", "X")
|
| 115 |
+
var = handle["raw/var"] if matrix_path.startswith("raw/") else handle["var"]
|
| 116 |
+
ids = _h5_index(var)
|
| 117 |
+
symbols = None
|
| 118 |
+
for name in ("gene", "gene_symbols", "gene_symbol", "feature_name", "symbol"):
|
| 119 |
+
if name in var:
|
| 120 |
+
symbols = _h5_column(var, name)
|
| 121 |
+
break
|
| 122 |
+
if symbols is None:
|
| 123 |
+
symbols = ids
|
| 124 |
+
cells = _h5_index(handle["obs"])
|
| 125 |
+
return ids, symbols, cells, np.ones(len(ids), bool), {"matrix_path": matrix_path, "source": "H5AD embedded axes"}
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _read_csv(path: Path) -> pd.DataFrame:
|
| 129 |
+
return pd.read_csv(path, dtype=str, keep_default_na=False) if path.exists() else pd.DataFrame()
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def assign_metadata(item: dict, cells: np.ndarray, runroot: Path) -> tuple[pd.DataFrame, dict]:
|
| 133 |
+
accession, library = item["accession"], item["library_id"]
|
| 134 |
+
source_cells = np.asarray(cells, dtype=str)
|
| 135 |
+
if np.any(np.char.strip(source_cells) == "") or len(np.unique(source_cells)) != len(source_cells):
|
| 136 |
+
raise QCError("Source library cell identifiers are empty or nonunique")
|
| 137 |
+
obs = pd.DataFrame({"barcode": source_cells, "source_barcode": source_cells,
|
| 138 |
+
"raw_10x_barcode": "", "author_cell_id": "", "library_id": library, "donor_id": "", "sample_id": "", "visit_id": "",
|
| 139 |
+
"author_retained": "unknown", "mapping_basis": "unresolved", "protocol": ""})
|
| 140 |
+
key_representation = "unresolved"
|
| 141 |
+
audit = runroot / "pairing_audit"
|
| 142 |
+
mapping_path = audit / (accession + "_cell_map.csv.gz")
|
| 143 |
+
if mapping_path.exists():
|
| 144 |
+
# Avoid retaining the complete project mapping across 54 pooled libraries.
|
| 145 |
+
pieces = []
|
| 146 |
+
for chunk in pd.read_csv(mapping_path, dtype=str, keep_default_na=False, chunksize=100_000):
|
| 147 |
+
subset = chunk[chunk.library_id == library]
|
| 148 |
+
if len(subset):
|
| 149 |
+
pieces.append(subset)
|
| 150 |
+
if pieces:
|
| 151 |
+
mapping = pd.concat(pieces, ignore_index=True)
|
| 152 |
+
if mapping.duplicated(["library_id", "barcode"]).any():
|
| 153 |
+
raise QCError("Published cell map has duplicate library+barcode keys")
|
| 154 |
+
raw_rows = pd.Index(mapping.barcode).get_indexer(source_cells)
|
| 155 |
+
author_rows = np.full(len(source_cells), -1, dtype=np.int64)
|
| 156 |
+
if "author_cell_id" in mapping:
|
| 157 |
+
nonempty = mapping.author_cell_id.astype(str).str.len() > 0
|
| 158 |
+
if mapping.loc[nonempty].duplicated(["library_id", "author_cell_id"]).any():
|
| 159 |
+
raise QCError("Published cell map has duplicate library+author_cell_id keys")
|
| 160 |
+
indices = np.flatnonzero(nonempty.to_numpy())
|
| 161 |
+
found = pd.Index(mapping.loc[nonempty, "author_cell_id"]).get_indexer(source_cells)
|
| 162 |
+
author_rows[found >= 0] = indices[found[found >= 0]]
|
| 163 |
+
both = (raw_rows >= 0) & (author_rows >= 0)
|
| 164 |
+
if np.any(both & (raw_rows != author_rows)):
|
| 165 |
+
raise QCError("Ambiguous raw-barcode/author-cell-ID representations point to different published cells")
|
| 166 |
+
raw_only = (raw_rows >= 0) & (author_rows < 0)
|
| 167 |
+
author_only = (author_rows >= 0) & (raw_rows < 0)
|
| 168 |
+
if raw_only.any() and author_only.any():
|
| 169 |
+
raise QCError("Mixed raw-barcode and author-cell-ID representations within one source library")
|
| 170 |
+
if author_only.any():
|
| 171 |
+
match_column = "author_cell_id"
|
| 172 |
+
key_representation = "library_id+author_cell_id"
|
| 173 |
+
else:
|
| 174 |
+
match_column = "barcode"
|
| 175 |
+
key_representation = "library_id+barcode" if (raw_rows >= 0).any() else "no_exact_published_key_match"
|
| 176 |
+
# The source string is never split, stripped, or reconstructed. Both
|
| 177 |
+
# accepted representations already occur explicitly in author metadata.
|
| 178 |
+
right = mapping.copy()
|
| 179 |
+
right["_source_match_key"] = right[match_column]
|
| 180 |
+
right = right[right._source_match_key.astype(str).str.len() > 0]
|
| 181 |
+
right = right.rename(columns={"barcode": "raw_10x_barcode"})
|
| 182 |
+
joined = obs[["library_id", "source_barcode"]].merge(
|
| 183 |
+
right, left_on=["library_id", "source_barcode"], right_on=["library_id", "_source_match_key"],
|
| 184 |
+
how="left", validate="one_to_one", sort=False)
|
| 185 |
+
for column in obs.columns:
|
| 186 |
+
if column in joined and column not in ("barcode", "source_barcode", "library_id"):
|
| 187 |
+
obs[column] = joined[column].fillna("unknown" if column == "author_retained" else "")
|
| 188 |
+
for column in ("cell_type", "author_cell_id", "author_pool_id"):
|
| 189 |
+
if column in joined:
|
| 190 |
+
obs[column] = joined[column].fillna("")
|
| 191 |
+
elif accession == "GSE155673":
|
| 192 |
+
pairs = _read_csv(audit / "D02_covid_pairs.csv")
|
| 193 |
+
number = re.search(r"cov_?(\d+)", Path(item["path"]).name, re.I)
|
| 194 |
+
if number and len(pairs):
|
| 195 |
+
labels = pairs.sc_title.str.extract(r"cov_?(\d+)", expand=False).astype(int)
|
| 196 |
+
selected = pairs[labels == int(number.group(1))]
|
| 197 |
+
if len(selected) == 1:
|
| 198 |
+
row = selected.iloc[0]
|
| 199 |
+
obs["library_id"] = row.sc_gsm
|
| 200 |
+
item["published_library_id"] = row.sc_gsm
|
| 201 |
+
obs["donor_id"], obs["sample_id"] = row.subject, row.sc_title
|
| 202 |
+
obs["visit_id"] = row.get("day_since_symptoms", "")
|
| 203 |
+
obs["mapping_basis"] = "published library identity in D02_covid_pairs.csv"
|
| 204 |
+
elif accession in ("GSE198616", "GSE201534", "GSE161610"):
|
| 205 |
+
inventory = _read_csv(audit / (accession + "_published_sample_inventory.csv"))
|
| 206 |
+
selected = inventory[inventory.gsm == library] if len(inventory) else inventory
|
| 207 |
+
if len(selected) == 1:
|
| 208 |
+
title = selected.iloc[0].title
|
| 209 |
+
obs["sample_id"] = title
|
| 210 |
+
obs["mapping_basis"] = "published unpooled GEO library/sample label; bulk linkage remains separate"
|
| 211 |
+
if accession == "GSE201534":
|
| 212 |
+
match = re.fullmatch(r"(.+)_Day(\d+)", title)
|
| 213 |
+
if match:
|
| 214 |
+
obs["donor_id"], obs["visit_id"] = match.group(1), "GEO_Day" + match.group(2)
|
| 215 |
+
if accession == "GSE161610":
|
| 216 |
+
obs["donor_id"] = title
|
| 217 |
+
elif accession == "GSE132044":
|
| 218 |
+
pairs = _read_csv(audit / "H03_ding_pairs.csv")
|
| 219 |
+
for _, row in pairs.iterrows():
|
| 220 |
+
selected = np.char.startswith(cells.astype(str), row.sc_cell_id_prefix)
|
| 221 |
+
obs.loc[selected, "protocol"] = [value.split(".")[1] if len(value.split(".")) > 1 else "" for value in cells[selected]]
|
| 222 |
+
# Protocols measure different numeric units; never aggregate across them.
|
| 223 |
+
obs.loc[selected, "sample_id"] = row.sample_id + "|" + obs.loc[selected, "protocol"]
|
| 224 |
+
obs.loc[selected, "mapping_basis"] = "published specimen prefix; protocol retained separately"
|
| 225 |
+
elif accession == "GSE253173":
|
| 226 |
+
with h5py.File(item["path"], "r") as handle:
|
| 227 |
+
for source, target in (("LibraryName", "published_LibraryName"), ("Timepoint", "published_Timepoint")):
|
| 228 |
+
if source in handle["obs"]:
|
| 229 |
+
obs[target] = _h5_column(handle["obs"], source)
|
| 230 |
+
crosswalk = _read_csv(audit / "GSE253173_library_map.csv")
|
| 231 |
+
if len(crosswalk) and "published_LibraryName" in obs:
|
| 232 |
+
key = "LibraryName" if "LibraryName" in crosswalk else "published_LibraryName"
|
| 233 |
+
if crosswalk[key].duplicated().any():
|
| 234 |
+
raise QCError("DREAM published library crosswalk has duplicate keys")
|
| 235 |
+
indexed = crosswalk.set_index(key)
|
| 236 |
+
for column in ("donor_id", "sample_id", "visit_id"):
|
| 237 |
+
if column in indexed:
|
| 238 |
+
obs[column] = obs.published_LibraryName.map(indexed[column]).fillna("")
|
| 239 |
+
obs.loc[obs.sample_id != "", "mapping_basis"] = "published DREAM library crosswalk"
|
| 240 |
+
matched = obs.sample_id.astype(str).str.len() > 0
|
| 241 |
+
return obs, {"n_cells": len(obs), "mapped_sample_cells": int(matched.sum()),
|
| 242 |
+
"unresolved_sample_cells": int((~matched).sum()), "full_sample_mapping": bool(matched.all()),
|
| 243 |
+
"donor_resolved_cells": int((obs.donor_id.astype(str).str.len() > 0).sum()),
|
| 244 |
+
"n_published_samples": int(obs.loc[matched, "sample_id"].nunique()),
|
| 245 |
+
"source_key_representation": key_representation,
|
| 246 |
+
"join_policy": "exact published keys only; no expression or row-order inference"}
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def _mtx_dimensions(path: Path) -> tuple[int, int, int]:
|
| 250 |
+
with _text_open(path) as handle:
|
| 251 |
+
next(handle)
|
| 252 |
+
for line in handle:
|
| 253 |
+
if line.strip() and not line.startswith("%"):
|
| 254 |
+
return tuple(map(int, line.split()))
|
| 255 |
+
raise QCError("Missing matrix dimensions")
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def _mtx_entries(path: Path):
|
| 259 |
+
"""Iterate already-audited coordinates; no matrix allocation."""
|
| 260 |
+
with _text_open(path) as handle:
|
| 261 |
+
next(handle)
|
| 262 |
+
for line in handle:
|
| 263 |
+
if line.strip() and not line.lstrip().startswith("%"):
|
| 264 |
+
break # dimensions
|
| 265 |
+
for line in handle:
|
| 266 |
+
if line.strip() and not line.lstrip().startswith("%"):
|
| 267 |
+
fields = line.split()
|
| 268 |
+
if len(fields) != 3:
|
| 269 |
+
raise QCError("MTX source changed or malformed during export")
|
| 270 |
+
yield int(fields[0]) - 1, int(fields[1]) - 1, float(fields[2])
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def _mtx_cell_ordered(path: Path) -> bool:
|
| 274 |
+
previous = -1
|
| 275 |
+
for _, cell, _ in _mtx_entries(path):
|
| 276 |
+
if cell < previous:
|
| 277 |
+
return False
|
| 278 |
+
previous = cell
|
| 279 |
+
return True
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _stream_mtx_cells(path: Path, n_features: int, n_cells: int, block_cells: int):
|
| 283 |
+
start, previous, seen = 0, -1, 0
|
| 284 |
+
rows, genes, values = [], [], []
|
| 285 |
+
for gene, cell, value in _mtx_entries(path):
|
| 286 |
+
if cell < previous or not (0 <= gene < n_features and 0 <= cell < n_cells):
|
| 287 |
+
raise QCError("MTX coordinate order/bounds changed during streaming export")
|
| 288 |
+
previous = cell
|
| 289 |
+
seen += 1
|
| 290 |
+
while cell >= min(start + block_cells, n_cells):
|
| 291 |
+
stop = min(start + block_cells, n_cells)
|
| 292 |
+
yield start, sparse.csr_matrix((values, (rows, genes)), shape=(stop - start, n_features), dtype=np.float64)
|
| 293 |
+
start = stop
|
| 294 |
+
rows, genes, values = [], [], []
|
| 295 |
+
rows.append(cell - start)
|
| 296 |
+
genes.append(gene)
|
| 297 |
+
values.append(value)
|
| 298 |
+
expected = _mtx_dimensions(path)[2]
|
| 299 |
+
if seen != expected:
|
| 300 |
+
raise QCError(f"MTX nnz changed during streaming export: {seen} vs {expected}")
|
| 301 |
+
while start < n_cells:
|
| 302 |
+
stop = min(start + block_cells, n_cells)
|
| 303 |
+
yield start, sparse.csr_matrix((values, (rows, genes)), shape=(stop - start, n_features), dtype=np.float64)
|
| 304 |
+
start = stop
|
| 305 |
+
rows, genes, values = [], [], []
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def source_blocks(item: dict, n_features: int, n_cells: int, block_cells: int = 256) -> Iterator[tuple[int, sparse.csr_matrix]]:
|
| 309 |
+
"""Yield cells×source_features sparse blocks; cap full-MTX sparse allocation."""
|
| 310 |
+
path = Path(item["path"])
|
| 311 |
+
if item["format"] == "mtx":
|
| 312 |
+
_, _, nnz = _mtx_dimensions(path)
|
| 313 |
+
estimate = nnz * 96 + (n_cells + n_features) * 32
|
| 314 |
+
if estimate > MAX_MTX_ALLOCATION_ESTIMATE:
|
| 315 |
+
if not _mtx_cell_ordered(path):
|
| 316 |
+
raise QCError(f"Canonical MTX export resource quarantine: unsorted coordinates and conservative allocation estimate {estimate} exceeds 4 GiB")
|
| 317 |
+
item["source_iteration"] = "verified cell-column-ordered MTX streaming"
|
| 318 |
+
yield from _stream_mtx_cells(path, n_features, n_cells, block_cells)
|
| 319 |
+
return
|
| 320 |
+
item["source_iteration"] = "bounded sparse MTX load below conservative 4 GiB allocation estimate"
|
| 321 |
+
matrix = mmread(path).tocsc()
|
| 322 |
+
if matrix.shape != (n_features, n_cells):
|
| 323 |
+
raise QCError("MTX dimensions changed after audit")
|
| 324 |
+
for start in range(0, n_cells, block_cells):
|
| 325 |
+
yield start, matrix[:, start:start + block_cells].T.tocsr()
|
| 326 |
+
return
|
| 327 |
+
with h5py.File(path, "r", rdcc_nbytes=256 * 1024**2) as handle:
|
| 328 |
+
item["source_iteration"] = "backed HDF5 cell blocks"
|
| 329 |
+
tenx = "matrix" in handle
|
| 330 |
+
matrix = handle["matrix" if tenx else item.get("matrix_path", "X")]
|
| 331 |
+
if isinstance(matrix, h5py.Dataset):
|
| 332 |
+
for start in range(0, n_cells, block_cells):
|
| 333 |
+
yield start, sparse.csr_matrix(matrix[start:start + block_cells, :])
|
| 334 |
+
return
|
| 335 |
+
encoding = matrix.attrs.get("encoding-type", "")
|
| 336 |
+
if isinstance(encoding, bytes):
|
| 337 |
+
encoding = encoding.decode()
|
| 338 |
+
if not tenx and encoding != "csr_matrix":
|
| 339 |
+
raise QCError("H5AD canonical export requires cell-major CSR; non-CSR input remains QC-only")
|
| 340 |
+
# Retain dataset handles: the HDF5 raw chunk cache belongs to each
|
| 341 |
+
# open dataset. Reopening matrix["data"] per block discards the cache.
|
| 342 |
+
data_dataset, index_dataset, pointer_dataset = matrix["data"], matrix["indices"], matrix["indptr"]
|
| 343 |
+
for start in range(0, n_cells, block_cells):
|
| 344 |
+
stop = min(start + block_cells, n_cells)
|
| 345 |
+
pointers = np.asarray(pointer_dataset[start:stop + 1], dtype=np.int64)
|
| 346 |
+
first, last = int(pointers[0]), int(pointers[-1])
|
| 347 |
+
pointers -= first
|
| 348 |
+
data = np.asarray(data_dataset[first:last])
|
| 349 |
+
indices = np.asarray(index_dataset[first:last])
|
| 350 |
+
yield start, sparse.csr_matrix((data, indices, pointers), shape=(stop - start, n_features))
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def _h5_array(group, name: str, values) -> None:
|
| 354 |
+
values = np.asarray(values)
|
| 355 |
+
if values.dtype.kind in "OUS":
|
| 356 |
+
dataset = group.create_dataset(name, data=values.astype(object), dtype=h5py.string_dtype("utf-8"))
|
| 357 |
+
dataset.attrs["encoding-type"], dataset.attrs["encoding-version"] = "string-array", "0.2.0"
|
| 358 |
+
else:
|
| 359 |
+
dataset = group.create_dataset(name, data=values)
|
| 360 |
+
dataset.attrs["encoding-type"], dataset.attrs["encoding-version"] = "array", "0.2.0"
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def _h5_dataframe(parent, name: str, columns: dict, index: np.ndarray) -> None:
|
| 364 |
+
group = parent.create_group(name)
|
| 365 |
+
group.attrs["encoding-type"], group.attrs["encoding-version"] = "dataframe", "0.2.0"
|
| 366 |
+
group.attrs["_index"] = "_index"
|
| 367 |
+
group.attrs["column-order"] = np.asarray(list(columns), dtype=h5py.string_dtype())
|
| 368 |
+
_h5_array(group, "_index", index)
|
| 369 |
+
for column, values in columns.items():
|
| 370 |
+
_h5_array(group, column, values)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def _h5_scalar(group, name: str, value: str | bool) -> None:
|
| 374 |
+
if isinstance(value, str):
|
| 375 |
+
dataset = group.create_dataset(name, data=value, dtype=h5py.string_dtype("utf-8"))
|
| 376 |
+
dataset.attrs["encoding-type"] = "string"
|
| 377 |
+
else:
|
| 378 |
+
dataset = group.create_dataset(name, data=value)
|
| 379 |
+
dataset.attrs["encoding-type"] = "numeric-scalar"
|
| 380 |
+
dataset.attrs["encoding-version"] = "0.2.0"
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def validate_sample_context(obs: pd.DataFrame, aggregation_mask: np.ndarray) -> dict[str, dict]:
|
| 384 |
+
"""Reject contextual collisions; retain missing metadata explicitly as empty.
|
| 385 |
+
|
| 386 |
+
A published sample can be valid without a disclosed donor identity. Missing
|
| 387 |
+
context is not filled from another record; only consistent, published values
|
| 388 |
+
are recorded in the aggregate metadata.
|
| 389 |
+
"""
|
| 390 |
+
contexts = {}
|
| 391 |
+
for sample, rows in obs.loc[aggregation_mask].groupby("sample_id", sort=True):
|
| 392 |
+
context = {}
|
| 393 |
+
for field in ("donor_id", "visit_id", "protocol"):
|
| 394 |
+
values = rows[field].astype(str).str.strip() if field in rows else pd.Series("", index=rows.index)
|
| 395 |
+
observed = sorted(set(values[~values.isin(["", "unknown", "not_published"])]))
|
| 396 |
+
if len(observed) > 1:
|
| 397 |
+
raise QCError(f"Conflicting {field} within published sample {sample!r}: {observed}")
|
| 398 |
+
context[field] = observed[0] if observed else ""
|
| 399 |
+
context[field + "_missing_cells"] = int(values.isin(["", "unknown", "not_published"]).sum())
|
| 400 |
+
contexts[str(sample)] = context
|
| 401 |
+
return contexts
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def canonical_export(item: dict, out: Path, mapping: list[dict], canonical: list[dict],
|
| 405 |
+
obs: pd.DataFrame, rna: np.ndarray, *, verified_counts: bool, units: str,
|
| 406 |
+
full_mapping: bool) -> dict:
|
| 407 |
+
"""Write canonical CSR incrementally; prove mapped/excluded mass accounting."""
|
| 408 |
+
target = np.asarray([row["target_index"] for row in mapping], dtype=np.int64)
|
| 409 |
+
target[~rna] = -1
|
| 410 |
+
present = np.zeros(len(canonical), dtype=bool)
|
| 411 |
+
present[target[target >= 0]] = True
|
| 412 |
+
ambiguous_candidate = np.zeros(len(canonical), dtype=bool)
|
| 413 |
+
canonical_index = {row["gene_id"]: index for index, row in enumerate(canonical)}
|
| 414 |
+
for row, is_rna in zip(mapping, rna):
|
| 415 |
+
if is_rna and "ambiguous" in row.get("status", ""):
|
| 416 |
+
for candidate in row.get("candidate_ids", "").split("|"):
|
| 417 |
+
if candidate in canonical_index:
|
| 418 |
+
ambiguous_candidate[canonical_index[candidate]] = True
|
| 419 |
+
multiplicity = Counter(target[target >= 0])
|
| 420 |
+
collision = np.asarray([value >= 0 and multiplicity[value] > 1 for value in target])
|
| 421 |
+
if not verified_counts:
|
| 422 |
+
target[collision] = -1
|
| 423 |
+
harmonization_valid = np.zeros(len(canonical), dtype=bool)
|
| 424 |
+
harmonization_valid[target[target >= 0]] = True
|
| 425 |
+
reducer = sparse.csr_matrix((np.ones(np.sum(target >= 0)),
|
| 426 |
+
(np.flatnonzero(target >= 0), target[target >= 0])),
|
| 427 |
+
shape=(len(mapping), len(canonical)))
|
| 428 |
+
destination = out / "canonical.h5ad"
|
| 429 |
+
temporary = out / "canonical.h5ad.partial"
|
| 430 |
+
qcpass = np.load(out / "metrics/flag_conservative_review_pass.npy", mmap_mode="r")
|
| 431 |
+
cell_total = np.load(out / "metrics/cell_total.npy", mmap_mode="r")
|
| 432 |
+
observed_mass = excluded_mass = exported_mass = 0.0
|
| 433 |
+
mapped = obs.sample_id.astype(str).str.len().to_numpy() > 0
|
| 434 |
+
author_retained = obs.get("author_retained", pd.Series("unknown", index=obs.index)).astype(str).str.lower().isin(["true", "1", "yes"]).to_numpy()
|
| 435 |
+
aggregation_mask = mapped & (np.ones(len(obs), bool) if full_mapping else author_retained)
|
| 436 |
+
samples = sorted(obs.loc[aggregation_mask, "sample_id"].unique()) if verified_counts else []
|
| 437 |
+
sample_contexts = validate_sample_context(obs, aggregation_mask) if samples else {}
|
| 438 |
+
sample_index = {value: i for i, value in enumerate(samples)}
|
| 439 |
+
pseudobulk = np.zeros((2, len(samples), len(canonical)), dtype=np.float64)
|
| 440 |
+
sample_n = np.zeros((2, len(samples)), dtype=np.int64)
|
| 441 |
+
sample_source_mass = np.zeros((2, len(samples)), dtype=np.float64)
|
| 442 |
+
pseudobulk_enabled = bool(samples)
|
| 443 |
+
non_rna = np.flatnonzero(~rna)
|
| 444 |
+
with h5py.File(temporary, "w") as handle:
|
| 445 |
+
handle.attrs["encoding-type"], handle.attrs["encoding-version"] = "anndata", "0.1.0"
|
| 446 |
+
handle.attrs["source_path"] = item["path"]
|
| 447 |
+
handle.attrs["numeric_units"] = units
|
| 448 |
+
handle.attrs["missing_gene_semantics"] = "Zero storage with source_feature_present=False means absent from or unresolved in the supplied feature table; assay coverage is unknown"
|
| 449 |
+
handle.attrs["duplicate_gene_policy"] = "sum mapped collisions in verified count space" if verified_counts else "exclude all colliding source features"
|
| 450 |
+
x = handle.create_group("X")
|
| 451 |
+
x.attrs["encoding-type"], x.attrs["encoding-version"] = "csr_matrix", "0.1.0"
|
| 452 |
+
x.attrs["shape"] = [len(obs), len(canonical)]
|
| 453 |
+
data = x.create_dataset("data", shape=(0,), maxshape=(None,), dtype="f8", chunks=(250_000,), compression="gzip", compression_opts=1)
|
| 454 |
+
indices = x.create_dataset("indices", shape=(0,), maxshape=(None,), dtype="i4", chunks=(250_000,), compression="gzip", compression_opts=1)
|
| 455 |
+
indptr = x.create_dataset("indptr", shape=(len(obs) + 1,), dtype="i8")
|
| 456 |
+
indptr[0] = 0
|
| 457 |
+
auxiliary = handle.create_group("obsm")
|
| 458 |
+
auxiliary.attrs["encoding-type"], auxiliary.attrs["encoding-version"] = "dict", "0.1.0"
|
| 459 |
+
if len(non_rna):
|
| 460 |
+
auxiliary_counts = auxiliary.create_dataset("source_non_rna_counts", shape=(len(obs), len(non_rna)),
|
| 461 |
+
dtype="f8", chunks=(min(256, len(obs)), len(non_rna)),
|
| 462 |
+
compression="gzip", compression_opts=1)
|
| 463 |
+
auxiliary_counts.attrs["encoding-type"], auxiliary_counts.attrs["encoding-version"] = "array", "0.2.0"
|
| 464 |
+
cursor = 0
|
| 465 |
+
for start, source in source_blocks(item, len(mapping), len(obs)):
|
| 466 |
+
stop = start + source.shape[0]
|
| 467 |
+
source = source.astype(np.float64, copy=False)
|
| 468 |
+
if len(non_rna):
|
| 469 |
+
auxiliary_counts[start:stop] = source[:, non_rna].toarray()
|
| 470 |
+
if not np.all(np.isfinite(source.data)) or np.any(source.data < 0):
|
| 471 |
+
raise QCError("Export source changed or failed nonnegative finite invariant")
|
| 472 |
+
numeric_total = np.asarray(source[:, rna].sum(axis=1)).ravel()
|
| 473 |
+
if not np.allclose(numeric_total, cell_total[start:stop], rtol=1e-10, atol=1e-8):
|
| 474 |
+
raise QCError("Per-cell source mass disagrees with independent QC scan")
|
| 475 |
+
transformed = (source @ reducer).tocsr()
|
| 476 |
+
transformed.sum_duplicates()
|
| 477 |
+
transformed.eliminate_zeros()
|
| 478 |
+
transformed.sort_indices()
|
| 479 |
+
kept = np.asarray(transformed.sum(axis=1)).ravel()
|
| 480 |
+
removed = np.asarray(source[:, rna & (target < 0)].sum(axis=1)).ravel()
|
| 481 |
+
if not np.allclose(numeric_total, kept + removed, rtol=1e-10, atol=1e-8):
|
| 482 |
+
raise QCError("Canonical export mass conservation failed")
|
| 483 |
+
observed_mass += float(numeric_total.sum())
|
| 484 |
+
exported_mass += float(kept.sum())
|
| 485 |
+
excluded_mass += float(removed.sum())
|
| 486 |
+
end = cursor + transformed.nnz
|
| 487 |
+
data.resize((end,)); indices.resize((end,))
|
| 488 |
+
data[cursor:end], indices[cursor:end] = transformed.data, transformed.indices
|
| 489 |
+
indptr[start + 1:stop + 1] = transformed.indptr[1:] + cursor
|
| 490 |
+
cursor = end
|
| 491 |
+
if pseudobulk_enabled:
|
| 492 |
+
block_samples = obs.sample_id.iloc[start:stop].to_numpy()
|
| 493 |
+
block_eligible = aggregation_mask[start:stop]
|
| 494 |
+
for sample in np.unique(block_samples[block_eligible]):
|
| 495 |
+
s = sample_index[sample]
|
| 496 |
+
all_mask = (block_samples == sample) & block_eligible
|
| 497 |
+
for selection, mask in enumerate((all_mask, all_mask & qcpass[start:stop])):
|
| 498 |
+
pseudobulk[selection, s] += np.asarray(transformed[mask].sum(axis=0)).ravel()
|
| 499 |
+
sample_n[selection, s] += int(mask.sum())
|
| 500 |
+
sample_source_mass[selection, s] += float(numeric_total[mask].sum())
|
| 501 |
+
obs_columns = {column: obs[column].to_numpy() for column in obs.columns}
|
| 502 |
+
for flag in sorted((out / "metrics").glob("flag_*.npy")):
|
| 503 |
+
obs_columns[flag.stem] = np.load(flag, mmap_mode="r")
|
| 504 |
+
for metric in ("cell_total", "cell_detected", "cell_mito_percent"):
|
| 505 |
+
obs_columns[metric] = np.load(out / "metrics" / (metric + ".npy"), mmap_mode="r")
|
| 506 |
+
# Source barcodes are unique within this source matrix; library stays a column.
|
| 507 |
+
_h5_dataframe(handle, "obs", obs_columns, obs.barcode.to_numpy())
|
| 508 |
+
_h5_dataframe(handle, "var", {"gene_symbol": np.asarray([row["gene_symbol"] for row in canonical]),
|
| 509 |
+
"source_feature_present": present,
|
| 510 |
+
"harmonization_valid": harmonization_valid,
|
| 511 |
+
"source_ambiguous_candidate": ambiguous_candidate}, np.asarray([row["gene_id"] for row in canonical]))
|
| 512 |
+
for name in ("varm", "obsp", "varp", "layers", "uns"):
|
| 513 |
+
group = handle.create_group(name)
|
| 514 |
+
group.attrs["encoding-type"], group.attrs["encoding-version"] = "dict", "0.1.0"
|
| 515 |
+
if len(non_rna):
|
| 516 |
+
_h5_array(handle["uns"], "source_non_rna_feature_ids", [mapping[i]["source_id"] for i in non_rna])
|
| 517 |
+
_h5_array(handle["uns"], "source_non_rna_feature_symbols", [mapping[i]["source_symbol"] for i in non_rna])
|
| 518 |
+
source_sha = item.get("source_sha256") or sha256_file(item["path"])
|
| 519 |
+
canonical_sha = item.get("canonical_identity_sha256") or hashlib.sha256(json.dumps(
|
| 520 |
+
[{"panel_index": str(i), "gene_id": row["gene_id"], "gene_symbol": row["gene_symbol"]}
|
| 521 |
+
for i, row in enumerate(canonical)], sort_keys=True, separators=(",", ":")).encode()).hexdigest()
|
| 522 |
+
metadata = {"units": units, "source_path": str(Path(item["path"]).resolve()), "source_sha256": source_sha,
|
| 523 |
+
"source_matrix_path": str(item.get("matrix_path") or "MatrixMarket coordinate table"),
|
| 524 |
+
"canonical_identity_sha256": canonical_sha,
|
| 525 |
+
"raw_count_eligible": verified_counts,
|
| 526 |
+
"count_provenance": COUNT_SOURCE_EVIDENCE.get(item.get("accession", ""), "Source count provenance not established") if verified_counts else "Source count provenance not established; integer-valued entries alone are insufficient",
|
| 527 |
+
"source_feature_present_semantics": "True if an RNA feature in the supplied source table maps uniquely to this canonical gene before collision quarantine; not assay coverage or expression detection",
|
| 528 |
+
"harmonization_valid_semantics": "True if canonical values may be used after mapping and duplicate-collision quarantine; false values are storage zeros, not observed zero expression",
|
| 529 |
+
"source_ambiguous_candidate_semantics": "True if a source feature has this canonical gene among its unresolved ambiguous candidates; no expression assigned",
|
| 530 |
+
"missing_gene_semantics": "source_feature_present=False means absent from or unresolved in the supplied feature table, not proof of an unmeasured assay feature",
|
| 531 |
+
"duplicate_policy": "Sum only in verified count space; otherwise retain pre-quarantine presence and set harmonization_valid=False for collided targets",
|
| 532 |
+
"expression_transform": "canonical gene mapping only; source units unchanged; all original cells retained",
|
| 533 |
+
"aggregation_context_json": json.dumps(sample_contexts, sort_keys=True)}
|
| 534 |
+
for name, value in metadata.items():
|
| 535 |
+
_h5_scalar(handle["uns"], name, value)
|
| 536 |
+
handle.flush()
|
| 537 |
+
os.replace(temporary, destination)
|
| 538 |
+
if pseudobulk_enabled:
|
| 539 |
+
rows = []
|
| 540 |
+
with h5py.File(out / "pseudobulk_per_published_sample.h5", "w") as handle:
|
| 541 |
+
_h5_array(handle, "sample_id", samples)
|
| 542 |
+
_h5_array(handle, "gene_id", [row["gene_id"] for row in canonical])
|
| 543 |
+
handle["source_feature_present"] = present
|
| 544 |
+
handle["harmonization_valid"] = harmonization_valid
|
| 545 |
+
handle["all_mapped_cells_sum"] = pseudobulk[0]
|
| 546 |
+
handle["qc_review_pass_cells_sum"] = pseudobulk[1]
|
| 547 |
+
handle["n_cells"] = sample_n
|
| 548 |
+
handle["source_total_mass"] = sample_source_mass
|
| 549 |
+
handle.attrs["units"] = units
|
| 550 |
+
handle.attrs["aggregation"] = "SUM; no averaging, normalization or donor imputation"
|
| 551 |
+
for sample, i in sample_index.items():
|
| 552 |
+
context = sample_contexts[str(sample)]
|
| 553 |
+
rows.append({"sample_id": sample, **context, "n_cells": int(sample_n[0, i]),
|
| 554 |
+
"n_qc_review_pass": int(sample_n[1, i]), "all_source_mass": float(sample_source_mass[0, i]),
|
| 555 |
+
"all_canonical_mass": float(pseudobulk[0, i].sum()), "units": units})
|
| 556 |
+
pd.DataFrame(rows).to_csv(out / "pseudobulk_sample_summary.csv", index=False)
|
| 557 |
+
return {"path": str(destination), "n_canonical_genes": len(canonical), "n_present": int(present.sum()),
|
| 558 |
+
"source_iteration": item.get("source_iteration", ""),
|
| 559 |
+
"n_harmonization_valid": int(harmonization_valid.sum()), "n_ambiguous_candidates": int(ambiguous_candidate.sum()),
|
| 560 |
+
"canonical_valid_fraction": float(harmonization_valid.mean()),
|
| 561 |
+
"non_rna_auxiliary_features": len(non_rna), "non_rna_storage": "obsm/source_non_rna_counts; uns/source_non_rna_feature_ids; no cell assignment inferred" if len(non_rna) else None,
|
| 562 |
+
"canonical_coverage_fraction": float(present.mean()), "excluded_collision_features": int(collision.sum()) if not verified_counts else 0,
|
| 563 |
+
"source_selected_mass": observed_mass, "canonical_mass": exported_mass, "excluded_mass": excluded_mass,
|
| 564 |
+
"mass_conservation_pass": bool(np.isclose(observed_mass, exported_mass + excluded_mass, rtol=1e-10, atol=1e-8)),
|
| 565 |
+
"pseudobulk_enabled": pseudobulk_enabled,
|
| 566 |
+
"aggregation_population": "all cells with complete published assignment" if full_mapping else "author_retained_mapped_subset",
|
| 567 |
+
"aggregation_eligible_cells": int(aggregation_mask.sum()) if verified_counts else 0,
|
| 568 |
+
"aggregation_excluded_unassigned_cells": int((~mapped).sum()),
|
| 569 |
+
"aggregation_excluded_other_cells": int((mapped & ~aggregation_mask).sum()),
|
| 570 |
+
"pseudobulk_reason": "verified counts and exact published cell-to-sample assignment for every included cell" if pseudobulk_enabled else "requires verified count units and an explicitly assigned author-retained population"}
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def run_singlecell(root: str | Path, runroot: str | Path) -> list[dict]:
|
| 574 |
+
root, runroot = Path(root), Path(runroot)
|
| 575 |
+
mapper = GeneMapper(runroot / "reference")
|
| 576 |
+
output = runroot / "singlecell"
|
| 577 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 578 |
+
summaries = []
|
| 579 |
+
for item in discover_libraries(root, runroot):
|
| 580 |
+
accession, library = item["accession"], item["library_id"]
|
| 581 |
+
suffix = "__mtx_validation" if item["duplicate_representation"] else ""
|
| 582 |
+
out = output / accession / (library + suffix)
|
| 583 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 584 |
+
summary_path = out / "summary.json"
|
| 585 |
+
if summary_path.exists():
|
| 586 |
+
previous = json.loads(summary_path.read_text())
|
| 587 |
+
if previous.get("status") in ("PASS", "PASS_QC_EXPORT_QUARANTINED", "DUPLICATE_REPRESENTATION_VALIDATED"):
|
| 588 |
+
summaries.append(previous)
|
| 589 |
+
continue
|
| 590 |
+
summary = {**item, "status": "RUNNING", "output_dir": str(out)}
|
| 591 |
+
_write_json(summary_path, summary)
|
| 592 |
+
print(json.dumps({"stage": "singlecell", "library": library, "accession": accession, "event": "start"}), flush=True)
|
| 593 |
+
try:
|
| 594 |
+
ids, symbols, cells, rna, axes = read_axes(item)
|
| 595 |
+
item["matrix_path"] = axes["matrix_path"]
|
| 596 |
+
mapping = mapper.map_features(ids, symbols)
|
| 597 |
+
mapping_summary = mapper.write_rows(mapping, out / "gene_mapping")
|
| 598 |
+
mito = np.asarray([row["mitochondrial"] for row in mapping])
|
| 599 |
+
obs, linkage = assign_metadata(item, cells, runroot)
|
| 600 |
+
obs.to_csv(out / "cell_metadata.csv.gz", index=False, compression="gzip")
|
| 601 |
+
metrics = out / "metrics"
|
| 602 |
+
if (metrics / "qc_summary.json").exists():
|
| 603 |
+
qc = json.loads((metrics / "qc_summary.json").read_text())
|
| 604 |
+
elif item["format"] == "mtx":
|
| 605 |
+
qc = scan_mtx(item["path"], metrics, mito_mask=mito, feature_mask=rna,
|
| 606 |
+
sample_ids=obs.sample_id.where(obs.sample_id != "", "unresolved_library").to_numpy(),
|
| 607 |
+
feature_ids=ids, feature_symbols=symbols, cell_ids=cells)
|
| 608 |
+
else:
|
| 609 |
+
qc = scan_h5(item["path"], metrics, matrix_path=axes["matrix_path"], mito_mask=mito, feature_mask=rna,
|
| 610 |
+
sample_ids=obs.sample_id.where(obs.sample_id != "", "unresolved_library").to_numpy())
|
| 611 |
+
total = np.load(metrics / "cell_total.npy", mmap_mode="r")
|
| 612 |
+
detected = np.load(metrics / "cell_detected.npy", mmap_mode="r")
|
| 613 |
+
mito_pct = np.load(metrics / "cell_mito_percent.npy", mmap_mode="r")
|
| 614 |
+
sensitivity = [{"min_genes": genes, "min_abundance": 500, "max_mito_percent": threshold,
|
| 615 |
+
"n_review_pass": int(((detected >= genes) & (total >= 500) & (mito_pct <= threshold)).sum())}
|
| 616 |
+
for genes in (100, 200, 500) for threshold in (10, 20, 30)]
|
| 617 |
+
pd.DataFrame(sensitivity).to_csv(out / "threshold_sensitivity.csv", index=False)
|
| 618 |
+
# The file/format provenance supports counts, then numeric evidence
|
| 619 |
+
# verifies it. An integer-valued arbitrary H5AD X alone is insufficient.
|
| 620 |
+
tenx_provenance = accession in COUNT_SOURCE_EVIDENCE and (axes["matrix_path"] == "matrix" or item["format"] == "mtx")
|
| 621 |
+
integral = qc["numeric"]["integer_fraction_selected_stored"] == 1
|
| 622 |
+
item["source_sha256"] = qc["input"].get("sha256", "")
|
| 623 |
+
item["canonical_identity_sha256"] = mapper.manifest.get("canonical_identity_sha256", "")
|
| 624 |
+
verified_counts = tenx_provenance and integral
|
| 625 |
+
units = "UMI_counts" if verified_counts and accession != "GSE132044" else "protocol_specific_read_or_UMI_counts" if verified_counts else "nonnegative_abundance_source_units_unproven"
|
| 626 |
+
summary.update({"published_library_id": item.get("published_library_id", library),
|
| 627 |
+
"n_cells": len(cells), "n_features": len(ids), "n_qc_review_pass": qc["flag_counts"]["conservative_review_pass"],
|
| 628 |
+
"numeric": qc["numeric"], "units": units, "count_space_verified": verified_counts,
|
| 629 |
+
"count_provenance": COUNT_SOURCE_EVIDENCE[accession] if verified_counts else "count interpretation unavailable; integer values alone insufficient",
|
| 630 |
+
"canonicalcoverage": mapping_summary, "author_map_match": linkage,
|
| 631 |
+
"source_axes": axes, "biological_interpretation": "none; file and numeric audit only"})
|
| 632 |
+
if item["duplicate_representation"]:
|
| 633 |
+
primary = output / accession / library / "metrics"
|
| 634 |
+
comparison = {name: bool(np.array_equal(np.load(metrics / (name + ".npy")), np.load(primary / (name + ".npy"))))
|
| 635 |
+
for name in ("cell_total", "cell_detected", "gene_total", "gene_detected")}
|
| 636 |
+
comparison["feature_ids"] = (metrics / "feature_ids.tsv").read_bytes() == (primary / "feature_ids.tsv").read_bytes()
|
| 637 |
+
comparison["cell_ids"] = (metrics / "cell_ids.tsv").read_bytes() == (primary / "cell_ids.tsv").read_bytes()
|
| 638 |
+
if not all(comparison.values()):
|
| 639 |
+
raise QCError(f"Alternate MTX/H5 representation differs: {comparison}")
|
| 640 |
+
summary.update(status="DUPLICATE_REPRESENTATION_VALIDATED", comparison=comparison,
|
| 641 |
+
comparison_limit="axes and exact gene/cell marginals agree; full elementwise identity not asserted")
|
| 642 |
+
else:
|
| 643 |
+
try:
|
| 644 |
+
export = canonical_export(item, out, mapping, mapper.canonical, obs, rna,
|
| 645 |
+
verified_counts=verified_counts, units=units,
|
| 646 |
+
full_mapping=linkage["full_sample_mapping"])
|
| 647 |
+
summary.update(status="PASS", canonical_export=export)
|
| 648 |
+
except QCError as error:
|
| 649 |
+
summary.update(status="PASS_QC_EXPORT_QUARANTINED", export_error=str(error))
|
| 650 |
+
except Exception as error:
|
| 651 |
+
summary.update(status="QUARANTINED", error_type=type(error).__name__, error=str(error))
|
| 652 |
+
_write_json(summary_path, summary)
|
| 653 |
+
summaries.append(summary)
|
| 654 |
+
_write_json(output / "SINGLECELL_SUMMARY.json", {"libraries": summaries, "complete": False})
|
| 655 |
+
print(json.dumps({"stage": "singlecell", "library": library, "event": "finish", "status": summary["status"]}), flush=True)
|
| 656 |
+
gc.collect()
|
| 657 |
+
_write_json(output / "SINGLECELL_SUMMARY.json", {"libraries": summaries, "complete": True})
|
| 658 |
+
return summaries
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
if __name__ == "__main__":
|
| 662 |
+
import argparse
|
| 663 |
+
parser = argparse.ArgumentParser()
|
| 664 |
+
parser.add_argument("root", type=Path)
|
| 665 |
+
parser.add_argument("runroot", type=Path)
|
| 666 |
+
args = parser.parse_args()
|
| 667 |
+
run_singlecell(args.root, args.runroot)
|
paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/cacc70e2bf7a0b8c/strict_qc_driver.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Resumable, resource-bounded orchestration for the paired PBMC audit."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import fcntl
|
| 7 |
+
import gzip
|
| 8 |
+
import hashlib
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
import shutil
|
| 13 |
+
import signal
|
| 14 |
+
import subprocess
|
| 15 |
+
import sys
|
| 16 |
+
import time
|
| 17 |
+
from datetime import datetime, timezone
|
| 18 |
+
|
| 19 |
+
from qc_core import extract_archive, sha256_file
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def now() -> str:
|
| 23 |
+
return datetime.now(timezone.utc).isoformat()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def atomic_json(path: Path, value: object) -> None:
|
| 27 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 28 |
+
temporary = path.with_suffix(path.suffix + '.tmp')
|
| 29 |
+
temporary.write_text(json.dumps(value, indent=2, default=str) + '\n')
|
| 30 |
+
os.replace(temporary, path)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Driver:
|
| 34 |
+
def __init__(self, root: Path, runroot: Path):
|
| 35 |
+
self.root, self.runroot = root.resolve(), runroot.resolve()
|
| 36 |
+
runroot.mkdir(parents=True, exist_ok=True)
|
| 37 |
+
self.state = {'state': 'running', 'started_at': now(), 'pid': os.getpid(), 'stage': None,
|
| 38 |
+
'completed_stages': [], 'errors': []}
|
| 39 |
+
|
| 40 |
+
def event(self, event: str, **values: object) -> None:
|
| 41 |
+
record = {'time': now(), 'event': event, **values}
|
| 42 |
+
with (self.runroot / 'events.jsonl').open('a') as stream:
|
| 43 |
+
stream.write(json.dumps(record, default=str) + '\n')
|
| 44 |
+
print(json.dumps(record, default=str), flush=True)
|
| 45 |
+
self.state['updated_at'] = now()
|
| 46 |
+
atomic_json(self.runroot / 'STATUS.json', self.state)
|
| 47 |
+
|
| 48 |
+
def guard(self) -> None:
|
| 49 |
+
fields = dict(line.split(':', 1) for line in Path('/proc/meminfo').read_text().splitlines())
|
| 50 |
+
available = int(fields['MemAvailable'].split()[0]) * 1024
|
| 51 |
+
if available < 22 * 1024**3:
|
| 52 |
+
raise RuntimeError('Global MemAvailable below 22 GiB; preserving partial outputs')
|
| 53 |
+
if shutil.disk_usage(self.runroot).free < 100 * 1024**3:
|
| 54 |
+
raise RuntimeError('Free disk below 100 GiB; preserving partial outputs')
|
| 55 |
+
|
| 56 |
+
def verify_sources(self) -> None:
|
| 57 |
+
manifest = json.loads((self.root / 'SOURCE_MANIFEST.json').read_text())
|
| 58 |
+
receipts = {}
|
| 59 |
+
for line in (self.root / 'manifests/download_receipts.jsonl').read_text().splitlines():
|
| 60 |
+
row = json.loads(line)
|
| 61 |
+
receipts[row['id']] = row
|
| 62 |
+
output = self.runroot / 'SOURCE_VERIFICATION.json'
|
| 63 |
+
prior = json.loads(output.read_text()) if output.exists() else {}
|
| 64 |
+
frozen = []
|
| 65 |
+
for number, item in enumerate(manifest['files'], 1):
|
| 66 |
+
self.guard()
|
| 67 |
+
path = (self.root / item['path']).resolve()
|
| 68 |
+
if not path.is_relative_to(self.root) or not path.is_file():
|
| 69 |
+
raise ValueError(f'Invalid or missing acquisition path: {path}')
|
| 70 |
+
stat = path.stat()
|
| 71 |
+
receipt = receipts[item['id']]
|
| 72 |
+
if stat.st_size != item['expected_bytes']:
|
| 73 |
+
raise ValueError(f'Source size changed: {path}')
|
| 74 |
+
previous = next((r for r in prior.get('files', []) if r['id'] == item['id']), None)
|
| 75 |
+
if previous and previous['mtime_ns'] == stat.st_mtime_ns and previous['sha256'] == receipt['sha256']:
|
| 76 |
+
digest = previous['sha256']
|
| 77 |
+
else:
|
| 78 |
+
digest = sha256_file(path)
|
| 79 |
+
if digest != receipt['sha256']:
|
| 80 |
+
raise ValueError(f'Source SHA256 changed: {path}')
|
| 81 |
+
frozen.append({'id': item['id'], 'path': str(path), 'bytes': stat.st_size,
|
| 82 |
+
'mtime_ns': stat.st_mtime_ns, 'sha256': digest})
|
| 83 |
+
if number % 20 == 0:
|
| 84 |
+
self.event('source_progress', files=number, total=len(manifest['files']))
|
| 85 |
+
atomic_json(output, {'verified_at': now(), 'complete': True, 'files': frozen,
|
| 86 |
+
'manifest_sha256': sha256_file(self.root / 'SOURCE_MANIFEST.json')})
|
| 87 |
+
self.event('source_verified', files=len(frozen), bytes=sum(r['bytes'] for r in frozen))
|
| 88 |
+
|
| 89 |
+
def expand_gzip(self, path: Path, destination: Path) -> None:
|
| 90 |
+
self.guard()
|
| 91 |
+
receipt_path = destination.with_suffix(destination.suffix + '.expansion.json')
|
| 92 |
+
source_hash = sha256_file(path)
|
| 93 |
+
if destination.exists():
|
| 94 |
+
if not receipt_path.exists():
|
| 95 |
+
raise ValueError(f'Expansion destination lacks provenance: {destination}')
|
| 96 |
+
previous = json.loads(receipt_path.read_text())
|
| 97 |
+
if previous['source_sha256'] != source_hash or sha256_file(destination) != previous['sha256']:
|
| 98 |
+
raise ValueError(f'Expansion output changed: {destination}')
|
| 99 |
+
return
|
| 100 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 101 |
+
temporary = destination.with_suffix(destination.suffix + '.partial')
|
| 102 |
+
digest, size = hashlib.sha256(), 0
|
| 103 |
+
with gzip.open(path, 'rb') as source, temporary.open('wb') as target:
|
| 104 |
+
for chunk in iter(lambda: source.read(4 * 1024**2), b''):
|
| 105 |
+
self.guard()
|
| 106 |
+
target.write(chunk)
|
| 107 |
+
digest.update(chunk)
|
| 108 |
+
size += len(chunk)
|
| 109 |
+
target.flush()
|
| 110 |
+
os.fsync(target.fileno())
|
| 111 |
+
os.replace(temporary, destination)
|
| 112 |
+
atomic_json(receipt_path, {'source': str(path), 'source_sha256': source_hash,
|
| 113 |
+
'path': str(destination), 'bytes': size, 'sha256': digest.hexdigest(),
|
| 114 |
+
'completed_at': now()})
|
| 115 |
+
|
| 116 |
+
def extract(self) -> None:
|
| 117 |
+
self.verify_sources()
|
| 118 |
+
reports = []
|
| 119 |
+
for dataset in sorted((self.root / 'datasets').iterdir()):
|
| 120 |
+
if not dataset.is_dir():
|
| 121 |
+
continue
|
| 122 |
+
self.guard()
|
| 123 |
+
target = self.runroot / 'extracted' / dataset.name
|
| 124 |
+
target.mkdir(parents=True, exist_ok=True)
|
| 125 |
+
for source in sorted((dataset / 'raw').glob('*')):
|
| 126 |
+
if source.name.endswith(('.tar', '.tar.gz', '.zip')):
|
| 127 |
+
destination = target / source.name.replace('.', '_')
|
| 128 |
+
self.event('archive_start', accession=dataset.name, path=str(source))
|
| 129 |
+
report = extract_archive(source, destination, disk_floor_bytes=100 * 1024**3)
|
| 130 |
+
reports.append(report)
|
| 131 |
+
self.event('archive_complete', accession=dataset.name, members=report['member_count'])
|
| 132 |
+
elif source.name.endswith('.h5ad.gz'):
|
| 133 |
+
self.event('gzip_start', accession=dataset.name, path=str(source))
|
| 134 |
+
self.expand_gzip(source, target / source.name[:-3])
|
| 135 |
+
self.event('gzip_complete', accession=dataset.name)
|
| 136 |
+
# Nested archives are common in GEO; each source receives an isolated destination.
|
| 137 |
+
seen = set()
|
| 138 |
+
for _ in range(5):
|
| 139 |
+
candidates = [f for f in target.rglob('*') if f.is_file() and
|
| 140 |
+
f.name.endswith(('.tar.gz', '.tar', '.zip.gz', '.zip')) and str(f) not in seen]
|
| 141 |
+
if not candidates:
|
| 142 |
+
break
|
| 143 |
+
for source in candidates:
|
| 144 |
+
self.guard()
|
| 145 |
+
seen.add(str(source))
|
| 146 |
+
if source.name.endswith('.zip.gz'):
|
| 147 |
+
self.expand_gzip(source, source.with_suffix(''))
|
| 148 |
+
continue
|
| 149 |
+
destination = source.parent / (source.name.replace('.', '_') + '_expanded')
|
| 150 |
+
self.event('nested_archive_start', accession=dataset.name, path=str(source))
|
| 151 |
+
report = extract_archive(source, destination, disk_floor_bytes=100 * 1024**3)
|
| 152 |
+
reports.append(report)
|
| 153 |
+
self.event('dataset_expanded', accession=dataset.name)
|
| 154 |
+
atomic_json(self.runroot / 'EXTRACTION.json', {'complete': True, 'completed_at': now(), 'archives': reports})
|
| 155 |
+
|
| 156 |
+
def run(self, stages: list[str]) -> int:
|
| 157 |
+
if subprocess.run(['systemctl', '--user', 'is-active', '--quiet', 'ml-memory-guard.service']).returncode:
|
| 158 |
+
raise RuntimeError('Host memory guard is not active')
|
| 159 |
+
lock = (self.runroot / 'processing.lock').open('a')
|
| 160 |
+
fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 161 |
+
try:
|
| 162 |
+
for stage in stages:
|
| 163 |
+
self.guard()
|
| 164 |
+
self.state['stage'] = stage
|
| 165 |
+
self.event('stage_start', stage=stage)
|
| 166 |
+
if stage == 'extract':
|
| 167 |
+
self.extract()
|
| 168 |
+
elif stage == 'bulk':
|
| 169 |
+
from qc_bulk import run_bulk
|
| 170 |
+
results = run_bulk(self.root, self.runroot)
|
| 171 |
+
atomic_json(self.runroot / 'BULK_RESULTS.json', results)
|
| 172 |
+
elif stage == 'singlecell':
|
| 173 |
+
from qc_singlecell import run_singlecell
|
| 174 |
+
results = run_singlecell(self.root, self.runroot)
|
| 175 |
+
atomic_json(self.runroot / 'SINGLECELL_RESULTS.json', results)
|
| 176 |
+
elif stage == 'report':
|
| 177 |
+
from qc_finalize import finalize
|
| 178 |
+
finalize(self.root, self.runroot)
|
| 179 |
+
else:
|
| 180 |
+
raise ValueError(f'Unknown stage: {stage}')
|
| 181 |
+
self.state['completed_stages'].append(stage)
|
| 182 |
+
self.event('stage_complete', stage=stage)
|
| 183 |
+
self.state['state'] = 'completed_selected_stages'
|
| 184 |
+
self.state['stage'] = None
|
| 185 |
+
self.event('run_complete', stages=stages)
|
| 186 |
+
return 0
|
| 187 |
+
except BaseException as error:
|
| 188 |
+
self.state['state'] = 'interrupted' if isinstance(error, KeyboardInterrupt) else 'failed'
|
| 189 |
+
self.state['errors'].append({'type': type(error).__name__, 'error': str(error), 'stage': self.state['stage']})
|
| 190 |
+
self.event('run_stopped', error=repr(error))
|
| 191 |
+
raise
|
| 192 |
+
finally:
|
| 193 |
+
lock.close()
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def main() -> None:
|
| 197 |
+
parser = argparse.ArgumentParser()
|
| 198 |
+
parser.add_argument('--root', type=Path, required=True)
|
| 199 |
+
parser.add_argument('--runroot', type=Path, required=True)
|
| 200 |
+
parser.add_argument('--stages', default='extract,bulk,singlecell,report')
|
| 201 |
+
args = parser.parse_args()
|
| 202 |
+
signal.signal(signal.SIGTERM, lambda *_: (_ for _ in ()).throw(KeyboardInterrupt()))
|
| 203 |
+
raise SystemExit(Driver(args.root, args.runroot).run(args.stages.split(',')))
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
if __name__ == '__main__':
|
| 207 |
+
main()
|
paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/dependency/eee279f6185909b7/qc_validate_outputs.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent bounded inspection of standardized data files and masks."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
from datetime import datetime, timezone
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import h5py
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
from qc_finalize import stage_coverage
|
| 15 |
+
|
| 16 |
+
SCAN_CHUNK_ENTRIES = 1_000_000
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def sha256(path: Path) -> str:
|
| 20 |
+
digest = hashlib.sha256()
|
| 21 |
+
with path.open('rb') as stream:
|
| 22 |
+
for block in iter(lambda: stream.read(4 * 1024**2), b''):
|
| 23 |
+
digest.update(block)
|
| 24 |
+
return digest.hexdigest()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def inspect_export(path: Path, canonical: list[str]) -> dict:
|
| 28 |
+
with h5py.File(path, 'r') as h:
|
| 29 |
+
var, obs, matrix = h['var'], h['obs'], h['X']
|
| 30 |
+
ids = var[var.attrs.get('_index', '_index')].asstr()[...].tolist()
|
| 31 |
+
if ids != canonical:
|
| 32 |
+
raise ValueError('Feature axis differs from frozen canonical identity/order')
|
| 33 |
+
if 'units' not in h['uns']:
|
| 34 |
+
raise ValueError('Units unavailable through standard AnnData uns')
|
| 35 |
+
obs_index = obs[obs.attrs.get('_index', '_index')]
|
| 36 |
+
shape = tuple(matrix.attrs['shape']) if isinstance(matrix, h5py.Group) else matrix.shape
|
| 37 |
+
if shape != (len(obs_index), len(canonical)):
|
| 38 |
+
raise ValueError('X dimensions differ from declared obs/var')
|
| 39 |
+
if isinstance(matrix, h5py.Group):
|
| 40 |
+
if matrix.attrs.get('encoding-type') != 'csr_matrix':
|
| 41 |
+
raise ValueError('Canonical sparse export must use cells-by-genes CSR')
|
| 42 |
+
for key in ['source_feature_present', 'harmonization_valid']:
|
| 43 |
+
if key not in var:
|
| 44 |
+
raise ValueError(f'Sparse var lacks {key}')
|
| 45 |
+
present, valid = var['source_feature_present'][...], var['harmonization_valid'][...]
|
| 46 |
+
if present.shape != (shape[1],) or valid.shape != (shape[1],):
|
| 47 |
+
raise ValueError('Feature mask dimensions differ from canonical gene axis')
|
| 48 |
+
if present.dtype.kind != 'b' or valid.dtype.kind != 'b' or np.any(valid & ~present):
|
| 49 |
+
raise ValueError('Feature masks are not boolean or valid is not subset of present')
|
| 50 |
+
if not all(name in matrix for name in ['data', 'indices', 'indptr']):
|
| 51 |
+
raise ValueError('CSR required vectors missing')
|
| 52 |
+
if any(matrix[name].ndim != 1 for name in ['data', 'indices', 'indptr']):
|
| 53 |
+
raise ValueError('CSR vectors must be one-dimensional')
|
| 54 |
+
if matrix['indptr'].dtype.kind not in 'iu' or matrix['indices'].dtype.kind not in 'iu':
|
| 55 |
+
raise ValueError('CSR indptr and indices must have integer dtypes')
|
| 56 |
+
if matrix['data'].dtype.kind not in 'iuf':
|
| 57 |
+
raise ValueError('CSR data must be real numeric abundance')
|
| 58 |
+
pointers = matrix['indptr'][...]
|
| 59 |
+
nnz = len(matrix['data'])
|
| 60 |
+
if len(matrix['indices']) != nnz or len(pointers) != shape[0] + 1 or pointers[0] != 0 or pointers[-1] != nnz:
|
| 61 |
+
raise ValueError('CSR vector dimensions or endpoints invalid')
|
| 62 |
+
if np.any(pointers < 0) or np.any(pointers > nnz):
|
| 63 |
+
raise ValueError('CSR indptr outside data bounds')
|
| 64 |
+
# Pairwise comparison is safe for unsigned integers; np.diff wraps.
|
| 65 |
+
if np.any(pointers[1:] < pointers[:-1]):
|
| 66 |
+
raise ValueError('CSR indptr not monotone')
|
| 67 |
+
pointers = pointers.astype(np.int64, copy=False)
|
| 68 |
+
total = 0.0
|
| 69 |
+
absolute_total = 0.0
|
| 70 |
+
previous_index = None
|
| 71 |
+
for start in range(0, nnz, SCAN_CHUNK_ENTRIES):
|
| 72 |
+
index = matrix['indices'][start:start + SCAN_CHUNK_ENTRIES]
|
| 73 |
+
values = matrix['data'][start:start + SCAN_CHUNK_ENTRIES]
|
| 74 |
+
if np.any(index < 0) or np.any(index >= shape[1]) or np.any(~valid[index]):
|
| 75 |
+
raise ValueError('Sparse expression references invalid/unmapped gene index')
|
| 76 |
+
if not np.all(np.isfinite(values)) or np.any(values < 0):
|
| 77 |
+
raise ValueError('Sparse abundance contains nonfinite/negative values')
|
| 78 |
+
first_row = int(np.searchsorted(pointers, start, side='right') - 1)
|
| 79 |
+
last_row = int(np.searchsorted(pointers, start + len(index) - 1, side='right') - 1)
|
| 80 |
+
if previous_index is not None and start != pointers[first_row] and index[0] <= previous_index:
|
| 81 |
+
raise ValueError('CSR indices are not strictly sorted/unique within a row across chunks')
|
| 82 |
+
nonincreasing = index[1:] <= index[:-1]
|
| 83 |
+
boundaries = pointers[first_row + 1:last_row + 1] - start
|
| 84 |
+
boundaries = boundaries[(boundaries > 0) & (boundaries < len(index))]
|
| 85 |
+
nonincreasing[boundaries - 1] = False
|
| 86 |
+
if np.any(nonincreasing):
|
| 87 |
+
raise ValueError('CSR indices are not strictly sorted/unique within a row')
|
| 88 |
+
previous_index = index[-1]
|
| 89 |
+
if 'raw_count_eligible' in h['uns'] and bool(h['uns/raw_count_eligible'][()]):
|
| 90 |
+
if np.any(values != np.floor(values)):
|
| 91 |
+
raise ValueError('Count-eligible sparse export contains fractional abundance')
|
| 92 |
+
total += float(np.sum(values, dtype=np.float64))
|
| 93 |
+
absolute_total += float(np.sum(np.abs(values), dtype=np.float64))
|
| 94 |
+
mask_scope = 'gene axis'
|
| 95 |
+
valid_entries = int(valid.sum())
|
| 96 |
+
else:
|
| 97 |
+
layers = h['layers']
|
| 98 |
+
for key in ['source_feature_present', 'harmonization_valid']:
|
| 99 |
+
if key not in layers or layers[key].shape != shape or layers[key].dtype.kind != 'b':
|
| 100 |
+
raise ValueError(f'Invalid dense per-sample {key} layer')
|
| 101 |
+
valid_entries, total, absolute_total = 0, 0.0, 0.0
|
| 102 |
+
for start in range(0, shape[0], 32):
|
| 103 |
+
values = matrix[start:start + 32]
|
| 104 |
+
present = layers['source_feature_present'][start:start + 32]
|
| 105 |
+
valid = layers['harmonization_valid'][start:start + 32]
|
| 106 |
+
if np.any(valid & ~present) or np.any(~np.isfinite(values[valid])):
|
| 107 |
+
raise ValueError('Dense mask subset/finite-value invariant failed')
|
| 108 |
+
if not np.all(np.isnan(values[~valid])):
|
| 109 |
+
raise ValueError('Dense unavailable/quarantined feature must remain NaN')
|
| 110 |
+
if 'raw_count_eligible' in h['uns'] and bool(h['uns/raw_count_eligible'][()]):
|
| 111 |
+
counted = values[valid]
|
| 112 |
+
if np.any(counted < 0) or np.any(counted != np.floor(counted)):
|
| 113 |
+
raise ValueError('Count-eligible dense export contains negative/fractional abundance')
|
| 114 |
+
valid_entries += int(valid.sum())
|
| 115 |
+
total += float(np.sum(values[valid], dtype=np.float64))
|
| 116 |
+
absolute_total += float(np.sum(np.abs(values[valid]), dtype=np.float64))
|
| 117 |
+
nnz, mask_scope = None, 'sample by gene'
|
| 118 |
+
return {'path': str(path), 'shape': [int(value) for value in shape], 'stored_sparse_entries': nnz,
|
| 119 |
+
'valid_mask_entries': valid_entries, 'mask_scope': mask_scope,
|
| 120 |
+
'numeric_sum_source_units': total, 'numeric_absolute_sum_source_units': absolute_total, 'bytes': path.stat().st_size,
|
| 121 |
+
'sha256': sha256(path), 'status': 'PASS'}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def validate(runroot: Path, root: Path | None = None) -> dict:
|
| 125 |
+
runroot = Path(runroot)
|
| 126 |
+
root = Path(root) if root is not None else runroot.parent.parent
|
| 127 |
+
canonical = pd.read_csv(runroot / 'reference/canonical_genes.tsv', sep='\t', dtype=str)['gene_id'].tolist()
|
| 128 |
+
def stage_records(name: str) -> list[dict]:
|
| 129 |
+
path = runroot / name
|
| 130 |
+
value = json.loads(path.read_text()) if path.is_file() else []
|
| 131 |
+
return value if isinstance(value, list) else []
|
| 132 |
+
bulk_records, sc_records = stage_records('BULK_RESULTS.json'), stage_records('SINGLECELL_RESULTS.json')
|
| 133 |
+
coverage = stage_coverage(root, runroot, bulk_records, sc_records)
|
| 134 |
+
expected_totals = {}
|
| 135 |
+
for row in sc_records:
|
| 136 |
+
export = row.get('canonical_export', {})
|
| 137 |
+
if export.get('path') and export.get('canonical_mass') is not None:
|
| 138 |
+
expected_totals[export['path']] = (float(export['canonical_mass']), 'singlecell_producer_canonical_mass')
|
| 139 |
+
for row in bulk_records:
|
| 140 |
+
if not row.get('harmonized_path'):
|
| 141 |
+
continue
|
| 142 |
+
metrics_path = Path(row['harmonized_path']).parent / 'source_gene_metrics.csv'
|
| 143 |
+
if metrics_path.exists() and row.get('nonfinite_values', 0) == 0:
|
| 144 |
+
metrics = pd.read_csv(metrics_path)
|
| 145 |
+
required = {'target_index', 'duplicate_target_quarantined', 'absolute_mass_across_samples'}
|
| 146 |
+
if required.issubset(metrics):
|
| 147 |
+
quarantined = metrics.duplicate_target_quarantined.astype(str).str.lower().isin(['true', '1'])
|
| 148 |
+
selected = (metrics.target_index >= 0) & ~quarantined
|
| 149 |
+
expected_totals[row['harmonized_path']] = (float(metrics.loc[selected, 'absolute_mass_across_samples'].sum()), 'bulk_source_feature_absolute_mass')
|
| 150 |
+
results = []
|
| 151 |
+
expected = sorted({row['path'] for row in coverage['expected_exports']})
|
| 152 |
+
for path in expected:
|
| 153 |
+
try:
|
| 154 |
+
checked = inspect_export(Path(path), canonical)
|
| 155 |
+
if path in expected_totals:
|
| 156 |
+
expected_mass, basis = expected_totals[path]
|
| 157 |
+
actual = checked['numeric_absolute_sum_source_units']
|
| 158 |
+
if not np.isclose(actual, expected_mass, rtol=1e-10, atol=1e-8):
|
| 159 |
+
raise ValueError(f'Independent exported value total differs from producer/source record: {actual} vs {expected_mass}')
|
| 160 |
+
checked.update(producer_value_total_verified=True, expected_absolute_mass=expected_mass, value_total_basis=basis)
|
| 161 |
+
else:
|
| 162 |
+
checked['producer_value_total_verified'] = False
|
| 163 |
+
results.append(checked)
|
| 164 |
+
except Exception as error:
|
| 165 |
+
results.append({'path': str(path), 'status': 'FAIL', 'error': str(error)})
|
| 166 |
+
print(json.dumps(results[-1]), flush=True)
|
| 167 |
+
coverage_failures = list(coverage['issues'])
|
| 168 |
+
if not coverage['required_exports_complete'] and not coverage_failures:
|
| 169 |
+
coverage_failures.append({'code': 'exports_incomplete_due_to_failed_or_quarantined_records',
|
| 170 |
+
'problem': 'Terminal processing includes missing/failed/quarantined required exports'})
|
| 171 |
+
report = {'checked_at': datetime.now(timezone.utc).isoformat(),
|
| 172 |
+
'scope': 'Independent file-layout, every-value/index, mask and canonical-axis audit; not biological interpretation',
|
| 173 |
+
'files': len(results), 'passed': sum(r['status'] == 'PASS' for r in results),
|
| 174 |
+
'failed': sum(r['status'] == 'FAIL' for r in results) + len(coverage_failures), 'results': results,
|
| 175 |
+
'stage_coverage': coverage, 'coverage_failures': coverage_failures,
|
| 176 |
+
'expected_export_files': len(expected),
|
| 177 |
+
'validation_pass': bool(results and all(row['status'] == 'PASS' for row in results) and not coverage_failures),
|
| 178 |
+
'auditor_sha256': sha256(Path(__file__))}
|
| 179 |
+
out = runroot / 'reports/INDEPENDENT_VALIDATION.json'
|
| 180 |
+
out.parent.mkdir(exist_ok=True)
|
| 181 |
+
out.write_text(json.dumps(report, indent=2) + '\n')
|
| 182 |
+
return report
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
if __name__ == '__main__':
|
| 186 |
+
parser = argparse.ArgumentParser()
|
| 187 |
+
parser.add_argument('runroot', type=Path)
|
| 188 |
+
parser.add_argument('--root', type=Path)
|
| 189 |
+
args = parser.parse_args()
|
| 190 |
+
result = validate(args.runroot, args.root)
|
| 191 |
+
raise SystemExit(1 if result['failed'] else 0)
|
paper-releases/pbisc-diffusion/updates/20261002T124820Z-crosscohort-liu-default/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/README.md
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Cross-cohort fine-tuning benchmark (leave-one-cohort-out), 2026-10-02
|
| 2 |
+
|
| 3 |
+
**Question.** Can the final model (f01 6k · 1× · E16), fine-tuned on paired bulk–sc data of *other* cohorts, generate
|
| 4 |
+
cells from the real bulk of a cohort it has never seen, with no pair from that cohort? Requested by the user on
|
| 5 |
+
2026-10-02; fine-tuning modes LoRA r16, LoRA r64 and full; recipe size K = 1000 and 2000. The metrics are the
|
| 6 |
+
within-cohort benchmark's (`plans/paired_finetune_intradataset_20260927`).
|
| 7 |
+
|
| 8 |
+
## Design
|
| 9 |
+
|
| 10 |
+
**Cohorts** (the within-cohort benchmark's five; same QC, identity checks, usable rows and cells):
|
| 11 |
+
|
| 12 |
+
| cohort | bulk | usable pairs | donors | role |
|
| 13 |
+
|---|---|---:|---:|---|
|
| 14 |
+
| ImMicro | PBMC | 107 | 107 | train and test |
|
| 15 |
+
| Ye 2026 sepsis | PBMC | 82 | 82 | train and test |
|
| 16 |
+
| Imperial ESKD COVID | PBMC | 157 | 57 | train and test |
|
| 17 |
+
| Giroux 2022 | PBMC | 24 | 9 | train and test |
|
| 18 |
+
| Ji 2025 ChILI | whole blood | 33 | 20 | test only |
|
| 19 |
+
|
| 20 |
+
**Splits.** Each split trains one model:
|
| 21 |
+
- **`ho_<X>`, X a PBMC cohort:** the model trains on every usable pair of the other three PBMC cohorts. It is tested on every usable pair of X.
|
| 22 |
+
- **`ho_ji2025_chili`:** the model trains on all four PBMC cohorts. This is also the candidate "pan-cohort" model to release.
|
| 23 |
+
|
| 24 |
+
Ji is not used for training. Its bulk is whole blood while its single cells are PBMC, so its pairs teach a different mapping than every other cohort's.
|
| 25 |
+
|
| 26 |
+
**Leakage.** No sample, cell, condition or calibration value of the held-out cohort is read when a split's training inputs are built. Both `prepare_loco.py` and the trainer assert this.
|
| 27 |
+
|
| 28 |
+
**Training** (`tools/ft_sdd_multi.py`). The loss, optimiser and EMA are the same as `ft_sdd.py`.
|
| 29 |
+
- **Learning rate:** LoRA 5e-4 (r16 with α 16, r64 with α 64); full fine-tune 5e-5.
|
| 30 |
+
- **Steps and early stopping:** evaluation every 250 steps, patience 8, cap 20,000 steps.
|
| 31 |
+
- **Batches are cohort-balanced.** Each cell picks a training cohort uniformly, then a pair, then a cell. Otherwise Imperial (146 training pairs) would dominate and Giroux (24) would barely count.
|
| 32 |
+
- **Inner validation:** 10 % of each training cohort's donors per group, always the same donors (ImMicro 12, sepsis 9, Imperial 5 donors / 11 rows, Giroux 0). The early-stopping loss is the mean over cohorts, so it is cohort-balanced too.
|
| 33 |
+
|
| 34 |
+
**Conditions.**
|
| 35 |
+
- **Fixed-depth real bulk at recipe size K.** Counts = CPM / 1e6 × K × 3,869.6, and `recipe_k` = K.
|
| 36 |
+
- **Same K for training and testing.** K = 1000 is the protocol so far; its arrays equal the within-cohort benchmark's byte for byte.
|
| 37 |
+
- **K = 2000 tests a different input depth.** It changes the gene features log1p(raw · K / total); the depth-per-cell scalar is unchanged.
|
| 38 |
+
|
| 39 |
+
**Arms scored per held-out cohort.** All arms score the cohort's usable samples against the same frozen reference.
|
| 40 |
+
|
| 41 |
+
| arm | target pairs used | what it is |
|
| 42 |
+
|---|---|---|
|
| 43 |
+
| `zs_K1000`, `zs_K2000` | 0 | zero-shot, real bulk |
|
| 44 |
+
| `xcal_K1000`, `xcal_K2000` | 0 | zero-shot + **cross-cohort** gene-wise calibration (α from the training cohorts' pairs, cohort-balanced). This is the control for "LOCO only learns a per-gene correction" |
|
| 45 |
+
| `loco_{lora16,lora64,full}_K{1000,2000}` | 0 | fine-tuned on the other cohorts |
|
| 46 |
+
| within-cohort `zs__cal`, `real_lora__raw`, `real_full__raw` | all (5-fold) | reference ceilings from the within-cohort benchmark (read, not rerun) |
|
| 47 |
+
|
| 48 |
+
**Metrics** (`score_ft.py`, one call per arm):
|
| 49 |
+
- composition L1 (scANVI, frozen f01common);
|
| 50 |
+
- precision / coverage (and depth-matched);
|
| 51 |
+
- pseudobulk r;
|
| 52 |
+
- disease logFC r with the bulk-broadcast baseline and partial r;
|
| 53 |
+
- top-50 DEG overlap.
|
| 54 |
+
|
| 55 |
+
Giroux's disease metrics exclude the 196 sex-linked genes, as in the deck. Composition gets a paired Wilcoxon over samples against `zs_K1000` and against the within-cohort LoRA.
|
| 56 |
+
|
| 57 |
+
## Running (both servers)
|
| 58 |
+
|
| 59 |
+
- `queues/loco_20261002.txt` has 45 units in priority order:
|
| 60 |
+
1. K = 1000 LoRA r16 for all 5 splits;
|
| 61 |
+
2. its cross-cohort calibration control;
|
| 62 |
+
3. LoRA r64 and full at K = 1000;
|
| 63 |
+
4. K = 2000 zero-shot, calibration and the three modes.
|
| 64 |
+
- **`tools/run_loco_queue.sh`** runs the same queue on both hosts. A host claims a unit (atomic `mkdir` in `claims/` on server_1) only after its GPU gate passes, so no unit runs twice.
|
| 65 |
+
- server_1 walks the queue forward and server_2 backward.
|
| 66 |
+
- server_2 copies finished runs and outputs back to the same absolute paths on server_1.
|
| 67 |
+
- A failed unit is marked FAILED and not retried; two failures in a row stop the queue.
|
| 68 |
+
- Every GPU step goes through `ml-run`. On server_1 it alternates on the shared lock with the scSemiProfiler CV queue.
|
| 69 |
+
- **`tools/score_pending.sh`** (`loco-score-s1`, server_1, CPU) scores each arm as soon as it exists. A failed call leaves `<out>.FAILED` and is not retried.
|
| 70 |
+
- **`tools/aggregate_loco.py`** writes `scores/AGGREGATE.md` and `scores/aggregate.csv`.
|
| 71 |
+
|
| 72 |
+
Units: `loco-queue-s1` and `loco-score-s1` on server_1, `loco-queue-s2` on server_2. Started 2026-10-02 20:35 KST. server_2 waits at its gate while another user's vLLM occupies its GPU (96 %, 91 GB).
|
| 73 |
+
|
| 74 |
+
**GPU time (estimate):**
|
| 75 |
+
- A training run takes ~16 min at the 20k cap (LoRA, ~21 steps/s) and somewhat more for full fine-tuning.
|
| 76 |
+
- Sampling one split's test set takes 2–11 min.
|
| 77 |
+
- Total ≈ 12 GPU h: 30 fine-tunes ≈ 8 h, 45 sampling sets ≈ 4 h.
|
| 78 |
+
- On server_1 alone, sharing the lock with the scSemiProfiler CV queue, expect about 1–1.5 days.
|
| 79 |
+
|
| 80 |
+
## Update 2026-10-02 21:45: Liu 2021 is in every training pool (user decision)
|
| 81 |
+
|
| 82 |
+
**What changed.** The user asked to add Liu 2021 (GSE161918) as a training-only cohort, to stop all training, and to make Liu the default. The first queue (`queues/loco_20261002.txt`, splits `ho_*`) was stopped at 21:30. Its 3 finished units (K = 1000, LoRA r16, held out Giroux / Ji / sepsis) are kept as a no-Liu reference. The ImMicro unit had trained for a few seconds; it is marked `STOPPED` and has no checkpoint.
|
| 83 |
+
|
| 84 |
+
**Liu 2021.**
|
| 85 |
+
- Built by `processing/liu2021_v1_20261002/` → `plans/paired_finetune_intradataset_20260927/data/liu2021/`, using the same QC bundle, gene axis and identity checks as the other cohorts. See its `QC_REPORT.md`.
|
| 86 |
+
- **Bulk is PBMC:** unsorted PBMC, TruSeq, htseq.
|
| 87 |
+
- **Single cells:** unsorted fraction only; hashtag and demuxlet singlets.
|
| 88 |
+
- **Size:** 65 pairs, 44 subjects; 58 usable rows from 41 subjects.
|
| 89 |
+
- Never a test cohort: its single cells are in the pretraining corpus.
|
| 90 |
+
|
| 91 |
+
**Training exclusion** (`tools/prepare_loco_extra.py`, `EXCLUDE`, read from the processing run's `hto_negative_sensitivity.csv`).
|
| 92 |
+
- Rule: 14 rows lost > 30 % of their unsorted cells to hashtag-negative calls (weak pools B2 HTO3 and B3 HTO5); they are not trained on.
|
| 93 |
+
- Why: negatives carry about 20 points fewer classical monocytes, so these rows' retained cells over-represent monocytes against the all-cell bulk.
|
| 94 |
+
- Liu's pool is 44 rows from 37 donors: 40 training rows plus 4 inner-validation donors.
|
| 95 |
+
|
| 96 |
+
**Splits `hoL_<X>`.** Each is `ho_<X>`'s pool plus Liu. Test samples and test files are unchanged. The cross-cohort calibration is refitted on the enlarged pool.
|
| 97 |
+
|
| 98 |
+
| split | training rows | inner-val rows | test |
|
| 99 |
+
|---|---:|---:|---:|
|
| 100 |
+
| hoL_immicro | 283 | 24 | 107 |
|
| 101 |
+
| hoL_ye2026_sepsis | 305 | 27 | 82 |
|
| 102 |
+
| hoL_imperial_eskd | 232 | 25 | 157 |
|
| 103 |
+
| hoL_giroux2022 | 354 | 36 | 24 |
|
| 104 |
+
| hoL_ji2025_chili | 378 | 36 | 33 |
|
| 105 |
+
|
| 106 |
+
**Queue.** `queues/loco_liu_20261002.txt` has 45 units in the same order as before. It was launched at 21:45 on server_1 (forward) and server_2 (backward, waiting at its gate). Arms are scored as `locoL_<tag>_K<K>` and `xcalL_K<K>`.
|
| 107 |
+
|
| 108 |
+
**No-Liu reference so far** (K = 1000, LoRA r16; `scores/AGGREGATE.md`):
|
| 109 |
+
|
| 110 |
+
| held out | coverage, zs → LOCO (within-cohort LoRA) | comp. L1, zs → LOCO (within) | logFC r, zs → LOCO (within) |
|
| 111 |
+
|---|---|---|---|
|
| 112 |
+
| Giroux | 0.29 → 0.81 (0.93) | 0.337 → 0.347, p 0.83 (0.258) | 0.34 → 0.30 (0.46) |
|
| 113 |
+
| Sepsis | 0.07 → 0.29 (0.83) | 0.509 → 0.538, p 0.18 (0.362) | −0.02 → 0.09 (0.53) |
|
| 114 |
+
| Ji | 0.06 → 0.31 (0.86) | 0.725 → 0.494, p 6e-4 (0.504) | 0.07 → 0.09 (0.48) |
|
| 115 |
+
|
| 116 |
+
Pairs from other cohorts recover part of the cell realism. In Ji they also fix composition, as much as Ji's own pairs. They barely move the disease signal, which so far needs the cohort's own pairs.
|
| 117 |
+
|
| 118 |
+
## Files
|
| 119 |
+
|
| 120 |
+
- `tools/prepare_loco.py` → `data/<cohort>/`, `splits/`, `PREPARE.json` (CPU; run 2026-10-02 20:31, all checks true)
|
| 121 |
+
- `tools/ft_sdd_multi.py`: trainer (CPU smoke and 20-step GPU smoke passed)
|
| 122 |
+
- `runs/<split>/K<K>/<tag>/` (RUN.json, history.json with per-cohort inner-val loss, checkpoint)
|
| 123 |
+
- `generated/<cohort>/{zs_K2000.npz, <split>/xcal_K<K>.npz, <split>/K<K>_<tag>.npz}` + receipts
|
| 124 |
+
- `scores/<cohort>/<arm>/`, `scores_nosex/giroux2022/<arm>/`
|