File size: 22,006 Bytes
d09695b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
#!/usr/bin/env python3
"""Conservative ontology mapping for HESRT metadata.

Maps source-preserving normalized metadata to:
- UBERON / Plant Ontology for anatomy/tissue
- MONDO for disease
- NCBI Taxonomy for organism

Only unique lexical identity matches and a small set of source-validated aliases
are accepted automatically. Original metadata values are never overwritten.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import re
import unicodedata
from collections import Counter
from pathlib import Path
from typing import Any

import pandas as pd

ROOT = Path(__file__).resolve().parents[2]
DEFAULT_RELEASE = ROOT / "standardized_data/releases/hesrt-hf-20260917-v1"
DEFAULT_WORK = DEFAULT_RELEASE / "work/ontology_mapping_v1"
DEFAULT_CATALOG = DEFAULT_RELEASE / "public/releases/2026-09-17/catalog.parquet"

CONTROL_OR_NON_DISEASE = {
    "normal": "control label",
    "healthy": "control label",
    "control": "control label",
    "reference": "control/reference label",
    "non-diabetic": "control/risk-state label",
    "non-diabetic single autoantibody positive": "risk-state label, not a disease identity",
    "non-diabetic multiple autoantibody positive": "risk-state label, not a disease identity",
    "ngt": "normal glucose tolerance phenotype",
    "cci": "controlled cortical impact procedure/injury model",
    "ir surgery": "intervention label",
}

CURATED_DISEASE: dict[str, dict[str, str]] = {
    "MS": {
        "id": "MONDO:0005301",
        "label": "multiple sclerosis",
        "reason": "GSE174647 title/summary explicitly expand MS as multiple sclerosis",
        "source": "NCBI GEO GSE174647 checked 2026-09-18",
    },
    "CD": {
        "id": "MONDO:0005011",
        "label": "Crohn disease",
        "reason": "GSE283945 title/summary explicitly describe Crohn's disease",
        "source": "NCBI GEO GSE283945 checked 2026-09-18",
    },
    "cSCC": {
        "id": "MONDO:0002529",
        "label": "skin squamous cell carcinoma",
        "reason": "GSE144239 title/summary explicitly describe cutaneous squamous cell carcinoma",
        "source": "NCBI GEO GSE144239 checked 2026-09-18",
    },
}

CURATED_TISSUE: dict[str, dict[str, str]] = {
    "brain cortex": {
        "id": "UBERON:0000956",
        "label": "cerebral cortex",
        "reason": "UBERON lists 'brain cortex' as a related synonym of cerebral cortex",
    },
    "entorhinal cortex (ERC)": {
        "id": "UBERON:0002728",
        "label": "entorhinal cortex",
        "reason": "parenthetical acronym retained in source label; anatomy term is explicit",
    },
    "dorsal root ganglia": {
        "id": "UBERON:0000044",
        "label": "dorsal root ganglion",
        "reason": "plural source label corresponds to UBERON dorsal root ganglion",
    },
    "mouse brain": {
        "id": "UBERON:0000955",
        "label": "brain",
        "reason": "species modifier stripped; sample organism is checked separately",
    },
    "human coronary artery": {
        "id": "UBERON:0001621",
        "label": "coronary artery",
        "reason": "species modifier stripped; anatomy term is explicit",
    },
    "normal colon": {
        "id": "UBERON:0001155",
        "label": "colon",
        "reason": "control-state modifier stripped; anatomy term is explicit",
    },
    "Skin punch biopsy": {
        "id": "UBERON:0000014",
        "label": "zone of skin",
        "reason": "biopsy specimen explicitly identifies skin as anatomical source",
    },
    "coronal brain section": {
        "id": "UBERON:0000955",
        "label": "brain",
        "reason": "section/orientation modifiers stripped; anatomy term is explicit",
    },
    "Coronal brain section": {
        "id": "UBERON:0000955",
        "label": "brain",
        "reason": "section/orientation modifiers stripped; anatomy term is explicit",
    },
    "left hemisphere mice brain": {
        "id": "UBERON:0000955",
        "label": "brain",
        "reason": "laterality/species modifiers stripped; anatomy term is explicit",
    },
    "Lumbar spinal cord (L3/L4)": {
        "id": "UBERON:0002240",
        "label": "spinal cord",
        "reason": "regional modifier stripped; spinal cord is explicit",
    },
    "Postmortem temporal cortex": {
        "id": "UBERON:0016538",
        "label": "temporal cortex",
        "reason": "postmortem modifier stripped; anatomy term is explicit",
    },
    "Whole skin": {
        "id": "UBERON:0000014",
        "label": "zone of skin",
        "reason": "whole-specimen modifier stripped; skin is explicit",
    },
    "brain (hypothalamus)": {
        "id": "UBERON:0001898",
        "label": "hypothalamus",
        "reason": "more specific anatomy is explicit in parentheses",
    },
}

# Frozen exact NCBI Taxonomy lookups, queried with the Scientific Name field on
# 2026-09-18. Multi-species values are represented as multiple IDs.
NCBITAXON = {
    "Ambystoma mexicanum": ["8296"],
    "Anolis carolinensis": ["28377"],
    "Canis lupus familiaris": ["9615"],
    "Ciona intestinalis": ["7719"],
    "Columba livia": ["8932"],
    "Dugesia japonica": ["6161"],
    "Electrophorus voltai": ["2609070"],
    "Gallus gallus": ["9031"],
    "Homo sapiens": ["9606"],
    "Homo sapiens; Mus musculus": ["9606", "10090"],
    "Macaca mulatta": ["9544"],
    "Mchenga conophoros": ["35575"],
    "Medicago truncatula": ["3880"],
    "Mesocricetus auratus": ["10036"],
    "Mus musculus": ["10090"],
    "Oryctolagus cuniculus": ["9986"],
    "Rattus norvegicus": ["10116"],
    "Sus scrofa": ["9823"],
    "Taeniopygia guttata": ["59729"],
    "Takifugu alboplumbeus": ["433688"],
    "Xenopus laevis": ["8355"],
    "human skin metagenome": ["539655"],
}


def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as handle:
        for block in iter(lambda: handle.read(8 * 1024**2), b""):
            h.update(block)
    return h.hexdigest()


def norm(value: str) -> str:
    text = unicodedata.normalize("NFKC", str(value)).casefold()
    text = text.replace("’", "'").replace("–", "-").replace("—", "-")
    return " ".join(text.split())


def lexical_norm(value: str) -> str:
    """Normalize punctuation without erasing biologically meaningful +/- signs."""
    text = unicodedata.normalize("NFKD", str(value)).casefold().replace("’", "'")
    text = re.sub(r"(?<=\w)-(?=\w)", " ", text)
    text = text.replace("'", "")
    text = re.sub(r"[^\w+\-]+", " ", text)
    return " ".join(text.split())


def parse_obo(path: Path, prefix: str, ontology: str) -> dict[str, Any]:
    terms: dict[str, dict[str, Any]] = {}
    current: dict[str, Any] = {}

    def flush() -> None:
        if (
            current.get("id", "").startswith(prefix)
            and current.get("name")
            and not current.get("obsolete")
        ):
            terms[current["id"]] = {
                "id": current["id"],
                "name": current["name"],
                "synonyms": list(current.get("synonyms", [])),
                "ontology": ontology,
            }

    with path.open(errors="replace") as handle:
        for raw in handle:
            line = raw.rstrip("\n")
            if line == "[Term]":
                flush()
                current = {}
                continue
            if line.startswith("["):
                flush()
                current = {}
                continue
            if line.startswith("id: "):
                current["id"] = line[4:]
            elif line.startswith("name: "):
                current["name"] = line[6:]
            elif line == "is_obsolete: true":
                current["obsolete"] = True
            elif line.startswith("synonym: "):
                match = re.match(r'synonym: "(.*?)" (EXACT|BROAD|NARROW|RELATED)', line)
                if match:
                    current.setdefault("synonyms", []).append(
                        {"text": match.group(1), "scope": match.group(2)}
                    )
    flush()

    exact: dict[str, set[str]] = {}
    lexical: dict[str, set[str]] = {}
    for term_id, term in terms.items():
        entries = [(term["name"], "label")] + [
            (item["text"], "exact_synonym")
            for item in term["synonyms"]
            if item["scope"] == "EXACT"
        ]
        for text, _ in entries:
            exact.setdefault(norm(text), set()).add(term_id)
            lexical.setdefault(lexical_norm(text), set()).add(term_id)
    return {
        "terms": terms,
        "exact": exact,
        "lexical": lexical,
        "path": str(path),
        "sha256": sha256_file(path),
    }


def choose_unique(index: dict[str, set[str]], key: str) -> str | None:
    ids = index.get(key, set())
    return next(iter(ids)) if len(ids) == 1 else None


def ontology_match(
    value: Any,
    ontology: dict[str, Any],
    *,
    allow_lexical: bool = False,
) -> dict[str, Any]:
    if value is None or (isinstance(value, float) and pd.isna(value)):
        return {
            "id": None,
            "label": None,
            "ontology": None,
            "status": "missing_source_value",
            "match_type": None,
            "note": None,
        }
    text = str(value).strip()
    exact_ids = ontology["exact"].get(norm(text), set())
    exact_id = next(iter(exact_ids)) if len(exact_ids) == 1 else None
    if exact_id:
        term = ontology["terms"][exact_id]
        match_type = "exact_label" if norm(term["name"]) == norm(text) else "exact_synonym"
        return {
            "id": exact_id,
            "label": term["name"],
            "ontology": term["ontology"],
            "status": "mapped",
            "match_type": match_type,
            "note": None,
        }
    if len(exact_ids) > 1:
        return {
            "id": None, "label": None, "ontology": None, "status": "ambiguous",
            "match_type": "ambiguous_exact", "note": "; ".join(sorted(exact_ids)),
        }
    if allow_lexical:
        lexical_ids = ontology["lexical"].get(lexical_norm(text), set())
        lexical_id = next(iter(lexical_ids)) if len(lexical_ids) == 1 else None
        if lexical_id:
            term = ontology["terms"][lexical_id]
            return {
                "id": lexical_id,
                "label": term["name"],
                "ontology": term["ontology"],
                "status": "mapped",
                "match_type": "punctuation_normalized_exact",
                "note": None,
            }
        if len(lexical_ids) > 1:
            return {
                "id": None, "label": None, "ontology": None, "status": "ambiguous",
                "match_type": "ambiguous_punctuation_normalized_exact",
                "note": "; ".join(sorted(lexical_ids)),
            }
    return {
        "id": None,
        "label": None,
        "ontology": None,
        "status": "unmapped",
        "match_type": None,
        "note": None,
    }


def map_tissue(value: Any, organism: Any, uberon: dict[str, Any], po: dict[str, Any]) -> dict[str, Any]:
    if value is None or (isinstance(value, float) and pd.isna(value)):
        return ontology_match(value, uberon)
    text = str(value).strip()
    org = "" if organism is None or pd.isna(organism) else str(organism)

    # Plant Ontology is preferred for known plant samples.
    if org == "Medicago truncatula":
        result = ontology_match(text, po, allow_lexical=True)
        if result["status"] == "mapped":
            return result

    result = ontology_match(text, uberon, allow_lexical=True)
    if result["status"] == "mapped":
        return result

    if text in CURATED_TISSUE:
        item = CURATED_TISSUE[text]
        # Guard species-specific rewrites against incompatible samples.
        if text == "mouse brain" and org != "Mus musculus":
            return result
        if text == "human coronary artery" and org != "Homo sapiens":
            return result
        return {
            "id": item["id"],
            "label": item["label"],
            "ontology": "UBERON",
            "status": "mapped",
            "match_type": "curated_anatomy_phrase",
            "note": item["reason"],
        }
    return result


def map_disease(value: Any, organism: Any, mondo: dict[str, Any]) -> dict[str, Any]:
    if value is None or (isinstance(value, float) and pd.isna(value)):
        return ontology_match(value, mondo)
    text = str(value).strip()
    key = norm(text)

    if key in CONTROL_OR_NON_DISEASE:
        return {
            "id": None,
            "label": None,
            "ontology": None,
            "status": "control_or_non_disease",
            "match_type": "curated_non_disease_state",
            "note": CONTROL_OR_NON_DISEASE[key],
        }

    result = ontology_match(text, mondo, allow_lexical=True)
    if result["status"] == "mapped":
        return result

    if text in CURATED_DISEASE:
        item = CURATED_DISEASE[text]
        return {
            "id": item["id"],
            "label": item["label"],
            "ontology": "MONDO",
            "status": "mapped",
            "match_type": "source_validated_alias",
            "note": item["reason"] + "; " + item["source"],
        }

    # A few source labels carry an explicit parenthetical acronym. Only strip
    # a frozen allow-list where the remaining full phrase is an ontology term.
    parenthetical = {
        "Psoriasis (PsO)": "psoriasis",
        "Biliary tract cancer (BTC)": "biliary tract cancer",
        "Diabetic Kidney Disease (DKD)": "diabetic kidney disease",
        "Psoriatic Arthritis (PsA)": "psoriatic arthritis",
        "Acute Kidney Injury (AKI)": "acute kidney injury",
    }
    if text in parenthetical:
        base = parenthetical[text]
        base_result = ontology_match(base, mondo, allow_lexical=True)
        if base_result["status"] == "mapped":
            base_result["match_type"] = "parenthetical_acronym_stripped_exact"
            base_result["note"] = f"mapped full disease phrase after stripping source acronym from {text!r}"
            return base_result

    # Human context resolves the single observed MONDO ambiguity for multiple
    # myeloma: the alternative term is explicitly non-human-animal.
    if text.casefold() == "multiple myeloma" and str(organism) == "Homo sapiens":
        return {
            "id": "MONDO:0009693",
            "label": "plasma cell myeloma",
            "ontology": "MONDO",
            "status": "mapped",
            "match_type": "human_context_disambiguation",
            "note": "human sample; rejected MONDO non-human-animal alternative",
        }

    return result


def map_organism(value: Any) -> dict[str, Any]:
    if value is None or (isinstance(value, float) and pd.isna(value)):
        return {
            "ids": None,
            "labels": None,
            "status": "missing_source_value",
            "match_type": None,
        }
    text = str(value).strip()
    ids = NCBITAXON.get(text)
    if not ids:
        return {"ids": None, "labels": None, "status": "unmapped", "match_type": None}
    labels = [part.strip() for part in text.split(";")]
    return {
        "ids": "; ".join(f"NCBITaxon:{taxid}" for taxid in ids),
        "labels": "; ".join(labels),
        "status": "mapped",
        "match_type": "exact_scientific_name" if len(ids) == 1 else "multi_taxon_exact",
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--catalog", type=Path, default=DEFAULT_CATALOG)
    parser.add_argument("--work-dir", type=Path, default=DEFAULT_WORK)
    parser.add_argument("--output-catalog", type=Path)
    args = parser.parse_args()

    catalog_path = args.catalog.resolve()
    work = args.work_dir.resolve()
    ont = work / "ontologies"
    work.mkdir(parents=True, exist_ok=True)

    uberon = parse_obo(ont / "uberon.obo", "UBERON:", "UBERON")
    mondo = parse_obo(ont / "mondo.obo", "MONDO:", "MONDO")
    po = parse_obo(ont / "po.obo", "PO:", "PO")

    frame = pd.read_parquet(catalog_path)
    before_columns = list(frame.columns)
    before_gsm = frame["gsm_id"].astype(str).tolist()
    output_rows: list[dict[str, Any]] = []

    for row in frame.itertuples(index=False):
        tissue = map_tissue(row.tissue, row.organism, uberon, po)
        disease = map_disease(row.disease, row.organism, mondo)
        organism = map_organism(row.organism)
        output_rows.append({
            "gsm_id": row.gsm_id,
            "tissue_ontology_id": tissue["id"],
            "tissue_ontology_label": tissue["label"],
            "tissue_ontology": tissue["ontology"],
            "tissue_ontology_status": tissue["status"],
            "tissue_ontology_match_type": tissue["match_type"],
            "tissue_ontology_note": tissue["note"],
            "disease_ontology_id": disease["id"],
            "disease_ontology_label": disease["label"],
            "disease_ontology": disease["ontology"],
            "disease_ontology_status": disease["status"],
            "disease_ontology_match_type": disease["match_type"],
            "disease_ontology_note": disease["note"],
            "organism_ontology_ids": organism["ids"],
            "organism_ontology_labels": organism["labels"],
            "organism_ontology_status": organism["status"],
            "organism_ontology_match_type": organism["match_type"],
        })

    mapping = pd.DataFrame(output_rows)
    assert len(mapping) == len(frame) == 4468
    assert mapping.gsm_id.is_unique
    assert mapping.gsm_id.astype(str).tolist() == before_gsm

    merged = frame.merge(mapping, on="gsm_id", how="left", validate="one_to_one", sort=False)
    assert merged[before_columns].equals(frame[before_columns])

    mapping.to_parquet(work / "ontology_mapping.parquet", index=False, compression="zstd")
    mapping.to_csv(work / "ontology_mapping.csv", index=False)
    merged.to_parquet(work / "catalog.ontology-mapped.parquet", index=False, compression="zstd")
    merged.to_csv(work / "catalog.ontology-mapped.csv", index=False)

    unresolved_rows: list[dict[str, Any]] = []
    for field, status_col in [
        ("tissue", "tissue_ontology_status"),
        ("disease", "disease_ontology_status"),
        ("organism", "organism_ontology_status"),
    ]:
        tmp = merged[[field, status_col]].copy()
        tmp = tmp[tmp[field].notna()]
        grouped = tmp.groupby([field, status_col], dropna=False).size().reset_index(name="samples")
        for item in grouped.to_dict("records"):
            if item[status_col] != "mapped":
                unresolved_rows.append({
                    "field": field,
                    "value": item[field],
                    "status": item[status_col],
                    "samples": int(item["samples"]),
                })
    unresolved = pd.DataFrame(unresolved_rows)
    if not unresolved.empty:
        unresolved = unresolved.sort_values(["field", "samples", "value"], ascending=[True, False, True])
    unresolved.to_csv(work / "unresolved_terms.csv", index=False)

    summary = {
        "schema_version": "hesrt-ontology-mapping-v1",
        "input_catalog": str(catalog_path),
        "input_catalog_sha256": sha256_file(catalog_path),
        "samples": len(frame),
        "ontologies": {
            "UBERON": {"data_version": "releases/2026-06-19", "sha256": uberon["sha256"]},
            "MONDO": {"data_version": "releases/2026-09-01", "sha256": mondo["sha256"]},
            "PO": {"data_version": "releases/2026-01-09", "sha256": po["sha256"]},
            "NCBITaxon": {
                "lookup": "NCBI E-utilities taxonomy Scientific Name exact queries",
                "queried": "2026-09-18",
                "frozen_names": len(NCBITAXON),
            },
        },
        "coverage": {
            "tissue": dict(Counter(merged.tissue_ontology_status)),
            "disease": dict(Counter(merged.disease_ontology_status)),
            "organism": dict(Counter(merged.organism_ontology_status)),
        },
        "match_types": {
            "tissue": dict(Counter(merged.tissue_ontology_match_type.dropna())),
            "disease": dict(Counter(merged.disease_ontology_match_type.dropna())),
            "organism": dict(Counter(merged.organism_ontology_match_type.dropna())),
        },
        "invariants": {
            "row_count_preserved": len(merged) == len(frame),
            "gsm_order_preserved": merged.gsm_id.astype(str).tolist() == before_gsm,
            "original_columns_bytewise_dataframe_equal": bool(merged[before_columns].equals(frame[before_columns])),
            "original_values_overwritten": False,
        },
    }
    (work / "summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n")

    provenance = {
        "schema_version": "hesrt-ontology-provenance-v1",
        "mapping_policy": (
            "Unique ontology label/EXACT synonym matches are accepted. Punctuation-only lexical "
            "normalization is accepted only when unique. A small frozen set of anatomy phrases and "
            "three disease abbreviations are curated with explicit reasons/source checks. Controls, "
            "procedures and non-disease states are not forced into MONDO. No fuzzy candidate is "
            "accepted automatically."
        ),
        "curated_tissue": CURATED_TISSUE,
        "curated_disease": CURATED_DISEASE,
        "control_or_non_disease": CONTROL_OR_NON_DISEASE,
        "ncbitaxon": NCBITAXON,
        "ontologies": summary["ontologies"],
        "script_sha256": sha256_file(Path(__file__)),
    }
    (work / "ontology_provenance.json").write_text(
        json.dumps(provenance, indent=2, ensure_ascii=False) + "\n"
    )

    if args.output_catalog:
        out = args.output_catalog.resolve()
        out.parent.mkdir(parents=True, exist_ok=True)
        merged.to_parquet(out, index=False, compression="zstd")

    print(json.dumps(summary, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()