junidude14 commited on
Commit
26e5759
·
verified ·
1 Parent(s): 9b7684d

Archive 4 checkpoints (1-4)

Browse files
paper-releases/20260928/diffusion/data/source_prep/giroux2022/code/giroux2022_pipeline.py ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Giroux et al., Sci Rep 2022 (Duke outpatient COVID-19) PBMC bulk (GSE206263) + scRNA (GSE206283) processing.
3
+
4
+ CPU only; never imports torch or initializes CUDA.
5
+
6
+ Reuses the frozen ImMicro strict-QC code bundle v5 VERBATIM (copied to code/strict_qc_v1_code_bundle_v5,
7
+ sha256 verified against its MANIFEST), exactly as the Ye 2026 build did:
8
+ * qc_core.extract_archive / scan_mtx (safe extraction, streaming MTX audit, cell flags:
9
+ min_genes 200, min_counts 500, max mito 20 %, 5-MAD outliers)
10
+ * qc_genes.GeneMapper (frozen 20,097-gene GENCODE v49 axis; symbol / ID mapping with
11
+ ambiguity and conflict quarantine)
12
+ * qc_singlecell.read_axes / canonical_export (canonical sparse H5AD, measured-gene masks,
13
+ per-sample SUM pseudobulk of all / review-pass cells)
14
+ * qc_bulk.from_assembled-style BulkInput + harmonize (bulk canonical matrix, NaN + masks)
15
+ Only study-specific glue (GEO title parsing, the author count-table column names, per-library obs) is new.
16
+
17
+ Subcommands: sources | extract | pairing | bulk | sc
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import csv
23
+ import gzip
24
+ import json
25
+ import re
26
+ import sys
27
+ import time
28
+ from collections import defaultdict
29
+ from concurrent.futures import ProcessPoolExecutor, as_completed
30
+ from datetime import datetime, timezone
31
+ from pathlib import Path
32
+
33
+ import numpy as np
34
+ import pandas as pd
35
+
36
+ DATALAKE = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc")
37
+ RAW = {"GSE206263": DATALAKE / "datasets/GSE206263", "GSE206283": DATALAKE / "datasets/GSE206283"}
38
+ RUN = DATALAKE / "processing/giroux2022_v1_20260928"
39
+ BUNDLE = RUN / "code/strict_qc_v1_code_bundle_v5" # verbatim copy of strict_qc_v1_20260913/code_bundle_v5
40
+ REFERENCE = DATALAKE / "processing/strict_qc_v1_20260913/reference" # frozen; read only, sha-verified by GeneMapper
41
+ RECEIPTS = DATALAKE / "acquisition/20260927/manifests/download_receipts.jsonl"
42
+ BULK_TABLE = RUN / "extracted/GSE206263/bulk_RNA-seq_all_counts.csv"
43
+ BULK_META = RUN / "extracted/GSE206263/bulk_RNA-seq_sample_metadata.tsv"
44
+ sys.path.insert(0, str(BUNDLE))
45
+
46
+ import qc_core # noqa: E402
47
+ import qc_genes # noqa: E402
48
+
49
+ GROUP_CODES = {"Mild": "mild", "Severe": "severe", "Exposed": "exposed", "Healthy": "healthy"}
50
+ SEX_GENES = {"XIST": "ENSG00000229807", "RPS4Y1": "ENSG00000129824", "DDX3Y": "ENSG00000067048",
51
+ "UTY": "ENSG00000183878", "KDM5D": "ENSG00000012817"}
52
+ META_FIELDS = ["ch_age", "ch_Sex", "ch_exposure", "ch_serostatus"]
53
+ COUNT_EVIDENCE = ("Published per-GSM 10x Cell Ranger 3.1.0 filtered_feature_bc_matrix (matrix/features/barcodes, "
54
+ "refdata hg19 32,738 genes); GEO: 10x Genomics Single Cell 5' v1, Cell Ranger count")
55
+
56
+
57
+ def now() -> str:
58
+ return datetime.now(timezone.utc).isoformat()
59
+
60
+
61
+ def log(event: dict) -> None:
62
+ event = {"t": now(), **event}
63
+ line = json.dumps(event, default=str)
64
+ print(line, flush=True)
65
+ with open(RUN / "events.jsonl", "a") as handle:
66
+ handle.write(line + "\n")
67
+
68
+
69
+ def sha256(path: Path) -> str:
70
+ return qc_core.sha256_file(path)
71
+
72
+
73
+ def verify_bundle() -> dict:
74
+ manifest = json.loads((BUNDLE / "MANIFEST.json").read_text())
75
+ for name, digest in manifest["files"].items():
76
+ if sha256(BUNDLE / name) != digest:
77
+ raise RuntimeError(f"Code bundle file changed: {name}")
78
+ return manifest
79
+
80
+
81
+ # ----------------------------------------------------------------- sources
82
+ def receipts() -> dict:
83
+ out = {}
84
+ for line in open(RECEIPTS):
85
+ rec = json.loads(line)
86
+ out[rec["local_path"]] = rec
87
+ return out
88
+
89
+
90
+ def cmd_sources(_args) -> None:
91
+ """sha256 every acquired Giroux file used here and compare with the acquisition receipt."""
92
+ verify_bundle()
93
+ known = receipts()
94
+ records = []
95
+ for acc, base in RAW.items():
96
+ for path in sorted(list((base / "raw").glob("*")) + list((base / "metadata").glob("*"))):
97
+ if not path.is_file() or path.name.endswith((".partial", ".tmp")):
98
+ continue
99
+ rec = {"accession": acc, "path": str(path), "bytes": path.stat().st_size, "sha256": sha256(path)}
100
+ receipt = known.get(str(path))
101
+ rec["acquisition_receipt"] = bool(receipt)
102
+ if receipt:
103
+ rec.update(url=receipt["url"], receipt_sha256=receipt["sha256"], receipt_bytes=receipt["bytes"],
104
+ receipt_completed_at=receipt["completed_at"],
105
+ matches_receipt=(receipt["sha256"] == rec["sha256"] and receipt["bytes"] == rec["bytes"]))
106
+ if not rec["matches_receipt"]:
107
+ raise RuntimeError(f"Acquired file differs from its receipt: {path}")
108
+ records.append(rec)
109
+ urls = json.loads((RUN / "external_metadata/URLS.json").read_text())["files"]
110
+ external = [{"path": str(RUN / "external_metadata" / name), "url": url,
111
+ "bytes": (RUN / "external_metadata" / name).stat().st_size,
112
+ "sha256": sha256(RUN / "external_metadata" / name)} for name, url in sorted(urls.items())]
113
+ qc_core._write_json(RUN / "SOURCES.json", {"created_at_utc": now(), "files": records,
114
+ "external_metadata_fetched_20260928": external,
115
+ "acquisition": "paired-datasets-20260927 acquisition (read only; not modified)",
116
+ "receipts": str(RECEIPTS)})
117
+ log({"stage": "sources", "n_files": len(records), "n_external": len(external),
118
+ "unreceipted": [r["path"] for r in records if not r["acquisition_receipt"]]})
119
+
120
+
121
+ # ----------------------------------------------------------------- extract
122
+ def cmd_extract(_args) -> None:
123
+ known = receipts()
124
+ # bulk: small tar.gz with one CSV count table and one TSV sample sheet
125
+ tgz = RAW["GSE206263"] / "raw/GSE206263_bulkRNA_processed.tar.gz"
126
+ rec = known[str(tgz)]
127
+ if tgz.stat().st_size != rec["bytes"] or sha256(tgz) != rec["sha256"]:
128
+ raise RuntimeError(f"Archive differs from acquisition receipt: {tgz}")
129
+ r = qc_core.extract_archive(tgz, RUN / "extracted/GSE206263", RUN / "extracted/GSE206263.extraction_receipt.json",
130
+ disk_floor_bytes=50 * 1024**3)
131
+ log({"stage": "extract", "accession": "GSE206263", "members": r["member_count"], "complete": r["complete"]})
132
+ # scRNA: outer tar of 41 per-GSM tar.gz, each holding one filtered_feature_bc_matrix directory
133
+ tar = RAW["GSE206283"] / "raw/GSE206283_RAW.tar"
134
+ rec = known[str(tar)]
135
+ if tar.stat().st_size != rec["bytes"] or sha256(tar) != rec["sha256"]:
136
+ raise RuntimeError(f"Tar differs from acquisition receipt: {tar}")
137
+ outer_dir = RUN / "extracted/GSE206283_outer"
138
+ outer = qc_core.extract_archive(tar, outer_dir, RUN / "extracted/GSE206283_outer.extraction_receipt.json",
139
+ disk_floor_bytes=50 * 1024**3)
140
+ inner_receipts = {}
141
+ for name in sorted(outer["files"]):
142
+ m = re.fullmatch(r"(GSM\d+)_scRNA_(.+)_filtered_feature_bc_matrix\.tar\.gz", name)
143
+ if not m:
144
+ raise RuntimeError(f"Unexpected outer member: {name}")
145
+ dest = RUN / "extracted/GSE206283" / m.group(1)
146
+ inner = qc_core.extract_archive(outer_dir / name, dest, dest / ".extraction_receipt.json",
147
+ disk_floor_bytes=50 * 1024**3)
148
+ inner_receipts[name] = {"gsm": m.group(1), "author_library": m.group(2), "dest": str(dest),
149
+ "members": sorted(inner["files"]), "complete": inner["complete"],
150
+ "inner_archive_sha256": outer["files"][name]["sha256"]}
151
+ # The per-GSM tar.gz copies are redundant with the read-only original tar (sha256 kept in both receipts).
152
+ for name in outer["files"]:
153
+ (outer_dir / name).unlink()
154
+ qc_core._write_json(RUN / "extracted/GSE206283.inner_extraction.json",
155
+ {"created_at_utc": now(), "outer_receipt": str(RUN / "extracted/GSE206283_outer.extraction_receipt.json"),
156
+ "inner": inner_receipts,
157
+ "note": "outer members (per-GSM tar.gz) were deleted after their verified inner extraction; "
158
+ "their sha256 remain in the outer receipt and the original tar is unchanged"})
159
+ log({"stage": "extract", "accession": "GSE206283", "libraries": len(inner_receipts),
160
+ "complete": all(v["complete"] for v in inner_receipts.values())})
161
+
162
+
163
+ # ----------------------------------------------------------------- pairing
164
+ def parse_soft(path: Path) -> pd.DataFrame:
165
+ samples, cur, section = [], None, None
166
+ with gzip.open(path, "rt", encoding="utf-8") as fh:
167
+ for line in fh:
168
+ line = line.rstrip("\n")
169
+ if line.startswith("^"):
170
+ section = line[1:].split(" = ")[0]
171
+ if section == "SAMPLE":
172
+ cur = defaultdict(list)
173
+ cur["gsm"] = [line.split(" = ")[1]]
174
+ samples.append(cur)
175
+ continue
176
+ if section != "SAMPLE" or not line.startswith("!") or " = " not in line:
177
+ continue
178
+ key, val = line[1:].split(" = ", 1)
179
+ if key == "Sample_characteristics_ch1" and ": " in val:
180
+ k, v = val.split(": ", 1)
181
+ cur["ch_" + k.strip()].append(v.strip())
182
+ else:
183
+ cur[key].append(val)
184
+ return pd.DataFrame([{k: "|".join(v) for k, v in s.items()} for s in samples]).fillna("")
185
+
186
+
187
+ TITLE = re.compile(r"^([0-9A-F]{6}), (\d+|NA), (Mild|Severe|Exposed|Healthy), (Negative|Positive|Exposed|Healthy)$")
188
+
189
+
190
+ def parse_title(frame: pd.DataFrame, suffix: str = "") -> pd.DataFrame:
191
+ t = frame.Sample_title.str.removesuffix(suffix)
192
+ parts = t.str.extract(TITLE)
193
+ if parts.isna().any().any():
194
+ raise RuntimeError(f"Unexpected GEO title format: {t[parts.isna().any(axis=1)].tolist()}")
195
+ frame = frame.copy()
196
+ frame["subject"], frame["day"], frame["title_group"], frame["title_serostatus"] = parts[0], parts[1], parts[2], parts[3]
197
+ # every title field must equal its characteristics field
198
+ bad = frame[(frame.day != frame.ch_time) | (frame.title_group != frame.ch_exposure) |
199
+ (frame.title_serostatus != frame.ch_serostatus)]
200
+ if len(bad):
201
+ raise RuntimeError(f"Title differs from characteristics: {bad.gsm.tolist()}")
202
+ return frame
203
+
204
+
205
+ def sample_key(subject: str, day: str) -> str:
206
+ return f"{subject}_d{day}"
207
+
208
+
209
+ def read_bulk_header() -> list[str]:
210
+ with open(BULK_TABLE, newline="") as handle:
211
+ header = next(csv.reader(handle))
212
+ if len(set(header)) != len(header) or any(not h.strip() for h in header):
213
+ raise RuntimeError("Bulk count-table header has duplicate or empty sample names")
214
+ return header
215
+
216
+
217
+ def cmd_pairing(_args) -> None:
218
+ out = RUN / "pairing"
219
+ out.mkdir(parents=True, exist_ok=True)
220
+ bulk = parse_title(parse_soft(RAW["GSE206263"] / "metadata/GSE206263_family.soft.gz"))
221
+ sc = parse_title(parse_soft(RAW["GSE206283"] / "metadata/GSE206283_family.soft.gz"), " [scRNA-Seq]")
222
+ bulk.to_csv(out / "GSE206263_samples.csv", index=False)
223
+ sc.to_csv(out / "GSE206283_samples.csv", index=False)
224
+ if not (sc.ch_library == sc.subject).all():
225
+ raise RuntimeError("sc 'library' characteristic differs from the title subject")
226
+ sc["matrix_archive"] = sc.Sample_supplementary_file_1.str.extract(r"/(GSM\d+_scRNA_[^/]+_filtered_feature_bc_matrix\.tar\.gz)$")[0]
227
+ sc["author_library"] = sc.matrix_archive.str.extract(r"^GSM\d+_scRNA_(.+)_filtered_feature_bc_matrix\.tar\.gz$")[0]
228
+ if sc.author_library.isna().any():
229
+ raise RuntimeError("sc GSM without a filtered_feature_bc_matrix archive")
230
+ # author library names are '<internal no>-<day>' for infected/exposed subjects and '<no>' for healthy
231
+ lib_day = sc.author_library.str.extract(r"^\d+-(\d+)$")[0].fillna("NA")
232
+ if not (lib_day == sc.day).all():
233
+ raise RuntimeError("sc author library day suffix differs from GEO time")
234
+ for name, frame in (("bulk", bulk), ("sc", sc)):
235
+ frame["sample_id"] = [sample_key(s, d) for s, d in zip(frame.subject, frame.day)]
236
+ if not frame.sample_id.is_unique:
237
+ raise RuntimeError(f"Duplicate {name} subject-day keys")
238
+ # author count-table columns: '<subject>-<day>' (infected) or '<subject>' (healthy)
239
+ header = read_bulk_header()
240
+ cols = pd.DataFrame({"bulk_column": header})
241
+ parsed = cols.bulk_column.str.extract(r"^([0-9A-F]{6})(?:-(\d+))?$")
242
+ if parsed[0].isna().any():
243
+ raise RuntimeError(f"Unparsed bulk column names: {cols.bulk_column[parsed[0].isna()].tolist()}")
244
+ cols["subject"], cols["day"] = parsed[0], parsed[1].fillna("NA")
245
+ cols["sample_id"] = [sample_key(s, d) for s, d in zip(cols.subject, cols.day)]
246
+ author_meta = pd.read_csv(BULK_META, sep="\t", dtype=str, keep_default_na=False)
247
+ cols = cols.merge(author_meta.rename(columns={"SampleID": "subject", "Cohort": "author_cohort"})[
248
+ ["subject", "author_cohort", "IgG_Negative_Day", "IgG_Positive_Day"]], on="subject", how="left")
249
+ by_key = dict(zip(bulk.sample_id, bulk.gsm))
250
+ cols["bulk_gsm"] = cols.sample_id.map(by_key)
251
+ cols["column_to_gsm"] = np.where(cols.bulk_gsm.notna(), "exact_subject_day", "no_GEO_bulk_GSM_with_this_subject_day")
252
+ cols.to_csv(out / "bulk_count_columns.csv", index=False)
253
+ col_by_gsm = dict(zip(cols.bulk_gsm.dropna(), cols.bulk_column[cols.bulk_gsm.notna()]))
254
+ bulk["bulk_count_column"] = bulk.gsm.map(col_by_gsm).fillna("")
255
+ bulk["group"] = bulk.ch_exposure.map(GROUP_CODES)
256
+
257
+ brow = bulk.set_index("sample_id")
258
+ rows = []
259
+ for _, g in sc.iterrows():
260
+ rec = {"sc_gsm": g.gsm, "sc_title": g.Sample_title, "sample_id": g.sample_id, "subject": g.subject,
261
+ "day": g.day, "group": GROUP_CODES[g.ch_exposure], "author_library": g.author_library,
262
+ "sc_age": g.ch_age, "sc_sex": g.ch_Sex, "sc_serostatus": g.ch_serostatus}
263
+ if g.sample_id in brow.index:
264
+ b = brow.loc[g.sample_id]
265
+ mismatch = [f for f in META_FIELDS if b[f] != g[f]]
266
+ rec.update({"bulk_gsm": b.gsm, "bulk_title": b.Sample_title, "bulk_count_column": b.bulk_count_column,
267
+ "metadata_mismatch_fields": ";".join(mismatch)})
268
+ if mismatch:
269
+ status = "geo_metadata_mismatch"
270
+ elif b.bulk_count_column:
271
+ status = "paired"
272
+ else:
273
+ status = "bulk_GSM_has_no_column_in_author_count_table"
274
+ else:
275
+ status = "no_bulk_GSM_for_this_subject_day"
276
+ other = bulk[bulk.subject == g.subject]
277
+ rec["bulk_days_for_subject"] = ",".join(other.day) if len(other) else ""
278
+ rec["pair_status"] = status
279
+ rows.append(rec)
280
+ table = pd.DataFrame(rows)
281
+ table["paired"] = table.pair_status == "paired"
282
+ table["pair_sample_id"] = np.where(table.paired, table.sample_id, "")
283
+ for c in ("bulk_gsm", "bulk_title", "bulk_count_column", "metadata_mismatch_fields", "bulk_days_for_subject"):
284
+ if c not in table:
285
+ table[c] = ""
286
+ table[c] = table[c].fillna("")
287
+ table.to_csv(out / "sc_libraries_with_bulk_match.csv", index=False)
288
+ used_cols = set(table.bulk_count_column[table.paired])
289
+ cols["paired"] = cols.bulk_column.isin(used_cols)
290
+ sc_keys = set(sc.sample_id)
291
+ cols["unpaired_reason"] = np.where(cols.paired, "",
292
+ np.where(cols.bulk_gsm.isna(), "column_name_not_a_GEO_subject_day",
293
+ np.where(cols.sample_id.isin(sc_keys), "sc_exists_but_not_accepted",
294
+ "no_sc_library_for_this_subject_day")))
295
+ cols.to_csv(out / "bulk_count_columns.csv", index=False)
296
+ bulk_no_col = bulk[bulk.bulk_count_column == ""][["gsm", "Sample_title", "sample_id", "subject", "day", "group"]]
297
+ bulk_no_col.to_csv(out / "bulk_GSM_without_count_column.csv", index=False)
298
+ cohort = cols.drop_duplicates("subject").set_index("subject").author_cohort
299
+ geo_group = bulk.drop_duplicates("subject").set_index("subject").ch_exposure
300
+ both = sorted(set(cohort.index) & set(geo_group.index))
301
+ summary = {
302
+ "bulk_gsms": len(bulk), "bulk_subjects_geo": int(bulk.subject.nunique()),
303
+ "bulk_count_table_columns": len(cols), "bulk_count_table_subjects": int(cols.subject.nunique()),
304
+ "bulk_columns_matched_to_GSM": int(cols.bulk_gsm.notna().sum()),
305
+ "bulk_columns_without_GSM": cols[cols.bulk_gsm.isna()].bulk_column.tolist(),
306
+ "bulk_GSMs_without_count_column": len(bulk_no_col),
307
+ "bulk_GSMs_without_count_column_by_group": bulk_no_col.group.value_counts().to_dict(),
308
+ "sc_gsms": len(sc), "sc_subjects": int(sc.subject.nunique()),
309
+ "geo_level_subject_day_matches": int(table.bulk_gsm.astype(bool).sum()),
310
+ "geo_level_subject_day_matches_by_group": table[table.bulk_gsm.astype(bool)].group.value_counts().to_dict(),
311
+ "geo_level_subjects": int(table[table.bulk_gsm.astype(bool)].subject.nunique()),
312
+ "pairs_total": int(table.paired.sum()), "pairs_subjects": int(table[table.paired].subject.nunique()),
313
+ "pairs_by_group": table[table.paired].group.value_counts().to_dict(),
314
+ "pairs_by_day": table[table.paired].day.value_counts().to_dict(),
315
+ "sc_by_pair_status": table.pair_status.value_counts().to_dict(),
316
+ "sc_unpaired": table[~table.paired][["sc_gsm", "sample_id", "group", "pair_status"]].to_dict("records"),
317
+ "author_cohort_vs_geo_exposure": {s: {"author_cohort": cohort[s], "geo_exposure": geo_group[s]} for s in both
318
+ if cohort[s] != geo_group[s]},
319
+ "rule": ("A pair is one sc GEX GSM and one bulk GSM with the same GEO subject ID and the same GEO sampling day "
320
+ "(title '<subject>, <day>, <group>, <serostatus>' = characteristics subject/time); both GSMs must "
321
+ "agree on GEO age, sex, exposure group and serostatus; and the bulk GSM must have a column in the "
322
+ "author featureCounts table (column '<subject>-<day>' for infected/exposed subjects, '<subject>' "
323
+ "for healthy). No expression, age-sex or row-order matching is used to create a pair."),
324
+ }
325
+ qc_core._write_json(out / "PAIRING_SUMMARY.json", summary)
326
+ log({"stage": "pairing", **{k: summary[k] for k in ("pairs_total", "pairs_subjects", "pairs_by_group",
327
+ "geo_level_subject_day_matches", "bulk_columns_without_GSM")}})
328
+
329
+
330
+ # ----------------------------------------------------------------- bulk
331
+ def read_bulk_table():
332
+ header = read_bulk_header()
333
+ ids, rows = [], []
334
+ with open(BULK_TABLE, newline="") as handle:
335
+ reader = csv.reader(handle)
336
+ next(reader)
337
+ for line_number, fields in enumerate(reader, start=2):
338
+ if len(fields) != len(header) + 1:
339
+ raise ValueError(f"Line {line_number}: expected gene symbol + {len(header)} values, got {len(fields)}")
340
+ ids.append(fields[0])
341
+ rows.append([float(x) for x in fields[1:]]) # float() raises on any non-numeric token
342
+ values = np.asarray(rows, dtype=np.float64)
343
+ if len(set(ids)) != len(ids):
344
+ raise ValueError("Duplicate gene symbols in the author count table")
345
+ return header, ids, values
346
+
347
+
348
+ def cmd_bulk(_args) -> None:
349
+ import qc_bulk
350
+ verify_bundle()
351
+ mapper = qc_genes.GeneMapper(REFERENCE)
352
+ samples, ids, values = read_bulk_table()
353
+ (RUN / "bulk").mkdir(exist_ok=True)
354
+ cols = pd.read_csv(RUN / "pairing/bulk_count_columns.csv", dtype=str, keep_default_na=False).set_index("bulk_column")
355
+ np.savez_compressed(RUN / "bulk/bulk_source_counts.npz", gene_ids=np.asarray(ids), sample_ids=np.asarray(samples),
356
+ gsm=np.asarray([cols.loc[s, "bulk_gsm"] for s in samples]), counts=values.T.copy())
357
+ meta = [{"bulk_column": s, "GSM": cols.loc[s, "bulk_gsm"], "subject": cols.loc[s, "subject"],
358
+ "day": cols.loc[s, "day"], "author_cohort": cols.loc[s, "author_cohort"],
359
+ "assigned_gene_total": float(values[:, j].sum())} for j, s in enumerate(samples)]
360
+ assay = qc_bulk.BulkInput(
361
+ "GSE206263", "GSE206263_featureCounts", "featureCounts_raw_gene_counts", ids, samples, values.T.copy(),
362
+ symbols=None, present=None, declared_raw_counts=True, sources=[BULK_TABLE, BULK_META], sample_metadata=meta,
363
+ caveats=["GEO: PBMC total RNA (Zymo Direct-zol), NuGEN Ovation SoLo RNA-Seq library kit, NovaSeq 6000, "
364
+ "SortMeRNA rRNA removal, STAR to hg19, featureCounts; strandedness option not stated.",
365
+ "Author table (bulk_RNA-seq_all_counts.csv) holds 49 of the 71 GEO bulk GSMs; genes are hg19 "
366
+ "annotation symbols (no Ensembl IDs), mapped to the canonical axis by symbol only.",
367
+ "Five healthy column names (77DA77, 22CBD6, 4F2EAD, F8FF1A, 56E219) are not GEO subject IDs and "
368
+ "column 3F05F3-14 has no GEO GSM (GEO lists 3F05F3 days 0, 7, 28); see pairing/.",
369
+ "The table header has no gene-ID column label; each data row is symbol + 49 values (checked)."],
370
+ extra={"source_format": "CSV, header = 49 sample names, rows = gene symbol + 49 integer values",
371
+ "source_gene_rows": len(ids)})
372
+ report = qc_bulk.harmonize(assay, mapper, RUN / "bulk" / assay.assay_id)
373
+ log({"stage": "bulk", "status": report["status"], "n_samples": report["n_samples"],
374
+ "raw_count_eligible": report["raw_count_eligible"], "canonical_coverage": report["canonical_coverage"],
375
+ "duplicate_target_groups_summed": report["duplicate_target_groups_summed_counts"]})
376
+
377
+
378
+ # ----------------------------------------------------------------- single cell
379
+ def library_files(gsm: str) -> dict:
380
+ base = RUN / "extracted/GSE206283" / gsm
381
+ found = {}
382
+ for kind in ("barcodes.tsv.gz", "features.tsv.gz", "matrix.mtx.gz"):
383
+ hits = sorted(base.rglob(kind))
384
+ if len(hits) != 1:
385
+ raise RuntimeError(f"{gsm}: expected one {kind}, found {len(hits)}")
386
+ found[kind.split(".")[0]] = hits[0]
387
+ return found
388
+
389
+
390
+ def process_library(row: dict) -> dict:
391
+ import qc_singlecell as qs
392
+ import scipy.io._fast_matrix_market as fmm
393
+ from scipy.io import mmread
394
+
395
+ fmm.PARALLELISM = 1 # single-threaded MTX reader (host CPU budget)
396
+
397
+ qs.COUNT_SOURCE_EVIDENCE["GSE206283"] = COUNT_EVIDENCE # provenance string only
398
+ gsm, sid = row["sc_gsm"], row["sample_id"]
399
+ out = RUN / "singlecell" / gsm
400
+ out.mkdir(parents=True, exist_ok=True)
401
+ summary_path = out / "summary.json"
402
+ if summary_path.exists() and json.loads(summary_path.read_text()).get("status") == "PASS":
403
+ return json.loads(summary_path.read_text())
404
+ files = library_files(gsm)
405
+ item = {"accession": "GSE206283", "library_id": gsm, "path": str(files["matrix"]), "format": "mtx",
406
+ "duplicate_representation": False, "features_path": str(files["features"]),
407
+ "barcodes_path": str(files["barcodes"])}
408
+ summary = {**item, "sample_id": sid, "author_library": row["author_library"], "status": "RUNNING",
409
+ "output_dir": str(out), "started": now()}
410
+ qc_core._write_json(summary_path, summary)
411
+ t0 = time.time()
412
+ try:
413
+ mapper = qc_genes.GeneMapper(REFERENCE)
414
+ ids, symbols, cells, rna, axes = qs.read_axes(item)
415
+ item["matrix_path"] = axes["matrix_path"]
416
+ mapping = mapper.map_features(ids, symbols)
417
+ mapping_summary = mapper.write_rows(mapping, out / "gene_mapping")
418
+ mito = np.asarray([r["mitochondrial"] for r in mapping])
419
+ n = len(cells)
420
+ if len(set(cells)) != n:
421
+ raise qs.QCError("Duplicate barcodes within library")
422
+ obs = pd.DataFrame({"barcode": cells, "source_barcode": cells, "raw_10x_barcode": cells,
423
+ "author_cell_id": "", "library_id": gsm, "donor_id": row["subject"], "sample_id": sid,
424
+ "visit_id": "day_" + row["day"], "author_retained": "unknown",
425
+ "mapping_basis": "one 10x library per GEO GSM; subject and day from GEO title/characteristics",
426
+ "protocol": "10x_5prime_v1"})
427
+ obs.to_csv(out / "cell_metadata.csv.gz", index=False, compression="gzip")
428
+ metrics = out / "metrics"
429
+ if (metrics / "qc_summary.json").exists():
430
+ qc = json.loads((metrics / "qc_summary.json").read_text())
431
+ else:
432
+ qc = qc_core.scan_mtx(item["path"], metrics, mito_mask=mito, feature_mask=rna,
433
+ sample_ids=obs.sample_id.to_numpy(), feature_ids=ids,
434
+ feature_symbols=symbols, cell_ids=cells)
435
+ total = np.load(metrics / "cell_total.npy")
436
+ detected = np.load(metrics / "cell_detected.npy")
437
+ mito_pct = np.load(metrics / "cell_mito_percent.npy")
438
+ pd.DataFrame([{"min_genes": g, "min_abundance": 500, "max_mito_percent": m,
439
+ "n_review_pass": int(((detected >= g) & (total >= 500) & (mito_pct <= m)).sum())}
440
+ for g in (100, 200, 500) for m in (10, 20, 30)]).to_csv(out / "threshold_sensitivity.csv", index=False)
441
+ integral = qc["numeric"]["integer_fraction_selected_stored"] == 1
442
+ item["source_sha256"] = qc["input"].get("sha256", "")
443
+ item["canonical_identity_sha256"] = mapper.manifest.get("canonical_identity_sha256", "")
444
+ verified = bool(integral)
445
+ units = "UMI_counts" if verified else "nonnegative_abundance_source_units_unproven"
446
+ export = qs.canonical_export(item, out, mapping, mapper.canonical, obs, rna,
447
+ verified_counts=verified, units=units, full_mapping=True)
448
+ # Source-axis sums (all RNA features, incl. non-protein-coding XIST) for identity checks.
449
+ qcpass = np.load(metrics / "flag_conservative_review_pass.npy")
450
+ matrix = mmread(item["path"]).tocsc()
451
+ if matrix.shape != (len(ids), n):
452
+ raise qs.QCError("MTX shape changed")
453
+ all_sum = np.asarray(matrix.sum(axis=1)).ravel()
454
+ pass_sum = np.asarray(matrix[:, np.flatnonzero(qcpass)].sum(axis=1)).ravel()
455
+ if not np.isclose(all_sum[rna].sum(), total.sum(), rtol=1e-12):
456
+ raise qs.QCError("Source-axis sum differs from QC scan")
457
+ np.savez_compressed(out / "source_axis_pseudobulk.npz", feature_ids=np.asarray(ids),
458
+ feature_symbols=np.asarray(symbols), rna=rna, all_cells_sum=all_sum,
459
+ qc_pass_sum=pass_sum, n_cells=n, n_qc_pass=int(qcpass.sum()))
460
+ where = {g: i for i, g in enumerate(ids)}
461
+ sex_rows = [where.get(g, -1) for g in SEX_GENES.values()]
462
+ per_cell = np.zeros((len(SEX_GENES), n), dtype=np.float64)
463
+ csr = matrix.tocsr()
464
+ for k, r in enumerate(sex_rows):
465
+ if r >= 0:
466
+ per_cell[k] = csr[r].toarray().ravel()
467
+ np.savez_compressed(out / "cell_sex_gene_counts.npz", genes=np.asarray(list(SEX_GENES)),
468
+ gene_ids=np.asarray(list(SEX_GENES.values())), found=np.asarray(sex_rows) >= 0,
469
+ counts=per_cell)
470
+ del matrix, csr
471
+ # Author filtering evidence (GEO: Seurat removed cells with > 5 % mito reads or > 2,500 genes).
472
+ author = {"cells": n, "mito_gt_5pct": int((mito_pct > 5).sum()), "genes_gt_2500": int((detected > 2500).sum()),
473
+ "author_rule_would_keep": int(((mito_pct <= 5) & (detected <= 2500)).sum()),
474
+ "counts_lt_500": int((total < 500).sum()), "genes_lt_200": int((detected < 200).sum()),
475
+ "min_genes": int(detected.min()), "min_total": float(total.min()),
476
+ "max_mito_pct": float(mito_pct.max()), "median_genes": float(np.median(detected)),
477
+ "median_total": float(np.median(total))}
478
+ barcodes = sorted(cells)
479
+ chemistry = {"first_sorted_barcode": barcodes[0], "barcode_suffixes": sorted({c.rsplit("-", 1)[-1] for c in cells}),
480
+ "barcode_length": sorted({len(c.split("-")[0]) for c in cells}),
481
+ "mtx_header": open_mtx_header(item["path"])}
482
+ summary.update({"status": "PASS", "n_cells": n, "n_features": len(ids),
483
+ "n_rna_features": int(rna.sum()), "n_qc_review_pass": int(qcpass.sum()),
484
+ "flag_counts": qc["flag_counts"], "numeric": qc["numeric"], "units": units,
485
+ "count_space_verified": verified, "count_provenance": COUNT_EVIDENCE,
486
+ "canonicalcoverage": mapping_summary, "canonical_export": export,
487
+ "author_prefilter_evidence": author, "chemistry_evidence": chemistry,
488
+ "features_sha256": sha256(files["features"]),
489
+ "seconds": round(time.time() - t0, 1), "finished": now()})
490
+ except Exception as error: # noqa: BLE001 - recorded, not hidden
491
+ summary.update({"status": "QUARANTINED", "error_type": type(error).__name__, "error": str(error)})
492
+ qc_core._write_json(summary_path, summary)
493
+ return summary
494
+
495
+
496
+ def open_mtx_header(path: str) -> str:
497
+ with gzip.open(path, "rt") as handle:
498
+ lines = [handle.readline().strip() for _ in range(2)]
499
+ return " | ".join(lines)
500
+
501
+
502
+ def cmd_sc(args) -> None:
503
+ verify_bundle()
504
+ table = pd.read_csv(RUN / "pairing/sc_libraries_with_bulk_match.csv", dtype=str, keep_default_na=False)
505
+ rows = table.to_dict("records")
506
+ if args.only_paired:
507
+ rows = [r for r in rows if r["paired"] == "True"]
508
+ if args.gsm:
509
+ rows = [r for r in rows if r["sc_gsm"] in set(args.gsm.split(","))]
510
+ if args.limit:
511
+ rows = rows[:args.limit]
512
+ log({"stage": "sc", "event": "start", "n_libraries": len(rows), "workers": args.workers})
513
+ done = []
514
+ with ProcessPoolExecutor(max_workers=args.workers, max_tasks_per_child=1) as pool:
515
+ futures = {pool.submit(process_library, r): r["sc_gsm"] for r in rows}
516
+ for future in as_completed(futures):
517
+ s = future.result()
518
+ done.append(s)
519
+ log({"stage": "sc", "library": futures[future], "status": s["status"], "n_cells": s.get("n_cells"),
520
+ "n_qc_review_pass": s.get("n_qc_review_pass"), "seconds": s.get("seconds"), "error": s.get("error")})
521
+ if not args.gsm and not args.limit:
522
+ qc_core._write_json(RUN / "singlecell/SINGLECELL_SUMMARY.json",
523
+ {"created_at_utc": now(), "libraries": sorted(done, key=lambda s: s["library_id"])})
524
+ log({"stage": "sc", "event": "finish", "pass": sum(s["status"] == "PASS" for s in done), "n": len(done)})
525
+
526
+
527
+ def main() -> None:
528
+ parser = argparse.ArgumentParser(description=__doc__)
529
+ sub = parser.add_subparsers(dest="cmd", required=True)
530
+ sub.add_parser("sources")
531
+ sub.add_parser("extract")
532
+ sub.add_parser("pairing")
533
+ sub.add_parser("bulk")
534
+ p = sub.add_parser("sc")
535
+ p.add_argument("--workers", type=int, default=3)
536
+ p.add_argument("--limit", type=int, default=0)
537
+ p.add_argument("--only-paired", action="store_true")
538
+ p.add_argument("--gsm", default="", help="comma-separated GSM subset")
539
+ args = parser.parse_args()
540
+ RUN.mkdir(parents=True, exist_ok=True)
541
+ {"sources": cmd_sources, "extract": cmd_extract, "pairing": cmd_pairing, "bulk": cmd_bulk, "sc": cmd_sc}[args.cmd](args)
542
+
543
+
544
+ if __name__ == "__main__":
545
+ main()
paper-releases/20260928/diffusion/data/source_prep/giroux2022/code/run_step.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Run one CPU-only pipeline step as a transient systemd user unit.
3
+ # Limits: 12 GiB memory (no swap), <= 4 CPUs, positive OOM score, no restart,
4
+ # CUDA hidden, single-threaded BLAS/OpenMP. Usage: run_step.sh <subcommand> [args]
5
+ set -euo pipefail
6
+ RUN=/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/giroux2022_v1_20260928
7
+ PY=/home/sj_server_1/miniforge3/envs/scanvi/bin/python
8
+ step="$1"
9
+ shift || true
10
+ unit="giroux2022-${step}-$(date +%H%M%S)"
11
+ systemctl --user is-active --quiet ml-memory-guard.service
12
+ case "$step" in
13
+ assemble) script=giroux2022_assemble.py ;;
14
+ findings) script=giroux2022_findings.py ;;
15
+ fullcells) script=giroux2022_full_cells.py ;;
16
+ *) script=giroux2022_pipeline.py; set -- "$step" "$@" ;;
17
+ esac
18
+ exec systemd-run --user --wait --collect --quiet --unit="$unit" --slice=app.slice \
19
+ -p MemoryHigh=10G -p MemoryMax=12G -p MemorySwapMax=0 -p CPUQuota=400% \
20
+ -p OOMPolicy=kill -p OOMScoreAdjust=500 -p Nice=10 -p IOSchedulingClass=idle \
21
+ --working-directory="$RUN" \
22
+ -E CUDA_VISIBLE_DEVICES= -E OMP_NUM_THREADS=1 -E OPENBLAS_NUM_THREADS=1 -E MKL_NUM_THREADS=1 \
23
+ -E NUMEXPR_NUM_THREADS=1 -E PYTHONDONTWRITEBYTECODE=1 -E PYTHONUNBUFFERED=1 \
24
+ -p StandardOutput="append:$RUN/logs/${step}.log" -p StandardError="append:$RUN/logs/${step}.log" \
25
+ "$PY" "$RUN/code/$script" "$@"
paper-releases/20260928/diffusion/data/source_prep/giroux2022/code/strict_qc_v1_code_bundle_v5/qc_bulk.py ADDED
@@ -0,0 +1,667 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Bulk expression file validation and lossless unit-preserving organization.
3
+
4
+ No biological inference, donor guessing, normalization, integer coercion,
5
+ inverse log transformation, or imputation is performed. Run through the root
6
+ orchestrator; this module does not start a process or initialize CUDA.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from collections import Counter, defaultdict
11
+ from dataclasses import dataclass, field
12
+ import csv
13
+ import gzip
14
+ import io
15
+ import json
16
+ from pathlib import Path
17
+ import re
18
+ from typing import Iterable
19
+
20
+ import numpy as np
21
+ import pandas as pd
22
+
23
+ from qc_genes import GeneMapper, clean_token, sha256
24
+
25
+
26
+ @dataclass
27
+ class BulkInput:
28
+ accession: str
29
+ assay_id: str
30
+ units: str
31
+ ids: list[str]
32
+ samples: list[str]
33
+ values: np.ndarray # samples x source features, float64, unchanged units
34
+ symbols: list[str] | None = None
35
+ present: np.ndarray | None = None
36
+ declared_raw_counts: bool = False
37
+ allow_negative: bool = False
38
+ sources: list[Path] = field(default_factory=list)
39
+ sample_metadata: list[dict] = field(default_factory=list)
40
+ feature_metadata: list[dict] = field(default_factory=list)
41
+ caveats: list[str] = field(default_factory=list)
42
+ extra: dict = field(default_factory=dict)
43
+
44
+
45
+ def opener(path: Path):
46
+ return gzip.open(path, "rt", encoding="utf-8-sig", newline="") if path.suffix == ".gz" else path.open("r", encoding="utf-8-sig", newline="")
47
+
48
+
49
+ def validate_original_header(fields: list[str], source: str, *, allow_first_empty: bool = True) -> list[str]:
50
+ """Refuse identity loss before pandas can rename repeated/empty headers."""
51
+ if not fields:
52
+ raise ValueError(f"Missing table header: {source}")
53
+ duplicates = [name for name, count in Counter(fields).items() if count > 1]
54
+ if duplicates:
55
+ raise ValueError(f"Duplicate original table headers in {source}: {duplicates}")
56
+ for index, name in enumerate(fields):
57
+ if not name.strip() and not (allow_first_empty and index == 0):
58
+ raise ValueError(f"Empty original sample/column header at position {index} in {source}")
59
+ return fields
60
+
61
+
62
+ def read_original_header(path: Path, sep: str = "\t", *, comment: str | None = None) -> list[str]:
63
+ with opener(path) as handle:
64
+ for row in csv.reader(handle, delimiter=sep):
65
+ if not row or (comment and row[0].startswith(comment)):
66
+ continue
67
+ return validate_original_header(row, str(path))
68
+ raise ValueError(f"No table header in {path}")
69
+
70
+
71
+ def load_table(path: Path, sep: str = "\t", **kwargs) -> pd.DataFrame:
72
+ if kwargs.get("header", "infer") is not None:
73
+ read_original_header(path, sep, comment=kwargs.get("comment"))
74
+ with opener(path) as handle:
75
+ return pd.read_csv(handle, sep=sep, keep_default_na=False, **kwargs)
76
+
77
+
78
+ def load_space_header_matrix(path: Path) -> tuple[list[str], pd.DataFrame]:
79
+ """Randolph's first line contains samples only, with no gene-ID placeholder.
80
+
81
+ Use positional dataframe columns: supplying synthetic pandas column names
82
+ could promote an extra source field to an implicit index or collide with a
83
+ real sample named 'gene_id'. Width is checked before assigning identities.
84
+ """
85
+ with opener(path) as handle:
86
+ samples = validate_original_header(handle.readline().split(), str(path), allow_first_empty=False)
87
+ frame = pd.read_csv(handle, sep=r"\s+", header=None, keep_default_na=False)
88
+ if frame.shape[1] != len(samples) + 1:
89
+ raise ValueError(f"Space-header matrix requires one gene ID plus {len(samples)} values, got {frame.shape[1]} columns: {path}")
90
+ return samples, frame
91
+
92
+
93
+ def validate_featurecounts_header(path: Path) -> list[str]:
94
+ header = read_original_header(path, comment="#")
95
+ metadata = ["Geneid", "Chr", "Start", "End", "Strand", "Length", "gene_name"]
96
+ if len(header) != 8 or header[:7] != metadata:
97
+ raise ValueError(f"featureCounts requires seven expected metadata columns and exactly one expression column; got {len(header)} columns in {path}")
98
+ return header
99
+
100
+
101
+ def numeric_values(frame: pd.DataFrame) -> np.ndarray:
102
+ # Reject arbitrary strings rather than silently coercing them to missing.
103
+ return frame.apply(pd.to_numeric, errors="raise").to_numpy(dtype=np.float64).T
104
+
105
+
106
+ def raw_file(root: Path, accession: str, glob: str) -> Path:
107
+ found = sorted((root / "datasets" / accession / "raw").glob(glob))
108
+ found = [p for p in found if not p.name.endswith(".sha256")]
109
+ if len(found) != 1:
110
+ raise ValueError(f"Expected one {accession}/{glob}, found {len(found)}")
111
+ return found[0]
112
+
113
+
114
+ def extracted_files(runroot: Path, accession: str, predicate) -> list[Path]:
115
+ files = [p for p in (runroot / "extracted" / accession).rglob("*") if p.is_file() and predicate(p.name)]
116
+ # Prefer an expanded sibling if both gzip and expanded copies are present.
117
+ by_name: dict[str, Path] = {}
118
+ for path in sorted(files):
119
+ key = path.name[:-3] if path.name.endswith(".gz") else path.name
120
+ if key in by_name and by_name[key].parent != path.parent:
121
+ raise ValueError(f"Ambiguous extracted source filename across directories: {key}")
122
+ if key not in by_name or path.suffix != ".gz":
123
+ by_name[key] = path
124
+ if not by_name:
125
+ raise FileNotFoundError(f"No extracted expression files for {accession}")
126
+ return sorted(by_name.values())
127
+
128
+
129
+ def sample_file_label(path: Path, suffix: str) -> tuple[str, str]:
130
+ name = path.name.removesuffix(".gz").removesuffix(suffix)
131
+ match = re.match(r"^(GSM\d+)_(.*)$", name)
132
+ return (match[2], match[1]) if match else (name, "")
133
+
134
+
135
+ def assemble_samples(records: Iterable[tuple[str, list[str], list[str] | None, np.ndarray, dict]]) -> tuple:
136
+ """Exact union with per-sample feature-table masks; no positional joins.
137
+
138
+ Repeated source identities get an occurrence key and remain separate rows.
139
+ The harmonizer alone decides whether count-only aggregation is allowed.
140
+ """
141
+ keys: dict[tuple[str, str, int], int] = {}
142
+ sample_names, stored, metadata = [], [], []
143
+ for sample, ids, symbols, vector, meta in records:
144
+ if sample in sample_names:
145
+ raise ValueError(f"Duplicate bulk sample label: {sample}")
146
+ vector = np.asarray(vector, dtype=np.float64)
147
+ if vector.ndim != 1 or len(ids) != len(vector):
148
+ raise ValueError(f"Feature/value dimensions differ for {sample}")
149
+ if symbols is not None and len(symbols) != len(ids):
150
+ raise ValueError(f"ID/symbol dimensions differ for {sample}")
151
+ occurrence: Counter = Counter()
152
+ indices = []
153
+ for i, gid in enumerate(ids):
154
+ symbol = symbols[i] if symbols is not None else ""
155
+ identity = (clean_token(gid), clean_token(symbol))
156
+ nth = occurrence[identity]
157
+ occurrence[identity] += 1
158
+ key = identity + (nth,)
159
+ if key not in keys:
160
+ keys[key] = len(keys)
161
+ indices.append(keys[key])
162
+ stored.append((np.asarray(indices, dtype=np.int64), vector))
163
+ sample_names.append(sample)
164
+ metadata.append(meta)
165
+ if not stored:
166
+ raise ValueError("No bulk samples parsed")
167
+ matrix = np.full((len(stored), len(keys)), np.nan, dtype=np.float64)
168
+ present = np.zeros(matrix.shape, dtype=bool)
169
+ for i, (indices, vector) in enumerate(stored):
170
+ matrix[i, indices] = vector
171
+ present[i, indices] = True
172
+ identities = list(keys)
173
+ return ([k[0] for k in identities], [k[1] for k in identities], sample_names, matrix, present, metadata)
174
+
175
+
176
+ def from_assembled(accession: str, assay_id: str, units: str, records, **kwargs) -> BulkInput:
177
+ ids, symbols, samples, values, present, metadata = assemble_samples(records)
178
+ return BulkInput(accession, assay_id, units, ids, samples, values,
179
+ symbols=symbols if any(symbols) else None, present=present,
180
+ sample_metadata=metadata, **kwargs)
181
+
182
+
183
+ def json_safe(value):
184
+ if isinstance(value, dict):
185
+ return {str(k): json_safe(v) for k, v in value.items()}
186
+ if isinstance(value, (list, tuple)):
187
+ return [json_safe(v) for v in value]
188
+ if isinstance(value, np.ndarray):
189
+ return json_safe(value.tolist())
190
+ if isinstance(value, (np.integer, np.bool_)):
191
+ return value.item()
192
+ if isinstance(value, (float, np.floating)):
193
+ return float(value) if np.isfinite(value) else None
194
+ if isinstance(value, Path):
195
+ return str(value)
196
+ return value
197
+
198
+
199
+ def write_json(path: Path, value) -> None:
200
+ path.parent.mkdir(parents=True, exist_ok=True)
201
+ path.write_text(json.dumps(json_safe(value), ensure_ascii=False, indent=2, allow_nan=False) + "\n")
202
+
203
+
204
+ def _fraction(numerator: float, denominator: float) -> float:
205
+ return float(numerator / denominator) if denominator else np.nan
206
+
207
+
208
+ def harmonize(assay: BulkInput, mapper: GeneMapper, output: Path) -> dict:
209
+ """Validate source numbers and organize them without changing their units."""
210
+ import anndata as ad
211
+
212
+ output.mkdir(parents=True, exist_ok=True)
213
+ values = np.asarray(assay.values, dtype=np.float64)
214
+ if values.shape != (len(assay.samples), len(assay.ids)):
215
+ raise ValueError(f"Bulk matrix dimensions do not match declared axes: {assay.assay_id}")
216
+ if len(set(assay.samples)) != len(assay.samples):
217
+ raise ValueError("Nonunique sample IDs are not automatically renamed")
218
+ present = np.ones(values.shape, dtype=bool) if assay.present is None else np.asarray(assay.present, dtype=bool)
219
+ if present.shape != values.shape:
220
+ raise ValueError("Presence-mask dimensions differ from expression matrix")
221
+ finite = np.isfinite(values) & present
222
+ selected = values[present]
223
+ finite_values = selected[np.isfinite(selected)]
224
+ negative = int(np.sum(finite_values < 0))
225
+ fractional = int(np.sum(finite_values != np.trunc(finite_values)))
226
+ invalid = int(selected.size - finite_values.size)
227
+ raw_eligible = bool(assay.declared_raw_counts and not negative and not fractional and not invalid)
228
+ rows = mapper.map_features(assay.ids, assay.symbols)
229
+ if assay.feature_metadata and len(assay.feature_metadata) != len(rows):
230
+ raise ValueError("Feature annotation length differs from source feature axis")
231
+ for i, row in enumerate(rows):
232
+ if assay.feature_metadata:
233
+ annotation = assay.feature_metadata[i]
234
+ row["source_annotation"] = json.dumps(annotation, ensure_ascii=False, sort_keys=True)
235
+ if annotation.get("mapping_blocker"):
236
+ row["target_index"] = -1
237
+ row["target_gene_id"] = ""
238
+ row["target_gene_symbol"] = ""
239
+ row["status"] = str(annotation["mapping_blocker"])
240
+ row["evidence"] += ";explicit_source_annotation_refusal"
241
+ mapper.write_rows(rows, output / "source_feature_mapping")
242
+ groups: dict[int, list[int]] = defaultdict(list)
243
+ for i, row in enumerate(rows):
244
+ if row["target_index"] >= 0:
245
+ groups[row["target_index"]].append(i)
246
+ n, g = len(assay.samples), mapper.canonical_size
247
+ aligned = np.full((n, g), np.nan, dtype=np.float64)
248
+ target_present = np.zeros((n, g), dtype=bool)
249
+ valid = np.zeros((n, g), dtype=bool)
250
+ duplicate_quarantine = np.zeros(values.shape[1], dtype=bool)
251
+ duplicate_count_groups = 0
252
+ for target, indices in groups.items():
253
+ member_present = present[:, indices]
254
+ target_present[:, target] = np.any(member_present, axis=1)
255
+ count_per_sample = np.sum(member_present, axis=1)
256
+ if len(indices) > 1 and not raw_eligible:
257
+ # Even if only one occurrence is exported in one sample, a shared
258
+ # axis with unresolved many-to-one normalized features is refused.
259
+ duplicate_quarantine[indices] = True
260
+ continue
261
+ ok = target_present[:, target] & np.all(finite[:, indices] | ~member_present, axis=1)
262
+ if not assay.allow_negative:
263
+ ok &= np.all((values[:, indices] >= 0) | ~member_present, axis=1)
264
+ if len(indices) == 1:
265
+ aligned[ok, target] = values[ok, indices[0]]
266
+ else:
267
+ duplicate_count_groups += int(np.any(count_per_sample > 1))
268
+ summed = np.sum(np.where(member_present, values[:, indices], 0.0), axis=1)
269
+ aligned[ok, target] = summed[ok]
270
+ valid[ok, target] = True
271
+ mapped = np.asarray([r["target_index"] >= 0 for r in rows])
272
+ ambiguous = np.asarray([r["status"] == "ambiguous_symbol" or "ambiguous" in r["status"] for r in rows])
273
+ blank = np.asarray([not r["source_id"] for r in rows])
274
+ mito = np.asarray([bool(r["mitochondrial"]) for r in rows])
275
+ ribo = np.asarray([bool(r["ribosomal"]) for r in rows])
276
+ metrics = []
277
+ for s, name in enumerate(assay.samples):
278
+ current = values[s, finite[s]]
279
+ absolute = np.where(finite[s], np.abs(values[s]), 0.0)
280
+ total_abs = float(np.sum(absolute))
281
+ rec = {"sample_id": name, "accession": assay.accession, "assay_id": assay.assay_id,
282
+ "units": assay.units, "source_features_present": int(np.sum(present[s])),
283
+ "source_values_finite": len(current), "source_values_nonfinite": int(np.sum(present[s] & ~finite[s])),
284
+ "source_values_negative": int(np.sum(current < 0)),
285
+ "source_values_fractional": int(np.sum(current != np.trunc(current))),
286
+ "source_values_zero": int(np.sum(current == 0)),
287
+ "source_values_positive": int(np.sum(current > 0)),
288
+ "source_min": float(np.min(current)) if len(current) else np.nan,
289
+ "source_max": float(np.max(current)) if len(current) else np.nan,
290
+ "source_median": float(np.median(current)) if len(current) else np.nan,
291
+ "source_sum_in_original_units": float(np.sum(current)),
292
+ "source_absolute_mass": total_abs,
293
+ "unmapped_absolute_mass": float(np.sum(absolute[~mapped])),
294
+ "unmapped_absolute_mass_fraction": _fraction(np.sum(absolute[~mapped]), total_abs),
295
+ "ambiguous_absolute_mass_fraction": _fraction(np.sum(absolute[ambiguous]), total_abs),
296
+ "blank_id_absolute_mass_fraction": _fraction(np.sum(absolute[blank]), total_abs),
297
+ "duplicate_quarantined_absolute_mass_fraction": _fraction(np.sum(absolute[duplicate_quarantine]), total_abs),
298
+ "canonical_features_present": int(np.sum(target_present[s])),
299
+ "canonical_values_valid": int(np.sum(valid[s])),
300
+ "canonical_features_absent": int(np.sum(~target_present[s])),
301
+ "canonical_present_but_quarantined": int(np.sum(target_present[s] & ~valid[s])),
302
+ "source_mitochondrial_features_present": int(np.sum(present[s] & mito)),
303
+ "source_ribosomal_features_present": int(np.sum(present[s] & ribo)),
304
+ "raw_count_eligible": raw_eligible,
305
+ "numeric_validation_pass": bool(not np.any(present[s] & ~finite[s]) and (assay.allow_negative or not np.any(current < 0)))}
306
+ if assay.sample_metadata:
307
+ for key, value in assay.sample_metadata[s].items():
308
+ rec["source_" + key] = json.dumps(value, ensure_ascii=False) if isinstance(value, (list, dict)) else value
309
+ metrics.append(rec)
310
+ pd.DataFrame(metrics).to_csv(output / "sample_metrics.csv", index=False)
311
+ feature_metrics = []
312
+ for j, row in enumerate(rows):
313
+ feature = values[finite[:, j], j]
314
+ feature_metrics.append({"source_index": j, "source_id": row["source_id"],
315
+ "source_symbol": row["source_symbol"], "status": row["status"],
316
+ "target_index": row["target_index"], "samples_feature_present": int(present[:, j].sum()),
317
+ "finite_values": len(feature), "nonfinite_values": int(np.sum(present[:, j] & ~finite[:, j])),
318
+ "positive_values": int(np.sum(feature > 0)), "zero_values": int(np.sum(feature == 0)),
319
+ "negative_values": int(np.sum(feature < 0)),
320
+ "fractional_values": int(np.sum(feature != np.trunc(feature))),
321
+ "absolute_mass_across_samples": float(np.sum(np.abs(feature))),
322
+ "duplicate_target_quarantined": bool(duplicate_quarantine[j])})
323
+ pd.DataFrame(feature_metrics).to_csv(output / "source_gene_metrics.csv", index=False)
324
+ canon = pd.DataFrame(mapper.canonical).copy()
325
+ canon.index = pd.Index(canon["gene_id"].astype(str), name="canonical_gene_id")
326
+ for column in canon.columns:
327
+ if canon[column].dtype == object:
328
+ canon[column] = canon[column].astype(str)
329
+ canon["samples_source_feature_present"] = target_present.sum(axis=0)
330
+ canon["samples_harmonization_valid"] = valid.sum(axis=0)
331
+ canon["source_rows_targeted"] = [len(groups.get(j, [])) for j in range(g)]
332
+ canon.to_csv(output / "canonical_gene_metrics.csv", index=False)
333
+ obs = pd.DataFrame(metrics).set_index("sample_id")
334
+ for column in obs.columns:
335
+ if obs[column].dtype == object:
336
+ obs[column] = obs[column].fillna("").astype(str)
337
+ organized = ad.AnnData(X=aligned, obs=obs, var=canon)
338
+ organized.layers["source_feature_present"] = target_present
339
+ organized.layers["harmonization_valid"] = valid
340
+ organized.uns["units"] = assay.units
341
+ organized.uns["expression_transform"] = "none;float64_representation;NaN_for_missing_or_quarantined"
342
+ organized.uns["presence_mask_semantics"] = "source_feature_table_membership_not_assay_coverage_or_nonzero_detection"
343
+ organized.uns["raw_count_eligible"] = raw_eligible
344
+ organized.uns["canonical_identity_sha256"] = mapper.manifest.get("canonical_identity_sha256", "fixture")
345
+ organized.uns["duplicate_policy"] = "sum_only_if_entire_assay_verified_finite_nonnegative_integer_declared_counts;otherwise_quarantine"
346
+ organized.uns["donor_pair_validation"] = "external_manifest_required;not_inferred_by_bulk_file_organization"
347
+ organized.uns["caveats_json"] = json.dumps(assay.caveats, ensure_ascii=False)
348
+ organized.write_h5ad(output / "harmonized.h5ad", compression="gzip")
349
+ sources = [{"path": str(p), "bytes": p.stat().st_size, "sha256": sha256(p)} for p in assay.sources]
350
+ status = "organized_with_explicit_masks"
351
+ if invalid or (negative and not assay.allow_negative):
352
+ status = "organized_with_numeric_quarantine"
353
+ if assay.declared_raw_counts and not raw_eligible:
354
+ status = "organized_declared_count_semantics_failed"
355
+ report = {"schema": "bulk_file_organization_v1", "assay_id": assay.assay_id,
356
+ "accession": assay.accession, "units": assay.units, "raw_count_eligible": raw_eligible,
357
+ "n_genes": len(assay.ids), "n_samples": len(assay.samples),
358
+ "canonical_genes": g, "canonical_coverage": len(groups) / g if g else 0,
359
+ "canonical_coverage_valid_min": float(np.min(valid.sum(axis=1)) / g) if g else 0,
360
+ "canonical_coverage_valid_max": float(np.max(valid.sum(axis=1)) / g) if g else 0,
361
+ "harmonized_path": str(output / "harmonized.h5ad"), "status": status,
362
+ "caveats": assay.caveats, "n_values_present": int(selected.size),
363
+ "nonfinite_values": invalid, "negative_values": negative, "fractional_values": fractional,
364
+ "integer_fraction_of_finite_values": 1 - fractional / len(finite_values) if len(finite_values) else None,
365
+ "duplicate_target_groups_summed_counts": duplicate_count_groups,
366
+ "duplicate_source_rows_quarantined": int(duplicate_quarantine.sum()),
367
+ "source_gene_mapping_summary": mapper.summarize(rows), "sources": sources,
368
+ "missing_value_policy": "NaN plus source_feature_present and harmonization_valid boolean layers",
369
+ "analysis_scope": "file_format_numeric_integrity_gene_identity_organization_only",
370
+ "pairing_status": "not_determined_by_this_module", "extra": assay.extra}
371
+ write_json(output / "REPORT.json", report)
372
+ return report
373
+
374
+
375
+ def parse_simple(root: Path, accession: str) -> list[BulkInput]:
376
+ if accession == "GSE152418":
377
+ path = raw_file(root, accession, "*RawCounts.txt.gz")
378
+ frame = load_table(path)
379
+ return [BulkInput(accession, accession + "_counts", "raw_gene_counts", frame.iloc[:, 0].astype(str).tolist(),
380
+ frame.columns[1:].tolist(), numeric_values(frame.iloc[:, 1:]), declared_raw_counts=True, sources=[path])]
381
+ if accession == "GSE198533":
382
+ path = raw_file(root, accession, "*Raw_gene_counts_matrix.csv.gz")
383
+ frame = load_table(path, sep=",")
384
+ result = []
385
+ for suffix, unit, raw in [("_count", "raw_gene_counts", True), ("_fpkm", "FPKM", False)]:
386
+ columns = [c for c in frame.columns if c.endswith(suffix)]
387
+ result.append(BulkInput(accession, accession + suffix, unit, frame.iloc[:, 0].astype(str).tolist(),
388
+ [c.removesuffix(suffix) for c in columns], numeric_values(frame[columns]),
389
+ declared_raw_counts=raw, sources=[path], caveats=["Condition/age/sex similarities do not establish donor pairing."]))
390
+ return result
391
+ if accession == "GSE162632":
392
+ result = []
393
+ for kind in ["bulk", "time_course"]:
394
+ path = raw_file(root, accession, f"{accession}_{kind}_PBMCs.*ScaledTPM.txt.gz")
395
+ samples, frame = load_space_header_matrix(path)
396
+ result.append(BulkInput(accession, accession + "_" + kind + "_ScaledTPM", "kallisto_gene_level_ScaledTPM",
397
+ frame.iloc[:, 0].astype(str).tolist(), samples, numeric_values(frame.iloc[:, 1:]), sources=[path],
398
+ caveats=["ScaledTPM is retained in its deposited units; not converted to counts.",
399
+ "Main and time-course arms remain separate."]))
400
+ return result
401
+ if accession == "GSE132044":
402
+ path = raw_file(root, accession, "*TPM_bulk.tsv.gz")
403
+ frame = load_table(path)
404
+ ids, symbols = [], []
405
+ for token in frame.iloc[:, 0].astype(str):
406
+ match = re.fullmatch(r"(ENSG\d{11}(?:\.\d+)?)_(.+)", token)
407
+ if not match:
408
+ raise ValueError(f"Unexpected Ding composite feature identity: {token}")
409
+ ids.append(match[1]); symbols.append(match[2])
410
+ samples = ["PBMC1", "PBMC2"]
411
+ return [BulkInput(accession, accession + "_PBMC_TPM", "TPM", ids, samples, numeric_values(frame[samples]), symbols=symbols,
412
+ sources=[path], caveats=["HEK293 mixtures omitted from the PBMC assay; PBMC1/PBMC2 are source labels, not independently verified donor identities."])]
413
+ if accession == "GSE246525":
414
+ path = raw_file(root, accession, "*raw_counts.csv.gz")
415
+ frame = load_table(path, sep=",")
416
+ return [BulkInput(accession, accession + "_kallisto_values", "kallisto_estimated_counts",
417
+ frame.iloc[:, 0].astype(str).tolist(), frame.columns[1:].tolist(), numeric_values(frame.iloc[:, 1:]), sources=[path],
418
+ caveats=["kallisto 0.46.1 estimated counts preserve fractional assignments; strict integer-read-count eligibility is false.",
419
+ "Blank gene-ID rows are retained in source metrics and excluded from canonical expression.",
420
+ "Generic sample labels require an external metadata crosswalk; bulk material is whole blood."])]
421
+ if accession == "GSE252990":
422
+ result = []
423
+ for kind, unit in [("count", "kallisto_estimated_counts"), ("tpm", "TPM")]:
424
+ path = raw_file(root, accession, f"*_{kind}_matrix.csv.gz")
425
+ frame = load_table(path, sep=",")
426
+ result.append(BulkInput(accession, accession + "_" + kind, unit, frame.iloc[:, 0].astype(str).tolist(),
427
+ frame.columns[1:].tolist(), numeric_values(frame.iloc[:, 1:]), sources=[path],
428
+ caveats=["Whole-blood versus PBMC material descriptions conflict; pairing/material review is separate.",
429
+ "kallisto 0.43.0 count output via sleuth_to_matrix is retained as fractional estimated counts; TPM remains separate."]))
430
+ return result
431
+ if accession == "GSE161711":
432
+ path = raw_file(root, accession, "*log2CPM_counts.txt.gz")
433
+ frame = load_table(path)
434
+ samples = [c for c in frame.columns[9:] if c.endswith("_PB_CD19")]
435
+ if not samples:
436
+ raise ValueError("No explicitly PB_CD19-labeled CLL columns")
437
+ return [BulkInput(accession, accession + "_PB_CD19_log2CPM", "log2CPM", frame.gene_id.astype(str).tolist(), samples,
438
+ numeric_values(frame[samples]), symbols=frame.gene_name.astype(str).tolist(), allow_negative=True, sources=[path],
439
+ caveats=["Sorted CD19-positive peripheral-blood cells, not whole PBMC bulk.",
440
+ "Lymph-node and mixed-cell columns omitted; negative log2CPM values are valid and remain unchanged."],
441
+ extra={"omitted_non_PB_CD19_columns": [c for c in frame.columns[9:] if c not in samples]})]
442
+ raise ValueError(f"No simple parser for {accession}")
443
+
444
+
445
+ def parse_star_file(path: Path) -> tuple[str, list[str], None, np.ndarray, dict]:
446
+ frame = load_table(path, header=None)
447
+ if frame.shape[1] != 4:
448
+ raise ValueError(f"STAR ReadsPerGene must have exactly four columns: {path}")
449
+ ids = frame.iloc[:, 0].astype(str)
450
+ counts = frame.iloc[:, 1:].apply(pd.to_numeric, errors="raise").to_numpy(dtype=np.float64)
451
+ meta_rows = ids.str.startswith("N_").to_numpy()
452
+ if not {"N_unmapped", "N_multimapping", "N_noFeature", "N_ambiguous"}.issubset(set(ids[meta_rows])):
453
+ raise ValueError(f"Missing STAR summary rows: {path}")
454
+ gene_counts = counts[~meta_rows]
455
+ totals = np.sum(gene_counts, axis=0)
456
+ sample, gsm = sample_file_label(path, "_ReadsPerGene.out.tab")
457
+ names = ["unstranded", "forward", "reverse"]
458
+ meta = {"GSM": gsm, "file": str(path), "selected_STAR_column_one_based": 3,
459
+ "strand_selection": "forward;retained_alternatives_in_original_ReadsPerGene_file",
460
+ "gene_counts_total_unstranded": float(totals[0]),
461
+ "gene_counts_total_forward": float(totals[1]),
462
+ "gene_counts_total_reverse": float(totals[2]),
463
+ "forward_fraction_of_stranded_assigned_counts": _fraction(totals[1], totals[1] + totals[2]),
464
+ "strand_selection_requires_review": bool(totals[1] + totals[2] == 0 or totals[1] / (totals[1] + totals[2]) < 0.8)}
465
+ for gid, row in zip(ids[meta_rows], counts[meta_rows]):
466
+ for name, count in zip(names, row):
467
+ meta[f"STAR_{gid}_{name}"] = float(count)
468
+ return sample, ids[~meta_rows].tolist(), None, gene_counts[:, 1], meta
469
+
470
+
471
+ def parse_star(runroot: Path) -> BulkInput:
472
+ accession = "GSE314922"
473
+ paths = extracted_files(runroot, accession, lambda n: n.removesuffix(".gz").endswith("_ReadsPerGene.out.tab"))
474
+ return from_assembled(accession, accession + "_STAR_forward_counts", "STAR_forward_raw_gene_counts",
475
+ (parse_star_file(path) for path in paths), declared_raw_counts=True, sources=paths,
476
+ caveats=["STAR column 3 (one based; first-read strand aligned with RNA) selected; unstranded and reverse columns are never summed.",
477
+ "Tecan Universal Plus mRNA-Seq with NuQuant protocol is recorded in GEO. Per-sample forward fractions below 0.8 trigger review flags, not data correction.",
478
+ "Original genotype VCF files remain outside expression matrices."],
479
+ extra={"source_format": "STAR_ReadsPerGene_4_columns", "strand_review_threshold": 0.8})
480
+
481
+
482
+ def parse_two_column(path: Path) -> tuple[str, list[str], None, np.ndarray, dict]:
483
+ frame = load_table(path, header=None)
484
+ if frame.shape[1] != 2:
485
+ raise ValueError(f"Expected exactly two columns in Asan bulk file: {path}")
486
+ sample, gsm = sample_file_label(path, ".txt")
487
+ return sample, frame.iloc[:, 0].astype(str).tolist(), None, pd.to_numeric(frame.iloc[:, 1], errors="raise").to_numpy(dtype=np.float64), {"GSM": gsm, "file": str(path)}
488
+
489
+
490
+ def parse_asan(runroot: Path) -> BulkInput:
491
+ accession = "GSE201533"
492
+ paths = extracted_files(runroot, accession, lambda n: n.removesuffix(".gz").endswith(".txt"))
493
+ return from_assembled(accession, accession + "_counts", "raw_gene_counts", (parse_two_column(path) for path in paths),
494
+ declared_raw_counts=True, sources=paths,
495
+ caveats=["Exact source symbol union/reordering; absent features have per-sample masks.",
496
+ "Bulk-to-single-cell donor identities are not inferred from cohort, condition, or timepoint labels."])
497
+
498
+
499
+ def parse_featurecounts_group(gsm: str, paths: list[Path]) -> tuple:
500
+ lanes = []
501
+ first_ids = first_symbols = total = None
502
+ for path in paths:
503
+ lane_match = re.search(r"_L(\d{3})_", path.name)
504
+ if lane_match is None:
505
+ raise ValueError(f"Cannot verify technical lane identity: {path}")
506
+ lane = lane_match[1]
507
+ if lane in lanes:
508
+ raise ValueError(f"Multiple files for the same GSM/lane, refusing duplicate sum: {gsm}/L{lane}")
509
+ lanes.append(lane)
510
+ validate_featurecounts_header(path)
511
+ frame = load_table(path, comment="#")
512
+ if frame.shape[1] != 8:
513
+ raise ValueError(f"Not the expected gene-level featureCounts table: {path}")
514
+ if not frame.Geneid.astype(str).is_unique:
515
+ raise ValueError(f"Duplicate gene IDs within a featureCounts lane: {path}")
516
+ ids = frame.Geneid.astype(str).tolist()
517
+ symbols = frame.gene_name.astype(str).tolist()
518
+ counts = pd.to_numeric(frame.iloc[:, -1], errors="raise").to_numpy(dtype=np.float64)
519
+ if np.any(~np.isfinite(counts)) or np.any(counts < 0) or np.any(counts != np.trunc(counts)):
520
+ raise ValueError(f"Lane sum requires verified nonnegative integer counts: {path}")
521
+ if first_ids is None:
522
+ first_ids, first_symbols, total = ids, symbols, counts.copy()
523
+ else:
524
+ if set(ids) != set(first_ids):
525
+ raise ValueError(f"Lane feature sets differ for {gsm}; partial-lane sums are refused")
526
+ index = {gid: i for i, gid in enumerate(ids)}
527
+ order = [index[gid] for gid in first_ids]
528
+ if [symbols[i] for i in order] != first_symbols:
529
+ raise ValueError(f"Lane gene symbols conflict for {gsm}")
530
+ total += counts[order]
531
+ return gsm, first_ids, first_symbols, total, {"GSM": gsm, "lane_ids": lanes,
532
+ "lane_files": [str(p) for p in paths], "technical_lane_count": len(paths),
533
+ "lane_sum_basis": "same_GSM_distinct_explicit_lane_IDs_exact_gene_set_and_symbol_match"}
534
+
535
+
536
+ def parse_featurecounts(runroot: Path) -> BulkInput:
537
+ accession = "GSE161777"
538
+ paths = extracted_files(runroot, accession, lambda n: n.removesuffix(".gz").endswith("_gene.featureCounts.txt"))
539
+ grouped: dict[str, list[Path]] = defaultdict(list)
540
+ for path in paths:
541
+ gsm = re.match(r"^(GSM\d+)_", path.name)
542
+ if not gsm:
543
+ raise ValueError(f"No explicit GSM prefix in featureCounts source: {path}")
544
+ grouped[gsm[1]].append(path)
545
+ return from_assembled(accession, accession + "_lane_summed_featureCounts", "featureCounts_raw_gene_counts",
546
+ (parse_featurecounts_group(gsm, group) for gsm, group in sorted(grouped.items())),
547
+ declared_raw_counts=True, sources=paths,
548
+ caveats=["Whole-blood bulk, not PBMC bulk. BCR clonotype files are excluded.",
549
+ "Only distinct explicitly labeled technical lanes within one GSM are added after exact gene identity alignment."])
550
+
551
+
552
+ def read_platform_assignments(path: Path) -> dict[str, dict]:
553
+ """Use only the deposited GPL table; never infer symbols from probe IDs."""
554
+ with opener(path) as handle:
555
+ for line in handle:
556
+ if line.startswith("!platform_table_begin"):
557
+ break
558
+ else:
559
+ return {}
560
+ header = handle.readline().rstrip("\r\n").split("\t")
561
+ if "ID" not in header or "gene_assignment" not in header:
562
+ return {}
563
+ assignments = {}
564
+ for line in handle:
565
+ if line.startswith("!platform_table_end"):
566
+ break
567
+ row = dict(zip(header, line.rstrip("\r\n").split("\t")))
568
+ original = row.get("gene_assignment", "")
569
+ symbols = set()
570
+ for assignment in original.split(" /// "):
571
+ fields = assignment.split(" // ")
572
+ if len(fields) >= 2 and fields[1].strip() not in {"", "---"}:
573
+ symbols.add(fields[1].strip())
574
+ assignments[row["ID"]] = {"platform": "GPL6244", "gene_assignment": original,
575
+ "candidate_symbols": sorted(symbols),
576
+ "symbol": next(iter(symbols)) if len(symbols) == 1 else "",
577
+ "mapping_blocker": "platform_ambiguous_symbols" if len(symbols) > 1 else ("platform_unassigned_probe" if not symbols else "")}
578
+ return assignments
579
+
580
+
581
+ def parse_series_matrix(path: Path) -> pd.DataFrame:
582
+ # Read only the table, retaining its exact numeric values and source IDs.
583
+ with opener(path) as handle:
584
+ for line in handle:
585
+ if line.startswith("!series_matrix_table_begin"):
586
+ break
587
+ else:
588
+ raise ValueError(f"No GEO series matrix table: {path}")
589
+ header_line = handle.readline()
590
+ validate_original_header(next(csv.reader([header_line], delimiter="\t")), str(path))
591
+ lines = [header_line]
592
+ for line in handle:
593
+ if line.startswith("!series_matrix_table_end"):
594
+ break
595
+ lines.append(line)
596
+ else:
597
+ raise ValueError(f"Unclosed GEO series matrix table: {path}")
598
+ return pd.read_csv(io.StringIO("".join(lines)), sep="\t", keep_default_na=False)
599
+
600
+
601
+ def parse_microarray(root: Path) -> BulkInput:
602
+ accession = "GSE47353"
603
+ directory = root / "datasets" / accession / "metadata"
604
+ paths = sorted(directory.glob("*series_matrix*.txt.gz"))
605
+ if len(paths) != 1:
606
+ raise ValueError("Expected one GSE47353 series matrix")
607
+ platform_path = directory / f"{accession}_family.soft.gz"
608
+ assignments = read_platform_assignments(platform_path)
609
+ frame = parse_series_matrix(paths[0])
610
+ ids = frame.iloc[:, 0].astype(str).tolist()
611
+ annotation = [assignments.get(gid, {"platform": "GPL6244", "mapping_blocker": "platform_missing_probe_annotation", "symbol": ""}) for gid in ids]
612
+ return BulkInput(accession, accession + "_GPL6244_RMA_microarray", "RMA_normalized_microarray_log_intensity",
613
+ ids, frame.columns[1:].tolist(), numeric_values(frame.iloc[:, 1:]),
614
+ symbols=[a["symbol"] for a in annotation], feature_metadata=annotation,
615
+ allow_negative=True, sources=paths + [platform_path],
616
+ caveats=["Microarray RMA/log intensity, not RNA-seq counts; units unchanged.",
617
+ "Only source probes with one unique GPL gene-assignment symbol may map.",
618
+ "Multiple normalized probes targeting one model gene are quarantined, not averaged or summed."])
619
+
620
+
621
+ def run_bulk(root: Path, runroot: Path) -> list[dict]:
622
+ """Run serially inside the root CPU service; return one record per assay."""
623
+ root, runroot = Path(root), Path(runroot)
624
+ mapper = GeneMapper(runroot / "reference")
625
+ results = []
626
+ accessions = ["GSE152418", "GSE198533", "GSE314922", "GSE162632", "GSE132044", "GSE201533",
627
+ "GSE246525", "GSE252990", "GSE161711", "GSE161777", "GSE47353", "GSE247706"]
628
+ for accession in accessions:
629
+ if accession == "GSE247706":
630
+ result = {"accession": accession, "assay_id": accession + "_bulk_expression_unavailable",
631
+ "status": "missing_bulk_expression_VCF_only", "units": "not_applicable", "raw_count_eligible": False,
632
+ "n_genes": 0, "n_samples": 0, "canonical_coverage": 0, "harmonized_path": "",
633
+ "caveats": ["Downloaded bulk supplementary archive contains genotype VCFs, not an expression matrix."]}
634
+ write_json(runroot / "bulk" / result["assay_id"] / "REPORT.json", result)
635
+ results.append(result)
636
+ continue
637
+ try:
638
+ if accession == "GSE314922":
639
+ assays = [parse_star(runroot)]
640
+ elif accession == "GSE201533":
641
+ assays = [parse_asan(runroot)]
642
+ elif accession == "GSE161777":
643
+ assays = [parse_featurecounts(runroot)]
644
+ elif accession == "GSE47353":
645
+ assays = [parse_microarray(root)]
646
+ else:
647
+ assays = parse_simple(root, accession)
648
+ for assay in assays:
649
+ try:
650
+ results.append(harmonize(assay, mapper, runroot / "bulk" / assay.assay_id))
651
+ except Exception as error:
652
+ result = {"accession": accession, "assay_id": assay.assay_id, "units": assay.units,
653
+ "status": "failed_harmonization", "raw_count_eligible": False,
654
+ "error_type": type(error).__name__, "error": str(error), "harmonized_path": "",
655
+ "caveats": ["Partial output directory may exist; REPORT failure status is authoritative."]}
656
+ write_json(runroot / "bulk" / assay.assay_id / "REPORT.json", result)
657
+ results.append(result)
658
+ del assays
659
+ except Exception as error:
660
+ result = {"accession": accession, "assay_id": accession + "_parse_failure", "status": "failed_source_parse",
661
+ "units": "unresolved", "raw_count_eligible": False, "error_type": type(error).__name__,
662
+ "error": str(error), "harmonized_path": "", "caveats": ["Source files remain unchanged."]}
663
+ write_json(runroot / "bulk" / result["assay_id"] / "REPORT.json", result)
664
+ results.append(result)
665
+ write_json(runroot / "bulk" / "BULK_ORGANIZATION_STATUS.json", {"results_so_far": results, "last_accession": accession})
666
+ write_json(runroot / "bulk" / "BULK_ORGANIZATION_SUMMARY.json", results)
667
+ return results
paper-releases/20260928/diffusion/data/source_prep/giroux2022/code/strict_qc_v1_code_bundle_v5/qc_core.py ADDED
@@ -0,0 +1,650 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Strict, disk-backed expression auditing. No input is modified or filtered.
2
+
3
+ Public scanners return JSON dictionaries and persist NPY metrics/flags. MTX input
4
+ is features x cells. H5AD is cells x features and 10x H5 is features x cells.
5
+ Duplicate coordinates are rejected, including unsorted input: a disk-backed
6
+ uint64 coordinate key vector is sorted in place (quicksort, O(log n) scratch).
7
+ Integral numeric values are evidence about representation, NEVER proof of raw
8
+ counts. Callers must establish count provenance before any aggregation.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import csv
14
+ import gzip
15
+ import hashlib
16
+ import json
17
+ import os
18
+ from pathlib import Path, PurePosixPath
19
+ import shutil
20
+ import stat
21
+ import tarfile
22
+ import tempfile
23
+ from typing import Iterable, Sequence
24
+ import zipfile
25
+
26
+ import numpy as np
27
+
28
+
29
+ class QCError(ValueError):
30
+ """Input failed a structural or safety requirement."""
31
+
32
+
33
+ def sha256_file(path: str | Path, chunk_bytes: int = 4 * 1024**2) -> str:
34
+ digest = hashlib.sha256()
35
+ with open(path, "rb") as handle:
36
+ for chunk in iter(lambda: handle.read(chunk_bytes), b""):
37
+ digest.update(chunk)
38
+ return digest.hexdigest()
39
+
40
+
41
+ def _write_json(path: Path, value: dict) -> None:
42
+ path.parent.mkdir(parents=True, exist_ok=True)
43
+ fd, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".partial", dir=path.parent)
44
+ try:
45
+ with os.fdopen(fd, "w") as handle:
46
+ json.dump(value, handle, indent=2, allow_nan=False)
47
+ handle.write("\n")
48
+ handle.flush()
49
+ os.fsync(handle.fileno())
50
+ os.replace(temporary, path)
51
+ finally:
52
+ if os.path.exists(temporary):
53
+ os.unlink(temporary)
54
+
55
+
56
+ def _safe_member(name: str) -> str:
57
+ if not name or "\\" in name or "\x00" in name:
58
+ raise QCError(f"Unsafe archive member: {name!r}")
59
+ path = PurePosixPath(name)
60
+ if path.is_absolute() or ".." in path.parts or any(":" in p for p in path.parts):
61
+ raise QCError(f"Unsafe archive member: {name!r}")
62
+ normalized = str(path)
63
+ if normalized in ("", "."):
64
+ raise QCError(f"Empty archive member: {name!r}")
65
+ return normalized
66
+
67
+
68
+ def inventory_archive(path: str | Path) -> list[dict]:
69
+ """Inspect zip/tar without extracting; reject links, special files and collisions."""
70
+ path = Path(path)
71
+ members: list[dict] = []
72
+ if zipfile.is_zipfile(path):
73
+ with zipfile.ZipFile(path) as archive:
74
+ for item in archive.infolist():
75
+ name = _safe_member(item.filename)
76
+ mode = item.external_attr >> 16
77
+ kind = stat.S_IFMT(mode)
78
+ if kind not in (0, stat.S_IFREG, stat.S_IFDIR) or item.flag_bits & 1:
79
+ raise QCError(f"Unsupported zip member: {item.filename}")
80
+ members.append({"name": name, "size": item.file_size, "directory": item.is_dir()})
81
+ elif tarfile.is_tarfile(path):
82
+ with tarfile.open(path, "r:*") as archive:
83
+ for item in archive:
84
+ if item.name in (".", "./") and item.isdir():
85
+ continue
86
+ name = _safe_member(item.name)
87
+ if not (item.isfile() or item.isdir()) or getattr(item, "sparse", None):
88
+ raise QCError(f"Unsupported tar member: {item.name}")
89
+ members.append({"name": name, "size": item.size, "directory": item.isdir()})
90
+ else:
91
+ raise QCError(f"Unsupported archive format: {path}")
92
+ seen: dict[str, bool] = {}
93
+ for member in members:
94
+ name = member["name"]
95
+ if name in seen:
96
+ raise QCError(f"Duplicate archive path: {name}")
97
+ if member["size"] < 0:
98
+ raise QCError(f"Negative member size: {name}")
99
+ seen[name] = member["directory"]
100
+ for name in seen:
101
+ for parent in PurePosixPath(name).parents:
102
+ if str(parent) in seen and not seen[str(parent)]:
103
+ raise QCError(f"Archive file/directory collision: {name}")
104
+ return members
105
+
106
+
107
+ def _safe_destination(root: Path, relative: str) -> Path:
108
+ destination = root / relative
109
+ for component in (destination, *destination.parents):
110
+ if component == root.parent:
111
+ break
112
+ if component.is_symlink():
113
+ raise QCError(f"Extraction destination contains symlink: {component}")
114
+ if not destination.resolve().is_relative_to(root.resolve()):
115
+ raise QCError(f"Extraction escaped destination: {destination}")
116
+ return destination
117
+
118
+
119
+ def extract_archive(
120
+ path: str | Path,
121
+ dest: str | Path,
122
+ receipt_path: str | Path | None = None,
123
+ disk_floor_bytes: int = 5 * 1024**3,
124
+ ) -> dict:
125
+ """Safely extract regular files; atomic members and SHA256-verified resume.
126
+
127
+ The receipt is rewritten atomically after every completed member. Existing
128
+ files without a matching receipt are compared to freshly streamed archive
129
+ bytes, then adopted only if identical. Source archives are preserved.
130
+ """
131
+ path, dest = Path(path), Path(dest)
132
+ if dest.is_symlink():
133
+ raise QCError("Extraction root must not be a symlink")
134
+ inventory = inventory_archive(path)
135
+ dest.mkdir(parents=True, exist_ok=True)
136
+ source_hash = sha256_file(path)
137
+ receipt_file = Path(receipt_path) if receipt_path else dest / ".extraction_receipt.json"
138
+ receipt = {"source": str(path.resolve()), "source_sha256": source_hash, "files": {}, "complete": False}
139
+ if receipt_file.exists():
140
+ previous = json.loads(receipt_file.read_text())
141
+ if previous.get("source_sha256") != source_hash:
142
+ raise QCError("Existing extraction receipt belongs to a different archive")
143
+ receipt = previous
144
+ receipt["complete"] = False
145
+ required = sum(item["size"] for item in inventory if not item["directory"] and not (dest / item["name"]).exists())
146
+ if shutil.disk_usage(dest).free < required + disk_floor_bytes:
147
+ raise QCError(f"Insufficient disk headroom: need {required + disk_floor_bytes} bytes")
148
+ zipped = zipfile.is_zipfile(path)
149
+ archive = zipfile.ZipFile(path) if zipped else tarfile.open(path, "r:*")
150
+ try:
151
+ lookup = {(_safe_member(m.filename) if zipped else _safe_member(m.name)): m
152
+ for m in (archive.infolist() if zipped else archive.getmembers())
153
+ if (m.filename if zipped else m.name) not in (".", "./")}
154
+ for item in inventory:
155
+ destination = _safe_destination(dest, item["name"])
156
+ if item["directory"]:
157
+ destination.mkdir(parents=True, exist_ok=True)
158
+ continue
159
+ destination.parent.mkdir(parents=True, exist_ok=True)
160
+ old = receipt["files"].get(item["name"])
161
+ if old and destination.is_file() and destination.stat().st_size == item["size"]:
162
+ if old.get("size") == item["size"] and sha256_file(destination) == old.get("sha256"):
163
+ continue
164
+ raise QCError(f"Previously extracted member has changed: {destination}")
165
+ if destination.exists() and not destination.is_file():
166
+ raise QCError(f"Non-file extraction target: {destination}")
167
+ if shutil.disk_usage(dest).free < item["size"] + disk_floor_bytes:
168
+ raise QCError("Disk floor reached before extraction")
169
+ fd, temporary = tempfile.mkstemp(prefix=destination.name + ".", suffix=".partial", dir=destination.parent)
170
+ digest, written = hashlib.sha256(), 0
171
+ try:
172
+ entry = lookup[item["name"]]
173
+ stream = archive.open(entry) if zipped else archive.extractfile(entry)
174
+ if stream is None:
175
+ raise QCError(f"Unreadable archive member: {item['name']}")
176
+ with stream, os.fdopen(fd, "wb") as output:
177
+ for chunk in iter(lambda: stream.read(4 * 1024**2), b""):
178
+ written += len(chunk)
179
+ if written > item["size"]:
180
+ raise QCError(f"Member exceeds declared size: {item['name']}")
181
+ if shutil.disk_usage(dest).free < len(chunk) + disk_floor_bytes:
182
+ raise QCError("Disk floor reached during extraction")
183
+ output.write(chunk)
184
+ digest.update(chunk)
185
+ output.flush()
186
+ os.fsync(output.fileno())
187
+ if written != item["size"]:
188
+ raise QCError(f"Truncated member: {item['name']}")
189
+ checksum = digest.hexdigest()
190
+ if destination.exists():
191
+ if destination.stat().st_size != written or sha256_file(destination) != checksum:
192
+ raise QCError(f"Existing extraction target differs: {destination}")
193
+ else:
194
+ os.replace(temporary, destination)
195
+ receipt["files"][item["name"]] = {"size": written, "sha256": checksum}
196
+ _write_json(receipt_file, receipt)
197
+ finally:
198
+ if os.path.exists(temporary):
199
+ os.unlink(temporary)
200
+ finally:
201
+ archive.close()
202
+ receipt["complete"] = True
203
+ receipt["member_count"] = len(inventory)
204
+ _write_json(receipt_file, receipt)
205
+ return receipt
206
+
207
+
208
+ def _vector(value: Sequence | None, size: int, name: str, default: bool = False) -> np.ndarray:
209
+ if value is None:
210
+ return np.full(size, default, dtype=bool)
211
+ vector = np.asarray(value, dtype=bool)
212
+ if vector.shape != (size,):
213
+ raise QCError(f"{name} length mismatch: {vector.shape} vs {(size,)}")
214
+ return vector
215
+
216
+
217
+ def _quantiles(values: np.ndarray) -> dict:
218
+ if not len(values):
219
+ return {"n": 0}
220
+ quantiles = np.quantile(values, [0, .01, .05, .25, .5, .75, .95, .99, 1])
221
+ return {"n": len(values), **{key: float(number) for key, number in zip(
222
+ ["min", "p01", "p05", "p25", "median", "p75", "p95", "p99", "max"], quantiles)}}
223
+
224
+
225
+ class _Accumulator:
226
+ def __init__(self, out_dir: Path, n_features: int, n_cells: int, nnz: int,
227
+ mito_mask: Sequence | None, feature_mask: Sequence | None,
228
+ duplicate_policy: str = "reject", disk_floor_bytes: int = 1024**3):
229
+ if min(n_features, n_cells, nnz) < 0 or n_features == 0 or n_cells == 0:
230
+ raise QCError("Matrix dimensions must be positive; nnz must be nonnegative")
231
+ if n_features * n_cells > np.iinfo(np.uint64).max:
232
+ raise QCError("Matrix dimensions exceed supported coordinate-key range")
233
+ if duplicate_policy != "reject":
234
+ raise QCError("Only duplicate_policy='reject' is supported; duplicates require provenance-aware repair")
235
+ out_dir.mkdir(parents=True, exist_ok=True)
236
+ if (out_dir / "qc_summary.json").exists():
237
+ raise QCError(f"Refusing to overwrite an existing QC result: {out_dir}")
238
+ required = nnz * 8 + (n_features * 16) + (n_cells * 60)
239
+ if shutil.disk_usage(out_dir).free < required + disk_floor_bytes:
240
+ raise QCError(f"Insufficient disk for audit vectors: {required} bytes plus floor")
241
+ self.out, self.n_features, self.n_cells, self.nnz = out_dir, n_features, n_cells, nnz
242
+ self.selected = _vector(feature_mask, n_features, "feature_mask", default=True)
243
+ self.mito = _vector(mito_mask, n_features, "mito_mask") & self.selected
244
+ if not np.any(self.selected):
245
+ raise QCError("No expression features selected")
246
+ self.arrays: dict[str, np.ndarray] = {}
247
+ for name, size, dtype in [("cell_total", n_cells, "f8"), ("cell_detected", n_cells, "i8"),
248
+ ("cell_mito_total", n_cells, "f8"), ("gene_total", n_features, "f8"),
249
+ ("gene_detected", n_features, "i8")]:
250
+ array = np.lib.format.open_memmap(out_dir / (name + ".npy"), mode="w+", dtype=dtype, shape=(size,))
251
+ array[:] = 0
252
+ self.arrays[name] = array
253
+ self.keys_path = out_dir / ".coordinate_keys.uint64"
254
+ self.keys = np.memmap(self.keys_path, mode="w+", dtype="u8", shape=(nnz,)) if nnz else None
255
+ self.offset = self.nonzero = self.selected_nonzero = self.integer_values = self.selected_integer_values = 0
256
+ self.stored_zero = self.selected_stored = 0
257
+ self.minimum, self.maximum = float("inf"), float("-inf")
258
+
259
+ def add(self, features: np.ndarray, cells: np.ndarray, values: np.ndarray) -> None:
260
+ if not (len(features) == len(cells) == len(values)):
261
+ raise QCError("Sparse vector length mismatch")
262
+ if self.offset + len(values) > self.nnz:
263
+ raise QCError("More coordinates than declared nnz")
264
+ if np.any(features < 0) or np.any(features >= self.n_features) or np.any(cells < 0) or np.any(cells >= self.n_cells):
265
+ raise QCError("Sparse coordinate out of bounds")
266
+ if not np.all(np.isfinite(values)):
267
+ raise QCError("Nonfinite expression value")
268
+ if np.any(values < 0):
269
+ raise QCError("Negative expression value; assay/layer is not nonnegative abundance")
270
+ if self.keys is not None:
271
+ self.keys[self.offset:self.offset + len(values)] = cells.astype("u8") * self.n_features + features.astype("u8")
272
+ self.offset += len(values)
273
+ self.stored_zero += int(np.count_nonzero(values == 0))
274
+ self.nonzero += int(np.count_nonzero(values))
275
+ integral = np.equal(values, np.floor(values))
276
+ self.integer_values += int(np.count_nonzero(integral))
277
+ if len(values):
278
+ self.minimum = min(self.minimum, float(values.min()))
279
+ self.maximum = max(self.maximum, float(values.max()))
280
+ keep = self.selected[features]
281
+ self.selected_stored += int(keep.sum())
282
+ self.selected_integer_values += int(np.count_nonzero(integral & keep))
283
+ genes, columns, expression = features[keep], cells[keep], values[keep]
284
+ positive = expression > 0
285
+ self.selected_nonzero += int(positive.sum())
286
+ np.add.at(self.arrays["cell_total"], columns, expression)
287
+ np.add.at(self.arrays["gene_total"], genes, expression)
288
+ np.add.at(self.arrays["cell_detected"], columns[positive], 1)
289
+ np.add.at(self.arrays["gene_detected"], genes[positive], 1)
290
+ mitochondrial = self.mito[genes]
291
+ np.add.at(self.arrays["cell_mito_total"], columns[mitochondrial], expression[mitochondrial])
292
+
293
+ def finish(self, metadata: dict, sample_ids: Sequence | None = None,
294
+ feature_ids: Sequence | None = None, feature_symbols: Sequence | None = None,
295
+ cell_ids: Sequence | None = None) -> dict:
296
+ for ids, expected, kind in ((feature_ids, self.n_features, "feature_ids"),
297
+ (feature_symbols, self.n_features, "feature_symbols"),
298
+ (cell_ids, self.n_cells, "cell_ids")):
299
+ if ids is not None and len(ids) != expected:
300
+ raise QCError(f"{kind} length mismatch")
301
+ if cell_ids is not None:
302
+ labels = np.asarray(cell_ids, dtype=str)
303
+ if np.any(np.char.strip(labels) == "") or len(np.unique(labels)) != len(labels):
304
+ raise QCError("Empty or duplicate cell_ids within matrix/library")
305
+ if self.offset != self.nnz:
306
+ raise QCError(f"Truncated matrix: observed {self.offset}, declared {self.nnz} coordinates")
307
+ if self.keys is not None:
308
+ self.keys.flush()
309
+ self.keys.sort(kind="quicksort")
310
+ previous = None
311
+ for start in range(0, self.nnz, 250_000):
312
+ part = self.keys[start:start + 250_000]
313
+ if (previous is not None and part[0] == previous) or np.any(part[1:] == part[:-1]):
314
+ raise QCError("Duplicate sparse coordinates; matrix quarantined (no automatic summation)")
315
+ previous = part[-1]
316
+ del self.keys
317
+ self.keys = None
318
+ self.keys_path.unlink()
319
+ for array in self.arrays.values():
320
+ if not np.all(np.isfinite(array)):
321
+ raise QCError("Nonfinite accumulated metrics (numeric overflow)")
322
+ array.flush()
323
+ total, detected = self.arrays["cell_total"], self.arrays["cell_detected"]
324
+ mito_percent = np.divide(self.arrays["cell_mito_total"] * 100, total,
325
+ out=np.zeros(self.n_cells), where=total > 0)
326
+ np.save(self.out / "cell_mito_percent.npy", mito_percent)
327
+ flags = {"zero_total": total == 0, "low_genes_200": detected < 200,
328
+ "low_abundance_500": total < 500, "mito_above_20pct": mito_percent > 20}
329
+ if sample_ids is None:
330
+ sample_ids = np.full(self.n_cells, "__matrix__", dtype=object)
331
+ sample_scope = "whole matrix; donor/sample IDs unavailable"
332
+ else:
333
+ sample_ids = np.asarray(sample_ids, dtype=str)
334
+ if sample_ids.shape != (self.n_cells,):
335
+ raise QCError("sample_ids length mismatch")
336
+ sample_scope = "caller-provided sample IDs"
337
+ sample_summaries = []
338
+ for name in ["low_total_mad", "low_genes_mad", "high_mito_mad", "high_total_review_only"]:
339
+ flags[name] = np.zeros(self.n_cells, dtype=bool)
340
+ for sample in np.unique(sample_ids):
341
+ indices = np.flatnonzero(sample_ids == sample)
342
+ sample_info = {"sample_id": str(sample), "n_cells": len(indices), "mad_applied": len(indices) >= 20}
343
+ if len(indices) >= 20:
344
+ for name, vector, transform, direction in [
345
+ ("low_total_mad", total, True, -1), ("low_genes_mad", detected, True, -1),
346
+ ("high_mito_mad", mito_percent, False, 1), ("high_total_review_only", total, True, 1)]:
347
+ values = np.log1p(vector[indices]) if transform else vector[indices]
348
+ median = float(np.median(values))
349
+ mad = float(np.median(np.abs(values - median)))
350
+ # A zero MAD has no useful scale and must not flag every departure.
351
+ cutoff = median + direction * 5 * 1.4826 * mad
352
+ if mad > 0:
353
+ flags[name][indices] = values < cutoff if direction < 0 else values > cutoff
354
+ sample_info[name] = {"median": median, "mad": mad, "cutoff": cutoff, "enabled": mad > 0}
355
+ sample_summaries.append(sample_info)
356
+ flags["structural_nonempty"] = (total > 0) & (detected > 0)
357
+ flags["conservative_review_pass"] = ~(flags["low_genes_200"] | flags["low_abundance_500"] | flags["mito_above_20pct"])
358
+ for name, vector in flags.items():
359
+ np.save(self.out / ("flag_" + name + ".npy"), vector)
360
+ np.save(self.out / "feature_selected.npy", self.selected)
361
+ np.save(self.out / "feature_mito.npy", self.mito)
362
+ for values, size, name in [(feature_ids, self.n_features, "feature_ids"),
363
+ (feature_symbols, self.n_features, "feature_symbols"),
364
+ (cell_ids, self.n_cells, "cell_ids")]:
365
+ if values is not None:
366
+ if len(values) != size:
367
+ raise QCError(f"{name} length mismatch")
368
+ with open(self.out / (name + ".tsv"), "w", newline="") as handle:
369
+ writer = csv.writer(handle, delimiter="\t")
370
+ writer.writerow(["index", name.rstrip("s")])
371
+ writer.writerows(enumerate(str(value) for value in values))
372
+ summary = {"schema_version": "1.0", "structural_status": "PASS", "input": metadata,
373
+ "orientation": "features_by_cells", "n_features": self.n_features, "n_cells": self.n_cells,
374
+ "n_selected_features": int(self.selected.sum()), "n_mito_features": int(self.mito.sum()),
375
+ "declared_stored_entries": self.nnz, "observed_stored_entries": self.offset,
376
+ "explicit_zero_entries": self.stored_zero, "positive_entries": self.nonzero,
377
+ "selected_positive_entries": self.selected_nonzero, "duplicate_coordinates": 0,
378
+ "duplicates_policy": "reject; exact disk-backed coordinate sort",
379
+ "numeric": {"minimum_stored": self.minimum if self.nnz else None,
380
+ "maximum_stored": self.maximum if self.nnz else None,
381
+ "integer_fraction_stored": self.integer_values / self.nnz if self.nnz else None,
382
+ "integer_fraction_selected_stored": self.selected_integer_values / self.selected_stored if self.selected_stored else None,
383
+ "raw_counts_proven": False,
384
+ "interpretation": "Integer-valued entries do not establish raw-count provenance; normalized integer tables can exist."},
385
+ "cell_total": _quantiles(total), "cell_detected": _quantiles(detected),
386
+ "cell_mito_percent": _quantiles(mito_percent),
387
+ "gene_total": _quantiles(self.arrays["gene_total"][self.selected]),
388
+ "gene_detected": _quantiles(self.arrays["gene_detected"][self.selected]),
389
+ "flag_counts": {name: int(vector.sum()) for name, vector in flags.items()},
390
+ "sample_scope": sample_scope, "sample_summaries": sample_summaries,
391
+ "outlier_mad_multiplier": 5, "mad_normal_consistency_factor": 1.4826,
392
+ "warnings": ["Flags are review annotations, not irreversible filtering.",
393
+ "High-count cells are review-only; immune activation can increase RNA content.",
394
+ "Abundance 500 threshold is count-like and requires raw-count provenance.",
395
+ "Mitochondrial percentage requires a validated feature mask; zero mask is not a biological zero."],
396
+ "metrics_directory": str(self.out.resolve())}
397
+ _write_json(self.out / "qc_summary.json", summary)
398
+ return summary
399
+
400
+
401
+ def _text_open(path: str | Path):
402
+ return gzip.open(path, "rt") if str(path).lower().endswith(".gz") else open(path, "rt")
403
+
404
+
405
+ def scan_mtx(path: str | Path, out_dir: str | Path, *, mito_mask: Sequence | None = None,
406
+ feature_mask: Sequence | None = None, sample_ids: Sequence | None = None,
407
+ feature_ids: Sequence | None = None, feature_symbols: Sequence | None = None,
408
+ cell_ids: Sequence | None = None, duplicate_policy: str = "reject",
409
+ chunk_nnz: int = 250_000, disk_floor_bytes: int = 1024**3) -> dict:
410
+ """Stream general coordinate MTX (integer/real), validating every entry."""
411
+ if not 1 <= chunk_nnz <= 2_000_000:
412
+ raise QCError("chunk_nnz must be between 1 and 2000000")
413
+ with _text_open(path) as handle:
414
+ header = handle.readline().strip().split()
415
+ if len(header) != 5 or [part.lower() for part in header[:3]] != ["%%matrixmarket", "matrix", "coordinate"]:
416
+ raise QCError("Expected MatrixMarket coordinate matrix header")
417
+ field, symmetry = header[3].lower(), header[4].lower()
418
+ if field not in ("integer", "real") or symmetry != "general":
419
+ raise QCError(f"Unsupported MatrixMarket field/symmetry: {field}/{symmetry}")
420
+ dimensions = None
421
+ for line in handle:
422
+ if line.strip() and not line.lstrip().startswith("%"):
423
+ try:
424
+ dimensions = tuple(int(value) for value in line.split())
425
+ except ValueError as error:
426
+ raise QCError("Invalid MatrixMarket dimensions") from error
427
+ break
428
+ if dimensions is None or len(dimensions) != 3:
429
+ raise QCError("Missing or malformed MatrixMarket dimensions")
430
+ features, cells, nnz = dimensions
431
+ accumulator = _Accumulator(Path(out_dir), features, cells, nnz, mito_mask, feature_mask, duplicate_policy, disk_floor_bytes)
432
+ rows, columns, values = [], [], []
433
+ for line_number, line in enumerate(handle, start=1):
434
+ if not line.strip() or line.lstrip().startswith("%"):
435
+ continue
436
+ fields = line.split()
437
+ if len(fields) != 3:
438
+ raise QCError(f"Malformed coordinate line {line_number}: expected three fields")
439
+ try:
440
+ row, column = int(fields[0]), int(fields[1])
441
+ value = float(fields[2])
442
+ if field == "integer":
443
+ integer = int(fields[2])
444
+ if abs(integer) > 2**53:
445
+ raise QCError("Integer exceeds exact float64 accumulation range")
446
+ except (ValueError, OverflowError) as error:
447
+ raise QCError(f"Invalid numeric field at coordinate line {line_number}") from error
448
+ rows.append(row - 1)
449
+ columns.append(column - 1)
450
+ values.append(value)
451
+ if len(values) >= chunk_nnz:
452
+ accumulator.add(np.asarray(rows, dtype="i8"), np.asarray(columns, dtype="i8"), np.asarray(values, dtype="f8"))
453
+ rows, columns, values = [], [], []
454
+ if values:
455
+ accumulator.add(np.asarray(rows, dtype="i8"), np.asarray(columns, dtype="i8"), np.asarray(values, dtype="f8"))
456
+ return accumulator.finish({"path": str(Path(path).resolve()), "format": "mtx", "field": field,
457
+ "sha256": sha256_file(path)}, sample_ids, feature_ids, feature_symbols, cell_ids)
458
+
459
+
460
+ def _strings(dataset) -> np.ndarray:
461
+ array = np.asarray(dataset[...])
462
+ if array.ndim != 1:
463
+ raise QCError("Expected one-dimensional string metadata")
464
+ return np.asarray([value.decode("utf-8") if isinstance(value, bytes) else str(value) for value in array])
465
+
466
+
467
+ def _h5_column(group, name: str) -> np.ndarray | None:
468
+ import h5py
469
+ if name not in group:
470
+ return None
471
+ column = group[name]
472
+ if isinstance(column, h5py.Dataset):
473
+ return _strings(column)
474
+ if "codes" in column and "categories" in column:
475
+ categories = _strings(column["categories"])
476
+ codes = np.asarray(column["codes"][...])
477
+ if not np.issubdtype(codes.dtype, np.integer) or np.any(codes < -1) or np.any(codes >= len(categories)):
478
+ raise QCError(f"Invalid H5AD categorical codes: {name}")
479
+ return np.asarray([categories[code] if code >= 0 else "" for code in codes])
480
+ raise QCError(f"Unsupported H5 metadata column encoding: {name}")
481
+
482
+
483
+ def _h5_index(group) -> np.ndarray:
484
+ key = group.attrs.get("_index", "_index")
485
+ if isinstance(key, bytes):
486
+ key = key.decode()
487
+ if key not in group and "index" in group:
488
+ key = "index"
489
+ result = _h5_column(group, key)
490
+ if result is None:
491
+ raise QCError("H5AD dataframe index missing")
492
+ return result
493
+
494
+
495
+ def scan_h5(path: str | Path, out_dir: str | Path, *, matrix_path: str | None = None,
496
+ mito_mask: Sequence | None = None, feature_mask: Sequence | None = None,
497
+ sample_ids: Sequence | None = None, chunk_nnz: int = 250_000,
498
+ disk_floor_bytes: int = 1024**3) -> dict:
499
+ """Audit backed sparse/dense H5AD or 10x H5; only RNA features contribute.
500
+
501
+ H5AD defaults to X; raw/X or layers/counts must be selected explicitly.
502
+ All source coordinates, including non-RNA features, are structurally checked.
503
+ """
504
+ import h5py
505
+ if not 1 <= chunk_nnz <= 2_000_000:
506
+ raise QCError("chunk_nnz must be between 1 and 2000000")
507
+ with h5py.File(path, "r", rdcc_nbytes=256 * 1024**2) as handle:
508
+ tenx = "matrix" in handle and all(name in handle["matrix"] for name in ("data", "indices", "indptr", "shape", "features"))
509
+ if tenx:
510
+ matrix_path = matrix_path or "matrix"
511
+ matrix = handle[matrix_path]
512
+ shape = tuple(int(value) for value in matrix["shape"][...])
513
+ if len(shape) != 2:
514
+ raise QCError("10x shape must have two dimensions")
515
+ n_features, n_cells = shape
516
+ features = matrix["features"]
517
+ feature_ids = _strings(features["id"])
518
+ symbols = _strings(features["name"]) if "name" in features else feature_ids
519
+ feature_types = _strings(features["feature_type"]) if "feature_type" in features else None
520
+ cell_ids = _strings(matrix["barcodes"])
521
+ orientation, encoding = "features_by_cells", "csc_matrix"
522
+ else:
523
+ matrix_path = matrix_path or "X"
524
+ if matrix_path not in handle or "obs" not in handle or "var" not in handle:
525
+ raise QCError("Unsupported HDF5 layout: expected 10x matrix or H5AD X/obs/var")
526
+ matrix = handle[matrix_path]
527
+ feature_group = handle["raw/var"] if matrix_path.startswith("raw/") and "raw/var" in handle else handle["var"]
528
+ feature_ids = _h5_index(feature_group)
529
+ symbols = None
530
+ for name in ("gene_symbols", "gene_symbol", "feature_name", "gene_names", "symbol"):
531
+ symbols = _h5_column(feature_group, name)
532
+ if symbols is not None:
533
+ break
534
+ if symbols is None:
535
+ symbols = feature_ids
536
+ feature_types = None
537
+ for name in ("feature_types", "feature_type"):
538
+ feature_types = _h5_column(feature_group, name)
539
+ if feature_types is not None:
540
+ break
541
+ cell_ids = _h5_index(handle["obs"])
542
+ n_features, n_cells = len(feature_ids), len(cell_ids)
543
+ shape = (n_cells, n_features)
544
+ orientation = "cells_by_features"
545
+ encoding = matrix.attrs.get("encoding-type", "")
546
+ if isinstance(encoding, bytes):
547
+ encoding = encoding.decode()
548
+ if isinstance(matrix, h5py.Dataset):
549
+ encoding = "dense"
550
+ actual_shape = matrix.shape
551
+ else:
552
+ actual_shape = tuple(matrix.attrs.get("shape", ()))
553
+ if tuple(actual_shape) != shape:
554
+ raise QCError(f"H5AD shape/metadata mismatch: {actual_shape} vs {shape}")
555
+ if len(feature_ids) != n_features or len(symbols) != n_features or len(cell_ids) != n_cells:
556
+ raise QCError("H5 matrix dimensions and metadata lengths differ")
557
+ rna = np.ones(n_features, dtype=bool) if feature_types is None else feature_types == "Gene Expression"
558
+ if rna.shape != (n_features,):
559
+ raise QCError("H5 feature_type length mismatch")
560
+ rna &= _vector(feature_mask, n_features, "feature_mask", default=True)
561
+ inferred_mito = np.char.startswith(np.char.upper(symbols.astype(str)), "MT-") if mito_mask is None else mito_mask
562
+ metadata = {"path": str(Path(path).resolve()), "format": "10x_h5" if tenx else "h5ad",
563
+ "matrix_path": matrix_path, "source_orientation": orientation, "encoding": encoding,
564
+ "rna_selection": "feature_type == Gene Expression" if feature_types is not None else "No feature types supplied; all features assumed expression",
565
+ "mito_selection": "symbols beginning MT- (case insensitive)" if mito_mask is None else "caller-provided mask"}
566
+ if encoding == "dense":
567
+ if matrix.ndim != 2 or not np.issubdtype(matrix.dtype, np.number) or np.issubdtype(matrix.dtype, np.complexfloating):
568
+ raise QCError("Unsupported dense H5 dtype or dimensions")
569
+ # Dense input is visited in bounded blocks; zeros are omitted from the
570
+ # coordinate stream. Count positive entries in a bounded first pass.
571
+ block_rows = max(1, chunk_nnz // n_features)
572
+ nnz = 0
573
+ for start in range(0, n_cells, block_rows):
574
+ block = np.asarray(matrix[start:start + block_rows, :])
575
+ if not np.all(np.isfinite(block)) or np.any(block < 0):
576
+ raise QCError("Dense matrix contains nonfinite or negative values")
577
+ nnz += int(np.count_nonzero(block))
578
+ accumulator = _Accumulator(Path(out_dir), n_features, n_cells, nnz, inferred_mito, rna, disk_floor_bytes=disk_floor_bytes)
579
+ for start in range(0, n_cells, block_rows):
580
+ block = np.asarray(matrix[start:start + block_rows, :])
581
+ rows, cols = np.nonzero(block)
582
+ accumulator.add(cols, rows + start, block[rows, cols].astype("f8"))
583
+ elif encoding in ("csr_matrix", "csc_matrix"):
584
+ if not all(key in matrix for key in ("data", "indices", "indptr")):
585
+ raise QCError("Sparse H5 lacks required arrays")
586
+ data, indices, indptr = matrix["data"], matrix["indices"], matrix["indptr"]
587
+ if any(array.ndim != 1 for array in (data, indices, indptr)):
588
+ raise QCError("Sparse H5 arrays must be one-dimensional")
589
+ if not np.issubdtype(data.dtype, np.number) or np.issubdtype(data.dtype, np.complexfloating):
590
+ raise QCError("Unsupported sparse expression dtype")
591
+ if not np.issubdtype(indices.dtype, np.integer) or not np.issubdtype(indptr.dtype, np.integer):
592
+ raise QCError("Sparse indices/indptr must have integer dtypes")
593
+ nnz = len(data)
594
+ major_size = shape[0] if encoding == "csr_matrix" else shape[1]
595
+ minor_size = shape[1] if encoding == "csr_matrix" else shape[0]
596
+ if len(indices) != nnz or len(indptr) != major_size + 1:
597
+ raise QCError("Sparse H5 array lengths disagree with shape/nnz")
598
+ if int(indptr[0]) != 0 or int(indptr[-1]) != nnz:
599
+ raise QCError("Sparse indptr endpoints disagree with nnz")
600
+ accumulator = _Accumulator(Path(out_dir), n_features, n_cells, nnz, inferred_mito, rna, disk_floor_bytes=disk_floor_bytes)
601
+ pointer_path = Path(out_dir) / ".indptr.int64"
602
+ pointer = np.memmap(pointer_path, mode="w+", dtype="i8", shape=(major_size + 1,))
603
+ previous = 0
604
+ for start in range(0, major_size + 1, chunk_nnz):
605
+ part = np.asarray(indptr[start:start + chunk_nnz])
606
+ if np.any(part < 0) or np.any(part > nnz) or part[0] < previous or np.any(part[1:] < part[:-1]):
607
+ raise QCError("Sparse indptr is nonmonotonic or out of bounds")
608
+ pointer[start:start + len(part)] = part
609
+ previous = int(part[-1])
610
+ for start in range(0, nnz, chunk_nnz):
611
+ stop = min(start + chunk_nnz, nnz)
612
+ minor = np.asarray(indices[start:stop])
613
+ if np.any(minor < 0) or np.any(minor >= minor_size):
614
+ raise QCError("Sparse H5 index out of bounds")
615
+ major = np.searchsorted(pointer, np.arange(start, stop), side="right") - 1
616
+ rows, cols = (major, minor) if encoding == "csr_matrix" else (minor, major)
617
+ genes, cells = (rows, cols) if tenx else (cols, rows)
618
+ accumulator.add(genes.astype("i8"), cells.astype("i8"), np.asarray(data[start:stop], dtype="f8"))
619
+ del pointer
620
+ pointer_path.unlink()
621
+ else:
622
+ raise QCError(f"Unsupported H5 sparse encoding: {encoding!r}")
623
+ metadata["sha256"] = sha256_file(path)
624
+ return accumulator.finish(metadata, sample_ids, feature_ids, symbols, cell_ids)
625
+
626
+
627
+ def harmonize_coordinate_chunks(chunks: Iterable[tuple[np.ndarray, np.ndarray, np.ndarray]],
628
+ feature_mapping: Sequence[int], *, verified_raw_counts: bool,
629
+ has_duplicate_targets: bool) -> Iterable[tuple[np.ndarray, np.ndarray, np.ndarray]]:
630
+ """Map sparse chunks without densifying; -1 mappings are quarantined/omitted.
631
+
632
+ This helper does NOT combine coordinates. A downstream sparse reducer may
633
+ sum collisions only when verified_raw_counts is true. Normalized duplicate
634
+ targets raise before consuming input. Callers must retain the original map
635
+ and explicitly account for excluded -1 features in their audit manifest.
636
+ """
637
+ mapping = np.asarray(feature_mapping, dtype="i8")
638
+ if mapping.ndim != 1 or np.any(mapping < -1):
639
+ raise QCError("Invalid canonical feature mapping")
640
+ actual_duplicates = len(np.unique(mapping[mapping >= 0])) < int(np.sum(mapping >= 0))
641
+ if actual_duplicates != has_duplicate_targets:
642
+ raise QCError("Declared target duplication disagrees with feature mapping")
643
+ if actual_duplicates and not verified_raw_counts:
644
+ raise QCError("Normalized/unknown duplicate gene mappings quarantined; summation is prohibited")
645
+ for features, cells, values in chunks:
646
+ if np.any(features < 0) or np.any(features >= len(mapping)):
647
+ raise QCError("Feature index outside canonical mapping")
648
+ target = mapping[features]
649
+ keep = target >= 0
650
+ yield target[keep], cells[keep], values[keep]