Skip to content

KEEP Integration etc. - #1661

Draft
rishabshah wants to merge 31 commits into
sunlabuiuc:masterfrom
rishabshah:keep
Draft

rishabshah wants to merge 31 commits into
sunlabuiuc:masterfrom
rishabshah:keep

Conversation

@rishabshah

@rishabshah rishabshah commented Nov 28, 2026 •

Copy link
Copy Markdown

Contributors

Contribution Type

Dataset + Task (reproducibility). The task also needs a new feature processor and OMOP vocabulary utilities in pyhealth.medcode; both are included.

Paper

Elhussein et al., "KEEP: Integrating Medical Ontologies with Clinical Data for Robust Code Embeddings," CHIL 2025 (PMLR 287).

Description

KEEP learns diagnosis-code embeddings in two stages: first it embeds the OMOP condition graph, then it refines those embeddings on patient co-occurrence, regularized toward the graph. This PR builds both inputs in PyHealth, from MIMIC-IV (or any OMOP CDM extract) and a local Athena vocabulary download:

  1. OMOP vocabulary and condition graph (pyhealth.medcode). Reads Athena's CONCEPT, CONCEPT_RELATIONSHIP and CONCEPT_ANCESTOR files, builds the SNOMED condition hierarchy under "Disease" (KEEP §A.1.1), maps ICD-9-CM/ICD-10-CM codes to SNOMED, and exports the graph as a KnowledgeGraph.
  2. Dataset. MIMICOMOPDataset loads MIMIC-IV in OMOP CDM form, and PatientBuilder filters it down to a cohort.
  3. Ancestor roll-up. AncestorRollupProcessor maps each code to its retained ancestor(s) at a chosen depth. It supports first-retained vs. all-retained targets and closure vs. direct paths.
  4. Tasks. KeepConditionHistoryTask and KeepPatientHistory build per-patient diagnosis histories. Identical diagnosis rows are merged, and KEEP's two-occurrence presence rule (§A.4) is applied after roll-up. build_keep_cooccurrence turns the histories into a sparse patient-level co-occurrence matrix.
  5. Ablations (examples/, all runnable on synthetic data):
  • Roll-up depth (3–6). Varies the depth and measures how the co-occurrence matrix changes (density, concentration, PMI/NPMI, and alignment with depth 5). It also trains PyHealth's LogisticRegression on next-admission mortality using each depth's features.
  • Roll-up target policy and root inclusion.
  • Occurrence rule. Requires one, two or three diagnoses, or two admissions.
  • Closure vs. direct graph traversal.

Scope. This PR implements KEEP's data pipeline: the ontology graph and the co-occurrence matrix. The embedding-training stage is not included. No MIMIC or Athena data is distributed, and all tests and the default example runs use synthetic data. .gitignore excludes local Athena and MIMIC downloads.

Depth ablation finding (MIMIC-IV, 1,000-patient dev subset). Shallower roll-up gives denser, more concentrated matrices with lower NPMI. On shared concepts, depth 3 diverges from depth 5, while depths 4 and 6 match it exactly. The mortality comparison is inconclusive at this sample size: each test fold has only 8–11 deaths. The script's docstring documents every setting and metric.

Files to Review

Core library

  • pyhealth/medcode/omop/vocabulary.py: OMOPVocabulary and OMOPVocabularyFormat, the Athena reader.
  • pyhealth/medcode/omop/condition_hierarchy.py: OMOPConditionHierarchy, the depth-limited SNOMED condition graph rooted at "Disease".
  • pyhealth/medcode/omop/icd_mapper.py: ICDToSNOMEDMapper.
  • pyhealth/graph/knowledge_graph.py: a small addition used by the hierarchy's KnowledgeGraph export.
  • pyhealth/processors/ancestor_rollup_processor.py: AncestorRollupProcessor.
  • pyhealth/graph/cooccurrence.py: build_cooccurrence, sparse pair counting.
  • pyhealth/tasks/keep.py: KeepConditionHistoryTask, build_keep_omop_ancestor_rollup, build_keep_cooccurrence, KeepCooccurrenceResult.
  • pyhealth/tasks/keep_patient_history.py: KeepPatientHistory.
  • pyhealth/datasets/mimic_omop_dataset.py: MIMICOMOPDataset.
  • pyhealth/patient_builder/patient_builder.py: PatientBuilder, for cohort filtering.
  • Dataset configs: pyhealth/datasets/configs/{mimic_omop,mimic3_keep,mimic4_keep,mimic4_keep_ehr}.yaml.
    Examples (each script's docstring lists its real-data flags)
  • examples/omop_keep_condition_graph_check.py: builds the condition graph from a real Athena download and checks MIMIC-IV coverage.
  • examples/{omop,mimic3,mimic4}_keep_cooccurrence_matrix.py: end-to-end matrix builds (shared helper: examples/_keep_mimic_example.py).
  • examples/mimic_omop_patient_history.py: OMOP dataset -> cohort -> KEEP histories.
  • examples/mimic4_keep_depth_ablation_logistic_regression.py: the depth ablation, with helpers in keep_depth_ablation_utils.py and keep_depth_mortality_utils.py.
  • examples/keep_ancestor_rollup_variants.py: the target-policy and root-inclusion ablation, with helpers in keep_ancestor_rollup_ablation_utils.py and accompanying notebooks.
  • examples/keep_occurrence_rule_ablation.py: the occurrence-rule ablation.
  • examples/keep_closure_mode_audit.py: the closure vs. direct traversal audit.
    Tests (synthetic, fast)
  • tests/core/test_omop_{vocabulary,condition_hierarchy,icd_mapper}.py
  • tests/core/test_ancestor_rollup_{processor,from_omop}.py
  • tests/core/test_graph_cooccurrence.py
  • tests/core/test_keep_*.py: history task, co-occurrence, OMOP ancestor loading, roll-up variants, occurrence rule, closure audit, and depth ablation.
  • tests/patient_builder/: MIMICOMOPDataset, PatientBuilder and KeepPatientHistory. These run as a new CI step in .github/workflows/test.yml, with a matching pixi task in pyproject.toml.
    Docs
  • docs/api/medcode.rst: new "OMOP Vocabularies (Athena)" section.
  • docs/api/processors/pyhealth.processors.AncestorRollupProcessor.rst
  • docs/api/graph/pyhealth.graph.cooccurrence.rst
  • docs/api/tasks/pyhealth.tasks.keep.rst
  • docs/api/tasks/pyhealth.tasks.KeepPatientHistory.rst
  • docs/api/datasets/pyhealth.datasets.MIMICOMOPDataset.rst
  • Index entries in docs/api/{datasets,graph,processors,tasks}.rst

How to Test

pytest tests/core/test_omop_*.py tests/core/test_ancestor_rollup_*.py \
       tests/core/test_graph_cooccurrence.py tests/core/test_keep_*.py \
       tests/patient_builder
python -m examples.mimic4_keep_depth_ablation_logistic_regression   # synthetic run

rishabshah and others added 28 commits November 12, 2026 13:49
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1
- 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1
Maps observed concept codes to retained SNOMED ancestors within a depth
limit of the "Disease" root (KEEP, Elhussein et al., CHIL 2025) and
projects the successful paths into one PyG Data graph per sample with
edge_index, edge_type, node_ids, x, seed_mask, target_mask and an
edge-aligned closure_only mask. Two entry points build the same internal
index: a generic constructor over pyhealth.graph.KnowledgeGraph (hierarchy
relation supplied parent -> child, optional authoritative root depths and
closure pairs) and from_omop, which derives the uncut condition subtree,
closure-derived root depths and the all-domain classification universe
from the OMOPVocabulary reader. pyhealth/medcode/omop.py is unchanged.

The depth cutoff is target eligibility over the uncut subtree, so deep
sources and intermediates stay traversable; the target policy
(first_retained / all_retained) is an explicit caller choice; rollup_codes
returns one typed result per input occurrence so tasks keep their event
IDs and count converging targets once; and path_source="closure" adds
separation-one CONCEPT_ANCESTOR pairs, flagged closure_only where no
direct "Is a" row supports them. Orphan-rescue shortcuts are deferred and
stay available through the reader's hierarchy export.

Tests port the standalone behavioural reference fixtures to the generic
path (exact edges and masks, both policies, root inclusion, supplied
depths that disagree with graph distances, invalid DAGs, PyG batching and
disk round-trip) and add a synthetic Athena-discrepancy suite reproducing
the recorded 1075201/140708 signature: direct mode reports no_target
where closure mode returns the target and flags the stitched edge, with
parity checks against ConditionHierarchy.retained_ancestors and ICD
one-to-many event mapping. Adds an RST page with runnable examples,
cross-linked from the medcode OMOP section and the processors toctree.
The OMOP factory now builds a pyhealth.graph.KnowledgeGraph over the
uncut Disease subtree with explicit entity ids, so isolated concepts
(concepts whose incoming edges were filtered out) stay addressable and
even an edge-free, root-only subtree supports identity mappings;
KnowledgeGraph accordingly accepts an empty triple list when explicit
entity and relation mappings are provided. Both entry points emit
Data.node_ids as integer graph entity ids decoded through id2entity.

process() now projects node features: the generic path uses
KnowledgeGraph.node_features, and from_omop accepts node_features_by_code
keyed by string OMOP concept id, aligns the vectors to the graph, and
zero-fills entities without vectors (untrained deep sources and traversal
intermediates included). Empty samples keep the feature width so empty
and nonempty samples batch together. The cache fingerprint (schema v2)
covers the entity-id mapping and the feature contents.

Adds tests for feature projection and alignment, zero filling,
empty/nonempty batching, pickle round-tripping, identity projection on an
edge-free ontology, and the ICD-to-embedding path, and documents a
pretrained-embedding section with a runnable example. Line lengths on
the new code are held to the 88-character contributor limit.
Add OMOP vocabulary reader + KEEP condition hierarchy + ICD mapper
Build KEEP co-occurrence from OMOP and MIMIC histories
Varies only the SNOMED depth limit (3, 4, 5, 6) and reports, per depth, the
KEEP co-occurrence matrix's size, roll-up, concentration and PMI statistics
(plus a comparison with depth 5 on shared concepts), and next-admission
mortality with PyHealth's LogisticRegression on diagnoses rolled up to that
depth. Runs on synthetic data by default; outputs aggregates only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1
Move ConditionMortalityMIMIC4, ConceptFeaturizer and featurize_arms into
examples/keep_depth_mortality_utils.py (tests to test_keep_depth_mortality.py)
so keep_depth_ablation_utils.py holds only reusable co-occurrence measures.
No behavior change: the synthetic run's output is identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1
Previously each arm's SampleDataset was built from all samples, so the code
vocabulary was fitted on validation and test patients too. Now patient folds
are chosen once per seed with PatientSplit and shared by every arm; each arm
fits its processors on that seed's training patients and reuses them for
validation and test, so held-out-only codes map to <unk>. Reports the mean
train vocabulary size. Adds tests from the review's 40-patient fixture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1
Before any training, check that each seed's shared patient folds give train,
validation and test both labels; otherwise stop with the seed and per-part
sample/positive counts (ROC-AUC/PR-AUC are undefined on one class and a
one-class validation part cannot select an epoch). Scores are checked with
math.isfinite before mean/std, so a NaN stops the run instead of being
averaged or dropped. Reports per-seed scores and the fold counts in the
printed tables and JSON. Adds tests using the review's one-positive fixture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1
Document the reference (depth 5, first_retained, closure, include_root
False, on_unmapped empty, PRESENCE_THRESHOLD, same cohort and histories,
Athena release) at the top of the example, record it as a "reference" block
in the JSON, and mark the reference column in the printed table. State that
the mortality model never uses the co-occurrence matrix, give the one-flag
command for the #7 reproduction baseline (--policy all_retained
--path-source direct), and note that synthetic checks establish our
reproduction's behavior, not the original authors'. Results are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1
Per depth: name every denominator (possible_pairs_observed for density,
possible_pairs_axes as in #7), report raw pair entropy in bits plus
pair_entropy_norm_nonzero_pairs and pair_entropy_norm_possible_pairs (not
interchangeable), and median per-concept partner entropy.

Against the reference depth, a new aligned_comparison replaces
shared_concept_comparison on common retained axes (same patients, aligned
by concept ID, diagonal excluded): concepts and pairs gained/lost/excluded
and the excluded pair-mass share; absolute prevalence and count changes;
base-2 JSD and cosine for both count and PPMI partner profiles with
valid/undefined row counts and mean/median/p90 (p10 for cosine); matched-
pair PPMI/NPMI changes with undefined counts; and |P(B|A)| changes in both
directions. The example prints it as its own table and JSON block, and the
docstring defines each measure. Tests check hand-computed values and an
independent JSD/cosine implementation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1
depth ablation: co-occurrence statistics and LogisticRegression
Load the uncut Disease subtree, authoritative root depths and direct Is a
edges without materializing unused transitive ancestry. Collect separation-one
pairs only for closure traversal, preserving target policies and defaults.

Add synthetic validation and notebooks that trace ancestor selection, root
inclusion, closure and a separately specified rescue shortcut through diagnosis
targets, patient presence, co-occurrence counts and association distributions.
Check a dense reference against single-parent and root-inclusive variants.

The studies establish preprocessing behavior and synthetic loading costs;
they do not establish author-artifact parity or better learned embeddings.
…ge (#8)

Add a reusable audit helper, synthetic semantic checks and a notebook comparing
direct Is a traversal with a minimum-separation-one ancestry overlay at fixed
root depths, eligibility and target policy. Record input identity, exact edge
deltas, structural gaps, typed mapping failures and local path witnesses.

On the identified Athena bundle, the overlay adds 334 edges, reduces nodes
unreachable from Disease from 190 to 133 and recovers 26 of 33 deep mapping
failures under both target policies. Seven deep failures remain. The eligible
target vocabulary is unchanged; additional nonempty target sets also change.

The base KnowledgeGraph remains direct; the traversal overlay can change
successful sample paths. Connectivity and coverage improve on this bundle,
but embedding quality and downstream learning effects remain inconclusive.
@rishabshah
rishabshah marked this pull request as draft November 28, 2026 18:09
Expose a positive occurrence threshold and diagnosis-row or admission support
unit in both public KEEP counting routes, retaining the default of two distinct
diagnosis rows after mapping and roll-up. Deduplicate diagnosis IDs and reject
conflicting copies; scope admission IDs to each patient and require them for
mapped diagnoses in admission mode.

Compare one, two and three diagnosis rows with two admissions on identical
synthetic histories, target axes and cohort denominators. Validate public OMOP,
mapped-MIMIC and independent counters against literal presence/count oracles.
Trace pair-count changes and report association, distribution, concentration
and potential GloVe-input changes without training embeddings.

The study establishes the counting contract and synthetic policy sensitivity,
not real-cohort effect sizes, original-author parity or improved prediction.
@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 87.67% (53657 / 61203 lines)

Modified file Coverage Lines
pyhealth/graph/cooccurrence.py 91.18% 31 / 34
pyhealth/graph/knowledge_graph.py 45.22% 71 / 157
pyhealth/medcode/__init__.py 100.00% 16 / 16
pyhealth/medcode/omop/__init__.py 100.00% 4 / 4
pyhealth/medcode/omop/condition_hierarchy.py 97.39% 112 / 115
pyhealth/medcode/omop/icd_mapper.py 100.00% 59 / 59
pyhealth/medcode/omop/vocabulary.py 98.10% 103 / 105
pyhealth/models/__init__.py 100.00% 107 / 107
pyhealth/models/hicu.py 96.61% 285 / 295
pyhealth/processors/__init__.py 95.83% 46 / 48
pyhealth/processors/ancestor_rollup_processor.py 87.23% 321 / 368
pyhealth/tasks/__init__.py 98.36% 120 / 122
pyhealth/tasks/keep.py 89.97% 287 / 319
pyhealth/tasks/mimic3_icd9_category_classification.py 100.00% 70 / 70

Workflow run · 263f709

@solarsys

Copy link
Copy Markdown
Collaborator

A heads-up while this is still a draft: #1666 adds the KEEP embedding trainer. This PR covers the data side (OMOP vocabulary, SNOMED hierarchy, ICD→SNOMED mapping, ancestor roll-up, co-occurrence), which is closer to the paper's SNOMED setup, so the two fit together.

When you're ready, please split this into small PRs:

  1. The OMOP vocabulary, hierarchy and mapper in medcode, ruff-clean. Contribution-rules currently fails with 52 ruff errors such as UP006/UP007/UP045.
  2. Co-occurrence building, which can replace Add KEEP: Ontology-Informed Clinical Code Embeddings with MIMIC-IV Reproduction #1666's example-only builder.
  3. The roll-up processor and the history task, feeding Add KEEP: Ontology-Informed Clinical Code Embeddings with MIMIC-IV Reproduction #1666's fit_keep.

Drop:

  • the notebooks (about 9,400 lines);
  • the behavior change to knowledge_graph.py, unless it's justified on its own;
  • the .gitignore edit.

The description also lists files that aren't in the diff: MIMICOMOPDataset, PatientBuilder, a CI workflow and a pyproject change.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants