diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index 6f6bc9bb63..84217e1e93 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -225,6 +225,7 @@ Available Tasks ETHOS Timelines (MEDS) ETHOS Zero-Shot Outcomes (MEDS) MIMIC-III ICD-9 Coding + MIMIC-III ICD-9 Category Classification BMD-HS Disease Classification Cardiology Detection COVID-19 CXR Classification diff --git a/docs/api/tasks/pyhealth.tasks.MIMIC3ICD9CategoryClassification.rst b/docs/api/tasks/pyhealth.tasks.MIMIC3ICD9CategoryClassification.rst new file mode 100644 index 0000000000..ed891685c8 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.MIMIC3ICD9CategoryClassification.rst @@ -0,0 +1,9 @@ +pyhealth.tasks.MIMIC3ICD9CategoryClassification +=============================================== + +.. autoclass:: pyhealth.tasks.mimic3_icd9_category_classification.MIMIC3ICD9CategoryClassification + :members: + :undoc-members: + :show-inheritance: + +.. autofunction:: pyhealth.tasks.mimic3_icd9_category_classification.icd9_to_category diff --git a/examples/mimic3_icd9_category_classification_transformers.py b/examples/mimic3_icd9_category_classification_transformers.py new file mode 100644 index 0000000000..c773cec25a --- /dev/null +++ b/examples/mimic3_icd9_category_classification_transformers.py @@ -0,0 +1,352 @@ +# Author(s): Nishanth Manjunath, Esther Hwang, Hekili Jordan +# NetID(s): inseoh2, nm89, hekilij2 +"""Ablation of the MIMIC-III ICD-9 category task with a Transformers encoder. + +The task ``MIMIC3ICD9CategoryClassification`` turns MIMIC-III discharge +summaries into a 19-label multilabel problem (Gao et al., MLHC 2022). This +script trains PyHealth's ``TransformersModel`` on it under several task +configurations and compares them on a held-out set of patients. + +Ablation (not part of the paper, which uses one text setting): + +* **How much of the note is read.** Only the first 64, 128 or 256 words of the + discharge summary are kept. If the diagnoses are mostly stated early in the + note, a short prefix is enough, and the classifier is cheaper to train. +* **Which notes are used.** Discharge summaries only, or discharge summaries + plus physician notes. The notes of an admission are joined in time order and + then cut to the first N words. + +Each configuration is run with each seed. The seed changes the patient split +and the model initialisation, so the table reports the mean and the standard +deviation over seeds. The metrics are micro-averaged, so they stay defined +when a small split lacks some of the 19 categories. + +Usage with MIMIC-III (needs credentialed access):: + + python examples/mimic3_icd9_category_classification_transformers.py \\ + --root /path/to/mimic-iii/1.4 --epochs 5 --seeds 0 1 2 + +Usage without any real data, to check that the pipeline runs. The notes are +synthetic, so the numbers say nothing about the real task:: + + python examples/mimic3_icd9_category_classification_transformers.py \\ + --synthetic --epochs 3 + +The default encoder is ``emilyalsentzer/Bio_ClinicalBERT`` and is downloaded +from Hugging Face on first use. Use a GPU for the full MIMIC-III data. + +The encoder reads at most ``--max-length`` tokens (512 by default), which is +roughly 350 words of clinical text. Word limits above that make no difference, +because the extra words are cut by the encoder, not by the task. + +Results on synthetic notes (``--synthetic --epochs 3 --seeds 0 1 2``, Colab T4 +GPU, ``Bio_ClinicalBERT``, 80 patients and 122 admissions). The notes are +synthetic, so this only shows that the pipeline trains end to end. It says +nothing about the real task:: + + | configuration | pr_auc_micro | roc_auc_micro | f1_micro | + |---|---|---|---| + | discharge_64_words | 0.181 ± 0.020 | 0.755 ± 0.012 | 0.221 ± 0.015 | + | discharge_128_words | 0.222 ± 0.064 | 0.779 ± 0.050 | 0.225 ± 0.038 | + | discharge_256_words | 0.201 ± 0.035 | 0.796 ± 0.047 | 0.276 ± 0.042 | + | discharge_physician_256_words | 0.187 ± 0.037 | 0.780 ± 0.047 | 0.264 ± 0.029 | + +Mean ± standard deviation over 3 seeds. The test split has only about 18 +admissions, and the differences between settings are no larger than the spread +across seeds, so no setting is better than another here. Real MIMIC-III notes +have not been run. +""" + +import argparse +import csv +import gzip +import random +import tempfile +from pathlib import Path +from typing import Any + +import numpy as np +import torch + +from pyhealth.datasets import MIMIC3Dataset, get_dataloader, split_by_patient +from pyhealth.models import TransformersModel +from pyhealth.tasks import MIMIC3ICD9CategoryClassification +from pyhealth.trainer import Trainer + +# Name -> keyword arguments of the task. Each entry is one ablation setting. +ABLATION: dict[str, dict[str, Any]] = { + "discharge_64_words": {"max_words": 64}, + "discharge_128_words": {"max_words": 128}, + "discharge_256_words": {"max_words": 256}, + "discharge_physician_256_words": { + "note_categories": ("Discharge summary", "Physician"), + "max_words": 256, + }, +} +METRICS = ["pr_auc_micro", "roc_auc_micro", "f1_micro"] +MONITOR = "pr_auc_micro" + +# Synthetic data: ICD-9 code and the phrase that signals it in a note. +SYNTHETIC_CONDITIONS = { + "4280": "heart failure", + "486": "pneumonia", + "25000": "diabetes", + "5849": "kidney failure", + "311": "depression", + "1629": "lung cancer", +} +FILLER_WORDS = [ + "patient", + "admitted", + "stable", + "discharged", + "follow", + "plan", + "medication", + "history", + "exam", + "vitals", + "normal", + "labs", + "reviewed", + "family", + "social", + "allergies", + "denies", + "pain", +] + + +def set_seed(seed: int) -> None: + """Seed Python, NumPy and PyTorch. + + Args: + seed: The seed. + """ + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + + +def write_gz_csv(path: Path, header: list[str], rows: list[list[Any]]) -> None: + """Write a gzipped CSV file. + + Args: + path: The output path. + header: The column names. + rows: The rows. + """ + with gzip.open(path, "wt", newline="") as file: + writer = csv.writer(file) + writer.writerow(header) + writer.writerows(rows) + + +def make_note(phrases: list[str], num_words: int, rng: random.Random) -> str: + """Build a synthetic note with the given phrases at random positions. + + Args: + phrases: Phrases to hide in the note, one per diagnosis. + num_words: Number of filler words around the phrases. + rng: Random generator. + + Returns: + The note text. + """ + words = [rng.choice(FILLER_WORDS) for _ in range(num_words)] + for phrase in phrases: + words.insert(rng.randrange(len(words) + 1), phrase) + return " ".join(words) + + +def write_synthetic_mimic3(root: Path, num_patients: int, seed: int) -> None: + """Write a small fake MIMIC-III folder with synthetic discharge summaries. + + Each admission gets one or two of the conditions in + ``SYNTHETIC_CONDITIONS``, and a discharge summary that mentions them at a + random position, so a longer prefix of the note is more likely to contain + the signal. It also gets a physician note that mentions nothing. + + Args: + root: An existing empty folder. + num_patients: Number of patients, with one or two admissions each. + seed: Random seed. + """ + rng = random.Random(seed) + patients, admissions, icustays, diagnoses, notes = [], [], [], [], [] + hadm_id, row_id = 100, 1 + for subject_id in range(1, num_patients + 1): + patients.append([subject_id, "F", "2050-01-01", "", "", "", 0]) + for visit in range(rng.randint(1, 2)): + hadm_id += 1 + day = f"21{visit:02d}-01" + admissions.append( + [subject_id, hadm_id, f"{day}-01 10:00:00", f"{day}-05 10:00:00"] + + [""] * 14 + ) + icustays.append( + [subject_id, hadm_id, hadm_id, "MICU", "metavision", "MICU"] + + [f"{day}-01 11:00:00", f"{day}-02 11:00:00"] + ) + codes = rng.sample(sorted(SYNTHETIC_CONDITIONS), rng.randint(1, 2)) + for seq_num, code in enumerate(codes, start=1): + diagnoses.append([row_id, subject_id, hadm_id, seq_num, code]) + row_id += 1 + phrases = [SYNTHETIC_CONDITIONS[code] for code in codes] + for category, text in ( + ("Physician", make_note([], 150, rng)), + ("Discharge summary", make_note(phrases, 300, rng)), + ): + notes.append( + [row_id, subject_id, hadm_id, f"{day}-05", f"{day}-05 09:00:00"] + + ["", category, "Report", "", "", text] + ) + row_id += 1 + + admission_columns = [ + "subject_id", "hadm_id", "admittime", "dischtime", "admission_type", + "admission_location", "insurance", "language", "religion", + "marital_status", "ethnicity", "edregtime", "edouttime", "deathtime", + "discharge_location", "diagnosis", "hospital_expire_flag", + "has_chartevents_data", + ] # fmt: skip + write_gz_csv( + root / "PATIENTS.csv.gz", + ["subject_id", "gender", "dob", "dod", "dod_hosp", "dod_ssn", "expire_flag"], + patients, + ) + write_gz_csv(root / "ADMISSIONS.csv.gz", admission_columns, admissions) + write_gz_csv( + root / "ICUSTAYS.csv.gz", + ["subject_id", "hadm_id", "icustay_id", "first_careunit", "dbsource", + "last_careunit", "intime", "outtime"], + icustays, + ) # fmt: skip + write_gz_csv( + root / "DIAGNOSES_ICD.csv.gz", + ["row_id", "subject_id", "hadm_id", "seq_num", "icd9_code"], + diagnoses, + ) + write_gz_csv( + root / "NOTEEVENTS.csv.gz", + ["row_id", "subject_id", "hadm_id", "chartdate", "charttime", "storetime", + "category", "description", "cgid", "iserror", "text"], + notes, + ) # fmt: skip + + +def run_once( + dataset: MIMIC3Dataset, + task_kwargs: dict[str, Any], + args: argparse.Namespace, + seed: int, +) -> dict[str, float]: + """Train and test one model for one task configuration and one seed. + + Args: + dataset: The MIMIC-III dataset, with the notes and diagnoses tables. + task_kwargs: Keyword arguments of ``MIMIC3ICD9CategoryClassification``. + args: The command-line arguments. + seed: Seed for the patient split and the model initialisation. + + Returns: + The test-set metrics, keyed by metric name. + """ + set_seed(seed) + task = MIMIC3ICD9CategoryClassification(**task_kwargs) + samples = dataset.set_task(task) + train_set, val_set, test_set = split_by_patient( + samples, [0.7, 0.15, 0.15], seed=seed + ) + loaders = [ + get_dataloader(subset, batch_size=args.batch_size, shuffle=shuffle) + for subset, shuffle in ((train_set, True), (val_set, False), (test_set, False)) + ] + model = TransformersModel( + dataset=samples, model_name=args.model_name, max_length=args.max_length + ) + trainer = Trainer( + model=model, + metrics=METRICS, + device="cuda" if torch.cuda.is_available() else "cpu", + enable_logging=False, + ) + trainer.train( + train_dataloader=loaders[0], + val_dataloader=loaders[1], + epochs=args.epochs, + optimizer_params={"lr": args.lr}, + monitor=MONITOR, + ) + return trainer.evaluate(loaders[2]) + + +def print_table(results: dict[str, list[dict[str, float]]]) -> None: + """Print the mean and standard deviation of each metric per configuration. + + Args: + results: For each configuration name, the test metrics of every seed. + """ + print(f"\n| configuration | {' | '.join(METRICS)} |") + print(f"|---|{'---|' * len(METRICS)}") + for name, runs in results.items(): + cells = [] + for metric in METRICS: + values = np.array([run[metric] for run in runs]) + cells.append(f"{values.mean():.3f} ± {values.std():.3f}") + print(f"| {name} | {' | '.join(cells)} |") + num_seeds = len(next(iter(results.values()))) + print(f"\nMean ± standard deviation over {num_seeds} seed(s).") + + +def parse_args() -> argparse.Namespace: + """Parse the command line. + + Returns: + The parsed arguments. + """ + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--root", help="Path to the MIMIC-III folder.") + parser.add_argument( + "--synthetic", action="store_true", help="Use synthetic notes, no real data." + ) + parser.add_argument("--dev", action="store_true", help="Load a small dev subset.") + parser.add_argument("--model-name", default="emilyalsentzer/Bio_ClinicalBERT") + parser.add_argument("--max-length", type=int, default=512) + parser.add_argument("--epochs", type=int, default=5) + parser.add_argument("--batch-size", type=int, default=16) + parser.add_argument("--lr", type=float, default=2e-5) + parser.add_argument("--seeds", type=int, nargs="+", default=[0]) + parser.add_argument("--num-synthetic-patients", type=int, default=80) + args = parser.parse_args() + if not args.synthetic and not args.root: + parser.error("give --root, or use --synthetic") + return args + + +def main() -> None: + """Run the ablation and print the results table.""" + args = parse_args() + with tempfile.TemporaryDirectory() as scratch: + root = args.root + if args.synthetic: + root = Path(scratch) / "mimic3" + root.mkdir() + write_synthetic_mimic3(root, args.num_synthetic_patients, seed=0) + dataset = MIMIC3Dataset( + root=str(root), + tables=["diagnoses_icd", "noteevents"], + cache_dir=scratch, + dev=args.dev, + ) + results: dict[str, list[dict[str, float]]] = {} + for name, task_kwargs in ABLATION.items(): + print(f"\n=== {name} ===") + results[name] = [ + run_once(dataset, task_kwargs, args, seed) for seed in args.seeds + ] + print_table(results) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index a895ac6f22..3c54e45802 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -119,6 +119,11 @@ ) from .length_of_stay_stagenet_mimic4 import LengthOfStayStageNetMIMIC4 from .medical_coding import MIMIC3ICD9Coding +from .mimic3_icd9_category_classification import ( + ICD9_CATEGORIES as ICD9_CATEGORIES, + MIMIC3ICD9CategoryClassification as MIMIC3ICD9CategoryClassification, + icd9_to_category as icd9_to_category, +) from .medmod_decompensation_mimic4 import ( MedModDecompensationMIMIC4 as MedModDecompensationMIMIC4, ) diff --git a/pyhealth/tasks/mimic3_icd9_category_classification.py b/pyhealth/tasks/mimic3_icd9_category_classification.py new file mode 100644 index 0000000000..42663e2468 --- /dev/null +++ b/pyhealth/tasks/mimic3_icd9_category_classification.py @@ -0,0 +1,294 @@ +# Author(s): Nishanth Manjunath, Esther Hwang, Hekili Jordan +# NetID(s): inseoh2, nm89, hekilij2 +# Paper: Classifying Unstructured Clinical Notes via Automatic Weak +# Supervision (Gao et al., MLHC 2022) +# Paper link: https://proceedings.mlr.press/v182/gao22a.html +# Description: Multilabel classification of MIMIC-III discharge summaries into +# the 19 top-level ICD-9 diagnosis categories used by the paper (which +# follows FasTag, Venkataraman et al., 2020). This is the data side of +# the paper's clinical experiment, which the authors' public repository +# does not include. + +"""MIMIC-III discharge summaries to the 19 top-level ICD-9 categories. + +This module is the data side of the clinical experiment in "Classifying +Unstructured Clinical Notes via Automatic Weak Supervision" (Gao et al., +MLHC 2022). The paper labels MIMIC-III discharge summaries with the 19 +top-level ICD-9 diagnosis categories, following FasTag (Venkataraman et al., +2020), and trains a text classifier without human-labelled notes. The +authors' public code covers only the four non-clinical benchmarks, so this +task supplies the MIMIC-III side in PyHealth. + +For each hospital admission that has a discharge summary and at least one +diagnosis in one of the 19 categories, the task yields one sample:: + + { + "patient_id": "1", + "visit_id": "100", # the admission (hadm_id) + "text": "heart failure and ...", # the discharge summary + "categories": [ # multilabel target, 19 outputs + "Endocrine, nutritional and metabolic", + "Circulatory system", + ], + } + +Contents: + ICD9_CATEGORIES: The 19 category names, in the order of the paper's Table 4. + icd9_to_category: Maps one ICD-9 code to its category. + MIMIC3ICD9CategoryClassification: The task, for ``MIMIC3Dataset``. + +Typical use, with a MIMIC-III folder you have access to:: + + from pyhealth.datasets import MIMIC3Dataset + from pyhealth.tasks import MIMIC3ICD9CategoryClassification + + dataset = MIMIC3Dataset( + root="/path/to/mimic-iii/1.4", + tables=["diagnoses_icd", "noteevents"], + ) + samples = dataset.set_task(MIMIC3ICD9CategoryClassification()) + +Codes in the ICD-9 symptoms range (780-799) belong to none of the 19 +categories and give no label. The category ranges are the standard ICD-9 +chapters, not taken from the paper, which lists only the category names. +""" + +from collections.abc import Sequence +from typing import Any, ClassVar + +from pyhealth.processors import MultiLabelProcessor, TextProcessor + +from ..data import Patient +from .base_task import BaseTask + +# The 19 categories, in the order of the paper's Table 4. Each numeric range is +# an inclusive range of three-digit ICD-9 codes. The last two categories are +# the E (external causes) and V (supplementary) code families. +ICD9_CATEGORY_RANGES = ( + ("Infectious & parasitic", 1, 139), + ("Neoplasms", 140, 239), + ("Endocrine, nutritional and metabolic", 240, 279), + ("Blood & blood-forming organs", 280, 289), + ("Mental disorders", 290, 319), + ("Nervous system", 320, 359), + ("Sense organs", 360, 389), + ("Circulatory system", 390, 459), + ("Respiratory system", 460, 519), + ("Digestive system", 520, 579), + ("Genitourinary system", 580, 629), + ("Pregnancy & childbirth complications", 630, 679), + ("Skin & subcutaneous tissue", 680, 709), + ("Musculoskeletal system & connective tissue", 710, 739), + ("Congenital anomalies", 740, 759), + ("Perinatal period conditions", 760, 779), + ("Injury and poisoning", 800, 999), +) +EXTERNAL_CAUSES = "External causes of injury" +SUPPLEMENTARY = "Supplementary" + +ICD9_CATEGORIES = tuple(name for name, _, _ in ICD9_CATEGORY_RANGES) + ( + EXTERNAL_CAUSES, + SUPPLEMENTARY, +) + + +def icd9_to_category(code: Any) -> str | None: + """Map an ICD-9 code to one of the paper's 19 top-level categories. + + MIMIC-III stores ICD-9 codes without the dot (for example ``"4019"`` for + 401.9). Codes in the symptoms and ill-defined range (780-799) belong to + none of the 19 categories and return ``None``, as do empty or malformed + codes. + + Args: + code: The ICD-9 code, such as ``"4019"``, ``"V1052"`` or ``"E8788"``. + + Returns: + The category name, or ``None`` if the code has no category. + + Examples: + >>> icd9_to_category("4019") + 'Circulatory system' + >>> icd9_to_category("V1052") + 'Supplementary' + >>> icd9_to_category("78650") is None + True + """ + if code is None: + return None + code = str(code).strip().upper() + if not code: + return None + if code[0] == "V": + return SUPPLEMENTARY + if code[0] == "E": + return EXTERNAL_CAUSES + prefix = code[:3] + if not prefix.isdigit(): + return None + value = int(prefix) + for name, low, high in ICD9_CATEGORY_RANGES: + if low <= value <= high: + return name + return None + + +class MIMIC3ICD9CategoryClassification(BaseTask): + """Classify MIMIC-III discharge summaries into top-level ICD-9 categories. + + Works with :class:`~pyhealth.datasets.MIMIC3Dataset` loaded with the + ``diagnoses_icd`` and ``noteevents`` tables. + + Each admission with a matching note and at least one categorised diagnosis + becomes one sample: the note text is the input and the set of the paper's + 19 ICD-9 categories present in the admission is the multilabel target. + + The defaults follow the clinical experiment in the paper: discharge + summaries only, labelled from diagnosis codes. The arguments change which + text is used, for ablations. + + Args: + note_categories: Note ``category`` values to keep (case-insensitive). + Notes from the same admission are joined with a space. + min_words: Skip admissions whose text has fewer words than this. + max_words: Keep only the first ``max_words`` words of the text. ``None`` + keeps all of it. + + Attributes: + task_name: ``"mimic3_icd9_category_classification"``. + input_schema: ``{"text": TextProcessor}``. The input is the note text, + as one string. + output_schema: ``{"categories": MultiLabelProcessor}``. The labels are + fixed to :data:`ICD9_CATEGORIES`, so the target is always a + 19-dimensional multi-hot vector, in the order of the paper's + Table 4. + + Examples: + >>> from pyhealth.datasets import MIMIC3Dataset + >>> from pyhealth.tasks import MIMIC3ICD9CategoryClassification + >>> dataset = MIMIC3Dataset( + ... root="/path/to/mimic-iii/1.4", + ... tables=["diagnoses_icd", "noteevents"], + ... ) # doctest: +SKIP + >>> task = MIMIC3ICD9CategoryClassification(max_words=1000) + >>> samples = dataset.set_task(task) # doctest: +SKIP + """ + + task_name: str = "mimic3_icd9_category_classification" + input_schema: ClassVar[dict[str, Any]] = {"text": TextProcessor} + # Fixing the labels keeps the target 19-dimensional, in the order of the + # paper's Table 4, even on a small subset that lacks some categories. + output_schema: ClassVar[dict[str, Any]] = { + "categories": (MultiLabelProcessor, {"labels": list(ICD9_CATEGORIES)}) + } + + def __init__( + self, + note_categories: Sequence[str] = ("Discharge summary",), + min_words: int = 1, + max_words: int | None = None, + ) -> None: + """Initialize the task configuration. + + Args: + note_categories: Note ``category`` values to keep. + min_words: Minimum number of words a sample's text must have. + max_words: Maximum number of words kept, or ``None`` for no cap. + + Raises: + ValueError: If ``note_categories`` is empty, ``min_words`` is + negative, or ``max_words`` is not positive. + + Examples: + >>> task = MIMIC3ICD9CategoryClassification(min_words=50) + >>> task.min_words + 50 + """ + super().__init__() + if not note_categories: + raise ValueError("note_categories must not be empty.") + if min_words < 0: + raise ValueError("min_words must be non-negative.") + if max_words is not None and max_words <= 0: + raise ValueError("max_words must be positive or None.") + self.note_categories = tuple(c.strip().lower() for c in note_categories) + self.min_words = min_words + self.max_words = max_words + + def __call__(self, patient: Patient) -> list[dict[str, Any]]: + """Build one sample per admission from a patient's events. + + Args: + patient: A patient with ``admissions``, ``diagnoses_icd`` and + ``noteevents`` events. + + Returns: + A list of samples with the keys ``patient_id``, ``visit_id``, + ``text`` and ``categories``. Admissions with no matching note, too + few words, or no categorised code are skipped. + + Examples: + >>> task = MIMIC3ICD9CategoryClassification() + >>> callable(task) + True + """ + samples: list[dict[str, Any]] = [] + for admission in patient.get_events(event_type="admissions"): + hadm_id = admission.hadm_id + text = self._admission_text(patient, hadm_id) + categories = self._admission_categories(patient, hadm_id) + if not text or not categories: + continue + samples.append( + { + "patient_id": patient.patient_id, + "visit_id": hadm_id, + "text": text, + "categories": categories, + } + ) + return samples + + def _admission_text(self, patient: Patient, hadm_id: str) -> str: + """Join the admission's selected notes and apply the word limits. + + Args: + patient: The patient the admission belongs to. + hadm_id: The admission id. + + Returns: + The text, or an empty string if the admission has no selected note + or fewer than ``min_words`` words. + """ + notes = patient.get_events( + event_type="noteevents", filters=[("hadm_id", "==", hadm_id)] + ) + texts = [] + for note in notes: + category = str(getattr(note, "category", "")).strip().lower() + text = getattr(note, "text", None) + if category in self.note_categories and text is not None: + texts.append(str(text).strip()) + words = " ".join(texts).split() + if len(words) < max(self.min_words, 1): + return "" + if self.max_words is not None: + words = words[: self.max_words] + return " ".join(words) + + def _admission_categories(self, patient: Patient, hadm_id: str) -> list[str]: + """Return the admission's ICD-9 categories, in the paper's order. + + Args: + patient: The patient the admission belongs to. + hadm_id: The admission id. + + Returns: + The category names present among the admission's diagnoses, ordered + as in :data:`ICD9_CATEGORIES`. Empty if no code has a category. + """ + diagnoses = patient.get_events( + event_type="diagnoses_icd", filters=[("hadm_id", "==", hadm_id)] + ) + present = {icd9_to_category(event.icd9_code) for event in diagnoses} + return [name for name in ICD9_CATEGORIES if name in present] diff --git a/tests/core/test_mimic3_icd9_category_classification.py b/tests/core/test_mimic3_icd9_category_classification.py new file mode 100644 index 0000000000..d6cc312ee4 --- /dev/null +++ b/tests/core/test_mimic3_icd9_category_classification.py @@ -0,0 +1,258 @@ +"""Tests for the MIMIC-III ICD-9 category task, on hand-built fake patients. + +No MIMIC data is read: patients are plain objects that answer ``get_events`` +the way :class:`pyhealth.data.Patient` does. +""" + +import unittest +from types import SimpleNamespace + +from pyhealth.datasets import create_sample_dataset +from pyhealth.tasks import ( + ICD9_CATEGORIES, + MIMIC3ICD9CategoryClassification, + icd9_to_category, +) + + +class FakePatient: + """Events by type, filtered on attributes like ``Patient.get_events``.""" + + def __init__(self, events, patient_id="p1"): + self.patient_id = patient_id + self.events = events + + def get_events(self, event_type=None, filters=None, **kwargs): + events = list(self.events.get(event_type, [])) + for attr, _, value in filters or []: + events = [e for e in events if getattr(e, attr) == value] + return events + + +def admission(hadm_id): + return SimpleNamespace(hadm_id=hadm_id) + + +def note(hadm_id, text, category="Discharge summary"): + return SimpleNamespace(hadm_id=hadm_id, text=text, category=category) + + +def diagnosis(hadm_id, code): + return SimpleNamespace(hadm_id=hadm_id, icd9_code=code) + + +def make_patient(admissions, notes, diagnoses, patient_id="p1"): + return FakePatient( + { + "admissions": admissions, + "noteevents": notes, + "diagnoses_icd": diagnoses, + }, + patient_id=patient_id, + ) + + +class TestIcd9ToCategory(unittest.TestCase): + def test_there_are_19_categories(self): + self.assertEqual(len(ICD9_CATEGORIES), 19) + self.assertEqual(len(set(ICD9_CATEGORIES)), 19) + + def test_common_codes(self): + self.assertEqual(icd9_to_category("4019"), "Circulatory system") + self.assertEqual(icd9_to_category("25000"), ICD9_CATEGORIES[2]) + self.assertEqual(icd9_to_category("486"), "Respiratory system") + self.assertEqual(icd9_to_category("V1052"), "Supplementary") + self.assertEqual(icd9_to_category("E8788"), "External causes of injury") + + def test_range_boundaries(self): + self.assertEqual(icd9_to_category("001"), "Infectious & parasitic") + self.assertEqual(icd9_to_category("139"), "Infectious & parasitic") + self.assertEqual(icd9_to_category("140"), "Neoplasms") + self.assertEqual(icd9_to_category("359"), "Nervous system") + self.assertEqual(icd9_to_category("360"), "Sense organs") + self.assertEqual(icd9_to_category("800"), "Injury and poisoning") + self.assertEqual(icd9_to_category("999"), "Injury and poisoning") + + def test_symptom_codes_have_no_category(self): + self.assertIsNone(icd9_to_category("780")) + self.assertIsNone(icd9_to_category("78650")) + self.assertIsNone(icd9_to_category("799")) + + def test_bad_input_returns_none(self): + for bad in (None, "", " ", "nan", "ABC", "0"): + self.assertIsNone(icd9_to_category(bad), msg=repr(bad)) + + def test_case_and_whitespace_are_ignored(self): + self.assertEqual(icd9_to_category(" v1052 "), "Supplementary") + self.assertEqual(icd9_to_category(" 4019"), "Circulatory system") + + +class TestTaskSamples(unittest.TestCase): + def test_one_sample_per_admission_with_ordered_labels(self): + patient = make_patient( + [admission("1")], + [note("1", "chest pain and diabetes")], + [diagnosis("1", "V1052"), diagnosis("1", "4019"), diagnosis("1", "25000")], + ) + samples = MIMIC3ICD9CategoryClassification()(patient) + self.assertEqual(len(samples), 1) + sample = samples[0] + self.assertEqual(sample["patient_id"], "p1") + self.assertEqual(sample["visit_id"], "1") + self.assertEqual(sample["text"], "chest pain and diabetes") + # labels follow the paper's category order, whatever the code order + self.assertEqual( + sample["categories"], + [ + "Endocrine, nutritional and metabolic", + "Circulatory system", + "Supplementary", + ], + ) + + def test_repeated_codes_give_one_label(self): + patient = make_patient( + [admission("1")], + [note("1", "text")], + [diagnosis("1", "4019"), diagnosis("1", "4280")], + ) + samples = MIMIC3ICD9CategoryClassification()(patient) + self.assertEqual(samples[0]["categories"], ["Circulatory system"]) + + def test_only_discharge_summaries_by_default(self): + patient = make_patient( + [admission("1")], + [note("1", "nursing text", category="Nursing")], + [diagnosis("1", "4019")], + ) + self.assertEqual(MIMIC3ICD9CategoryClassification()(patient), []) + + def test_note_categories_option_is_case_insensitive(self): + patient = make_patient( + [admission("1")], + [ + note("1", "discharge text"), + note("1", "nursing text", category="Nursing"), + ], + [diagnosis("1", "4019")], + ) + task = MIMIC3ICD9CategoryClassification( + note_categories=("discharge summary", "NURSING") + ) + self.assertEqual(task(patient)[0]["text"], "discharge text nursing text") + + def test_notes_of_the_same_admission_are_joined(self): + patient = make_patient( + [admission("1")], + [note("1", "first part"), note("1", "addendum")], + [diagnosis("1", "4019")], + ) + samples = MIMIC3ICD9CategoryClassification()(patient) + self.assertEqual(samples[0]["text"], "first part addendum") + + def test_each_admission_uses_only_its_own_notes_and_codes(self): + patient = make_patient( + [admission("1"), admission("2")], + [note("1", "heart"), note("2", "lungs")], + [diagnosis("1", "4019"), diagnosis("2", "486")], + ) + samples = MIMIC3ICD9CategoryClassification()(patient) + self.assertEqual(len(samples), 2) + by_visit = {s["visit_id"]: s for s in samples} + self.assertEqual(by_visit["1"]["categories"], ["Circulatory system"]) + self.assertEqual(by_visit["2"]["categories"], ["Respiratory system"]) + self.assertEqual(by_visit["2"]["text"], "lungs") + + def test_admission_without_a_note_is_skipped(self): + patient = make_patient([admission("1")], [], [diagnosis("1", "4019")]) + self.assertEqual(MIMIC3ICD9CategoryClassification()(patient), []) + + def test_admission_without_a_categorised_code_is_skipped(self): + patient = make_patient( + [admission("1")], + [note("1", "text")], + [diagnosis("1", "78650"), diagnosis("1", None)], + ) + self.assertEqual(MIMIC3ICD9CategoryClassification()(patient), []) + + def test_blank_or_missing_note_text_is_skipped(self): + patient = make_patient( + [admission("1")], + [note("1", " "), note("1", None)], + [diagnosis("1", "4019")], + ) + self.assertEqual(MIMIC3ICD9CategoryClassification()(patient), []) + + def test_max_words_keeps_the_start_of_the_text(self): + patient = make_patient( + [admission("1")], + [note("1", "one two three four five")], + [diagnosis("1", "4019")], + ) + samples = MIMIC3ICD9CategoryClassification(max_words=3)(patient) + self.assertEqual(samples[0]["text"], "one two three") + + def test_min_words_skips_short_notes(self): + patient = make_patient( + [admission("1")], + [note("1", "one two")], + [diagnosis("1", "4019")], + ) + self.assertEqual(MIMIC3ICD9CategoryClassification(min_words=3)(patient), []) + self.assertEqual(len(MIMIC3ICD9CategoryClassification(min_words=2)(patient)), 1) + + def test_patient_without_admissions_gives_no_samples(self): + patient = make_patient([], [], []) + self.assertEqual(MIMIC3ICD9CategoryClassification()(patient), []) + + +class TestTaskConfiguration(unittest.TestCase): + def test_invalid_arguments_raise(self): + with self.assertRaises(ValueError): + MIMIC3ICD9CategoryClassification(note_categories=()) + with self.assertRaises(ValueError): + MIMIC3ICD9CategoryClassification(min_words=-1) + with self.assertRaises(ValueError): + MIMIC3ICD9CategoryClassification(max_words=0) + + def test_schemas(self): + task = MIMIC3ICD9CategoryClassification() + self.assertEqual(task.task_name, "mimic3_icd9_category_classification") + self.assertEqual(list(task.input_schema), ["text"]) + self.assertEqual(list(task.output_schema), ["categories"]) + + def test_samples_load_into_a_sample_dataset(self): + patients = [ + make_patient( + [admission("1")], + [note("1", "heart failure")], + [diagnosis("1", "4280")], + patient_id="p1", + ), + make_patient( + [admission("2")], + [note("2", "pneumonia and diabetes")], + [diagnosis("2", "486"), diagnosis("2", "25000")], + patient_id="p2", + ), + ] + task = MIMIC3ICD9CategoryClassification() + samples = [s for p in patients for s in task(p)] + dataset = create_sample_dataset( + samples=samples, + input_schema=task.input_schema, + output_schema=task.output_schema, + dataset_name="test_icd9_categories", + ) + self.assertEqual(len(dataset), 2) + self.assertIn("text", dataset[0]) + # the target is always 19-dimensional, even though these two + # samples only use three of the categories + self.assertEqual(len(dataset[0]["categories"]), 19) + self.assertEqual(len(dataset[1]["categories"]), 19) + self.assertEqual(float(dataset[0]["categories"].sum()), 1.0) + self.assertEqual(float(dataset[1]["categories"].sum()), 2.0) + + +if __name__ == "__main__": + unittest.main()