junidude14 commited on
Commit
a9e2a20
·
verified ·
1 Parent(s): 17c4392

Archive 4 checkpoints (1-4)

Browse files
paper-releases/20260928/diffusion/data/source_prep/ji2025_chili/code/strict_qc_v1_code_bundle_v5/qc_genes.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Frozen model-axis gene mapping; never transforms or aggregates expression.
3
+
4
+ Only identity membership is established. An absent feature is missing, not a
5
+ measured zero. Presence in a supplied feature table is not proof that the
6
+ experiment assayed an all-zero feature (some pipelines export padded tables).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ from collections import Counter, defaultdict
12
+ import csv
13
+ from datetime import datetime, timezone
14
+ import gzip
15
+ import hashlib
16
+ import json
17
+ from pathlib import Path
18
+ import re
19
+ import shutil
20
+ from typing import Sequence
21
+
22
+ BASE = Path(__file__).resolve().parents[1]
23
+ DEFAULT_REFERENCE = BASE / "processing/strict_qc_v1_20260913/reference"
24
+ PBISC = Path("/home/sj_server_1/PBISC/immun-pbmc-fm")
25
+ CONTRACT = PBISC / "B048_test/shared/contracts/b048_baseline.json"
26
+ PARENT_REFERENCE = BASE.parent / "reference"
27
+ ENSEMBL_PATTERN = re.compile(r"^(ENSG\d{11})(?:\.(\d+))?(_PAR_Y)?$")
28
+
29
+
30
+ def sha256(path: Path) -> str:
31
+ digest = hashlib.sha256()
32
+ with path.open("rb") as handle:
33
+ for block in iter(lambda: handle.read(1024 * 1024), b""):
34
+ digest.update(block)
35
+ return digest.hexdigest()
36
+
37
+
38
+ def read_tsv(path: Path) -> list[dict[str, str]]:
39
+ opener = gzip.open if path.suffix == ".gz" else open
40
+ with opener(path, "rt", encoding="utf-8-sig", newline="") as handle:
41
+ return list(csv.DictReader(handle, delimiter="\t"))
42
+
43
+
44
+ def write_tsv(path: Path, rows: Sequence[dict], fields: Sequence[str]) -> None:
45
+ path.parent.mkdir(parents=True, exist_ok=True)
46
+ with path.open("w", encoding="utf-8", newline="") as handle:
47
+ writer = csv.DictWriter(handle, fieldnames=fields, delimiter="\t", extrasaction="ignore")
48
+ writer.writeheader()
49
+ writer.writerows(rows)
50
+
51
+
52
+ def clean_token(value: object) -> str:
53
+ if value is None:
54
+ return ""
55
+ if isinstance(value, bytes):
56
+ value = value.decode("utf-8", errors="strict")
57
+ text = str(value).strip()
58
+ return "" if text in {"", "nan", "None", "<NA>"} else text
59
+
60
+
61
+ def stable_ensembl(value: str) -> tuple[str, bool, bool]:
62
+ """Strip ONLY a numeric gene version. Preserve the locus-bearing PAR suffix."""
63
+ match = ENSEMBL_PATTERN.fullmatch(value)
64
+ if not match:
65
+ return value, False, False
66
+ return match[1] + (match[3] or ""), bool(match[2]), bool(match[3])
67
+
68
+
69
+ def split_hgnc(value: str) -> list[str]:
70
+ return [x.strip().strip('"') for x in value.split("|") if x.strip().strip('"')]
71
+
72
+
73
+ class GeneMapper:
74
+ """Map features to the exact frozen B048 panel with per-row audit evidence.
75
+
76
+ target_index == -1 means excluded/unresolved. Mapped conflicting Ensembl
77
+ IDs retain their authoritative target and set symbol_conflict=True.
78
+ Duplicate rows are never collapsed here; target_multiplicity makes later
79
+ count-only aggregation or a refusal an explicit caller decision.
80
+ """
81
+
82
+ def __init__(self, reference_dir: Path | str = DEFAULT_REFERENCE):
83
+ self.reference_dir = Path(reference_dir)
84
+ manifest_path = self.reference_dir / "REFERENCE_MANIFEST.json"
85
+ self.manifest = json.loads(manifest_path.read_text())
86
+ for item in self.manifest["frozen_files"]:
87
+ path = self.reference_dir / item["frozen_name"]
88
+ if sha256(path) != item["sha256"]:
89
+ raise ValueError(f"Frozen gene reference hash mismatch: {path}")
90
+ self._initialize(
91
+ read_tsv(self.reference_dir / "canonical_genes.tsv"),
92
+ read_tsv(self.reference_dir / "ensembl109_genes.tsv.gz"),
93
+ read_tsv(self.reference_dir / "hgnc_complete_set_frozen.tsv"),
94
+ read_tsv(self.reference_dir / "hgnc_withdrawn_frozen.tsv"),
95
+ )
96
+ if len(self.canonical) != self.manifest["canonical_gene_count"]:
97
+ raise ValueError("Canonical gene count differs from reference manifest")
98
+
99
+ @classmethod
100
+ def from_records(cls, canonical: Sequence[dict], ensembl: Sequence[dict] = (),
101
+ hgnc: Sequence[dict] = (), withdrawn: Sequence[dict] = ()) -> "GeneMapper":
102
+ """Small in-memory constructor for focused identity tests only."""
103
+ mapper = cls.__new__(cls)
104
+ mapper.reference_dir = None
105
+ mapper.manifest = {"canonical_gene_count": len(canonical)}
106
+ mapper._initialize(canonical, ensembl, hgnc, withdrawn)
107
+ return mapper
108
+
109
+ def _initialize(self, canonical: Sequence[dict], ensembl: Sequence[dict],
110
+ hgnc: Sequence[dict], withdrawn: Sequence[dict]) -> None:
111
+ self.canonical = sorted((dict(r) for r in canonical), key=lambda r: int(r["panel_index"]))
112
+ self.canonical_size = len(self.canonical)
113
+ indexes = [int(r["panel_index"]) for r in self.canonical]
114
+ if indexes != list(range(len(indexes))):
115
+ raise ValueError("Canonical panel indices must be contiguous and zero based")
116
+ self.by_id = {r["gene_id"]: r for r in self.canonical}
117
+ if len(self.by_id) != len(self.canonical):
118
+ raise ValueError("Duplicate canonical stable Ensembl gene IDs")
119
+ if any(r.get("gene_biotype") != "protein_coding" for r in self.canonical):
120
+ raise ValueError("Canonical model axis must contain only protein_coding genes")
121
+ self.info: dict[str, dict] = {}
122
+ self.canonical_symbols: dict[str, set[str]] = defaultdict(set)
123
+ self.approved_symbols: dict[str, set[str]] = defaultdict(set)
124
+ self.ensembl_symbols: dict[str, set[str]] = defaultdict(set)
125
+ self.previous_symbols: dict[str, set[str]] = defaultdict(set)
126
+ self.alias_symbols: dict[str, set[str]] = defaultdict(set)
127
+ self.withdrawn_symbols = {r.get("WITHDRAWN_SYMBOL", r.get("symbol", "")) for r in withdrawn}
128
+ self.withdrawn_symbols.discard("")
129
+ for r in ensembl:
130
+ gid = r["ensembl_gene_id"]
131
+ self.info[gid] = {"gene_id": gid, "gene_symbol": r.get("gene_name", ""),
132
+ "chromosome": r.get("seqname", ""), "gene_biotype": r.get("gene_biotype", "")}
133
+ if r.get("gene_name"):
134
+ self.ensembl_symbols[r["gene_name"]].add(gid)
135
+ for r in self.canonical:
136
+ self.info[r["gene_id"]] = r # Canonical release takes precedence for annotation.
137
+ if r.get("gene_symbol"):
138
+ self.canonical_symbols[r["gene_symbol"]].add(r["gene_id"])
139
+ for r in hgnc:
140
+ symbol = r.get("symbol", "")
141
+ if r.get("status") != "Approved":
142
+ if symbol:
143
+ self.withdrawn_symbols.add(symbol)
144
+ continue
145
+ genes = {stable_ensembl(g)[0] for g in split_hgnc(r.get("ensembl_gene_id", ""))
146
+ if ENSEMBL_PATTERN.fullmatch(g)}
147
+ if not genes:
148
+ genes = set(self.canonical_symbols.get(symbol, set()))
149
+ if not genes:
150
+ genes = {r.get("hgnc_id", "HGNC_UNMAPPED:" + symbol)}
151
+ self.approved_symbols[symbol].update(genes)
152
+ for gid in genes:
153
+ if gid not in self.info:
154
+ self.info[gid] = {"gene_id": gid, "gene_symbol": symbol,
155
+ "chromosome": "MT" if r.get("location") == "mitochondria" else "",
156
+ "gene_biotype": "protein_coding" if r.get("locus_group") == "protein-coding gene" else r.get("locus_type", "")}
157
+ if "Cytoplasmic ribosomal proteins" in r.get("gene_group", ""):
158
+ self.info[gid]["hgnc_cytoplasmic_ribosomal"] = True
159
+ for previous in split_hgnc(r.get("prev_symbol", "")):
160
+ self.previous_symbols[previous].update(genes)
161
+ for alias in split_hgnc(r.get("alias_symbol", "")):
162
+ self.alias_symbols[alias].update(genes)
163
+
164
+ def _symbol(self, symbol: str) -> tuple[set[str], str, list[str]]:
165
+ if not symbol:
166
+ return set(), "empty_symbol", []
167
+ # Multiple GENCODE loci must remain ambiguous even if older HGNC stores
168
+ # just one locus (notably the distinct X/Y PAR loci in GENCODE v49).
169
+ canonical = self.canonical_symbols.get(symbol, set())
170
+ approved = self.approved_symbols.get(symbol, set())
171
+ exact = canonical | approved
172
+ if exact:
173
+ method = "canonical_symbol" if canonical else "approved_symbol"
174
+ other = (self.previous_symbols.get(symbol, set()) | self.alias_symbols.get(symbol, set())) - exact
175
+ warnings = ["exact_symbol_also_alias_of:" + ",".join(sorted(other))] if other else []
176
+ return exact, method, warnings
177
+ if symbol in self.withdrawn_symbols:
178
+ return set(), "withdrawn_symbol", []
179
+ previous = self.previous_symbols.get(symbol, set())
180
+ aliases = self.alias_symbols.get(symbol, set())
181
+ if previous or aliases:
182
+ return previous | aliases, "previous_symbol" if previous else "alias_symbol", []
183
+ # Ensembl109 is used for all-feature QC annotation, not unchecked
184
+ # historical symbol-to-model reassignment.
185
+ legacy = self.ensembl_symbols.get(symbol, set())
186
+ if legacy:
187
+ return legacy, "ensembl109_symbol_annotation_only", []
188
+ return set(), "unmapped_symbol", []
189
+
190
+ def map_features(self, ids: Sequence[object], symbols: Sequence[object] | None = None) -> list[dict]:
191
+ if symbols is not None and len(ids) != len(symbols):
192
+ raise ValueError("Feature IDs and symbols differ in length")
193
+ rows: list[dict] = []
194
+ for index, value in enumerate(ids):
195
+ raw = clean_token(value)
196
+ supplied_symbol = clean_token(symbols[index]) if symbols is not None else ""
197
+ stable, version_stripped, par_y = stable_ensembl(raw)
198
+ ensembl = bool(ENSEMBL_PATTERN.fullmatch(raw))
199
+ evidence: list[str] = []
200
+ target = -1
201
+ conflict = False
202
+ candidates: set[str] = set()
203
+ gid = stable if ensembl else ""
204
+ if ensembl:
205
+ evidence.append("numeric_version_stripped" if version_stripped else "unversioned_ensembl")
206
+ if par_y:
207
+ status = "excluded_par_y_identity"
208
+ evidence.append("PAR_Y_preserved;assembly_crosswalk_required;never_collapse_to_X")
209
+ elif stable in self.by_id:
210
+ target = int(self.by_id[stable]["panel_index"])
211
+ status = "mapped_ensembl"
212
+ evidence.append("exact_canonical_stable_id")
213
+ elif stable in self.info:
214
+ status = "excluded_outside_canonical"
215
+ evidence.append("known_stable_id_absent_from_model_axis;no_symbol_rescue")
216
+ else:
217
+ status = "unknown_ensembl_id"
218
+ evidence.append("unknown_stable_id;no_symbol_rescue")
219
+ if supplied_symbol:
220
+ symbol_ids, method, warning = self._symbol(supplied_symbol)
221
+ evidence += warning
222
+ candidates = symbol_ids
223
+ if symbol_ids and stable not in symbol_ids:
224
+ conflict = True
225
+ evidence.append("source_id_symbol_conflict:" + ",".join(sorted(symbol_ids)))
226
+ if target >= 0:
227
+ status = "mapped_ensembl_symbol_conflict"
228
+ elif len(symbol_ids) > 1:
229
+ evidence.append("source_symbol_ambiguous_but_authoritative_id_retained")
230
+ elif not symbol_ids:
231
+ evidence.append("source_symbol_unresolved:" + method)
232
+ else:
233
+ symbol = supplied_symbol or raw
234
+ candidates, method, warnings = self._symbol(symbol)
235
+ evidence = [method] + warnings
236
+ if raw and supplied_symbol and raw != supplied_symbol:
237
+ id_candidates, _, _ = self._symbol(raw)
238
+ if id_candidates and candidates and id_candidates != candidates:
239
+ conflict = True
240
+ candidates |= id_candidates
241
+ evidence.append("two_symbol_columns_conflict;reject_union")
242
+ if len(candidates) > 1:
243
+ status = "ambiguous_symbol"
244
+ elif not candidates:
245
+ status = "excluded_withdrawn_symbol" if method == "withdrawn_symbol" else "unmapped_symbol"
246
+ else:
247
+ gid = next(iter(candidates))
248
+ if method == "ensembl109_symbol_annotation_only":
249
+ status = "excluded_legacy_symbol_annotation_only"
250
+ elif gid in self.by_id:
251
+ target = int(self.by_id[gid]["panel_index"])
252
+ status = "mapped_" + method
253
+ else:
254
+ status = "excluded_outside_canonical"
255
+ info = self.info.get(gid, {})
256
+ chromosome = str(info.get("chromosome", ""))
257
+ resolved_symbol = str(info.get("gene_symbol", ""))
258
+ mito = chromosome in {"M", "MT", "chrM", "chrMT"}
259
+ ribo = bool(info.get("hgnc_cytoplasmic_ribosomal", False)) or (
260
+ info.get("gene_biotype") == "protein_coding"
261
+ and bool(re.fullmatch(r"RP[SL](?:\d+[A-Z]*|[AP]\d*)", resolved_symbol))
262
+ )
263
+ rows.append({"source_index": index, "source_id": raw, "source_symbol": supplied_symbol,
264
+ "stable_id": stable if ensembl else gid, "target_index": target,
265
+ "target_gene_id": self.canonical[target]["gene_id"] if target >= 0 else "",
266
+ "target_gene_symbol": self.canonical[target]["gene_symbol"] if target >= 0 else "",
267
+ "status": status, "evidence": ";".join(evidence),
268
+ "candidate_ids": "|".join(sorted(candidates)),
269
+ "version_stripped": version_stripped, "par_y_suffix": par_y,
270
+ "symbol_conflict": conflict, "resolved_symbol": resolved_symbol,
271
+ "chromosome": chromosome, "source_biotype": info.get("gene_biotype", ""),
272
+ "mitochondrial": mito, "ribosomal": ribo,
273
+ "qc_annotation_resolved": bool(info)})
274
+ id_counts = Counter(r["source_id"] for r in rows if r["source_id"])
275
+ stable_counts = Counter(r["stable_id"] for r in rows if r["stable_id"])
276
+ target_counts = Counter(r["target_index"] for r in rows if r["target_index"] >= 0)
277
+ for row in rows:
278
+ row["source_id_multiplicity"] = id_counts.get(row["source_id"], 0)
279
+ row["stable_id_multiplicity"] = stable_counts.get(row["stable_id"], 0)
280
+ row["target_multiplicity"] = target_counts.get(row["target_index"], 0)
281
+ return rows
282
+
283
+ def summarize(self, rows: Sequence[dict]) -> dict:
284
+ targets = Counter(r["target_index"] for r in rows if r["target_index"] >= 0)
285
+ return {"schema": "strict_gene_mapping_summary_v1", "source_features": len(rows),
286
+ "canonical_genes": len(self.canonical), "mapped_source_features": sum(targets.values()),
287
+ "unique_canonical_features_present": len(targets),
288
+ "canonical_coverage_fraction": len(targets) / len(self.canonical) if self.canonical else 0,
289
+ "canonical_features_absent": len(self.canonical) - len(targets),
290
+ "ambiguous_features": sum(r["status"] == "ambiguous_symbol" for r in rows),
291
+ "unmapped_or_excluded_features": sum(r["target_index"] < 0 for r in rows),
292
+ "version_stripped_features": sum(r["version_stripped"] for r in rows),
293
+ "source_id_symbol_conflicts": sum(r["symbol_conflict"] for r in rows),
294
+ "duplicate_source_id_rows": sum(r["source_id_multiplicity"] > 1 for r in rows),
295
+ "duplicate_target_groups": sum(n > 1 for n in targets.values()),
296
+ "duplicate_target_rows": sum(n for n in targets.values() if n > 1),
297
+ "mitochondrial_features_source_axis": sum(r["mitochondrial"] for r in rows),
298
+ "ribosomal_features_source_axis": sum(r["ribosomal"] for r in rows),
299
+ "source_qc_annotation_unresolved_features": sum(not r["qc_annotation_resolved"] for r in rows),
300
+ "status_counts": dict(sorted(Counter(r["status"] for r in rows).items())),
301
+ "presence_mask_semantics": "source_feature_table_membership;not_detection_or_proof_of_assay_coverage",
302
+ "absent_feature_policy": "masked_missing;never_observed_zero",
303
+ "duplicate_policy": "flag_only;no_expression_aggregation_performed",
304
+ "expression_transformation": "none",
305
+ "canonical_file_sha256": self.manifest.get("canonical_panel_file_sha256"),
306
+ "canonical_identity_sha256": self.manifest.get("canonical_identity_sha256")}
307
+
308
+ def write_mapping(self, ids: Sequence[object], symbols: Sequence[object] | None = None,
309
+ output_prefix: Path | str | None = None) -> dict:
310
+ if output_prefix is None:
311
+ raise ValueError("output_prefix is required")
312
+ rows = self.map_features(ids, symbols)
313
+ return self.write_rows(rows, output_prefix)
314
+
315
+ def write_rows(self, rows: Sequence[dict], output_prefix: Path | str) -> dict:
316
+ prefix = str(output_prefix)
317
+ fields = list(rows[0]) if rows else ["source_index", "source_id", "target_index", "status", "evidence"]
318
+ write_tsv(Path(prefix + ".mapping.tsv"), rows, fields)
319
+ summary = self.summarize(rows)
320
+ Path(prefix + ".summary.json").write_text(json.dumps(summary, indent=2) + "\n")
321
+ targets = Counter(r["target_index"] for r in rows if r["target_index"] >= 0)
322
+ mask = [{"panel_index": i, "gene_id": r["gene_id"], "gene_symbol": r["gene_symbol"],
323
+ "source_feature_present": i in targets, "source_rows_mapped": targets.get(i, 0),
324
+ "missing_semantics": "" if i in targets else "not_in_supplied_feature_table;do_not_treat_as_observed_zero"}
325
+ for i, r in enumerate(self.canonical)]
326
+ write_tsv(Path(prefix + ".presence_mask.tsv"), mask,
327
+ ["panel_index", "gene_id", "gene_symbol", "source_feature_present", "source_rows_mapped", "missing_semantics"])
328
+ return summary
329
+
330
+
331
+ def freeze_reference(reference_dir: Path | str = DEFAULT_REFERENCE) -> dict:
332
+ """Freeze existing validated artifacts; no network or reference upgrade."""
333
+ import pandas as pd # Only needed once to read the 755 KB canonical parquet.
334
+
335
+ destination = Path(reference_dir)
336
+ destination.mkdir(parents=True, exist_ok=True)
337
+ contract = json.loads(CONTRACT.read_text())
338
+ panel_path = Path(contract["gene_panel_path"])
339
+ panel_hash = sha256(panel_path)
340
+ if panel_hash != contract["gene_panel_file_sha256"]:
341
+ raise ValueError("Canonical model panel differs from frozen B048 contract")
342
+ panel = pd.read_parquet(panel_path)
343
+ columns = ["gene_id", "gene_symbol", "panel_index"]
344
+ records = [{column: str(row[column]) for column in columns} for _, row in panel.iterrows()]
345
+ identity_hash = hashlib.sha256(json.dumps(records, ensure_ascii=False, sort_keys=True,
346
+ separators=(",", ":")).encode()).hexdigest()
347
+ if identity_hash != contract["gene_order_sha256"]:
348
+ raise ValueError("Ordered model identity hash differs from frozen B048 contract")
349
+ if len(panel) != 20097 or not panel.gene_id.is_unique or set(panel.gene_biotype) != {"protein_coding"}:
350
+ raise ValueError("Canonical model-axis cardinality, uniqueness, or biotype check failed")
351
+ if panel.panel_index.tolist() != list(range(20097)):
352
+ raise ValueError("Canonical parquet row order differs from its panel_index")
353
+ files = [(panel_path, "canonical_var.parquet"), (CONTRACT, "b048_baseline_contract.json"),
354
+ (PBISC / "model/vae_bulk2sc/method_1/src/method1/gene_alignment.py", "model_gene_alignment_hash_source.py"),
355
+ (BASE / "README.md", "datalake_readme_at_reference_freeze.md"),
356
+ (PARENT_REFERENCE / "ensembl/ensembl109_genes.tsv.gz", "ensembl109_genes.tsv.gz"),
357
+ (PARENT_REFERENCE / "ensembl/ensembl109_panel_stats.json", "ensembl109_panel_stats.json"),
358
+ (PARENT_REFERENCE / "hgnc/hgnc_complete_set_frozen.tsv", "hgnc_complete_set_frozen.tsv"),
359
+ (PARENT_REFERENCE / "hgnc/hgnc_withdrawn_frozen.tsv", "hgnc_withdrawn_frozen.tsv")]
360
+ frozen_files = []
361
+ for source, name in files:
362
+ target = destination / name
363
+ digest = sha256(source)
364
+ if target.exists() and sha256(target) != digest:
365
+ raise ValueError(f"Refusing to overwrite changed frozen reference: {target}")
366
+ if not target.exists():
367
+ shutil.copy2(source, target)
368
+ frozen_files.append({"source_path": str(source), "source_resolved_path": str(source.resolve()),
369
+ "frozen_name": name, "sha256": digest, "bytes": source.stat().st_size})
370
+ canonical_path = destination / "canonical_genes.tsv"
371
+ panel["target_index"] = panel["panel_index"]
372
+ canonical_columns = ["target_index", "panel_index", "gene_id", "gene_symbol", "gene_biotype", "chromosome", "start", "end"]
373
+ canonical_text = panel[canonical_columns].to_csv(sep="\t", index=False)
374
+ if canonical_path.exists() and canonical_path.read_text() != canonical_text:
375
+ raise ValueError("Refusing to overwrite changed canonical TSV")
376
+ canonical_path.write_text(canonical_text)
377
+ frozen_files.append({"source_path": str(panel_path), "frozen_name": canonical_path.name,
378
+ "sha256": sha256(canonical_path), "bytes": canonical_path.stat().st_size,
379
+ "derivation": "ordered identity/annotation columns from hash-verified canonical parquet"})
380
+ reference109 = read_tsv(destination / "ensembl109_genes.tsv.gz")
381
+ old_pc = {r["ensembl_gene_id"] for r in reference109 if r["gene_biotype"] == "protein_coding"}
382
+ canonical_ids = set(panel.gene_id)
383
+ duplicate_symbols = panel[panel.gene_symbol.duplicated(False)][canonical_columns].to_dict("records")
384
+ write_tsv(destination / "canonical_ambiguous_symbols.tsv", duplicate_symbols, canonical_columns)
385
+ compatibility = {
386
+ "canonical_genes": len(canonical_ids), "ensembl109_protein_coding_genes_all_contigs": len(old_pc),
387
+ "intersection": len(canonical_ids & old_pc), "canonical_only": len(canonical_ids - old_pc),
388
+ "ensembl109_pc_only": len(old_pc - canonical_ids),
389
+ "canonical_duplicated_symbol_groups": len({r["gene_symbol"] for r in duplicate_symbols}),
390
+ "canonical_duplicated_symbol_genes": len(duplicate_symbols),
391
+ "canonical_only_ids": sorted(canonical_ids - old_pc), "ensembl109_pc_only_ids": sorted(old_pc - canonical_ids),
392
+ "decision": "model_axis_unchanged;Ensembl109_and_HGNC_are_auxiliary_annotation_only;no_reference_upgrade"}
393
+ (destination / "COMPATIBILITY_AUDIT.json").write_text(json.dumps(compatibility, indent=2) + "\n")
394
+ manifest = {"schema": "strict_qc_gene_reference_v1", "created_at_utc": datetime.now(timezone.utc).isoformat(),
395
+ "canonical_label": "PBISC B048 GENCODE v49 protein_coding model panel",
396
+ "canonical_gene_count": len(panel), "canonical_panel_file_sha256": panel_hash,
397
+ "canonical_identity_sha256": identity_hash,
398
+ "identity_hash_serialization": "ordered {gene_id,gene_symbol,panel_index} string records;json ensure_ascii=False sort_keys=True separators=(',',':')",
399
+ "label_provenance": "local datalake README and PBISC model contract;original full GENCODE49 GTF not re-downloaded",
400
+ "auxiliary_hgnc_snapshot": "existing local frozen 2023 snapshot;not asserted current",
401
+ "frozen_files": frozen_files, "compatibility_audit": "COMPATIBILITY_AUDIT.json"}
402
+ manifest_path = destination / "REFERENCE_MANIFEST.json"
403
+ if manifest_path.exists():
404
+ previous = json.loads(manifest_path.read_text())
405
+ if previous["frozen_files"] != frozen_files:
406
+ raise ValueError("Frozen reference manifest differs; create a new version instead")
407
+ return previous
408
+ manifest_path.write_text(json.dumps(manifest, indent=2) + "\n")
409
+ return manifest
410
+
411
+
412
+ def main() -> None:
413
+ parser = argparse.ArgumentParser(description=__doc__)
414
+ parser.add_argument("--reference-dir", type=Path, default=DEFAULT_REFERENCE)
415
+ parser.add_argument("--freeze", action="store_true")
416
+ parser.add_argument("--input-tsv", type=Path)
417
+ parser.add_argument("--id-column", default="gene_id")
418
+ parser.add_argument("--symbol-column")
419
+ parser.add_argument("--output-prefix", type=Path)
420
+ args = parser.parse_args()
421
+ if args.freeze:
422
+ print(json.dumps(freeze_reference(args.reference_dir), indent=2))
423
+ if args.input_tsv:
424
+ if not args.output_prefix:
425
+ parser.error("--output-prefix required with --input-tsv")
426
+ mapper = GeneMapper(args.reference_dir)
427
+ records = read_tsv(args.input_tsv)
428
+ ids = [r[args.id_column] for r in records]
429
+ symbols = [r[args.symbol_column] for r in records] if args.symbol_column else None
430
+ print(json.dumps(mapper.write_mapping(ids, symbols, args.output_prefix), indent=2))
431
+
432
+
433
+ if __name__ == "__main__":
434
+ main()
paper-releases/20260928/diffusion/data/source_prep/ji2025_chili/code/strict_qc_v1_code_bundle_v5/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/20260928/diffusion/data/source_prep/ji2025_chili/code/strict_qc_v1_code_bundle_v5/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/20260928/diffusion/data/source_prep/ji2025_chili/code/strict_qc_v1_code_bundle_v5/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()