junidude14 commited on
Commit
021d7c5
·
verified ·
1 Parent(s): 26e5759

Archive 4 checkpoints (1-4)

Browse files
paper-releases/20260928/diffusion/data/source_prep/giroux2022/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
paper-releases/20260928/diffusion/data/source_prep/giroux2022/code/strict_qc_v1_code_bundle_v5/qc_genes.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Frozen model-axis gene mapping; never transforms or aggregates expression.
3
+
4
+ Only identity membership is established. An absent feature is missing, not a
5
+ measured zero. Presence in a supplied feature table is not proof that the
6
+ experiment assayed an all-zero feature (some pipelines export padded tables).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ from collections import Counter, defaultdict
12
+ import csv
13
+ from datetime import datetime, timezone
14
+ import gzip
15
+ import hashlib
16
+ import json
17
+ from pathlib import Path
18
+ import re
19
+ import shutil
20
+ from typing import Sequence
21
+
22
+ BASE = Path(__file__).resolve().parents[1]
23
+ DEFAULT_REFERENCE = BASE / "processing/strict_qc_v1_20260913/reference"
24
+ PBISC = Path("/home/sj_server_1/PBISC/immun-pbmc-fm")
25
+ CONTRACT = PBISC / "B048_test/shared/contracts/b048_baseline.json"
26
+ PARENT_REFERENCE = BASE.parent / "reference"
27
+ ENSEMBL_PATTERN = re.compile(r"^(ENSG\d{11})(?:\.(\d+))?(_PAR_Y)?$")
28
+
29
+
30
+ def sha256(path: Path) -> str:
31
+ digest = hashlib.sha256()
32
+ with path.open("rb") as handle:
33
+ for block in iter(lambda: handle.read(1024 * 1024), b""):
34
+ digest.update(block)
35
+ return digest.hexdigest()
36
+
37
+
38
+ def read_tsv(path: Path) -> list[dict[str, str]]:
39
+ opener = gzip.open if path.suffix == ".gz" else open
40
+ with opener(path, "rt", encoding="utf-8-sig", newline="") as handle:
41
+ return list(csv.DictReader(handle, delimiter="\t"))
42
+
43
+
44
+ def write_tsv(path: Path, rows: Sequence[dict], fields: Sequence[str]) -> None:
45
+ path.parent.mkdir(parents=True, exist_ok=True)
46
+ with path.open("w", encoding="utf-8", newline="") as handle:
47
+ writer = csv.DictWriter(handle, fieldnames=fields, delimiter="\t", extrasaction="ignore")
48
+ writer.writeheader()
49
+ writer.writerows(rows)
50
+
51
+
52
+ def clean_token(value: object) -> str:
53
+ if value is None:
54
+ return ""
55
+ if isinstance(value, bytes):
56
+ value = value.decode("utf-8", errors="strict")
57
+ text = str(value).strip()
58
+ return "" if text in {"", "nan", "None", "<NA>"} else text
59
+
60
+
61
+ def stable_ensembl(value: str) -> tuple[str, bool, bool]:
62
+ """Strip ONLY a numeric gene version. Preserve the locus-bearing PAR suffix."""
63
+ match = ENSEMBL_PATTERN.fullmatch(value)
64
+ if not match:
65
+ return value, False, False
66
+ return match[1] + (match[3] or ""), bool(match[2]), bool(match[3])
67
+
68
+
69
+ def split_hgnc(value: str) -> list[str]:
70
+ return [x.strip().strip('"') for x in value.split("|") if x.strip().strip('"')]
71
+
72
+
73
+ class GeneMapper:
74
+ """Map features to the exact frozen B048 panel with per-row audit evidence.
75
+
76
+ target_index == -1 means excluded/unresolved. Mapped conflicting Ensembl
77
+ IDs retain their authoritative target and set symbol_conflict=True.
78
+ Duplicate rows are never collapsed here; target_multiplicity makes later
79
+ count-only aggregation or a refusal an explicit caller decision.
80
+ """
81
+
82
+ def __init__(self, reference_dir: Path | str = DEFAULT_REFERENCE):
83
+ self.reference_dir = Path(reference_dir)
84
+ manifest_path = self.reference_dir / "REFERENCE_MANIFEST.json"
85
+ self.manifest = json.loads(manifest_path.read_text())
86
+ for item in self.manifest["frozen_files"]:
87
+ path = self.reference_dir / item["frozen_name"]
88
+ if sha256(path) != item["sha256"]:
89
+ raise ValueError(f"Frozen gene reference hash mismatch: {path}")
90
+ self._initialize(
91
+ read_tsv(self.reference_dir / "canonical_genes.tsv"),
92
+ read_tsv(self.reference_dir / "ensembl109_genes.tsv.gz"),
93
+ read_tsv(self.reference_dir / "hgnc_complete_set_frozen.tsv"),
94
+ read_tsv(self.reference_dir / "hgnc_withdrawn_frozen.tsv"),
95
+ )
96
+ if len(self.canonical) != self.manifest["canonical_gene_count"]:
97
+ raise ValueError("Canonical gene count differs from reference manifest")
98
+
99
+ @classmethod
100
+ def from_records(cls, canonical: Sequence[dict], ensembl: Sequence[dict] = (),
101
+ hgnc: Sequence[dict] = (), withdrawn: Sequence[dict] = ()) -> "GeneMapper":
102
+ """Small in-memory constructor for focused identity tests only."""
103
+ mapper = cls.__new__(cls)
104
+ mapper.reference_dir = None
105
+ mapper.manifest = {"canonical_gene_count": len(canonical)}
106
+ mapper._initialize(canonical, ensembl, hgnc, withdrawn)
107
+ return mapper
108
+
109
+ def _initialize(self, canonical: Sequence[dict], ensembl: Sequence[dict],
110
+ hgnc: Sequence[dict], withdrawn: Sequence[dict]) -> None:
111
+ self.canonical = sorted((dict(r) for r in canonical), key=lambda r: int(r["panel_index"]))
112
+ self.canonical_size = len(self.canonical)
113
+ indexes = [int(r["panel_index"]) for r in self.canonical]
114
+ if indexes != list(range(len(indexes))):
115
+ raise ValueError("Canonical panel indices must be contiguous and zero based")
116
+ self.by_id = {r["gene_id"]: r for r in self.canonical}
117
+ if len(self.by_id) != len(self.canonical):
118
+ raise ValueError("Duplicate canonical stable Ensembl gene IDs")
119
+ if any(r.get("gene_biotype") != "protein_coding" for r in self.canonical):
120
+ raise ValueError("Canonical model axis must contain only protein_coding genes")
121
+ self.info: dict[str, dict] = {}
122
+ self.canonical_symbols: dict[str, set[str]] = defaultdict(set)
123
+ self.approved_symbols: dict[str, set[str]] = defaultdict(set)
124
+ self.ensembl_symbols: dict[str, set[str]] = defaultdict(set)
125
+ self.previous_symbols: dict[str, set[str]] = defaultdict(set)
126
+ self.alias_symbols: dict[str, set[str]] = defaultdict(set)
127
+ self.withdrawn_symbols = {r.get("WITHDRAWN_SYMBOL", r.get("symbol", "")) for r in withdrawn}
128
+ self.withdrawn_symbols.discard("")
129
+ for r in ensembl:
130
+ gid = r["ensembl_gene_id"]
131
+ self.info[gid] = {"gene_id": gid, "gene_symbol": r.get("gene_name", ""),
132
+ "chromosome": r.get("seqname", ""), "gene_biotype": r.get("gene_biotype", "")}
133
+ if r.get("gene_name"):
134
+ self.ensembl_symbols[r["gene_name"]].add(gid)
135
+ for r in self.canonical:
136
+ self.info[r["gene_id"]] = r # Canonical release takes precedence for annotation.
137
+ if r.get("gene_symbol"):
138
+ self.canonical_symbols[r["gene_symbol"]].add(r["gene_id"])
139
+ for r in hgnc:
140
+ symbol = r.get("symbol", "")
141
+ if r.get("status") != "Approved":
142
+ if symbol:
143
+ self.withdrawn_symbols.add(symbol)
144
+ continue
145
+ genes = {stable_ensembl(g)[0] for g in split_hgnc(r.get("ensembl_gene_id", ""))
146
+ if ENSEMBL_PATTERN.fullmatch(g)}
147
+ if not genes:
148
+ genes = set(self.canonical_symbols.get(symbol, set()))
149
+ if not genes:
150
+ genes = {r.get("hgnc_id", "HGNC_UNMAPPED:" + symbol)}
151
+ self.approved_symbols[symbol].update(genes)
152
+ for gid in genes:
153
+ if gid not in self.info:
154
+ self.info[gid] = {"gene_id": gid, "gene_symbol": symbol,
155
+ "chromosome": "MT" if r.get("location") == "mitochondria" else "",
156
+ "gene_biotype": "protein_coding" if r.get("locus_group") == "protein-coding gene" else r.get("locus_type", "")}
157
+ if "Cytoplasmic ribosomal proteins" in r.get("gene_group", ""):
158
+ self.info[gid]["hgnc_cytoplasmic_ribosomal"] = True
159
+ for previous in split_hgnc(r.get("prev_symbol", "")):
160
+ self.previous_symbols[previous].update(genes)
161
+ for alias in split_hgnc(r.get("alias_symbol", "")):
162
+ self.alias_symbols[alias].update(genes)
163
+
164
+ def _symbol(self, symbol: str) -> tuple[set[str], str, list[str]]:
165
+ if not symbol:
166
+ return set(), "empty_symbol", []
167
+ # Multiple GENCODE loci must remain ambiguous even if older HGNC stores
168
+ # just one locus (notably the distinct X/Y PAR loci in GENCODE v49).
169
+ canonical = self.canonical_symbols.get(symbol, set())
170
+ approved = self.approved_symbols.get(symbol, set())
171
+ exact = canonical | approved
172
+ if exact:
173
+ method = "canonical_symbol" if canonical else "approved_symbol"
174
+ other = (self.previous_symbols.get(symbol, set()) | self.alias_symbols.get(symbol, set())) - exact
175
+ warnings = ["exact_symbol_also_alias_of:" + ",".join(sorted(other))] if other else []
176
+ return exact, method, warnings
177
+ if symbol in self.withdrawn_symbols:
178
+ return set(), "withdrawn_symbol", []
179
+ previous = self.previous_symbols.get(symbol, set())
180
+ aliases = self.alias_symbols.get(symbol, set())
181
+ if previous or aliases:
182
+ return previous | aliases, "previous_symbol" if previous else "alias_symbol", []
183
+ # Ensembl109 is used for all-feature QC annotation, not unchecked
184
+ # historical symbol-to-model reassignment.
185
+ legacy = self.ensembl_symbols.get(symbol, set())
186
+ if legacy:
187
+ return legacy, "ensembl109_symbol_annotation_only", []
188
+ return set(), "unmapped_symbol", []
189
+
190
+ def map_features(self, ids: Sequence[object], symbols: Sequence[object] | None = None) -> list[dict]:
191
+ if symbols is not None and len(ids) != len(symbols):
192
+ raise ValueError("Feature IDs and symbols differ in length")
193
+ rows: list[dict] = []
194
+ for index, value in enumerate(ids):
195
+ raw = clean_token(value)
196
+ supplied_symbol = clean_token(symbols[index]) if symbols is not None else ""
197
+ stable, version_stripped, par_y = stable_ensembl(raw)
198
+ ensembl = bool(ENSEMBL_PATTERN.fullmatch(raw))
199
+ evidence: list[str] = []
200
+ target = -1
201
+ conflict = False
202
+ candidates: set[str] = set()
203
+ gid = stable if ensembl else ""
204
+ if ensembl:
205
+ evidence.append("numeric_version_stripped" if version_stripped else "unversioned_ensembl")
206
+ if par_y:
207
+ status = "excluded_par_y_identity"
208
+ evidence.append("PAR_Y_preserved;assembly_crosswalk_required;never_collapse_to_X")
209
+ elif stable in self.by_id:
210
+ target = int(self.by_id[stable]["panel_index"])
211
+ status = "mapped_ensembl"
212
+ evidence.append("exact_canonical_stable_id")
213
+ elif stable in self.info:
214
+ status = "excluded_outside_canonical"
215
+ evidence.append("known_stable_id_absent_from_model_axis;no_symbol_rescue")
216
+ else:
217
+ status = "unknown_ensembl_id"
218
+ evidence.append("unknown_stable_id;no_symbol_rescue")
219
+ if supplied_symbol:
220
+ symbol_ids, method, warning = self._symbol(supplied_symbol)
221
+ evidence += warning
222
+ candidates = symbol_ids
223
+ if symbol_ids and stable not in symbol_ids:
224
+ conflict = True
225
+ evidence.append("source_id_symbol_conflict:" + ",".join(sorted(symbol_ids)))
226
+ if target >= 0:
227
+ status = "mapped_ensembl_symbol_conflict"
228
+ elif len(symbol_ids) > 1:
229
+ evidence.append("source_symbol_ambiguous_but_authoritative_id_retained")
230
+ elif not symbol_ids:
231
+ evidence.append("source_symbol_unresolved:" + method)
232
+ else:
233
+ symbol = supplied_symbol or raw
234
+ candidates, method, warnings = self._symbol(symbol)
235
+ evidence = [method] + warnings
236
+ if raw and supplied_symbol and raw != supplied_symbol:
237
+ id_candidates, _, _ = self._symbol(raw)
238
+ if id_candidates and candidates and id_candidates != candidates:
239
+ conflict = True
240
+ candidates |= id_candidates
241
+ evidence.append("two_symbol_columns_conflict;reject_union")
242
+ if len(candidates) > 1:
243
+ status = "ambiguous_symbol"
244
+ elif not candidates:
245
+ status = "excluded_withdrawn_symbol" if method == "withdrawn_symbol" else "unmapped_symbol"
246
+ else:
247
+ gid = next(iter(candidates))
248
+ if method == "ensembl109_symbol_annotation_only":
249
+ status = "excluded_legacy_symbol_annotation_only"
250
+ elif gid in self.by_id:
251
+ target = int(self.by_id[gid]["panel_index"])
252
+ status = "mapped_" + method
253
+ else:
254
+ status = "excluded_outside_canonical"
255
+ info = self.info.get(gid, {})
256
+ chromosome = str(info.get("chromosome", ""))
257
+ resolved_symbol = str(info.get("gene_symbol", ""))
258
+ mito = chromosome in {"M", "MT", "chrM", "chrMT"}
259
+ ribo = bool(info.get("hgnc_cytoplasmic_ribosomal", False)) or (
260
+ info.get("gene_biotype") == "protein_coding"
261
+ and bool(re.fullmatch(r"RP[SL](?:\d+[A-Z]*|[AP]\d*)", resolved_symbol))
262
+ )
263
+ rows.append({"source_index": index, "source_id": raw, "source_symbol": supplied_symbol,
264
+ "stable_id": stable if ensembl else gid, "target_index": target,
265
+ "target_gene_id": self.canonical[target]["gene_id"] if target >= 0 else "",
266
+ "target_gene_symbol": self.canonical[target]["gene_symbol"] if target >= 0 else "",
267
+ "status": status, "evidence": ";".join(evidence),
268
+ "candidate_ids": "|".join(sorted(candidates)),
269
+ "version_stripped": version_stripped, "par_y_suffix": par_y,
270
+ "symbol_conflict": conflict, "resolved_symbol": resolved_symbol,
271
+ "chromosome": chromosome, "source_biotype": info.get("gene_biotype", ""),
272
+ "mitochondrial": mito, "ribosomal": ribo,
273
+ "qc_annotation_resolved": bool(info)})
274
+ id_counts = Counter(r["source_id"] for r in rows if r["source_id"])
275
+ stable_counts = Counter(r["stable_id"] for r in rows if r["stable_id"])
276
+ target_counts = Counter(r["target_index"] for r in rows if r["target_index"] >= 0)
277
+ for row in rows:
278
+ row["source_id_multiplicity"] = id_counts.get(row["source_id"], 0)
279
+ row["stable_id_multiplicity"] = stable_counts.get(row["stable_id"], 0)
280
+ row["target_multiplicity"] = target_counts.get(row["target_index"], 0)
281
+ return rows
282
+
283
+ def summarize(self, rows: Sequence[dict]) -> dict:
284
+ targets = Counter(r["target_index"] for r in rows if r["target_index"] >= 0)
285
+ return {"schema": "strict_gene_mapping_summary_v1", "source_features": len(rows),
286
+ "canonical_genes": len(self.canonical), "mapped_source_features": sum(targets.values()),
287
+ "unique_canonical_features_present": len(targets),
288
+ "canonical_coverage_fraction": len(targets) / len(self.canonical) if self.canonical else 0,
289
+ "canonical_features_absent": len(self.canonical) - len(targets),
290
+ "ambiguous_features": sum(r["status"] == "ambiguous_symbol" for r in rows),
291
+ "unmapped_or_excluded_features": sum(r["target_index"] < 0 for r in rows),
292
+ "version_stripped_features": sum(r["version_stripped"] for r in rows),
293
+ "source_id_symbol_conflicts": sum(r["symbol_conflict"] for r in rows),
294
+ "duplicate_source_id_rows": sum(r["source_id_multiplicity"] > 1 for r in rows),
295
+ "duplicate_target_groups": sum(n > 1 for n in targets.values()),
296
+ "duplicate_target_rows": sum(n for n in targets.values() if n > 1),
297
+ "mitochondrial_features_source_axis": sum(r["mitochondrial"] for r in rows),
298
+ "ribosomal_features_source_axis": sum(r["ribosomal"] for r in rows),
299
+ "source_qc_annotation_unresolved_features": sum(not r["qc_annotation_resolved"] for r in rows),
300
+ "status_counts": dict(sorted(Counter(r["status"] for r in rows).items())),
301
+ "presence_mask_semantics": "source_feature_table_membership;not_detection_or_proof_of_assay_coverage",
302
+ "absent_feature_policy": "masked_missing;never_observed_zero",
303
+ "duplicate_policy": "flag_only;no_expression_aggregation_performed",
304
+ "expression_transformation": "none",
305
+ "canonical_file_sha256": self.manifest.get("canonical_panel_file_sha256"),
306
+ "canonical_identity_sha256": self.manifest.get("canonical_identity_sha256")}
307
+
308
+ def write_mapping(self, ids: Sequence[object], symbols: Sequence[object] | None = None,
309
+ output_prefix: Path | str | None = None) -> dict:
310
+ if output_prefix is None:
311
+ raise ValueError("output_prefix is required")
312
+ rows = self.map_features(ids, symbols)
313
+ return self.write_rows(rows, output_prefix)
314
+
315
+ def write_rows(self, rows: Sequence[dict], output_prefix: Path | str) -> dict:
316
+ prefix = str(output_prefix)
317
+ fields = list(rows[0]) if rows else ["source_index", "source_id", "target_index", "status", "evidence"]
318
+ write_tsv(Path(prefix + ".mapping.tsv"), rows, fields)
319
+ summary = self.summarize(rows)
320
+ Path(prefix + ".summary.json").write_text(json.dumps(summary, indent=2) + "\n")
321
+ targets = Counter(r["target_index"] for r in rows if r["target_index"] >= 0)
322
+ mask = [{"panel_index": i, "gene_id": r["gene_id"], "gene_symbol": r["gene_symbol"],
323
+ "source_feature_present": i in targets, "source_rows_mapped": targets.get(i, 0),
324
+ "missing_semantics": "" if i in targets else "not_in_supplied_feature_table;do_not_treat_as_observed_zero"}
325
+ for i, r in enumerate(self.canonical)]
326
+ write_tsv(Path(prefix + ".presence_mask.tsv"), mask,
327
+ ["panel_index", "gene_id", "gene_symbol", "source_feature_present", "source_rows_mapped", "missing_semantics"])
328
+ return summary
329
+
330
+
331
+ def freeze_reference(reference_dir: Path | str = DEFAULT_REFERENCE) -> dict:
332
+ """Freeze existing validated artifacts; no network or reference upgrade."""
333
+ import pandas as pd # Only needed once to read the 755 KB canonical parquet.
334
+
335
+ destination = Path(reference_dir)
336
+ destination.mkdir(parents=True, exist_ok=True)
337
+ contract = json.loads(CONTRACT.read_text())
338
+ panel_path = Path(contract["gene_panel_path"])
339
+ panel_hash = sha256(panel_path)
340
+ if panel_hash != contract["gene_panel_file_sha256"]:
341
+ raise ValueError("Canonical model panel differs from frozen B048 contract")
342
+ panel = pd.read_parquet(panel_path)
343
+ columns = ["gene_id", "gene_symbol", "panel_index"]
344
+ records = [{column: str(row[column]) for column in columns} for _, row in panel.iterrows()]
345
+ identity_hash = hashlib.sha256(json.dumps(records, ensure_ascii=False, sort_keys=True,
346
+ separators=(",", ":")).encode()).hexdigest()
347
+ if identity_hash != contract["gene_order_sha256"]:
348
+ raise ValueError("Ordered model identity hash differs from frozen B048 contract")
349
+ if len(panel) != 20097 or not panel.gene_id.is_unique or set(panel.gene_biotype) != {"protein_coding"}:
350
+ raise ValueError("Canonical model-axis cardinality, uniqueness, or biotype check failed")
351
+ if panel.panel_index.tolist() != list(range(20097)):
352
+ raise ValueError("Canonical parquet row order differs from its panel_index")
353
+ files = [(panel_path, "canonical_var.parquet"), (CONTRACT, "b048_baseline_contract.json"),
354
+ (PBISC / "model/vae_bulk2sc/method_1/src/method1/gene_alignment.py", "model_gene_alignment_hash_source.py"),
355
+ (BASE / "README.md", "datalake_readme_at_reference_freeze.md"),
356
+ (PARENT_REFERENCE / "ensembl/ensembl109_genes.tsv.gz", "ensembl109_genes.tsv.gz"),
357
+ (PARENT_REFERENCE / "ensembl/ensembl109_panel_stats.json", "ensembl109_panel_stats.json"),
358
+ (PARENT_REFERENCE / "hgnc/hgnc_complete_set_frozen.tsv", "hgnc_complete_set_frozen.tsv"),
359
+ (PARENT_REFERENCE / "hgnc/hgnc_withdrawn_frozen.tsv", "hgnc_withdrawn_frozen.tsv")]
360
+ frozen_files = []
361
+ for source, name in files:
362
+ target = destination / name
363
+ digest = sha256(source)
364
+ if target.exists() and sha256(target) != digest:
365
+ raise ValueError(f"Refusing to overwrite changed frozen reference: {target}")
366
+ if not target.exists():
367
+ shutil.copy2(source, target)
368
+ frozen_files.append({"source_path": str(source), "source_resolved_path": str(source.resolve()),
369
+ "frozen_name": name, "sha256": digest, "bytes": source.stat().st_size})
370
+ canonical_path = destination / "canonical_genes.tsv"
371
+ panel["target_index"] = panel["panel_index"]
372
+ canonical_columns = ["target_index", "panel_index", "gene_id", "gene_symbol", "gene_biotype", "chromosome", "start", "end"]
373
+ canonical_text = panel[canonical_columns].to_csv(sep="\t", index=False)
374
+ if canonical_path.exists() and canonical_path.read_text() != canonical_text:
375
+ raise ValueError("Refusing to overwrite changed canonical TSV")
376
+ canonical_path.write_text(canonical_text)
377
+ frozen_files.append({"source_path": str(panel_path), "frozen_name": canonical_path.name,
378
+ "sha256": sha256(canonical_path), "bytes": canonical_path.stat().st_size,
379
+ "derivation": "ordered identity/annotation columns from hash-verified canonical parquet"})
380
+ reference109 = read_tsv(destination / "ensembl109_genes.tsv.gz")
381
+ old_pc = {r["ensembl_gene_id"] for r in reference109 if r["gene_biotype"] == "protein_coding"}
382
+ canonical_ids = set(panel.gene_id)
383
+ duplicate_symbols = panel[panel.gene_symbol.duplicated(False)][canonical_columns].to_dict("records")
384
+ write_tsv(destination / "canonical_ambiguous_symbols.tsv", duplicate_symbols, canonical_columns)
385
+ compatibility = {
386
+ "canonical_genes": len(canonical_ids), "ensembl109_protein_coding_genes_all_contigs": len(old_pc),
387
+ "intersection": len(canonical_ids & old_pc), "canonical_only": len(canonical_ids - old_pc),
388
+ "ensembl109_pc_only": len(old_pc - canonical_ids),
389
+ "canonical_duplicated_symbol_groups": len({r["gene_symbol"] for r in duplicate_symbols}),
390
+ "canonical_duplicated_symbol_genes": len(duplicate_symbols),
391
+ "canonical_only_ids": sorted(canonical_ids - old_pc), "ensembl109_pc_only_ids": sorted(old_pc - canonical_ids),
392
+ "decision": "model_axis_unchanged;Ensembl109_and_HGNC_are_auxiliary_annotation_only;no_reference_upgrade"}
393
+ (destination / "COMPATIBILITY_AUDIT.json").write_text(json.dumps(compatibility, indent=2) + "\n")
394
+ manifest = {"schema": "strict_qc_gene_reference_v1", "created_at_utc": datetime.now(timezone.utc).isoformat(),
395
+ "canonical_label": "PBISC B048 GENCODE v49 protein_coding model panel",
396
+ "canonical_gene_count": len(panel), "canonical_panel_file_sha256": panel_hash,
397
+ "canonical_identity_sha256": identity_hash,
398
+ "identity_hash_serialization": "ordered {gene_id,gene_symbol,panel_index} string records;json ensure_ascii=False sort_keys=True separators=(',',':')",
399
+ "label_provenance": "local datalake README and PBISC model contract;original full GENCODE49 GTF not re-downloaded",
400
+ "auxiliary_hgnc_snapshot": "existing local frozen 2023 snapshot;not asserted current",
401
+ "frozen_files": frozen_files, "compatibility_audit": "COMPATIBILITY_AUDIT.json"}
402
+ manifest_path = destination / "REFERENCE_MANIFEST.json"
403
+ if manifest_path.exists():
404
+ previous = json.loads(manifest_path.read_text())
405
+ if previous["frozen_files"] != frozen_files:
406
+ raise ValueError("Frozen reference manifest differs; create a new version instead")
407
+ return previous
408
+ manifest_path.write_text(json.dumps(manifest, indent=2) + "\n")
409
+ return manifest
410
+
411
+
412
+ def main() -> None:
413
+ parser = argparse.ArgumentParser(description=__doc__)
414
+ parser.add_argument("--reference-dir", type=Path, default=DEFAULT_REFERENCE)
415
+ parser.add_argument("--freeze", action="store_true")
416
+ parser.add_argument("--input-tsv", type=Path)
417
+ parser.add_argument("--id-column", default="gene_id")
418
+ parser.add_argument("--symbol-column")
419
+ parser.add_argument("--output-prefix", type=Path)
420
+ args = parser.parse_args()
421
+ if args.freeze:
422
+ print(json.dumps(freeze_reference(args.reference_dir), indent=2))
423
+ if args.input_tsv:
424
+ if not args.output_prefix:
425
+ parser.error("--output-prefix required with --input-tsv")
426
+ mapper = GeneMapper(args.reference_dir)
427
+ records = read_tsv(args.input_tsv)
428
+ ids = [r[args.id_column] for r in records]
429
+ symbols = [r[args.symbol_column] for r in records] if args.symbol_column else None
430
+ print(json.dumps(mapper.write_mapping(ids, symbols, args.output_prefix), indent=2))
431
+
432
+
433
+ if __name__ == "__main__":
434
+ main()
paper-releases/20260928/diffusion/data/source_prep/giroux2022/code/strict_qc_v1_code_bundle_v5/qc_singlecell.py ADDED
@@ -0,0 +1,667 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Organize single-cell files, audit numbers and identities, export sparse H5AD.
2
+
3
+ No biological inference is performed. Original cells are retained; thresholds
4
+ are reversible annotations. Published metadata is joined on explicit keys.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from collections import Counter
9
+ import csv
10
+ import gc
11
+ import gzip
12
+ import hashlib
13
+ import json
14
+ import os
15
+ from pathlib import Path
16
+ import re
17
+ from typing import Iterator
18
+
19
+ import h5py
20
+ import numpy as np
21
+ import pandas as pd
22
+ from scipy import sparse
23
+ from scipy.io import mmread
24
+
25
+ from qc_core import QCError, _h5_column, _h5_index, _strings, _text_open, _write_json, scan_h5, scan_mtx, sha256_file
26
+ from qc_genes import GeneMapper
27
+
28
+
29
+ SC_ACCESSIONS = {"GSE132044", "GSE155673", "GSE161610", "GSE162632", "GSE198616",
30
+ "GSE201534", "GSE246937", "GSE247707", "GSE253173", "GSE314416"}
31
+ MAX_MTX_ALLOCATION_ESTIMATE = 4 * 1024**3
32
+ COUNT_SOURCE_EVIDENCE = {
33
+ "GSE132044": "Published protocol benchmark pbmc_hg38_count_matrix; read/UMI units kept separate by published barcode protocol",
34
+ "GSE155673": "Published 10x covXX RNA matrix/features/barcodes companions",
35
+ "GSE161610": "Published 10x PB patient feature-barcode count matrices",
36
+ "GSE162632": "Published Bx-cx-10X expression count matrices",
37
+ "GSE198616": "Published 10x PBMC/monocyte feature-barcode expression count matrices",
38
+ "GSE201534": "Published 10x filtered_feature_bc_matrix.h5 with independent MTX representation",
39
+ "GSE246937": "Published 10x pooled feature-barcode matrices; antibody features excluded from RNA counts",
40
+ "GSE247707": "Published 10x PBMC_Pooled feature-barcode matrix; author-filtering status separate",
41
+ "GSE314416": "Published GEX.h5 10x gene-expression counts; separate ADT files omitted",
42
+ }
43
+
44
+
45
+ def _stem(path: Path) -> str:
46
+ return re.sub(r"(?:_?count_?)?matrix\.mtx(?:\.gz)?$", "", path.name, flags=re.I).rstrip("_")
47
+
48
+
49
+ def discover_libraries(root: Path, runroot: Path) -> list[dict]:
50
+ """Find expression sources; prefer 10x H5 when matching MTX also exists."""
51
+ libraries = []
52
+ for accession in sorted(SC_ACCESSIONS):
53
+ paths = sorted({p for base in (root / "datasets" / accession / "raw", runroot / "extracted" / accession)
54
+ if base.exists() for p in base.rglob("*") if p.is_file()})
55
+ h5_sources = [p for p in paths if p.suffix.lower() in (".h5", ".h5ad") and "_adt" not in p.name.lower()]
56
+ h5_gsm = {re.search(r"GSM\d+", str(p)).group() for p in h5_sources if re.search(r"GSM\d+", str(p))}
57
+ for path in paths:
58
+ is_mtx = bool(re.search(r"matrix\.mtx(?:\.gz)?$", path.name, re.I))
59
+ if path not in h5_sources and not is_mtx:
60
+ continue
61
+ if (accession == "GSE247707" and "pbmc" not in path.name.lower()) or (accession == "GSE161610" and re.search(r"(?:_|/)LN\d", str(path))):
62
+ continue
63
+ match = re.search(r"GSM\d+", str(path))
64
+ library = match.group() if match else (_stem(path) if is_mtx else path.stem)
65
+ if not library:
66
+ library = path.parent.name
67
+ item = {"accession": accession, "library_id": library, "path": str(path),
68
+ "format": "mtx" if is_mtx else "h5", "duplicate_representation": bool(is_mtx and match and library in h5_gsm)}
69
+ if is_mtx:
70
+ prefix = _stem(path)
71
+ siblings = list(path.parent.iterdir())
72
+ feature_names = [(prefix + "_" if prefix else "") + part + suffix
73
+ for part in ("features", "genes", "gene") for suffix in (".tsv.gz", ".tsv")]
74
+ barcode_names = [(prefix + "_" if prefix else "") + part + suffix
75
+ for part in ("barcodes", "cell", "cells") for suffix in (".tsv.gz", ".tsv")]
76
+ feature = next((p for p in siblings if p.name.lower() in [n.lower() for n in feature_names]), None)
77
+ barcode = next((p for p in siblings if p.name.lower() in [n.lower() for n in barcode_names]), None)
78
+ if accession == "GSE155673":
79
+ feature = root / "datasets/GSE155673/raw/GSE155673_features.tsv.gz"
80
+ if accession == "GSE132044":
81
+ feature = root / "datasets/GSE132044/raw/GSE132044_pbmc_hg38_gene.tsv.gz"
82
+ barcode = root / "datasets/GSE132044/raw/GSE132044_pbmc_hg38_cell.tsv.gz"
83
+ item["features_path"] = str(feature) if feature else ""
84
+ item["barcodes_path"] = str(barcode) if barcode else ""
85
+ libraries.append(item)
86
+ return sorted(libraries, key=lambda item: (item["duplicate_representation"], item["accession"], item["library_id"]))
87
+
88
+
89
+ def read_axes(item: dict) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, dict]:
90
+ path = Path(item["path"])
91
+ if item["format"] == "mtx":
92
+ if not item["features_path"] or not item["barcodes_path"]:
93
+ raise QCError("Missing paired feature or barcode file")
94
+ with _text_open(item["features_path"]) as handle:
95
+ rows = [line.rstrip("\n\r").split("\t") for line in handle if line.strip()]
96
+ ids = [row[0] for row in rows]
97
+ symbols = [row[1] if len(row) > 1 else row[0] for row in rows]
98
+ if item["accession"] == "GSE132044":
99
+ ids = [value.split("_", 1)[0] for value in ids]
100
+ symbols = [row[0].split("_", 1)[1] if "_" in row[0] else row[0] for row in rows]
101
+ rna = np.asarray([len(row) < 3 or row[2] == "Gene Expression" for row in rows])
102
+ with _text_open(item["barcodes_path"]) as handle:
103
+ cells = [line.rstrip("\n\r").split("\t")[0] for line in handle if line.strip()]
104
+ return np.asarray(ids), np.asarray(symbols), np.asarray(cells), rna, {"matrix_path": None, "source": "feature/barcode companion files"}
105
+ with h5py.File(path, "r", rdcc_nbytes=256 * 1024**2) as handle:
106
+ if "matrix" in handle:
107
+ matrix = handle["matrix"]
108
+ features = matrix["features"]
109
+ ids = _strings(features["id"])
110
+ symbols = _strings(features["name"]) if "name" in features else ids
111
+ rna = _strings(features["feature_type"]) == "Gene Expression" if "feature_type" in features else np.ones(len(ids), bool)
112
+ cells = _strings(matrix["barcodes"])
113
+ return ids, symbols, cells, rna, {"matrix_path": "matrix", "source": "10x H5 embedded axes"}
114
+ matrix_path = item.get("matrix_path", "X")
115
+ var = handle["raw/var"] if matrix_path.startswith("raw/") else handle["var"]
116
+ ids = _h5_index(var)
117
+ symbols = None
118
+ for name in ("gene", "gene_symbols", "gene_symbol", "feature_name", "symbol"):
119
+ if name in var:
120
+ symbols = _h5_column(var, name)
121
+ break
122
+ if symbols is None:
123
+ symbols = ids
124
+ cells = _h5_index(handle["obs"])
125
+ return ids, symbols, cells, np.ones(len(ids), bool), {"matrix_path": matrix_path, "source": "H5AD embedded axes"}
126
+
127
+
128
+ def _read_csv(path: Path) -> pd.DataFrame:
129
+ return pd.read_csv(path, dtype=str, keep_default_na=False) if path.exists() else pd.DataFrame()
130
+
131
+
132
+ def assign_metadata(item: dict, cells: np.ndarray, runroot: Path) -> tuple[pd.DataFrame, dict]:
133
+ accession, library = item["accession"], item["library_id"]
134
+ source_cells = np.asarray(cells, dtype=str)
135
+ if np.any(np.char.strip(source_cells) == "") or len(np.unique(source_cells)) != len(source_cells):
136
+ raise QCError("Source library cell identifiers are empty or nonunique")
137
+ obs = pd.DataFrame({"barcode": source_cells, "source_barcode": source_cells,
138
+ "raw_10x_barcode": "", "author_cell_id": "", "library_id": library, "donor_id": "", "sample_id": "", "visit_id": "",
139
+ "author_retained": "unknown", "mapping_basis": "unresolved", "protocol": ""})
140
+ key_representation = "unresolved"
141
+ audit = runroot / "pairing_audit"
142
+ mapping_path = audit / (accession + "_cell_map.csv.gz")
143
+ if mapping_path.exists():
144
+ # Avoid retaining the complete project mapping across 54 pooled libraries.
145
+ pieces = []
146
+ for chunk in pd.read_csv(mapping_path, dtype=str, keep_default_na=False, chunksize=100_000):
147
+ subset = chunk[chunk.library_id == library]
148
+ if len(subset):
149
+ pieces.append(subset)
150
+ if pieces:
151
+ mapping = pd.concat(pieces, ignore_index=True)
152
+ if mapping.duplicated(["library_id", "barcode"]).any():
153
+ raise QCError("Published cell map has duplicate library+barcode keys")
154
+ raw_rows = pd.Index(mapping.barcode).get_indexer(source_cells)
155
+ author_rows = np.full(len(source_cells), -1, dtype=np.int64)
156
+ if "author_cell_id" in mapping:
157
+ nonempty = mapping.author_cell_id.astype(str).str.len() > 0
158
+ if mapping.loc[nonempty].duplicated(["library_id", "author_cell_id"]).any():
159
+ raise QCError("Published cell map has duplicate library+author_cell_id keys")
160
+ indices = np.flatnonzero(nonempty.to_numpy())
161
+ found = pd.Index(mapping.loc[nonempty, "author_cell_id"]).get_indexer(source_cells)
162
+ author_rows[found >= 0] = indices[found[found >= 0]]
163
+ both = (raw_rows >= 0) & (author_rows >= 0)
164
+ if np.any(both & (raw_rows != author_rows)):
165
+ raise QCError("Ambiguous raw-barcode/author-cell-ID representations point to different published cells")
166
+ raw_only = (raw_rows >= 0) & (author_rows < 0)
167
+ author_only = (author_rows >= 0) & (raw_rows < 0)
168
+ if raw_only.any() and author_only.any():
169
+ raise QCError("Mixed raw-barcode and author-cell-ID representations within one source library")
170
+ if author_only.any():
171
+ match_column = "author_cell_id"
172
+ key_representation = "library_id+author_cell_id"
173
+ else:
174
+ match_column = "barcode"
175
+ key_representation = "library_id+barcode" if (raw_rows >= 0).any() else "no_exact_published_key_match"
176
+ # The source string is never split, stripped, or reconstructed. Both
177
+ # accepted representations already occur explicitly in author metadata.
178
+ right = mapping.copy()
179
+ right["_source_match_key"] = right[match_column]
180
+ right = right[right._source_match_key.astype(str).str.len() > 0]
181
+ right = right.rename(columns={"barcode": "raw_10x_barcode"})
182
+ joined = obs[["library_id", "source_barcode"]].merge(
183
+ right, left_on=["library_id", "source_barcode"], right_on=["library_id", "_source_match_key"],
184
+ how="left", validate="one_to_one", sort=False)
185
+ for column in obs.columns:
186
+ if column in joined and column not in ("barcode", "source_barcode", "library_id"):
187
+ obs[column] = joined[column].fillna("unknown" if column == "author_retained" else "")
188
+ for column in ("cell_type", "author_cell_id", "author_pool_id"):
189
+ if column in joined:
190
+ obs[column] = joined[column].fillna("")
191
+ elif accession == "GSE155673":
192
+ pairs = _read_csv(audit / "D02_covid_pairs.csv")
193
+ number = re.search(r"cov_?(\d+)", Path(item["path"]).name, re.I)
194
+ if number and len(pairs):
195
+ labels = pairs.sc_title.str.extract(r"cov_?(\d+)", expand=False).astype(int)
196
+ selected = pairs[labels == int(number.group(1))]
197
+ if len(selected) == 1:
198
+ row = selected.iloc[0]
199
+ obs["library_id"] = row.sc_gsm
200
+ item["published_library_id"] = row.sc_gsm
201
+ obs["donor_id"], obs["sample_id"] = row.subject, row.sc_title
202
+ obs["visit_id"] = row.get("day_since_symptoms", "")
203
+ obs["mapping_basis"] = "published library identity in D02_covid_pairs.csv"
204
+ elif accession in ("GSE198616", "GSE201534", "GSE161610"):
205
+ inventory = _read_csv(audit / (accession + "_published_sample_inventory.csv"))
206
+ selected = inventory[inventory.gsm == library] if len(inventory) else inventory
207
+ if len(selected) == 1:
208
+ title = selected.iloc[0].title
209
+ obs["sample_id"] = title
210
+ obs["mapping_basis"] = "published unpooled GEO library/sample label; bulk linkage remains separate"
211
+ if accession == "GSE201534":
212
+ match = re.fullmatch(r"(.+)_Day(\d+)", title)
213
+ if match:
214
+ obs["donor_id"], obs["visit_id"] = match.group(1), "GEO_Day" + match.group(2)
215
+ if accession == "GSE161610":
216
+ obs["donor_id"] = title
217
+ elif accession == "GSE132044":
218
+ pairs = _read_csv(audit / "H03_ding_pairs.csv")
219
+ for _, row in pairs.iterrows():
220
+ selected = np.char.startswith(cells.astype(str), row.sc_cell_id_prefix)
221
+ obs.loc[selected, "protocol"] = [value.split(".")[1] if len(value.split(".")) > 1 else "" for value in cells[selected]]
222
+ # Protocols measure different numeric units; never aggregate across them.
223
+ obs.loc[selected, "sample_id"] = row.sample_id + "|" + obs.loc[selected, "protocol"]
224
+ obs.loc[selected, "mapping_basis"] = "published specimen prefix; protocol retained separately"
225
+ elif accession == "GSE253173":
226
+ with h5py.File(item["path"], "r") as handle:
227
+ for source, target in (("LibraryName", "published_LibraryName"), ("Timepoint", "published_Timepoint")):
228
+ if source in handle["obs"]:
229
+ obs[target] = _h5_column(handle["obs"], source)
230
+ crosswalk = _read_csv(audit / "GSE253173_library_map.csv")
231
+ if len(crosswalk) and "published_LibraryName" in obs:
232
+ key = "LibraryName" if "LibraryName" in crosswalk else "published_LibraryName"
233
+ if crosswalk[key].duplicated().any():
234
+ raise QCError("DREAM published library crosswalk has duplicate keys")
235
+ indexed = crosswalk.set_index(key)
236
+ for column in ("donor_id", "sample_id", "visit_id"):
237
+ if column in indexed:
238
+ obs[column] = obs.published_LibraryName.map(indexed[column]).fillna("")
239
+ obs.loc[obs.sample_id != "", "mapping_basis"] = "published DREAM library crosswalk"
240
+ matched = obs.sample_id.astype(str).str.len() > 0
241
+ return obs, {"n_cells": len(obs), "mapped_sample_cells": int(matched.sum()),
242
+ "unresolved_sample_cells": int((~matched).sum()), "full_sample_mapping": bool(matched.all()),
243
+ "donor_resolved_cells": int((obs.donor_id.astype(str).str.len() > 0).sum()),
244
+ "n_published_samples": int(obs.loc[matched, "sample_id"].nunique()),
245
+ "source_key_representation": key_representation,
246
+ "join_policy": "exact published keys only; no expression or row-order inference"}
247
+
248
+
249
+ def _mtx_dimensions(path: Path) -> tuple[int, int, int]:
250
+ with _text_open(path) as handle:
251
+ next(handle)
252
+ for line in handle:
253
+ if line.strip() and not line.startswith("%"):
254
+ return tuple(map(int, line.split()))
255
+ raise QCError("Missing matrix dimensions")
256
+
257
+
258
+ def _mtx_entries(path: Path):
259
+ """Iterate already-audited coordinates; no matrix allocation."""
260
+ with _text_open(path) as handle:
261
+ next(handle)
262
+ for line in handle:
263
+ if line.strip() and not line.lstrip().startswith("%"):
264
+ break # dimensions
265
+ for line in handle:
266
+ if line.strip() and not line.lstrip().startswith("%"):
267
+ fields = line.split()
268
+ if len(fields) != 3:
269
+ raise QCError("MTX source changed or malformed during export")
270
+ yield int(fields[0]) - 1, int(fields[1]) - 1, float(fields[2])
271
+
272
+
273
+ def _mtx_cell_ordered(path: Path) -> bool:
274
+ previous = -1
275
+ for _, cell, _ in _mtx_entries(path):
276
+ if cell < previous:
277
+ return False
278
+ previous = cell
279
+ return True
280
+
281
+
282
+ def _stream_mtx_cells(path: Path, n_features: int, n_cells: int, block_cells: int):
283
+ start, previous, seen = 0, -1, 0
284
+ rows, genes, values = [], [], []
285
+ for gene, cell, value in _mtx_entries(path):
286
+ if cell < previous or not (0 <= gene < n_features and 0 <= cell < n_cells):
287
+ raise QCError("MTX coordinate order/bounds changed during streaming export")
288
+ previous = cell
289
+ seen += 1
290
+ while cell >= min(start + block_cells, n_cells):
291
+ stop = min(start + block_cells, n_cells)
292
+ yield start, sparse.csr_matrix((values, (rows, genes)), shape=(stop - start, n_features), dtype=np.float64)
293
+ start = stop
294
+ rows, genes, values = [], [], []
295
+ rows.append(cell - start)
296
+ genes.append(gene)
297
+ values.append(value)
298
+ expected = _mtx_dimensions(path)[2]
299
+ if seen != expected:
300
+ raise QCError(f"MTX nnz changed during streaming export: {seen} vs {expected}")
301
+ while start < n_cells:
302
+ stop = min(start + block_cells, n_cells)
303
+ yield start, sparse.csr_matrix((values, (rows, genes)), shape=(stop - start, n_features), dtype=np.float64)
304
+ start = stop
305
+ rows, genes, values = [], [], []
306
+
307
+
308
+ def source_blocks(item: dict, n_features: int, n_cells: int, block_cells: int = 256) -> Iterator[tuple[int, sparse.csr_matrix]]:
309
+ """Yield cells×source_features sparse blocks; cap full-MTX sparse allocation."""
310
+ path = Path(item["path"])
311
+ if item["format"] == "mtx":
312
+ _, _, nnz = _mtx_dimensions(path)
313
+ estimate = nnz * 96 + (n_cells + n_features) * 32
314
+ if estimate > MAX_MTX_ALLOCATION_ESTIMATE:
315
+ if not _mtx_cell_ordered(path):
316
+ raise QCError(f"Canonical MTX export resource quarantine: unsorted coordinates and conservative allocation estimate {estimate} exceeds 4 GiB")
317
+ item["source_iteration"] = "verified cell-column-ordered MTX streaming"
318
+ yield from _stream_mtx_cells(path, n_features, n_cells, block_cells)
319
+ return
320
+ item["source_iteration"] = "bounded sparse MTX load below conservative 4 GiB allocation estimate"
321
+ matrix = mmread(path).tocsc()
322
+ if matrix.shape != (n_features, n_cells):
323
+ raise QCError("MTX dimensions changed after audit")
324
+ for start in range(0, n_cells, block_cells):
325
+ yield start, matrix[:, start:start + block_cells].T.tocsr()
326
+ return
327
+ with h5py.File(path, "r", rdcc_nbytes=256 * 1024**2) as handle:
328
+ item["source_iteration"] = "backed HDF5 cell blocks"
329
+ tenx = "matrix" in handle
330
+ matrix = handle["matrix" if tenx else item.get("matrix_path", "X")]
331
+ if isinstance(matrix, h5py.Dataset):
332
+ for start in range(0, n_cells, block_cells):
333
+ yield start, sparse.csr_matrix(matrix[start:start + block_cells, :])
334
+ return
335
+ encoding = matrix.attrs.get("encoding-type", "")
336
+ if isinstance(encoding, bytes):
337
+ encoding = encoding.decode()
338
+ if not tenx and encoding != "csr_matrix":
339
+ raise QCError("H5AD canonical export requires cell-major CSR; non-CSR input remains QC-only")
340
+ # Retain dataset handles: the HDF5 raw chunk cache belongs to each
341
+ # open dataset. Reopening matrix["data"] per block discards the cache.
342
+ data_dataset, index_dataset, pointer_dataset = matrix["data"], matrix["indices"], matrix["indptr"]
343
+ for start in range(0, n_cells, block_cells):
344
+ stop = min(start + block_cells, n_cells)
345
+ pointers = np.asarray(pointer_dataset[start:stop + 1], dtype=np.int64)
346
+ first, last = int(pointers[0]), int(pointers[-1])
347
+ pointers -= first
348
+ data = np.asarray(data_dataset[first:last])
349
+ indices = np.asarray(index_dataset[first:last])
350
+ yield start, sparse.csr_matrix((data, indices, pointers), shape=(stop - start, n_features))
351
+
352
+
353
+ def _h5_array(group, name: str, values) -> None:
354
+ values = np.asarray(values)
355
+ if values.dtype.kind in "OUS":
356
+ dataset = group.create_dataset(name, data=values.astype(object), dtype=h5py.string_dtype("utf-8"))
357
+ dataset.attrs["encoding-type"], dataset.attrs["encoding-version"] = "string-array", "0.2.0"
358
+ else:
359
+ dataset = group.create_dataset(name, data=values)
360
+ dataset.attrs["encoding-type"], dataset.attrs["encoding-version"] = "array", "0.2.0"
361
+
362
+
363
+ def _h5_dataframe(parent, name: str, columns: dict, index: np.ndarray) -> None:
364
+ group = parent.create_group(name)
365
+ group.attrs["encoding-type"], group.attrs["encoding-version"] = "dataframe", "0.2.0"
366
+ group.attrs["_index"] = "_index"
367
+ group.attrs["column-order"] = np.asarray(list(columns), dtype=h5py.string_dtype())
368
+ _h5_array(group, "_index", index)
369
+ for column, values in columns.items():
370
+ _h5_array(group, column, values)
371
+
372
+
373
+ def _h5_scalar(group, name: str, value: str | bool) -> None:
374
+ if isinstance(value, str):
375
+ dataset = group.create_dataset(name, data=value, dtype=h5py.string_dtype("utf-8"))
376
+ dataset.attrs["encoding-type"] = "string"
377
+ else:
378
+ dataset = group.create_dataset(name, data=value)
379
+ dataset.attrs["encoding-type"] = "numeric-scalar"
380
+ dataset.attrs["encoding-version"] = "0.2.0"
381
+
382
+
383
+ def validate_sample_context(obs: pd.DataFrame, aggregation_mask: np.ndarray) -> dict[str, dict]:
384
+ """Reject contextual collisions; retain missing metadata explicitly as empty.
385
+
386
+ A published sample can be valid without a disclosed donor identity. Missing
387
+ context is not filled from another record; only consistent, published values
388
+ are recorded in the aggregate metadata.
389
+ """
390
+ contexts = {}
391
+ for sample, rows in obs.loc[aggregation_mask].groupby("sample_id", sort=True):
392
+ context = {}
393
+ for field in ("donor_id", "visit_id", "protocol"):
394
+ values = rows[field].astype(str).str.strip() if field in rows else pd.Series("", index=rows.index)
395
+ observed = sorted(set(values[~values.isin(["", "unknown", "not_published"])]))
396
+ if len(observed) > 1:
397
+ raise QCError(f"Conflicting {field} within published sample {sample!r}: {observed}")
398
+ context[field] = observed[0] if observed else ""
399
+ context[field + "_missing_cells"] = int(values.isin(["", "unknown", "not_published"]).sum())
400
+ contexts[str(sample)] = context
401
+ return contexts
402
+
403
+
404
+ def canonical_export(item: dict, out: Path, mapping: list[dict], canonical: list[dict],
405
+ obs: pd.DataFrame, rna: np.ndarray, *, verified_counts: bool, units: str,
406
+ full_mapping: bool) -> dict:
407
+ """Write canonical CSR incrementally; prove mapped/excluded mass accounting."""
408
+ target = np.asarray([row["target_index"] for row in mapping], dtype=np.int64)
409
+ target[~rna] = -1
410
+ present = np.zeros(len(canonical), dtype=bool)
411
+ present[target[target >= 0]] = True
412
+ ambiguous_candidate = np.zeros(len(canonical), dtype=bool)
413
+ canonical_index = {row["gene_id"]: index for index, row in enumerate(canonical)}
414
+ for row, is_rna in zip(mapping, rna):
415
+ if is_rna and "ambiguous" in row.get("status", ""):
416
+ for candidate in row.get("candidate_ids", "").split("|"):
417
+ if candidate in canonical_index:
418
+ ambiguous_candidate[canonical_index[candidate]] = True
419
+ multiplicity = Counter(target[target >= 0])
420
+ collision = np.asarray([value >= 0 and multiplicity[value] > 1 for value in target])
421
+ if not verified_counts:
422
+ target[collision] = -1
423
+ harmonization_valid = np.zeros(len(canonical), dtype=bool)
424
+ harmonization_valid[target[target >= 0]] = True
425
+ reducer = sparse.csr_matrix((np.ones(np.sum(target >= 0)),
426
+ (np.flatnonzero(target >= 0), target[target >= 0])),
427
+ shape=(len(mapping), len(canonical)))
428
+ destination = out / "canonical.h5ad"
429
+ temporary = out / "canonical.h5ad.partial"
430
+ qcpass = np.load(out / "metrics/flag_conservative_review_pass.npy", mmap_mode="r")
431
+ cell_total = np.load(out / "metrics/cell_total.npy", mmap_mode="r")
432
+ observed_mass = excluded_mass = exported_mass = 0.0
433
+ mapped = obs.sample_id.astype(str).str.len().to_numpy() > 0
434
+ author_retained = obs.get("author_retained", pd.Series("unknown", index=obs.index)).astype(str).str.lower().isin(["true", "1", "yes"]).to_numpy()
435
+ aggregation_mask = mapped & (np.ones(len(obs), bool) if full_mapping else author_retained)
436
+ samples = sorted(obs.loc[aggregation_mask, "sample_id"].unique()) if verified_counts else []
437
+ sample_contexts = validate_sample_context(obs, aggregation_mask) if samples else {}
438
+ sample_index = {value: i for i, value in enumerate(samples)}
439
+ pseudobulk = np.zeros((2, len(samples), len(canonical)), dtype=np.float64)
440
+ sample_n = np.zeros((2, len(samples)), dtype=np.int64)
441
+ sample_source_mass = np.zeros((2, len(samples)), dtype=np.float64)
442
+ pseudobulk_enabled = bool(samples)
443
+ non_rna = np.flatnonzero(~rna)
444
+ with h5py.File(temporary, "w") as handle:
445
+ handle.attrs["encoding-type"], handle.attrs["encoding-version"] = "anndata", "0.1.0"
446
+ handle.attrs["source_path"] = item["path"]
447
+ handle.attrs["numeric_units"] = units
448
+ handle.attrs["missing_gene_semantics"] = "Zero storage with source_feature_present=False means absent from or unresolved in the supplied feature table; assay coverage is unknown"
449
+ handle.attrs["duplicate_gene_policy"] = "sum mapped collisions in verified count space" if verified_counts else "exclude all colliding source features"
450
+ x = handle.create_group("X")
451
+ x.attrs["encoding-type"], x.attrs["encoding-version"] = "csr_matrix", "0.1.0"
452
+ x.attrs["shape"] = [len(obs), len(canonical)]
453
+ data = x.create_dataset("data", shape=(0,), maxshape=(None,), dtype="f8", chunks=(250_000,), compression="gzip", compression_opts=1)
454
+ indices = x.create_dataset("indices", shape=(0,), maxshape=(None,), dtype="i4", chunks=(250_000,), compression="gzip", compression_opts=1)
455
+ indptr = x.create_dataset("indptr", shape=(len(obs) + 1,), dtype="i8")
456
+ indptr[0] = 0
457
+ auxiliary = handle.create_group("obsm")
458
+ auxiliary.attrs["encoding-type"], auxiliary.attrs["encoding-version"] = "dict", "0.1.0"
459
+ if len(non_rna):
460
+ auxiliary_counts = auxiliary.create_dataset("source_non_rna_counts", shape=(len(obs), len(non_rna)),
461
+ dtype="f8", chunks=(min(256, len(obs)), len(non_rna)),
462
+ compression="gzip", compression_opts=1)
463
+ auxiliary_counts.attrs["encoding-type"], auxiliary_counts.attrs["encoding-version"] = "array", "0.2.0"
464
+ cursor = 0
465
+ for start, source in source_blocks(item, len(mapping), len(obs)):
466
+ stop = start + source.shape[0]
467
+ source = source.astype(np.float64, copy=False)
468
+ if len(non_rna):
469
+ auxiliary_counts[start:stop] = source[:, non_rna].toarray()
470
+ if not np.all(np.isfinite(source.data)) or np.any(source.data < 0):
471
+ raise QCError("Export source changed or failed nonnegative finite invariant")
472
+ numeric_total = np.asarray(source[:, rna].sum(axis=1)).ravel()
473
+ if not np.allclose(numeric_total, cell_total[start:stop], rtol=1e-10, atol=1e-8):
474
+ raise QCError("Per-cell source mass disagrees with independent QC scan")
475
+ transformed = (source @ reducer).tocsr()
476
+ transformed.sum_duplicates()
477
+ transformed.eliminate_zeros()
478
+ transformed.sort_indices()
479
+ kept = np.asarray(transformed.sum(axis=1)).ravel()
480
+ removed = np.asarray(source[:, rna & (target < 0)].sum(axis=1)).ravel()
481
+ if not np.allclose(numeric_total, kept + removed, rtol=1e-10, atol=1e-8):
482
+ raise QCError("Canonical export mass conservation failed")
483
+ observed_mass += float(numeric_total.sum())
484
+ exported_mass += float(kept.sum())
485
+ excluded_mass += float(removed.sum())
486
+ end = cursor + transformed.nnz
487
+ data.resize((end,)); indices.resize((end,))
488
+ data[cursor:end], indices[cursor:end] = transformed.data, transformed.indices
489
+ indptr[start + 1:stop + 1] = transformed.indptr[1:] + cursor
490
+ cursor = end
491
+ if pseudobulk_enabled:
492
+ block_samples = obs.sample_id.iloc[start:stop].to_numpy()
493
+ block_eligible = aggregation_mask[start:stop]
494
+ for sample in np.unique(block_samples[block_eligible]):
495
+ s = sample_index[sample]
496
+ all_mask = (block_samples == sample) & block_eligible
497
+ for selection, mask in enumerate((all_mask, all_mask & qcpass[start:stop])):
498
+ pseudobulk[selection, s] += np.asarray(transformed[mask].sum(axis=0)).ravel()
499
+ sample_n[selection, s] += int(mask.sum())
500
+ sample_source_mass[selection, s] += float(numeric_total[mask].sum())
501
+ obs_columns = {column: obs[column].to_numpy() for column in obs.columns}
502
+ for flag in sorted((out / "metrics").glob("flag_*.npy")):
503
+ obs_columns[flag.stem] = np.load(flag, mmap_mode="r")
504
+ for metric in ("cell_total", "cell_detected", "cell_mito_percent"):
505
+ obs_columns[metric] = np.load(out / "metrics" / (metric + ".npy"), mmap_mode="r")
506
+ # Source barcodes are unique within this source matrix; library stays a column.
507
+ _h5_dataframe(handle, "obs", obs_columns, obs.barcode.to_numpy())
508
+ _h5_dataframe(handle, "var", {"gene_symbol": np.asarray([row["gene_symbol"] for row in canonical]),
509
+ "source_feature_present": present,
510
+ "harmonization_valid": harmonization_valid,
511
+ "source_ambiguous_candidate": ambiguous_candidate}, np.asarray([row["gene_id"] for row in canonical]))
512
+ for name in ("varm", "obsp", "varp", "layers", "uns"):
513
+ group = handle.create_group(name)
514
+ group.attrs["encoding-type"], group.attrs["encoding-version"] = "dict", "0.1.0"
515
+ if len(non_rna):
516
+ _h5_array(handle["uns"], "source_non_rna_feature_ids", [mapping[i]["source_id"] for i in non_rna])
517
+ _h5_array(handle["uns"], "source_non_rna_feature_symbols", [mapping[i]["source_symbol"] for i in non_rna])
518
+ source_sha = item.get("source_sha256") or sha256_file(item["path"])
519
+ canonical_sha = item.get("canonical_identity_sha256") or hashlib.sha256(json.dumps(
520
+ [{"panel_index": str(i), "gene_id": row["gene_id"], "gene_symbol": row["gene_symbol"]}
521
+ for i, row in enumerate(canonical)], sort_keys=True, separators=(",", ":")).encode()).hexdigest()
522
+ metadata = {"units": units, "source_path": str(Path(item["path"]).resolve()), "source_sha256": source_sha,
523
+ "source_matrix_path": str(item.get("matrix_path") or "MatrixMarket coordinate table"),
524
+ "canonical_identity_sha256": canonical_sha,
525
+ "raw_count_eligible": verified_counts,
526
+ "count_provenance": COUNT_SOURCE_EVIDENCE.get(item.get("accession", ""), "Source count provenance not established") if verified_counts else "Source count provenance not established; integer-valued entries alone are insufficient",
527
+ "source_feature_present_semantics": "True if an RNA feature in the supplied source table maps uniquely to this canonical gene before collision quarantine; not assay coverage or expression detection",
528
+ "harmonization_valid_semantics": "True if canonical values may be used after mapping and duplicate-collision quarantine; false values are storage zeros, not observed zero expression",
529
+ "source_ambiguous_candidate_semantics": "True if a source feature has this canonical gene among its unresolved ambiguous candidates; no expression assigned",
530
+ "missing_gene_semantics": "source_feature_present=False means absent from or unresolved in the supplied feature table, not proof of an unmeasured assay feature",
531
+ "duplicate_policy": "Sum only in verified count space; otherwise retain pre-quarantine presence and set harmonization_valid=False for collided targets",
532
+ "expression_transform": "canonical gene mapping only; source units unchanged; all original cells retained",
533
+ "aggregation_context_json": json.dumps(sample_contexts, sort_keys=True)}
534
+ for name, value in metadata.items():
535
+ _h5_scalar(handle["uns"], name, value)
536
+ handle.flush()
537
+ os.replace(temporary, destination)
538
+ if pseudobulk_enabled:
539
+ rows = []
540
+ with h5py.File(out / "pseudobulk_per_published_sample.h5", "w") as handle:
541
+ _h5_array(handle, "sample_id", samples)
542
+ _h5_array(handle, "gene_id", [row["gene_id"] for row in canonical])
543
+ handle["source_feature_present"] = present
544
+ handle["harmonization_valid"] = harmonization_valid
545
+ handle["all_mapped_cells_sum"] = pseudobulk[0]
546
+ handle["qc_review_pass_cells_sum"] = pseudobulk[1]
547
+ handle["n_cells"] = sample_n
548
+ handle["source_total_mass"] = sample_source_mass
549
+ handle.attrs["units"] = units
550
+ handle.attrs["aggregation"] = "SUM; no averaging, normalization or donor imputation"
551
+ for sample, i in sample_index.items():
552
+ context = sample_contexts[str(sample)]
553
+ rows.append({"sample_id": sample, **context, "n_cells": int(sample_n[0, i]),
554
+ "n_qc_review_pass": int(sample_n[1, i]), "all_source_mass": float(sample_source_mass[0, i]),
555
+ "all_canonical_mass": float(pseudobulk[0, i].sum()), "units": units})
556
+ pd.DataFrame(rows).to_csv(out / "pseudobulk_sample_summary.csv", index=False)
557
+ return {"path": str(destination), "n_canonical_genes": len(canonical), "n_present": int(present.sum()),
558
+ "source_iteration": item.get("source_iteration", ""),
559
+ "n_harmonization_valid": int(harmonization_valid.sum()), "n_ambiguous_candidates": int(ambiguous_candidate.sum()),
560
+ "canonical_valid_fraction": float(harmonization_valid.mean()),
561
+ "non_rna_auxiliary_features": len(non_rna), "non_rna_storage": "obsm/source_non_rna_counts; uns/source_non_rna_feature_ids; no cell assignment inferred" if len(non_rna) else None,
562
+ "canonical_coverage_fraction": float(present.mean()), "excluded_collision_features": int(collision.sum()) if not verified_counts else 0,
563
+ "source_selected_mass": observed_mass, "canonical_mass": exported_mass, "excluded_mass": excluded_mass,
564
+ "mass_conservation_pass": bool(np.isclose(observed_mass, exported_mass + excluded_mass, rtol=1e-10, atol=1e-8)),
565
+ "pseudobulk_enabled": pseudobulk_enabled,
566
+ "aggregation_population": "all cells with complete published assignment" if full_mapping else "author_retained_mapped_subset",
567
+ "aggregation_eligible_cells": int(aggregation_mask.sum()) if verified_counts else 0,
568
+ "aggregation_excluded_unassigned_cells": int((~mapped).sum()),
569
+ "aggregation_excluded_other_cells": int((mapped & ~aggregation_mask).sum()),
570
+ "pseudobulk_reason": "verified counts and exact published cell-to-sample assignment for every included cell" if pseudobulk_enabled else "requires verified count units and an explicitly assigned author-retained population"}
571
+
572
+
573
+ def run_singlecell(root: str | Path, runroot: str | Path) -> list[dict]:
574
+ root, runroot = Path(root), Path(runroot)
575
+ mapper = GeneMapper(runroot / "reference")
576
+ output = runroot / "singlecell"
577
+ output.mkdir(parents=True, exist_ok=True)
578
+ summaries = []
579
+ for item in discover_libraries(root, runroot):
580
+ accession, library = item["accession"], item["library_id"]
581
+ suffix = "__mtx_validation" if item["duplicate_representation"] else ""
582
+ out = output / accession / (library + suffix)
583
+ out.mkdir(parents=True, exist_ok=True)
584
+ summary_path = out / "summary.json"
585
+ if summary_path.exists():
586
+ previous = json.loads(summary_path.read_text())
587
+ if previous.get("status") in ("PASS", "PASS_QC_EXPORT_QUARANTINED", "DUPLICATE_REPRESENTATION_VALIDATED"):
588
+ summaries.append(previous)
589
+ continue
590
+ summary = {**item, "status": "RUNNING", "output_dir": str(out)}
591
+ _write_json(summary_path, summary)
592
+ print(json.dumps({"stage": "singlecell", "library": library, "accession": accession, "event": "start"}), flush=True)
593
+ try:
594
+ ids, symbols, cells, rna, axes = read_axes(item)
595
+ item["matrix_path"] = axes["matrix_path"]
596
+ mapping = mapper.map_features(ids, symbols)
597
+ mapping_summary = mapper.write_rows(mapping, out / "gene_mapping")
598
+ mito = np.asarray([row["mitochondrial"] for row in mapping])
599
+ obs, linkage = assign_metadata(item, cells, runroot)
600
+ obs.to_csv(out / "cell_metadata.csv.gz", index=False, compression="gzip")
601
+ metrics = out / "metrics"
602
+ if (metrics / "qc_summary.json").exists():
603
+ qc = json.loads((metrics / "qc_summary.json").read_text())
604
+ elif item["format"] == "mtx":
605
+ qc = scan_mtx(item["path"], metrics, mito_mask=mito, feature_mask=rna,
606
+ sample_ids=obs.sample_id.where(obs.sample_id != "", "unresolved_library").to_numpy(),
607
+ feature_ids=ids, feature_symbols=symbols, cell_ids=cells)
608
+ else:
609
+ qc = scan_h5(item["path"], metrics, matrix_path=axes["matrix_path"], mito_mask=mito, feature_mask=rna,
610
+ sample_ids=obs.sample_id.where(obs.sample_id != "", "unresolved_library").to_numpy())
611
+ total = np.load(metrics / "cell_total.npy", mmap_mode="r")
612
+ detected = np.load(metrics / "cell_detected.npy", mmap_mode="r")
613
+ mito_pct = np.load(metrics / "cell_mito_percent.npy", mmap_mode="r")
614
+ sensitivity = [{"min_genes": genes, "min_abundance": 500, "max_mito_percent": threshold,
615
+ "n_review_pass": int(((detected >= genes) & (total >= 500) & (mito_pct <= threshold)).sum())}
616
+ for genes in (100, 200, 500) for threshold in (10, 20, 30)]
617
+ pd.DataFrame(sensitivity).to_csv(out / "threshold_sensitivity.csv", index=False)
618
+ # The file/format provenance supports counts, then numeric evidence
619
+ # verifies it. An integer-valued arbitrary H5AD X alone is insufficient.
620
+ tenx_provenance = accession in COUNT_SOURCE_EVIDENCE and (axes["matrix_path"] == "matrix" or item["format"] == "mtx")
621
+ integral = qc["numeric"]["integer_fraction_selected_stored"] == 1
622
+ item["source_sha256"] = qc["input"].get("sha256", "")
623
+ item["canonical_identity_sha256"] = mapper.manifest.get("canonical_identity_sha256", "")
624
+ verified_counts = tenx_provenance and integral
625
+ units = "UMI_counts" if verified_counts and accession != "GSE132044" else "protocol_specific_read_or_UMI_counts" if verified_counts else "nonnegative_abundance_source_units_unproven"
626
+ summary.update({"published_library_id": item.get("published_library_id", library),
627
+ "n_cells": len(cells), "n_features": len(ids), "n_qc_review_pass": qc["flag_counts"]["conservative_review_pass"],
628
+ "numeric": qc["numeric"], "units": units, "count_space_verified": verified_counts,
629
+ "count_provenance": COUNT_SOURCE_EVIDENCE[accession] if verified_counts else "count interpretation unavailable; integer values alone insufficient",
630
+ "canonicalcoverage": mapping_summary, "author_map_match": linkage,
631
+ "source_axes": axes, "biological_interpretation": "none; file and numeric audit only"})
632
+ if item["duplicate_representation"]:
633
+ primary = output / accession / library / "metrics"
634
+ comparison = {name: bool(np.array_equal(np.load(metrics / (name + ".npy")), np.load(primary / (name + ".npy"))))
635
+ for name in ("cell_total", "cell_detected", "gene_total", "gene_detected")}
636
+ comparison["feature_ids"] = (metrics / "feature_ids.tsv").read_bytes() == (primary / "feature_ids.tsv").read_bytes()
637
+ comparison["cell_ids"] = (metrics / "cell_ids.tsv").read_bytes() == (primary / "cell_ids.tsv").read_bytes()
638
+ if not all(comparison.values()):
639
+ raise QCError(f"Alternate MTX/H5 representation differs: {comparison}")
640
+ summary.update(status="DUPLICATE_REPRESENTATION_VALIDATED", comparison=comparison,
641
+ comparison_limit="axes and exact gene/cell marginals agree; full elementwise identity not asserted")
642
+ else:
643
+ try:
644
+ export = canonical_export(item, out, mapping, mapper.canonical, obs, rna,
645
+ verified_counts=verified_counts, units=units,
646
+ full_mapping=linkage["full_sample_mapping"])
647
+ summary.update(status="PASS", canonical_export=export)
648
+ except QCError as error:
649
+ summary.update(status="PASS_QC_EXPORT_QUARANTINED", export_error=str(error))
650
+ except Exception as error:
651
+ summary.update(status="QUARANTINED", error_type=type(error).__name__, error=str(error))
652
+ _write_json(summary_path, summary)
653
+ summaries.append(summary)
654
+ _write_json(output / "SINGLECELL_SUMMARY.json", {"libraries": summaries, "complete": False})
655
+ print(json.dumps({"stage": "singlecell", "library": library, "event": "finish", "status": summary["status"]}), flush=True)
656
+ gc.collect()
657
+ _write_json(output / "SINGLECELL_SUMMARY.json", {"libraries": summaries, "complete": True})
658
+ return summaries
659
+
660
+
661
+ if __name__ == "__main__":
662
+ import argparse
663
+ parser = argparse.ArgumentParser()
664
+ parser.add_argument("root", type=Path)
665
+ parser.add_argument("runroot", type=Path)
666
+ args = parser.parse_args()
667
+ run_singlecell(args.root, args.runroot)
paper-releases/20260928/diffusion/data/source_prep/giroux2022/code/strict_qc_v1_code_bundle_v5/qc_validate_outputs.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent bounded inspection of standardized data files and masks."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ from datetime import datetime, timezone
6
+ import hashlib
7
+ import json
8
+ from pathlib import Path
9
+
10
+ import h5py
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+ from qc_finalize import stage_coverage
15
+
16
+ SCAN_CHUNK_ENTRIES = 1_000_000
17
+
18
+
19
+ def sha256(path: Path) -> str:
20
+ digest = hashlib.sha256()
21
+ with path.open('rb') as stream:
22
+ for block in iter(lambda: stream.read(4 * 1024**2), b''):
23
+ digest.update(block)
24
+ return digest.hexdigest()
25
+
26
+
27
+ def inspect_export(path: Path, canonical: list[str]) -> dict:
28
+ with h5py.File(path, 'r') as h:
29
+ var, obs, matrix = h['var'], h['obs'], h['X']
30
+ ids = var[var.attrs.get('_index', '_index')].asstr()[...].tolist()
31
+ if ids != canonical:
32
+ raise ValueError('Feature axis differs from frozen canonical identity/order')
33
+ if 'units' not in h['uns']:
34
+ raise ValueError('Units unavailable through standard AnnData uns')
35
+ obs_index = obs[obs.attrs.get('_index', '_index')]
36
+ shape = tuple(matrix.attrs['shape']) if isinstance(matrix, h5py.Group) else matrix.shape
37
+ if shape != (len(obs_index), len(canonical)):
38
+ raise ValueError('X dimensions differ from declared obs/var')
39
+ if isinstance(matrix, h5py.Group):
40
+ if matrix.attrs.get('encoding-type') != 'csr_matrix':
41
+ raise ValueError('Canonical sparse export must use cells-by-genes CSR')
42
+ for key in ['source_feature_present', 'harmonization_valid']:
43
+ if key not in var:
44
+ raise ValueError(f'Sparse var lacks {key}')
45
+ present, valid = var['source_feature_present'][...], var['harmonization_valid'][...]
46
+ if present.shape != (shape[1],) or valid.shape != (shape[1],):
47
+ raise ValueError('Feature mask dimensions differ from canonical gene axis')
48
+ if present.dtype.kind != 'b' or valid.dtype.kind != 'b' or np.any(valid & ~present):
49
+ raise ValueError('Feature masks are not boolean or valid is not subset of present')
50
+ if not all(name in matrix for name in ['data', 'indices', 'indptr']):
51
+ raise ValueError('CSR required vectors missing')
52
+ if any(matrix[name].ndim != 1 for name in ['data', 'indices', 'indptr']):
53
+ raise ValueError('CSR vectors must be one-dimensional')
54
+ if matrix['indptr'].dtype.kind not in 'iu' or matrix['indices'].dtype.kind not in 'iu':
55
+ raise ValueError('CSR indptr and indices must have integer dtypes')
56
+ if matrix['data'].dtype.kind not in 'iuf':
57
+ raise ValueError('CSR data must be real numeric abundance')
58
+ pointers = matrix['indptr'][...]
59
+ nnz = len(matrix['data'])
60
+ if len(matrix['indices']) != nnz or len(pointers) != shape[0] + 1 or pointers[0] != 0 or pointers[-1] != nnz:
61
+ raise ValueError('CSR vector dimensions or endpoints invalid')
62
+ if np.any(pointers < 0) or np.any(pointers > nnz):
63
+ raise ValueError('CSR indptr outside data bounds')
64
+ # Pairwise comparison is safe for unsigned integers; np.diff wraps.
65
+ if np.any(pointers[1:] < pointers[:-1]):
66
+ raise ValueError('CSR indptr not monotone')
67
+ pointers = pointers.astype(np.int64, copy=False)
68
+ total = 0.0
69
+ absolute_total = 0.0
70
+ previous_index = None
71
+ for start in range(0, nnz, SCAN_CHUNK_ENTRIES):
72
+ index = matrix['indices'][start:start + SCAN_CHUNK_ENTRIES]
73
+ values = matrix['data'][start:start + SCAN_CHUNK_ENTRIES]
74
+ if np.any(index < 0) or np.any(index >= shape[1]) or np.any(~valid[index]):
75
+ raise ValueError('Sparse expression references invalid/unmapped gene index')
76
+ if not np.all(np.isfinite(values)) or np.any(values < 0):
77
+ raise ValueError('Sparse abundance contains nonfinite/negative values')
78
+ first_row = int(np.searchsorted(pointers, start, side='right') - 1)
79
+ last_row = int(np.searchsorted(pointers, start + len(index) - 1, side='right') - 1)
80
+ if previous_index is not None and start != pointers[first_row] and index[0] <= previous_index:
81
+ raise ValueError('CSR indices are not strictly sorted/unique within a row across chunks')
82
+ nonincreasing = index[1:] <= index[:-1]
83
+ boundaries = pointers[first_row + 1:last_row + 1] - start
84
+ boundaries = boundaries[(boundaries > 0) & (boundaries < len(index))]
85
+ nonincreasing[boundaries - 1] = False
86
+ if np.any(nonincreasing):
87
+ raise ValueError('CSR indices are not strictly sorted/unique within a row')
88
+ previous_index = index[-1]
89
+ if 'raw_count_eligible' in h['uns'] and bool(h['uns/raw_count_eligible'][()]):
90
+ if np.any(values != np.floor(values)):
91
+ raise ValueError('Count-eligible sparse export contains fractional abundance')
92
+ total += float(np.sum(values, dtype=np.float64))
93
+ absolute_total += float(np.sum(np.abs(values), dtype=np.float64))
94
+ mask_scope = 'gene axis'
95
+ valid_entries = int(valid.sum())
96
+ else:
97
+ layers = h['layers']
98
+ for key in ['source_feature_present', 'harmonization_valid']:
99
+ if key not in layers or layers[key].shape != shape or layers[key].dtype.kind != 'b':
100
+ raise ValueError(f'Invalid dense per-sample {key} layer')
101
+ valid_entries, total, absolute_total = 0, 0.0, 0.0
102
+ for start in range(0, shape[0], 32):
103
+ values = matrix[start:start + 32]
104
+ present = layers['source_feature_present'][start:start + 32]
105
+ valid = layers['harmonization_valid'][start:start + 32]
106
+ if np.any(valid & ~present) or np.any(~np.isfinite(values[valid])):
107
+ raise ValueError('Dense mask subset/finite-value invariant failed')
108
+ if not np.all(np.isnan(values[~valid])):
109
+ raise ValueError('Dense unavailable/quarantined feature must remain NaN')
110
+ if 'raw_count_eligible' in h['uns'] and bool(h['uns/raw_count_eligible'][()]):
111
+ counted = values[valid]
112
+ if np.any(counted < 0) or np.any(counted != np.floor(counted)):
113
+ raise ValueError('Count-eligible dense export contains negative/fractional abundance')
114
+ valid_entries += int(valid.sum())
115
+ total += float(np.sum(values[valid], dtype=np.float64))
116
+ absolute_total += float(np.sum(np.abs(values[valid]), dtype=np.float64))
117
+ nnz, mask_scope = None, 'sample by gene'
118
+ return {'path': str(path), 'shape': [int(value) for value in shape], 'stored_sparse_entries': nnz,
119
+ 'valid_mask_entries': valid_entries, 'mask_scope': mask_scope,
120
+ 'numeric_sum_source_units': total, 'numeric_absolute_sum_source_units': absolute_total, 'bytes': path.stat().st_size,
121
+ 'sha256': sha256(path), 'status': 'PASS'}
122
+
123
+
124
+ def validate(runroot: Path, root: Path | None = None) -> dict:
125
+ runroot = Path(runroot)
126
+ root = Path(root) if root is not None else runroot.parent.parent
127
+ canonical = pd.read_csv(runroot / 'reference/canonical_genes.tsv', sep='\t', dtype=str)['gene_id'].tolist()
128
+ def stage_records(name: str) -> list[dict]:
129
+ path = runroot / name
130
+ value = json.loads(path.read_text()) if path.is_file() else []
131
+ return value if isinstance(value, list) else []
132
+ bulk_records, sc_records = stage_records('BULK_RESULTS.json'), stage_records('SINGLECELL_RESULTS.json')
133
+ coverage = stage_coverage(root, runroot, bulk_records, sc_records)
134
+ expected_totals = {}
135
+ for row in sc_records:
136
+ export = row.get('canonical_export', {})
137
+ if export.get('path') and export.get('canonical_mass') is not None:
138
+ expected_totals[export['path']] = (float(export['canonical_mass']), 'singlecell_producer_canonical_mass')
139
+ for row in bulk_records:
140
+ if not row.get('harmonized_path'):
141
+ continue
142
+ metrics_path = Path(row['harmonized_path']).parent / 'source_gene_metrics.csv'
143
+ if metrics_path.exists() and row.get('nonfinite_values', 0) == 0:
144
+ metrics = pd.read_csv(metrics_path)
145
+ required = {'target_index', 'duplicate_target_quarantined', 'absolute_mass_across_samples'}
146
+ if required.issubset(metrics):
147
+ quarantined = metrics.duplicate_target_quarantined.astype(str).str.lower().isin(['true', '1'])
148
+ selected = (metrics.target_index >= 0) & ~quarantined
149
+ expected_totals[row['harmonized_path']] = (float(metrics.loc[selected, 'absolute_mass_across_samples'].sum()), 'bulk_source_feature_absolute_mass')
150
+ results = []
151
+ expected = sorted({row['path'] for row in coverage['expected_exports']})
152
+ for path in expected:
153
+ try:
154
+ checked = inspect_export(Path(path), canonical)
155
+ if path in expected_totals:
156
+ expected_mass, basis = expected_totals[path]
157
+ actual = checked['numeric_absolute_sum_source_units']
158
+ if not np.isclose(actual, expected_mass, rtol=1e-10, atol=1e-8):
159
+ raise ValueError(f'Independent exported value total differs from producer/source record: {actual} vs {expected_mass}')
160
+ checked.update(producer_value_total_verified=True, expected_absolute_mass=expected_mass, value_total_basis=basis)
161
+ else:
162
+ checked['producer_value_total_verified'] = False
163
+ results.append(checked)
164
+ except Exception as error:
165
+ results.append({'path': str(path), 'status': 'FAIL', 'error': str(error)})
166
+ print(json.dumps(results[-1]), flush=True)
167
+ coverage_failures = list(coverage['issues'])
168
+ if not coverage['required_exports_complete'] and not coverage_failures:
169
+ coverage_failures.append({'code': 'exports_incomplete_due_to_failed_or_quarantined_records',
170
+ 'problem': 'Terminal processing includes missing/failed/quarantined required exports'})
171
+ report = {'checked_at': datetime.now(timezone.utc).isoformat(),
172
+ 'scope': 'Independent file-layout, every-value/index, mask and canonical-axis audit; not biological interpretation',
173
+ 'files': len(results), 'passed': sum(r['status'] == 'PASS' for r in results),
174
+ 'failed': sum(r['status'] == 'FAIL' for r in results) + len(coverage_failures), 'results': results,
175
+ 'stage_coverage': coverage, 'coverage_failures': coverage_failures,
176
+ 'expected_export_files': len(expected),
177
+ 'validation_pass': bool(results and all(row['status'] == 'PASS' for row in results) and not coverage_failures),
178
+ 'auditor_sha256': sha256(Path(__file__))}
179
+ out = runroot / 'reports/INDEPENDENT_VALIDATION.json'
180
+ out.parent.mkdir(exist_ok=True)
181
+ out.write_text(json.dumps(report, indent=2) + '\n')
182
+ return report
183
+
184
+
185
+ if __name__ == '__main__':
186
+ parser = argparse.ArgumentParser()
187
+ parser.add_argument('runroot', type=Path)
188
+ parser.add_argument('--root', type=Path)
189
+ args = parser.parse_args()
190
+ result = validate(args.runroot, args.root)
191
+ raise SystemExit(1 if result['failed'] else 0)