From c9819c78eb7fd8935ff649c6b2fa14912ad79260 Mon Sep 17 00:00:00 2001 From: rishabshah Date: Thu, 12 Nov 2026 13:49:14 -0800 Subject: [PATCH 1/5] Add OMOP vocabulary reader, KEEP condition hierarchy and ICD mapper Reads Athena OMOP vocabularies and builds the SNOMED "Disease" hierarchy used by KEEP (depth-limited, all parents kept, orphans re-attached) plus an ICD-9-CM/ICD-10-CM to standard concept mapper that accepts MIMIC's dot-free codes. Adds synthetic-data tests, docs, and an example script that reports the depth ablation and MIMIC-IV coverage as counts only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1 --- .gitignore | 7 + docs/api/medcode.rst | 62 ++ examples/omop_keep_condition_graph_check.py | 142 ++++ pyhealth/medcode/__init__.py | 10 + pyhealth/medcode/omop.py | 834 ++++++++++++++++++++ tests/core/test_omop_vocabulary.py | 420 ++++++++++ 6 files changed, 1475 insertions(+) create mode 100644 examples/omop_keep_condition_graph_check.py create mode 100644 pyhealth/medcode/omop.py create mode 100644 tests/core/test_omop_vocabulary.py diff --git a/.gitignore b/.gitignore index 3166795791..26de22b202 100644 --- a/.gitignore +++ b/.gitignore @@ -159,3 +159,10 @@ test-resources/meds_demo/ # Generated Synthea outputs and dataset caches .artifacts/ examples/.artifacts/ + +# OMOP vocabularies from Athena: licensed, must never be committed +athena/ +CONCEPT*.csv +cpt4.jar +# MIMIC-IV downloads (credentialed data): keep them outside the repo +mimiciv/ diff --git a/docs/api/medcode.rst b/docs/api/medcode.rst index 9038eaccdf..8ca2d4a48d 100644 --- a/docs/api/medcode.rst +++ b/docs/api/medcode.rst @@ -227,3 +227,65 @@ Pair Notes :members: :undoc-members: :show-inheritance: + +OMOP Vocabularies (Athena) +-------------------------- + +``OMOPVocabulary`` reads a local download of the OMOP standardized vocabularies +from `Athena `_. Athena vocabularies are licensed and +cannot be redistributed, so PyHealth does not download them: create an Athena +account, download a bundle that includes SNOMED, ICD9CM and ICD10CM, unzip it +outside your repository, and pass that folder to ``OMOPVocabulary``. + +It builds two objects: + +- ``ConditionHierarchy``: the SNOMED condition graph rooted at "Disease" + (concept 4274025) and cut off at a chosen depth, as in KEEP + (`Elhussein et al., CHIL 2025 `_). By + default a concept is kept when its shortest path to "Disease" is at most + five levels; every "Is a" link between kept concepts is an edge, so concepts + with several parents keep all of them. +- ``ICDToSNOMEDMapper``: maps ICD-9-CM and ICD-10-CM diagnosis codes, written + with or without dots (MIMIC omits them), to standard concepts through + Athena's "Maps to" links. + +.. code-block:: python + + import polars as pl + from pyhealth.medcode import ConditionHierarchy, ICDToSNOMEDMapper, OMOPVocabulary + + vocab = OMOPVocabulary("~/data/athena") + + # Build once from the multi-GB Athena files, then save for later runs + hierarchy = vocab.condition_hierarchy(max_depth=5) + hierarchy.save("~/.cache/pyhealth/omop/hierarchy_d5") + hierarchy = ConditionHierarchy.load("~/.cache/pyhealth/omop/hierarchy_d5") + + # Shallower graphs for a depth ablation, without re-reading Athena + depth_3 = hierarchy.restrict(3) + + mapper = vocab.icd_mapper() + concept_ids = mapper.map("I214", version=10) + + # Kept ancestors of any concept under "Disease", nearest first + hierarchy.retained_ancestors(concept_ids[0]) + + # Map a whole diagnoses table, e.g. MIMIC-IV hosp/diagnoses_icd + diagnoses = pl.read_csv("~/data/mimiciv/3.1/hosp/diagnoses_icd.csv.gz", + schema_overrides={"icd_code": pl.Utf8}) + mapped = mapper.map_frame(diagnoses) + + # Triples for pyhealth.graph.KnowledgeGraph + triples = hierarchy.to_triples() + +.. autoclass:: pyhealth.medcode.OMOPVocabulary + :members: + :show-inheritance: + +.. autoclass:: pyhealth.medcode.ConditionHierarchy + :members: + :show-inheritance: + +.. autoclass:: pyhealth.medcode.ICDToSNOMEDMapper + :members: + :show-inheritance: diff --git a/examples/omop_keep_condition_graph_check.py b/examples/omop_keep_condition_graph_check.py new file mode 100644 index 0000000000..f838bf9a28 --- /dev/null +++ b/examples/omop_keep_condition_graph_check.py @@ -0,0 +1,142 @@ +"""Build KEEP's SNOMED condition graph from Athena and check MIMIC-IV coverage. + +KEEP (Elhussein et al., CHIL 2025, https://arxiv.org/abs/2510.05049) embeds the +SNOMED "Disease" hierarchy cut at five levels. This script builds that graph +from a local Athena download, reports its size at several depths (the depth +ablation in our proposal), and, given MIMIC-IV, counts how many diagnosis codes +land on it. + +It prints counts only: no patient rows and no individual codes, so its output +is safe to share. + +Usage: + python examples/omop_keep_condition_graph_check.py \\ + --athena ~/data/athena \\ + --mimic ~/data/mimiciv/3.1 + +The first run reads the multi-GB Athena files (several minutes) and caches the +results under --cache; later runs take seconds. Pass --rebuild to ignore the +cache. +""" + +import argparse +import time +from pathlib import Path + +import polars as pl + +from pyhealth.medcode import ConditionHierarchy, ICDToSNOMEDMapper, OMOPVocabulary + +BASE_DEPTH = 6 # deepest graph in the ablation; shallower ones are cut from it + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--athena", required=True, help="Unzipped Athena folder") + parser.add_argument("--mimic", help="MIMIC-IV folder containing hosp/") + parser.add_argument( + "--cache", + default="~/.cache/pyhealth/omop_keep", + help="Where to save the built graph and mapping", + ) + parser.add_argument( + "--depths", type=int, nargs="+", default=[3, 4, 5, 6], + help=f"Depths to report (at most {BASE_DEPTH})", + ) + parser.add_argument("--rebuild", action="store_true", help="Ignore the cache") + return parser.parse_args() + + +def vocabulary_version(athena: Path) -> str: + path = athena / "VOCABULARY.csv" + if not path.is_file(): + return "unknown" + table = pl.read_csv(path, separator="\t", quote_char=None, infer_schema=False) + row = table.filter(pl.col("vocabulary_id") == "None") + return row["vocabulary_version"][0] if row.height else "unknown" + + +def load_or_build(args: argparse.Namespace): + cache = Path(args.cache).expanduser() + graph_dir = cache / f"hierarchy_min_d{BASE_DEPTH}" + mapper_path = cache / "icd_to_snomed.parquet" + if not args.rebuild and graph_dir.is_dir() and mapper_path.is_file(): + print(f"Using cached graph and mapping in {cache}") + return ConditionHierarchy.load(graph_dir), ICDToSNOMEDMapper.load(mapper_path) + + vocab = OMOPVocabulary(args.athena) + start = time.time() + hierarchy = vocab.condition_hierarchy(max_depth=BASE_DEPTH) + print(f"Built condition graph in {time.time() - start:.0f}s") + start = time.time() + mapper = vocab.icd_mapper() + print(f"Built ICD mapping in {time.time() - start:.0f}s") + hierarchy.save(graph_dir) + mapper.save(mapper_path) + print(f"Cached in {cache}") + return hierarchy, mapper + + +def report_graphs(hierarchy: ConditionHierarchy, depths) -> None: + print("\nCondition graph by depth limit (root = Disease, depth 0)") + print(f"{'measure':>8} {'depth':>5} {'nodes':>8} {'edges':>8} {'rescued':>8}") + for measure in ("min", "max"): + for depth in sorted(depths): + graph = hierarchy.restrict(depth, measure) + rescued = int(graph.edges["rescued"].sum()) + print( + f"{measure:>8} {depth:>5} {len(graph):>8} " + f"{graph.edges.height:>8} {rescued:>8}" + ) + by_depth = hierarchy.nodes.group_by("min_depth").len().sort("min_depth") + print("\nNodes per level (shortest path):") + for level, count in by_depth.iter_rows(): + print(f" level {level}: {count}") + + +def report_mimic(mimic: Path, hierarchy, mapper: ICDToSNOMEDMapper) -> None: + path = mimic.expanduser() / "hosp" / "diagnoses_icd.csv.gz" + diagnoses = pl.read_csv( + path, + columns=["icd_code", "icd_version"], + schema_overrides={"icd_code": pl.Utf8, "icd_version": pl.Int64}, + ) + print(f"\nMIMIC-IV diagnoses: {diagnoses.height} rows") + for version in (9, 10): + subset = diagnoses.filter(pl.col("icd_version") == version) + counts = mapper.coverage(subset, hierarchy=hierarchy) + print(f"\nICD-{version} distinct codes") + for key, value in counts.items(): + share = f" ({value / counts['codes']:.1%})" if counts["codes"] else "" + print(f" {key:<18} {value:>7}{share}") + + under_root = set(hierarchy.nodes["concept_id"]) | set( + hierarchy.ancestors["concept_id"] + ) + rows = ( + mapper.map_frame(diagnoses.with_row_index("row")) + .group_by("row") + .agg( + pl.col("concept_id").is_not_null().any().alias("mapped"), + pl.col("concept_id").is_in(list(under_root)).any().alias("in_graph"), + ) + ) + print("\nDiagnosis rows") + print(f" mapped to a concept {rows['mapped'].mean():.1%}") + print(f" landing under Disease {rows['in_graph'].mean():.1%}") + + +def main() -> None: + args = parse_args() + if max(args.depths) > BASE_DEPTH: + raise SystemExit(f"--depths must be at most {BASE_DEPTH}") + athena = Path(args.athena).expanduser() + print(f"Athena vocabulary release: {vocabulary_version(athena)}") + hierarchy, mapper = load_or_build(args) + report_graphs(hierarchy, args.depths) + if args.mimic: + report_mimic(Path(args.mimic), hierarchy, mapper) + + +if __name__ == "__main__": + main() diff --git a/pyhealth/medcode/__init__.py b/pyhealth/medcode/__init__.py index 7e9438cb55..d2f7590171 100644 --- a/pyhealth/medcode/__init__.py +++ b/pyhealth/medcode/__init__.py @@ -21,6 +21,12 @@ from .cross_map import CrossMap from .flat_map import FlatMap from .inner_map import InnerMap +from .omop import ( + DISEASE_CONCEPT_ID, + ConditionHierarchy, + ICDToSNOMEDMapper, + OMOPVocabulary, +) __all__ = [ "ATC", @@ -40,8 +46,12 @@ "ICD10PROC", "NDC", "UMLS", + "ConditionHierarchy", "CrossMap", + "DISEASE_CONCEPT_ID", "FlatMap", + "ICDToSNOMEDMapper", "InnerMap", + "OMOPVocabulary", "RxNorm", ] diff --git a/pyhealth/medcode/omop.py b/pyhealth/medcode/omop.py new file mode 100644 index 0000000000..fd06892783 --- /dev/null +++ b/pyhealth/medcode/omop.py @@ -0,0 +1,834 @@ +"""OMOP standardized vocabularies (Athena) for PyHealth. + +This module reads a local download of the OMOP standardized vocabularies from +Athena (https://athena.ohdsi.org) and provides two things: + +* :class:`ConditionHierarchy`: the SNOMED condition graph rooted at the concept + "Disease" and cut off at a chosen depth, as used by KEEP (Elhussein et al., + CHIL 2025, appendix A.1.1). +* :class:`ICDToSNOMEDMapper`: a lookup from ICD-9-CM and ICD-10-CM diagnosis + codes, in the dot-free form MIMIC stores them, to standard OMOP concepts. + +Athena vocabularies are licensed and cannot be redistributed, so PyHealth does +not download them. Point :class:`OMOPVocabulary` at the folder you unzipped. + +Example: + >>> from pyhealth.medcode import OMOPVocabulary + >>> vocab = OMOPVocabulary("~/data/athena") # doctest: +SKIP + >>> hierarchy = vocab.condition_hierarchy(max_depth=5) # doctest: +SKIP + >>> mapper = vocab.icd_mapper() # doctest: +SKIP + >>> concept_ids = mapper.map("I214", version=10) # doctest: +SKIP + >>> # kept ancestors of each target, nearest first: [(ancestor_id, levels)] + >>> hierarchy.retained_ancestors(concept_ids[0]) # doctest: +SKIP +""" + +from __future__ import annotations + +import json +import logging +from collections import defaultdict +from pathlib import Path +from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union + +import networkx as nx +import polars as pl + +logger = logging.getLogger(__name__) + +#: OMOP concept_id of SNOMED 64572001 "Disease", the root KEEP uses. +DISEASE_CONCEPT_ID = 4274025 + +#: ICD version number (as in MIMIC's ``icd_version`` column) -> OMOP vocabulary. +ICD_VERSION_TO_VOCABULARY = {9: "ICD9CM", 10: "ICD10CM"} + +_REQUIRED_COLUMNS = { + "CONCEPT": [ + "concept_id", + "concept_name", + "domain_id", + "vocabulary_id", + "concept_class_id", + "standard_concept", + "concept_code", + "invalid_reason", + ], + "CONCEPT_RELATIONSHIP": [ + "concept_id_1", + "concept_id_2", + "relationship_id", + "invalid_reason", + ], + "CONCEPT_ANCESTOR": [ + "ancestor_concept_id", + "descendant_concept_id", + "min_levels_of_separation", + "max_levels_of_separation", + ], +} + +_ID_COLUMNS = { + "concept_id", + "concept_id_1", + "concept_id_2", + "ancestor_concept_id", + "descendant_concept_id", + "min_levels_of_separation", + "max_levels_of_separation", +} + + +def _is_valid() -> pl.Expr: + """Rows Athena has not marked deprecated ("D") or upgraded ("U").""" + reason = pl.col("invalid_reason") + return reason.is_null() | (reason.str.strip_chars() == "") + + +def _collect(frame: pl.LazyFrame) -> pl.DataFrame: + """Collects with the streaming engine, so multi-GB files fit in memory.""" + return frame.collect(engine="streaming") + + +def normalize_icd_code(code: str) -> str: + """Puts an ICD code in the dot-free, upper-case form MIMIC uses. + + Athena stores ``I21.4`` and MIMIC stores ``I214``. Comparing both in the + dot-free form avoids having to know where each ICD version puts its dot + (ICD-9 E-codes put it after the fourth character, everything else after + the third). + + Args: + code: An ICD-9-CM or ICD-10-CM code, with or without a dot. + + Returns: + The code without dots or surrounding whitespace, in upper case. + + Example: + >>> normalize_icd_code(" i21.4 ") + 'I214' + >>> normalize_icd_code("E880.9") + 'E8809' + """ + return str(code).strip().replace(".", "").upper() + + +def _icd_vocabulary(version: Union[int, str]) -> str: + try: + return ICD_VERSION_TO_VOCABULARY[int(version)] + except (KeyError, ValueError) as err: + raise ValueError( + f"Unsupported ICD version {version!r}; expected 9 or 10." + ) from err + + +def _rescue_orphans( + nodes: pl.DataFrame, + edges: pl.DataFrame, + ancestors: pl.DataFrame, + root_concept_id: int, +) -> pl.DataFrame: + """Attaches each parentless non-root node to its nearest kept ancestor. + + Ties on distance go to the smaller ancestor id, so the result does not + depend on file order. + """ + orphans = nodes.filter(pl.col("concept_id") != root_concept_id).join( + edges, left_on="concept_id", right_on="child_id", how="anti" + ) + if orphans.height == 0: + return edges + rescue = ( + ancestors.join(orphans.select("concept_id"), on="concept_id", how="semi") + .join(nodes.select("concept_id"), left_on="ancestor_id", + right_on="concept_id", how="semi") + .sort("concept_id", "distance", "ancestor_id") + .group_by("concept_id", maintain_order=True) + .first() + .select( + pl.col("ancestor_id").alias("parent_id"), + pl.col("concept_id").alias("child_id"), + pl.lit(True).alias("rescued"), + ) + ) + return pl.concat([edges, rescue]) + + +class OMOPVocabulary: + """Reads an Athena download of the OMOP standardized vocabularies. + + Only ``CONCEPT.csv``, ``CONCEPT_RELATIONSHIP.csv`` and + ``CONCEPT_ANCESTOR.csv`` are read. Athena writes them tab-separated despite + the ``.csv`` name, and they are several GB, so they are scanned lazily and + filtered while reading rather than loaded whole. + + Args: + root: Folder containing the unzipped Athena files. + + Raises: + FileNotFoundError: If ``root`` or one of the three files is missing. + ValueError: If a file lacks a column this module needs (for example + because it was re-saved comma-separated). + + Example: + >>> vocab = OMOPVocabulary("~/data/athena") # doctest: +SKIP + >>> hierarchy = vocab.condition_hierarchy(max_depth=5) # doctest: +SKIP + """ + + def __init__(self, root: Union[str, Path]): + self.root = Path(root).expanduser() + if not self.root.is_dir(): + raise FileNotFoundError(f"Athena folder not found: {self.root}") + for table, columns in _REQUIRED_COLUMNS.items(): + self._check_header(table, columns) + + def __repr__(self) -> str: + return f"OMOPVocabulary(root={str(self.root)!r})" + + def _path(self, table: str) -> Path: + return self.root / f"{table}.csv" + + def _check_header(self, table: str, columns: Sequence[str]) -> None: + path = self._path(table) + if not path.is_file(): + raise FileNotFoundError( + f"{path.name} not found in {self.root}. Download the " + "vocabularies from https://athena.ohdsi.org and unzip them there." + ) + with open(path, encoding="utf-8", errors="replace") as handle: + header = handle.readline().rstrip("\r\n").split("\t") + missing = [column for column in columns if column not in header] + if missing: + raise ValueError( + f"{path.name} is missing columns {missing}. Athena files are " + "tab-separated; use the files exactly as unzipped from Athena." + ) + + def scan(self, table: str) -> pl.LazyFrame: + """Lazily reads one Athena table. + + Every column is read as text, then id and level columns are cast to + integers. Quote characters are not treated specially because concept + names contain unbalanced quotes. + + Args: + table: ``"CONCEPT"``, ``"CONCEPT_RELATIONSHIP"`` or + ``"CONCEPT_ANCESTOR"``. + + Returns: + A polars ``LazyFrame`` over the file. + """ + if table not in _REQUIRED_COLUMNS: + raise ValueError( + f"Unknown table {table!r}; expected one of " + f"{sorted(_REQUIRED_COLUMNS)}." + ) + frame = pl.scan_csv( + self._path(table), + separator="\t", + quote_char=None, + infer_schema=False, + encoding="utf8-lossy", + ) + names = frame.collect_schema().names() + return frame.with_columns( + pl.col(name).cast(pl.Int64) for name in names if name in _ID_COLUMNS + ) + + def condition_hierarchy( + self, + root_concept_id: int = DISEASE_CONCEPT_ID, + max_depth: Optional[int] = 5, + depth_measure: str = "min", + connect_orphans: bool = True, + ) -> "ConditionHierarchy": + """Builds the depth-limited SNOMED condition graph KEEP uses. + + Nodes are valid, standard SNOMED concepts in the Condition domain that + descend from ``root_concept_id`` within ``max_depth`` levels, plus the + root. Edges are the "Is a" relationships between nodes, so a concept + with several parents keeps all of them. + + Args: + root_concept_id: Root of the graph. Defaults to "Disease". + max_depth: Deepest level to keep, counted from the root (depth 0). + ``None`` keeps every descendant. + depth_measure: How a concept's depth is counted, because SNOMED + concepts can sit at several depths at once. ``"min"`` (the + KEEP paper) uses the shortest path to the root; + ``"max"`` uses the longest. + connect_orphans: Some kept concepts have only parents that were + filtered out (for example a parent in another domain). If + True, each such concept is attached to its nearest kept + ancestor so the graph stays connected; these edges are marked + ``rescued`` in :attr:`ConditionHierarchy.edges`. + + Returns: + The :class:`ConditionHierarchy`. + """ + if depth_measure not in ("min", "max"): + raise ValueError("depth_measure must be 'min' or 'max'.") + if max_depth is not None and max_depth < 0: + raise ValueError("max_depth must be non-negative or None.") + logger.info("Building SNOMED condition hierarchy from %s", self.root) + + conditions = ( + self.scan("CONCEPT") + .filter( + (pl.col("vocabulary_id") == "SNOMED") + & (pl.col("domain_id") == "Condition") + & (pl.col("standard_concept") == "S") + & _is_valid() + ) + .select("concept_id", "concept_name", "concept_code") + ) + levels = ( + self.scan("CONCEPT_ANCESTOR") + .filter(pl.col("ancestor_concept_id") == root_concept_id) + .select( + pl.col("descendant_concept_id").alias("concept_id"), + pl.col("min_levels_of_separation").alias("min_depth"), + pl.col("max_levels_of_separation").alias("max_depth"), + ) + ) + subtree = _collect(levels.join(conditions, on="concept_id", how="inner")) + root = _collect( + conditions.filter(pl.col("concept_id") == root_concept_id) + ) + if root.height == 0: + raise ValueError( + f"Root concept {root_concept_id} is not a valid standard SNOMED " + "Condition concept in this vocabulary." + ) + if root_concept_id not in subtree["concept_id"]: + subtree = pl.concat( + [ + subtree, + root.with_columns( + pl.lit(0, pl.Int64).alias("min_depth"), + pl.lit(0, pl.Int64).alias("max_depth"), + ).select(subtree.columns), + ] + ) + subtree = subtree.with_columns( + pl.col(f"{depth_measure}_depth").alias("depth") + ).unique("concept_id") + + nodes = subtree + if max_depth is not None: + nodes = subtree.filter(pl.col("depth") <= max_depth) + nodes = nodes.sort("depth", "concept_id") + node_ids = nodes.select("concept_id").lazy() + + edges = _collect( + self.scan("CONCEPT_RELATIONSHIP") + .filter((pl.col("relationship_id") == "Is a") & _is_valid()) + .select( + pl.col("concept_id_2").alias("parent_id"), + pl.col("concept_id_1").alias("child_id"), + ) + .join(node_ids, left_on="parent_id", right_on="concept_id", how="semi") + .join(node_ids, left_on="child_id", right_on="concept_id", how="semi") + .filter(pl.col("parent_id") != pl.col("child_id")) + .unique() + ).with_columns(pl.lit(False).alias("rescued")) + + ancestors = _collect( + self.scan("CONCEPT_ANCESTOR") + .filter(pl.col("min_levels_of_separation") > 0) + .select( + pl.col("descendant_concept_id").alias("concept_id"), + pl.col("ancestor_concept_id").alias("ancestor_id"), + pl.col("min_levels_of_separation").alias("distance"), + ) + .join(subtree.select("concept_id").lazy(), on="concept_id", how="semi") + .join(node_ids, left_on="ancestor_id", right_on="concept_id", how="semi") + ) + + if connect_orphans: + edges = _rescue_orphans(nodes, edges, ancestors, root_concept_id) + logger.info( + "Condition hierarchy: %d concepts, %d edges, %d orphans re-attached", + nodes.height, + edges.height, + int(edges["rescued"].sum()), + ) + + return ConditionHierarchy( + nodes=nodes, + edges=edges.sort("parent_id", "child_id"), + ancestors=ancestors.sort("concept_id", "distance", "ancestor_id"), + root_concept_id=root_concept_id, + max_depth=max_depth, + depth_measure=depth_measure, + connect_orphans=connect_orphans, + ) + + def icd_mapper( + self, versions: Iterable[Union[int, str]] = (9, 10) + ) -> "ICDToSNOMEDMapper": + """Builds the ICD -> standard concept lookup from "Maps to" links. + + Source ICD concepts are kept even when Athena has deprecated them, + because older records (such as MIMIC's ICD-9 era) still use them; + only the "Maps to" links themselves must be valid. + + Args: + versions: ICD versions to include (9 and/or 10). + + Returns: + The :class:`ICDToSNOMEDMapper`. + """ + vocabularies = [_icd_vocabulary(version) for version in versions] + concept = self.scan("CONCEPT") + sources = concept.filter(pl.col("vocabulary_id").is_in(vocabularies)).select( + pl.col("vocabulary_id"), + pl.col("concept_code").alias("source_code"), + pl.col("concept_id").alias("source_concept_id"), + ) + maps_to = ( + self.scan("CONCEPT_RELATIONSHIP") + .filter((pl.col("relationship_id") == "Maps to") & _is_valid()) + .select( + pl.col("concept_id_1").alias("source_concept_id"), + pl.col("concept_id_2").alias("concept_id"), + ) + .join(sources.select("source_concept_id"), on="source_concept_id", + how="semi") + ) + targets = concept.select( + "concept_id", + pl.col("concept_name"), + pl.col("domain_id").alias("target_domain_id"), + pl.col("vocabulary_id").alias("target_vocabulary_id"), + ) + version_of = {name: number for number, name in + ICD_VERSION_TO_VOCABULARY.items()} + table = _collect( + sources.join(maps_to, on="source_concept_id", how="left") + .join(targets, on="concept_id", how="left") + .with_columns( + pl.col("vocabulary_id") + .replace_strict(version_of, return_dtype=pl.Int64) + .alias("icd_version"), + pl.col("source_code") + .str.strip_chars() + .str.replace_all(".", "", literal=True) + .str.to_uppercase() + .alias("icd_code"), + ) + .unique() + ) + return ICDToSNOMEDMapper( + table.select( + "icd_version", + "icd_code", + "source_code", + "source_concept_id", + "concept_id", + "concept_name", + "target_domain_id", + "target_vocabulary_id", + ).sort("icd_version", "icd_code", "concept_id", nulls_last=True) + ) + + +class ConditionHierarchy: + """A depth-limited SNOMED condition graph rooted at one concept. + + Build it with :meth:`OMOPVocabulary.condition_hierarchy`, or reload a saved + one with :meth:`load`. Concept ids are OMOP ``concept_id`` integers. + + Attributes: + nodes: One row per kept concept: ``concept_id``, ``concept_name``, + ``concept_code`` (the SNOMED code), ``min_depth``, ``max_depth`` + and ``depth`` (whichever of the two was used to cut the graph). + edges: ``parent_id``, ``child_id`` and ``rescued`` for every "Is a" + link between kept concepts, plus any orphan rescues. + ancestors: ``concept_id``, ``ancestor_id``, ``distance`` for every + concept under the root (kept or deeper) and each of its kept + ancestors, with ``distance`` the shortest number of levels between + them. Roll-up uses this to place deep concepts on the graph. + root_concept_id: The root concept. + max_depth: The depth limit, or None for no limit. + depth_measure: ``"min"`` or ``"max"``. + connect_orphans: Whether orphans were attached to their nearest kept + ancestor. + """ + + def __init__( + self, + nodes: pl.DataFrame, + edges: pl.DataFrame, + ancestors: pl.DataFrame, + root_concept_id: int, + max_depth: Optional[int], + depth_measure: str, + connect_orphans: bool = True, + ): + self.nodes = nodes + self.edges = edges + self.ancestors = ancestors + self.root_concept_id = root_concept_id + self.max_depth = max_depth + self.depth_measure = depth_measure + self.connect_orphans = connect_orphans + self._info = { + row["concept_id"]: row for row in nodes.iter_rows(named=True) + } + self._parents: Dict[int, List[int]] = defaultdict(list) + self._children: Dict[int, List[int]] = defaultdict(list) + for parent, child in edges.select("parent_id", "child_id").iter_rows(): + self._parents[child].append(parent) + self._children[parent].append(child) + self._ancestor_index: Optional[Dict[int, List[Tuple[int, int]]]] = None + + def __repr__(self) -> str: + return ( + f"ConditionHierarchy(root={self.root_concept_id}, " + f"max_depth={self.max_depth}, depth_measure={self.depth_measure!r}, " + f"nodes={len(self)}, edges={self.edges.height})" + ) + + def __len__(self) -> int: + return self.nodes.height + + def __contains__(self, concept_id: int) -> bool: + return concept_id in self._info + + def _require(self, concept_id: int) -> dict: + try: + return self._info[concept_id] + except KeyError: + raise KeyError(f"Concept {concept_id} is not in the hierarchy.") from None + + def name(self, concept_id: int) -> str: + """Returns a kept concept's name.""" + return self._require(concept_id)["concept_name"] + + def depth(self, concept_id: int) -> int: + """Returns a kept concept's depth below the root.""" + return self._require(concept_id)["depth"] + + def parents(self, concept_id: int) -> List[int]: + """Returns a kept concept's parents in the graph, sorted.""" + self._require(concept_id) + return sorted(self._parents.get(concept_id, [])) + + def children(self, concept_id: int) -> List[int]: + """Returns a kept concept's children in the graph, sorted.""" + self._require(concept_id) + return sorted(self._children.get(concept_id, [])) + + def retained_ancestors(self, concept_id: int) -> List[Tuple[int, int]]: + """Lists the kept ancestors of any concept under the root. + + Works for concepts deeper than ``max_depth`` too, which is what + roll-up needs. A concept with several parents gets ancestors along + every path. + + Args: + concept_id: Any concept under the root, kept or not. + + Returns: + ``(ancestor_id, distance)`` pairs, nearest first. Empty if the + concept is not under the root. + """ + if self._ancestor_index is None: + self._ancestor_index = defaultdict(list) + for child, ancestor, distance in self.ancestors.iter_rows(): + self._ancestor_index[child].append((ancestor, distance)) + return list(self._ancestor_index.get(concept_id, [])) + + def restrict( + self, max_depth: int, depth_measure: Optional[str] = None + ) -> "ConditionHierarchy": + """Cuts this hierarchy to a shallower depth without re-reading Athena. + + Build once with a generous limit (or ``max_depth=None``), then call + this for each depth in an ablation. The result is the same as + building at the smaller depth directly. + + Args: + max_depth: The new, smaller depth limit. + depth_measure: ``"min"`` or ``"max"``; defaults to this + hierarchy's measure. + + Returns: + A new :class:`ConditionHierarchy`. + + Raises: + ValueError: If the new graph would need concepts this one dropped. + """ + depth_measure = depth_measure or self.depth_measure + if depth_measure not in ("min", "max"): + raise ValueError("depth_measure must be 'min' or 'max'.") + if max_depth is None or max_depth < 0: + raise ValueError("max_depth must be a non-negative integer.") + # a concept's max depth is never below its min depth, so a cut on + # max depth keeps a subset of the same cut on min depth + covered = self.max_depth is None or ( + max_depth <= self.max_depth + and (self.depth_measure == "min" or depth_measure == "max") + ) + if not covered: + raise ValueError( + f"Cannot restrict a hierarchy built with max_depth=" + f"{self.max_depth} ({self.depth_measure}) to max_depth=" + f"{max_depth} ({depth_measure}); build a deeper one first." + ) + nodes = ( + self.nodes.with_columns(pl.col(f"{depth_measure}_depth").alias("depth")) + .filter(pl.col("depth") <= max_depth) + .sort("depth", "concept_id") + ) + kept = nodes.select("concept_id") + edges = ( + self.edges.filter(~pl.col("rescued")) + .join(kept, left_on="parent_id", right_on="concept_id", how="semi") + .join(kept, left_on="child_id", right_on="concept_id", how="semi") + ) + ancestors = self.ancestors.join( + kept, left_on="ancestor_id", right_on="concept_id", how="semi" + ) + if self.connect_orphans: + edges = _rescue_orphans(nodes, edges, ancestors, self.root_concept_id) + return ConditionHierarchy( + nodes=nodes, + edges=edges.sort("parent_id", "child_id"), + ancestors=ancestors, + root_concept_id=self.root_concept_id, + max_depth=max_depth, + depth_measure=depth_measure, + connect_orphans=self.connect_orphans, + ) + + def to_networkx(self) -> nx.DiGraph: + """Returns the graph as a ``networkx.DiGraph`` with parent -> child edges. + + Node attributes are ``name``, ``code`` and ``depth``; edge attribute + ``rescued`` marks orphan rescues. + """ + graph = nx.DiGraph() + for row in self.nodes.iter_rows(named=True): + graph.add_node( + row["concept_id"], + name=row["concept_name"], + code=row["concept_code"], + depth=row["depth"], + ) + for parent, child, rescued in self.edges.iter_rows(): + graph.add_edge(parent, child, rescued=rescued) + return graph + + def to_triples(self, relation: str = "is_a") -> List[Tuple[str, str, str]]: + """Returns ``(child, relation, parent)`` string triples. + + This is the input format of :class:`pyhealth.graph.KnowledgeGraph`. + + Args: + relation: Relation name to use for every edge. + """ + return [ + (str(child), relation, str(parent)) + for parent, child in self.edges.select("parent_id", "child_id") + .iter_rows() + ] + + def save(self, folder: Union[str, Path]) -> None: + """Saves the hierarchy as parquet files, so later runs skip Athena. + + Args: + folder: Folder to write to; created if needed. + """ + folder = Path(folder).expanduser() + folder.mkdir(parents=True, exist_ok=True) + self.nodes.write_parquet(folder / "nodes.parquet") + self.edges.write_parquet(folder / "edges.parquet") + self.ancestors.write_parquet(folder / "ancestors.parquet") + meta = { + "root_concept_id": self.root_concept_id, + "max_depth": self.max_depth, + "depth_measure": self.depth_measure, + "connect_orphans": self.connect_orphans, + } + (folder / "meta.json").write_text(json.dumps(meta, indent=2)) + + @classmethod + def load(cls, folder: Union[str, Path]) -> "ConditionHierarchy": + """Loads a hierarchy written by :meth:`save`. + + Args: + folder: Folder passed to :meth:`save`. + """ + folder = Path(folder).expanduser() + meta = json.loads((folder / "meta.json").read_text()) + return cls( + nodes=pl.read_parquet(folder / "nodes.parquet"), + edges=pl.read_parquet(folder / "edges.parquet"), + ancestors=pl.read_parquet(folder / "ancestors.parquet"), + **meta, + ) + + +class ICDToSNOMEDMapper: + """Maps ICD-9-CM and ICD-10-CM diagnosis codes to standard OMOP concepts. + + Build it with :meth:`OMOPVocabulary.icd_mapper`, or reload a saved one with + :meth:`load`. Codes are matched in MIMIC's dot-free form, so ``"I214"`` + and ``"I21.4"`` are the same code. One ICD code can map to several + concepts, and some map to none. + + Attributes: + table: One row per (ICD code, target concept): ``icd_version``, + ``icd_code`` (dot-free), ``source_code`` (as Athena writes it), + ``source_concept_id``, ``concept_id`` (null when the code has no + valid "Maps to" link), ``concept_name``, ``target_domain_id`` and + ``target_vocabulary_id``. + """ + + def __init__(self, table: pl.DataFrame): + self.table = table + self._lookup: Dict[Tuple[int, str], List[int]] = defaultdict(list) + self._known = set() + for version, code, concept_id in table.select( + "icd_version", "icd_code", "concept_id" + ).iter_rows(): + self._known.add((version, code)) + if concept_id is not None: + self._lookup[(version, code)].append(concept_id) + + def __repr__(self) -> str: + return f"ICDToSNOMEDMapper(codes={len(self._known)})" + + def __contains__(self, key: Tuple[Union[int, str], str]) -> bool: + version, code = key + return (int(version), normalize_icd_code(code)) in self._known + + def map(self, code: str, version: Union[int, str]) -> List[int]: + """Maps one ICD code to standard concept ids. + + Args: + code: The ICD code, with or without a dot. + version: 9 or 10 (MIMIC's ``icd_version``). + + Returns: + Sorted, de-duplicated target concept ids; empty if the code is + unknown or has no valid mapping. + """ + _icd_vocabulary(version) + key = (int(version), normalize_icd_code(code)) + return sorted(set(self._lookup.get(key, []))) + + def map_frame( + self, + frame: pl.DataFrame, + code_column: str = "icd_code", + version_column: str = "icd_version", + ) -> pl.DataFrame: + """Adds mapped concepts to a table of diagnoses, such as MIMIC's. + + Rows whose code maps to several concepts are repeated, one per + concept. Rows that do not map keep a null ``concept_id``. + + Args: + frame: A table with an ICD code column and a version column. + code_column: Name of the code column. + version_column: Name of the version column. + + Returns: + ``frame`` with ``concept_id`` and ``target_domain_id`` added. + """ + lookup = self.table.select( + "icd_version", "icd_code", "concept_id", "target_domain_id" + ).filter(pl.col("concept_id").is_not_null()) + keyed = frame.with_columns( + pl.col(version_column).cast(pl.Int64).alias("__version"), + pl.col(code_column) + .cast(pl.Utf8) + .str.strip_chars() + .str.replace_all(".", "", literal=True) + .str.to_uppercase() + .alias("__code"), + ) + return keyed.join( + lookup, + left_on=["__version", "__code"], + right_on=["icd_version", "icd_code"], + how="left", + ).drop("__version", "__code") + + def coverage( + self, + frame: pl.DataFrame, + hierarchy: Optional[ConditionHierarchy] = None, + code_column: str = "icd_code", + version_column: str = "icd_version", + ) -> Dict[str, int]: + """Counts how many distinct codes in a table map, without listing any. + + Args: + frame: A table with an ICD code column and a version column. + hierarchy: If given, also counts codes that land under its root + (kept, or deeper and reachable by roll-up). + code_column: Name of the code column. + version_column: Name of the version column. + + Returns: + Counts of distinct (version, code) pairs: ``codes``, + ``unknown`` (not in Athena), ``no_mapping`` (in Athena, no valid + "Maps to"), ``mapped``; with a hierarchy, also ``in_hierarchy`` + (at least one target under the root) and ``outside_hierarchy``. + """ + codes = frame.select( + pl.col(version_column).cast(pl.Int64).alias("icd_version"), + pl.col(code_column) + .cast(pl.Utf8) + .str.strip_chars() + .str.replace_all(".", "", literal=True) + .str.to_uppercase() + .alias("icd_code"), + ).unique() + known = codes.join( + self.table.select("icd_version", "icd_code").unique(), + on=["icd_version", "icd_code"], + how="semi", + ) + mapped = self.map_frame(codes).filter(pl.col("concept_id").is_not_null()) + mapped_codes = mapped.select("icd_version", "icd_code").unique() + result = { + "codes": codes.height, + "unknown": codes.height - known.height, + "no_mapping": known.height - mapped_codes.height, + "mapped": mapped_codes.height, + } + if hierarchy is not None: + under_root = set(hierarchy.nodes["concept_id"]) | set( + hierarchy.ancestors["concept_id"] + ) + inside = ( + mapped.filter(pl.col("concept_id").is_in(list(under_root))) + .select("icd_version", "icd_code") + .unique() + .height + ) + result["in_hierarchy"] = inside + result["outside_hierarchy"] = mapped_codes.height - inside + return result + + def save(self, path: Union[str, Path]) -> None: + """Saves the mapping table as one parquet file. + + Args: + path: File to write, for example ``icd_to_snomed.parquet``. + """ + path = Path(path).expanduser() + path.parent.mkdir(parents=True, exist_ok=True) + self.table.write_parquet(path) + + @classmethod + def load(cls, path: Union[str, Path]) -> "ICDToSNOMEDMapper": + """Loads a mapper written by :meth:`save`. + + Args: + path: File passed to :meth:`save`. + """ + return cls(pl.read_parquet(Path(path).expanduser())) diff --git a/tests/core/test_omop_vocabulary.py b/tests/core/test_omop_vocabulary.py new file mode 100644 index 0000000000..cbf63bcd71 --- /dev/null +++ b/tests/core/test_omop_vocabulary.py @@ -0,0 +1,420 @@ +"""Tests for pyhealth.medcode.omop on a small synthetic Athena bundle. + +The bundle is written to a temporary folder. It mimics Athena's layout +(tab-separated ``.csv`` files) with a dozen concepts arranged to cover the +cases that matter: a depth cutoff, a concept with two parents at different +depths, an orphan whose only parent is in another domain, deprecated rows, +and ICD codes that map to zero, one or two concepts. + +Hierarchy ("Is a", child -> parent):: + + 700 Clinical finding + |-- 4274025 Disease (root) 300 Fever -> 700 (not under root) + |-- 100 Heart disease + | |-- 101 Ischemic heart disease + | | `-- 102 Acute MI + | | `-- 103 Acute MI, inferior wall + | | `-- 104 (also directly under 100) + | |-- 600 Cardiac observation (Observation domain) + | | `-- 105 Orphan disorder + | |-- 400 non-standard concept + | `-- 401 deprecated concept + `-- 200 Lung disease +""" + +import shutil +import tempfile +import unittest +from collections import defaultdict +from pathlib import Path + +import polars as pl + +from pyhealth.medcode import ( + DISEASE_CONCEPT_ID, + ConditionHierarchy, + ICDToSNOMEDMapper, + OMOPVocabulary, +) +from pyhealth.medcode.omop import normalize_icd_code + +ROOT = DISEASE_CONCEPT_ID + +# concept_id, name, domain, vocabulary, standard, code, invalid_reason +CONCEPTS = [ + (700, "Clinical finding", "Condition", "SNOMED", "S", "404684003", ""), + (ROOT, "Disease", "Condition", "SNOMED", "S", "64572001", ""), + (100, "Heart disease", "Condition", "SNOMED", "S", "56265001", ""), + (200, "Lung disease", "Condition", "SNOMED", "S", "19829001", ""), + (101, "Ischemic heart disease", "Condition", "SNOMED", "S", "414545008", ""), + (102, 'Acute "MI', "Condition", "SNOMED", "S", "57054005", ""), + (103, "Acute MI, inferior wall", "Condition", "SNOMED", "S", "73795002", ""), + (104, "Two-parent disorder", "Condition", "SNOMED", "S", "1000004", ""), + (600, "Cardiac observation", "Observation", "SNOMED", "S", "1000600", ""), + (105, "Orphan disorder", "Condition", "SNOMED", "S", "1000005", ""), + (300, "Fever", "Condition", "SNOMED", "S", "386661006", ""), + (400, "Non-standard disorder", "Condition", "SNOMED", "", "1000400", ""), + (401, "Deprecated disorder", "Condition", "SNOMED", "", "1000401", "D"), + (9001, "NSTEMI", "Condition", "ICD10CM", "", "I21.4", ""), + (9002, "CAD", "Condition", "ICD10CM", "", "I25.10", ""), + (9003, "Fever, unspecified", "Condition", "ICD10CM", "", "R50.9", ""), + (9004, "Other dependence", "Observation", "ICD10CM", "", "Z99.89", ""), + (9005, "Type 2 MI", "Condition", "ICD10CM", "", "I21.A1", ""), + (9006, "Old MI code", "Condition", "ICD10CM", "", "I21.9", "D"), + (8001, "AMI inferior", "Condition", "ICD9CM", "", "410.71", ""), + (8002, "Fall on stairs", "Observation", "ICD9CM", "", "E880.9", ""), + (8003, "CABG status", "Observation", "ICD9CM", "", "V45.81", ""), + (8004, "CHF", "Condition", "ICD9CM", "", "428.0", ""), +] + +# concept_id_1, concept_id_2, relationship_id, invalid_reason +RELATIONSHIPS = [ + (ROOT, 700, "Is a", ""), + (100, ROOT, "Is a", ""), + (200, ROOT, "Is a", ""), + (101, 100, "Is a", ""), + (102, 101, "Is a", ""), + (103, 102, "Is a", ""), + (104, 103, "Is a", ""), + (104, 100, "Is a", ""), + (600, 100, "Is a", ""), + (105, 600, "Is a", ""), + (300, 700, "Is a", ""), + (400, 100, "Is a", ""), + (401, 100, "Is a", ""), + (102, 200, "Is a", "D"), # deprecated link: must be ignored + (100, 101, "Subsumes", ""), # other relationship types are ignored + (9001, 102, "Maps to", ""), + (9001, 101, "Maps to", "D"), # deprecated mapping: must be ignored + (9002, 101, "Maps to", ""), + (9002, 104, "Maps to", ""), + (9003, 300, "Maps to", ""), + (9005, 103, "Maps to", ""), + (9006, 102, "Maps to", ""), + (8001, 102, "Maps to", ""), + (8002, 104, "Maps to", ""), + (8003, 101, "Maps to", ""), + (8004, 100, "Maps to", ""), +] + + +def _concept_ancestor_rows(): + """Derives CONCEPT_ANCESTOR the way Athena does: valid standard concepts, + valid "Is a" links, shortest and longest path lengths, self rows at 0.""" + standard = { + row[0] for row in CONCEPTS if row[4] == "S" and row[6] == "" + } + parents = defaultdict(set) + for child, parent, relation, invalid in RELATIONSHIPS: + if relation == "Is a" and not invalid and {child, parent} <= standard: + parents[child].add(parent) + + def levels(concept): + found = defaultdict(list) + stack = [(concept, 0)] + while stack: + node, distance = stack.pop() + found[node].append(distance) + for parent in parents[node]: + stack.append((parent, distance + 1)) + return found + + rows = [] + for concept in sorted(standard): + for ancestor, distances in levels(concept).items(): + rows.append((ancestor, concept, min(distances), max(distances))) + return rows + + +def _write(path, header, rows): + lines = ["\t".join(header)] + lines += ["\t".join(str(value) for value in row) for row in rows] + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + +def write_athena_bundle(folder): + """Writes the synthetic bundle in Athena's tab-separated layout.""" + folder = Path(folder) + _write( + folder / "CONCEPT.csv", + [ + "concept_id", "concept_name", "domain_id", "vocabulary_id", + "concept_class_id", "standard_concept", "concept_code", + "valid_start_date", "valid_end_date", "invalid_reason", + ], + [ + (cid, name, domain, vocab, "Clinical Finding", std, code, + "19700101", "20991231", invalid) + for cid, name, domain, vocab, std, code, invalid in CONCEPTS + ], + ) + _write( + folder / "CONCEPT_RELATIONSHIP.csv", + [ + "concept_id_1", "concept_id_2", "relationship_id", + "valid_start_date", "valid_end_date", "invalid_reason", + ], + [(a, b, rel, "19700101", "20991231", inv) + for a, b, rel, inv in RELATIONSHIPS], + ) + _write( + folder / "CONCEPT_ANCESTOR.csv", + [ + "ancestor_concept_id", "descendant_concept_id", + "min_levels_of_separation", "max_levels_of_separation", + ], + _concept_ancestor_rows(), + ) + + +class _AthenaFixture(unittest.TestCase): + """Builds the bundle once per test class; holds no tests itself.""" + + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.mkdtemp() + write_athena_bundle(cls.tmp) + cls.vocab = OMOPVocabulary(cls.tmp) + cls.hierarchy = cls.vocab.condition_hierarchy(max_depth=3) + cls.mapper = cls.vocab.icd_mapper() + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp) + + +class TestOMOPVocabulary(_AthenaFixture): + def test_missing_folder(self): + with self.assertRaises(FileNotFoundError): + OMOPVocabulary(Path(self.tmp) / "nope") + + def test_missing_file(self): + with tempfile.TemporaryDirectory() as folder: + write_athena_bundle(folder) + (Path(folder) / "CONCEPT_ANCESTOR.csv").unlink() + with self.assertRaises(FileNotFoundError): + OMOPVocabulary(folder) + + def test_comma_separated_file_is_rejected(self): + with tempfile.TemporaryDirectory() as folder: + write_athena_bundle(folder) + path = Path(folder) / "CONCEPT.csv" + path.write_text(path.read_text().replace("\t", ",")) + with self.assertRaisesRegex(ValueError, "tab-separated"): + OMOPVocabulary(folder) + + def test_scan_reads_ids_as_integers_and_keeps_quotes(self): + concept = self.vocab.scan("CONCEPT").collect() + self.assertEqual(concept.schema["concept_id"], pl.Int64) + names = dict(concept.select("concept_id", "concept_name").iter_rows()) + self.assertEqual(names[102], 'Acute "MI') + + def test_unknown_table(self): + with self.assertRaises(ValueError): + self.vocab.scan("DRUG_STRENGTH") + + +class TestConditionHierarchy(_AthenaFixture): + def test_nodes_respect_depth_domain_and_validity(self): + self.assertEqual( + set(self.hierarchy.nodes["concept_id"]), + {ROOT, 100, 200, 101, 102, 104, 105}, + ) + for excluded in (103, 600, 300, 400, 401, 700): + self.assertNotIn(excluded, self.hierarchy) + + def test_depths(self): + self.assertEqual(self.hierarchy.depth(ROOT), 0) + self.assertEqual(self.hierarchy.depth(102), 3) + # two parents: shortest path (via 100) is 2, longest (via 103) is 5 + row = self.hierarchy.nodes.filter(pl.col("concept_id") == 104).row( + 0, named=True + ) + self.assertEqual((row["depth"], row["min_depth"], row["max_depth"]), + (2, 2, 5)) + + def test_max_depth_measure(self): + deepest = self.vocab.condition_hierarchy(max_depth=3, depth_measure="max") + self.assertNotIn(104, deepest) + self.assertIn(102, deepest) + + def test_no_depth_limit(self): + full = self.vocab.condition_hierarchy(max_depth=None) + self.assertIn(103, full) + self.assertEqual(full.parents(104), [100, 103]) + + def test_edges_only_between_kept_concepts(self): + edges = set( + self.hierarchy.edges.filter(~pl.col("rescued")) + .select("parent_id", "child_id") + .iter_rows() + ) + self.assertEqual( + edges, {(ROOT, 100), (ROOT, 200), (100, 101), (101, 102), (100, 104)} + ) + # the deprecated 102 -> 200 link is not an edge + self.assertEqual(self.hierarchy.parents(102), [101]) + + def test_orphan_is_attached_to_nearest_kept_ancestor(self): + self.assertEqual(self.hierarchy.parents(105), [100]) + rescued = self.hierarchy.edges.filter(pl.col("rescued")) + self.assertEqual(list(rescued.select("parent_id", "child_id").iter_rows()), + [(100, 105)]) + + def test_orphans_left_alone_when_asked(self): + loose = self.vocab.condition_hierarchy(max_depth=3, connect_orphans=False) + self.assertEqual(loose.parents(105), []) + self.assertFalse(loose.edges["rescued"].any()) + + def test_retained_ancestors_of_deep_and_multi_parent_concepts(self): + # 103 is below the cutoff; roll-up needs its kept ancestors + self.assertEqual( + self.hierarchy.retained_ancestors(103), + [(102, 1), (101, 2), (100, 3), (ROOT, 4)], + ) + self.assertEqual( + self.hierarchy.retained_ancestors(104), + [(100, 1), (102, 2), (ROOT, 2), (101, 3)], + ) + self.assertEqual(self.hierarchy.retained_ancestors(300), []) + + def test_lookups(self): + self.assertEqual(self.hierarchy.name(ROOT), "Disease") + self.assertEqual(self.hierarchy.children(ROOT), [100, 200]) + with self.assertRaises(KeyError): + self.hierarchy.depth(103) + + def test_bad_arguments(self): + with self.assertRaises(ValueError): + self.vocab.condition_hierarchy(depth_measure="mean") + with self.assertRaises(ValueError): + self.vocab.condition_hierarchy(max_depth=-1) + with self.assertRaises(ValueError): + self.vocab.condition_hierarchy(root_concept_id=600) + + def test_networkx_and_triples(self): + graph = self.hierarchy.to_networkx() + self.assertEqual(graph.number_of_nodes(), len(self.hierarchy)) + self.assertEqual(graph.nodes[102]["depth"], 3) + self.assertTrue(graph.edges[100, 105]["rescued"]) + triples = self.hierarchy.to_triples() + self.assertIn(("101", "is_a", "100"), triples) + self.assertEqual(len(triples), self.hierarchy.edges.height) + + def test_restrict_matches_direct_build(self): + full = self.vocab.condition_hierarchy(max_depth=None) + for depth, measure in [(3, "min"), (2, "min"), (3, "max"), (0, "min")]: + direct = self.vocab.condition_hierarchy( + max_depth=depth, depth_measure=measure + ) + cut = full.restrict(depth, measure) + with self.subTest(depth=depth, measure=measure): + self.assertTrue(cut.nodes.equals(direct.nodes)) + self.assertTrue(cut.edges.equals(direct.edges)) + self.assertTrue( + cut.ancestors.sort(cut.ancestors.columns).equals( + direct.ancestors.sort(direct.ancestors.columns) + ) + ) + self.assertEqual((cut.max_depth, cut.depth_measure), + (depth, measure)) + + def test_restrict_refuses_to_add_concepts(self): + with self.assertRaises(ValueError): + self.hierarchy.restrict(4) + by_max = self.vocab.condition_hierarchy(max_depth=3, depth_measure="max") + with self.assertRaises(ValueError): + by_max.restrict(3, "min") + self.assertEqual(len(self.hierarchy.restrict(3, "max")), + len(by_max)) + + def test_save_and_load(self): + with tempfile.TemporaryDirectory() as folder: + self.hierarchy.save(folder) + loaded = ConditionHierarchy.load(folder) + self.assertEqual(loaded.max_depth, 3) + self.assertEqual(loaded.depth_measure, "min") + self.assertTrue(loaded.nodes.equals(self.hierarchy.nodes)) + self.assertEqual(loaded.retained_ancestors(103), + self.hierarchy.retained_ancestors(103)) + + +class TestICDToSNOMEDMapper(_AthenaFixture): + def test_normalize(self): + self.assertEqual(normalize_icd_code(" i21.4 "), "I214") + self.assertEqual(normalize_icd_code("E880.9"), "E8809") + + def test_map_mimic_and_dotted_codes(self): + self.assertEqual(self.mapper.map("I214", 10), [102]) + self.assertEqual(self.mapper.map("I21.4", "10"), [102]) + self.assertEqual(self.mapper.map("41071", 9), [102]) + self.assertEqual(self.mapper.map("E8809", 9), [104]) + self.assertEqual(self.mapper.map("V4581", 9), [101]) + + def test_one_code_several_concepts(self): + self.assertEqual(self.mapper.map("I2510", 10), [101, 104]) + + def test_unmapped_unknown_and_deprecated(self): + self.assertEqual(self.mapper.map("Z9989", 10), []) # no "Maps to" + self.assertIn((10, "Z9989"), self.mapper) + self.assertEqual(self.mapper.map("XYZ", 10), []) # not in Athena + self.assertNotIn((10, "XYZ"), self.mapper) + # deprecated source code still maps through a valid link + self.assertEqual(self.mapper.map("I219", 10), [102]) + + def test_versions_are_separate(self): + self.assertEqual(self.mapper.map("I214", 9), []) + with self.assertRaises(ValueError): + self.mapper.map("I214", 11) + icd10_only = self.vocab.icd_mapper(versions=[10]) + self.assertEqual(icd10_only.map("41071", 9), []) + + def test_map_frame(self): + diagnoses = pl.DataFrame( + { + "subject_id": [1, 1, 2], + "icd_code": ["I214", "I2510", "Z9989"], + "icd_version": [10, 10, 10], + } + ) + mapped = self.mapper.map_frame(diagnoses) + self.assertEqual(mapped.height, 4) # I2510 maps to two concepts + self.assertEqual( + sorted(mapped.filter(pl.col("icd_code") == "I2510")["concept_id"]), + [101, 104], + ) + self.assertIsNone( + mapped.filter(pl.col("icd_code") == "Z9989")["concept_id"][0] + ) + self.assertEqual(mapped.columns[:3], diagnoses.columns) + + def test_coverage(self): + diagnoses = pl.DataFrame( + { + "icd_code": ["I214", "I214", "I2510", "R509", "Z9989", "XYZ", + "41071", "E8809"], + "icd_version": [10, 10, 10, 10, 10, 10, 9, 9], + } + ) + self.assertEqual( + self.mapper.coverage(diagnoses, hierarchy=self.hierarchy), + { + "codes": 7, + "unknown": 1, + "no_mapping": 1, + "mapped": 5, + "in_hierarchy": 4, + "outside_hierarchy": 1, # R50.9 -> Fever, not a disease + }, + ) + + def test_save_and_load(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "icd_to_snomed.parquet" + self.mapper.save(path) + loaded = ICDToSNOMEDMapper.load(path) + self.assertEqual(loaded.map("I2510", 10), [101, 104]) + + +if __name__ == "__main__": + unittest.main() From 58d8f68b46ab50967e09d029073bdc8b198b86cb Mon Sep 17 00:00:00 2001 From: rishabshah Date: Sat, 14 Nov 2026 16:57:05 -0800 Subject: [PATCH 2/5] Address review: split OMOP package, KnowledgeGraph export, format config - Split omop.py into pyhealth/medcode/omop/ (vocabulary, condition_hierarchy, icd_mapper); public imports unchanged. Tests split to match, sharing tests/core/omop_test_utils.py. - Rename ConditionHierarchy to OMOPConditionHierarchy. - to_triples(direction=...) and new to_knowledge_graph(); rescue edges get their own relation; knowledge graph defaults to parent -> child so GraphProcessor reaches ancestors from a child seed. - Add OMOPVocabularyFormat for non-Athena vocabulary files. - map_frame() and coverage() accept polars LazyFrames. - Docs: KnowledgeGraph/GraphProcessor example; rescue described as an adapter policy. Example script documents task and processor entry points. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1 --- docs/api/medcode.rst | 109 ++- examples/omop_keep_condition_graph_check.py | 57 +- pyhealth/medcode/__init__.py | 6 +- pyhealth/medcode/omop.py | 834 ------------------- pyhealth/medcode/omop/__init__.py | 37 + pyhealth/medcode/omop/condition_hierarchy.py | 361 ++++++++ pyhealth/medcode/omop/icd_mapper.py | 222 +++++ pyhealth/medcode/omop/vocabulary.py | 404 +++++++++ tests/core/omop_test_utils.py | 196 +++++ tests/core/test_omop_condition_hierarchy.py | 243 ++++++ tests/core/test_omop_icd_mapper.py | 115 +++ tests/core/test_omop_vocabulary.py | 415 +-------- 12 files changed, 1771 insertions(+), 1228 deletions(-) delete mode 100644 pyhealth/medcode/omop.py create mode 100644 pyhealth/medcode/omop/__init__.py create mode 100644 pyhealth/medcode/omop/condition_hierarchy.py create mode 100644 pyhealth/medcode/omop/icd_mapper.py create mode 100644 pyhealth/medcode/omop/vocabulary.py create mode 100644 tests/core/omop_test_utils.py create mode 100644 tests/core/test_omop_condition_hierarchy.py create mode 100644 tests/core/test_omop_icd_mapper.py diff --git a/docs/api/medcode.rst b/docs/api/medcode.rst index 8ca2d4a48d..4419396296 100644 --- a/docs/api/medcode.rst +++ b/docs/api/medcode.rst @@ -235,31 +235,44 @@ OMOP Vocabularies (Athena) from `Athena `_. Athena vocabularies are licensed and cannot be redistributed, so PyHealth does not download them: create an Athena account, download a bundle that includes SNOMED, ICD9CM and ICD10CM, unzip it -outside your repository, and pass that folder to ``OMOPVocabulary``. +outside your repository, and pass that folder to ``OMOPVocabulary``. Athena +writes tab-separated files; for vocabulary tables from another source, pass an +``OMOPVocabularyFormat`` (separator, quoting, encoding, file names). It builds two objects: -- ``ConditionHierarchy``: the SNOMED condition graph rooted at "Disease" +- ``OMOPConditionHierarchy``: the SNOMED condition graph rooted at "Disease" (concept 4274025) and cut off at a chosen depth, as in KEEP - (`Elhussein et al., CHIL 2025 `_). By - default a concept is kept when its shortest path to "Disease" is at most - five levels; every "Is a" link between kept concepts is an edge, so concepts - with several parents keep all of them. + (`Elhussein et al., CHIL 2025 `_, + Appendix A.1.1). By default a concept is kept when its shortest path to + "Disease" in ``CONCEPT_ANCESTOR`` is at most five levels; every "Is a" link + between kept concepts is an edge, so concepts with several parents keep all + of them. - ``ICDToSNOMEDMapper``: maps ICD-9-CM and ICD-10-CM diagnosis codes, written with or without dots (MIMIC omits them), to standard concepts through - Athena's "Maps to" links. + Athena's "Maps to" links. It accepts in-memory and lazy polars tables. + +**Orphan rescue is an adapter policy, not part of KEEP.** Filtering to the +Condition domain leaves a few kept concepts whose only parents were dropped +(for example, a parent in the Observation domain). With +``connect_orphans=True`` (the default) each is attached to its nearest kept +ancestor, which may be several levels up. These edges are flagged ``rescued`` +and exported under their own relation (``rescued_is_a`` / +``rescued_subsumes``) so they are never mistaken for direct "Is a" links. The +KEEP paper does not say how such concepts are handled; pass +``connect_orphans=False`` to leave them unattached. .. code-block:: python import polars as pl - from pyhealth.medcode import ConditionHierarchy, ICDToSNOMEDMapper, OMOPVocabulary + from pyhealth.medcode import ICDToSNOMEDMapper, OMOPConditionHierarchy, OMOPVocabulary vocab = OMOPVocabulary("~/data/athena") # Build once from the multi-GB Athena files, then save for later runs hierarchy = vocab.condition_hierarchy(max_depth=5) hierarchy.save("~/.cache/pyhealth/omop/hierarchy_d5") - hierarchy = ConditionHierarchy.load("~/.cache/pyhealth/omop/hierarchy_d5") + hierarchy = OMOPConditionHierarchy.load("~/.cache/pyhealth/omop/hierarchy_d5") # Shallower graphs for a depth ablation, without re-reading Athena depth_3 = hierarchy.restrict(3) @@ -270,19 +283,87 @@ It builds two objects: # Kept ancestors of any concept under "Disease", nearest first hierarchy.retained_ancestors(concept_ids[0]) - # Map a whole diagnoses table, e.g. MIMIC-IV hosp/diagnoses_icd - diagnoses = pl.read_csv("~/data/mimiciv/3.1/hosp/diagnoses_icd.csv.gz", + # Map a whole diagnoses table, e.g. MIMIC-IV hosp/diagnoses_icd; a + # LazyFrame stays lazy, so this can sit inside a streaming pipeline + diagnoses = pl.scan_csv("~/data/mimiciv/3.1/hosp/diagnoses_icd.csv.gz", schema_overrides={"icd_code": pl.Utf8}) mapped = mapper.map_frame(diagnoses) - # Triples for pyhealth.graph.KnowledgeGraph - triples = hierarchy.to_triples() +Using the hierarchy as a ``KnowledgeGraph`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``to_knowledge_graph()`` returns a :class:`pyhealth.graph.KnowledgeGraph` +whose entities are OMOP ``concept_id`` values as strings. Every kept concept is +an entity, including any without edges. Depth, ancestor distances and rescue +flags stay on ``OMOPConditionHierarchy``; the graph only carries the edges and +their relation types. + +Edge direction matters for ``GraphProcessor``: its k-hop extraction follows +edges *into* the seed codes. ``to_knowledge_graph()`` therefore defaults to +``direction="parent_to_child"`` (``(parent, "subsumes", child)``), so a +patient's codes reach their ancestors. ``to_triples()`` defaults to +``direction="child_to_parent"`` (``(child, "is_a", parent)``); from a child +seed, a graph built from those triples reaches only descendants. + +The example below builds a three-concept hierarchy by hand; it needs +``torch-geometric`` for ``GraphProcessor``. + +.. code-block:: python + + import polars as pl + from pyhealth.medcode import OMOPConditionHierarchy + from pyhealth.processors import GraphProcessor + + # Disease (4274025) -> Heart disease (100) -> Ischemic heart disease (101) + hierarchy = OMOPConditionHierarchy( + nodes=pl.DataFrame({ + "concept_id": [4274025, 100, 101], + "concept_name": ["Disease", "Heart disease", "Ischemic heart disease"], + "concept_code": ["64572001", "56265001", "414545008"], + "min_depth": [0, 1, 2], + "max_depth": [0, 1, 2], + "depth": [0, 1, 2], + }), + edges=pl.DataFrame({ + "parent_id": [4274025, 100], + "child_id": [100, 101], + "rescued": [False, False], + }), + ancestors=pl.DataFrame({ + "concept_id": [100, 101, 101], + "ancestor_id": [4274025, 100, 4274025], + "distance": [1, 1, 2], + }), + root_concept_id=4274025, + max_depth=5, + depth_measure="min", + ) + + # Triples point child -> parent by default + assert hierarchy.to_triples() == [("100", "is_a", "4274025"), ("101", "is_a", "100")] + + # The KnowledgeGraph points parent -> child, keyed by string concept ids + kg = hierarchy.to_knowledge_graph() + assert set(kg.entity2id) == {"4274025", "100", "101"} + assert set(kg.relation2id) == {"subsumes", "rescued_subsumes"} + + # From the child seed, GraphProcessor reaches its ancestors + graph = GraphProcessor(knowledge_graph=kg, num_hops=2).process(["101"]) + assert {kg.id2entity[i] for i in graph.node_ids.tolist()} == {"101", "100", "4274025"} + + # Metadata stays on the hierarchy + assert hierarchy.depth(101) == 2 + assert hierarchy.retained_ancestors(101) == [(100, 1), (4274025, 2)] .. autoclass:: pyhealth.medcode.OMOPVocabulary :members: :show-inheritance: -.. autoclass:: pyhealth.medcode.ConditionHierarchy +.. autoclass:: pyhealth.medcode.OMOPVocabularyFormat + :members: + :show-inheritance: + +.. autoclass:: pyhealth.medcode.OMOPConditionHierarchy :members: :show-inheritance: diff --git a/examples/omop_keep_condition_graph_check.py b/examples/omop_keep_condition_graph_check.py index f838bf9a28..236295e835 100644 --- a/examples/omop_keep_condition_graph_check.py +++ b/examples/omop_keep_condition_graph_check.py @@ -14,9 +14,51 @@ --athena ~/data/athena \\ --mimic ~/data/mimiciv/3.1 -The first run reads the multi-GB Athena files (several minutes) and caches the +The first run reads the multi-GB Athena files (about a minute) and caches the results under --cache; later runs take seconds. Pass --rebuild to ignore the cache. + +Where these pieces fit in a PyHealth pipeline: + +1. Preparation (this script): build the hierarchy and the ICD mapper once from + Athena and save them. Everything below loads the saved copies. + +2. Task: a ``BaseTask`` maps diagnosis events to concepts while it builds + samples, the same way existing tasks call ``CrossMap``:: + + from pyhealth.medcode import ICDToSNOMEDMapper, OMOPConditionHierarchy + from pyhealth.tasks import BaseTask + + class KEEPConditions(BaseTask): + task_name = "keep_conditions" + input_schema = {"conditions": "sequence"} + output_schema = {} + + def __init__(self, cache="~/.cache/pyhealth/omop_keep"): + self.mapper = ICDToSNOMEDMapper.load(f"{cache}/icd_to_snomed.parquet") + self.hierarchy = OMOPConditionHierarchy.load( + f"{cache}/hierarchy_min_d6" + ).restrict(5) + + def __call__(self, patient): + concepts = set() + for event in patient.get_events(event_type="diagnoses_icd"): + for concept_id in self.mapper.map(event.icd_code, event.icd_version): + if concept_id in self.hierarchy: + concepts.add(str(concept_id)) + return [{"patient_id": patient.patient_id, + "conditions": sorted(concepts)}] if concepts else [] + + Codes deeper than the cutoff are skipped here; roll-up places them on the + graph with ``hierarchy.retained_ancestors()``. + +3. Processor: a model that wants a patient subgraph uses PyHealth's "graph" + processor on those concept ids:: + + input_schema = {"conditions": ("graph", { + "knowledge_graph": hierarchy.to_knowledge_graph(), # parent_to_child + "num_hops": 2, + })} """ import argparse @@ -25,7 +67,11 @@ import polars as pl -from pyhealth.medcode import ConditionHierarchy, ICDToSNOMEDMapper, OMOPVocabulary +from pyhealth.medcode import ( + ICDToSNOMEDMapper, + OMOPConditionHierarchy, + OMOPVocabulary, +) BASE_DEPTH = 6 # deepest graph in the ablation; shallower ones are cut from it @@ -62,7 +108,10 @@ def load_or_build(args: argparse.Namespace): mapper_path = cache / "icd_to_snomed.parquet" if not args.rebuild and graph_dir.is_dir() and mapper_path.is_file(): print(f"Using cached graph and mapping in {cache}") - return ConditionHierarchy.load(graph_dir), ICDToSNOMEDMapper.load(mapper_path) + return ( + OMOPConditionHierarchy.load(graph_dir), + ICDToSNOMEDMapper.load(mapper_path), + ) vocab = OMOPVocabulary(args.athena) start = time.time() @@ -77,7 +126,7 @@ def load_or_build(args: argparse.Namespace): return hierarchy, mapper -def report_graphs(hierarchy: ConditionHierarchy, depths) -> None: +def report_graphs(hierarchy: OMOPConditionHierarchy, depths) -> None: print("\nCondition graph by depth limit (root = Disease, depth 0)") print(f"{'measure':>8} {'depth':>5} {'nodes':>8} {'edges':>8} {'rescued':>8}") for measure in ("min", "max"): diff --git a/pyhealth/medcode/__init__.py b/pyhealth/medcode/__init__.py index d2f7590171..713a27b90b 100644 --- a/pyhealth/medcode/__init__.py +++ b/pyhealth/medcode/__init__.py @@ -23,9 +23,10 @@ from .inner_map import InnerMap from .omop import ( DISEASE_CONCEPT_ID, - ConditionHierarchy, ICDToSNOMEDMapper, + OMOPConditionHierarchy, OMOPVocabulary, + OMOPVocabularyFormat, ) __all__ = [ @@ -46,12 +47,13 @@ "ICD10PROC", "NDC", "UMLS", - "ConditionHierarchy", "CrossMap", "DISEASE_CONCEPT_ID", "FlatMap", "ICDToSNOMEDMapper", "InnerMap", + "OMOPConditionHierarchy", "OMOPVocabulary", + "OMOPVocabularyFormat", "RxNorm", ] diff --git a/pyhealth/medcode/omop.py b/pyhealth/medcode/omop.py deleted file mode 100644 index fd06892783..0000000000 --- a/pyhealth/medcode/omop.py +++ /dev/null @@ -1,834 +0,0 @@ -"""OMOP standardized vocabularies (Athena) for PyHealth. - -This module reads a local download of the OMOP standardized vocabularies from -Athena (https://athena.ohdsi.org) and provides two things: - -* :class:`ConditionHierarchy`: the SNOMED condition graph rooted at the concept - "Disease" and cut off at a chosen depth, as used by KEEP (Elhussein et al., - CHIL 2025, appendix A.1.1). -* :class:`ICDToSNOMEDMapper`: a lookup from ICD-9-CM and ICD-10-CM diagnosis - codes, in the dot-free form MIMIC stores them, to standard OMOP concepts. - -Athena vocabularies are licensed and cannot be redistributed, so PyHealth does -not download them. Point :class:`OMOPVocabulary` at the folder you unzipped. - -Example: - >>> from pyhealth.medcode import OMOPVocabulary - >>> vocab = OMOPVocabulary("~/data/athena") # doctest: +SKIP - >>> hierarchy = vocab.condition_hierarchy(max_depth=5) # doctest: +SKIP - >>> mapper = vocab.icd_mapper() # doctest: +SKIP - >>> concept_ids = mapper.map("I214", version=10) # doctest: +SKIP - >>> # kept ancestors of each target, nearest first: [(ancestor_id, levels)] - >>> hierarchy.retained_ancestors(concept_ids[0]) # doctest: +SKIP -""" - -from __future__ import annotations - -import json -import logging -from collections import defaultdict -from pathlib import Path -from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union - -import networkx as nx -import polars as pl - -logger = logging.getLogger(__name__) - -#: OMOP concept_id of SNOMED 64572001 "Disease", the root KEEP uses. -DISEASE_CONCEPT_ID = 4274025 - -#: ICD version number (as in MIMIC's ``icd_version`` column) -> OMOP vocabulary. -ICD_VERSION_TO_VOCABULARY = {9: "ICD9CM", 10: "ICD10CM"} - -_REQUIRED_COLUMNS = { - "CONCEPT": [ - "concept_id", - "concept_name", - "domain_id", - "vocabulary_id", - "concept_class_id", - "standard_concept", - "concept_code", - "invalid_reason", - ], - "CONCEPT_RELATIONSHIP": [ - "concept_id_1", - "concept_id_2", - "relationship_id", - "invalid_reason", - ], - "CONCEPT_ANCESTOR": [ - "ancestor_concept_id", - "descendant_concept_id", - "min_levels_of_separation", - "max_levels_of_separation", - ], -} - -_ID_COLUMNS = { - "concept_id", - "concept_id_1", - "concept_id_2", - "ancestor_concept_id", - "descendant_concept_id", - "min_levels_of_separation", - "max_levels_of_separation", -} - - -def _is_valid() -> pl.Expr: - """Rows Athena has not marked deprecated ("D") or upgraded ("U").""" - reason = pl.col("invalid_reason") - return reason.is_null() | (reason.str.strip_chars() == "") - - -def _collect(frame: pl.LazyFrame) -> pl.DataFrame: - """Collects with the streaming engine, so multi-GB files fit in memory.""" - return frame.collect(engine="streaming") - - -def normalize_icd_code(code: str) -> str: - """Puts an ICD code in the dot-free, upper-case form MIMIC uses. - - Athena stores ``I21.4`` and MIMIC stores ``I214``. Comparing both in the - dot-free form avoids having to know where each ICD version puts its dot - (ICD-9 E-codes put it after the fourth character, everything else after - the third). - - Args: - code: An ICD-9-CM or ICD-10-CM code, with or without a dot. - - Returns: - The code without dots or surrounding whitespace, in upper case. - - Example: - >>> normalize_icd_code(" i21.4 ") - 'I214' - >>> normalize_icd_code("E880.9") - 'E8809' - """ - return str(code).strip().replace(".", "").upper() - - -def _icd_vocabulary(version: Union[int, str]) -> str: - try: - return ICD_VERSION_TO_VOCABULARY[int(version)] - except (KeyError, ValueError) as err: - raise ValueError( - f"Unsupported ICD version {version!r}; expected 9 or 10." - ) from err - - -def _rescue_orphans( - nodes: pl.DataFrame, - edges: pl.DataFrame, - ancestors: pl.DataFrame, - root_concept_id: int, -) -> pl.DataFrame: - """Attaches each parentless non-root node to its nearest kept ancestor. - - Ties on distance go to the smaller ancestor id, so the result does not - depend on file order. - """ - orphans = nodes.filter(pl.col("concept_id") != root_concept_id).join( - edges, left_on="concept_id", right_on="child_id", how="anti" - ) - if orphans.height == 0: - return edges - rescue = ( - ancestors.join(orphans.select("concept_id"), on="concept_id", how="semi") - .join(nodes.select("concept_id"), left_on="ancestor_id", - right_on="concept_id", how="semi") - .sort("concept_id", "distance", "ancestor_id") - .group_by("concept_id", maintain_order=True) - .first() - .select( - pl.col("ancestor_id").alias("parent_id"), - pl.col("concept_id").alias("child_id"), - pl.lit(True).alias("rescued"), - ) - ) - return pl.concat([edges, rescue]) - - -class OMOPVocabulary: - """Reads an Athena download of the OMOP standardized vocabularies. - - Only ``CONCEPT.csv``, ``CONCEPT_RELATIONSHIP.csv`` and - ``CONCEPT_ANCESTOR.csv`` are read. Athena writes them tab-separated despite - the ``.csv`` name, and they are several GB, so they are scanned lazily and - filtered while reading rather than loaded whole. - - Args: - root: Folder containing the unzipped Athena files. - - Raises: - FileNotFoundError: If ``root`` or one of the three files is missing. - ValueError: If a file lacks a column this module needs (for example - because it was re-saved comma-separated). - - Example: - >>> vocab = OMOPVocabulary("~/data/athena") # doctest: +SKIP - >>> hierarchy = vocab.condition_hierarchy(max_depth=5) # doctest: +SKIP - """ - - def __init__(self, root: Union[str, Path]): - self.root = Path(root).expanduser() - if not self.root.is_dir(): - raise FileNotFoundError(f"Athena folder not found: {self.root}") - for table, columns in _REQUIRED_COLUMNS.items(): - self._check_header(table, columns) - - def __repr__(self) -> str: - return f"OMOPVocabulary(root={str(self.root)!r})" - - def _path(self, table: str) -> Path: - return self.root / f"{table}.csv" - - def _check_header(self, table: str, columns: Sequence[str]) -> None: - path = self._path(table) - if not path.is_file(): - raise FileNotFoundError( - f"{path.name} not found in {self.root}. Download the " - "vocabularies from https://athena.ohdsi.org and unzip them there." - ) - with open(path, encoding="utf-8", errors="replace") as handle: - header = handle.readline().rstrip("\r\n").split("\t") - missing = [column for column in columns if column not in header] - if missing: - raise ValueError( - f"{path.name} is missing columns {missing}. Athena files are " - "tab-separated; use the files exactly as unzipped from Athena." - ) - - def scan(self, table: str) -> pl.LazyFrame: - """Lazily reads one Athena table. - - Every column is read as text, then id and level columns are cast to - integers. Quote characters are not treated specially because concept - names contain unbalanced quotes. - - Args: - table: ``"CONCEPT"``, ``"CONCEPT_RELATIONSHIP"`` or - ``"CONCEPT_ANCESTOR"``. - - Returns: - A polars ``LazyFrame`` over the file. - """ - if table not in _REQUIRED_COLUMNS: - raise ValueError( - f"Unknown table {table!r}; expected one of " - f"{sorted(_REQUIRED_COLUMNS)}." - ) - frame = pl.scan_csv( - self._path(table), - separator="\t", - quote_char=None, - infer_schema=False, - encoding="utf8-lossy", - ) - names = frame.collect_schema().names() - return frame.with_columns( - pl.col(name).cast(pl.Int64) for name in names if name in _ID_COLUMNS - ) - - def condition_hierarchy( - self, - root_concept_id: int = DISEASE_CONCEPT_ID, - max_depth: Optional[int] = 5, - depth_measure: str = "min", - connect_orphans: bool = True, - ) -> "ConditionHierarchy": - """Builds the depth-limited SNOMED condition graph KEEP uses. - - Nodes are valid, standard SNOMED concepts in the Condition domain that - descend from ``root_concept_id`` within ``max_depth`` levels, plus the - root. Edges are the "Is a" relationships between nodes, so a concept - with several parents keeps all of them. - - Args: - root_concept_id: Root of the graph. Defaults to "Disease". - max_depth: Deepest level to keep, counted from the root (depth 0). - ``None`` keeps every descendant. - depth_measure: How a concept's depth is counted, because SNOMED - concepts can sit at several depths at once. ``"min"`` (the - KEEP paper) uses the shortest path to the root; - ``"max"`` uses the longest. - connect_orphans: Some kept concepts have only parents that were - filtered out (for example a parent in another domain). If - True, each such concept is attached to its nearest kept - ancestor so the graph stays connected; these edges are marked - ``rescued`` in :attr:`ConditionHierarchy.edges`. - - Returns: - The :class:`ConditionHierarchy`. - """ - if depth_measure not in ("min", "max"): - raise ValueError("depth_measure must be 'min' or 'max'.") - if max_depth is not None and max_depth < 0: - raise ValueError("max_depth must be non-negative or None.") - logger.info("Building SNOMED condition hierarchy from %s", self.root) - - conditions = ( - self.scan("CONCEPT") - .filter( - (pl.col("vocabulary_id") == "SNOMED") - & (pl.col("domain_id") == "Condition") - & (pl.col("standard_concept") == "S") - & _is_valid() - ) - .select("concept_id", "concept_name", "concept_code") - ) - levels = ( - self.scan("CONCEPT_ANCESTOR") - .filter(pl.col("ancestor_concept_id") == root_concept_id) - .select( - pl.col("descendant_concept_id").alias("concept_id"), - pl.col("min_levels_of_separation").alias("min_depth"), - pl.col("max_levels_of_separation").alias("max_depth"), - ) - ) - subtree = _collect(levels.join(conditions, on="concept_id", how="inner")) - root = _collect( - conditions.filter(pl.col("concept_id") == root_concept_id) - ) - if root.height == 0: - raise ValueError( - f"Root concept {root_concept_id} is not a valid standard SNOMED " - "Condition concept in this vocabulary." - ) - if root_concept_id not in subtree["concept_id"]: - subtree = pl.concat( - [ - subtree, - root.with_columns( - pl.lit(0, pl.Int64).alias("min_depth"), - pl.lit(0, pl.Int64).alias("max_depth"), - ).select(subtree.columns), - ] - ) - subtree = subtree.with_columns( - pl.col(f"{depth_measure}_depth").alias("depth") - ).unique("concept_id") - - nodes = subtree - if max_depth is not None: - nodes = subtree.filter(pl.col("depth") <= max_depth) - nodes = nodes.sort("depth", "concept_id") - node_ids = nodes.select("concept_id").lazy() - - edges = _collect( - self.scan("CONCEPT_RELATIONSHIP") - .filter((pl.col("relationship_id") == "Is a") & _is_valid()) - .select( - pl.col("concept_id_2").alias("parent_id"), - pl.col("concept_id_1").alias("child_id"), - ) - .join(node_ids, left_on="parent_id", right_on="concept_id", how="semi") - .join(node_ids, left_on="child_id", right_on="concept_id", how="semi") - .filter(pl.col("parent_id") != pl.col("child_id")) - .unique() - ).with_columns(pl.lit(False).alias("rescued")) - - ancestors = _collect( - self.scan("CONCEPT_ANCESTOR") - .filter(pl.col("min_levels_of_separation") > 0) - .select( - pl.col("descendant_concept_id").alias("concept_id"), - pl.col("ancestor_concept_id").alias("ancestor_id"), - pl.col("min_levels_of_separation").alias("distance"), - ) - .join(subtree.select("concept_id").lazy(), on="concept_id", how="semi") - .join(node_ids, left_on="ancestor_id", right_on="concept_id", how="semi") - ) - - if connect_orphans: - edges = _rescue_orphans(nodes, edges, ancestors, root_concept_id) - logger.info( - "Condition hierarchy: %d concepts, %d edges, %d orphans re-attached", - nodes.height, - edges.height, - int(edges["rescued"].sum()), - ) - - return ConditionHierarchy( - nodes=nodes, - edges=edges.sort("parent_id", "child_id"), - ancestors=ancestors.sort("concept_id", "distance", "ancestor_id"), - root_concept_id=root_concept_id, - max_depth=max_depth, - depth_measure=depth_measure, - connect_orphans=connect_orphans, - ) - - def icd_mapper( - self, versions: Iterable[Union[int, str]] = (9, 10) - ) -> "ICDToSNOMEDMapper": - """Builds the ICD -> standard concept lookup from "Maps to" links. - - Source ICD concepts are kept even when Athena has deprecated them, - because older records (such as MIMIC's ICD-9 era) still use them; - only the "Maps to" links themselves must be valid. - - Args: - versions: ICD versions to include (9 and/or 10). - - Returns: - The :class:`ICDToSNOMEDMapper`. - """ - vocabularies = [_icd_vocabulary(version) for version in versions] - concept = self.scan("CONCEPT") - sources = concept.filter(pl.col("vocabulary_id").is_in(vocabularies)).select( - pl.col("vocabulary_id"), - pl.col("concept_code").alias("source_code"), - pl.col("concept_id").alias("source_concept_id"), - ) - maps_to = ( - self.scan("CONCEPT_RELATIONSHIP") - .filter((pl.col("relationship_id") == "Maps to") & _is_valid()) - .select( - pl.col("concept_id_1").alias("source_concept_id"), - pl.col("concept_id_2").alias("concept_id"), - ) - .join(sources.select("source_concept_id"), on="source_concept_id", - how="semi") - ) - targets = concept.select( - "concept_id", - pl.col("concept_name"), - pl.col("domain_id").alias("target_domain_id"), - pl.col("vocabulary_id").alias("target_vocabulary_id"), - ) - version_of = {name: number for number, name in - ICD_VERSION_TO_VOCABULARY.items()} - table = _collect( - sources.join(maps_to, on="source_concept_id", how="left") - .join(targets, on="concept_id", how="left") - .with_columns( - pl.col("vocabulary_id") - .replace_strict(version_of, return_dtype=pl.Int64) - .alias("icd_version"), - pl.col("source_code") - .str.strip_chars() - .str.replace_all(".", "", literal=True) - .str.to_uppercase() - .alias("icd_code"), - ) - .unique() - ) - return ICDToSNOMEDMapper( - table.select( - "icd_version", - "icd_code", - "source_code", - "source_concept_id", - "concept_id", - "concept_name", - "target_domain_id", - "target_vocabulary_id", - ).sort("icd_version", "icd_code", "concept_id", nulls_last=True) - ) - - -class ConditionHierarchy: - """A depth-limited SNOMED condition graph rooted at one concept. - - Build it with :meth:`OMOPVocabulary.condition_hierarchy`, or reload a saved - one with :meth:`load`. Concept ids are OMOP ``concept_id`` integers. - - Attributes: - nodes: One row per kept concept: ``concept_id``, ``concept_name``, - ``concept_code`` (the SNOMED code), ``min_depth``, ``max_depth`` - and ``depth`` (whichever of the two was used to cut the graph). - edges: ``parent_id``, ``child_id`` and ``rescued`` for every "Is a" - link between kept concepts, plus any orphan rescues. - ancestors: ``concept_id``, ``ancestor_id``, ``distance`` for every - concept under the root (kept or deeper) and each of its kept - ancestors, with ``distance`` the shortest number of levels between - them. Roll-up uses this to place deep concepts on the graph. - root_concept_id: The root concept. - max_depth: The depth limit, or None for no limit. - depth_measure: ``"min"`` or ``"max"``. - connect_orphans: Whether orphans were attached to their nearest kept - ancestor. - """ - - def __init__( - self, - nodes: pl.DataFrame, - edges: pl.DataFrame, - ancestors: pl.DataFrame, - root_concept_id: int, - max_depth: Optional[int], - depth_measure: str, - connect_orphans: bool = True, - ): - self.nodes = nodes - self.edges = edges - self.ancestors = ancestors - self.root_concept_id = root_concept_id - self.max_depth = max_depth - self.depth_measure = depth_measure - self.connect_orphans = connect_orphans - self._info = { - row["concept_id"]: row for row in nodes.iter_rows(named=True) - } - self._parents: Dict[int, List[int]] = defaultdict(list) - self._children: Dict[int, List[int]] = defaultdict(list) - for parent, child in edges.select("parent_id", "child_id").iter_rows(): - self._parents[child].append(parent) - self._children[parent].append(child) - self._ancestor_index: Optional[Dict[int, List[Tuple[int, int]]]] = None - - def __repr__(self) -> str: - return ( - f"ConditionHierarchy(root={self.root_concept_id}, " - f"max_depth={self.max_depth}, depth_measure={self.depth_measure!r}, " - f"nodes={len(self)}, edges={self.edges.height})" - ) - - def __len__(self) -> int: - return self.nodes.height - - def __contains__(self, concept_id: int) -> bool: - return concept_id in self._info - - def _require(self, concept_id: int) -> dict: - try: - return self._info[concept_id] - except KeyError: - raise KeyError(f"Concept {concept_id} is not in the hierarchy.") from None - - def name(self, concept_id: int) -> str: - """Returns a kept concept's name.""" - return self._require(concept_id)["concept_name"] - - def depth(self, concept_id: int) -> int: - """Returns a kept concept's depth below the root.""" - return self._require(concept_id)["depth"] - - def parents(self, concept_id: int) -> List[int]: - """Returns a kept concept's parents in the graph, sorted.""" - self._require(concept_id) - return sorted(self._parents.get(concept_id, [])) - - def children(self, concept_id: int) -> List[int]: - """Returns a kept concept's children in the graph, sorted.""" - self._require(concept_id) - return sorted(self._children.get(concept_id, [])) - - def retained_ancestors(self, concept_id: int) -> List[Tuple[int, int]]: - """Lists the kept ancestors of any concept under the root. - - Works for concepts deeper than ``max_depth`` too, which is what - roll-up needs. A concept with several parents gets ancestors along - every path. - - Args: - concept_id: Any concept under the root, kept or not. - - Returns: - ``(ancestor_id, distance)`` pairs, nearest first. Empty if the - concept is not under the root. - """ - if self._ancestor_index is None: - self._ancestor_index = defaultdict(list) - for child, ancestor, distance in self.ancestors.iter_rows(): - self._ancestor_index[child].append((ancestor, distance)) - return list(self._ancestor_index.get(concept_id, [])) - - def restrict( - self, max_depth: int, depth_measure: Optional[str] = None - ) -> "ConditionHierarchy": - """Cuts this hierarchy to a shallower depth without re-reading Athena. - - Build once with a generous limit (or ``max_depth=None``), then call - this for each depth in an ablation. The result is the same as - building at the smaller depth directly. - - Args: - max_depth: The new, smaller depth limit. - depth_measure: ``"min"`` or ``"max"``; defaults to this - hierarchy's measure. - - Returns: - A new :class:`ConditionHierarchy`. - - Raises: - ValueError: If the new graph would need concepts this one dropped. - """ - depth_measure = depth_measure or self.depth_measure - if depth_measure not in ("min", "max"): - raise ValueError("depth_measure must be 'min' or 'max'.") - if max_depth is None or max_depth < 0: - raise ValueError("max_depth must be a non-negative integer.") - # a concept's max depth is never below its min depth, so a cut on - # max depth keeps a subset of the same cut on min depth - covered = self.max_depth is None or ( - max_depth <= self.max_depth - and (self.depth_measure == "min" or depth_measure == "max") - ) - if not covered: - raise ValueError( - f"Cannot restrict a hierarchy built with max_depth=" - f"{self.max_depth} ({self.depth_measure}) to max_depth=" - f"{max_depth} ({depth_measure}); build a deeper one first." - ) - nodes = ( - self.nodes.with_columns(pl.col(f"{depth_measure}_depth").alias("depth")) - .filter(pl.col("depth") <= max_depth) - .sort("depth", "concept_id") - ) - kept = nodes.select("concept_id") - edges = ( - self.edges.filter(~pl.col("rescued")) - .join(kept, left_on="parent_id", right_on="concept_id", how="semi") - .join(kept, left_on="child_id", right_on="concept_id", how="semi") - ) - ancestors = self.ancestors.join( - kept, left_on="ancestor_id", right_on="concept_id", how="semi" - ) - if self.connect_orphans: - edges = _rescue_orphans(nodes, edges, ancestors, self.root_concept_id) - return ConditionHierarchy( - nodes=nodes, - edges=edges.sort("parent_id", "child_id"), - ancestors=ancestors, - root_concept_id=self.root_concept_id, - max_depth=max_depth, - depth_measure=depth_measure, - connect_orphans=self.connect_orphans, - ) - - def to_networkx(self) -> nx.DiGraph: - """Returns the graph as a ``networkx.DiGraph`` with parent -> child edges. - - Node attributes are ``name``, ``code`` and ``depth``; edge attribute - ``rescued`` marks orphan rescues. - """ - graph = nx.DiGraph() - for row in self.nodes.iter_rows(named=True): - graph.add_node( - row["concept_id"], - name=row["concept_name"], - code=row["concept_code"], - depth=row["depth"], - ) - for parent, child, rescued in self.edges.iter_rows(): - graph.add_edge(parent, child, rescued=rescued) - return graph - - def to_triples(self, relation: str = "is_a") -> List[Tuple[str, str, str]]: - """Returns ``(child, relation, parent)`` string triples. - - This is the input format of :class:`pyhealth.graph.KnowledgeGraph`. - - Args: - relation: Relation name to use for every edge. - """ - return [ - (str(child), relation, str(parent)) - for parent, child in self.edges.select("parent_id", "child_id") - .iter_rows() - ] - - def save(self, folder: Union[str, Path]) -> None: - """Saves the hierarchy as parquet files, so later runs skip Athena. - - Args: - folder: Folder to write to; created if needed. - """ - folder = Path(folder).expanduser() - folder.mkdir(parents=True, exist_ok=True) - self.nodes.write_parquet(folder / "nodes.parquet") - self.edges.write_parquet(folder / "edges.parquet") - self.ancestors.write_parquet(folder / "ancestors.parquet") - meta = { - "root_concept_id": self.root_concept_id, - "max_depth": self.max_depth, - "depth_measure": self.depth_measure, - "connect_orphans": self.connect_orphans, - } - (folder / "meta.json").write_text(json.dumps(meta, indent=2)) - - @classmethod - def load(cls, folder: Union[str, Path]) -> "ConditionHierarchy": - """Loads a hierarchy written by :meth:`save`. - - Args: - folder: Folder passed to :meth:`save`. - """ - folder = Path(folder).expanduser() - meta = json.loads((folder / "meta.json").read_text()) - return cls( - nodes=pl.read_parquet(folder / "nodes.parquet"), - edges=pl.read_parquet(folder / "edges.parquet"), - ancestors=pl.read_parquet(folder / "ancestors.parquet"), - **meta, - ) - - -class ICDToSNOMEDMapper: - """Maps ICD-9-CM and ICD-10-CM diagnosis codes to standard OMOP concepts. - - Build it with :meth:`OMOPVocabulary.icd_mapper`, or reload a saved one with - :meth:`load`. Codes are matched in MIMIC's dot-free form, so ``"I214"`` - and ``"I21.4"`` are the same code. One ICD code can map to several - concepts, and some map to none. - - Attributes: - table: One row per (ICD code, target concept): ``icd_version``, - ``icd_code`` (dot-free), ``source_code`` (as Athena writes it), - ``source_concept_id``, ``concept_id`` (null when the code has no - valid "Maps to" link), ``concept_name``, ``target_domain_id`` and - ``target_vocabulary_id``. - """ - - def __init__(self, table: pl.DataFrame): - self.table = table - self._lookup: Dict[Tuple[int, str], List[int]] = defaultdict(list) - self._known = set() - for version, code, concept_id in table.select( - "icd_version", "icd_code", "concept_id" - ).iter_rows(): - self._known.add((version, code)) - if concept_id is not None: - self._lookup[(version, code)].append(concept_id) - - def __repr__(self) -> str: - return f"ICDToSNOMEDMapper(codes={len(self._known)})" - - def __contains__(self, key: Tuple[Union[int, str], str]) -> bool: - version, code = key - return (int(version), normalize_icd_code(code)) in self._known - - def map(self, code: str, version: Union[int, str]) -> List[int]: - """Maps one ICD code to standard concept ids. - - Args: - code: The ICD code, with or without a dot. - version: 9 or 10 (MIMIC's ``icd_version``). - - Returns: - Sorted, de-duplicated target concept ids; empty if the code is - unknown or has no valid mapping. - """ - _icd_vocabulary(version) - key = (int(version), normalize_icd_code(code)) - return sorted(set(self._lookup.get(key, []))) - - def map_frame( - self, - frame: pl.DataFrame, - code_column: str = "icd_code", - version_column: str = "icd_version", - ) -> pl.DataFrame: - """Adds mapped concepts to a table of diagnoses, such as MIMIC's. - - Rows whose code maps to several concepts are repeated, one per - concept. Rows that do not map keep a null ``concept_id``. - - Args: - frame: A table with an ICD code column and a version column. - code_column: Name of the code column. - version_column: Name of the version column. - - Returns: - ``frame`` with ``concept_id`` and ``target_domain_id`` added. - """ - lookup = self.table.select( - "icd_version", "icd_code", "concept_id", "target_domain_id" - ).filter(pl.col("concept_id").is_not_null()) - keyed = frame.with_columns( - pl.col(version_column).cast(pl.Int64).alias("__version"), - pl.col(code_column) - .cast(pl.Utf8) - .str.strip_chars() - .str.replace_all(".", "", literal=True) - .str.to_uppercase() - .alias("__code"), - ) - return keyed.join( - lookup, - left_on=["__version", "__code"], - right_on=["icd_version", "icd_code"], - how="left", - ).drop("__version", "__code") - - def coverage( - self, - frame: pl.DataFrame, - hierarchy: Optional[ConditionHierarchy] = None, - code_column: str = "icd_code", - version_column: str = "icd_version", - ) -> Dict[str, int]: - """Counts how many distinct codes in a table map, without listing any. - - Args: - frame: A table with an ICD code column and a version column. - hierarchy: If given, also counts codes that land under its root - (kept, or deeper and reachable by roll-up). - code_column: Name of the code column. - version_column: Name of the version column. - - Returns: - Counts of distinct (version, code) pairs: ``codes``, - ``unknown`` (not in Athena), ``no_mapping`` (in Athena, no valid - "Maps to"), ``mapped``; with a hierarchy, also ``in_hierarchy`` - (at least one target under the root) and ``outside_hierarchy``. - """ - codes = frame.select( - pl.col(version_column).cast(pl.Int64).alias("icd_version"), - pl.col(code_column) - .cast(pl.Utf8) - .str.strip_chars() - .str.replace_all(".", "", literal=True) - .str.to_uppercase() - .alias("icd_code"), - ).unique() - known = codes.join( - self.table.select("icd_version", "icd_code").unique(), - on=["icd_version", "icd_code"], - how="semi", - ) - mapped = self.map_frame(codes).filter(pl.col("concept_id").is_not_null()) - mapped_codes = mapped.select("icd_version", "icd_code").unique() - result = { - "codes": codes.height, - "unknown": codes.height - known.height, - "no_mapping": known.height - mapped_codes.height, - "mapped": mapped_codes.height, - } - if hierarchy is not None: - under_root = set(hierarchy.nodes["concept_id"]) | set( - hierarchy.ancestors["concept_id"] - ) - inside = ( - mapped.filter(pl.col("concept_id").is_in(list(under_root))) - .select("icd_version", "icd_code") - .unique() - .height - ) - result["in_hierarchy"] = inside - result["outside_hierarchy"] = mapped_codes.height - inside - return result - - def save(self, path: Union[str, Path]) -> None: - """Saves the mapping table as one parquet file. - - Args: - path: File to write, for example ``icd_to_snomed.parquet``. - """ - path = Path(path).expanduser() - path.parent.mkdir(parents=True, exist_ok=True) - self.table.write_parquet(path) - - @classmethod - def load(cls, path: Union[str, Path]) -> "ICDToSNOMEDMapper": - """Loads a mapper written by :meth:`save`. - - Args: - path: File passed to :meth:`save`. - """ - return cls(pl.read_parquet(Path(path).expanduser())) diff --git a/pyhealth/medcode/omop/__init__.py b/pyhealth/medcode/omop/__init__.py new file mode 100644 index 0000000000..05f8a7688f --- /dev/null +++ b/pyhealth/medcode/omop/__init__.py @@ -0,0 +1,37 @@ +"""OMOP standardized vocabularies (Athena) for PyHealth. + +Reads a local download of the OMOP standardized vocabularies from Athena +(https://athena.ohdsi.org) and provides: + +* :class:`OMOPVocabulary`: the reader (``vocabulary.py``). +* :class:`OMOPConditionHierarchy`: the SNOMED condition graph rooted at + "Disease" and cut off at a chosen depth, as used by KEEP (Elhussein et al., + CHIL 2025, appendix A.1.1) (``condition_hierarchy.py``). +* :class:`ICDToSNOMEDMapper`: maps ICD-9-CM and ICD-10-CM diagnosis codes, in + the dot-free form MIMIC stores them, to standard OMOP concepts + (``icd_mapper.py``). + +Example: + >>> from pyhealth.medcode import OMOPVocabulary + >>> vocab = OMOPVocabulary("~/data/athena") # doctest: +SKIP + >>> hierarchy = vocab.condition_hierarchy(max_depth=5) # doctest: +SKIP + >>> mapper = vocab.icd_mapper() # doctest: +SKIP + >>> concept_ids = mapper.map("I214", version=10) # doctest: +SKIP + >>> # kept ancestors of each target, nearest first: [(ancestor_id, levels)] + >>> hierarchy.retained_ancestors(concept_ids[0]) # doctest: +SKIP +""" + +from .condition_hierarchy import RELATIONS, OMOPConditionHierarchy +from .icd_mapper import ICD_VERSION_TO_VOCABULARY, ICDToSNOMEDMapper, normalize_icd_code +from .vocabulary import DISEASE_CONCEPT_ID, OMOPVocabulary, OMOPVocabularyFormat + +__all__ = [ + "DISEASE_CONCEPT_ID", + "ICD_VERSION_TO_VOCABULARY", + "ICDToSNOMEDMapper", + "OMOPConditionHierarchy", + "OMOPVocabulary", + "OMOPVocabularyFormat", + "RELATIONS", + "normalize_icd_code", +] diff --git a/pyhealth/medcode/omop/condition_hierarchy.py b/pyhealth/medcode/omop/condition_hierarchy.py new file mode 100644 index 0000000000..627b2158ab --- /dev/null +++ b/pyhealth/medcode/omop/condition_hierarchy.py @@ -0,0 +1,361 @@ +"""SNOMED condition hierarchy built from OMOP vocabularies, as used by KEEP. + +Build one with :meth:`pyhealth.medcode.OMOPVocabulary.condition_hierarchy`. +""" + +from __future__ import annotations + +import json +import logging +from collections import defaultdict +from pathlib import Path +from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union + +import networkx as nx +import polars as pl + +if TYPE_CHECKING: + from pyhealth.graph import KnowledgeGraph + +logger = logging.getLogger(__name__) + +#: Relation names for exported edges, by direction: (direct link, rescue edge). +RELATIONS = { + "child_to_parent": ("is_a", "rescued_is_a"), + "parent_to_child": ("subsumes", "rescued_subsumes"), +} + + +def _rescue_orphans( + nodes: pl.DataFrame, + edges: pl.DataFrame, + ancestors: pl.DataFrame, + root_concept_id: int, +) -> pl.DataFrame: + """Attaches each parentless non-root node to its nearest kept ancestor. + + Ties on distance go to the smaller ancestor id, so the result does not + depend on file order. + """ + orphans = nodes.filter(pl.col("concept_id") != root_concept_id).join( + edges, left_on="concept_id", right_on="child_id", how="anti" + ) + if orphans.height == 0: + return edges + rescue = ( + ancestors.join(orphans.select("concept_id"), on="concept_id", how="semi") + .join(nodes.select("concept_id"), left_on="ancestor_id", + right_on="concept_id", how="semi") + .sort("concept_id", "distance", "ancestor_id") + .group_by("concept_id", maintain_order=True) + .first() + .select( + pl.col("ancestor_id").alias("parent_id"), + pl.col("concept_id").alias("child_id"), + pl.lit(True).alias("rescued"), + ) + ) + return pl.concat([edges, rescue]) + + +class OMOPConditionHierarchy: + """A depth-limited SNOMED condition graph rooted at one concept. + + Build it with :meth:`OMOPVocabulary.condition_hierarchy`, or reload a saved + one with :meth:`load`. Concept ids are OMOP ``concept_id`` integers. + + Attributes: + nodes: One row per kept concept: ``concept_id``, ``concept_name``, + ``concept_code`` (the SNOMED code), ``min_depth``, ``max_depth`` + and ``depth`` (whichever of the two was used to cut the graph). + edges: ``parent_id``, ``child_id`` and ``rescued`` for every "Is a" + link between kept concepts, plus any orphan rescues. Rescue is an + adapter policy of this module, not part of KEEP, whose paper does + not say how disconnected concepts are handled. + ancestors: ``concept_id``, ``ancestor_id``, ``distance`` for every + concept under the root (kept or deeper) and each of its kept + ancestors, with ``distance`` the shortest number of levels between + them. Roll-up uses this to place deep concepts on the graph. + root_concept_id: The root concept. + max_depth: The depth limit, or None for no limit. + depth_measure: ``"min"`` or ``"max"``. + connect_orphans: Whether orphans were attached to their nearest kept + ancestor. + """ + + def __init__( + self, + nodes: pl.DataFrame, + edges: pl.DataFrame, + ancestors: pl.DataFrame, + root_concept_id: int, + max_depth: Optional[int], + depth_measure: str, + connect_orphans: bool = True, + ): + self.nodes = nodes + self.edges = edges + self.ancestors = ancestors + self.root_concept_id = root_concept_id + self.max_depth = max_depth + self.depth_measure = depth_measure + self.connect_orphans = connect_orphans + self._info = { + row["concept_id"]: row for row in nodes.iter_rows(named=True) + } + self._parents: Dict[int, List[int]] = defaultdict(list) + self._children: Dict[int, List[int]] = defaultdict(list) + for parent, child in edges.select("parent_id", "child_id").iter_rows(): + self._parents[child].append(parent) + self._children[parent].append(child) + self._ancestor_index: Optional[Dict[int, List[Tuple[int, int]]]] = None + + def __repr__(self) -> str: + return ( + f"OMOPConditionHierarchy(root={self.root_concept_id}, " + f"max_depth={self.max_depth}, depth_measure={self.depth_measure!r}, " + f"nodes={len(self)}, edges={self.edges.height})" + ) + + def __len__(self) -> int: + return self.nodes.height + + def __contains__(self, concept_id: int) -> bool: + return concept_id in self._info + + def _require(self, concept_id: int) -> dict: + try: + return self._info[concept_id] + except KeyError: + raise KeyError(f"Concept {concept_id} is not in the hierarchy.") from None + + def name(self, concept_id: int) -> str: + """Returns a kept concept's name.""" + return self._require(concept_id)["concept_name"] + + def depth(self, concept_id: int) -> int: + """Returns a kept concept's depth below the root.""" + return self._require(concept_id)["depth"] + + def parents(self, concept_id: int) -> List[int]: + """Returns a kept concept's parents in the graph, sorted.""" + self._require(concept_id) + return sorted(self._parents.get(concept_id, [])) + + def children(self, concept_id: int) -> List[int]: + """Returns a kept concept's children in the graph, sorted.""" + self._require(concept_id) + return sorted(self._children.get(concept_id, [])) + + def retained_ancestors(self, concept_id: int) -> List[Tuple[int, int]]: + """Lists the kept ancestors of any concept under the root. + + Works for concepts deeper than ``max_depth`` too, which is what + roll-up needs. A concept with several parents gets ancestors along + every path. + + Args: + concept_id: Any concept under the root, kept or not. + + Returns: + ``(ancestor_id, distance)`` pairs, nearest first. Empty if the + concept is not under the root. + """ + if self._ancestor_index is None: + self._ancestor_index = defaultdict(list) + for child, ancestor, distance in self.ancestors.iter_rows(): + self._ancestor_index[child].append((ancestor, distance)) + return list(self._ancestor_index.get(concept_id, [])) + + def restrict( + self, max_depth: int, depth_measure: Optional[str] = None + ) -> "OMOPConditionHierarchy": + """Cuts this hierarchy to a shallower depth without re-reading Athena. + + Build once with a generous limit (or ``max_depth=None``), then call + this for each depth in an ablation. The result is the same as + building at the smaller depth directly. + + Args: + max_depth: The new, smaller depth limit. + depth_measure: ``"min"`` or ``"max"``; defaults to this + hierarchy's measure. + + Returns: + A new :class:`OMOPConditionHierarchy`. + + Raises: + ValueError: If the new graph would need concepts this one dropped. + """ + depth_measure = depth_measure or self.depth_measure + if depth_measure not in ("min", "max"): + raise ValueError("depth_measure must be 'min' or 'max'.") + if max_depth is None or max_depth < 0: + raise ValueError("max_depth must be a non-negative integer.") + # a concept's max depth is never below its min depth, so a cut on + # max depth keeps a subset of the same cut on min depth + covered = self.max_depth is None or ( + max_depth <= self.max_depth + and (self.depth_measure == "min" or depth_measure == "max") + ) + if not covered: + raise ValueError( + f"Cannot restrict a hierarchy built with max_depth=" + f"{self.max_depth} ({self.depth_measure}) to max_depth=" + f"{max_depth} ({depth_measure}); build a deeper one first." + ) + nodes = ( + self.nodes.with_columns(pl.col(f"{depth_measure}_depth").alias("depth")) + .filter(pl.col("depth") <= max_depth) + .sort("depth", "concept_id") + ) + kept = nodes.select("concept_id") + edges = ( + self.edges.filter(~pl.col("rescued")) + .join(kept, left_on="parent_id", right_on="concept_id", how="semi") + .join(kept, left_on="child_id", right_on="concept_id", how="semi") + ) + ancestors = self.ancestors.join( + kept, left_on="ancestor_id", right_on="concept_id", how="semi" + ) + if self.connect_orphans: + edges = _rescue_orphans(nodes, edges, ancestors, self.root_concept_id) + return OMOPConditionHierarchy( + nodes=nodes, + edges=edges.sort("parent_id", "child_id"), + ancestors=ancestors, + root_concept_id=self.root_concept_id, + max_depth=max_depth, + depth_measure=depth_measure, + connect_orphans=self.connect_orphans, + ) + + def to_networkx(self) -> nx.DiGraph: + """Returns the graph as a ``networkx.DiGraph`` with parent -> child edges. + + Node attributes are ``name``, ``code`` and ``depth``; edge attribute + ``rescued`` marks orphan rescues. + """ + graph = nx.DiGraph() + for row in self.nodes.iter_rows(named=True): + graph.add_node( + row["concept_id"], + name=row["concept_name"], + code=row["concept_code"], + depth=row["depth"], + ) + for parent, child, rescued in self.edges.iter_rows(): + graph.add_edge(parent, child, rescued=rescued) + return graph + + def to_triples( + self, direction: str = "child_to_parent" + ) -> List[Tuple[str, str, str]]: + """Returns the edges as ``(head, relation, tail)`` string triples. + + This is the input format of :class:`pyhealth.graph.KnowledgeGraph`. + Entities are OMOP ``concept_id`` values as strings. Depth, ancestor + distances and other metadata stay on this object. + + Args: + direction: ``"child_to_parent"`` gives ``(child, "is_a", parent)``; + ``"parent_to_child"`` gives ``(parent, "subsumes", child)`` + (OMOP's name for the reverse of "Is a"). Orphan rescue edges + get their own relation (``"rescued_is_a"`` or + ``"rescued_subsumes"``) because they can skip several levels. + + Returns: + One triple per edge, sorted by head then tail. + + Example: + >>> hierarchy.to_triples()[:1] # doctest: +SKIP + [('100', 'is_a', '4274025')] + """ + try: + direct, rescued = RELATIONS[direction] + except KeyError: + raise ValueError( + f"direction must be one of {sorted(RELATIONS)}, got {direction!r}." + ) from None + triples = [] + for parent, child, is_rescue in self.edges.iter_rows(): + relation = rescued if is_rescue else direct + if direction == "child_to_parent": + triples.append((str(child), relation, str(parent))) + else: + triples.append((str(parent), relation, str(child))) + return sorted(triples, key=lambda triple: (triple[0], triple[2])) + + def to_knowledge_graph( + self, direction: str = "parent_to_child" + ) -> "KnowledgeGraph": + """Returns the hierarchy as a :class:`pyhealth.graph.KnowledgeGraph`. + + Every kept concept is an entity (as a string ``concept_id``), including + any without edges. The direct and rescue relations are always both + registered, so ``edge_type`` tells rescue edges apart. + + The default direction matters for + :class:`pyhealth.processors.GraphProcessor`: its k-hop extraction + follows edges *into* the seed codes. With ``"parent_to_child"`` edges, + a patient's codes reach their ancestors; with ``"child_to_parent"`` + they reach only their descendants. + + Args: + direction: ``"parent_to_child"`` (default) or ``"child_to_parent"``; + see :meth:`to_triples`. + + Returns: + A new ``KnowledgeGraph``. + + Raises: + ValueError: If the hierarchy has no edges (for example + ``max_depth=0``), which ``KnowledgeGraph`` cannot hold. + """ + from pyhealth.graph import KnowledgeGraph + + triples = self.to_triples(direction) + if not triples: + raise ValueError("The hierarchy has no edges to export.") + entities = sorted(str(concept_id) for concept_id in self.nodes["concept_id"]) + relations = sorted(RELATIONS[direction]) + return KnowledgeGraph( + triples=triples, + entity2id={entity: index for index, entity in enumerate(entities)}, + relation2id={name: index for index, name in enumerate(relations)}, + ) + + def save(self, folder: Union[str, Path]) -> None: + """Saves the hierarchy as parquet files, so later runs skip Athena. + + Args: + folder: Folder to write to; created if needed. + """ + folder = Path(folder).expanduser() + folder.mkdir(parents=True, exist_ok=True) + self.nodes.write_parquet(folder / "nodes.parquet") + self.edges.write_parquet(folder / "edges.parquet") + self.ancestors.write_parquet(folder / "ancestors.parquet") + meta = { + "root_concept_id": self.root_concept_id, + "max_depth": self.max_depth, + "depth_measure": self.depth_measure, + "connect_orphans": self.connect_orphans, + } + (folder / "meta.json").write_text(json.dumps(meta, indent=2)) + + @classmethod + def load(cls, folder: Union[str, Path]) -> "OMOPConditionHierarchy": + """Loads a hierarchy written by :meth:`save`. + + Args: + folder: Folder passed to :meth:`save`. + """ + folder = Path(folder).expanduser() + meta = json.loads((folder / "meta.json").read_text()) + return cls( + nodes=pl.read_parquet(folder / "nodes.parquet"), + edges=pl.read_parquet(folder / "edges.parquet"), + ancestors=pl.read_parquet(folder / "ancestors.parquet"), + **meta, + ) diff --git a/pyhealth/medcode/omop/icd_mapper.py b/pyhealth/medcode/omop/icd_mapper.py new file mode 100644 index 0000000000..6c87503049 --- /dev/null +++ b/pyhealth/medcode/omop/icd_mapper.py @@ -0,0 +1,222 @@ +"""Maps ICD-9-CM and ICD-10-CM diagnosis codes to standard OMOP concepts. + +Build one with :meth:`pyhealth.medcode.OMOPVocabulary.icd_mapper`. +""" + +from __future__ import annotations + +from collections import defaultdict +from pathlib import Path +from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union + +import polars as pl + +if TYPE_CHECKING: + from .condition_hierarchy import OMOPConditionHierarchy + +#: A polars table, in memory or lazy. +Frame = Union[pl.DataFrame, pl.LazyFrame] + +#: ICD version number (as in MIMIC's ``icd_version`` column) -> OMOP vocabulary. +ICD_VERSION_TO_VOCABULARY = {9: "ICD9CM", 10: "ICD10CM"} + + +def normalize_icd_code(code: str) -> str: + """Puts an ICD code in the dot-free, upper-case form MIMIC uses. + + Athena stores ``I21.4`` and MIMIC stores ``I214``. Comparing both in the + dot-free form avoids having to know where each ICD version puts its dot + (ICD-9 E-codes put it after the fourth character, everything else after + the third). + + Args: + code: An ICD-9-CM or ICD-10-CM code, with or without a dot. + + Returns: + The code without dots or surrounding whitespace, in upper case. + + Example: + >>> normalize_icd_code(" i21.4 ") + 'I214' + >>> normalize_icd_code("E880.9") + 'E8809' + """ + return str(code).strip().replace(".", "").upper() + + +def _icd_vocabulary(version: Union[int, str]) -> str: + try: + return ICD_VERSION_TO_VOCABULARY[int(version)] + except (KeyError, ValueError) as err: + raise ValueError( + f"Unsupported ICD version {version!r}; expected 9 or 10." + ) from err + + +class ICDToSNOMEDMapper: + """Maps ICD-9-CM and ICD-10-CM diagnosis codes to standard OMOP concepts. + + Build it with :meth:`OMOPVocabulary.icd_mapper`, or reload a saved one with + :meth:`load`. Codes are matched in MIMIC's dot-free form, so ``"I214"`` + and ``"I21.4"`` are the same code. One ICD code can map to several + concepts, and some map to none. + + Attributes: + table: One row per (ICD code, target concept): ``icd_version``, + ``icd_code`` (dot-free), ``source_code`` (as Athena writes it), + ``source_concept_id``, ``concept_id`` (null when the code has no + valid "Maps to" link), ``concept_name``, ``target_domain_id`` and + ``target_vocabulary_id``. + """ + + def __init__(self, table: pl.DataFrame): + self.table = table + self._lookup: Dict[Tuple[int, str], List[int]] = defaultdict(list) + self._known = set() + for version, code, concept_id in table.select( + "icd_version", "icd_code", "concept_id" + ).iter_rows(): + self._known.add((version, code)) + if concept_id is not None: + self._lookup[(version, code)].append(concept_id) + + def __repr__(self) -> str: + return f"ICDToSNOMEDMapper(codes={len(self._known)})" + + def __contains__(self, key: Tuple[Union[int, str], str]) -> bool: + version, code = key + return (int(version), normalize_icd_code(code)) in self._known + + def map(self, code: str, version: Union[int, str]) -> List[int]: + """Maps one ICD code to standard concept ids. + + Args: + code: The ICD code, with or without a dot. + version: 9 or 10 (MIMIC's ``icd_version``). + + Returns: + Sorted, de-duplicated target concept ids; empty if the code is + unknown or has no valid mapping. + """ + _icd_vocabulary(version) + key = (int(version), normalize_icd_code(code)) + return sorted(set(self._lookup.get(key, []))) + + def map_frame(self, frame: Frame, code_column: str = "icd_code", + version_column: str = "icd_version") -> Frame: + """Adds mapped concepts to a table of diagnoses, such as MIMIC's. + + Rows whose code maps to several concepts are repeated, one per + concept. Rows that do not map keep a null ``concept_id``. A + ``LazyFrame`` stays lazy, so this can sit inside a streaming pipeline. + + Args: + frame: A ``DataFrame`` or ``LazyFrame`` with an ICD code column + and a version column. + code_column: Name of the code column. + version_column: Name of the version column. + + Returns: + ``frame`` with ``concept_id`` and ``target_domain_id`` added, of + the same type as ``frame``. + """ + lookup = self.table.select( + "icd_version", "icd_code", "concept_id", "target_domain_id" + ).filter(pl.col("concept_id").is_not_null()) + if isinstance(frame, pl.LazyFrame): + lookup = lookup.lazy() + keyed = frame.with_columns( + pl.col(version_column).cast(pl.Int64).alias("__version"), + pl.col(code_column) + .cast(pl.Utf8) + .str.strip_chars() + .str.replace_all(".", "", literal=True) + .str.to_uppercase() + .alias("__code"), + ) + return keyed.join( + lookup, + left_on=["__version", "__code"], + right_on=["icd_version", "icd_code"], + how="left", + ).drop("__version", "__code") + + def coverage( + self, + frame: Frame, + hierarchy: Optional[OMOPConditionHierarchy] = None, + code_column: str = "icd_code", + version_column: str = "icd_version", + ) -> Dict[str, int]: + """Counts how many distinct codes in a table map, without listing any. + + Args: + frame: A ``DataFrame`` or ``LazyFrame`` with an ICD code column and + a version column. Only its distinct codes are collected. + hierarchy: If given, also counts codes that land under its root + (kept, or deeper and reachable by roll-up). + code_column: Name of the code column. + version_column: Name of the version column. + + Returns: + Counts of distinct (version, code) pairs: ``codes``, + ``unknown`` (not in Athena), ``no_mapping`` (in Athena, no valid + "Maps to"), ``mapped``; with a hierarchy, also ``in_hierarchy`` + (at least one target under the root) and ``outside_hierarchy``. + """ + codes = frame.select( + pl.col(version_column).cast(pl.Int64).alias("icd_version"), + pl.col(code_column) + .cast(pl.Utf8) + .str.strip_chars() + .str.replace_all(".", "", literal=True) + .str.to_uppercase() + .alias("icd_code"), + ).unique() + if isinstance(codes, pl.LazyFrame): + codes = codes.collect() + known = codes.join( + self.table.select("icd_version", "icd_code").unique(), + on=["icd_version", "icd_code"], + how="semi", + ) + mapped = self.map_frame(codes).filter(pl.col("concept_id").is_not_null()) + mapped_codes = mapped.select("icd_version", "icd_code").unique() + result = { + "codes": codes.height, + "unknown": codes.height - known.height, + "no_mapping": known.height - mapped_codes.height, + "mapped": mapped_codes.height, + } + if hierarchy is not None: + under_root = set(hierarchy.nodes["concept_id"]) | set( + hierarchy.ancestors["concept_id"] + ) + inside = ( + mapped.filter(pl.col("concept_id").is_in(list(under_root))) + .select("icd_version", "icd_code") + .unique() + .height + ) + result["in_hierarchy"] = inside + result["outside_hierarchy"] = mapped_codes.height - inside + return result + + def save(self, path: Union[str, Path]) -> None: + """Saves the mapping table as one parquet file. + + Args: + path: File to write, for example ``icd_to_snomed.parquet``. + """ + path = Path(path).expanduser() + path.parent.mkdir(parents=True, exist_ok=True) + self.table.write_parquet(path) + + @classmethod + def load(cls, path: Union[str, Path]) -> "ICDToSNOMEDMapper": + """Loads a mapper written by :meth:`save`. + + Args: + path: File passed to :meth:`save`. + """ + return cls(pl.read_parquet(Path(path).expanduser())) diff --git a/pyhealth/medcode/omop/vocabulary.py b/pyhealth/medcode/omop/vocabulary.py new file mode 100644 index 0000000000..184f744ded --- /dev/null +++ b/pyhealth/medcode/omop/vocabulary.py @@ -0,0 +1,404 @@ +"""Reads OMOP standardized vocabularies downloaded from Athena. + +Athena vocabularies are licensed and cannot be redistributed, so PyHealth does +not download them. Point :class:`OMOPVocabulary` at the folder you unzipped. +""" + +from __future__ import annotations + +import csv +import logging +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable, List, Optional, Sequence, Union + +import polars as pl + +from .condition_hierarchy import OMOPConditionHierarchy, _rescue_orphans +from .icd_mapper import ICD_VERSION_TO_VOCABULARY, ICDToSNOMEDMapper, _icd_vocabulary + +logger = logging.getLogger(__name__) + +#: OMOP concept_id of SNOMED 64572001 "Disease", the root KEEP uses. +DISEASE_CONCEPT_ID = 4274025 + + +_REQUIRED_COLUMNS = { + "CONCEPT": [ + "concept_id", + "concept_name", + "domain_id", + "vocabulary_id", + "concept_class_id", + "standard_concept", + "concept_code", + "invalid_reason", + ], + "CONCEPT_RELATIONSHIP": [ + "concept_id_1", + "concept_id_2", + "relationship_id", + "invalid_reason", + ], + "CONCEPT_ANCESTOR": [ + "ancestor_concept_id", + "descendant_concept_id", + "min_levels_of_separation", + "max_levels_of_separation", + ], +} + +_ID_COLUMNS = { + "concept_id", + "concept_id_1", + "concept_id_2", + "ancestor_concept_id", + "descendant_concept_id", + "min_levels_of_separation", + "max_levels_of_separation", +} + + +def _is_valid() -> pl.Expr: + """Rows Athena has not marked deprecated ("D") or upgraded ("U").""" + reason = pl.col("invalid_reason") + return reason.is_null() | (reason.str.strip_chars() == "") + + +def _collect(frame: pl.LazyFrame) -> pl.DataFrame: + """Collects with the streaming engine, so multi-GB files fit in memory.""" + return frame.collect(engine="streaming") + + +@dataclass(frozen=True) +class OMOPVocabularyFormat: + """How the vocabulary files are written. The defaults match Athena. + + Change these only for vocabulary tables from another source, such as a + comma-separated export from an OMOP database. + + Args: + separator: Column separator. Athena uses a tab despite the ``.csv`` + file names. + quote_char: Quote character, or None to treat quotes as ordinary + text. Athena does not quote fields, and some concept names + contain stray quotes, so the default is None. + encoding: ``"utf8-lossy"`` (replace invalid bytes) or ``"utf8"``. + file_name: File name pattern; ``{table}`` becomes ``CONCEPT``, + ``CONCEPT_RELATIONSHIP`` or ``CONCEPT_ANCESTOR``. + + Example: + >>> OMOPVocabularyFormat(separator=",", quote_char='"').separator + ',' + """ + + separator: str = "\t" + quote_char: Optional[str] = None + encoding: str = "utf8-lossy" + file_name: str = "{table}.csv" + + def __post_init__(self) -> None: + if len(self.separator) != 1: + raise ValueError("separator must be a single character.") + if self.quote_char is not None and len(self.quote_char) != 1: + raise ValueError("quote_char must be a single character or None.") + if self.encoding not in ("utf8", "utf8-lossy"): + raise ValueError("encoding must be 'utf8' or 'utf8-lossy'.") + if "{table}" not in self.file_name: + raise ValueError("file_name must contain '{table}'.") + + def split_header(self, line: str) -> List[str]: + """Splits a header line into column names.""" + if self.quote_char is None: + return line.split(self.separator) + return next(csv.reader([line], delimiter=self.separator, + quotechar=self.quote_char)) + + +class OMOPVocabulary: + """Reads an Athena download of the OMOP standardized vocabularies. + + Only ``CONCEPT.csv``, ``CONCEPT_RELATIONSHIP.csv`` and + ``CONCEPT_ANCESTOR.csv`` are read. Athena writes them tab-separated despite + the ``.csv`` name, and they are several GB, so they are scanned lazily and + filtered while reading rather than loaded whole. + + Args: + root: Folder containing the unzipped Athena files. + file_format: How the files are written; defaults to Athena's format. + See :class:`OMOPVocabularyFormat`. + + Raises: + FileNotFoundError: If ``root`` or one of the three files is missing. + ValueError: If a file lacks a column this module needs (for example + because it was re-saved with a different separator than + ``file_format`` says). + + Example: + >>> vocab = OMOPVocabulary("~/data/athena") # doctest: +SKIP + >>> hierarchy = vocab.condition_hierarchy(max_depth=5) # doctest: +SKIP + """ + + def __init__( + self, + root: Union[str, Path], + file_format: Optional[OMOPVocabularyFormat] = None, + ): + self.root = Path(root).expanduser() + self.file_format = file_format or OMOPVocabularyFormat() + if not self.root.is_dir(): + raise FileNotFoundError(f"Athena folder not found: {self.root}") + for table, columns in _REQUIRED_COLUMNS.items(): + self._check_header(table, columns) + + def __repr__(self) -> str: + return f"OMOPVocabulary(root={str(self.root)!r})" + + def _path(self, table: str) -> Path: + return self.root / self.file_format.file_name.format(table=table) + + def _check_header(self, table: str, columns: Sequence[str]) -> None: + path = self._path(table) + if not path.is_file(): + raise FileNotFoundError( + f"{path.name} not found in {self.root}. Download the " + "vocabularies from https://athena.ohdsi.org and unzip them there." + ) + with open(path, encoding="utf-8", errors="replace") as handle: + line = handle.readline().rstrip("\r\n") + header = self.file_format.split_header(line) + missing = [column for column in columns if column not in header] + if missing: + raise ValueError( + f"{path.name} is missing columns {missing} when split on " + f"{self.file_format.separator!r}. Athena files are tab-separated; " + "for files from another source, pass a matching " + "OMOPVocabularyFormat as file_format." + ) + + def scan(self, table: str) -> pl.LazyFrame: + """Lazily reads one Athena table. + + Every column is read as text, then id and level columns are cast to + integers. Separator, quoting and encoding come from ``file_format``. + + Args: + table: ``"CONCEPT"``, ``"CONCEPT_RELATIONSHIP"`` or + ``"CONCEPT_ANCESTOR"``. + + Returns: + A polars ``LazyFrame`` over the file. + """ + if table not in _REQUIRED_COLUMNS: + raise ValueError( + f"Unknown table {table!r}; expected one of " + f"{sorted(_REQUIRED_COLUMNS)}." + ) + frame = pl.scan_csv( + self._path(table), + separator=self.file_format.separator, + quote_char=self.file_format.quote_char, + infer_schema=False, + encoding=self.file_format.encoding, + ) + names = frame.collect_schema().names() + return frame.with_columns( + pl.col(name).cast(pl.Int64) for name in names if name in _ID_COLUMNS + ) + + def condition_hierarchy( + self, + root_concept_id: int = DISEASE_CONCEPT_ID, + max_depth: Optional[int] = 5, + depth_measure: str = "min", + connect_orphans: bool = True, + ) -> "OMOPConditionHierarchy": + """Builds the depth-limited SNOMED condition graph KEEP uses. + + Nodes are valid, standard SNOMED concepts in the Condition domain that + descend from ``root_concept_id`` within ``max_depth`` levels, plus the + root. Edges are the "Is a" relationships between nodes, so a concept + with several parents keeps all of them. + + Args: + root_concept_id: Root of the graph. Defaults to "Disease". + max_depth: Deepest level to keep, counted from the root (depth 0). + ``None`` keeps every descendant. + depth_measure: How a concept's depth is counted, because SNOMED + concepts can sit at several depths at once. ``"min"`` (the + KEEP paper) uses the shortest path to the root; + ``"max"`` uses the longest. + connect_orphans: Some kept concepts have only parents that were + filtered out (for example a parent in another domain). If + True, each such concept is attached to its nearest kept + ancestor so the graph stays connected; these edges are marked + ``rescued`` in :attr:`OMOPConditionHierarchy.edges`. + + Returns: + The :class:`OMOPConditionHierarchy`. + """ + if depth_measure not in ("min", "max"): + raise ValueError("depth_measure must be 'min' or 'max'.") + if max_depth is not None and max_depth < 0: + raise ValueError("max_depth must be non-negative or None.") + logger.info("Building SNOMED condition hierarchy from %s", self.root) + + conditions = ( + self.scan("CONCEPT") + .filter( + (pl.col("vocabulary_id") == "SNOMED") + & (pl.col("domain_id") == "Condition") + & (pl.col("standard_concept") == "S") + & _is_valid() + ) + .select("concept_id", "concept_name", "concept_code") + ) + levels = ( + self.scan("CONCEPT_ANCESTOR") + .filter(pl.col("ancestor_concept_id") == root_concept_id) + .select( + pl.col("descendant_concept_id").alias("concept_id"), + pl.col("min_levels_of_separation").alias("min_depth"), + pl.col("max_levels_of_separation").alias("max_depth"), + ) + ) + subtree = _collect(levels.join(conditions, on="concept_id", how="inner")) + root = _collect( + conditions.filter(pl.col("concept_id") == root_concept_id) + ) + if root.height == 0: + raise ValueError( + f"Root concept {root_concept_id} is not a valid standard SNOMED " + "Condition concept in this vocabulary." + ) + if root_concept_id not in subtree["concept_id"]: + subtree = pl.concat( + [ + subtree, + root.with_columns( + pl.lit(0, pl.Int64).alias("min_depth"), + pl.lit(0, pl.Int64).alias("max_depth"), + ).select(subtree.columns), + ] + ) + subtree = subtree.with_columns( + pl.col(f"{depth_measure}_depth").alias("depth") + ).unique("concept_id") + + nodes = subtree + if max_depth is not None: + nodes = subtree.filter(pl.col("depth") <= max_depth) + nodes = nodes.sort("depth", "concept_id") + node_ids = nodes.select("concept_id").lazy() + + edges = _collect( + self.scan("CONCEPT_RELATIONSHIP") + .filter((pl.col("relationship_id") == "Is a") & _is_valid()) + .select( + pl.col("concept_id_2").alias("parent_id"), + pl.col("concept_id_1").alias("child_id"), + ) + .join(node_ids, left_on="parent_id", right_on="concept_id", how="semi") + .join(node_ids, left_on="child_id", right_on="concept_id", how="semi") + .filter(pl.col("parent_id") != pl.col("child_id")) + .unique() + ).with_columns(pl.lit(False).alias("rescued")) + + ancestors = _collect( + self.scan("CONCEPT_ANCESTOR") + .filter(pl.col("min_levels_of_separation") > 0) + .select( + pl.col("descendant_concept_id").alias("concept_id"), + pl.col("ancestor_concept_id").alias("ancestor_id"), + pl.col("min_levels_of_separation").alias("distance"), + ) + .join(subtree.select("concept_id").lazy(), on="concept_id", how="semi") + .join(node_ids, left_on="ancestor_id", right_on="concept_id", how="semi") + ) + + if connect_orphans: + edges = _rescue_orphans(nodes, edges, ancestors, root_concept_id) + logger.info( + "Condition hierarchy: %d concepts, %d edges, %d orphans re-attached", + nodes.height, + edges.height, + int(edges["rescued"].sum()), + ) + + return OMOPConditionHierarchy( + nodes=nodes, + edges=edges.sort("parent_id", "child_id"), + ancestors=ancestors.sort("concept_id", "distance", "ancestor_id"), + root_concept_id=root_concept_id, + max_depth=max_depth, + depth_measure=depth_measure, + connect_orphans=connect_orphans, + ) + + def icd_mapper( + self, versions: Iterable[Union[int, str]] = (9, 10) + ) -> "ICDToSNOMEDMapper": + """Builds the ICD -> standard concept lookup from "Maps to" links. + + Source ICD concepts are kept even when Athena has deprecated them, + because older records (such as MIMIC's ICD-9 era) still use them; + only the "Maps to" links themselves must be valid. + + Args: + versions: ICD versions to include (9 and/or 10). + + Returns: + The :class:`ICDToSNOMEDMapper`. + """ + vocabularies = [_icd_vocabulary(version) for version in versions] + concept = self.scan("CONCEPT") + sources = concept.filter(pl.col("vocabulary_id").is_in(vocabularies)).select( + pl.col("vocabulary_id"), + pl.col("concept_code").alias("source_code"), + pl.col("concept_id").alias("source_concept_id"), + ) + maps_to = ( + self.scan("CONCEPT_RELATIONSHIP") + .filter((pl.col("relationship_id") == "Maps to") & _is_valid()) + .select( + pl.col("concept_id_1").alias("source_concept_id"), + pl.col("concept_id_2").alias("concept_id"), + ) + .join(sources.select("source_concept_id"), on="source_concept_id", + how="semi") + ) + targets = concept.select( + "concept_id", + pl.col("concept_name"), + pl.col("domain_id").alias("target_domain_id"), + pl.col("vocabulary_id").alias("target_vocabulary_id"), + ) + version_of = {name: number for number, name in + ICD_VERSION_TO_VOCABULARY.items()} + table = _collect( + sources.join(maps_to, on="source_concept_id", how="left") + .join(targets, on="concept_id", how="left") + .with_columns( + pl.col("vocabulary_id") + .replace_strict(version_of, return_dtype=pl.Int64) + .alias("icd_version"), + pl.col("source_code") + .str.strip_chars() + .str.replace_all(".", "", literal=True) + .str.to_uppercase() + .alias("icd_code"), + ) + .unique() + ) + return ICDToSNOMEDMapper( + table.select( + "icd_version", + "icd_code", + "source_code", + "source_concept_id", + "concept_id", + "concept_name", + "target_domain_id", + "target_vocabulary_id", + ).sort("icd_version", "icd_code", "concept_id", nulls_last=True) + ) diff --git a/tests/core/omop_test_utils.py b/tests/core/omop_test_utils.py new file mode 100644 index 0000000000..69847b255f --- /dev/null +++ b/tests/core/omop_test_utils.py @@ -0,0 +1,196 @@ +"""A small synthetic Athena bundle shared by the OMOP vocabulary tests. + +The bundle is written to a temporary folder. It mimics Athena's layout +(tab-separated ``.csv`` files) with a dozen concepts arranged to cover the +cases that matter: a depth cutoff, a concept with two parents at different +depths, an orphan whose only parent is in another domain, deprecated rows, +and ICD codes that map to zero, one or two concepts. + +Hierarchy ("Is a", child -> parent):: + + 700 Clinical finding + |-- 4274025 Disease (root) 300 Fever -> 700 (not under root) + |-- 100 Heart disease + | |-- 101 Ischemic heart disease + | | `-- 102 Acute MI + | | `-- 103 Acute MI, inferior wall + | | `-- 104 (also directly under 100) + | |-- 600 Cardiac observation (Observation domain) + | | `-- 105 Orphan disorder + | |-- 400 non-standard concept + | `-- 401 deprecated concept + `-- 200 Lung disease +""" + +import csv +import shutil +import tempfile +import unittest +from collections import defaultdict +from pathlib import Path + +from pyhealth.medcode import DISEASE_CONCEPT_ID, OMOPVocabulary + +ROOT = DISEASE_CONCEPT_ID + +# concept_id, name, domain, vocabulary, standard, code, invalid_reason +CONCEPTS = [ + (700, "Clinical finding", "Condition", "SNOMED", "S", "404684003", ""), + (ROOT, "Disease", "Condition", "SNOMED", "S", "64572001", ""), + (100, "Heart disease", "Condition", "SNOMED", "S", "56265001", ""), + (200, "Lung disease", "Condition", "SNOMED", "S", "19829001", ""), + (101, "Ischemic heart disease", "Condition", "SNOMED", "S", "414545008", ""), + (102, 'Acute "MI', "Condition", "SNOMED", "S", "57054005", ""), + (103, "Acute MI, inferior wall", "Condition", "SNOMED", "S", "73795002", ""), + (104, "Two-parent disorder", "Condition", "SNOMED", "S", "1000004", ""), + (600, "Cardiac observation", "Observation", "SNOMED", "S", "1000600", ""), + (105, "Orphan disorder", "Condition", "SNOMED", "S", "1000005", ""), + (300, "Fever", "Condition", "SNOMED", "S", "386661006", ""), + (400, "Non-standard disorder", "Condition", "SNOMED", "", "1000400", ""), + (401, "Deprecated disorder", "Condition", "SNOMED", "", "1000401", "D"), + (9001, "NSTEMI", "Condition", "ICD10CM", "", "I21.4", ""), + (9002, "CAD", "Condition", "ICD10CM", "", "I25.10", ""), + (9003, "Fever, unspecified", "Condition", "ICD10CM", "", "R50.9", ""), + (9004, "Other dependence", "Observation", "ICD10CM", "", "Z99.89", ""), + (9005, "Type 2 MI", "Condition", "ICD10CM", "", "I21.A1", ""), + (9006, "Old MI code", "Condition", "ICD10CM", "", "I21.9", "D"), + (8001, "AMI inferior", "Condition", "ICD9CM", "", "410.71", ""), + (8002, "Fall on stairs", "Observation", "ICD9CM", "", "E880.9", ""), + (8003, "CABG status", "Observation", "ICD9CM", "", "V45.81", ""), + (8004, "CHF", "Condition", "ICD9CM", "", "428.0", ""), +] + +# concept_id_1, concept_id_2, relationship_id, invalid_reason +RELATIONSHIPS = [ + (ROOT, 700, "Is a", ""), + (100, ROOT, "Is a", ""), + (200, ROOT, "Is a", ""), + (101, 100, "Is a", ""), + (102, 101, "Is a", ""), + (103, 102, "Is a", ""), + (104, 103, "Is a", ""), + (104, 100, "Is a", ""), + (600, 100, "Is a", ""), + (105, 600, "Is a", ""), + (300, 700, "Is a", ""), + (400, 100, "Is a", ""), + (401, 100, "Is a", ""), + (102, 200, "Is a", "D"), # deprecated link: must be ignored + (100, 101, "Subsumes", ""), # other relationship types are ignored + (9001, 102, "Maps to", ""), + (9001, 101, "Maps to", "D"), # deprecated mapping: must be ignored + (9002, 101, "Maps to", ""), + (9002, 104, "Maps to", ""), + (9003, 300, "Maps to", ""), + (9005, 103, "Maps to", ""), + (9006, 102, "Maps to", ""), + (8001, 102, "Maps to", ""), + (8002, 104, "Maps to", ""), + (8003, 101, "Maps to", ""), + (8004, 100, "Maps to", ""), +] + + +def _concept_ancestor_rows(): + """Derives CONCEPT_ANCESTOR the way Athena does: valid standard concepts, + valid "Is a" links, shortest and longest path lengths, self rows at 0.""" + standard = { + row[0] for row in CONCEPTS if row[4] == "S" and row[6] == "" + } + parents = defaultdict(set) + for child, parent, relation, invalid in RELATIONSHIPS: + if relation == "Is a" and not invalid and {child, parent} <= standard: + parents[child].add(parent) + + def levels(concept): + found = defaultdict(list) + stack = [(concept, 0)] + while stack: + node, distance = stack.pop() + found[node].append(distance) + for parent in parents[node]: + stack.append((parent, distance + 1)) + return found + + rows = [] + for concept in sorted(standard): + for ancestor, distances in levels(concept).items(): + rows.append((ancestor, concept, min(distances), max(distances))) + return rows + + +def _write(path, header, rows, separator="\t"): + if separator == "\t": # Athena style: no quoting at all + lines = ["\t".join(header)] + lines += ["\t".join(str(value) for value in row) for row in rows] + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + return + with open(path, "w", newline="", encoding="utf-8") as handle: + writer = csv.writer(handle, delimiter=separator, lineterminator="\n") + writer.writerow(header) + writer.writerows(rows) + + +def write_athena_bundle(folder, separator="\t", file_name="{table}.csv"): + """Writes the synthetic bundle, by default in Athena's layout. + + Args: + folder: Where to write. + separator: Column separator; anything but a tab is written with + standard CSV quoting. + file_name: File name pattern containing ``{table}``. + """ + folder = Path(folder) + + def path(table): + return folder / file_name.format(table=table) + + _write( + path("CONCEPT"), + [ + "concept_id", "concept_name", "domain_id", "vocabulary_id", + "concept_class_id", "standard_concept", "concept_code", + "valid_start_date", "valid_end_date", "invalid_reason", + ], + [ + (cid, name, domain, vocab, "Clinical Finding", std, code, + "19700101", "20991231", invalid) + for cid, name, domain, vocab, std, code, invalid in CONCEPTS + ], + separator, + ) + _write( + path("CONCEPT_RELATIONSHIP"), + [ + "concept_id_1", "concept_id_2", "relationship_id", + "valid_start_date", "valid_end_date", "invalid_reason", + ], + [(a, b, rel, "19700101", "20991231", inv) + for a, b, rel, inv in RELATIONSHIPS], + separator, + ) + _write( + path("CONCEPT_ANCESTOR"), + [ + "ancestor_concept_id", "descendant_concept_id", + "min_levels_of_separation", "max_levels_of_separation", + ], + _concept_ancestor_rows(), + separator, + ) + + +class AthenaFixture(unittest.TestCase): + """Builds the bundle once per test class; holds no tests itself.""" + + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.mkdtemp() + write_athena_bundle(cls.tmp) + cls.vocab = OMOPVocabulary(cls.tmp) + cls.hierarchy = cls.vocab.condition_hierarchy(max_depth=3) + cls.mapper = cls.vocab.icd_mapper() + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp) diff --git a/tests/core/test_omop_condition_hierarchy.py b/tests/core/test_omop_condition_hierarchy.py new file mode 100644 index 0000000000..da2274c6e7 --- /dev/null +++ b/tests/core/test_omop_condition_hierarchy.py @@ -0,0 +1,243 @@ +"""Tests for pyhealth.medcode.omop.condition_hierarchy. + +Uses the synthetic bundle in ``omop_test_utils``; see its docstring for the +concept tree. The GraphProcessor tests need torch-geometric and are skipped +without it. +""" + +import tempfile +import unittest + +import polars as pl + +from pyhealth.medcode import OMOPConditionHierarchy + +from tests.core.omop_test_utils import ROOT, AthenaFixture + +try: + from pyhealth.processors import GraphProcessor + import torch_geometric # noqa: F401 + + HAS_PYG = True +except ImportError: + HAS_PYG = False + + +class TestOMOPConditionHierarchy(AthenaFixture): + def test_nodes_respect_depth_domain_and_validity(self): + self.assertEqual( + set(self.hierarchy.nodes["concept_id"]), + {ROOT, 100, 200, 101, 102, 104, 105}, + ) + for excluded in (103, 600, 300, 400, 401, 700): + self.assertNotIn(excluded, self.hierarchy) + + def test_depths(self): + self.assertEqual(self.hierarchy.depth(ROOT), 0) + self.assertEqual(self.hierarchy.depth(102), 3) + # two parents: shortest path (via 100) is 2, longest (via 103) is 5 + row = self.hierarchy.nodes.filter(pl.col("concept_id") == 104).row( + 0, named=True + ) + self.assertEqual((row["depth"], row["min_depth"], row["max_depth"]), + (2, 2, 5)) + + def test_max_depth_measure(self): + deepest = self.vocab.condition_hierarchy(max_depth=3, depth_measure="max") + self.assertNotIn(104, deepest) + self.assertIn(102, deepest) + + def test_no_depth_limit(self): + full = self.vocab.condition_hierarchy(max_depth=None) + self.assertIn(103, full) + self.assertEqual(full.parents(104), [100, 103]) + + def test_edges_only_between_kept_concepts(self): + edges = set( + self.hierarchy.edges.filter(~pl.col("rescued")) + .select("parent_id", "child_id") + .iter_rows() + ) + self.assertEqual( + edges, {(ROOT, 100), (ROOT, 200), (100, 101), (101, 102), (100, 104)} + ) + # the deprecated 102 -> 200 link is not an edge + self.assertEqual(self.hierarchy.parents(102), [101]) + + def test_orphan_is_attached_to_nearest_kept_ancestor(self): + self.assertEqual(self.hierarchy.parents(105), [100]) + rescued = self.hierarchy.edges.filter(pl.col("rescued")) + self.assertEqual(list(rescued.select("parent_id", "child_id").iter_rows()), + [(100, 105)]) + + def test_orphans_left_alone_when_asked(self): + loose = self.vocab.condition_hierarchy(max_depth=3, connect_orphans=False) + self.assertEqual(loose.parents(105), []) + self.assertFalse(loose.edges["rescued"].any()) + + def test_retained_ancestors_of_deep_and_multi_parent_concepts(self): + # 103 is below the cutoff; roll-up needs its kept ancestors + self.assertEqual( + self.hierarchy.retained_ancestors(103), + [(102, 1), (101, 2), (100, 3), (ROOT, 4)], + ) + self.assertEqual( + self.hierarchy.retained_ancestors(104), + [(100, 1), (102, 2), (ROOT, 2), (101, 3)], + ) + self.assertEqual(self.hierarchy.retained_ancestors(300), []) + + def test_lookups(self): + self.assertEqual(self.hierarchy.name(ROOT), "Disease") + self.assertEqual(self.hierarchy.children(ROOT), [100, 200]) + with self.assertRaises(KeyError): + self.hierarchy.depth(103) + + def test_bad_arguments(self): + with self.assertRaises(ValueError): + self.vocab.condition_hierarchy(depth_measure="mean") + with self.assertRaises(ValueError): + self.vocab.condition_hierarchy(max_depth=-1) + with self.assertRaises(ValueError): + self.vocab.condition_hierarchy(root_concept_id=600) + + def test_networkx(self): + graph = self.hierarchy.to_networkx() + self.assertEqual(graph.number_of_nodes(), len(self.hierarchy)) + self.assertEqual(graph.nodes[102]["depth"], 3) + self.assertTrue(graph.edges[100, 105]["rescued"]) + + def test_restrict_matches_direct_build(self): + full = self.vocab.condition_hierarchy(max_depth=None) + for depth, measure in [(3, "min"), (2, "min"), (3, "max"), (0, "min")]: + direct = self.vocab.condition_hierarchy( + max_depth=depth, depth_measure=measure + ) + cut = full.restrict(depth, measure) + with self.subTest(depth=depth, measure=measure): + self.assertTrue(cut.nodes.equals(direct.nodes)) + self.assertTrue(cut.edges.equals(direct.edges)) + self.assertTrue( + cut.ancestors.sort(cut.ancestors.columns).equals( + direct.ancestors.sort(direct.ancestors.columns) + ) + ) + self.assertEqual((cut.max_depth, cut.depth_measure), + (depth, measure)) + + def test_restrict_refuses_to_add_concepts(self): + with self.assertRaises(ValueError): + self.hierarchy.restrict(4) + by_max = self.vocab.condition_hierarchy(max_depth=3, depth_measure="max") + with self.assertRaises(ValueError): + by_max.restrict(3, "min") + self.assertEqual(len(self.hierarchy.restrict(3, "max")), + len(by_max)) + + def test_save_and_load(self): + with tempfile.TemporaryDirectory() as folder: + self.hierarchy.save(folder) + loaded = OMOPConditionHierarchy.load(folder) + self.assertEqual(loaded.max_depth, 3) + self.assertEqual(loaded.depth_measure, "min") + self.assertTrue(loaded.nodes.equals(self.hierarchy.nodes)) + self.assertEqual(loaded.retained_ancestors(103), + self.hierarchy.retained_ancestors(103)) + + +class TestTriples(AthenaFixture): + def test_child_to_parent(self): + triples = self.hierarchy.to_triples() + self.assertEqual(triples, self.hierarchy.to_triples("child_to_parent")) + self.assertIn(("101", "is_a", "100"), triples) + self.assertEqual(len(triples), self.hierarchy.edges.height) + self.assertTrue(all(isinstance(part, str) for t in triples for part in t)) + + def test_parent_to_child(self): + triples = self.hierarchy.to_triples("parent_to_child") + self.assertIn(("100", "subsumes", "101"), triples) + self.assertNotIn(("101", "is_a", "100"), triples) + + def test_rescue_edges_keep_their_own_relation(self): + up = self.hierarchy.to_triples("child_to_parent") + down = self.hierarchy.to_triples("parent_to_child") + # 105's only parent was in another domain; it was attached to 100, + # two levels up, so the edge must not look like a direct link + self.assertIn(("105", "rescued_is_a", "100"), up) + self.assertNotIn(("105", "is_a", "100"), up) + self.assertIn(("100", "rescued_subsumes", "105"), down) + self.assertEqual(sum(r == "rescued_is_a" for _, r, _ in up), 1) + + def test_bad_direction(self): + with self.assertRaises(ValueError): + self.hierarchy.to_triples("sideways") + + +class TestKnowledgeGraph(AthenaFixture): + def test_entities_are_string_concept_ids(self): + kg = self.hierarchy.to_knowledge_graph() + self.assertEqual( + set(kg.entity2id), {str(c) for c in self.hierarchy.nodes["concept_id"]} + ) + self.assertEqual(kg.num_triples, self.hierarchy.edges.height) + # depth and distances stay on the hierarchy, not the graph + self.assertFalse(hasattr(kg, "depth")) + self.assertEqual(self.hierarchy.depth(102), 3) + + def test_direction_of_edges(self): + down = self.hierarchy.to_knowledge_graph() # parent_to_child + up = self.hierarchy.to_knowledge_graph("child_to_parent") + edge = (down.entity2id["100"], down.entity2id["101"]) + down_edges = set(map(tuple, down.edge_index.t().tolist())) + up_edges = set(map(tuple, up.edge_index.t().tolist())) + self.assertIn(edge, down_edges) + self.assertIn(edge[::-1], up_edges) + self.assertEqual(set(down.relation2id), {"subsumes", "rescued_subsumes"}) + self.assertEqual(set(up.relation2id), {"is_a", "rescued_is_a"}) + + def test_edge_type_marks_rescue_edges(self): + kg = self.hierarchy.to_knowledge_graph("child_to_parent") + rescued_type = kg.relation2id["rescued_is_a"] + rescued = [ + (kg.id2entity[h], kg.id2entity[t]) + for (h, t), r in zip(kg.edge_index.t().tolist(), kg.edge_type.tolist()) + if r == rescued_type + ] + self.assertEqual(rescued, [("105", "100")]) + + def test_isolated_concepts_are_kept(self): + loose = self.vocab.condition_hierarchy(max_depth=3, connect_orphans=False) + kg = loose.to_knowledge_graph() + self.assertTrue(kg.has_entity("105")) # no edges, still an entity + self.assertEqual(kg.num_entities, len(loose)) + + def test_no_edges(self): + with self.assertRaises(ValueError): + self.vocab.condition_hierarchy(max_depth=0).to_knowledge_graph() + + +@unittest.skipUnless(HAS_PYG, "torch-geometric required") +class TestGraphProcessor(AthenaFixture): + """GraphProcessor's k-hop extraction follows edges into the seed codes.""" + + def _subgraph_concepts(self, direction, codes, num_hops): + kg = self.hierarchy.to_knowledge_graph(direction) + graph = GraphProcessor(knowledge_graph=kg, num_hops=num_hops).process(codes) + return {kg.id2entity[i] for i in graph.node_ids.tolist()} + + def test_parent_to_child_reaches_ancestors_from_a_child_seed(self): + self.assertEqual( + self._subgraph_concepts("parent_to_child", ["102"], num_hops=3), + {"102", "101", "100", str(ROOT)}, + ) + + def test_child_to_parent_does_not_reach_ancestors(self): + # 102 has no kept children, so only the seed comes back + self.assertEqual( + self._subgraph_concepts("child_to_parent", ["102"], num_hops=3), + {"102"}, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_omop_icd_mapper.py b/tests/core/test_omop_icd_mapper.py new file mode 100644 index 0000000000..aefffafbab --- /dev/null +++ b/tests/core/test_omop_icd_mapper.py @@ -0,0 +1,115 @@ +"""Tests for pyhealth.medcode.omop.icd_mapper. + +Uses the synthetic bundle in ``omop_test_utils``; no real Athena or MIMIC data. +""" + +import tempfile +import unittest +from pathlib import Path + +import polars as pl + +from pyhealth.medcode import ICDToSNOMEDMapper +from pyhealth.medcode.omop import normalize_icd_code + +from tests.core.omop_test_utils import AthenaFixture + + +class TestICDToSNOMEDMapper(AthenaFixture): + def test_normalize(self): + self.assertEqual(normalize_icd_code(" i21.4 "), "I214") + self.assertEqual(normalize_icd_code("E880.9"), "E8809") + + def test_map_mimic_and_dotted_codes(self): + self.assertEqual(self.mapper.map("I214", 10), [102]) + self.assertEqual(self.mapper.map("I21.4", "10"), [102]) + self.assertEqual(self.mapper.map("41071", 9), [102]) + self.assertEqual(self.mapper.map("E8809", 9), [104]) + self.assertEqual(self.mapper.map("V4581", 9), [101]) + + def test_one_code_several_concepts(self): + self.assertEqual(self.mapper.map("I2510", 10), [101, 104]) + + def test_unmapped_unknown_and_deprecated(self): + self.assertEqual(self.mapper.map("Z9989", 10), []) # no "Maps to" + self.assertIn((10, "Z9989"), self.mapper) + self.assertEqual(self.mapper.map("XYZ", 10), []) # not in Athena + self.assertNotIn((10, "XYZ"), self.mapper) + # deprecated source code still maps through a valid link + self.assertEqual(self.mapper.map("I219", 10), [102]) + + def test_versions_are_separate(self): + self.assertEqual(self.mapper.map("I214", 9), []) + with self.assertRaises(ValueError): + self.mapper.map("I214", 11) + icd10_only = self.vocab.icd_mapper(versions=[10]) + self.assertEqual(icd10_only.map("41071", 9), []) + + def test_map_frame(self): + diagnoses = pl.DataFrame( + { + "subject_id": [1, 1, 2], + "icd_code": ["I214", "I2510", "Z9989"], + "icd_version": [10, 10, 10], + } + ) + mapped = self.mapper.map_frame(diagnoses) + self.assertEqual(mapped.height, 4) # I2510 maps to two concepts + self.assertEqual( + sorted(mapped.filter(pl.col("icd_code") == "I2510")["concept_id"]), + [101, 104], + ) + self.assertIsNone( + mapped.filter(pl.col("icd_code") == "Z9989")["concept_id"][0] + ) + self.assertEqual(mapped.columns[:3], diagnoses.columns) + + def test_coverage(self): + diagnoses = pl.DataFrame( + { + "icd_code": ["I214", "I214", "I2510", "R509", "Z9989", "XYZ", + "41071", "E8809"], + "icd_version": [10, 10, 10, 10, 10, 10, 9, 9], + } + ) + self.assertEqual( + self.mapper.coverage(diagnoses, hierarchy=self.hierarchy), + { + "codes": 7, + "unknown": 1, + "no_mapping": 1, + "mapped": 5, + "in_hierarchy": 4, + "outside_hierarchy": 1, # R50.9 -> Fever, not a disease + }, + ) + + def test_save_and_load(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "icd_to_snomed.parquet" + self.mapper.save(path) + loaded = ICDToSNOMEDMapper.load(path) + self.assertEqual(loaded.map("I2510", 10), [101, 104]) + + def test_map_frame_keeps_lazy_frames_lazy(self): + diagnoses = pl.LazyFrame( + {"icd_code": ["I214", "I2510"], "icd_version": [10, 10]} + ) + mapped = self.mapper.map_frame(diagnoses) + self.assertIsInstance(mapped, pl.LazyFrame) + self.assertEqual( + sorted(mapped.collect()["concept_id"].to_list()), [101, 102, 104] + ) + + def test_coverage_of_a_lazy_frame(self): + eager = pl.DataFrame( + {"icd_code": ["I214", "Z9989", "XYZ"], "icd_version": [10, 10, 10]} + ) + self.assertEqual( + self.mapper.coverage(eager.lazy(), hierarchy=self.hierarchy), + self.mapper.coverage(eager, hierarchy=self.hierarchy), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_omop_vocabulary.py b/tests/core/test_omop_vocabulary.py index cbf63bcd71..d5a2a90f71 100644 --- a/tests/core/test_omop_vocabulary.py +++ b/tests/core/test_omop_vocabulary.py @@ -1,189 +1,20 @@ -"""Tests for pyhealth.medcode.omop on a small synthetic Athena bundle. +"""Tests for pyhealth.medcode.omop.vocabulary (the Athena reader). -The bundle is written to a temporary folder. It mimics Athena's layout -(tab-separated ``.csv`` files) with a dozen concepts arranged to cover the -cases that matter: a depth cutoff, a concept with two parents at different -depths, an orphan whose only parent is in another domain, deprecated rows, -and ICD codes that map to zero, one or two concepts. - -Hierarchy ("Is a", child -> parent):: - - 700 Clinical finding - |-- 4274025 Disease (root) 300 Fever -> 700 (not under root) - |-- 100 Heart disease - | |-- 101 Ischemic heart disease - | | `-- 102 Acute MI - | | `-- 103 Acute MI, inferior wall - | | `-- 104 (also directly under 100) - | |-- 600 Cardiac observation (Observation domain) - | | `-- 105 Orphan disorder - | |-- 400 non-standard concept - | `-- 401 deprecated concept - `-- 200 Lung disease +Uses the synthetic bundle in ``omop_test_utils``; no real Athena files. """ -import shutil import tempfile import unittest -from collections import defaultdict from pathlib import Path import polars as pl -from pyhealth.medcode import ( - DISEASE_CONCEPT_ID, - ConditionHierarchy, - ICDToSNOMEDMapper, - OMOPVocabulary, -) -from pyhealth.medcode.omop import normalize_icd_code - -ROOT = DISEASE_CONCEPT_ID - -# concept_id, name, domain, vocabulary, standard, code, invalid_reason -CONCEPTS = [ - (700, "Clinical finding", "Condition", "SNOMED", "S", "404684003", ""), - (ROOT, "Disease", "Condition", "SNOMED", "S", "64572001", ""), - (100, "Heart disease", "Condition", "SNOMED", "S", "56265001", ""), - (200, "Lung disease", "Condition", "SNOMED", "S", "19829001", ""), - (101, "Ischemic heart disease", "Condition", "SNOMED", "S", "414545008", ""), - (102, 'Acute "MI', "Condition", "SNOMED", "S", "57054005", ""), - (103, "Acute MI, inferior wall", "Condition", "SNOMED", "S", "73795002", ""), - (104, "Two-parent disorder", "Condition", "SNOMED", "S", "1000004", ""), - (600, "Cardiac observation", "Observation", "SNOMED", "S", "1000600", ""), - (105, "Orphan disorder", "Condition", "SNOMED", "S", "1000005", ""), - (300, "Fever", "Condition", "SNOMED", "S", "386661006", ""), - (400, "Non-standard disorder", "Condition", "SNOMED", "", "1000400", ""), - (401, "Deprecated disorder", "Condition", "SNOMED", "", "1000401", "D"), - (9001, "NSTEMI", "Condition", "ICD10CM", "", "I21.4", ""), - (9002, "CAD", "Condition", "ICD10CM", "", "I25.10", ""), - (9003, "Fever, unspecified", "Condition", "ICD10CM", "", "R50.9", ""), - (9004, "Other dependence", "Observation", "ICD10CM", "", "Z99.89", ""), - (9005, "Type 2 MI", "Condition", "ICD10CM", "", "I21.A1", ""), - (9006, "Old MI code", "Condition", "ICD10CM", "", "I21.9", "D"), - (8001, "AMI inferior", "Condition", "ICD9CM", "", "410.71", ""), - (8002, "Fall on stairs", "Observation", "ICD9CM", "", "E880.9", ""), - (8003, "CABG status", "Observation", "ICD9CM", "", "V45.81", ""), - (8004, "CHF", "Condition", "ICD9CM", "", "428.0", ""), -] - -# concept_id_1, concept_id_2, relationship_id, invalid_reason -RELATIONSHIPS = [ - (ROOT, 700, "Is a", ""), - (100, ROOT, "Is a", ""), - (200, ROOT, "Is a", ""), - (101, 100, "Is a", ""), - (102, 101, "Is a", ""), - (103, 102, "Is a", ""), - (104, 103, "Is a", ""), - (104, 100, "Is a", ""), - (600, 100, "Is a", ""), - (105, 600, "Is a", ""), - (300, 700, "Is a", ""), - (400, 100, "Is a", ""), - (401, 100, "Is a", ""), - (102, 200, "Is a", "D"), # deprecated link: must be ignored - (100, 101, "Subsumes", ""), # other relationship types are ignored - (9001, 102, "Maps to", ""), - (9001, 101, "Maps to", "D"), # deprecated mapping: must be ignored - (9002, 101, "Maps to", ""), - (9002, 104, "Maps to", ""), - (9003, 300, "Maps to", ""), - (9005, 103, "Maps to", ""), - (9006, 102, "Maps to", ""), - (8001, 102, "Maps to", ""), - (8002, 104, "Maps to", ""), - (8003, 101, "Maps to", ""), - (8004, 100, "Maps to", ""), -] - - -def _concept_ancestor_rows(): - """Derives CONCEPT_ANCESTOR the way Athena does: valid standard concepts, - valid "Is a" links, shortest and longest path lengths, self rows at 0.""" - standard = { - row[0] for row in CONCEPTS if row[4] == "S" and row[6] == "" - } - parents = defaultdict(set) - for child, parent, relation, invalid in RELATIONSHIPS: - if relation == "Is a" and not invalid and {child, parent} <= standard: - parents[child].add(parent) - - def levels(concept): - found = defaultdict(list) - stack = [(concept, 0)] - while stack: - node, distance = stack.pop() - found[node].append(distance) - for parent in parents[node]: - stack.append((parent, distance + 1)) - return found - - rows = [] - for concept in sorted(standard): - for ancestor, distances in levels(concept).items(): - rows.append((ancestor, concept, min(distances), max(distances))) - return rows - - -def _write(path, header, rows): - lines = ["\t".join(header)] - lines += ["\t".join(str(value) for value in row) for row in rows] - path.write_text("\n".join(lines) + "\n", encoding="utf-8") - - -def write_athena_bundle(folder): - """Writes the synthetic bundle in Athena's tab-separated layout.""" - folder = Path(folder) - _write( - folder / "CONCEPT.csv", - [ - "concept_id", "concept_name", "domain_id", "vocabulary_id", - "concept_class_id", "standard_concept", "concept_code", - "valid_start_date", "valid_end_date", "invalid_reason", - ], - [ - (cid, name, domain, vocab, "Clinical Finding", std, code, - "19700101", "20991231", invalid) - for cid, name, domain, vocab, std, code, invalid in CONCEPTS - ], - ) - _write( - folder / "CONCEPT_RELATIONSHIP.csv", - [ - "concept_id_1", "concept_id_2", "relationship_id", - "valid_start_date", "valid_end_date", "invalid_reason", - ], - [(a, b, rel, "19700101", "20991231", inv) - for a, b, rel, inv in RELATIONSHIPS], - ) - _write( - folder / "CONCEPT_ANCESTOR.csv", - [ - "ancestor_concept_id", "descendant_concept_id", - "min_levels_of_separation", "max_levels_of_separation", - ], - _concept_ancestor_rows(), - ) - - -class _AthenaFixture(unittest.TestCase): - """Builds the bundle once per test class; holds no tests itself.""" +from pyhealth.medcode import OMOPVocabulary, OMOPVocabularyFormat - @classmethod - def setUpClass(cls): - cls.tmp = tempfile.mkdtemp() - write_athena_bundle(cls.tmp) - cls.vocab = OMOPVocabulary(cls.tmp) - cls.hierarchy = cls.vocab.condition_hierarchy(max_depth=3) - cls.mapper = cls.vocab.icd_mapper() +from tests.core.omop_test_utils import AthenaFixture, write_athena_bundle - @classmethod - def tearDownClass(cls): - shutil.rmtree(cls.tmp) - -class TestOMOPVocabulary(_AthenaFixture): +class TestOMOPVocabulary(AthenaFixture): def test_missing_folder(self): with self.assertRaises(FileNotFoundError): OMOPVocabulary(Path(self.tmp) / "nope") @@ -195,11 +26,9 @@ def test_missing_file(self): with self.assertRaises(FileNotFoundError): OMOPVocabulary(folder) - def test_comma_separated_file_is_rejected(self): + def test_comma_separated_file_is_rejected_by_default(self): with tempfile.TemporaryDirectory() as folder: - write_athena_bundle(folder) - path = Path(folder) / "CONCEPT.csv" - path.write_text(path.read_text().replace("\t", ",")) + write_athena_bundle(folder, separator=",") with self.assertRaisesRegex(ValueError, "tab-separated"): OMOPVocabulary(folder) @@ -214,206 +43,44 @@ def test_unknown_table(self): self.vocab.scan("DRUG_STRENGTH") -class TestConditionHierarchy(_AthenaFixture): - def test_nodes_respect_depth_domain_and_validity(self): - self.assertEqual( - set(self.hierarchy.nodes["concept_id"]), - {ROOT, 100, 200, 101, 102, 104, 105}, - ) - for excluded in (103, 600, 300, 400, 401, 700): - self.assertNotIn(excluded, self.hierarchy) - - def test_depths(self): - self.assertEqual(self.hierarchy.depth(ROOT), 0) - self.assertEqual(self.hierarchy.depth(102), 3) - # two parents: shortest path (via 100) is 2, longest (via 103) is 5 - row = self.hierarchy.nodes.filter(pl.col("concept_id") == 104).row( - 0, named=True - ) - self.assertEqual((row["depth"], row["min_depth"], row["max_depth"]), - (2, 2, 5)) - - def test_max_depth_measure(self): - deepest = self.vocab.condition_hierarchy(max_depth=3, depth_measure="max") - self.assertNotIn(104, deepest) - self.assertIn(102, deepest) - - def test_no_depth_limit(self): - full = self.vocab.condition_hierarchy(max_depth=None) - self.assertIn(103, full) - self.assertEqual(full.parents(104), [100, 103]) +class TestOMOPVocabularyFormat(AthenaFixture): + def test_defaults_match_athena(self): + self.assertEqual(self.vocab.file_format, OMOPVocabularyFormat()) + self.assertEqual(OMOPVocabularyFormat().separator, "\t") + self.assertIsNone(OMOPVocabularyFormat().quote_char) - def test_edges_only_between_kept_concepts(self): - edges = set( - self.hierarchy.edges.filter(~pl.col("rescued")) - .select("parent_id", "child_id") - .iter_rows() + def test_comma_separated_export_with_other_file_names(self): + file_format = OMOPVocabularyFormat( + separator=",", quote_char='"', file_name="vocab_{table}.txt" ) - self.assertEqual( - edges, {(ROOT, 100), (ROOT, 200), (100, 101), (101, 102), (100, 104)} - ) - # the deprecated 102 -> 200 link is not an edge - self.assertEqual(self.hierarchy.parents(102), [101]) - - def test_orphan_is_attached_to_nearest_kept_ancestor(self): - self.assertEqual(self.hierarchy.parents(105), [100]) - rescued = self.hierarchy.edges.filter(pl.col("rescued")) - self.assertEqual(list(rescued.select("parent_id", "child_id").iter_rows()), - [(100, 105)]) - - def test_orphans_left_alone_when_asked(self): - loose = self.vocab.condition_hierarchy(max_depth=3, connect_orphans=False) - self.assertEqual(loose.parents(105), []) - self.assertFalse(loose.edges["rescued"].any()) - - def test_retained_ancestors_of_deep_and_multi_parent_concepts(self): - # 103 is below the cutoff; roll-up needs its kept ancestors - self.assertEqual( - self.hierarchy.retained_ancestors(103), - [(102, 1), (101, 2), (100, 3), (ROOT, 4)], - ) - self.assertEqual( - self.hierarchy.retained_ancestors(104), - [(100, 1), (102, 2), (ROOT, 2), (101, 3)], - ) - self.assertEqual(self.hierarchy.retained_ancestors(300), []) - - def test_lookups(self): - self.assertEqual(self.hierarchy.name(ROOT), "Disease") - self.assertEqual(self.hierarchy.children(ROOT), [100, 200]) - with self.assertRaises(KeyError): - self.hierarchy.depth(103) - - def test_bad_arguments(self): - with self.assertRaises(ValueError): - self.vocab.condition_hierarchy(depth_measure="mean") - with self.assertRaises(ValueError): - self.vocab.condition_hierarchy(max_depth=-1) - with self.assertRaises(ValueError): - self.vocab.condition_hierarchy(root_concept_id=600) - - def test_networkx_and_triples(self): - graph = self.hierarchy.to_networkx() - self.assertEqual(graph.number_of_nodes(), len(self.hierarchy)) - self.assertEqual(graph.nodes[102]["depth"], 3) - self.assertTrue(graph.edges[100, 105]["rescued"]) - triples = self.hierarchy.to_triples() - self.assertIn(("101", "is_a", "100"), triples) - self.assertEqual(len(triples), self.hierarchy.edges.height) - - def test_restrict_matches_direct_build(self): - full = self.vocab.condition_hierarchy(max_depth=None) - for depth, measure in [(3, "min"), (2, "min"), (3, "max"), (0, "min")]: - direct = self.vocab.condition_hierarchy( - max_depth=depth, depth_measure=measure - ) - cut = full.restrict(depth, measure) - with self.subTest(depth=depth, measure=measure): - self.assertTrue(cut.nodes.equals(direct.nodes)) - self.assertTrue(cut.edges.equals(direct.edges)) - self.assertTrue( - cut.ancestors.sort(cut.ancestors.columns).equals( - direct.ancestors.sort(direct.ancestors.columns) - ) - ) - self.assertEqual((cut.max_depth, cut.depth_measure), - (depth, measure)) - - def test_restrict_refuses_to_add_concepts(self): - with self.assertRaises(ValueError): - self.hierarchy.restrict(4) - by_max = self.vocab.condition_hierarchy(max_depth=3, depth_measure="max") - with self.assertRaises(ValueError): - by_max.restrict(3, "min") - self.assertEqual(len(self.hierarchy.restrict(3, "max")), - len(by_max)) - - def test_save_and_load(self): with tempfile.TemporaryDirectory() as folder: - self.hierarchy.save(folder) - loaded = ConditionHierarchy.load(folder) - self.assertEqual(loaded.max_depth, 3) - self.assertEqual(loaded.depth_measure, "min") - self.assertTrue(loaded.nodes.equals(self.hierarchy.nodes)) - self.assertEqual(loaded.retained_ancestors(103), - self.hierarchy.retained_ancestors(103)) - - -class TestICDToSNOMEDMapper(_AthenaFixture): - def test_normalize(self): - self.assertEqual(normalize_icd_code(" i21.4 "), "I214") - self.assertEqual(normalize_icd_code("E880.9"), "E8809") - - def test_map_mimic_and_dotted_codes(self): - self.assertEqual(self.mapper.map("I214", 10), [102]) - self.assertEqual(self.mapper.map("I21.4", "10"), [102]) - self.assertEqual(self.mapper.map("41071", 9), [102]) - self.assertEqual(self.mapper.map("E8809", 9), [104]) - self.assertEqual(self.mapper.map("V4581", 9), [101]) - - def test_one_code_several_concepts(self): - self.assertEqual(self.mapper.map("I2510", 10), [101, 104]) - - def test_unmapped_unknown_and_deprecated(self): - self.assertEqual(self.mapper.map("Z9989", 10), []) # no "Maps to" - self.assertIn((10, "Z9989"), self.mapper) - self.assertEqual(self.mapper.map("XYZ", 10), []) # not in Athena - self.assertNotIn((10, "XYZ"), self.mapper) - # deprecated source code still maps through a valid link - self.assertEqual(self.mapper.map("I219", 10), [102]) - - def test_versions_are_separate(self): - self.assertEqual(self.mapper.map("I214", 9), []) - with self.assertRaises(ValueError): - self.mapper.map("I214", 11) - icd10_only = self.vocab.icd_mapper(versions=[10]) - self.assertEqual(icd10_only.map("41071", 9), []) - - def test_map_frame(self): - diagnoses = pl.DataFrame( - { - "subject_id": [1, 1, 2], - "icd_code": ["I214", "I2510", "Z9989"], - "icd_version": [10, 10, 10], - } - ) - mapped = self.mapper.map_frame(diagnoses) - self.assertEqual(mapped.height, 4) # I2510 maps to two concepts - self.assertEqual( - sorted(mapped.filter(pl.col("icd_code") == "I2510")["concept_id"]), - [101, 104], - ) - self.assertIsNone( - mapped.filter(pl.col("icd_code") == "Z9989")["concept_id"][0] - ) - self.assertEqual(mapped.columns[:3], diagnoses.columns) - - def test_coverage(self): - diagnoses = pl.DataFrame( - { - "icd_code": ["I214", "I214", "I2510", "R509", "Z9989", "XYZ", - "41071", "E8809"], - "icd_version": [10, 10, 10, 10, 10, 10, 9, 9], - } - ) - self.assertEqual( - self.mapper.coverage(diagnoses, hierarchy=self.hierarchy), - { - "codes": 7, - "unknown": 1, - "no_mapping": 1, - "mapped": 5, - "in_hierarchy": 4, - "outside_hierarchy": 1, # R50.9 -> Fever, not a disease - }, - ) + write_athena_bundle(folder, separator=",", file_name="vocab_{table}.txt") + vocab = OMOPVocabulary(folder, file_format=file_format) + hierarchy = vocab.condition_hierarchy(max_depth=3) + mapper = vocab.icd_mapper() + names = dict( + vocab.scan("CONCEPT") + .collect() + .select("concept_id", "concept_name") + .iter_rows() + ) + # same results as the Athena-format bundle + self.assertTrue(hierarchy.nodes.equals(self.hierarchy.nodes)) + self.assertTrue(hierarchy.edges.equals(self.hierarchy.edges)) + self.assertEqual(mapper.map("I2510", 10), [101, 104]) + # commas and quotes inside quoted fields survive + self.assertEqual(names[103], "Acute MI, inferior wall") + self.assertEqual(names[102], 'Acute "MI') - def test_save_and_load(self): - with tempfile.TemporaryDirectory() as folder: - path = Path(folder) / "icd_to_snomed.parquet" - self.mapper.save(path) - loaded = ICDToSNOMEDMapper.load(path) - self.assertEqual(loaded.map("I2510", 10), [101, 104]) + def test_invalid_values(self): + for kwargs in ( + {"separator": "::"}, + {"quote_char": "''"}, + {"encoding": "latin-1"}, + {"file_name": "CONCEPT.csv"}, + ): + with self.subTest(**kwargs), self.assertRaises(ValueError): + OMOPVocabularyFormat(**kwargs) if __name__ == "__main__": From 2e5a6ac749386bdfbf61cde3c5ae3c3427d9ef9b Mon Sep 17 00:00:00 2001 From: lee-leonardo Date: Thu, 19 Nov 2026 16:16:23 -0800 Subject: [PATCH 3/5] Split OMOP hierarchy loading into reusable vocabulary helpers Carries the vocabulary.py part of 24341db ("Reduce OMOP ancestor loading for KEEP roll-up") from #1661. The KEEP roll-up changes, their tests and the notebook from that commit stay with #1706. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1 --- pyhealth/medcode/omop/vocabulary.py | 109 +++++++++++++++------------- 1 file changed, 60 insertions(+), 49 deletions(-) diff --git a/pyhealth/medcode/omop/vocabulary.py b/pyhealth/medcode/omop/vocabulary.py index 184f744ded..da207cedb7 100644 --- a/pyhealth/medcode/omop/vocabulary.py +++ b/pyhealth/medcode/omop/vocabulary.py @@ -243,6 +243,52 @@ def condition_hierarchy( raise ValueError("max_depth must be non-negative or None.") logger.info("Building SNOMED condition hierarchy from %s", self.root) + subtree = self._rooted_condition_nodes(root_concept_id) + nodes = subtree.with_columns(pl.col(f"{depth_measure}_depth").alias("depth")) + if max_depth is not None: + nodes = nodes.filter(pl.col("depth") <= max_depth) + nodes = nodes.sort("depth", "concept_id") + node_ids = nodes.select("concept_id").lazy() + edges = self._direct_is_a_edges(nodes).with_columns( + pl.lit(False).alias("rescued") + ) + + # Descendants below the cutoff still need their kept ancestors. + ancestors = _collect( + self.scan("CONCEPT_ANCESTOR") + .filter(pl.col("min_levels_of_separation") > 0) + .select( + pl.col("descendant_concept_id").alias("concept_id"), + pl.col("ancestor_concept_id").alias("ancestor_id"), + pl.col("min_levels_of_separation").alias("distance"), + ) + .join(subtree.select("concept_id").lazy(), on="concept_id", how="semi") + .join(node_ids, left_on="ancestor_id", right_on="concept_id", how="semi") + ) + + if connect_orphans: + edges = _rescue_orphans(nodes, edges, ancestors, root_concept_id).sort( + "parent_id", "child_id" + ) + logger.info( + "Condition hierarchy: %d concepts, %d edges, %d orphans re-attached", + nodes.height, + edges.height, + int(edges["rescued"].sum()), + ) + + return OMOPConditionHierarchy( + nodes=nodes, + edges=edges, + ancestors=ancestors.sort("concept_id", "distance", "ancestor_id"), + root_concept_id=root_concept_id, + max_depth=max_depth, + depth_measure=depth_measure, + connect_orphans=connect_orphans, + ) + + def _rooted_condition_nodes(self, root_concept_id: int) -> pl.DataFrame: + """Collects the uncut SNOMED Condition subtree with both root depths.""" conditions = ( self.scan("CONCEPT") .filter( @@ -263,15 +309,16 @@ def condition_hierarchy( ) ) subtree = _collect(levels.join(conditions, on="concept_id", how="inner")) - root = _collect( - conditions.filter(pl.col("concept_id") == root_concept_id) - ) - if root.height == 0: - raise ValueError( - f"Root concept {root_concept_id} is not a valid standard SNOMED " - "Condition concept in this vocabulary." - ) + # Some bundles omit the root's self-row. if root_concept_id not in subtree["concept_id"]: + root = _collect( + conditions.filter(pl.col("concept_id") == root_concept_id) + ) + if root.height == 0: + raise ValueError( + f"Root concept {root_concept_id} is not a valid standard SNOMED " + "Condition concept in this vocabulary." + ) subtree = pl.concat( [ subtree, @@ -281,17 +328,12 @@ def condition_hierarchy( ).select(subtree.columns), ] ) - subtree = subtree.with_columns( - pl.col(f"{depth_measure}_depth").alias("depth") - ).unique("concept_id") + return subtree.unique("concept_id") - nodes = subtree - if max_depth is not None: - nodes = subtree.filter(pl.col("depth") <= max_depth) - nodes = nodes.sort("depth", "concept_id") + def _direct_is_a_edges(self, nodes: pl.DataFrame) -> pl.DataFrame: + """Collects valid direct 'Is a' edges between ``nodes``.""" node_ids = nodes.select("concept_id").lazy() - - edges = _collect( + return _collect( self.scan("CONCEPT_RELATIONSHIP") .filter((pl.col("relationship_id") == "Is a") & _is_valid()) .select( @@ -302,38 +344,7 @@ def condition_hierarchy( .join(node_ids, left_on="child_id", right_on="concept_id", how="semi") .filter(pl.col("parent_id") != pl.col("child_id")) .unique() - ).with_columns(pl.lit(False).alias("rescued")) - - ancestors = _collect( - self.scan("CONCEPT_ANCESTOR") - .filter(pl.col("min_levels_of_separation") > 0) - .select( - pl.col("descendant_concept_id").alias("concept_id"), - pl.col("ancestor_concept_id").alias("ancestor_id"), - pl.col("min_levels_of_separation").alias("distance"), - ) - .join(subtree.select("concept_id").lazy(), on="concept_id", how="semi") - .join(node_ids, left_on="ancestor_id", right_on="concept_id", how="semi") - ) - - if connect_orphans: - edges = _rescue_orphans(nodes, edges, ancestors, root_concept_id) - logger.info( - "Condition hierarchy: %d concepts, %d edges, %d orphans re-attached", - nodes.height, - edges.height, - int(edges["rescued"].sum()), - ) - - return OMOPConditionHierarchy( - nodes=nodes, - edges=edges.sort("parent_id", "child_id"), - ancestors=ancestors.sort("concept_id", "distance", "ancestor_id"), - root_concept_id=root_concept_id, - max_depth=max_depth, - depth_measure=depth_measure, - connect_orphans=connect_orphans, - ) + ).sort("parent_id", "child_id") def icd_mapper( self, versions: Iterable[Union[int, str]] = (9, 10) From afeb1b42e5edd645ed424d0062a3631d49193aaa Mon Sep 17 00:00:00 2001 From: lee-leonardo Date: Sat, 28 Nov 2026 10:18:58 -0800 Subject: [PATCH 4/5] Document OMOP mapper and hierarchy usage examples --- pyhealth/medcode/omop/condition_hierarchy.py | 25 ++++++++++++++++++++ pyhealth/medcode/omop/icd_mapper.py | 17 +++++++++++++ 2 files changed, 42 insertions(+) diff --git a/pyhealth/medcode/omop/condition_hierarchy.py b/pyhealth/medcode/omop/condition_hierarchy.py index 627b2158ab..74b9b5ec1b 100644 --- a/pyhealth/medcode/omop/condition_hierarchy.py +++ b/pyhealth/medcode/omop/condition_hierarchy.py @@ -81,6 +81,31 @@ class OMOPConditionHierarchy: depth_measure: ``"min"`` or ``"max"``. connect_orphans: Whether orphans were attached to their nearest kept ancestor. + + Example: + Construct a small synthetic hierarchy without external vocabulary files: + + >>> import polars as pl + >>> nodes = pl.DataFrame({ + ... "concept_id": [1, 2], + ... "concept_name": ["Root", "Child"], + ... "concept_code": ["SYN1", "SYN2"], + ... "min_depth": [0, 1], "max_depth": [0, 1], "depth": [0, 1], + ... }) + >>> edges = pl.DataFrame({ + ... "parent_id": [1], "child_id": [2], "rescued": [False], + ... }) + >>> ancestors = pl.DataFrame({ + ... "concept_id": [2], "ancestor_id": [1], "distance": [1], + ... }) + >>> hierarchy = OMOPConditionHierarchy( + ... nodes, edges, ancestors, root_concept_id=1, max_depth=1, + ... depth_measure="min", connect_orphans=False, + ... ) + >>> hierarchy.parents(2) + [1] + >>> hierarchy.depth(2) + 1 """ def __init__( diff --git a/pyhealth/medcode/omop/icd_mapper.py b/pyhealth/medcode/omop/icd_mapper.py index 6c87503049..6764136e08 100644 --- a/pyhealth/medcode/omop/icd_mapper.py +++ b/pyhealth/medcode/omop/icd_mapper.py @@ -67,6 +67,23 @@ class ICDToSNOMEDMapper: ``source_concept_id``, ``concept_id`` (null when the code has no valid "Maps to" link), ``concept_name``, ``target_domain_id`` and ``target_vocabulary_id``. + + Example: + Build a minimal synthetic lookup without downloading a vocabulary: + + >>> import polars as pl + >>> table = pl.DataFrame({ + ... "icd_version": [10, 10, 10], + ... "icd_code": ["SYN1", "SYN1", "SYN2"], + ... "concept_id": [101, 102, None], + ... }) + >>> mapper = ICDToSNOMEDMapper(table) + >>> mapper.map(" syn.1 ", version=10) + [101, 102] + >>> mapper.map("SYN2", version=10) + [] + >>> (10, "SYN2") in mapper + True """ def __init__(self, table: pl.DataFrame): From 78448c8fbab2def8a8ef060ccb670aaa4da92188 Mon Sep 17 00:00:00 2001 From: lee-leonardo Date: Sun, 29 Nov 2026 08:50:28 -0800 Subject: [PATCH 5/5] Modernize OMOP annotations for PyHealth's Ruff rules Takes the OMOP module annotations from 42556b0 in #1706 (built-in generics, `X | None`, unquoted forward references, sorted `__all__`). PyHealth's PR contribution check rejects the typing.Dict/Optional spellings. Behavior is unchanged, and the OMOP modules now match #1706's copy line for line. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1 --- pyhealth/medcode/omop/__init__.py | 2 +- pyhealth/medcode/omop/condition_hierarchy.py | 28 ++++++++++---------- pyhealth/medcode/omop/icd_mapper.py | 20 +++++++------- pyhealth/medcode/omop/vocabulary.py | 18 ++++++------- 4 files changed, 34 insertions(+), 34 deletions(-) diff --git a/pyhealth/medcode/omop/__init__.py b/pyhealth/medcode/omop/__init__.py index 05f8a7688f..0c060963a8 100644 --- a/pyhealth/medcode/omop/__init__.py +++ b/pyhealth/medcode/omop/__init__.py @@ -28,10 +28,10 @@ __all__ = [ "DISEASE_CONCEPT_ID", "ICD_VERSION_TO_VOCABULARY", + "RELATIONS", "ICDToSNOMEDMapper", "OMOPConditionHierarchy", "OMOPVocabulary", "OMOPVocabularyFormat", - "RELATIONS", "normalize_icd_code", ] diff --git a/pyhealth/medcode/omop/condition_hierarchy.py b/pyhealth/medcode/omop/condition_hierarchy.py index 74b9b5ec1b..82cf570fbd 100644 --- a/pyhealth/medcode/omop/condition_hierarchy.py +++ b/pyhealth/medcode/omop/condition_hierarchy.py @@ -9,7 +9,7 @@ import logging from collections import defaultdict from pathlib import Path -from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union +from typing import TYPE_CHECKING import networkx as nx import polars as pl @@ -114,7 +114,7 @@ def __init__( edges: pl.DataFrame, ancestors: pl.DataFrame, root_concept_id: int, - max_depth: Optional[int], + max_depth: int | None, depth_measure: str, connect_orphans: bool = True, ): @@ -128,12 +128,12 @@ def __init__( self._info = { row["concept_id"]: row for row in nodes.iter_rows(named=True) } - self._parents: Dict[int, List[int]] = defaultdict(list) - self._children: Dict[int, List[int]] = defaultdict(list) + self._parents: dict[int, list[int]] = defaultdict(list) + self._children: dict[int, list[int]] = defaultdict(list) for parent, child in edges.select("parent_id", "child_id").iter_rows(): self._parents[child].append(parent) self._children[parent].append(child) - self._ancestor_index: Optional[Dict[int, List[Tuple[int, int]]]] = None + self._ancestor_index: dict[int, list[tuple[int, int]]] | None = None def __repr__(self) -> str: return ( @@ -162,17 +162,17 @@ def depth(self, concept_id: int) -> int: """Returns a kept concept's depth below the root.""" return self._require(concept_id)["depth"] - def parents(self, concept_id: int) -> List[int]: + def parents(self, concept_id: int) -> list[int]: """Returns a kept concept's parents in the graph, sorted.""" self._require(concept_id) return sorted(self._parents.get(concept_id, [])) - def children(self, concept_id: int) -> List[int]: + def children(self, concept_id: int) -> list[int]: """Returns a kept concept's children in the graph, sorted.""" self._require(concept_id) return sorted(self._children.get(concept_id, [])) - def retained_ancestors(self, concept_id: int) -> List[Tuple[int, int]]: + def retained_ancestors(self, concept_id: int) -> list[tuple[int, int]]: """Lists the kept ancestors of any concept under the root. Works for concepts deeper than ``max_depth`` too, which is what @@ -193,8 +193,8 @@ def retained_ancestors(self, concept_id: int) -> List[Tuple[int, int]]: return list(self._ancestor_index.get(concept_id, [])) def restrict( - self, max_depth: int, depth_measure: Optional[str] = None - ) -> "OMOPConditionHierarchy": + self, max_depth: int, depth_measure: str | None = None + ) -> OMOPConditionHierarchy: """Cuts this hierarchy to a shallower depth without re-reading Athena. Build once with a generous limit (or ``max_depth=None``), then call @@ -275,7 +275,7 @@ def to_networkx(self) -> nx.DiGraph: def to_triples( self, direction: str = "child_to_parent" - ) -> List[Tuple[str, str, str]]: + ) -> list[tuple[str, str, str]]: """Returns the edges as ``(head, relation, tail)`` string triples. This is the input format of :class:`pyhealth.graph.KnowledgeGraph`. @@ -313,7 +313,7 @@ def to_triples( def to_knowledge_graph( self, direction: str = "parent_to_child" - ) -> "KnowledgeGraph": + ) -> KnowledgeGraph: """Returns the hierarchy as a :class:`pyhealth.graph.KnowledgeGraph`. Every kept concept is an entity (as a string ``concept_id``), including @@ -350,7 +350,7 @@ def to_knowledge_graph( relation2id={name: index for index, name in enumerate(relations)}, ) - def save(self, folder: Union[str, Path]) -> None: + def save(self, folder: str | Path) -> None: """Saves the hierarchy as parquet files, so later runs skip Athena. Args: @@ -370,7 +370,7 @@ def save(self, folder: Union[str, Path]) -> None: (folder / "meta.json").write_text(json.dumps(meta, indent=2)) @classmethod - def load(cls, folder: Union[str, Path]) -> "OMOPConditionHierarchy": + def load(cls, folder: str | Path) -> OMOPConditionHierarchy: """Loads a hierarchy written by :meth:`save`. Args: diff --git a/pyhealth/medcode/omop/icd_mapper.py b/pyhealth/medcode/omop/icd_mapper.py index 6764136e08..5c04a64955 100644 --- a/pyhealth/medcode/omop/icd_mapper.py +++ b/pyhealth/medcode/omop/icd_mapper.py @@ -7,7 +7,7 @@ from collections import defaultdict from pathlib import Path -from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union +from typing import TYPE_CHECKING import polars as pl @@ -15,7 +15,7 @@ from .condition_hierarchy import OMOPConditionHierarchy #: A polars table, in memory or lazy. -Frame = Union[pl.DataFrame, pl.LazyFrame] +Frame = pl.DataFrame | pl.LazyFrame #: ICD version number (as in MIMIC's ``icd_version`` column) -> OMOP vocabulary. ICD_VERSION_TO_VOCABULARY = {9: "ICD9CM", 10: "ICD10CM"} @@ -44,7 +44,7 @@ def normalize_icd_code(code: str) -> str: return str(code).strip().replace(".", "").upper() -def _icd_vocabulary(version: Union[int, str]) -> str: +def _icd_vocabulary(version: int | str) -> str: try: return ICD_VERSION_TO_VOCABULARY[int(version)] except (KeyError, ValueError) as err: @@ -88,7 +88,7 @@ class ICDToSNOMEDMapper: def __init__(self, table: pl.DataFrame): self.table = table - self._lookup: Dict[Tuple[int, str], List[int]] = defaultdict(list) + self._lookup: dict[tuple[int, str], list[int]] = defaultdict(list) self._known = set() for version, code, concept_id in table.select( "icd_version", "icd_code", "concept_id" @@ -100,11 +100,11 @@ def __init__(self, table: pl.DataFrame): def __repr__(self) -> str: return f"ICDToSNOMEDMapper(codes={len(self._known)})" - def __contains__(self, key: Tuple[Union[int, str], str]) -> bool: + def __contains__(self, key: tuple[int | str, str]) -> bool: version, code = key return (int(version), normalize_icd_code(code)) in self._known - def map(self, code: str, version: Union[int, str]) -> List[int]: + def map(self, code: str, version: int | str) -> list[int]: """Maps one ICD code to standard concept ids. Args: @@ -161,10 +161,10 @@ def map_frame(self, frame: Frame, code_column: str = "icd_code", def coverage( self, frame: Frame, - hierarchy: Optional[OMOPConditionHierarchy] = None, + hierarchy: OMOPConditionHierarchy | None = None, code_column: str = "icd_code", version_column: str = "icd_version", - ) -> Dict[str, int]: + ) -> dict[str, int]: """Counts how many distinct codes in a table map, without listing any. Args: @@ -219,7 +219,7 @@ def coverage( result["outside_hierarchy"] = mapped_codes.height - inside return result - def save(self, path: Union[str, Path]) -> None: + def save(self, path: str | Path) -> None: """Saves the mapping table as one parquet file. Args: @@ -230,7 +230,7 @@ def save(self, path: Union[str, Path]) -> None: self.table.write_parquet(path) @classmethod - def load(cls, path: Union[str, Path]) -> "ICDToSNOMEDMapper": + def load(cls, path: str | Path) -> ICDToSNOMEDMapper: """Loads a mapper written by :meth:`save`. Args: diff --git a/pyhealth/medcode/omop/vocabulary.py b/pyhealth/medcode/omop/vocabulary.py index da207cedb7..2ad4435704 100644 --- a/pyhealth/medcode/omop/vocabulary.py +++ b/pyhealth/medcode/omop/vocabulary.py @@ -8,9 +8,9 @@ import csv import logging +from collections.abc import Iterable, Sequence from dataclasses import dataclass from pathlib import Path -from typing import Iterable, List, Optional, Sequence, Union import polars as pl @@ -93,7 +93,7 @@ class OMOPVocabularyFormat: """ separator: str = "\t" - quote_char: Optional[str] = None + quote_char: str | None = None encoding: str = "utf8-lossy" file_name: str = "{table}.csv" @@ -107,7 +107,7 @@ def __post_init__(self) -> None: if "{table}" not in self.file_name: raise ValueError("file_name must contain '{table}'.") - def split_header(self, line: str) -> List[str]: + def split_header(self, line: str) -> list[str]: """Splits a header line into column names.""" if self.quote_char is None: return line.split(self.separator) @@ -141,8 +141,8 @@ class OMOPVocabulary: def __init__( self, - root: Union[str, Path], - file_format: Optional[OMOPVocabularyFormat] = None, + root: str | Path, + file_format: OMOPVocabularyFormat | None = None, ): self.root = Path(root).expanduser() self.file_format = file_format or OMOPVocabularyFormat() @@ -209,10 +209,10 @@ def scan(self, table: str) -> pl.LazyFrame: def condition_hierarchy( self, root_concept_id: int = DISEASE_CONCEPT_ID, - max_depth: Optional[int] = 5, + max_depth: int | None = 5, depth_measure: str = "min", connect_orphans: bool = True, - ) -> "OMOPConditionHierarchy": + ) -> OMOPConditionHierarchy: """Builds the depth-limited SNOMED condition graph KEEP uses. Nodes are valid, standard SNOMED concepts in the Condition domain that @@ -347,8 +347,8 @@ def _direct_is_a_edges(self, nodes: pl.DataFrame) -> pl.DataFrame: ).sort("parent_id", "child_id") def icd_mapper( - self, versions: Iterable[Union[int, str]] = (9, 10) - ) -> "ICDToSNOMEDMapper": + self, versions: Iterable[int | str] = (9, 10) + ) -> ICDToSNOMEDMapper: """Builds the ICD -> standard concept lookup from "Maps to" links. Source ICD concepts are kept even when Athena has deprecated them,