Repository navigation
KEEP Integration etc. - #1661
Draft
rishabshah wants to merge 31 commits into
Draft
rishabshah wants to merge 31 commits into
rishabshah wants to merge 31 commits into
Conversation
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
Depth based ancestor rollup logic
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
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.
Test CoverageTotal: 87.67% (53657 / 61203 lines)
|
This was referenced Nov 28, 2026
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:
Drop:
The description also lists files that aren't in the diff: MIMICOMOPDataset, PatientBuilder, a CI workflow and a pyproject change. |
This was referenced Nov 29, 2026
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Contributors
rishabs4, rishabs4@illinois.edu)ll37, ll37@illinois.edu)muralir2, muralir2@illinois.edu)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:
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 aKnowledgeGraph.MIMICOMOPDatasetloads MIMIC-IV in OMOP CDM form, and PatientBuilder filters it down to a cohort.AncestorRollupProcessormaps each code to its retained ancestor(s) at a chosen depth. It supports first-retained vs. all-retained targets and closure vs. direct paths.KeepConditionHistoryTaskandKeepPatientHistorybuild 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_cooccurrenceturns the histories into a sparse patient-level co-occurrence matrix.examples/, all runnable on synthetic data):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.
.gitignoreexcludes 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:OMOPVocabularyandOMOPVocabularyFormat, 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'sKnowledgeGraphexport.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.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 inkeep_depth_ablation_utils.pyandkeep_depth_mortality_utils.py.examples/keep_ancestor_rollup_variants.py: the target-policy and root-inclusion ablation, with helpers inkeep_ancestor_rollup_ablation_utils.pyand 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}.pytests/core/test_ancestor_rollup_{processor,from_omop}.pytests/core/test_graph_cooccurrence.pytests/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,PatientBuilderandKeepPatientHistory. These run as a new CI step in.github/workflows/test.yml, with a matching pixi task inpyproject.toml.Docs
docs/api/medcode.rst: new "OMOP Vocabularies (Athena)" section.docs/api/processors/pyhealth.processors.AncestorRollupProcessor.rstdocs/api/graph/pyhealth.graph.cooccurrence.rstdocs/api/tasks/pyhealth.tasks.keep.rstdocs/api/tasks/pyhealth.tasks.KeepPatientHistory.rstdocs/api/datasets/pyhealth.datasets.MIMICOMOPDataset.rstdocs/api/{datasets,graph,processors,tasks}.rstHow to Test