Skip to content

Add generic co-occurrence matrix builder (split from KEEP #1661 [CS 598 - DL4H]) - #1707

Merged
solarsys merged 3 commits into
sunlabuiuc:masterfrom
lee-leonardo:cooccurrence_matrix
Dec 1, 2026
Merged

solarsys merged 3 commits into
sunlabuiuc:masterfrom
lee-leonardo:cooccurrence_matrix

Conversation

@lee-leonardo

Copy link
Copy Markdown
Contributor

Overview

Extract the reusable patient-level co-occurrence counter from KEEP integration PR #1661, following the maintainer’s request to split co-occurrence construction into a separate contribution.

The counter accepts caller-selected concept sets and builds a symmetric sparse matrix. This contribution also replaces the local pair-counting implementation in examples/keep_mimic_preprocessing.py, introduced by KEEP embedding trainer PR #1666.

The original KEEP contribution includes work by Rishab Shah (rishabs4), Leo Lee (ll37), and Murali Rachakonda (muralir2). Existing source attribution is preserved.

Implementation

  • Add pyhealth.graph.cooccurrence.build_cooccurrence, independent of medical vocabularies, OMOP, and ancestor roll-up.
  • Preserve caller-specified concept order, absent-concept zero rows, and empty patients.
  • Return coalesced PyTorch sparse COO integer counts, with configurable output device placement and an optional transform receiving the matrix and total patient count.
  • Retain patient prevalence on the diagonal by default. Set include_diagonal=False to count only distinct-concept pairs.
  • Integrate the utility into the existing KEEP preprocessing example, preserving its sorted observed vocabulary, symmetric zero-diagonal SciPy CSR float32 output, ICD-10 filtering, and admission-based presence rule.
  • Add API documentation and focused synthetic tests.

Pair counting runs on CPU and requires no CUDA. The default output is also on CPU. The optional device argument controls where the resulting sparse tensor is constructed; it does not move pair counting to CUDA.

Clinical presence rules remain the caller’s responsibility. The counter counts the supplied patient sets without choosing occurrence thresholds or ontology policies.

Validation

  • 33 tests passed. Two optional CUDA output-placement checks were skipped because CUDA was unavailable; counting and the example integration were verified on CPU.
  • 100% statement coverage for the generic counter.
  • Independent regression against the example’s original pair-counting algorithm, including repeated codes, singleton-only concepts, empty patients, and permuted inputs.
  • Counter checks cover axis order and validation, empty cohorts, diagonal selection, single-pass iteration, CPU output placement, and transform behavior.
  • Public docstring example and PR contribution-rule checks passed.
python -m pytest \
  tests/core/test_graph_cooccurrence.py \
  tests/core/test_keep_mimic_preprocessing.py -q

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

Supporting preprocessing studies

The accompanying research notebooks in keep-validation examine how upstream preprocessing choices change the sets supplied to co-occurrence counting.

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.
  • Presence threshold and counting unit: On a separate ten-patient fixture, 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.

These studies motivate separating counting arithmetic from presence selection. They use the earlier KEEP development revision and establish synthetic preprocessing sensitivity; they do not validate improved embeddings or predictive performance for this extracted branch. The notebooks and research helpers remain in the external repository. Execution provenance and verification.

Copy the counter, focused tests and API documentation from task/llee_keep_cooccurrence (8e21a8a and a4b7bee). These files are unchanged on task/ablations_occurrence_rule. Omit the clinical task and OMOP dependencies, and describe presence independently in the docs.
Add explicit diagonal selection, retaining prevalence by default. Preserve the merged example’s zero-diagonal float32 CSR output and observed vocabulary by delegating only pair counting. Add independent old-builder regression and counter edge-case tests; retain admission and ICD filtering.
@github-actions

github-actions Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 89.32% (65267 / 73067 lines)

Modified file Coverage Lines
pyhealth/benchmarks/__init__.py 100.00% 4 / 4
pyhealth/benchmarks/robustness.py 85.71% 30 / 35
pyhealth/calib/calibration/hb.py 88.60% 101 / 114
pyhealth/calib/calibration/temperature_scale.py 100.00% 45 / 45
pyhealth/datasets/__init__.py 100.00% 95 / 95
pyhealth/datasets/chestxray14.py 84.26% 91 / 108
pyhealth/datasets/gwas_proxy_sim.py 97.70% 85 / 87
pyhealth/datasets/gwas_simulator.py 96.67% 116 / 120
pyhealth/datasets/ham10000.py 94.48% 137 / 145
pyhealth/datasets/hbn_eeg.py 94.59% 140 / 148
pyhealth/datasets/hirid.py 100.00% 32 / 32
pyhealth/datasets/physionet2012.py 96.64% 115 / 119
pyhealth/datasets/seer.py 92.19% 59 / 64
pyhealth/graph/cooccurrence.py 100.00% 37 / 37
pyhealth/medcode/pretrained_embeddings/lm_emb/openai_retriever.py 100.00% 13 / 13
pyhealth/metrics/__init__.py 100.00% 21 / 21
pyhealth/metrics/fairness_selection.py 100.00% 27 / 27
pyhealth/metrics/group_fairness.py 100.00% 97 / 97
pyhealth/metrics/gwas_discovery.py 98.39% 61 / 62
pyhealth/metrics/labtop.py 98.61% 71 / 72
pyhealth/models/__init__.py 100.00% 139 / 139
pyhealth/models/apex_gp.py 95.96% 499 / 520
pyhealth/models/brain_network_transformer.py 98.20% 164 / 167
pyhealth/models/causal_gated_imputer.py 98.75% 79 / 80
pyhealth/models/cehrgpt.py 98.31% 116 / 118
pyhealth/models/deepcoxph.py 96.43% 108 / 112
pyhealth/models/dkaft.py 95.37% 371 / 389
pyhealth/models/duett.py 93.52% 101 / 108
pyhealth/models/fedweight.py 98.48% 260 / 264
pyhealth/models/generators/corgan.py 98.77% 241 / 244
pyhealth/models/generators/gpt2.py 86.01% 123 / 143
pyhealth/models/generators/halo.py 92.07% 325 / 353
pyhealth/models/generators/medgan.py 98.95% 189 / 191
pyhealth/models/generators/promptehr.py 88.89% 184 / 207
pyhealth/models/generators/synthea.py 95.96% 261 / 272
pyhealth/models/giantmed.py 96.69% 409 / 423
pyhealth/models/labram.py 98.81% 250 / 253
pyhealth/models/labtop.py 94.87% 37 / 39
pyhealth/models/llm_code_transfer.py 94.61% 614 / 649
pyhealth/models/protoecgnet.py 98.18% 377 / 384
pyhealth/models/protoecgnet_h1.py 94.53% 259 / 274
pyhealth/models/protoecgnet_h1_checkpoint.py 87.71% 157 / 179
pyhealth/models/protoecgnet_h1_data.py 88.80% 111 / 125
pyhealth/models/protoecgnet_h1_reference.py 100.00% 153 / 153
pyhealth/models/robust_shy.py 91.67% 22 / 24
pyhealth/models/salientsleepnet.py 99.47% 189 / 190
pyhealth/models/shy.py 94.43% 339 / 359
pyhealth/models/stagenet_mha.py 94.33% 266 / 282
pyhealth/models/stepwise_embedding.py 95.58% 173 / 181
pyhealth/models/surgical_aggregation.py 96.30% 156 / 162
pyhealth/models/t3a.py 98.11% 104 / 106
pyhealth/models/temporalscl.py 87.63% 248 / 283
pyhealth/models/tpc.py 99.29% 422 / 425
pyhealth/nlp/metrics.py 84.17% 218 / 259
pyhealth/processors/__init__.py 95.92% 47 / 49
pyhealth/processors/band_power_processor.py 98.80% 82 / 83
pyhealth/processors/seer_processor.py 95.40% 83 / 87
pyhealth/processors/vit_embedding_processor.py 89.60% 155 / 173
pyhealth/sampler/__init__.py 100.00% 5 / 5
pyhealth/sampler/group_sampler.py 100.00% 83 / 83
pyhealth/tasks/__init__.py 98.69% 151 / 153
pyhealth/tasks/barttender_chestxray14.py 94.00% 94 / 100
pyhealth/tasks/barttender_encoding.py 100.00% 126 / 126
pyhealth/tasks/barttender_giou.py 100.00% 60 / 60
pyhealth/tasks/cehrgpt_omop.py 97.16% 205 / 211
pyhealth/tasks/drug_recommendation.py 94.98% 265 / 279
pyhealth/tasks/fedweight_eicu.py 100.00% 91 / 91
pyhealth/tasks/ham10000_malignancy.py 100.00% 42 / 42
pyhealth/tasks/hbn_psychopathology.py 98.67% 74 / 75
pyhealth/tasks/hbn_response_time.py 100.00% 134 / 134
pyhealth/tasks/in_icu_mortality_emdot_mimic4.py 95.82% 275 / 287
pyhealth/tasks/labtop.py 96.60% 199 / 206
pyhealth/tasks/phenotype_imputation.py 100.00% 29 / 29
pyhealth/tasks/physionet2012_stepwise_mortality.py 85.42% 41 / 48
pyhealth/tasks/ptbxl_reduced_lead_rhythm.py 100.00% 23 / 23
pyhealth/tasks/seer_survival.py 96.97% 32 / 33
pyhealth/tasks/shhs_multimodal_masking.py 90.48% 57 / 63
pyhealth/tasks/shhs_multimodal_sleep_staging.py 92.03% 127 / 138
pyhealth/tasks/sleep_staging.py 93.48% 86 / 92
pyhealth/tasks/sleep_staging_v2.py 98.84% 85 / 86
pyhealth/tasks/temporal_outcome_prediction_mimic4.py 85.81% 248 / 289
pyhealth/tasks/tpc_eicu.py 98.01% 197 / 201
pyhealth/tasks/tuh_referential_tasks.py 100.00% 37 / 37
pyhealth/tokenizer.py 79.75% 63 / 79

Workflow run · 265e910

@solarsys solarsys added the status: automatic The PR will go through automatic review process. label Nov 30, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 8019c7f

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: need change

Thank you for splitting this out of the KEEP work. build_cooccurrence is a clean, well-tested counter, and it replaces the example's local pair counting without changing the example's output. Tests cover axis order, validation, empty cohorts, diagonal choice, device placement and transform behavior. The example is also checked against an independent copy of the old algorithm. Coverage is 100% for pyhealth/graph/cooccurrence.py, above the 80% per-file bar. Whole-repo coverage is 88.2%, above the 60% bar.

To get this merged:

  • pyhealth/models/evicare.py appears to already contain patient-level co-occurrence counting in CooccurrenceGraph.fit, and the description doesn't mention it. Please say in the description how the new builder relates to it. For example, you could note that it is deliberately separate because it is sparse, uses a caller-defined axis order, and has a diagonal option and a transform. If the two do the same job, please say why a second implementation is needed. Either way, keep the components self-contained unless you intend to share code, and if you do share code, state the reason.

Optional suggestions:

  • The builder expects sets. If someone passes a list with a repeated concept, it overcounts. With include_diagonal=False, it can also put a nonzero value on the diagonal. You could convert each input with set(concepts) or state the requirement more prominently in the docstring.
  • The docs page could be shorter. The cosine-similarity and ETL-batching paragraphs could be cut or trimmed.
  • The example now imports pyhealth when it loads. This is fine, but it may be worth a short note in the example's docs.

Reviewed commit 8019c7f

@lee-leonardo lee-leonardo changed the title Add generic co-occurrence matrix builder (split from KEEP #1661) Add generic co-occurrence matrix builder (split from KEEP #1661 [CS 598 - DL4H] ) Dec 1, 2026
@lee-leonardo lee-leonardo changed the title Add generic co-occurrence matrix builder (split from KEEP #1661 [CS 598 - DL4H] ) Add generic co-occurrence matrix builder (split from KEEP #1661 [CS 598 - DL4H]) Dec 1, 2026
@solarsys

solarsys commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit 265e910

import torch


def build_cooccurrence(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Overlaps with existing EviCare CooccurrenceGraph.fit; description does not mention it

pyhealth/models/evicare.py:248-312 (CooccurrenceGraph.fit) already counts patient-level code co-occurrences by summing np.ix_ blocks over per-patient code sets, including diagonal prevalence. The new build_cooccurrence performs the same counting. It differs in output (sparse torch COO rather than dense numpy), include_diagonal, the transform hook and device placement, so it is not a near-copy and is not flagged as redundant. Please add a sentence to the description explaining why a separate generic counter is needed rather than reusing CooccurrenceGraph.

patient_count = 0
for patient_count, concepts in enumerate(patient_concepts, start=1):
try:
positions = sorted(axis_index[code] for code in concepts)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] List inputs with repeated codes silently overcount

positions = sorted(axis_index[code] for code in concepts) keeps duplicates. If a caller passes a list such as ["A", "A"] (the form the example's patient_codes naturally has), the diagonal is counted more than once with include_diagonal=True and the pair with include_diagonal=False is miscounted. The docstring warns about this, but deduplicating here with set(concepts) before sorting would remove the silent wrong result at negligible cost.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review

suggestion: approve
decision: approve

Thank you for this contribution, and for splitting it out of the KEEP work as the maintainer asked. pyhealth.graph.cooccurrence.build_cooccurrence is a clear, self-contained counter. It keeps the caller's concept order and returns a coalesced sparse COO integer matrix. It has a diagonal switch, output device placement and an optional transform. The KEEP preprocessing example now uses it, and a regression test checks that against the original algorithm.

It looks ready to merge.

  • Correctness: I found no problems in the diff. Empty cohorts, empty patients, absent concepts and the validation paths are all handled.
  • Docs: The API page matches the code, including the CPU-only counting note and the diagonal behavior.
  • Tests: pyhealth/graph/cooccurrence.py is at 100% coverage, above the 80% bar. Total repository coverage is 89.32%, above the 60% bar.
  • Links between components: The only new link is the example importing the new utility. The description explains it.

Optional suggestions:

  • pyhealth/models/evicare.py (CooccurrenceGraph.fit) already computes patient-level co-occurrence counts as dense numpy. Your counter returns a different output type and has different options, so I don't see it as a duplicate. You could add one sentence to the description saying how the two differ.
  • The counter does not deduplicate list inputs, so repeated codes overcount. The docstring warns about this. If you want it to be safer, you could deduplicate inside the function. That is entirely your choice.

Reviewed commit 265e910

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

Labels

status: automatic The PR will go through automatic review process.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants