HESRT / tools /map_metadata_ontologies.py
Biogod's picture
data: add conservative metadata ontology mapping v1
d09695b verified
Raw History Blame Contribute Delete
22 kB
#!/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()