Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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/
143 changes: 143 additions & 0 deletions docs/api/medcode.rst
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,146 @@ Pair Notes
:members:
:undoc-members:
:show-inheritance:

OMOP Vocabularies (Athena)
--------------------------

``OMOPVocabulary`` reads a local download of the OMOP standardized vocabularies
from `Athena <https://athena.ohdsi.org>`_. 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``. Athena
writes tab-separated files; for vocabulary tables from another source, pass an
``OMOPVocabularyFormat`` (separator, quoting, encoding, file names).

It builds two objects:

- ``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 <https://arxiv.org/abs/2510.05049>`_,
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. 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 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 = OMOPConditionHierarchy.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; 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)

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.OMOPVocabularyFormat
:members:
:show-inheritance:

.. autoclass:: pyhealth.medcode.OMOPConditionHierarchy
:members:
:show-inheritance:

.. autoclass:: pyhealth.medcode.ICDToSNOMEDMapper
:members:
:show-inheritance:
191 changes: 191 additions & 0 deletions examples/omop_keep_condition_graph_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
"""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 (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
import time
from pathlib import Path

import polars as pl

from pyhealth.medcode import (
ICDToSNOMEDMapper,
OMOPConditionHierarchy,
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 (
OMOPConditionHierarchy.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: 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"):
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()
12 changes: 12 additions & 0 deletions pyhealth/medcode/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@
from .cross_map import CrossMap
from .flat_map import FlatMap
from .inner_map import InnerMap
from .omop import (
DISEASE_CONCEPT_ID,
ICDToSNOMEDMapper,
OMOPConditionHierarchy,
OMOPVocabulary,
OMOPVocabularyFormat,
)

__all__ = [
"ATC",
Expand All @@ -41,7 +48,12 @@
"NDC",
"UMLS",
"CrossMap",
"DISEASE_CONCEPT_ID",
"FlatMap",
"ICDToSNOMEDMapper",
"InnerMap",
"OMOPConditionHierarchy",
"OMOPVocabulary",
"OMOPVocabularyFormat",
"RxNorm",
]
Loading
Loading