junidude14 commited on
Commit
0ab4e4e
·
verified ·
1 Parent(s): f5c98b9

Archive 4 checkpoints (1-4)

Browse files
paper-releases/20260928/diffusion/data/source_prep/imperial_eskd/code/run_step.sh ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Run one CPU-only step as a transient systemd user unit.
3
+ # Limits: 16 GiB memory (no swap), <= 4 CPUs, positive OOM score, no restart, CUDA hidden,
4
+ # single-threaded BLAS/OpenMP. Usage: run_step.sh [--nowait] <script> <args...>
5
+ # script: pipeline (imperial_pipeline.py) | assemble (imperial_assemble.py) | full (imperial_full_cells.py)
6
+ set -euo pipefail
7
+ RUN=/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/imperial_eskd_v1_20260928
8
+ PY=/home/sj_server_1/miniforge3/envs/scanvi/bin/python
9
+ wait_flag=--wait
10
+ if [[ "${1:-}" == "--nowait" ]]; then wait_flag=""; shift; fi
11
+ script="$1"; shift
12
+ case "$script" in
13
+ pipeline) file=imperial_pipeline.py; tag="${1:-x}";;
14
+ assemble) file=imperial_assemble.py; tag=assemble;;
15
+ full) file=imperial_full_cells.py; tag=fullcells;;
16
+ *) echo "unknown script $script" >&2; exit 2;;
17
+ esac
18
+ unit="imperial-${tag}-$(date +%H%M%S)"
19
+ systemctl --user is-active --quiet ml-memory-guard.service
20
+ exec systemd-run --user $wait_flag --collect --quiet --unit="$unit" --slice=app.slice \
21
+ -p MemoryHigh=14G -p MemoryMax=16G -p MemorySwapMax=0 -p CPUQuota=400% \
22
+ -p OOMPolicy=kill -p OOMScoreAdjust=500 -p Nice=10 -p IOSchedulingClass=idle \
23
+ --working-directory="$RUN" \
24
+ -E CUDA_VISIBLE_DEVICES= -E OMP_NUM_THREADS=1 -E OPENBLAS_NUM_THREADS=1 -E MKL_NUM_THREADS=1 \
25
+ -E NUMEXPR_NUM_THREADS=1 -E PYTHONDONTWRITEBYTECODE=1 -E PYTHONUNBUFFERED=1 \
26
+ -p StandardOutput="append:$RUN/logs/${tag}.log" -p StandardError="append:$RUN/logs/${tag}.log" \
27
+ "$PY" "$RUN/code/$file" "$@"
paper-releases/20260928/diffusion/data/source_prep/imperial_eskd/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/imperial_eskd/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]
paper-releases/20260928/diffusion/data/source_prep/imperial_eskd/code/strict_qc_v1_code_bundle_v5/qc_finalize.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Consolidate technical file QC and identity audits without inferring identities."""
2
+ from __future__ import annotations
3
+
4
+ import csv
5
+ from collections import Counter
6
+ from datetime import datetime, timezone
7
+ import hashlib
8
+ import json
9
+ from pathlib import Path
10
+
11
+ import h5py
12
+ import numpy as np
13
+ import pandas as pd
14
+
15
+
16
+ SC_TERMINAL = {'PASS', 'PASS_QC_EXPORT_QUARANTINED', 'QUARANTINED', 'DUPLICATE_REPRESENTATION_VALIDATED'}
17
+ BULK_ORGANIZED = {'organized_with_explicit_masks', 'organized_with_numeric_quarantine', 'organized_declared_count_semantics_failed'}
18
+
19
+
20
+ def bulk_failed(record: dict) -> bool:
21
+ status = str(record.get('status', '')).lower()
22
+ return status.startswith('failed_') or status in {'failed', 'error', 'quarantined'}
23
+
24
+
25
+ def stage_coverage(root: Path, runroot: Path, bulk: list[dict], sc: list[dict]) -> dict:
26
+ """Compare terminal stage records against acquired sources and exact exports."""
27
+ from qc_singlecell import discover_libraries
28
+ issues, expected_paths = [], []
29
+ manifest = read(root / 'SOURCE_MANIFEST.json', {})
30
+ datasets = manifest.get('datasets', [])
31
+ expected_bulk = {row['bulk_accession'] for row in datasets if row.get('bulk_accession')}
32
+ expected_sc_accessions = {row['sc_accession'] for row in datasets if row.get('sc_accession')}
33
+ discovered = discover_libraries(root, runroot)
34
+ key = lambda row: (row.get('accession', ''), row.get('library_id', ''), bool(row.get('duplicate_representation')))
35
+ expected_sc = Counter(key(row) for row in discovered)
36
+ actual_sc = Counter(key(row) for row in sc)
37
+ discovered_accessions = {row['accession'] for row in discovered}
38
+ for accession in sorted(expected_sc_accessions - discovered_accessions):
39
+ issues.append({'code': 'missing_expected_sc_source_accession', 'accession': accession})
40
+ if not datasets or not expected_bulk or not bulk:
41
+ issues.append({'code': 'empty_required_bulk_inventory_or_results', 'problem': 'Expected bulk inventory and terminal results must be nonempty'})
42
+ if not discovered or not sc:
43
+ issues.append({'code': 'empty_required_sc_inventory_or_results', 'problem': 'Discovered single-cell sources and terminal results must be nonempty'})
44
+ for identity, count in expected_sc.items():
45
+ if count != 1:
46
+ issues.append({'code': 'duplicate_discovered_sc_identity', 'identity': identity, 'count': count})
47
+ if actual_sc[identity] != count:
48
+ issues.append({'code': 'sc_result_coverage_mismatch', 'identity': identity, 'expected': count, 'observed': actual_sc[identity]})
49
+ for identity, count in actual_sc.items():
50
+ if identity not in expected_sc:
51
+ issues.append({'code': 'unexpected_sc_result', 'identity': identity, 'count': count})
52
+ if count != 1:
53
+ issues.append({'code': 'duplicate_sc_result', 'identity': identity, 'count': count})
54
+ bulk_present = {row.get('accession') for row in bulk}
55
+ for accession in sorted(expected_bulk - bulk_present):
56
+ issues.append({'code': 'missing_bulk_accession_result', 'accession': accession})
57
+ for accession in sorted(bulk_present - expected_bulk, key=str):
58
+ issues.append({'code': 'unexpected_bulk_accession_result', 'accession': accession})
59
+ bulk_ids = Counter(row.get('assay_id', '') for row in bulk)
60
+ for assay, count in bulk_ids.items():
61
+ if not assay or count != 1:
62
+ issues.append({'code': 'invalid_bulk_assay_identity', 'assay': assay, 'count': count})
63
+ terminal = True
64
+ required_exports_complete = True
65
+ for record in bulk:
66
+ status, path = record.get('status', ''), record.get('harmonized_path', '')
67
+ accepted_missing = status == 'missing_bulk_expression_VCF_only' and record.get('accession') == 'GSE247706'
68
+ if status not in BULK_ORGANIZED and not bulk_failed(record) and not accepted_missing:
69
+ terminal = False
70
+ issues.append({'code': 'nonterminal_or_unknown_bulk_status', 'assay': record.get('assay_id'), 'status': status})
71
+ if status in BULK_ORGANIZED:
72
+ if not path:
73
+ issues.append({'code': 'missing_success_export_path', 'assay': record.get('assay_id')})
74
+ required_exports_complete = False
75
+ else:
76
+ expected_paths.append({'modality': 'bulk', 'assay_id': record.get('assay_id'), 'path': str(Path(path).resolve())})
77
+ if bulk_failed(record):
78
+ required_exports_complete = False
79
+ for record in sc:
80
+ status = record.get('status', '')
81
+ if status not in SC_TERMINAL:
82
+ terminal = False
83
+ issues.append({'code': 'nonterminal_or_unknown_sc_status', 'identity': key(record), 'status': status})
84
+ if record.get('duplicate_representation'):
85
+ if status != 'DUPLICATE_REPRESENTATION_VALIDATED':
86
+ required_exports_complete = False
87
+ continue
88
+ if status == 'PASS':
89
+ path = record.get('canonical_export', {}).get('path', '')
90
+ if not path:
91
+ issues.append({'code': 'missing_success_export_path', 'identity': key(record)})
92
+ required_exports_complete = False
93
+ else:
94
+ expected_paths.append({'modality': 'singlecell', 'assay_id': record.get('library_id'), 'path': str(Path(path).resolve())})
95
+ else:
96
+ required_exports_complete = False
97
+ path_counts = Counter(row['path'] for row in expected_paths)
98
+ for path, count in path_counts.items():
99
+ if count != 1:
100
+ issues.append({'code': 'duplicate_export_path', 'path': path, 'count': count})
101
+ if not Path(path).is_file():
102
+ issues.append({'code': 'missing_expected_export', 'path': path})
103
+ required_exports_complete = False
104
+ actual_paths = {str(path.resolve()) for directory in ['bulk', 'singlecell']
105
+ for path in (runroot / directory).rglob('*.h5ad')}
106
+ for path in sorted(actual_paths - set(path_counts)):
107
+ issues.append({'code': 'untracked_export_file', 'path': path})
108
+ if not expected_paths:
109
+ issues.append({'code': 'zero_expected_exports', 'problem': 'No successful required expression exports'})
110
+ required_exports_complete = False
111
+ # Inventory coverage and terminal processing are distinct from export quality.
112
+ coverage_codes = {'empty_required_bulk_inventory_or_results', 'empty_required_sc_inventory_or_results',
113
+ 'duplicate_discovered_sc_identity', 'sc_result_coverage_mismatch', 'unexpected_sc_result',
114
+ 'duplicate_sc_result', 'missing_bulk_accession_result', 'unexpected_bulk_accession_result',
115
+ 'missing_expected_sc_source_accession',
116
+ 'invalid_bulk_assay_identity', 'nonterminal_or_unknown_bulk_status', 'nonterminal_or_unknown_sc_status'}
117
+ result_coverage = not any(row['code'] in coverage_codes for row in issues)
118
+ return {'issues': issues, 'expected_exports': expected_paths,
119
+ 'expected_bulk_accessions': sorted(expected_bulk), 'expected_sc_records': sum(expected_sc.values()),
120
+ 'expected_sc_accessions': sorted(expected_sc_accessions),
121
+ 'observed_sc_records': len(sc), 'result_coverage_complete': result_coverage,
122
+ 'file_processing_finished': bool(result_coverage and terminal),
123
+ 'required_exports_complete': bool(required_exports_complete and result_coverage and not issues),
124
+ 'bulk_failures': sum(bulk_failed(row) for row in bulk),
125
+ 'bulk_numeric_quarantine': sum(row.get('status') in {'organized_with_numeric_quarantine', 'organized_declared_count_semantics_failed'} for row in bulk),
126
+ 'bulk_expression_unavailable': sum(row.get('status') == 'missing_bulk_expression_VCF_only' for row in bulk),
127
+ 'sc_quarantined': sum(row.get('status') == 'QUARANTINED' for row in sc),
128
+ 'sc_export_resource_or_semantic_quarantine': sum(row.get('status') == 'PASS_QC_EXPORT_QUARANTINED' for row in sc)}
129
+
130
+
131
+ def digest(path: Path) -> str:
132
+ value = hashlib.sha256()
133
+ with path.open('rb') as source:
134
+ for chunk in iter(lambda: source.read(4 * 1024**2), b''):
135
+ value.update(chunk)
136
+ return value.hexdigest()
137
+
138
+
139
+ def write_json(path: Path, value: object) -> None:
140
+ path.write_text(json.dumps(value, indent=2, ensure_ascii=False, default=str) + '\n')
141
+
142
+
143
+ def read(path: Path, default: object = None) -> object:
144
+ return json.loads(path.read_text()) if path.exists() else default
145
+
146
+
147
+ def scalar_column(row: dict, key: str, default: object = '') -> object:
148
+ value = row.get(key, default)
149
+ return json.dumps(value, ensure_ascii=False, default=str) if isinstance(value, (dict, list)) else value
150
+
151
+
152
+ def csv_rows(path: Path, rows: list[dict]) -> None:
153
+ if not rows:
154
+ path.write_text('status\nno_records\n')
155
+ return
156
+ fields = list(dict.fromkeys(key for row in rows for key in row))
157
+ with path.open('w', newline='') as target:
158
+ writer = csv.DictWriter(target, fieldnames=fields)
159
+ writer.writeheader()
160
+ writer.writerows({key: scalar_column(row, key) for key in fields} for row in rows)
161
+
162
+
163
+ def validate_h5ad(path: Path, canonical: list[str], require_units: bool) -> dict:
164
+ with h5py.File(path, 'r') as handle:
165
+ var = handle['var']
166
+ index = var.attrs.get('_index', '_index')
167
+ if isinstance(index, bytes):
168
+ index = index.decode()
169
+ ids = var[index].asstr()[...].tolist()
170
+ if ids != canonical:
171
+ raise ValueError('Canonical feature order mismatch')
172
+ matrix = handle['X']
173
+ shape = tuple(matrix.attrs['shape']) if isinstance(matrix, h5py.Group) else matrix.shape
174
+ if shape[1] != len(canonical):
175
+ raise ValueError('Export matrix gene dimension differs from reference')
176
+ if require_units and ('uns' not in handle or 'units' not in handle['uns']):
177
+ raise ValueError('Export units absent from standard AnnData uns')
178
+ return {'path': str(path), 'n_samples_or_cells': int(shape[0]), 'n_genes': len(ids),
179
+ 'gene_order_verified': True, 'bytes': path.stat().st_size, 'sha256': digest(path)}
180
+
181
+
182
+ def finalize(root: Path, runroot: Path) -> dict:
183
+ root, runroot = Path(root), Path(runroot)
184
+ bulk = read(runroot / 'BULK_RESULTS.json')
185
+ sc = read(runroot / 'SINGLECELL_RESULTS.json')
186
+ if not isinstance(bulk, list) or not isinstance(sc, list):
187
+ raise ValueError('Both bulk and singlecell stage result lists are required')
188
+ source = read(runroot / 'SOURCE_VERIFICATION.json', {})
189
+ extraction = read(runroot / 'EXTRACTION.json', {})
190
+ pairing = read(runroot / 'pairing_audit/PAIRING_AUDIT.json', {})
191
+ canonical = pd.read_csv(runroot / 'reference/canonical_genes.tsv', sep='\t', dtype=str)['gene_id'].tolist()
192
+ if len(canonical) != 20097 or len(set(canonical)) != len(canonical):
193
+ raise ValueError('Frozen canonical axis is not 20097 unique IDs')
194
+ reportdir = runroot / 'reports'
195
+ reportdir.mkdir(exist_ok=True)
196
+ coverage = stage_coverage(root, runroot, bulk, sc)
197
+ assay_rows, export_checks, problems = [], [], list(coverage['issues'])
198
+ for record in bulk:
199
+ row = {'modality': 'bulk', 'accession': record.get('accession'), 'assay_id': record.get('assay_id'),
200
+ 'status': record.get('status'), 'units': record.get('units'), 'samples': record.get('n_samples'),
201
+ 'source_genes': record.get('n_genes'), 'canonical_coverage': record.get('canonical_coverage'),
202
+ 'raw_integer_count_eligible': record.get('raw_count_eligible'),
203
+ 'nonfinite_values': record.get('nonfinite_values'), 'fractional_values': record.get('fractional_values'),
204
+ 'duplicate_source_rows_quarantined': record.get('duplicate_source_rows_quarantined'),
205
+ 'export_path': record.get('harmonized_path', ''), 'caveats': record.get('caveats', [])}
206
+ assay_rows.append(row)
207
+ if record.get('harmonized_path'):
208
+ try:
209
+ export_checks.append(validate_h5ad(Path(record['harmonized_path']), canonical, require_units=True))
210
+ except Exception as error:
211
+ problems.append({'assay': row['assay_id'], 'problem': str(error)})
212
+ primary_sc = [row for row in sc if not row.get('duplicate_representation')]
213
+ for record in sc:
214
+ export = record.get('canonical_export', {})
215
+ mapping = record.get('canonicalcoverage', {})
216
+ assay_rows.append({'modality': 'singlecell', 'accession': record.get('accession'),
217
+ 'assay_id': record.get('library_id'), 'status': record.get('status'),
218
+ 'units': record.get('units'), 'cells': record.get('n_cells'),
219
+ 'qc_review_pass_cells': record.get('n_qc_review_pass'),
220
+ 'source_genes': record.get('n_features'),
221
+ 'canonical_coverage': mapping.get('canonical_coverage_fraction'),
222
+ 'raw_integer_count_eligible': record.get('count_space_verified'),
223
+ 'duplicate_representation': record.get('duplicate_representation'),
224
+ 'export_path': export.get('path', ''),
225
+ 'cell_metadata_linkage': record.get('author_map_match', {}),
226
+ 'error': record.get('error', record.get('export_error', ''))})
227
+ if export.get('path'):
228
+ try:
229
+ if not export.get('mass_conservation_pass'):
230
+ raise ValueError('Selected-source = canonical + excluded mass identity failed')
231
+ export_checks.append(validate_h5ad(Path(export['path']), canonical, require_units=True))
232
+ except Exception as error:
233
+ problems.append({'assay': record['library_id'], 'problem': str(error)})
234
+ csv_rows(reportdir / 'ASSAY_QC_SUMMARY.csv', assay_rows)
235
+ samples = []
236
+ for record in primary_sc:
237
+ export = record.get('canonical_export', {})
238
+ if record.get('status') != 'PASS' or not export.get('pseudobulk_enabled') or not export.get('path'):
239
+ continue
240
+ path = Path(export['path']).parent / 'pseudobulk_sample_summary.csv'
241
+ if not path.is_file():
242
+ problems.append({'assay': record.get('library_id'), 'problem': 'Declared pseudobulk sample summary is missing'})
243
+ continue
244
+ frame = pd.read_csv(path, keep_default_na=False)
245
+ if frame.empty or 'sample_id' not in frame or frame.sample_id.duplicated().any():
246
+ problems.append({'assay': record.get('library_id'), 'problem': 'Pseudobulk sample summary is empty or has invalid/duplicate sample IDs'})
247
+ continue
248
+ frame['source_library_directory'] = str(path.parent)
249
+ frame['accession'] = path.parent.parent.name
250
+ samples.extend(frame.to_dict('records'))
251
+ csv_rows(reportdir / 'PUBLISHED_SAMPLE_AGGREGATES.csv', samples)
252
+ # Namespace sample IDs by accession; repeated libraries stay traceable.
253
+ pooled = []
254
+ if samples:
255
+ frame = pd.DataFrame(samples)
256
+ for (accession, sample_id), group in frame.groupby(['accession', 'sample_id'], sort=True):
257
+ contexts = {}
258
+ for key in ['donor_id', 'visit_id', 'protocol', 'units']:
259
+ values = group[key] if key in group else []
260
+ contexts[key] = sorted(set(str(v) for v in values if str(v) not in {'', 'unknown', 'not_published'}))
261
+ conflict = any(len(v) > 1 for v in contexts.values())
262
+ pooled.append({'accession': accession, 'sample_id': sample_id,
263
+ 'donor_id': contexts['donor_id'][0] if len(contexts['donor_id']) == 1 else '',
264
+ 'visit_id': contexts['visit_id'][0] if len(contexts['visit_id']) == 1 else '',
265
+ 'units': contexts['units'][0] if len(contexts['units']) == 1 else '',
266
+ 'protocol': contexts['protocol'][0] if len(contexts['protocol']) == 1 else '',
267
+ 'library_count': len(group), 'mapped_cells': int(group.n_cells.sum()),
268
+ 'review_pass_cells': int(group.n_qc_review_pass.sum()),
269
+ 'minimum_200_review_cells': bool(group.n_qc_review_pass.sum() >= 200),
270
+ 'minimum_1000_review_cells': bool(group.n_qc_review_pass.sum() >= 1000),
271
+ 'context_conflict': conflict, 'library_dirs': group.source_library_directory.tolist()})
272
+ if conflict:
273
+ problems.append({'sample_id': sample_id, 'accession': accession, 'problem': 'Cross-library donor/visit/protocol/unit conflict'})
274
+ csv_rows(reportdir / 'SAMPLE_QC_SUMMARY.csv', pooled)
275
+ studies = json.loads((root / 'SOURCE_MANIFEST.json').read_text())['datasets']
276
+ readiness = []
277
+ for study in studies:
278
+ sid = study['inventory_id']
279
+ b = [row for row in bulk if row.get('accession') == study.get('bulk_accession') and row.get('harmonized_path')]
280
+ c = [row for row in primary_sc if row.get('accession') == study.get('sc_accession')]
281
+ metadata = pairing.get('studies', {}).get(sid, {})
282
+ exports = [row for row in c if row.get('canonical_export', {}).get('path')]
283
+ readiness.append({'study_id': sid, 'study': study['study'], 'bulk_accession': study.get('bulk_accession'),
284
+ 'sc_accession': study.get('sc_accession'), 'bulk_export_assays': len(b),
285
+ 'sc_primary_libraries': len(c), 'sc_exported_libraries': len(exports),
286
+ 'sc_quarantined_libraries': sum(row.get('status') == 'QUARANTINED' for row in c),
287
+ 'sc_export_quarantined_libraries': sum(row.get('status') == 'PASS_QC_EXPORT_QUARANTINED' for row in c),
288
+ 'bulk_units': sorted(set(row.get('units', '') for row in b)),
289
+ 'metadata_audit': metadata, 'bulk_material': study.get('bulk_material'),
290
+ 'sc_material': study.get('sc_material'), 'caveats': study.get('caveats', []),
291
+ 'file_organization_status': 'both_sides_exported' if b and exports and len(exports) == len(c) else 'partial_or_missing_counterpart',
292
+ 'pair_use_status': 'requires_explicit_identity_material_and_unit_gates;not_inferred_from_export_success'})
293
+ csv_rows(reportdir / 'STUDY_READINESS.csv', readiness)
294
+ failures = [row for row in sc if row.get('status') == 'QUARANTINED']
295
+ bulk_failures = [row for row in bulk if bulk_failed(row)]
296
+ numeric_quality_pass = not (coverage['bulk_numeric_quarantine'] or coverage['bulk_failures'] or coverage['sc_quarantined'] or coverage['sc_export_resource_or_semantic_quarantine'])
297
+ result = {'generated_at': datetime.now(timezone.utc).isoformat(),
298
+ 'file_processing_finished': coverage['file_processing_finished'], 'source_verified': bool(source.get('complete')),
299
+ 'archive_expansion_complete': bool(extraction.get('complete')),
300
+ 'canonical_genes': len(canonical), 'bulk_records': len(bulk),
301
+ 'bulk_expression_exports': sum(bool(row.get('harmonized_path')) for row in bulk),
302
+ 'singlecell_primary_libraries': len(primary_sc),
303
+ 'singlecell_primary_cells': sum(row.get('n_cells', 0) for row in primary_sc),
304
+ 'singlecell_exported_libraries': sum(bool(row.get('canonical_export', {}).get('path')) for row in primary_sc),
305
+ 'alternate_format_validations': sum(row.get('status') == 'DUPLICATE_REPRESENTATION_VALIDATED' for row in sc),
306
+ 'quarantined_libraries': len(failures), 'bulk_failures': len(bulk_failures),
307
+ 'sc_export_quarantined_libraries': coverage['sc_export_resource_or_semantic_quarantine'],
308
+ 'bulk_numeric_quarantine': coverage['bulk_numeric_quarantine'],
309
+ 'bulk_expression_unavailable': coverage['bulk_expression_unavailable'],
310
+ 'stage_coverage': coverage,
311
+ 'required_exports_complete': coverage['required_exports_complete'],
312
+ 'file_organization_complete': bool(source.get('complete') and extraction.get('complete') and coverage['required_exports_complete'] and not problems),
313
+ 'numerical_file_quality_pass': bool(numeric_quality_pass and coverage['required_exports_complete'] and not problems),
314
+ 'export_validation_problems': problems, 'exports': export_checks,
315
+ 'technical_export_validation_pass': bool(not problems and export_checks and coverage['required_exports_complete']),
316
+ 'scope': 'File integrity, numerical representation, feature identifiers and published sample metadata only; no biological inference',
317
+ 'limits': ['Data access and unresolved sample IDs remain explicit constraints.',
318
+ 'Soft QC flags are preserved; they are not proof of biological quality.',
319
+ 'Fractional and normalized values retain original units.',
320
+ 'Missing or quarantined features are masked and are not observed zeros.']}
321
+ write_json(reportdir / 'VALIDATION.json', result)
322
+ lines = ['# PBMC 파일 QC·ID 표준화 결과', '',
323
+ f"원본 검증: {result['source_verified']}; 압축 해제: {result['archive_expansion_complete']}.",
324
+ f"Bulk 발현 결과 {result['bulk_expression_exports']}개, single-cell 기본 library {len(primary_sc)}개 중 표준 파일 {result['singlecell_exported_libraries']}개를 만들었다.",
325
+ f"모든 표준 파일은 검증된 20,097개 유전자 ID와 동일한 순서를 사용한다. Export 구조·해시 검사 문제: {len(problems)}건.", '',
326
+ '| 연구 | Bulk 결과 | sc 결과/기본 library | 시료·연결 제한 |', '|---|---:|---:|---|']
327
+ for row in readiness:
328
+ caveats = '; '.join(str(v) for v in row['caveats']).replace('|', '/')
329
+ lines.append(f"| {row['study_id']} | {row['bulk_export_assays']} | {row['sc_exported_libraries']}/{row['sc_primary_libraries']} | {caveats} |")
330
+ lines += ['', '파일 구조 검증과 분석용 pair의 적합성은 별개다. 동일 환자·시점·시료가 입증되지 않은 행은 임의로 연결하지 않았다.',
331
+ 'Count, estimated count, TPM, FPKM, log2CPM, microarray 값을 분리했으며 반올림·역변환·생물학적 의미 추론은 수행하지 않았다.',
332
+ 'Bulk는 NaN 및 source_feature_present/harmonization_valid mask로 결측과 격리를 구분한다. Sparse single-cell은 저장상 0과 별도로 var mask 및 uns의 단위·정책을 보존한다.', '',
333
+ '상세 결과: ASSAY_QC_SUMMARY.csv, STUDY_READINESS.csv, SAMPLE_QC_SUMMARY.csv, VALIDATION.json.',
334
+ '유전자 ID 근거는 ../reference/README.md, 샘플 ID 대응과 미해결 사항은 ../pairing_audit/README.md에 있다.', '']
335
+ (reportdir / 'REPORT_KO.md').write_text('\n'.join(lines))
336
+ return result