-
Notifications
You must be signed in to change notification settings - Fork 2
Feature/adaptive truncation #70
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
RH-MikkelWerling
wants to merge
18
commits into
main
Choose a base branch
from
feature/adaptive_truncation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
cdd7106
first try at adaptive truncation
RH-MikkelWerling 4951099
Polish adaptive mapping audit output
RH-MikkelWerling 5b08b0d
remove sks mapping
RH-MikkelWerling 402286e
move functionality and only keep levels functionality
RH-MikkelWerling dedb197
add default values config
RH-MikkelWerling 55a3adc
update fit_adaptive_code_mappings
RH-MikkelWerling f323559
add claude to gitignore
RH-MikkelWerling 18b8d3b
remove tracking for settings.json
RH-MikkelWerling fbd0684
remove temporary alias
RH-MikkelWerling 30a7f4d
declutter finalize adaptive
RH-MikkelWerling cd14345
make hierarchies empty result in error
RH-MikkelWerling 0bf9acd
remove default
RH-MikkelWerling 48d9c19
move explanations to readme
RH-MikkelWerling 5f2353e
make utils and restructure
RH-MikkelWerling 19a7d87
revert to simpler handling of external aggregation data
RH-MikkelWerling 34a6ecf
test functionality
RH-MikkelWerling 08ce42b
ruff is ruff
RH-MikkelWerling e5a229d
remove test file
RH-MikkelWerling File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -129,4 +129,7 @@ dmypy.json | |
| .pyre/ | ||
| */data/* | ||
| data/* | ||
| *.DS* | ||
| *.DS* | ||
|
|
||
| # Claude | ||
| .claude/ | ||
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| minimum_count: 100 | ||
| mapping_output_filepath: null | ||
| # Defaults to <mapping_output_filepath>.summary.json. | ||
| mapping_summary_output_filepath: null | ||
| # A frozen mapping (JSON or Parquet, with `code` and `adaptive/mapped_code` | ||
| # columns) from an external collaborator. Only used as a fallback when | ||
| # `fit_adaptive_code_mapping` did not run locally -- a local fit always | ||
| # takes precedence over this. | ||
| mapping_filepath: null | ||
|
|
||
| # Only namespace routing normally needs configuration; the level widths for | ||
| # each profile are defined below under `hierarchies`. | ||
| namespaces: | ||
| RD: sks_diagnosis | ||
| RC: sks_diagnosis | ||
| RC_ADM: sks_diagnosis | ||
| RPS: sks_operation | ||
| RPO: sks_other_procedure | ||
| RM: atc | ||
| RMA: atc | ||
|
|
||
| # Character-position level widths per code system. A pipeline config can | ||
| # override any single field of a profile (e.g. `hierarchies: {atc: {levels: | ||
| # [...]}}`) without repeating the rest, or add a wholly new profile name. | ||
| # See README.md ("Custom MEDS stages") for why level 1 is excluded from the | ||
| # SKS profiles here but kept for ATC. | ||
| hierarchies: | ||
| sks_diagnosis: | ||
| levels: [4, 3, 2] | ||
| sks_operation: | ||
| levels: [7, 6, 5, 4, 3, 2] | ||
| sks_other_procedure: | ||
| levels: [8, 7, 6, 5, 4, 3, 2] | ||
| atc: | ||
| levels: [1, 3, 4, 5, 7] |
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| description: |- | ||
| Variant of `lymphoma_pipeline.yaml` for sites that adopt an adaptive code | ||
| mapping and/or numeric-value metadata produced elsewhere (e.g. by a | ||
| consortium such as PHAIR) instead of fitting their own from local training | ||
| counts. The only differences from the base pipeline are: | ||
|
|
||
| 1. `fit_adaptive_code_mapping` is dropped from `stages` entirely -- no | ||
| local code-mapping fit is attempted. `apply_adaptive_code_mapping` and | ||
| `finalize_adaptive_code_metadata` both set `mapping_filepath` to the | ||
| externally-supplied mapping. | ||
| 2. `aggregate_numeric_metadata` is likewise dropped -- no local numeric fit | ||
| is attempted. `annotate_numeric_values` sets `numeric_metadata_filepath` | ||
| to the externally-supplied numeric metadata instead. | ||
|
|
||
| In both cases, the external source is a fallback, not an override: since | ||
| no local fit ran, the relevant metadata columns don't exist yet at that | ||
| point in the pipeline, so both stages fall back to the external source | ||
| (see README.md, "Custom MEDS stages", for why a local fit -- when one | ||
| exists -- always takes precedence over this instead of being merged with | ||
| it). | ||
|
|
||
| Set the same environment variables as the base pipeline, plus: | ||
|
|
||
| export EXTERNAL_MAPPING_FP=/path/to/phair_code_mapping.parquet # code + adaptive/mapped_code columns | ||
| export EXTERNAL_NUMERIC_METADATA_FP=/path/to/phair_numeric_metadata.json # fitted numeric-value transforms | ||
|
|
||
| input_dir: ${oc.env:PREMEDS_INPUT_DIR} | ||
| output_dir: ${oc.env:MEDS_OUTPUT_DIR} | ||
| shards_map_fp: ${output_dir}/metadata/.shards.json | ||
| source_event_conversion_config_fp: ${oc.env:EVENT_CONVERSION_CONFIG_FP} | ||
| event_conversion_config_fp: ${output_dir}/event_conversion_config.augmented.yaml | ||
| external_mapping_fp: ${oc.env:EXTERNAL_MAPPING_FP} | ||
| external_numeric_metadata_fp: ${oc.env:EXTERNAL_NUMERIC_METADATA_FP} | ||
|
|
||
|
|
||
| etl_metadata: | ||
| dataset_name: preMEDS | ||
| dataset_version: 2.0 | ||
|
|
||
| stages: | ||
| - augment_event_config: | ||
| source_event_conversion_config_fp: ${source_event_conversion_config_fp} | ||
| output_event_conversion_config_fp: ${event_conversion_config_fp} | ||
| event_columns: | ||
| row_idx: $row_idx | ||
|
|
||
| - shard_events: | ||
| infer_schema_length: 999999999 | ||
| # MEDS-Extract derives the raw cohort root from this path's parent. | ||
| data_input_dir: ${input_dir}/data | ||
|
|
||
| - split_and_shard_subjects: | ||
| n_subjects_per_shard: 10000 | ||
| split_fracs: | ||
| train: 0.9 | ||
| tuning: 0.1 | ||
| - convert_to_subject_sharded | ||
| - convert_to_MEDS_events: | ||
| do_dedup_text_and_numeric: true | ||
| - merge_to_MEDS_cohort: | ||
| # row_idx provides deterministic ordering for simultaneous events. | ||
| additional_sort_by: [row_idx] | ||
|
|
||
| # No local fit here -- adopt the externally-supplied mapping instead. | ||
| - extract_code_metadata | ||
|
|
||
| # APPLY the external mapping to all train/tuning/test event shards. | ||
| - apply_adaptive_code_mapping: | ||
| mapping_filepath: ${external_mapping_fp} | ||
|
|
||
| # RECONCILE codes.parquet with the vocabulary now present in the data. | ||
| - finalize_adaptive_code_metadata: | ||
| mapping_filepath: ${external_mapping_fp} | ||
|
|
||
| # No local fit here either -- adopt the externally-supplied numeric | ||
| # metadata instead. | ||
| - annotate_numeric_values: | ||
| numeric_metadata_filepath: ${external_numeric_metadata_fp} | ||
| # Final model representation: valid lab values become LAB_CODE//BIN. | ||
| - join_numeric_bins | ||
| - finalize_MEDS_metadata | ||
| - finalize_MEDS_data |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| """Column names and mapping I/O shared by the adaptive code-mapping stages.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import polars as pl | ||
| from ehr2meds.io_utils import load_frame | ||
| from meds import DataSchema | ||
|
|
||
| MAPPED_CODE_COLUMN = "adaptive/mapped_code" | ||
| COUNT_COLUMN = "adaptive/count" | ||
| MAPPED_COUNT_COLUMN = "adaptive/mapped_count" | ||
| PROFILE_COLUMN = "adaptive/profile" | ||
| REASON_COLUMN = "adaptive/reason" | ||
| MEMBER_COUNT_COLUMN = "adaptive/member_count" | ||
|
|
||
|
|
||
| def prepare_mapping(local_metadata: pl.DataFrame, external_mapping_filepath: str | None) -> pl.DataFrame: | ||
| """Use the local fitted mapping if one exists; otherwise fall back to an external mapping.""" | ||
| required_local = {DataSchema.code_name, MAPPED_CODE_COLUMN} | ||
| if required_local.issubset(local_metadata.columns): | ||
| return local_metadata.select(DataSchema.code_name, MAPPED_CODE_COLUMN) | ||
|
|
||
| if not external_mapping_filepath: | ||
| missing = sorted(required_local - set(local_metadata.columns)) | ||
| raise ValueError(f"local adaptive metadata is missing columns: {missing}") | ||
| external = load_frame(str(external_mapping_filepath), "external mapping") | ||
| missing = required_local - set(external.columns) | ||
| if missing: | ||
| raise ValueError(f"external mapping is missing columns: {sorted(missing)}") | ||
| external = external.select(DataSchema.code_name, MAPPED_CODE_COLUMN) | ||
| if external.get_column(DataSchema.code_name).n_unique() != external.height: | ||
| raise ValueError("external mapping must contain at most one row per code") | ||
| return external | ||
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| """Shared file-resolution and loading helpers used across ehr2meds stages.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import polars as pl | ||
| from MEDS_transforms.utils import PKG_PFX, resolve_pkg_path | ||
| from pathlib import Path | ||
|
|
||
|
|
||
| def resolve_resource_path(filepath: str) -> Path: | ||
| """Resolve normal and package resource paths.""" | ||
| return resolve_pkg_path(filepath) if filepath.startswith(PKG_PFX) else Path(filepath) | ||
|
|
||
|
|
||
| def load_frame(filepath: str, label: str) -> pl.DataFrame: | ||
| """Load a JSON or Parquet resource.""" | ||
| path = resolve_resource_path(filepath) | ||
| if not path.is_file(): | ||
| raise FileNotFoundError(f"{label} filepath '{filepath}' does not exist") | ||
| match path.suffix.lower(): | ||
| case ".parquet": | ||
| return pl.read_parquet(path) | ||
| case ".json": | ||
| return pl.read_json(path) | ||
| case _: | ||
| raise ValueError(f"{label} filepath must point to a JSON or Parquet file") |
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this should just be a default in the main function calling for this, or be contained in a yaml
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, moved it.