Skip to content
Merged
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/
1 change: 1 addition & 0 deletions docs/api/graph.rst
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,4 @@ API Reference
:maxdepth: 3

graph/pyhealth.graph.KnowledgeGraph
graph/pyhealth.graph.cooccurrence
99 changes: 99 additions & 0 deletions docs/api/graph/pyhealth.graph.cooccurrence.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
.. Author: lee-leonardo (NetID: ll37)

.. _patient-cooccurrence:

Patient co-occurrence matrices
==============================

A patient co-occurrence matrix summarizes which concepts appear together
across a cohort. Each patient contributes a set of present concepts.
Entry ``C[i, j]`` counts patients whose sets contain both concepts.
The diagonal ``C[i, i]`` gives the number of patients with concept ``i``.
For example, a pair count of 10 can be interpreted alongside each
concept's prevalence, or used to weight an edge or train concept embeddings.

Choose a single order for the concepts and use it for both axes. A row for a
concept absent from the cohort still has a position in that order. The
matrix is symmetric and uses sparse COO storage, which records the nonzero
counts with their row and column indices. The caller defines patient
presence. For example, the :doc:`KEEP workflow
<../tasks/pyhealth.tasks.keep>` establishes presence after ancestor roll-up.

Counting patient sets
---------------------

This example adapts an in-memory Polars frame with one row per patient.
The first patient contributes one count to A, B, and their pair. The
second contributes one count to A. The third has no present concepts.

.. code-block:: python

import polars as pl

from pyhealth.graph.cooccurrence import build_cooccurrence

patients = pl.DataFrame({"concepts": [["A", "B"], ["A"], []]})
patient_sets = (set(codes) for (codes,) in patients.select("concepts").iter_rows())
counts = build_cooccurrence(patient_sets, concept_ids=["B", "Z", "A"])
counts.to_dense().tolist()
# [[1, 0, 1], [0, 0, 0], [1, 0, 2]]

An ETL pipeline can also yield patient sets from successive input batches.
Combine a patient's events into one set before yielding it, including when
its events span multiple batches. The builder consumes the iterable once
and keeps a counter for the distinct observed pairs. A patient with
``k`` present concepts contributes ``k * (k + 1) / 2`` unordered
pairs including the diagonal. Pair counting runs on the CPU and uses no
files. Set ``device="cuda:0"`` to construct the sparse tensor on CUDA
when supported by the PyTorch installation.

Transforming the counts
-----------------------

Use ``transform`` to derive weights from the coalesced count tensor and
cohort size. The callable runs once, on the requested device, after
counting. The cohort size includes patients with empty concept sets.

For positive pointwise mutual information (PPMI), compare the observed
joint prevalence with the prevalence expected under independence. For
an observed pair, its weight is
``max(0, log(N * C[i, j] / (C[i, i] * C[j, j])))``, where ``N``
is the cohort size. This example drops weights that clip to zero.

.. code-block:: python

import torch

def ppmi(counts, patient_count):
rows, cols = counts.indices()
joint = counts.values().to(torch.float64)
marginal_counts = joint.new_zeros(counts.size(0))
diagonal = rows == cols
marginal_counts[rows[diagonal]] = joint[diagonal]
denominator = marginal_counts[rows] * marginal_counts[cols]
weights = (patient_count * joint / denominator).log()
positive = weights > 0
return torch.sparse_coo_tensor(
counts.indices()[:, positive],
weights[positive],
counts.shape,
device=counts.device,
is_coalesced=True,
)

weights = build_cooccurrence(
iter([{"A", "B"}, {"A"}, set()]),
concept_ids=["A", "B"],
transform=ppmi,
)

Cosine similarity between the concepts' binary patient incidence vectors
uses ``C[i, j] / sqrt(C[i, i] * C[j, j])`` on observed pairs. Absent
concepts keep zero rows and columns. A different similarity, such as
cosine similarity between rows of the co-occurrence matrix, would use
those rows and their norms as its inputs.

API Reference
-------------

.. autofunction:: pyhealth.graph.cooccurrence.build_cooccurrence
146 changes: 146 additions & 0 deletions docs/api/medcode.rst
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,149 @@ 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:

To roll conditions up to retained ancestors and project the paths into
per-sample graphs, use :func:`~pyhealth.tasks.keep.build_keep_omop_ancestor_rollup`.
2 changes: 2 additions & 0 deletions docs/api/processors.rst
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ pixels through the processor's ``collate`` method.
- ``MultiHotProcessor``: For multi-hot encoding
- ``IgnoreProcessor``: A special feature processor that marks a feature to be ignored.
- ``GraphProcessor``: For knowledge graph subgraph extraction (e.g., GraphCare, G-BERT)
- ``AncestorRollupProcessor``: For depth-limited ancestor roll-up over a condition hierarchy (e.g., KEEP), with an OMOP vocabulary factory

**Temporal Multimodal Processors (** :class:`~pyhealth.processors.TemporalFeatureProcessor` **subclasses):**

Expand Down Expand Up @@ -610,4 +611,5 @@ API Reference
processors/pyhealth.processors.StageNetProcessor
processors/pyhealth.processors.StageNetTensorProcessor
processors/pyhealth.processors.GraphProcessor
processors/pyhealth.processors.AncestorRollupProcessor
processors/pyhealth.processors.utils
Loading