-
Notifications
You must be signed in to change notification settings - Fork 772
Fix drug recommandation drug code and padding. #1138
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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
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
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,174 @@ | ||
| import csv | ||
| import gzip | ||
| import shutil | ||
| import tempfile | ||
| import unittest | ||
| from pathlib import Path | ||
| from unittest.mock import patch | ||
|
|
||
| import pyhealth.tasks.drug_recommendation as drug_rec | ||
| from pyhealth.datasets import MIMIC3Dataset, MIMIC4Dataset | ||
| from pyhealth.tasks import DrugRecommendationMIMIC3, DrugRecommendationMIMIC4 | ||
|
|
||
|
|
||
| class FakeNDCToATC3Map: | ||
| def __init__(self): | ||
| self.calls = [] | ||
| self.mapping = { | ||
| "11111111111": ["A10B"], | ||
| "22222222222": ["C03C", "C03C"], | ||
| "33333333333": ["N02B"], | ||
| } | ||
|
|
||
| def map(self, ndc, target_kwargs=None): | ||
| self.calls.append((ndc, target_kwargs)) | ||
| return self.mapping.get(ndc, []) | ||
|
|
||
|
|
||
| class TestDrugRecommendationATC3(unittest.TestCase): | ||
| @classmethod | ||
| def setUpClass(cls): | ||
| cls.resources_root = Path(__file__).parents[2] / "test-resources" / "core" | ||
|
|
||
| def setUp(self): | ||
| drug_rec._NDC_TO_ATC3_MAPPER = None | ||
| drug_rec._NDC_TO_ATC3_CACHE.clear() | ||
| self.mapper = FakeNDCToATC3Map() | ||
| patcher = patch( | ||
| "pyhealth.tasks.drug_recommendation.CrossMap.load", | ||
| return_value=self.mapper, | ||
| ) | ||
| self.addCleanup(patcher.stop) | ||
| self.crossmap_load = patcher.start() | ||
| self.temp_dirs = [] | ||
|
|
||
| def tearDown(self): | ||
| drug_rec._NDC_TO_ATC3_MAPPER = None | ||
| drug_rec._NDC_TO_ATC3_CACHE.clear() | ||
| for temp_dir in self.temp_dirs: | ||
| temp_dir.cleanup() | ||
|
|
||
| def _copy_demo(self, demo_name): | ||
| temp_dir = tempfile.TemporaryDirectory() | ||
| self.temp_dirs.append(temp_dir) | ||
| source = self.resources_root / demo_name | ||
| target = Path(temp_dir.name) / demo_name | ||
| shutil.copytree(source, target) | ||
| return target, temp_dir | ||
|
|
||
| def _rewrite_prescription_ndcs(self, path, replacements): | ||
| opener = gzip.open if path.suffix == ".gz" else open | ||
| with opener(path, "rt", newline="") as f: | ||
| reader = csv.DictReader(f) | ||
| rows = list(reader) | ||
| fieldnames = reader.fieldnames | ||
|
|
||
| if fieldnames is None: | ||
| raise ValueError(f"No CSV header found in {path}") | ||
|
|
||
| counts = {hadm_id: 0 for hadm_id in replacements} | ||
| templates = {} | ||
| rewritten_rows = [] | ||
| for row in rows: | ||
| hadm_id = str(row["hadm_id"]) | ||
| if hadm_id in replacements: | ||
| templates.setdefault(hadm_id, row.copy()) | ||
| index = counts[hadm_id] | ||
| ndcs = replacements[hadm_id] | ||
| row["ndc"] = ndcs[index] if index < len(ndcs) else "99999999999" | ||
| counts[hadm_id] += 1 | ||
| rewritten_rows.append(row) | ||
|
|
||
| for hadm_id, ndcs in replacements.items(): | ||
| if hadm_id not in templates: | ||
| raise ValueError(f"No prescription rows found for hadm_id={hadm_id}") | ||
| while counts[hadm_id] < len(ndcs): | ||
| row = templates[hadm_id].copy() | ||
| if "row_id" in row: | ||
| row["row_id"] = str(10_000_000 + len(rewritten_rows)) | ||
| row["ndc"] = ndcs[counts[hadm_id]] | ||
| rewritten_rows.append(row) | ||
| counts[hadm_id] += 1 | ||
|
|
||
| with opener(path, "wt", newline="") as f: | ||
| writer = csv.DictWriter(f, fieldnames=fieldnames) | ||
| writer.writeheader() | ||
| writer.writerows(rewritten_rows) | ||
|
|
||
| def _assert_atc3_samples(self, samples, first_hadm_id, second_hadm_id): | ||
| by_visit = {str(sample["visit_id"]): sample for sample in samples} | ||
| self.assertIn(first_hadm_id, by_visit) | ||
| self.assertIn(second_hadm_id, by_visit) | ||
|
|
||
| first_sample = by_visit[first_hadm_id] | ||
| second_sample = by_visit[second_hadm_id] | ||
| self.assertEqual(first_sample["drugs"], ["A10B", "C03C"]) | ||
| self.assertEqual(second_sample["drugs"], ["N02B"]) | ||
| self.assertNotIn("1111", first_sample["drugs"]) | ||
| self.assertNotIn("2222", first_sample["drugs"]) | ||
| self.assertNotIn("3333", second_sample["drugs"]) | ||
| self.assertNotIn("0", first_sample["drugs"]) | ||
| self.assertNotIn("9999", first_sample["drugs"]) | ||
|
|
||
| def test_mimic3_demo_drug_recommendation_maps_ndc_to_atc3(self): | ||
| demo_path, cache_dir = self._copy_demo("mimic3demo") | ||
| self._rewrite_prescription_ndcs( | ||
| demo_path / "PRESCRIPTIONS.csv.gz", | ||
| { | ||
| "142582": [ | ||
| "11111111111", | ||
| "22222222222", | ||
| "11111111111", | ||
| "0", | ||
| "99999999999", | ||
| ], | ||
| "122098": ["33333333333", "", "<NA>"], | ||
| }, | ||
| ) | ||
| dataset = MIMIC3Dataset( | ||
| root=str(demo_path), | ||
| tables=["diagnoses_icd", "procedures_icd", "prescriptions"], | ||
| cache_dir=cache_dir.name, | ||
| ) | ||
|
|
||
| samples = DrugRecommendationMIMIC3()(dataset.get_patient("10059")) | ||
|
|
||
| self.crossmap_load.assert_called_once_with("NDC", "ATC") | ||
| self._assert_atc3_samples(samples, "142582", "122098") | ||
| self.assertTrue( | ||
| all(kwargs == {"level": 3} for _, kwargs in self.mapper.calls) | ||
| ) | ||
|
|
||
| def test_mimic4_demo_drug_recommendation_maps_ndc_to_atc3(self): | ||
| demo_path, cache_dir = self._copy_demo("mimic4demo") | ||
| self._rewrite_prescription_ndcs( | ||
| demo_path / "hosp" / "prescriptions.csv", | ||
| { | ||
| "20001": [ | ||
| "11111111111", | ||
| "22222222222", | ||
| "11111111111", | ||
| "0", | ||
| "99999999999", | ||
| ], | ||
| "20002": ["33333333333", "", "<NA>"], | ||
| }, | ||
| ) | ||
| dataset = MIMIC4Dataset( | ||
| ehr_root=str(demo_path), | ||
| ehr_tables=["diagnoses_icd", "procedures_icd", "prescriptions"], | ||
| cache_dir=cache_dir.name, | ||
| num_workers=1, | ||
| ) | ||
|
|
||
| samples = DrugRecommendationMIMIC4()(dataset.get_patient("10001")) | ||
|
|
||
| self.crossmap_load.assert_called_once_with("NDC", "ATC") | ||
| self._assert_atc3_samples(samples, "20001", "20002") | ||
| self.assertTrue( | ||
| all(kwargs == {"level": 3} for _, kwargs in self.mapper.calls) | ||
| ) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
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,58 @@ | ||
| import unittest | ||
|
|
||
| import torch | ||
|
|
||
| from pyhealth.datasets import create_sample_dataset | ||
| from pyhealth.models import EmbeddingModel | ||
|
|
||
|
|
||
| class TestEmbeddingModelPadding(unittest.TestCase): | ||
| def setUp(self): | ||
| samples = [ | ||
| { | ||
| "patient_id": "patient-0", | ||
| "visit_id": "visit-0", | ||
| "conditions": [["cond-1", "cond-2"], ["cond-3"]], | ||
| "deep_codes": [[["deep-1"], ["deep-2", "deep-3"]]], | ||
| "label": 1, | ||
| }, | ||
| { | ||
| "patient_id": "patient-1", | ||
| "visit_id": "visit-1", | ||
| "conditions": [["cond-4"]], | ||
| "deep_codes": [[["deep-4"]]], | ||
| "label": 0, | ||
| }, | ||
| ] | ||
| self.dataset = create_sample_dataset( | ||
| samples=samples, | ||
| input_schema={ | ||
| "conditions": "nested_sequence", | ||
| "deep_codes": "deep_nested_sequence", | ||
| }, | ||
| output_schema={"label": "binary"}, | ||
| dataset_name="embedding-padding-test", | ||
| ) | ||
|
|
||
| def test_nested_sequence_embeddings_use_zero_padding(self): | ||
| model = EmbeddingModel(self.dataset, embedding_dim=8) | ||
|
|
||
| for field in ["conditions", "deep_codes"]: | ||
| embedding = model.embedding_layers[field] | ||
| self.assertEqual(embedding.padding_idx, 0) | ||
| self.assertTrue(torch.equal(embedding.weight[0], torch.zeros(8))) | ||
|
|
||
| def test_nested_sequence_padding_row_does_not_receive_gradients(self): | ||
| model = EmbeddingModel(self.dataset, embedding_dim=8) | ||
| embedding = model.embedding_layers["conditions"] | ||
| token_index = self.dataset.input_processors["conditions"].code_vocab["cond-1"] | ||
|
|
||
| output = embedding(torch.tensor([[[0, token_index]]])) | ||
| output.sum().backward() | ||
|
|
||
| self.assertTrue(torch.equal(embedding.weight.grad[0], torch.zeros(8))) | ||
| self.assertGreater(embedding.weight.grad[token_index].abs().sum().item(), 0) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
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 forgot to mention, sequence processor can also handle the code mappings now too. Don't think it matters that much here, but worth sharing.
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.
This is a bit tricky because NestedSequence & MultiLabel does not yet support this. May be better to left this into a future PR.