Skip to content

Prepare KEEP clinical histories and co-occurrence counts - #1706

Open
lee-leonardo wants to merge 5 commits into
sunlabuiuc:masterfrom
lee-leonardo:codex/c0019-rollup-history
Open

lee-leonardo wants to merge 5 commits into
sunlabuiuc:masterfrom
lee-leonardo:codex/c0019-rollup-history

Conversation

@lee-leonardo

@lee-leonardo lee-leonardo commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Prepare clinical diagnosis histories and patient-level co-occurrence inputs for the existing KEEP trainer. The task preserves diagnosis identity, unions converging mapping paths within each diagnosis, and applies diagnosis/admission support thresholds after mapping and roll-up. Synthetic examples reuse KEEP, KEEPConfig, fit_keep and embedding exports introduced in #1666.

This is the clinical-history and counting portion of the original KEEP contribution #1661. The processor and OMOP factory have been extracted into #1803.

The original KEEP contribution includes work by Rishab Shah (rishabs4), Leo Lee (ll37) and Murali Rachakonda (muralir2). Existing source attribution is preserved. The merged KEEP trainer and original synthetic training example are by Stanislav Sheludko and Kalindu Madduma Hewage.

Dependency and review order

Depends on #1803: ancestor roll-up processor and OMOP factory. Review and merge that PR first.

The processor PR is based on upstream master 209dc988 and contains the processor/factory implementation, their documentation and the latest regression tests. This branch remains intact at 22ad43c2 so its working history/counting/training pipeline is preserved. Its current diff against master therefore still includes the processor dependency.

After #1803 merges, rebase this branch onto master, remove the superseded processor/factory changes, resolve documentation/export/test conflicts and rerun the history/counting/trainer checks. The remaining review will cover clinical histories, support counting, MIMIC configs and runnable synthetic examples.

The generic counter #1707 and OMOP vocabulary/hierarchy/mapper #1709 are already merged. Their implementations come from master.

The counter follow-up #1787 is separate. This contribution supplies unique patient sets to the merged counter and keeps sparse COO counts. Its callers passed an isolated compatibility check against #1787's counter at 30bcd8bb.

The paper and inspected released code leave occurrence counting, roll-up boundaries, hierarchy construction, and matrix/vocabulary construction unresolved. #1802 tracks the study of preprocessing code, reference artifacts and author clarification needed to resolve these details and verify the choices used here.

Intended scope after the dependency merges

  • Add KeepConditionHistoryTask, opt-in MIMIC-III/IV reader configs and cohort counting. Preserve exact-copy deduplication, conflicting-copy rejection, the full MIMIC-IV diagnosis key (hadm_id, seq_num, icd_code, icd_version), cache versioning and effective-mapping fingerprints.
  • Apply diagnosis/admission support thresholds after mapping and roll-up. One diagnosis supplies at most one unit of support per target, even when several mapped concepts or paths converge.
  • Preserve integer raw counts, prevalence diagonals, caller-specified retained axes and absent-concept zero rows. Graph-only roots/intermediates align explicitly by concept ID.
  • Extend the existing examples/keep_synthetic.py with a training adapter, reused by the clinical examples through --train. It derives positive off-diagonal CPU NumPy triplets, preserves count-one pairs and both mirrored triangles, aligns reference vectors by concept ID, and exports the complete vocabulary in matrix order. It skips training when no eligible pairs exist.
  • Add processor/task API documentation and focused synthetic correctness, reader/cache, occurrence-rule and trainer-integration tests.

The clinical examples use all_retained, depth five, root excluded from targets and two distinct diagnoses per target. The existing ICD-10/two-admission preprocessing example retains its separate profile. Example training runs on CPU with explicit synthetic reference vectors.

The count matrix remains sparse through counting and preparation of the training triplets. NumPy is used for the trainer's one-dimensional input arrays, the V × embedding_dim reference array and embedding exports; it does not accumulate a dense V × V count matrix. The tiny example report does create a dense copy for printing, without changing the returned sparse tensor or the training input. The example adapter currently expects sparse COO counts; selecting #1787's optional dense layout would require a separate adapter change.

Processor construction and graph behavior are covered by #1803. Research notebooks and ablation helpers remain in keep-validation; the trainer implementation is unchanged.

Validation

The results below cover the unchanged combined branch, including its processor/factory dependency. A fresh task-focused validation will follow the rebase after #1803 merges.

Source and example validation was performed at e6b68bce, after the 2026-12-03 rebase onto the merged OMOP and co-occurrence contributions. The test-only follow-up 22ad43c2 reran the same selected suites; the totals below include existing dependency and trainer tests:

  • 260 tests passed, with two optional CUDA output-placement checks skipped; 41 subtests passed.
  • Six additional discrete tests cover malformed ICD-source diagnostics, malformed closure-pair structure and node-feature mapping/alignment requirements through existing public APIs. Production logic and API visibility are unchanged. With the same suite, processor line coverage rose from 96.20% to 97.01% and KEEP-task line coverage from 92.52% to 94.39%; branch coverage rose from 92.86% to 95.00% and 84.46% to 89.19%, respectively.
  • Hand-derived checks cover multi-parent/converging mappings, diagnosis identity, post-roll-up support, retained zero rows, exact matrices, coordinate alignment and empty training views. Synthetic reader tests exercise MIMIC identity and history-cache behavior.
  • 187 KEEP compatibility tests passed against Fix co-occurrence count modes and refactor EviCare counting to PyTorch #1787's proposed counter at 30bcd8bb, loaded in an isolated process without changing this branch's source.
  • 14 public docstring examples passed; three external-data examples were skipped.
  • Synthetic MIMIC-IV --train completes two CPU epochs with finite loss and all 12 retained concepts exported in matrix order. The MIMIC-III prevalence-only fixture correctly skips training. The original synthetic GloVe/cosine/L2 example also executes successfully.
  • PR contribution rules pass locally with Ruff 0.17.6 and in the source-validation contribution-rules run; git diff --check passes. The full GitHub Python test workflow is separate from the local results above.

These checks establish synthetic correctness and API compatibility. They are not throughput, memory-scaling or clinical-scale performance benchmarks. Historical coverage reports in the discussion are tied to their recorded commit; they should be read with that provenance.

python -m examples.mimic4_keep_cooccurrence_matrix --train
python -m examples.mimic3_keep_cooccurrence_matrix --train
python -m examples.keep_synthetic

python -m pytest \
  tests/core/test_graph_cooccurrence.py tests/core/test_keep_mimic_preprocessing.py \
  tests/core/test_omop_vocabulary.py tests/core/test_omop_condition_hierarchy.py \
  tests/core/test_omop_icd_mapper.py tests/core/test_ancestor_rollup_processor.py \
  tests/core/test_ancestor_rollup_from_omop.py tests/core/test_keep_omop_ancestor_loading.py \
  tests/core/test_keep_condition_history.py tests/core/test_keep_cooccurrence.py \
  tests/core/test_keep_cooccurrence_from_omop.py tests/core/test_keep_occurrence_rule.py \
  tests/core/test_keep_preprocessing_training.py tests/core/test_keep.py -q

python tools/check_pr_rules.py --base master --head HEAD

Supporting preprocessing studies

The accompanying research notebooks in keep-validation examine how ancestor selection and occurrence support change the histories and patient sets produced by this pipeline.

Two relevant synthetic findings are:

  • Ancestor selection and root inclusion: On a fixed ten-patient fixture, selecting exactly one ancestor reduced observed unordered off-diagonal pairs from 45 to 1, with pair-count mass falling from 136 to 2. Including Disease instead increased pairs from 45 to 55 and mass from 136 to 166; all added pairs involved Disease, while non-root raw counts stayed unchanged. This single-ancestor intervention differs from first_retained, which can retain several parents. Study and controls.
  • Presence threshold and counting unit: On a separate ten-patient fixture with fixed mapping and axes, requiring one, two, or three diagnosis rows, or two distinct admissions, produced 8, 5, 2, and 3 patients with present targets respectively. Every arm retained 45 observed pairs, but pair-count mass changed to 316, 180, 90, and 90. Identical pair support therefore did not imply identical counts. Study and controls.

These studies motivate explicit roll-up policies, diagnosis identity and support units. They use the earlier KEEP development revision 263f709e and establish synthetic preprocessing sensitivity; they are separate from validation of this extracted branch and do not demonstrate better embeddings, clinical predictive performance or published-result replication. The notebooks and research helpers remain in the external repository. Execution provenance and verification.

@github-actions

github-actions Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 89.41% (69558 / 77800 lines)

Modified file Coverage Lines
pyhealth/processors/__init__.py 96.00% 48 / 50
pyhealth/processors/ancestor_rollup_processor.py 86.68% 319 / 368
pyhealth/tasks/__init__.py 98.75% 158 / 160
pyhealth/tasks/keep.py 90.03% 289 / 321

Workflow run · e6b68bc

@lee-leonardo lee-leonardo changed the title Add ancestor roll-up and clinical histories feeding KEEP Add ancestor roll-up and clinical histories feeding KEEP (split from PR#1661) Nov 29, 2026
@lee-leonardo lee-leonardo changed the title Add ancestor roll-up and clinical histories feeding KEEP (split from PR#1661) [CS 598 - DL4H] Add ancestor roll-up and clinical histories feeding KEEP (split from PR#1661) Dec 1, 2026
@lee-leonardo
lee-leonardo force-pushed the codex/c0019-rollup-history branch from 6d2ebae to 234699b Compare December 2, 2026 00:00
solarsys pushed a commit that referenced this pull request Dec 3, 2026
* 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1

* 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1

* 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1

* Document OMOP mapper and hierarchy usage examples

* 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1

* Drop the .gitignore change

Changes outside docs/, examples/, pyhealth/, test-resources/ and tests/
send a PR to manual review. The OMOP code never writes into the repo:
tests use temporary directories and the example caches under --cache
(default ~/.cache/pyhealth/omop_keep), so the ignore entries for local
Athena and MIMIC-IV downloads are not needed here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JrebVyPi1jFyjkAiLbLSC1

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: lee-leonardo <hi@leeleonardo.dev>
Copy the processor, factory, API docs and focused tests from task/llee_depth_ancestor_rollup (6dfa49b..33c2cb6), with the reduced ancestor queries from codex/keep-rollup-scale (24341db). Retain explicit target policy, root eligibility, direct/closure traversal, provenance and graph feature projection. Depend on the separate OMOP prerequisite queries. Exclude the KnowledgeGraph behavior change and explicitly reject root-only and closure-only edgeless bases; preserve isolated nodes on nonempty graphs. Validation: 101 focused tests passed.
Copy task, MIMIC configs, minimal reader examples and correctness tests from task/llee_keep_cooccurrence (8e21a8a, a4b7bee, 46261db). Retain the occurrence-unit options and focused API tests from task/ablations_occurrence_rule (5c0577d), excluding its research study and notebooks. Preserve complete retained axes, prevalence diagonals, diagnosis deduplication, full MIMIC-IV diagnosis identity and cache fingerprinting. Reuse the C-0018 generic counter. Validation: 40 clinical workflow tests passed, including real synthetic reader/cache paths.
Extend the existing sunlabuiuc#1666 synthetic example with a raw-result adapter and use it from the synthetic MIMIC history examples. Derive positive off-diagonal CPU NumPy triplets without mutating raw counts, retain count-one pairs and complete axes, align synthetic reference vectors by concept ID, and export every retained concept in matrix order. Skip fit_keep when no training pairs exist. Use the depth-five clinical baseline while preserving the separate ICD/two-admission preprocessing example. Validation: 254 tests passed, two CUDA-only cases skipped, and 27 subtests passed across the assembled workflow; processor/task coverage is 96%/93%; 14 public doctests passed. Both clinical examples and the original synthetic trainer example execute successfully; contribution rules pass with the CI Ruff version.
CI installs Ruff 0.17.6 through ruff~=0.15. That version reports the E402 suppression as unused (RUF100), whereas the older 0.15.22 local check required it. Remove the suppression and verify contribution rules with the actual CI version. No runtime behavior changes.
@lee-leonardo
lee-leonardo force-pushed the codex/c0019-rollup-history branch 2 times, most recently from 8784a00 to e6b68bc Compare December 3, 2026 21:09
@lee-leonardo
lee-leonardo marked this pull request as ready for review December 4, 2026 00:54
@solarsys solarsys added the status: manual Pending maintainer's review label Dec 4, 2026
@solarsys

solarsys commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator

Thanks for splitting this out of #1661 and rebasing it onto the merged #1707 and #1709. I've labeled it status: manual. All files are inside the allowed folders, but the change is very large: about 6,500 added lines, with a diff of about 277k characters, which is over the AI review's 200k automatic limit. It also adds a new processor, a new task and two dataset configs, so a maintainer needs to review it.

I'll request the AI review once the build passes, so the maintainers have its notes as well.

@solarsys

solarsys commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator

/review

@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown

AI Review

suggestion: not available
decision: not available

This PR is too large for AI review (over 300 files or 200000 diff characters). The label stays as it is: you can make the PR smaller, for example by clearing notebook outputs or splitting it, and comment /review again, or a maintainer can review it as it is.

@lee-leonardo lee-leonardo changed the title [CS 598 - DL4H] Add ancestor roll-up and clinical histories feeding KEEP (split from PR#1661) Prepare KEEP clinical histories and co-occurrence counts Dec 4, 2026
@lee-leonardo

Copy link
Copy Markdown
Contributor Author

I've opted to split the PR again, #1803 is focused on the processor and the task functionality specific to the ancestor roll-up

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

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants