From b3f334e4b9f0d6a54982b300c86d11e48ee8f4c5 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 15 Nov 2026 00:45:50 -0800 Subject: [PATCH 01/50] Add files via upload --- test_hourly.py | 67 +++++++++++++++++++++++++++++++++ test_tpc_real.py | 57 ++++++++++++++++++++++++++++ tpc_eicu.py | 98 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 222 insertions(+) create mode 100644 test_hourly.py create mode 100644 test_tpc_real.py create mode 100644 tpc_eicu.py diff --git a/test_hourly.py b/test_hourly.py new file mode 100644 index 0000000000..2af434afb8 --- /dev/null +++ b/test_hourly.py @@ -0,0 +1,67 @@ +import pandas as pd + +# Create sample heart rate measurements for an ICU patient +data = pd.DataFrame({ + "hour": [0.17, 0.67, 1.33], + "heart_rate": [80, 90, 100] +}) + +# Assign each measurement to an hourly time bin +data["hour_bin"] = data["hour"].astype(int) + +# Calculate the average heart rate for each hour +hourly = data.groupby("hour_bin")["heart_rate"].mean() + +# Include hours with no recorded measurements +hourly = hourly.reindex(range(5)) + +# Display the hourly heart rate data +print(hourly) + +# Forward-fill missing values using the most recent observation +hourly_filled = hourly.ffill() + +# Display the data after forward filling +print("\nAfter forward fill:") +print(hourly_filled) + +# Track the time elapsed since the most recent measurement +last_observed_hour = None +hours_since_observed = [] + +for hour, value in hourly.items(): + if pd.notna(value): + last_observed_hour = hour + + if last_observed_hour is None: + hours_since_observed.append(float("nan")) + else: + hours_since_observed.append(hour - last_observed_hour) + +# Combine the results into one table +result = pd.DataFrame({ + "heart_rate_original": hourly, + "heart_rate_filled": hourly_filled, + "hours_since_observed": hours_since_observed +}) + +print("\nHourly data with time information:") +print(result) + +# Define the total ICU length of stay in hours +total_los_hours = 30 + +# Generate remaining LOS labels for each prediction hour +prediction_hours = range(5, total_los_hours) + +los_labels = pd.DataFrame({ + "hour": list(prediction_hours), + "remaining_los_hours": [ + total_los_hours - hour + for hour in prediction_hours + ] +}) + +# Display the first ten prediction labels +print("\nRemaining ICU LOS labels:") +print(los_labels.head(10)) \ No newline at end of file diff --git a/test_tpc_real.py b/test_tpc_real.py new file mode 100644 index 0000000000..3c192f10cd --- /dev/null +++ b/test_tpc_real.py @@ -0,0 +1,57 @@ + +from multiprocessing import freeze_support + +from pyhealth.datasets import eICUDataset +from pyhealth.tasks.tpc_eicu import TPCLengthOfStayEICU + + +def main(): + root = "eicu-crd-2.0" + + dataset = eICUDataset( + root=root, + tables=[ + "lab", + "vitalperiodic", + "vitalaperiodic", + "intakeoutput", + "respiratorycharting", + "nursecharting",] + ) + + print("Dataset loaded successfully.") + + for rate in [0.0, 0.1, 0.2]: + print(f"\nTesting missing rate: {rate:.0%}") + + task = TPCLengthOfStayEICU( + missing_rate=rate, + seed=42, + ) + + samples = dataset.set_task( + task=task, + num_workers=1, + ) + + print("Number of samples:", len(samples)) + + if len(samples) > 0: + sample = samples[0] + + print("Dynamic type:", type(sample["dynamic"])) + print("Dynamic structure:", [ + getattr(x, "shape", type(x).__name__) + for x in sample["dynamic"]]) + print("LOS type:", type(sample["los"])) + print("LOS structure:", [ + getattr(x, "shape", type(x).__name__) + for x in sample["los"]]) + + + print("\nIntegration test finished.") + + +if __name__ == "__main__": + freeze_support() + main() diff --git a/tpc_eicu.py b/tpc_eicu.py new file mode 100644 index 0000000000..58cf99795d --- /dev/null +++ b/tpc_eicu.py @@ -0,0 +1,98 @@ + +import hashlib +from typing import Any, ClassVar + +import numpy as np + +from .yaib_eicu import YAIBLengthOfStayEICU + + +class TPCLengthOfStayEICU(YAIBLengthOfStayEICU): + """Hourly ICU length-of-stay prediction with missingness experiments.""" + + task_name: str = "TPCLengthOfStayEICU" + MAX_HOURS: ClassVar[int] = 14 * 24 + START_HOUR: ClassVar[int] = 5 + + def __init__(self, missing_rate: float = 0.0, seed: int = 42): + """Configure random observation masking.""" + if not 0.0 <= missing_rate <= 1.0: + raise ValueError("missing_rate must be between 0 and 1.") + + self.missing_rate = missing_rate + self.seed = seed + + def _apply_missingness(self, values: np.ndarray, stay_id: Any) -> np.ndarray: + """Randomly hide a fraction of originally observed values.""" + values = values.copy() + + if self.missing_rate == 0.0: + return values + + observed = np.argwhere(~np.isnan(values)) + n_hide = round(len(observed) * self.missing_rate) + + if n_hide == 0: + return values + + key = f"{self.seed}:{stay_id}".encode("utf-8") + stay_seed = int.from_bytes( + hashlib.sha256(key).digest()[:8], "little" + ) + rng = np.random.default_rng(stay_seed) + + selected = rng.choice( + len(observed), size=n_hide, replace=False + ) + + rows, cols = observed[selected].T + values[rows, cols] = np.nan + + return values + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + """Generate hourly ICU samples with uncapped remaining LOS labels.""" + all_stays = self._stays(patient) + + if all_stays.height == 0: + return [] + + stays, hourly, static = self._base_cohort(patient, all_stays) + + samples = [] + + for stay_id, los_hours, end in stays.select( + "stay_id", "los_hours", "end" + ).iter_rows(): + if end < self.START_HOUR: + continue + + last_hour = min(end, self.MAX_HOURS) + + + dynamic = self._dynamic(hourly, stay_id, last_hour) + + # Keep all observations from hour 0 onward. + dynamic["values"] = self._apply_missingness(dynamic["values"], stay_id) + + prediction_hours = [ + float(hour) + for hour in range(self.START_HOUR, last_hour + 1) + ] + + remaining = [ + max(0.0, float(los_hours) - hour) + for hour in prediction_hours + ] + + samples.append( + { + "patient_id": patient.patient_id, + "stay_id": stay_id, + "dynamic": dynamic, + "static": self._static_series(static[stay_id]), + "los": self._labels(prediction_hours, remaining), + } + ) + + return samples From b6d2e6a330e7979a88c6159a1829b7d37ad8cb47 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Fri, 20 Nov 2026 00:32:16 -0800 Subject: [PATCH 02/50] Update tpc_eicu.py Add complete docstring --- tpc_eicu.py | 80 +++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 72 insertions(+), 8 deletions(-) diff --git a/tpc_eicu.py b/tpc_eicu.py index 58cf99795d..93bc96f334 100644 --- a/tpc_eicu.py +++ b/tpc_eicu.py @@ -8,14 +8,38 @@ class TPCLengthOfStayEICU(YAIBLengthOfStayEICU): - """Hourly ICU length-of-stay prediction with missingness experiments.""" + """Predict hourly remaining ICU length of stay using eICU data. + + Extends YAIBLengthOfStayEICU to generate hourly remaining + length-of-stay labels and support random observation masking. + + Dynamic observations are retained from hour 0, while predictions + start at hour 5 and continue for up to 14 days. + + Args: + missing_rate (float): Fraction of observed dynamic feature + values to randomly mask. Defaults to 0.0. + seed (int): Random seed for reproducible masking. + Defaults to 42. + """ task_name: str = "TPCLengthOfStayEICU" MAX_HOURS: ClassVar[int] = 14 * 24 START_HOUR: ClassVar[int] = 5 def __init__(self, missing_rate: float = 0.0, seed: int = 42): - """Configure random observation masking.""" + """Initialize the task with missingness settings. + + Args: + missing_rate (float): Fraction of observed dynamic feature + values to randomly mask, between 0.0 and 1.0. + Defaults to 0.0. + seed (int): Random seed used for reproducible masking. + Defaults to 42. + + Raises: + ValueError: If missing_rate is outside [0.0, 1.0]. + """ if not 0.0 <= missing_rate <= 1.0: raise ValueError("missing_rate must be between 0 and 1.") @@ -23,7 +47,21 @@ def __init__(self, missing_rate: float = 0.0, seed: int = 42): self.seed = seed def _apply_missingness(self, values: np.ndarray, stay_id: Any) -> np.ndarray: - """Randomly hide a fraction of originally observed values.""" + """Randomly mask a fraction of observed feature values with NaN. + + Masking is deterministic for each ICU stay based on the + configured seed and stay identifier. Originally missing + values are excluded from the masking selection. + + Args: + values (np.ndarray): Array of hourly dynamic feature values. + stay_id (Any): ICU stay identifier used to derive the + random seed. + + Returns: + np.ndarray: A copy of the input array with selected + observed values replaced by NaN. + """ values = values.copy() if self.missing_rate == 0.0: @@ -51,7 +89,31 @@ def _apply_missingness(self, values: np.ndarray, stay_id: Any) -> np.ndarray: return values def __call__(self, patient: Any) -> list[dict[str, Any]]: - """Generate hourly ICU samples with uncapped remaining LOS labels.""" + """Generate hourly ICU length-of-stay prediction samples. + + Extracts hourly dynamic and static features for eligible ICU + stays. Dynamic observations are retained from hour 0, and + random observation masking is applied when configured. + + Remaining length-of-stay labels are generated for each + prediction hour, starting at hour 5 and continuing up to + the maximum observation horizon. + + Args: + patient (Any): PyHealth patient object containing + ICU stay information and associated measurements. + + Returns: + list[dict[str, Any]]: A list of prediction samples. + Each sample contains: + - patient_id: Patient identifier. + - stay_id: ICU stay identifier. + - dynamic: Hourly dynamic feature observations. + - static: Static patient features. + - los: Hourly remaining length-of-stay labels. + + Returns an empty list if no eligible ICU stays exist. + """ all_stays = self._stays(patient) if all_stays.height == 0: @@ -68,12 +130,13 @@ def __call__(self, patient: Any) -> list[dict[str, Any]]: continue last_hour = min(end, self.MAX_HOURS) - - + dynamic = self._dynamic(hourly, stay_id, last_hour) - + # Keep all observations from hour 0 onward. - dynamic["values"] = self._apply_missingness(dynamic["values"], stay_id) + dynamic["values"] = self._apply_missingness( + dynamic["values"], stay_id + ) prediction_hours = [ float(hour) @@ -96,3 +159,4 @@ def __call__(self, patient: Any) -> list[dict[str, Any]]: ) return samples + From 5ed55a7aaf97e1a189e36b6978563b28a04ab696 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Fri, 20 Nov 2026 00:34:07 -0800 Subject: [PATCH 03/50] Update test_tpc_real.py Add docstring --- test_tpc_real.py | 50 +++++++++++++++++++++++++++++++++--------------- 1 file changed, 35 insertions(+), 15 deletions(-) diff --git a/test_tpc_real.py b/test_tpc_real.py index 3c192f10cd..7475435457 100644 --- a/test_tpc_real.py +++ b/test_tpc_real.py @@ -1,22 +1,33 @@  +"""Integration test for TPC hourly ICU length-of-stay prediction.""" + from multiprocessing import freeze_support from pyhealth.datasets import eICUDataset from pyhealth.tasks.tpc_eicu import TPCLengthOfStayEICU -def main(): +def main() -> None: + """Test TPC task processing on real eICU data. + + Loads the eICU dataset and generates task samples using + missing rates of 0%, 10%, and 20%. + + Prints the number of generated samples and the structure + of dynamic features and LOS labels for each missing rate. + """ root = "eicu-crd-2.0" dataset = eICUDataset( root=root, - tables=[ - "lab", - "vitalperiodic", - "vitalaperiodic", - "intakeoutput", - "respiratorycharting", - "nursecharting",] + tables=[ + "lab", + "vitalperiodic", + "vitalaperiodic", + "intakeoutput", + "respiratorycharting", + "nursecharting", + ], ) print("Dataset loaded successfully.") @@ -40,14 +51,22 @@ def main(): sample = samples[0] print("Dynamic type:", type(sample["dynamic"])) - print("Dynamic structure:", [ - getattr(x, "shape", type(x).__name__) - for x in sample["dynamic"]]) - print("LOS type:", type(sample["los"])) - print("LOS structure:", [ - getattr(x, "shape", type(x).__name__) - for x in sample["los"]]) + print( + "Dynamic structure:", + [ + getattr(x, "shape", type(x).__name__) + for x in sample["dynamic"] + ], + ) + print("LOS type:", type(sample["los"])) + print( + "LOS structure:", + [ + getattr(x, "shape", type(x).__name__) + for x in sample["los"] + ], + ) print("\nIntegration test finished.") @@ -55,3 +74,4 @@ def main(): if __name__ == "__main__": freeze_support() main() + From 9392038702b3652a4ca89a1d903caca9b9be0f34 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Fri, 20 Nov 2026 00:35:09 -0800 Subject: [PATCH 04/50] Update test_hourly.py Add docstring --- test_hourly.py | 126 +++++++++++++++++++++++++++++-------------------- 1 file changed, 76 insertions(+), 50 deletions(-) diff --git a/test_hourly.py b/test_hourly.py index 2af434afb8..af88d25a9d 100644 --- a/test_hourly.py +++ b/test_hourly.py @@ -1,67 +1,93 @@ + +"""Test hourly binning, forward filling, and ICU LOS label generation. + +Uses synthetic heart rate measurements to verify hourly aggregation, +missing-value handling, elapsed time since the last observation, +and hourly remaining length-of-stay labels. +""" + import pandas as pd -# Create sample heart rate measurements for an ICU patient -data = pd.DataFrame({ - "hour": [0.17, 0.67, 1.33], - "heart_rate": [80, 90, 100] -}) -# Assign each measurement to an hourly time bin -data["hour_bin"] = data["hour"].astype(int) +def main() -> None: + """Run synthetic hourly preprocessing and LOS label checks. + + Creates sample heart rate measurements, aggregates them into + hourly bins, and forward-fills missing values. + + Calculates the time elapsed since the most recent observation + and generates remaining ICU length-of-stay labels starting + at hour 5 for a simulated 30-hour ICU stay. + """ + # Create sample heart rate measurements for an ICU patient. + data = pd.DataFrame( + { + "hour": [0.17, 0.67, 1.33], + "heart_rate": [80, 90, 100], + } + ) + + # Assign each measurement to an hourly time bin. + data["hour_bin"] = data["hour"].astype(int) + + # Calculate the average heart rate for each hour. + hourly = data.groupby("hour_bin")["heart_rate"].mean() + + # Include hours with no recorded measurements. + hourly = hourly.reindex(range(5)) -# Calculate the average heart rate for each hour -hourly = data.groupby("hour_bin")["heart_rate"].mean() + # Display the hourly heart rate data. + print(hourly) -# Include hours with no recorded measurements -hourly = hourly.reindex(range(5)) + # Forward-fill missing values using the most recent observation. + hourly_filled = hourly.ffill() -# Display the hourly heart rate data -print(hourly) + print("\nAfter forward fill:") + print(hourly_filled) -# Forward-fill missing values using the most recent observation -hourly_filled = hourly.ffill() + # Track the time elapsed since the most recent measurement. + last_observed_hour = None + hours_since_observed = [] -# Display the data after forward filling -print("\nAfter forward fill:") -print(hourly_filled) + for hour, value in hourly.items(): + if pd.notna(value): + last_observed_hour = hour -# Track the time elapsed since the most recent measurement -last_observed_hour = None -hours_since_observed = [] + if last_observed_hour is None: + hours_since_observed.append(float("nan")) + else: + hours_since_observed.append(hour - last_observed_hour) -for hour, value in hourly.items(): - if pd.notna(value): - last_observed_hour = hour + # Combine the results into one table. + result = pd.DataFrame( + { + "heart_rate_original": hourly, + "heart_rate_filled": hourly_filled, + "hours_since_observed": hours_since_observed, + } + ) - if last_observed_hour is None: - hours_since_observed.append(float("nan")) - else: - hours_since_observed.append(hour - last_observed_hour) + print("\nHourly data with time information:") + print(result) -# Combine the results into one table -result = pd.DataFrame({ - "heart_rate_original": hourly, - "heart_rate_filled": hourly_filled, - "hours_since_observed": hours_since_observed -}) + # Define the total ICU length of stay in hours. + total_los_hours = 30 -print("\nHourly data with time information:") -print(result) + # Generate remaining LOS labels for each prediction hour. + prediction_hours = range(5, total_los_hours) -# Define the total ICU length of stay in hours -total_los_hours = 30 + los_labels = pd.DataFrame( + { + "hour": list(prediction_hours), + "remaining_los_hours": [ + total_los_hours - hour for hour in prediction_hours + ], + } + ) -# Generate remaining LOS labels for each prediction hour -prediction_hours = range(5, total_los_hours) + print("\nRemaining ICU LOS labels:") + print(los_labels.head(10)) -los_labels = pd.DataFrame({ - "hour": list(prediction_hours), - "remaining_los_hours": [ - total_los_hours - hour - for hour in prediction_hours - ] -}) -# Display the first ten prediction labels -print("\nRemaining ICU LOS labels:") -print(los_labels.head(10)) \ No newline at end of file +if __name__ == "__main__": + main() From e83131428126c3d27cb1a5d92e0034eacb2db993 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Fri, 20 Nov 2026 00:40:19 -0800 Subject: [PATCH 05/50] Update tpc_eicu.py Add docstring and apply black --- tpc_eicu.py | 21 +++++---------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/tpc_eicu.py b/tpc_eicu.py index 93bc96f334..f694dc4c55 100644 --- a/tpc_eicu.py +++ b/tpc_eicu.py @@ -1,4 +1,3 @@ - import hashlib from typing import Any, ClassVar @@ -74,14 +73,10 @@ def _apply_missingness(self, values: np.ndarray, stay_id: Any) -> np.ndarray: return values key = f"{self.seed}:{stay_id}".encode("utf-8") - stay_seed = int.from_bytes( - hashlib.sha256(key).digest()[:8], "little" - ) + stay_seed = int.from_bytes(hashlib.sha256(key).digest()[:8], "little") rng = np.random.default_rng(stay_seed) - selected = rng.choice( - len(observed), size=n_hide, replace=False - ) + selected = rng.choice(len(observed), size=n_hide, replace=False) rows, cols = observed[selected].T values[rows, cols] = np.nan @@ -134,19 +129,13 @@ def __call__(self, patient: Any) -> list[dict[str, Any]]: dynamic = self._dynamic(hourly, stay_id, last_hour) # Keep all observations from hour 0 onward. - dynamic["values"] = self._apply_missingness( - dynamic["values"], stay_id - ) + dynamic["values"] = self._apply_missingness(dynamic["values"], stay_id) prediction_hours = [ - float(hour) - for hour in range(self.START_HOUR, last_hour + 1) + float(hour) for hour in range(self.START_HOUR, last_hour + 1) ] - remaining = [ - max(0.0, float(los_hours) - hour) - for hour in prediction_hours - ] + remaining = [max(0.0, float(los_hours) - hour) for hour in prediction_hours] samples.append( { From b121553630120298f90ffd38ce369c2e4b5f208e Mon Sep 17 00:00:00 2001 From: manlingtan Date: Fri, 20 Nov 2026 00:45:50 -0800 Subject: [PATCH 06/50] Update test_tpc_real.py apply black --- test_tpc_real.py | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/test_tpc_real.py b/test_tpc_real.py index 7475435457..d8fe8a495b 100644 --- a/test_tpc_real.py +++ b/test_tpc_real.py @@ -1,5 +1,8 @@ - -"""Integration test for TPC hourly ICU length-of-stay prediction.""" +"""Integration test for TPC hourly ICU length-of-stay prediction. + +Loads real eICU data and inspects generated task samples +under different missing-data rates. +""" from multiprocessing import freeze_support @@ -53,19 +56,13 @@ def main() -> None: print("Dynamic type:", type(sample["dynamic"])) print( "Dynamic structure:", - [ - getattr(x, "shape", type(x).__name__) - for x in sample["dynamic"] - ], + [getattr(x, "shape", type(x).__name__) for x in sample["dynamic"]], ) print("LOS type:", type(sample["los"])) print( "LOS structure:", - [ - getattr(x, "shape", type(x).__name__) - for x in sample["los"] - ], + [getattr(x, "shape", type(x).__name__) for x in sample["los"]], ) print("\nIntegration test finished.") @@ -74,4 +71,3 @@ def main() -> None: if __name__ == "__main__": freeze_support() main() - From 276cc883267fe8918e4ec1aabef4b6bb95401384 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Fri, 20 Nov 2026 00:47:05 -0800 Subject: [PATCH 07/50] Update test_hourly.py apply black --- test_hourly.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/test_hourly.py b/test_hourly.py index af88d25a9d..e33dacfb1f 100644 --- a/test_hourly.py +++ b/test_hourly.py @@ -1,9 +1,8 @@ - """Test hourly binning, forward filling, and ICU LOS label generation. -Uses synthetic heart rate measurements to verify hourly aggregation, -missing-value handling, elapsed time since the last observation, -and hourly remaining length-of-stay labels. +Uses synthetic heart rate measurements to demonstrate hourly +aggregation, missing-value handling, time since last observation, +and remaining ICU length-of-stay label generation. """ import pandas as pd @@ -15,9 +14,9 @@ def main() -> None: Creates sample heart rate measurements, aggregates them into hourly bins, and forward-fills missing values. - Calculates the time elapsed since the most recent observation - and generates remaining ICU length-of-stay labels starting - at hour 5 for a simulated 30-hour ICU stay. + Calculates the elapsed time since the most recent observation + and generates remaining ICU LOS labels starting at hour 5 + for a simulated 30-hour ICU stay. """ # Create sample heart rate measurements for an ICU patient. data = pd.DataFrame( @@ -91,3 +90,4 @@ def main() -> None: if __name__ == "__main__": main() + From 319267e3cfe304d01c264de9fd63844b0e45d807 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 13:28:37 -0800 Subject: [PATCH 08/50] Update tpc_eicu.py Added header for paper title, authors, URL, and team mates name --- tpc_eicu.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tpc_eicu.py b/tpc_eicu.py index f694dc4c55..3c7de5ae48 100644 --- a/tpc_eicu.py +++ b/tpc_eicu.py @@ -1,3 +1,19 @@ +""" +Author: Manling Tan, Yining Jin, Xiao Luo +NetID: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) + +Paper URL: +https://arxiv.org/abs/2007.09483 +""" + + import hashlib from typing import Any, ClassVar From 93c7e862e1d4356dc858eae7ef64bd4f41a4c596 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 13:29:20 -0800 Subject: [PATCH 09/50] Update test_tpc_real.py Added team mates name, paper title, author and URL --- test_tpc_real.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/test_tpc_real.py b/test_tpc_real.py index d8fe8a495b..ee0d422e29 100644 --- a/test_tpc_real.py +++ b/test_tpc_real.py @@ -1,3 +1,19 @@ +""" +Author: Manling Tan, Yining Jin, Xiao Luo +NetID: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) + +Paper URL: +https://arxiv.org/abs/2007.09483 +""" + + """Integration test for TPC hourly ICU length-of-stay prediction. Loads real eICU data and inspects generated task samples From 61d78c4fccdc4dbf601d890b00d45a0d84c5a817 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 13:31:41 -0800 Subject: [PATCH 10/50] Update test_hourly.py Added paper title, author, URL and team mates name --- test_hourly.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/test_hourly.py b/test_hourly.py index e33dacfb1f..7db6488045 100644 --- a/test_hourly.py +++ b/test_hourly.py @@ -1,3 +1,19 @@ +""" +Author: Manling Tan, Yining Jin, Xiao Luo +NetID: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) + +Paper URL: +https://arxiv.org/abs/2007.09483 +""" + + """Test hourly binning, forward filling, and ICU LOS label generation. Uses synthetic heart rate measurements to demonstrate hourly From 2fb2b61a718f04ed94176b2baf048ce423c5b3f0 Mon Sep 17 00:00:00 2001 From: xiaoluo0916 Date: Tue, 17 Nov 2026 07:43:30 -0800 Subject: [PATCH 11/50] Add Person C hourly LOS task fixtures and LSTM checkpoint --- docs/api/tasks.rst | 1 + docs/api/tasks/pyhealth.tasks.tpc_eicu.rst | 45 ++++ project/person_c/EXPECTED_RESULTS.md | 51 +++++ project/person_c/INTERFACE.md | 46 ++++ project/person_c/README.md | 75 +++++++ project/person_c/checkpoint.py | 146 +++++++++++++ project/person_c/checkpoint_result.json | 28 +++ project/person_c/generate_synthetic.py | 144 +++++++++++++ project/person_c/synthetic_eicu/lab.csv | 26 +++ .../person_c/synthetic_eicu/nurseCharting.csv | 6 + project/person_c/synthetic_eicu/patient.csv | 6 + .../synthetic_eicu/respiratoryCharting.csv | 6 + .../synthetic_eicu/vitalAperiodic.csv | 6 + .../person_c/synthetic_eicu/vitalPeriodic.csv | 31 +++ project/person_c/validation.txt | 23 ++ pyhealth/tasks/__init__.py | 2 + pyhealth/tasks/tpc_eicu.py | 165 +++++++++++++++ tests/core/test_tpc_eicu.py | 200 ++++++++++++++++++ tests/core/tpc_fixtures.py | 96 +++++++++ tests/integration/test_tpc_checkpoint.py | 9 + 20 files changed, 1112 insertions(+) create mode 100644 docs/api/tasks/pyhealth.tasks.tpc_eicu.rst create mode 100644 project/person_c/EXPECTED_RESULTS.md create mode 100644 project/person_c/INTERFACE.md create mode 100644 project/person_c/README.md create mode 100644 project/person_c/checkpoint.py create mode 100644 project/person_c/checkpoint_result.json create mode 100644 project/person_c/generate_synthetic.py create mode 100644 project/person_c/synthetic_eicu/lab.csv create mode 100644 project/person_c/synthetic_eicu/nurseCharting.csv create mode 100644 project/person_c/synthetic_eicu/patient.csv create mode 100644 project/person_c/synthetic_eicu/respiratoryCharting.csv create mode 100644 project/person_c/synthetic_eicu/vitalAperiodic.csv create mode 100644 project/person_c/synthetic_eicu/vitalPeriodic.csv create mode 100644 project/person_c/validation.txt create mode 100644 pyhealth/tasks/tpc_eicu.py create mode 100644 tests/core/test_tpc_eicu.py create mode 100644 tests/core/tpc_fixtures.py create mode 100644 tests/integration/test_tpc_checkpoint.py diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index 64b79d0122..dbe61d4bf8 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -319,3 +319,4 @@ Available Tasks Value Set Pair Classification (VSAC) Time-to-event survival (GBSG and SUPPORT) TCGA RNA-seq Survival Prediction + Hourly remaining ICU LOS diff --git a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst new file mode 100644 index 0000000000..1e910f931c --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst @@ -0,0 +1,45 @@ +Hourly remaining ICU length of stay +================================== + +.. automodule:: pyhealth.tasks.tpc_eicu + :members: + :show-inheritance: + +Use ``TPCLengthOfStayEICU(missing_rate=0.1, seed=42)`` with ``eICUDataset``. +Load lab, vitalperiodic, vitalaperiodic, intakeoutput, respiratorycharting, +and nursecharting. Use ``set_task(task, split=...)`` to fit processors on +training patients only. Use RNN_V2 for sequence_v2 and hourly regression. + +The cohort includes known adults (age >= 18) with ICU stay >= 5 hours. +The privacy-preserving age value ``> 89`` is encoded as 90. Missing age is +excluded. Unknown sex and invalid admission height/weight remain missing. + +The label at hour h is total ICU stay in hours minus h. Prediction times +are 5 through min(floor(total stay hours), 336), inclusive. This explicitly +includes a zero label at exact discharge. The observation horizon is capped; +remaining LOS is not. Convert predictions and targets to days for comparison +with the paper. Never silently mix hourly and daily metrics. + +This task reuses YAIB's 48 dynamic and 4 static features. It is a partial +reproduction of the task in https://arxiv.org/abs/2007.09483, not the full TPC +architecture or exact original feature set. Observation removal occurs after +hourly aggregation, before processor imputation. Forward filling and training +normalization are inherited; optional paper-formula decay is described below. + +Run ``pytest tests/core/test_tpc_eicu.py`` for fast synthetic regression tests; +run ``pytest tests/integration/test_tpc_checkpoint.py`` for CSV-to-LSTM coverage. + +Optional decay input +-------------------- + +Set ``include_decay=True`` to add a separate ``decay`` sequence with 48 values +per hour. It is zero before any observation, one when observed, and +``1 / (gap_hours * 4/3)`` afterwards, following the authors' decay formula. +It is calculated after observation removal and is not standardized. Add the +``decay`` field to the RNN_V2 embedding configuration. The default remains +False for compatibility with the team prototype. + +The runnable synthetic checkpoint is +``python -m project.person_c.checkpoint``. It exercises CSV loading, task +processing, train-only processor fitting, an LSTM update, and held-out +inference. This is an integration check, not a clinical performance study. diff --git a/project/person_c/EXPECTED_RESULTS.md b/project/person_c/EXPECTED_RESULTS.md new file mode 100644 index 0000000000..c3be4f1461 --- /dev/null +++ b/project/person_c/EXPECTED_RESULTS.md @@ -0,0 +1,51 @@ +# Independent synthetic-data oracle + +These numbers were calculated from the invented source records, not emitted +by the task. The CSV generator populates every required measurement table. +Five unique patients cover three eligible stays, a short stay, and a minor. + +| Stay | Age | LOS (hours) | Expected inclusion | Labels | +|---|---|---|---|---| +| 101 | 18 | 12.5 | Yes: ordinary adult | hours 5–12; 7.5, 6.5, …, 0.5 | +| 102 | 60 | 4 | No: shorter than five hours | none | +| 103 | > 89 | 400.5 | Yes: long stay | hours 5–336; final value 64.5 | +| 104 | 17 | 12 | No: minor | none | +| 105 | 45 | 8 | Yes: missing admission height | hours 5–8; 3, 2, 1, 0 | + +## Stay 101 selected raw hourly values + +| Table / feature | Records | Expected result | +|---|---|---| +| vitalPeriodic / HR | minute 10: 80; minute 40: 100 | hour 0 median = 90 | +| vitalPeriodic / HR | minute 120: 110; minute 359: 120 | hours 2 and 5 = 110 and 120 | +| vitalPeriodic / HR | minute -60: 250; minute 900: 200 | excluded from this stay's grid | +| lab / potassium | minute 60: 4; minute 90: 6 | hour 1 median = 5 | +| lab / potassium | minute 240: 3; minute 300: 99 | hour 4 = 3; hour 5 missing (invalid 99) | +| lab / creatinine | minute 150: 1.2 | hour 2 = 1.2 | +| vitalAperiodic / systolic BP | minute 180: 130 | hour 3 = 130 | +| intakeOutput / urine | minute 65: 100; minute 95: 50 | hour 1 sum = 150 | +| respiratoryCharting / FiO2 | minute 180: 40% | hour 3 = 40 | +| nurseCharting / temperature | minute 240: 98.6 F | hour 4 = 37 C | + +Static vector for 101: `[18, 0, 165, 65]`. For 103: `[90, 1, 165, 65]`. +For 105, height remains NaN until the training-fitted processor imputes it. + +## First six hours, before normalization + +- HR raw: `[90, NaN, 110, NaN, NaN, 120]`. +- HR forward-filled: `[90, 90, 110, 110, 110, 120]`. +- HR decay: `[1, .75, 1, .75, .375, 1]`. +- Potassium raw: `[NaN, 5, NaN, NaN, 3, NaN]`. +- Potassium decay: `[0, 1, .75, .375, 1, .75]`. + +Decay uses the authors' formula: zero before first measurement; one on a +measurement; `1 / (gap_hours * 4/3)` after it. Removing all measurements gives +all-zero decay. Imputation is applied AFTER removal. Initial missing feature +values use training statistics, or zero if never observed in training. + +Source for decay only: +https://github.com/EmmaRocheteau/TPC-LoS-prediction/blob/master/eICU_preprocessing/timeseries.py + +Additional tiny unit fixtures cover exactly five hours, unknown age/sex, +invalid height/weight, no measurements, two stays of the same patient, +future-observation invariance and zero/10%/20%/100% removal. diff --git a/project/person_c/INTERFACE.md b/project/person_c/INTERFACE.md new file mode 100644 index 0000000000..690e7a7b40 --- /dev/null +++ b/project/person_c/INTERFACE.md @@ -0,0 +1,46 @@ +# Tested interface for A and B + +Status: locally implemented and integration-tested against origin/master +`e81a5574cb160798c9040de7b6fa32637913ef74`. This is a concrete proposed contract, +not evidence that teammates have approved it. No newer remote commits were +present when fetched for this revision. + +```python +from pyhealth.tasks import TPCLengthOfStayEICU +# Existing A code remains compatible: +task = TPCLengthOfStayEICU(missing_rate=0.1, seed=42) +# Enable tested decay for the full input: +task = TPCLengthOfStayEICU(missing_rate=0.1, seed=42, include_decay=True) +``` + +One sample per ICU stay: patient_id (unique person), stay_id, dynamic, static, +los, and optional decay. Dynamic is {time: 0..H, values: (H+1,48)}; static is +{time:[0], values:(1,4)}; los is {time:5..H, values:(H-4,1)}; decay mirrors +dynamic's time and dimensions. H=min(floor(total LOS hours),336). + +- Use RNN_V2 with `rnn_type="LSTM"` explicitly; its default is GRU. +- Add `decay: [{"values": 8}]` to embedding_dim when include_decay=True. +- Raw targets are HOURS. Convert predictions and targets together to days + before paper comparisons. Zero labels at exact discharge are preserved. + The smoke test uses the model's default regression objective; it is not an + MSLE experiment. A must explicitly select a zero-safe metric/loss convention. +- Preserve existing median/floor hourly binning and YAIB features. The paper + uses different mean/right-edge binning; this is a documented partial task + reproduction, not exact original preprocessing. +- Remove observed hourly cells before fitting/imputation. The proposal's raw + observation deletion differs; don't describe these as identical experiments. +- Fit all learned processors on training patients only and reuse for held-out + patients. Split by patient_id, never stay_id. The checkpoint uses patient 101 + for training and 103/105 as held out; it is too small for performance claims. +- Static fields are admission values, not discharge values. Missing age is + excluded; >89 maps to 90. Feature ordering comes from DYNAMIC_FEATURES and + STATIC_FEATURES rather than a separately maintained list. +- Decay is computed locally per stay, after masking. Default False preserves + A's prototype. B can retain this implementation or replace it only if the + expected-value tests still pass or the contract is explicitly revised. + +Integration command (from repository root): +`python -m project.person_c.checkpoint --output project/person_c/checkpoint_result.json` +This generates temporary CSVs, reads actual eICUDataset patients, applies the +actual task and processors, runs a true LSTM optimizer step and evaluates the +held-out batch. All temporary data/cache files are cleaned up. diff --git a/project/person_c/README.md b/project/person_c/README.md new file mode 100644 index 0000000000..af13902d54 --- /dev/null +++ b/project/person_c/README.md @@ -0,0 +1,75 @@ +# Person C checkpoint handoff — November 18 + +## Run locally + +From this checkout, activate the installed environment with +`source ../.venv/bin/activate`. On another machine install the repository and +pytest in a Python 3.12 or 3.13 environment. + +```sh +# Generate all seven populated synthetic CSVs (five invented patients). +python project/person_c/generate_synthetic.py project/person_c/synthetic_eicu +# Fast in-memory task checks; imports still add startup overhead. +python -m pytest tests/core/test_tpc_eicu.py -v --durations=5 +# Real CSV loader + preprocessing + LSTM optimizer step. +python -m pytest tests/integration/test_tpc_checkpoint.py -v +# Independently runnable checkpoint, with machine-readable evidence. +python -m project.person_c.checkpoint --output project/person_c/checkpoint_result.json +``` + +## Delivered + +- Five-patient fixtures populate lab, periodic/aperiodic vitals, intake/output, + respiratory and nursing tables; patient CSV defines admission/static fields. +- Adult/five-hour filtering, four static features and hourly remaining-LOS + labels; observations stop at hour 336 without capping remaining LOS. +- Optional decay input recomputed after masking, with the authors' formula. +- Independent numerical oracle: `EXPECTED_RESULTS.md`. +- Proposed team contract and reproduction differences: `INTERFACE.md`. +- Tests cover filtering, empty/missing records, static features, labels, + aggregation/conversions, removal, filling, decay, stay isolation and causality. +- CSV-to-LSTM integration uses actual PyHealth classes. Processors fit only on + training patients; held-out patients reuse them. Tests require finite loss, + correct prediction counts, finite nonzero gradients and parameter changes. +- RST API documentation and task index/public import updated. +- Background/implementation slides and 5:40 video outline prepared in this chat. + +Evidence: `validation.txt` (test results), `checkpoint_result.json` (training +check). Synthetic losses are only diagnostic; they are NOT clinical results. +No real patient data is used. Temporary integration data and caches are removed. + +## Timing + +Fast task assertions are measured separately from the CSV integration test. +The latter intentionally exercises PyHealth's Dask server, file conversion, +processors and model. Full command runtime includes imports and cannot be +represented as sub-second. See recorded timings rather than an estimated claim. + +## Team integration + +Work was based on origin/master e81a557. No newer remote commits were available +at the fetch. Existing calls remain compatible; enable `include_decay=True` +when adding the decay input to A's model. This runs a real LSTM using the public +PyHealth API; A's final training/ablation script is not present in the checkout, +so compatibility with that unseen script cannot be claimed. + +Review INTERFACE.md with A/B: units, discharge-zero policy, floor/median bins, +masking hourly cells rather than raw rows, and the feature list are explicit. +The checkpoint provides a tested integration path, not teammate approval. + +## Remaining scheduled work + +Person C: review the merged A/B code against this contract, update slides with +A's real experiment results, add contributor identities to the final PR draft, +help submit the team PR by November 24, and record the 4–7-minute video by +November 28. Current work follows Option 3 from the work distribution, rather +than the earlier proposal's full TPC model. No upstream PR is submitted here. +Course deadline: November 29, 2026 at 11:59 PM (rubric timezone unspecified). + +Video outline: motivation 0:00–0:20; TPC 0:20–1:10; paper results 1:10–1:45; +our scope 1:45–2:30; implementation/tests 2:30–3:30; A's results 3:30–5:00; +limitations/conclusions 5:00–5:40. + +AI assistance: code, tests and slide draft were produced with Codex. Review +and understand the changes and accurately disclose assistance in the required +course form. Reference: https://arxiv.org/abs/2007.09483. diff --git a/project/person_c/checkpoint.py b/project/person_c/checkpoint.py new file mode 100644 index 0000000000..11328478df --- /dev/null +++ b/project/person_c/checkpoint.py @@ -0,0 +1,146 @@ +"""Synthetic CSV-to-LSTM checkpoint; no clinical performance claims.""" + +from pathlib import Path +import json +import tempfile +import numpy as np +import torch +from pyhealth.datasets import eICUDataset, create_sample_dataset, get_dataloader +from pyhealth.models import RNN_V2 +from pyhealth.tasks import TPCLengthOfStayEICU +from project.person_c.generate_synthetic import generate, TABLES + + +def run(root: Path) -> dict: + """Generate data, check numerical expectations, and train one LSTM step.""" + torch.manual_seed(42) + torch.set_num_threads(1) + generate(root / "csv") + source = eICUDataset( + root=str(root / "csv"), tables=TABLES, cache_dir=root / "cache" + ) + task = TPCLengthOfStayEICU(include_decay=True) + samples = {} + for sid in (101, 102, 103, 104, 105): + out = task(source.get_patient(f"synthetic-{sid}")) + if sid in (102, 104): + assert out == [], f"Excluded stay {sid} survived" + else: + assert len(out) == 1 + samples[sid] = out[0] + short = samples[101] + names = task.DYNAMIC_FEATURES + + def value(hour, name): + return short["dynamic"]["values"][hour, names.index(name)] + + # Hand-calculated oracle: not computed by the task under test. + for hour, name, expected in [ + (0, "hr", 90), + (2, "hr", 110), + (5, "hr", 120), + (1, "k", 5), + (4, "k", 3), + (2, "crea", 1.2), + (3, "sbp", 130), + (1, "urine", 150), + (3, "fio2", 40), + (4, "temp", 37), + ]: + np.testing.assert_allclose(value(hour, name), expected) + assert np.isnan(value(1, "hr")) + assert np.isnan(value(5, "k")) # implausible 99 mmol/L discarded + assert short["static"]["values"] == [[18.0, 0.0, 165.0, 65.0]] + assert short["los"]["time"] == list(range(5, 13)) + np.testing.assert_allclose( + short["los"]["values"], [[7.5], [6.5], [5.5], [4.5], [3.5], [2.5], [1.5], [0.5]] + ) + np.testing.assert_allclose( + short["decay"]["values"][:6, names.index("hr")], [1, 0.75, 1, 0.75, 0.375, 1] + ) + np.testing.assert_allclose( + short["decay"]["values"][:6, names.index("k")], [0, 1, 0.75, 0.375, 1, 0.75] + ) + assert samples[103]["los"]["time"][-1] == 336 + assert samples[103]["los"]["values"][-1] == [64.5] + assert samples[103]["dynamic"]["values"][0, names.index("hr")] == 100 + assert np.isnan(samples[105]["static"]["values"][0][2]) + # Split BEFORE fitting: the high-valued long stay is held out. + train = create_sample_dataset([samples[101]], task.input_schema, task.output_schema) + heldout = create_sample_dataset( + [samples[103], samples[105]], + task.input_schema, + task.output_schema, + input_processors=train.input_processors, + output_processors=train.output_processors, + ) + train_before = train[0]["dynamic"][0].clone() + assert torch.isfinite(heldout[0]["dynamic"][0]).all() + torch.testing.assert_close(train_before, train[0]["dynamic"][0]) + # Same training processors must be reused, not refitted on held-out patients. + assert heldout.input_processors["dynamic"] is train.input_processors["dynamic"] + model = RNN_V2( + train, + embedding_dim={ + "dynamic": [{"values": 8}], + "static": [{"values": 4}], + "decay": [{"values": 8}], + }, + hidden_dim=8, + rnn_type="LSTM", + mask="concat", + ) + assert any(isinstance(m, torch.nn.LSTM) for m in model.modules()) + batch = next(iter(get_dataloader(train, batch_size=1, shuffle=False))) + optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) + before = [p.detach().clone() for p in model.parameters()] + out = model(**batch) + assert out["logit"].shape[0] == 8 + assert torch.isfinite(out["loss"]) + optimizer.zero_grad() + out["loss"].backward() + gradients = [p.grad for p in model.parameters() if p.grad is not None] + assert gradients and all(torch.isfinite(g).all() for g in gradients) + assert any(torch.count_nonzero(g) for g in gradients) + optimizer.step() + assert any(not torch.equal(a, b) for a, b in zip(before, model.parameters())) + model.eval() + with torch.no_grad(): + evaluation = model( + **next(iter(get_dataloader(heldout, batch_size=2, shuffle=False))) + ) + assert torch.isfinite(evaluation["loss"]) + assert evaluation["logit"].shape[0] == 332 + 4 + return { + "status": "passed", + "synthetic_patients": 5, + "included_stays": [101, 103, 105], + "excluded_stays": [102, 104], + "train_patient": 101, + "heldout_patients": [103, 105], + "training_labels": 8, + "heldout_labels": 336, + "model": "RNN_V2 / LSTM", + "decay_enabled": True, + "optimizer_steps": 1, + "finite_nonzero_gradients": True, + "parameters_changed": True, + "training_loss": float(out["loss"].detach()), + "heldout_loss": float(evaluation["loss"]), + "interpretation": "Synthetic integration check only; not model performance evidence.", + } + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix="person-c-checkpoint-") as tmp: + report = run(Path(tmp)) + text = json.dumps(report, indent=2) + print(text) + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(text + "\n") diff --git a/project/person_c/checkpoint_result.json b/project/person_c/checkpoint_result.json new file mode 100644 index 0000000000..43c8b13594 --- /dev/null +++ b/project/person_c/checkpoint_result.json @@ -0,0 +1,28 @@ +{ + "status": "passed", + "synthetic_patients": 5, + "included_stays": [ + 101, + 103, + 105 + ], + "excluded_stays": [ + 102, + 104 + ], + "train_patient": 101, + "heldout_patients": [ + 103, + 105 + ], + "training_labels": 8, + "heldout_labels": 336, + "model": "RNN_V2 / LSTM", + "decay_enabled": true, + "optimizer_steps": 1, + "finite_nonzero_gradients": true, + "parameters_changed": true, + "training_loss": 0.1641741394996643, + "heldout_loss": 1232.439697265625, + "interpretation": "Synthetic integration check only; not model performance evidence." +} diff --git a/project/person_c/generate_synthetic.py b/project/person_c/generate_synthetic.py new file mode 100644 index 0000000000..0fb590ec15 --- /dev/null +++ b/project/person_c/generate_synthetic.py @@ -0,0 +1,144 @@ +"""Write five invented patients in the shipped eICU CSV schema.""" + +import csv +from pathlib import Path +import yaml + +TABLES = [ + "lab", + "vitalperiodic", + "vitalaperiodic", + "intakeoutput", + "respiratorycharting", + "nursecharting", +] + + +def generate(root: Path) -> None: + """Create schema-complete CSVs; all values are invented.""" + root.mkdir(parents=True, exist_ok=True) + config = yaml.safe_load( + (Path(__file__).parents[2] / "pyhealth/datasets/configs/eicu.yaml").read_text() + ) + rows = {table: [] for table in ["patient", *TABLES]} + for sid, age, hours in [ + (101, "18", 12.5), + (102, "60", 4), + (103, "> 89", 400.5), + (104, "17", 12), + (105, "45", 8), + ]: + rows["patient"].append( + dict( + patientunitstayid=sid, + uniquepid=f"synthetic-{sid}", + patienthealthsystemstayid=sid, + unitvisitnumber=1, + hospitalid=1, + age=age, + gender="Male" if sid == 103 else "Female", + admissionheight="" if sid == 105 else 165, + admissionweight=65, + unitdischargeoffset=int(hours * 60), + unitdischargestatus="Alive", + hospitaladmitoffset=0, + hospitaldischargeoffset=int(hours * 60), + hospitaldischargeyear=2020, + hospitaldischargestatus="Alive", + ) + ) + # Identical timing, contrasting values: detect cross-patient leakage. + shift = 10 if sid == 103 else 0 + for minute, hr in [ + (-60, 250), + (10, 80 + shift), + (40, 100 + shift), + (120, 110 + shift), + (359, 120 + shift), + (900, 200), + ]: + rows["vitalperiodic"].append( + dict( + patientunitstayid=sid, + observationoffset=minute, + heartrate=hr, + sao2=98, + respiration=16, + systemicsystolic=120, + systemicdiastolic=70, + systemicmean=85, + temperature=37, + ) + ) + for minute, value in [(60, 4), (90, 6), (240, 3), (300, 99)]: + rows["lab"].append( + dict( + patientunitstayid=sid, + labresultoffset=minute, + labname="potassium", + labresult=value, + labmeasurenameinterface="mmol/L", + ) + ) + rows["lab"].append( + dict( + patientunitstayid=sid, + labresultoffset=150, + labname="creatinine", + labresult=1.2, + labmeasurenameinterface="mg/dL", + ) + ) + rows["vitalaperiodic"].append( + dict( + patientunitstayid=sid, + observationoffset=180, + noninvasivesystolic=130, + noninvasivediastolic=75, + noninvasivemean=90, + ) + ) + for minute, amount in [(65, 100), (95, 50)]: + rows["intakeoutput"].append( + dict( + patientunitstayid=sid, + intakeoutputoffset=minute, + celllabel="Urine", + cellvaluenumeric=amount, + ) + ) + rows["respiratorycharting"].append( + dict( + patientunitstayid=sid, + respchartoffset=180, + respchartvaluelabel="FiO2", + respchartvalue="40%", + ) + ) + rows["nursecharting"].append( + dict( + patientunitstayid=sid, + nursingchartoffset=240, + nursingchartcelltypevalname="Temperature (F)", + nursingchartvalue="98.6", + ) + ) + for table, values in rows.items(): + cfg = config["tables"][table] + fields = list( + dict.fromkeys( + [*cfg["attributes"], *(["uniquepid"] if table == "patient" else [])] + ) + ) + with (root / cfg["file_path"]).open("w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=fields) + writer.writeheader() + writer.writerows(values) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path) + generate(parser.parse_args().output) diff --git a/project/person_c/synthetic_eicu/lab.csv b/project/person_c/synthetic_eicu/lab.csv new file mode 100644 index 0000000000..cf061d5df8 --- /dev/null +++ b/project/person_c/synthetic_eicu/lab.csv @@ -0,0 +1,26 @@ +patientunitstayid,labresultoffset,labname,labresult,labresulttext,labmeasurenamesystem,labmeasurenameinterface,labtypeid +101,60,potassium,4,,,mmol/L, +101,90,potassium,6,,,mmol/L, +101,240,potassium,3,,,mmol/L, +101,300,potassium,99,,,mmol/L, +101,150,creatinine,1.2,,,mg/dL, +102,60,potassium,4,,,mmol/L, +102,90,potassium,6,,,mmol/L, +102,240,potassium,3,,,mmol/L, +102,300,potassium,99,,,mmol/L, +102,150,creatinine,1.2,,,mg/dL, +103,60,potassium,4,,,mmol/L, +103,90,potassium,6,,,mmol/L, +103,240,potassium,3,,,mmol/L, +103,300,potassium,99,,,mmol/L, +103,150,creatinine,1.2,,,mg/dL, +104,60,potassium,4,,,mmol/L, +104,90,potassium,6,,,mmol/L, +104,240,potassium,3,,,mmol/L, +104,300,potassium,99,,,mmol/L, +104,150,creatinine,1.2,,,mg/dL, +105,60,potassium,4,,,mmol/L, +105,90,potassium,6,,,mmol/L, +105,240,potassium,3,,,mmol/L, +105,300,potassium,99,,,mmol/L, +105,150,creatinine,1.2,,,mg/dL, diff --git a/project/person_c/synthetic_eicu/nurseCharting.csv b/project/person_c/synthetic_eicu/nurseCharting.csv new file mode 100644 index 0000000000..528236171d --- /dev/null +++ b/project/person_c/synthetic_eicu/nurseCharting.csv @@ -0,0 +1,6 @@ +patientunitstayid,nursingchartoffset,nursingchartcelltypevalname,nursingchartvalue +101,240,Temperature (F),98.6 +102,240,Temperature (F),98.6 +103,240,Temperature (F),98.6 +104,240,Temperature (F),98.6 +105,240,Temperature (F),98.6 diff --git a/project/person_c/synthetic_eicu/patient.csv b/project/person_c/synthetic_eicu/patient.csv new file mode 100644 index 0000000000..150c443681 --- /dev/null +++ b/project/person_c/synthetic_eicu/patient.csv @@ -0,0 +1,6 @@ +patientunitstayid,patienthealthsystemstayid,gender,age,ethnicity,hospitalid,wardid,apacheadmissiondx,admissionheight,admissionweight,dischargeweight,hospitaladmittime24,hospitaladmitoffset,hospitaladmitsource,hospitaldischargeyear,hospitaldischargeoffset,hospitaldischargestatus,hospitaldischargetime24,unittype,unitadmittime24,unitadmitsource,unitvisitnumber,unitstaytype,unitdischargeoffset,unitdischargestatus,unitdischargetime24,unitdischargelocation,uniquepid +101,101,Female,18,,1,,,165,65,,,0,,2020,750,Alive,,,,,1,,750,Alive,,,synthetic-101 +102,102,Female,60,,1,,,165,65,,,0,,2020,240,Alive,,,,,1,,240,Alive,,,synthetic-102 +103,103,Male,> 89,,1,,,165,65,,,0,,2020,24030,Alive,,,,,1,,24030,Alive,,,synthetic-103 +104,104,Female,17,,1,,,165,65,,,0,,2020,720,Alive,,,,,1,,720,Alive,,,synthetic-104 +105,105,Female,45,,1,,,,65,,,0,,2020,480,Alive,,,,,1,,480,Alive,,,synthetic-105 diff --git a/project/person_c/synthetic_eicu/respiratoryCharting.csv b/project/person_c/synthetic_eicu/respiratoryCharting.csv new file mode 100644 index 0000000000..03de0509a2 --- /dev/null +++ b/project/person_c/synthetic_eicu/respiratoryCharting.csv @@ -0,0 +1,6 @@ +patientunitstayid,respchartoffset,respcharttypecat,respchartvaluelabel,respchartvalue +101,180,,FiO2,40% +102,180,,FiO2,40% +103,180,,FiO2,40% +104,180,,FiO2,40% +105,180,,FiO2,40% diff --git a/project/person_c/synthetic_eicu/vitalAperiodic.csv b/project/person_c/synthetic_eicu/vitalAperiodic.csv new file mode 100644 index 0000000000..ed2465378d --- /dev/null +++ b/project/person_c/synthetic_eicu/vitalAperiodic.csv @@ -0,0 +1,6 @@ +patientunitstayid,observationoffset,noninvasivesystolic,noninvasivediastolic,noninvasivemean +101,180,130,75,90 +102,180,130,75,90 +103,180,130,75,90 +104,180,130,75,90 +105,180,130,75,90 diff --git a/project/person_c/synthetic_eicu/vitalPeriodic.csv b/project/person_c/synthetic_eicu/vitalPeriodic.csv new file mode 100644 index 0000000000..60c895309a --- /dev/null +++ b/project/person_c/synthetic_eicu/vitalPeriodic.csv @@ -0,0 +1,31 @@ +patientunitstayid,observationoffset,temperature,sao2,heartrate,respiration,systemicsystolic,systemicdiastolic,systemicmean +101,-60,37,98,250,16,120,70,85 +101,10,37,98,80,16,120,70,85 +101,40,37,98,100,16,120,70,85 +101,120,37,98,110,16,120,70,85 +101,359,37,98,120,16,120,70,85 +101,900,37,98,200,16,120,70,85 +102,-60,37,98,250,16,120,70,85 +102,10,37,98,80,16,120,70,85 +102,40,37,98,100,16,120,70,85 +102,120,37,98,110,16,120,70,85 +102,359,37,98,120,16,120,70,85 +102,900,37,98,200,16,120,70,85 +103,-60,37,98,250,16,120,70,85 +103,10,37,98,90,16,120,70,85 +103,40,37,98,110,16,120,70,85 +103,120,37,98,120,16,120,70,85 +103,359,37,98,130,16,120,70,85 +103,900,37,98,200,16,120,70,85 +104,-60,37,98,250,16,120,70,85 +104,10,37,98,80,16,120,70,85 +104,40,37,98,100,16,120,70,85 +104,120,37,98,110,16,120,70,85 +104,359,37,98,120,16,120,70,85 +104,900,37,98,200,16,120,70,85 +105,-60,37,98,250,16,120,70,85 +105,10,37,98,80,16,120,70,85 +105,40,37,98,100,16,120,70,85 +105,120,37,98,110,16,120,70,85 +105,359,37,98,120,16,120,70,85 +105,900,37,98,200,16,120,70,85 diff --git a/project/person_c/validation.txt b/project/person_c/validation.txt new file mode 100644 index 0000000000..383c9765c7 --- /dev/null +++ b/project/person_c/validation.txt @@ -0,0 +1,23 @@ +........................... [100%] +=============================== warnings summary =============================== +tests/integration/test_tpc_checkpoint.py::test_csv_to_lstm + /Users/luoxiao/.codex/.chatgpt-projects/g-p-6ac07c55e33881918976b24c72891f67/PyHealth/pyhealth/datasets/sample_dataset.py:208: FutureWarning: SequenceProcessorV2 and the 'sequence_v2' processor name are deprecated and will be removed in a future release; use JaggedFeatureProcessor and 'jagged', which behave identically. + return get_processor(spec)(**kwargs) + +-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html +============================= slowest 30 durations ============================= +4.47s call tests/integration/test_tpc_checkpoint.py::test_csv_to_lstm +0.05s call tests/core/test_tpc_eicu.py::test_cohort[4.99-60-False] +0.02s call tests/core/test_tpc_eicu.py::test_static_features +0.01s call tests/core/test_tpc_eicu.py::test_future_observations_do_not_change_earlier_hours +0.01s call tests/core/test_tpc_eicu.py::test_hourly_measurements_and_missing_data +0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0.2] +0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0] +0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[1] +0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0.1] +0.01s call tests/core/test_tpc_eicu.py::test_stays_are_isolated +0.01s call tests/core/test_tpc_eicu.py::test_labels_and_horizon +0.01s call tests/core/test_tpc_eicu.py::test_cohort[5-18-True] + +(18 durations < 0.005s hidden. Use -vv to show these durations.) +27 passed, 1 warning in 11.78s diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index 73e542a7ed..672689f57b 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -324,3 +324,5 @@ def __getattr__(name: str): return PTBXLSuperclassClassification raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + +from .tpc_eicu import TPCLengthOfStayEICU as TPCLengthOfStayEICU diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py new file mode 100644 index 0000000000..85156abe5d --- /dev/null +++ b/pyhealth/tasks/tpc_eicu.py @@ -0,0 +1,165 @@ +from copy import deepcopy +import hashlib +from typing import Any, ClassVar + +import numpy as np +import polars as pl + +from .yaib_eicu import YAIBLengthOfStayEICU, _DYNAMIC_FEATURES + + +class TPCLengthOfStayEICU(YAIBLengthOfStayEICU): + """Hourly remaining ICU stay prediction inspired by Rocheteau et al. + + Paper: https://arxiv.org/abs/2007.09483. + This is a standalone task, not a TPC model implementation. Static features + are age, sex (male=1, female=0), admission height and weight, inherited + from YAIB. Unknown sex and invalid height/weight remain NaN. + Labels are HOURS, from hour 5 through min(floor(LOS), 336), inclusive. + Remaining LOS is not clipped to 14 days. Dynamic values remain raw with + NaNs; sequence_v2 processors fit normalization on training patients and + forward-fill after observation masking. Optional decay is a separate input. + + Args: + missing_rate: Fraction of observed hourly cells hidden, in [0, 1]. + seed: Seed combined with each stay ID for repeatable masking. + include_decay: Add a separate 48-channel decay series. Defaults to + False for compatibility with the team prototype. + """ + + task_name: str = "TPCLengthOfStayEICU" + MAX_HOURS: ClassVar[int] = 14 * 24 + START_HOUR: ClassVar[int] = 5 + + def __init__( + self, missing_rate: float = 0.0, seed: int = 42, include_decay: bool = False + ) -> None: + """Configure random observation masking.""" + if not 0.0 <= missing_rate <= 1.0: + raise ValueError("missing_rate must be between 0 and 1.") + + self.missing_rate = missing_rate + self.seed = seed + self.input_schema = deepcopy(type(self).input_schema) + self.include_decay = include_decay + if include_decay: + self.input_schema["decay"] = ( + "sequence_v2", + { + "levels": [ + {"ordering": "series", "values": [len(self.DYNAMIC_FEATURES)]} + ] + }, + ) + + def _base_cohort( + self, patient: Any, stays: pl.DataFrame + ) -> tuple[pl.DataFrame, pl.DataFrame, dict[int, list[float]]]: + """Keep known adults with at least five hours; allow sparse records. + + YAIB's six-hour and measurement-density exclusions do not implement + this project's cohort. Missing age is excluded conservatively. + """ + static = self._static(patient, stays) + keep = [ + stay_id + for stay_id, hours in stays.select("stay_id", "los_hours").iter_rows() + if np.isfinite(hours) + and hours >= self.START_HOUR + and np.isfinite(static[stay_id][0]) + and static[stay_id][0] >= 18 + ] + stays = stays.filter(pl.col("stay_id").is_in(keep)) + hourly = self._hourly(self._measurements(patient, stays, _DYNAMIC_FEATURES)) + return stays, hourly, {key: static[key] for key in keep} + + @staticmethod + def _decay(values: np.ndarray) -> np.ndarray: + """Compute causal observation recency after masking. + + Reimplements the original TPC preprocessing formula: 0 before the + first observation, 1 when observed, 1 / (gap * 4/3) afterwards. + Source: EmmaRocheteau/TPC-LoS-prediction/eICU_preprocessing/timeseries.py. + No forward-looking information or cross-stay state is used. + """ + result = np.zeros_like(values, dtype=float) + last = np.full(values.shape[1], -1, dtype=int) + for hour, row in enumerate(values): + observed = np.isfinite(row) + last[observed] = hour + seen = last >= 0 + gap = hour - last[seen] + result[hour, seen] = 1.0 / np.maximum(1.0, gap * (4.0 / 3.0)) + return result + + def _apply_missingness(self, values: np.ndarray, stay_id: Any) -> np.ndarray: + """Randomly hide a fraction of originally observed values.""" + values = values.copy() + + if self.missing_rate == 0.0: + return values + + observed = np.argwhere(~np.isnan(values)) + n_hide = round(len(observed) * self.missing_rate) + + if n_hide == 0: + return values + + key = f"{self.seed}:{stay_id}".encode("utf-8") + stay_seed = int.from_bytes(hashlib.sha256(key).digest()[:8], "little") + rng = np.random.default_rng(stay_seed) + + selected = rng.choice(len(observed), size=n_hide, replace=False) + + rows, cols = observed[selected].T + values[rows, cols] = np.nan + + return values + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + """Generate hourly ICU samples with uncapped remaining LOS labels.""" + all_stays = self._stays(patient) + + if all_stays.height == 0: + return [] + + stays, hourly, static = self._base_cohort(patient, all_stays) + + samples = [] + + for stay_id, los_hours, end in stays.select( + "stay_id", "los_hours", "end" + ).iter_rows(): + if end < self.START_HOUR: + continue + + last_hour = min(end, self.MAX_HOURS) + + dynamic = self._dynamic(hourly, stay_id, last_hour) + + # Keep all observations from hour 0 onward. + dynamic["values"] = self._apply_missingness(dynamic["values"], stay_id) + + prediction_hours = [ + float(hour) for hour in range(self.START_HOUR, last_hour + 1) + ] + + remaining = [max(0.0, float(los_hours) - hour) for hour in prediction_hours] + + samples.append( + { + "patient_id": patient.patient_id, + "stay_id": stay_id, + "dynamic": dynamic, + "static": self._static_series(static[stay_id]), + "los": self._labels(prediction_hours, remaining), + } + ) + + if self.include_decay: + samples[-1]["decay"] = { + "time": list(dynamic["time"]), + "values": self._decay(dynamic["values"]), + } + + return samples diff --git a/tests/core/test_tpc_eicu.py b/tests/core/test_tpc_eicu.py new file mode 100644 index 0000000000..083fe9740a --- /dev/null +++ b/tests/core/test_tpc_eicu.py @@ -0,0 +1,200 @@ +"""Person C: synthetic cohort and hourly-label regression tests. + +Reference: https://arxiv.org/abs/2007.09483. No clinical records used. +""" + +import numpy as np +import pytest + +from pyhealth.tasks import TPCLengthOfStayEICU +from tests.core.tpc_fixtures import _patient, _labels, _lab + + +@pytest.mark.parametrize( + "hours,age,eligible", + [ + (4.99, "60", False), + (5, "18", True), + (5.5, "60", True), + (12, "17", False), + (12, None, False), + (12, "> 89", True), + (12, "invalid", False), + (-1, "60", False), + ], +) +def test_cohort(hours, age, eligible): + samples = TPCLengthOfStayEICU()(_patient(hours=hours, age=age, hr_hours=[])) + assert bool(samples) == eligible + + +def test_static_features(): + sample = TPCLengthOfStayEICU()(_patient(hours=5, age="> 89", gender="Female"))[0] + assert sample["static"]["values"] == [[90, 0, 180, 80]] + missing = TPCLengthOfStayEICU()( + _patient(hours=5, gender="Unknown", height=-1, weight=999) + )[0] + assert np.isnan(missing["static"]["values"][0][1:]).all() + + +def test_labels_and_horizon(): + task = TPCLengthOfStayEICU() + sample = task(_patient(hours=400.5, hr_hours=[0, 1]))[0] + assert sample["los"]["time"] == list(range(5, 337)) + assert _labels(sample["los"])[0] == 395.5 + assert _labels(sample["los"])[-1] == 64.5 + assert sample["dynamic"]["values"].shape == (337, 48) + assert _labels(task(_patient(hours=5, hr_hours=[]))[0]["los"]) == [0] + + +def test_fractional_remaining_hours(): + sample = TPCLengthOfStayEICU()(_patient(hours=6.5, hr_hours=[]))[0] + assert sample["los"]["time"] == [5, 6] + assert _labels(sample["los"]) == [1.5, 0.5] + + +def test_missingness_count_repeatability_no_mutation(): + values = np.arange(20, dtype=float).reshape(5, 4) + values[0, 0] = np.nan + original = values.copy() + for rate in [0, 0.1, 0.2, 1]: + task = TPCLengthOfStayEICU(rate) + result = task._apply_missingness(values, 10) + assert np.isnan(result).sum() == 1 + round(19 * rate) + np.testing.assert_equal(result, task._apply_missingness(values, 10)) + np.testing.assert_equal(values, original) + np.testing.assert_equal( + TPCLengthOfStayEICU()._apply_missingness(values, 10), values + ) + + +@pytest.mark.parametrize("rate", [-0.1, 1.1, float("nan")]) +def test_invalid_rate(rate): + with pytest.raises(ValueError): + TPCLengthOfStayEICU(rate) + + +def test_hourly_measurements_and_missing_data(): + task = TPCLengthOfStayEICU() + p = _patient( + hours=6, hr_hours=[], extra=[_lab(60, "potassium", 4), _lab(90, "potassium", 6)] + ) + sample = task(p)[0] + k = task.DYNAMIC_FEATURES.index("k") + assert sample["dynamic"]["values"][1, k] == 5 + assert np.isnan(sample["dynamic"]["values"][0, k]) + assert np.isnan(sample["dynamic"]["values"][2, k]) + masked = TPCLengthOfStayEICU(1)(p)[0] + assert np.isnan(masked["dynamic"]["values"]).all() + assert masked["los"] == sample["los"] + assert masked["static"] == sample["static"] + + +def test_forward_fill_after_removal(): + from pyhealth.processors import JaggedFeatureProcessor + + values = { + "time": [0.0, 1.0, 2.0, 3.0], + "values": [[80.0], [np.nan], [100.0], [np.nan]], + } + proc = JaggedFeatureProcessor( + levels=[ + { + "ordering": "series", + "values": [1], + "impute": [{"method": "forward_fill"}, {"method": "zero"}], + } + ] + ) + proc.fit([{"x": values}], "x") + result = proc.process(values) + np.testing.assert_allclose(result[0].reshape(-1).numpy(), [80, 80, 100, 100]) + removed = {"time": values["time"], "values": [[80.0], [np.nan], [np.nan], [np.nan]]} + np.testing.assert_allclose(proc.process(removed)[0].reshape(-1).numpy(), [80] * 4) + + +def test_decay_oracle_and_full_removal(): + raw = np.array( + [[np.nan, 80], [4, np.nan], [np.nan, 100], [np.nan, np.nan], [3, np.nan]], + dtype=float, + ) + expected = [[0, 1], [1, 0.75], [0.75, 1], [0.375, 0.75], [1, 0.375]] + np.testing.assert_allclose(TPCLengthOfStayEICU._decay(raw), expected) + removed = TPCLengthOfStayEICU(1)._apply_missingness(raw, 10) + assert not TPCLengthOfStayEICU._decay(removed).any() + + +def test_decay_optional_schema_does_not_mutate_other_instances(): + assert "decay" in TPCLengthOfStayEICU(include_decay=True).input_schema + assert "decay" not in TPCLengthOfStayEICU().input_schema + + +def test_future_observations_do_not_change_earlier_hours(): + task = TPCLengthOfStayEICU(include_decay=True) + first = task(_patient(hours=12, hr_hours=[0, 2]))[0] + future = task(_patient(hours=12, hr_hours=[0, 2, 10]))[0] + for field in ["dynamic", "decay"]: + np.testing.assert_equal( + first[field]["values"][:10], future[field]["values"][:10] + ) + + +def test_stays_are_isolated(): + from pyhealth.data import Patient + from tests.core.tpc_fixtures import _frame, _stay_rows + + task = TPCLengthOfStayEICU(include_decay=True) + rows = _stay_rows(10, 8, hr_hours=[0]) + _stay_rows(11, 8, hr_hours=[]) + samples = { + s["stay_id"]: s + for s in task(Patient(patient_id="same-patient", data_source=_frame(rows))) + } + assert samples[10]["decay"]["values"].any() + assert not samples[11]["decay"]["values"].any() + assert np.isnan(samples[11]["dynamic"]["values"]).all() + + +def test_empty_patient(): + from pyhealth.data import Patient + from tests.core.tpc_fixtures import _frame, _event + + # Patient with no patient-table admission record. + patient = Patient(patient_id="empty", data_source=_frame([_event("lab")])) + assert TPCLengthOfStayEICU()(patient) == [] + + +@pytest.mark.parametrize("rate", [0, 0.1, 0.2, 1]) +def test_combined_mask_fill_and_decay(rate): + from pyhealth.processors import JaggedFeatureProcessor + + patient = _patient(hours=8, hr_hours=[0, 2, 4, 6]) + task = TPCLengthOfStayEICU(missing_rate=rate, include_decay=True) + sample = task(patient)[0] + original = TPCLengthOfStayEICU()(patient)[0]["dynamic"]["values"] + raw = sample["dynamic"]["values"] + assert np.isfinite(original).sum() - np.isfinite(raw).sum() == round(4 * rate) + np.testing.assert_equal(raw, task(patient)[0]["dynamic"]["values"]) + proc = JaggedFeatureProcessor( + levels=[ + { + "ordering": "series", + "values": [48], + "impute": [{"method": "forward_fill"}, {"method": "zero"}], + } + ] + ) + proc.fit([{"x": sample["dynamic"]}], "x") + filled = proc.process(sample["dynamic"])[0].numpy() + hr = task.DYNAMIC_FEATURES.index("hr") + # A retained value must carry forward until the next retained observation; + # no measurements before the first retained observation may be invented. + retained = np.flatnonzero(np.isfinite(raw[:, hr])) + if len(retained): + assert not filled[: retained[0], hr].any() + assert not sample["decay"]["values"][: retained[0], hr].any() + for start, end in zip(retained, [*retained[1:], len(raw)]): + np.testing.assert_allclose(filled[start:end, hr], raw[start, hr]) + assert sample["decay"]["values"][start, hr] == 1 + else: + assert not filled.any() + assert not sample["decay"]["values"].any() diff --git a/tests/core/tpc_fixtures.py b/tests/core/tpc_fixtures.py new file mode 100644 index 0000000000..c9b02bd6f8 --- /dev/null +++ b/tests/core/tpc_fixtures.py @@ -0,0 +1,96 @@ +"""Small synthetic eICU records; adapted from YAIB regression fixtures.""" + +from pathlib import Path +import polars as pl +import yaml +from pyhealth.data import Patient + +# Every column of the eICU config, as in the dataset's event dataframe. +_CONFIG = yaml.safe_load( + ( + Path(__file__).parents[2] / "pyhealth" / "datasets" / "configs" / "eicu.yaml" + ).read_text() +) +COLUMNS = [ + f"{table}/{column}" + for table, config in _CONFIG["tables"].items() + for column in config["attributes"] +] + + +def _labels(records): + """The label values of a ``timeseries_*`` label series.""" + return [value[0] for value in records["values"]] + + +def _event(event_type, **attrs): + # Attributes are strings in the dataset's event dataframe. + row = {"event_type": event_type, "timestamp": None} + for key, value in attrs.items(): + row[f"{event_type}/{key}"] = None if value is None else str(value) + return row + + +def _frame(rows, patient_id="p1"): + df = pl.from_dicts(rows, infer_schema_length=None) + return df.with_columns( + pl.lit(patient_id).alias("patient_id"), + pl.col("timestamp").cast(pl.Datetime("ms")), + *( + (pl.col(c) if c in df.columns else pl.lit(None)).cast(pl.String).alias(c) + for c in COLUMNS + ), + ) + + +def _stay_rows( + stay_id, + hours, + age="60", + gender="Male", + height=180, + weight=80, + status="Alive", + hospital_id=1, + hr_hours=None, +): + """A stay and one heart rate per hour, so it passes the base cohort.""" + rows = [ + _event( + "patient", + patientunitstayid=stay_id, + unitdischargeoffset=int(hours * 60), + gender=gender, + age=age, + admissionheight=height, + admissionweight=weight, + unitdischargestatus=status, + hospitalid=hospital_id, + ) + ] + for hour in range(int(hours)) if hr_hours is None else hr_hours: + rows.append( + _event( + "vitalperiodic", + patientunitstayid=stay_id, + observationoffset=hour * 60 + 5, + heartrate=80 + hour, + ) + ) + return rows + + +def _patient(stay_id=10, hours: float = 48, extra=(), patient_id="p1", **stay): + rows = _stay_rows(stay_id, hours, **stay) + list(extra) + return Patient(patient_id=patient_id, data_source=_frame(rows, patient_id)) + + +def _lab(minute, name, value, unit="mg/dL", stay_id=10): + return _event( + "lab", + patientunitstayid=stay_id, + labresultoffset=minute, + labname=name, + labresult=value, + labmeasurenameinterface=unit, + ) diff --git a/tests/integration/test_tpc_checkpoint.py b/tests/integration/test_tpc_checkpoint.py new file mode 100644 index 0000000000..bb71ba67b6 --- /dev/null +++ b/tests/integration/test_tpc_checkpoint.py @@ -0,0 +1,9 @@ +"""Actual CSV loader, processors, and LSTM integration on invented patients.""" + +from project.person_c.checkpoint import run + + +def test_csv_to_lstm(tmp_path): + result = run(tmp_path) + assert result["status"] == "passed" + assert result["parameters_changed"] From 5a483a002997f9b00ef3f5a0d0efd21aaca1b885 Mon Sep 17 00:00:00 2001 From: xiaoluo0916 Date: Tue, 17 Nov 2026 07:43:42 -0800 Subject: [PATCH 12/50] Include synthetic intake-output fixture despite output ignore rule --- project/person_c/synthetic_eicu/intakeOutput.csv | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 project/person_c/synthetic_eicu/intakeOutput.csv diff --git a/project/person_c/synthetic_eicu/intakeOutput.csv b/project/person_c/synthetic_eicu/intakeOutput.csv new file mode 100644 index 0000000000..c9f6b41c50 --- /dev/null +++ b/project/person_c/synthetic_eicu/intakeOutput.csv @@ -0,0 +1,11 @@ +patientunitstayid,intakeoutputoffset,celllabel,cellvaluenumeric +101,65,Urine,100 +101,95,Urine,50 +102,65,Urine,100 +102,95,Urine,50 +103,65,Urine,100 +103,95,Urine,50 +104,65,Urine,100 +104,95,Urine,50 +105,65,Urine,100 +105,95,Urine,50 From 0fea0517d75c00b942ef1222b585cac9da135b0b Mon Sep 17 00:00:00 2001 From: xiaoluo0916 Date: Tue, 17 Nov 2026 18:09:06 -0800 Subject: [PATCH 13/50] Audit rubric readiness and fix hourly prediction look-ahead --- docs/api/tasks/pyhealth.tasks.tpc_eicu.rst | 17 +++ examples/eicu_hourly_los_lstm.py | 131 ++++++++++++++++++++ project/person_c/AI_USAGE.md | 37 ++++++ project/person_c/EXPECTED_RESULTS.md | 8 ++ project/person_c/INTERFACE.md | 10 +- project/person_c/PR_DRAFT.md | 53 ++++++++ project/person_c/README.md | 16 ++- project/person_c/RUBRIC_AUDIT.md | 91 ++++++++++++++ project/person_c/SYNTHETIC_RESULTS.md | 28 +++++ project/person_c/VIDEO_SCRIPT.md | 66 ++++++++++ project/person_c/checkpoint.py | 3 + project/person_c/checkpoint_result.json | 4 +- project/person_c/default_validation.txt | 8 ++ project/person_c/generate_synthetic.py | 3 + project/person_c/integration_validation.txt | 12 ++ project/person_c/synthetic_ablation.json | 68 ++++++++++ project/person_c/validation.txt | 23 ++-- pyhealth/tasks/tpc_eicu.py | 51 +++++++- tests/core/test_tpc_eicu.py | 22 +++- tests/core/tpc_fixtures.py | 3 + tests/integration/test_tpc_checkpoint.py | 14 ++- 21 files changed, 648 insertions(+), 20 deletions(-) create mode 100644 examples/eicu_hourly_los_lstm.py create mode 100644 project/person_c/AI_USAGE.md create mode 100644 project/person_c/PR_DRAFT.md create mode 100644 project/person_c/RUBRIC_AUDIT.md create mode 100644 project/person_c/SYNTHETIC_RESULTS.md create mode 100644 project/person_c/VIDEO_SCRIPT.md create mode 100644 project/person_c/default_validation.txt create mode 100644 project/person_c/integration_validation.txt create mode 100644 project/person_c/synthetic_ablation.json diff --git a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst index 1e910f931c..38604fcf13 100644 --- a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst +++ b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst @@ -43,3 +43,20 @@ The runnable synthetic checkpoint is ``python -m project.person_c.checkpoint``. It exercises CSV loading, task processing, train-only processor fitting, an LSTM update, and held-out inference. This is an integration check, not a clinical performance study. + +Timing correction (November 17 audit): array row b represents the interval +[b,b+1) and is timestamped b+1, when that bin is complete. A prediction at +hour 5 uses only bins 0–4. The 336-hour cap yields 336 rows, not 337. +The oracle's hour/bin numbers identify array rows, not availability timestamps. +Exact-boundary observations at minute 300 enter bin 5, available at hour 6. +This conservative floor-bin convention differs from the paper's right-closed +resampling, but prevents sub-hour look-ahead. + +Missingness example +------------------- + +``python -m examples.eicu_hourly_los_lstm --output /tmp/tpc_ablation.json`` +trains two synthetic LSTM configurations and evaluates each at three removal +rates. It reports MAD and explicitly named log1p-MSE in days. The latter is +not the original paper's log-MSE. These synthetic results demonstrate execution +only. Set ``PYHEALTH_RUN_TPC_INTEGRATION=1`` to enable the slow integration test. diff --git a/examples/eicu_hourly_los_lstm.py b/examples/eicu_hourly_los_lstm.py new file mode 100644 index 0000000000..a0f9a1f6e8 --- /dev/null +++ b/examples/eicu_hourly_los_lstm.py @@ -0,0 +1,131 @@ +"""Synthetic missingness ablation for the hourly LOS task. + +Contributor: Xiao Luo (Person C); UIUC NetID: xiaoluo6. +Paper: Temporal Pointwise Convolutional Networks for Length of Stay Prediction +in the Intensive Care Unit, https://arxiv.org/abs/2007.09483. + +Run from the repository root: + python -m examples.eicu_hourly_los_lstm --output /tmp/tpc_ablation.json + +Five invented patients; 101 trains, 103/105 test, 102/104 are excluded. +Two LSTMs train on 0%/10% removed hourly cells; both evaluate at 0%/10%/20%. +Shared initialization and test masks; processors fit on each training variant. +Default MSE on train-scaled targets, not the paper's logarithmic loss. +MAD in days; log1p-MSE in days is explicitly not the paper's log-MSE metric. +This runnable example checks experimental wiring only; clinical results and +novelty claims require A's real-data experiment and team review. +""" + +import argparse +import json +from pathlib import Path +import tempfile +import numpy as np +import torch +from pyhealth.datasets import eICUDataset, create_sample_dataset, get_dataloader +from pyhealth.models import RNN_V2 +from pyhealth.tasks import TPCLengthOfStayEICU +from project.person_c.generate_synthetic import TABLES, generate + + +def run(steps: int = 3) -> list[dict]: + """Run the six synthetic configurations and return measured metrics.""" + if steps < 1: + raise ValueError("steps must be positive") + torch.set_num_threads(1) + results = [] + with tempfile.TemporaryDirectory(prefix="tpc-ablation-") as temporary: + root = Path(temporary) + generate(root / "csv") + data = eICUDataset( + root=str(root / "csv"), tables=TABLES, cache_dir=root / "cache" + ) + patients = { + sid: data.get_patient(f"synthetic-{sid}") for sid in (101, 103, 105) + } + for train_rate in (0.0, 0.1): + torch.manual_seed(42) + task = TPCLengthOfStayEICU(train_rate, seed=42, include_decay=True) + train = create_sample_dataset( + task(patients[101]), task.input_schema, task.output_schema + ) + model = RNN_V2( + train, + embedding_dim={ + "dynamic": [{"values": 8}], + "static": [{"values": 4}], + "decay": [{"values": 8}], + }, + hidden_dim=8, + rnn_type="LSTM", + mask="concat", + ) + optimizer = torch.optim.Adam(model.parameters(), lr=0.001) + batch = next(iter(get_dataloader(train, batch_size=1, shuffle=False))) + for _ in range(steps): + optimizer.zero_grad() + loss = model(**batch)["loss"] + if not torch.isfinite(loss): + raise RuntimeError("Nonfinite training loss") + loss.backward() + optimizer.step() + model.eval() + for test_rate in (0.0, 0.1, 0.2): + evaluation_task = TPCLengthOfStayEICU( + test_rate, seed=42, include_decay=True + ) + samples = [evaluation_task(patients[sid])[0] for sid in (103, 105)] + evaluation = create_sample_dataset( + samples, + task.input_schema, + task.output_schema, + input_processors=train.input_processors, + output_processors=train.output_processors, + ) + with torch.no_grad(): + out = model( + **next( + iter( + get_dataloader(evaluation, batch_size=2, shuffle=False) + ) + ) + ) + # activation() reverses label normalization; y_prob is in hours. + pred = out["y_prob"].numpy().reshape(-1) / 24 + truth = ( + np.concatenate( + [np.asarray(s["los"]["values"]).ravel() for s in samples] + ) + / 24 + ) + if not np.isfinite(pred).all() or pred.shape != truth.shape: + raise RuntimeError("Invalid predictions") + results.append( + { + "train_missing_rate": train_rate, + "test_missing_rate": test_rate, + "mad_days": float(np.abs(pred - truth).mean()), + "log1p_mse_days": float( + ( + (np.log1p(np.maximum(pred, 0)) - np.log1p(truth)) ** 2 + ).mean() + ), + "negative_predictions_clipped_for_log1p": int((pred < 0).sum()), + "prediction_count": len(truth), + "steps": steps, + "seed": 42, + "data": "synthetic; not evidence of clinical performance", + } + ) + return results + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--steps", type=int, default=3) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + results = run(args.steps) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(results, indent=2) + "\n") + print(json.dumps(results, indent=2)) diff --git a/project/person_c/AI_USAGE.md b/project/person_c/AI_USAGE.md new file mode 100644 index 0000000000..f59dd5e06c --- /dev/null +++ b/project/person_c/AI_USAGE.md @@ -0,0 +1,37 @@ +# AI assistance record for Person C + +This is a factual aid for the course form, not a submitted form or a substitute +for the student's own reflection. Preserve this chat for exact prompts and +responses. Review all outputs and write your own evaluation. + +Assistant: Codex. The session supplied GPT-6-family model identifiers that +changed during the conversation; do not invent a single exact version for all +turns. Work performed November 16–17, 2026, America/Los_Angeles. + +Selected exact user prompts: +- "You need to finish these" +- "see if the work distribution is compatible with the original project requirements, and double check if anything needs to be done for person C of the project and can be done right now. Implement them" + +Earlier requests asked for rubric/plan analysis, local deliverables, test +execution instructions, and explanations of test timing and sparse fixtures. +These are excerpts, not a complete prompt count. + +Assistance: document interpretation, repository inspection, synthetic fixture +generation, cohort/label implementation, tests, decay formula lookup, LSTM +smoke execution, documentation and presentation drafting. + +Validation actually performed: independent expected-value assertions; real +CSV loader; known inclusion/exclusion cases; forward fill and decay after +masking; no stay mixing; completed-bin timing; finite loss/gradients; changed +model parameters; reused train-fitted processors on held-out patients. + +Corrections that were necessary: initial CSVs were too sparse, initial status +overstated integration readiness, inherited cohort excluded five-hour stays, +full test startup was slow, and original floor-bin timestamps leaked later +within-hour measurements. The latest audit corrected the timing and documented +scope differences. Synthetic performance is not clinical evidence. + +Student reflection still required: explain which code you reviewed, what you +understand about the task and paper, what assumptions you accepted or changed, +and how the assistant helped or misled you. Do not claim independent authorship +or experiments that were not run. Submit the form using your Illinois account. diff --git a/project/person_c/EXPECTED_RESULTS.md b/project/person_c/EXPECTED_RESULTS.md index c3be4f1461..1733fcfdbd 100644 --- a/project/person_c/EXPECTED_RESULTS.md +++ b/project/person_c/EXPECTED_RESULTS.md @@ -49,3 +49,11 @@ https://github.com/EmmaRocheteau/TPC-LoS-prediction/blob/master/eICU_preprocessi Additional tiny unit fixtures cover exactly five hours, unknown age/sex, invalid height/weight, no measurements, two stays of the same patient, future-observation invariance and zero/10%/20%/100% removal. + +Timing correction (November 17 audit): array row b represents the interval +[b,b+1) and is timestamped b+1, when that bin is complete. A prediction at +hour 5 uses only bins 0–4. The 336-hour cap yields 336 rows, not 337. +The oracle's hour/bin numbers identify array rows, not availability timestamps. +Exact-boundary observations at minute 300 enter bin 5, available at hour 6. +This conservative floor-bin convention differs from the paper's right-closed +resampling, but prevents sub-hour look-ahead. diff --git a/project/person_c/INTERFACE.md b/project/person_c/INTERFACE.md index 690e7a7b40..f8a5542b0d 100644 --- a/project/person_c/INTERFACE.md +++ b/project/person_c/INTERFACE.md @@ -14,7 +14,7 @@ task = TPCLengthOfStayEICU(missing_rate=0.1, seed=42, include_decay=True) ``` One sample per ICU stay: patient_id (unique person), stay_id, dynamic, static, -los, and optional decay. Dynamic is {time: 0..H, values: (H+1,48)}; static is +los, and optional decay. Dynamic is {time: 1..H, values: (H,48)}; static is {time:[0], values:(1,4)}; los is {time:5..H, values:(H-4,1)}; decay mirrors dynamic's time and dimensions. H=min(floor(total LOS hours),336). @@ -44,3 +44,11 @@ Integration command (from repository root): This generates temporary CSVs, reads actual eICUDataset patients, applies the actual task and processors, runs a true LSTM optimizer step and evaluates the held-out batch. All temporary data/cache files are cleaned up. + +Timing correction (November 17 audit): array row b represents the interval +[b,b+1) and is timestamped b+1, when that bin is complete. A prediction at +hour 5 uses only bins 0–4. The 336-hour cap yields 336 rows, not 337. +The oracle's hour/bin numbers identify array rows, not availability timestamps. +Exact-boundary observations at minute 300 enter bin 5, available at hour 6. +This conservative floor-bin convention differs from the paper's right-closed +resampling, but prevents sub-hour look-ahead. diff --git a/project/person_c/PR_DRAFT.md b/project/person_c/PR_DRAFT.md new file mode 100644 index 0000000000..93243952fe --- /dev/null +++ b/project/person_c/PR_DRAFT.md @@ -0,0 +1,53 @@ +# Add an hourly remaining-ICU-LOS task with missingness experiments + +**Contributors:** +- Person C: Xiao Luo — xiaoluo6 +- Person A: ____________________ +- Person B: ____________________ + +Fill the A/B fields before posting; their identities were not supplied. + +**Contribution type:** Standalone task for the existing eICUDataset (Option 3). + +**Paper:** Rocheteau, Liò and Hyland, *Temporal Pointwise Convolutional Networks +for Length of Stay Prediction in the Intensive Care Unit* (CHIL 2021). +https://arxiv.org/abs/2007.09483 + +**Description:** Add hourly remaining-LOS labels from hour 5 through the first +14 days of an adult ICU stay. Reuse YAIB measurement/static extraction with +project-specific eligibility, reproducible removal of hourly observations, +and optional recency-decay inputs. Completed-bin timestamps prevent +within-hour look-ahead. Synthetic examples train PyHealth's existing LSTM; +this contribution does not implement the TPC model. + +**Files to review:** +- pyhealth/tasks/tpc_eicu.py: task, cohort, label generation, masking and decay. +- pyhealth/tasks/__init__.py: public import. +- docs/api/tasks/pyhealth.tasks.tpc_eicu.rst and docs/api/tasks.rst: API/index. +- tests/core/test_tpc_eicu.py and tpc_fixtures.py: fast synthetic coverage. +- tests/integration/test_tpc_checkpoint.py: opt-in actual CSV-to-LSTM check. +- examples/eicu_hourly_los_lstm.py: six-condition synthetic example. +- project/person_c/generate_synthetic.py and checkpoint.py: shared example + support; curate this directory with the team before upstream submission. + +**Validation:** See validation.txt and checkpoint_result.json. Run: +``` +python -m pytest tests/core/test_tpc_eicu.py -q --durations=5 +PYHEALTH_RUN_TPC_INTEGRATION=1 python -m pytest tests/integration/test_tpc_checkpoint.py -q +python -m examples.eicu_hourly_los_lstm --output /tmp/tpc_ablation.json +``` + +**Results:** Synthetic example results are recorded in synthetic_ablation.json +and SYNTHETIC_RESULTS.md, solely to demonstrate executable comparisons. +Insert A's actual eICU/demo experiment setup and findings before final submission. +Do not claim synthetic metrics reproduce the paper or establish robustness. + +**Reproduction differences:** Existing LSTM rather than TPC; YAIB feature set; +median/floor bins with completion-time timestamps; hourly-cell removal; training +z-score imputation/normalization; default MSE rather than paper MSLE. Targets +and activated predictions are in hours; MAD conversion uses days. Example +log1p-MSE is clearly labeled and is not the paper's logarithmic metric. + +**Before posting:** fill contributors; include final evidence; verify upstream +main/master discrepancy; rebase; enable maintainer edits; ensure one team PR; +record PR link in Gradescope with all group members. No PR has been posted. diff --git a/project/person_c/README.md b/project/person_c/README.md index af13902d54..205733d2a5 100644 --- a/project/person_c/README.md +++ b/project/person_c/README.md @@ -12,7 +12,7 @@ python project/person_c/generate_synthetic.py project/person_c/synthetic_eicu # Fast in-memory task checks; imports still add startup overhead. python -m pytest tests/core/test_tpc_eicu.py -v --durations=5 # Real CSV loader + preprocessing + LSTM optimizer step. -python -m pytest tests/integration/test_tpc_checkpoint.py -v +PYHEALTH_RUN_TPC_INTEGRATION=1 python -m pytest tests/integration/test_tpc_checkpoint.py -v # Independently runnable checkpoint, with machine-readable evidence. python -m project.person_c.checkpoint --output project/person_c/checkpoint_result.json ``` @@ -73,3 +73,17 @@ limitations/conclusions 5:00–5:40. AI assistance: code, tests and slide draft were produced with Codex. Review and understand the changes and accurately disclose assistance in the required course form. Reference: https://arxiv.org/abs/2007.09483. + +## November 17 rubric audit + +Read `RUBRIC_AUDIT.md` for compatibility, `PR_DRAFT.md` for the prepared PR, +`AI_USAGE.md` for an honest assistance record, and `VIDEO_SCRIPT.md` for the +narration plan. The required example now lives at +`examples/eicu_hourly_los_lstm.py`; six measured synthetic configurations are +in `synthetic_ablation.json` and `SYNTHETIC_RESULTS.md`. + +A correctness fix changed dynamic/decay timestamps to **completed-bin times** +1..H (H rows). Labels remain at 5..H. Earlier snapshots timestamped floor bins +at their start, exposing later within-hour measurements. Rerun A's integration +with this revision and do not reuse older cached task samples. +The slow CSV-to-LSTM pytest is opt-in; the standalone checkpoint always runs. diff --git a/project/person_c/RUBRIC_AUDIT.md b/project/person_c/RUBRIC_AUDIT.md new file mode 100644 index 0000000000..86c8ad1cee --- /dev/null +++ b/project/person_c/RUBRIC_AUDIT.md @@ -0,0 +1,91 @@ +# Work-distribution compatibility audit — November 17, 2026 + +## Verdict +The distribution is compatible with **Option 3: standalone task (50 points)**. +The rubric expressly permits partial reproduction using an existing dataset. +Reusing eICUDataset and an existing LSTM is legitimate. The proposal's original +TPC-model scope is reduced; explain that change rather than claiming TPC was +implemented. Existing dataset + task + existing LSTM is not a new model and +does not establish the full-pipeline extra credit. + +This audit uses the supplied rubric (final requirements on PDF pages 7–14), +work distribution (Stages 0–4), project draft, repository code and the sources +below. It is a readiness assessment, not a guaranteed grade. + +## Checklist +| Rubric area | Evidence/status | Owner / next action | +|---|---|---| +| Core task (20) | BaseTask inherited via YAIB; cohort, static fields, hourly labels, schemas, masking, optional decay, validation and docs | B/C review exact feature/timing contract | +| Required files (12) | task, RST, index, tests and examples/eicu_hourly_los_lstm.py now exist | A replace/extend synthetic example with final experiment | +| Tests (11) | Small in-memory core cases; real-loader/LSTM smoke check separately opt-in | C completed available coverage; rerun after B changes | +| Ablation (5) | Runnable 2 training × 3 test missingness configurations and measured synthetic results | A must supply meaningful eICU/demo experiment and findings | +| PR formatting (7) | PR_DRAFT.md contains scope, paper link, file guide, validation, limitations | C fill missing names/NetIDs and actual final results | +| Google Form (15) | AI_USAGE.md records assistance and validation honestly | Each member reviews and submits with Illinois account | +| Video (10) | Background/implementation slides and timed outline exist | C add A's results, record 4–7 minutes, upload public link | + +The five PR subsections shown in the rubric sum to 55 despite the stated +50-point total. Do not normalize or reinterpret that discrepancy; address +all listed requirements and leave scoring to the course staff. + +## Corrections and risks +1. The work distribution's entire-suite-under-one-second target is stricter + than the rubric's milliseconds per test / seconds per suite language. + The rubric also warns about tests >1 second. Core tests are fast; the real + loader/model check is explicitly opt-in, as the contribution guide permits. + Startup/import time is still reported, never hidden as sub-second execution. +2. Stage 0 asks for 2–3 deliberately designed patients; the rubric permits 2–5. + Five invented patients for the rich example are acceptable. Small isolated + unit fixtures cover each boundary; the rich CSV example is not the default + fast test. The contribution guide suggests 5–20 events for tiny tests, so + avoid promoting the full multi-table example to a millisecond unit test. +3. Floor-hour bins previously exposed observations later in the same hour to + that hour's label. Fixed: bin [b,b+1) is available only at b+1; at hour 5, + only completed bins 0–4 are used. Dedicated regression test added. +4. The original paper already ablates decay, diagnoses, temporal/pointwise + components, loss functions, and feature groups. Merely toggling decay is + NOT a novel extension for this assignment. Its documented experiments do + not include the proposed two-training-by-three-test random-cell-removal + grid; this is a defensible proposed extension relative to that paper, not + a claim of novelty across all literature. +5. The proposal describes raw-observation deletion and TPC training; the + current implementation masks aggregated hourly cells and trains LSTM. + Record both changes. Mean/right-edge binning, original features, original + normalization, and original MSLE are not all reproduced here. +6. The smoke test uses MSE on train-scaled targets. The example reports MAD in + days and explicitly named log1p-MSE in days. It is not the paper's log-MSE. + Do not compare those logarithmic metrics numerically as if equivalent. +7. Course PDF says target main; current PyHealth contribution guide says + master. The team fork uses master. Resolve the upstream target with course + staff/current repository before submitting; do not invent a main branch. +8. A team PR must include all names and NetIDs/emails, original paper link, + maintainer edits, current upstream rebase, and Gradescope group membership. + A local branch or a PR only to the team fork is not the final submission. +9. The guide routes files outside approved code/docs/example/test directories + (including project/person_c handoff material) to manual review. That is not + rejection, but curate the upstream diff with B or accept manual review. +10. The current task depends on YAIB helper internals. Rebase against the + actual upstream target and rerun the full task tests before posting. + +## Person C: available work completed in this audit +- Added rubric-to-evidence mapping and explicit remaining dependencies. +- Fixed within-hour look-ahead and added regression coverage. +- Added the required named synthetic ablation example with measured results. +- Marked the heavyweight integration check opt-in while retaining the command + and recorded proof that the real pipeline passes. +- Prepared PR draft, AI-use record, video narration and final submission gate. + +## Cannot be completed honestly right now +- Final real-data ablation conclusions: need A's experiments. +- Verify B's unseen final code or obtain teammate agreement: need their code/review. +- Final public presentation: needs experiment results and recorded narration. +- Individual Google Form answers/submission: require each member's review. +- Publish the Git branch: prior push failed authentication; no new credentials + have been supplied. Local commits and patch remain available. +- Fill A/B contributor identifiers: left blank at the user’s request. C is Xiao Luo, xiaoluo6. + +Sources: +- Supplied Fall26CS598 DL4H Project Instructions and Rubric.pdf, pages 7–14. +- Supplied Work distribution.pdf, Stages 0–4. +- Supplied Fall26CS598 DL4H Final Project Draft.pdf, methodology/extension plan. +- https://pyhealth.readthedocs.io/en/latest/how_to_contribute.html +- https://arxiv.org/html/2007.09483v4 (Sections 6.2, 7.1 and Appendix E). diff --git a/project/person_c/SYNTHETIC_RESULTS.md b/project/person_c/SYNTHETIC_RESULTS.md new file mode 100644 index 0000000000..71439bc29a --- /dev/null +++ b/project/person_c/SYNTHETIC_RESULTS.md @@ -0,0 +1,28 @@ +# Measured synthetic example results + +Run: `python -m examples.eicu_hourly_los_lstm --output /tmp/tpc_ablation.json`. +Five invented patients; one training stay, two held out; three optimizer +steps; fixed seed 42; identical test masks across trained models. These are +wiring checks, not clinical evidence or an estimate of generalization. + +| Train removal | Test removal | MAD (days) | log1p-MSE (days) | +|---|---|---|---| +| 0% | 0% | 9.460001 | 5.254549 | +| 0% | 10% | 9.459250 | 5.251213 | +| 0% | 20% | 9.459991 | 5.254490 | +| 10% | 0% | 9.459687 | 5.253154 | +| 10% | 10% | 9.459093 | 5.250510 | +| 10% | 20% | 9.459677 | 5.253099 | + +All six conditions produced 336 predictions and finite metrics. The errors +are large because the test set includes a 400.5-hour stay while the only +training stay lasts 12.5 hours, and training lasts only three updates. Tiny +differences here do not support the augmentation hypothesis. The long stay +dominates hourly aggregation; a real experiment should specify weighting, +patient-disjoint splits, repeated seeds, and paper-compatible metrics. + +log1p-MSE is explicitly different from the original paper's log-MSE. +Predictions are converted from hours to days; negative predictions, if any, +are clipped only for log1p and counted in the JSON. MAD uses raw predictions. +A must replace these illustrative results with the team's real experiment +before drawing conclusions or comparing numerical scores to the paper. diff --git a/project/person_c/VIDEO_SCRIPT.md b/project/person_c/VIDEO_SCRIPT.md new file mode 100644 index 0000000000..667241aad6 --- /dev/null +++ b/project/person_c/VIDEO_SCRIPT.md @@ -0,0 +1,66 @@ +# Person C narration and completion plan + +Target: 5 minutes 40 seconds. This is rehearsal text for the available portions, +not a claim that a final video or clinical-results presentation exists. + +## 0:00–0:20 — Problem +Our project studies hourly prediction of remaining ICU length of stay. This +can help with bed planning, but measurements are irregular, incomplete and +heterogeneous, and the target distribution is strongly skewed. + +## 0:20–1:10 — Paper approach +Rocheteau and colleagues propose temporal pointwise convolutions. Temporal +convolutions learn how individual clinical features evolve, and pointwise +convolutions combine features. Skip connections retain information, while +missingness indicators represent observation recency. The paper also studies +a logarithmic loss and auxiliary mortality prediction. Our contribution focuses +on the hourly prediction task within PyHealth, using an existing LSTM baseline. + +## 1:10–1:45 — Published findings +The paper reports improvements over LSTM and Transformer baselines, with +results depending on dataset and metric. Show the source table alongside the +relevant baseline when discussing a number. These published results are not +our experimental results. We have not implemented the TPC architecture. +Source: https://arxiv.org/html/2007.09483v4, Tables 2–4. + +## 1:45–2:30 — Our contribution +We reuse PyHealth's eICU loader and YAIB feature extraction, keeping adults +with at least five hours in ICU. Each stay has static admission features, +hourly measurements and remaining-stay labels. We cap observation history at +14 days, not the remaining-stay target. We document changes from the original +paper, including the features, aggregation and baseline model. + +## 2:30–3:30 — Implementation and tests +Show the pipeline diagram, a short CSV excerpt and the numerical oracle. +Five invented patients exercise all measurement tables, including missing and +invalid observations. Small tests cover cohort boundaries, static values, +labels, observation removal, forward fill and decay. We found and corrected +a timing bug: an hourly bin must be timestamped when complete so that a +prediction cannot read measurements from later in that hour. The integration +check loads the CSVs, fits processors only on the training patient, and runs +an LSTM update with finite gradients. Synthetic results validate the pipeline; +they do not demonstrate useful medical prediction. + +## 3:30–5:00 — Results section to finish with A +Required inputs: actual dataset/subset size, patient split, seed(s), epochs, +loss, feature list, units and zero-target policy; 2-by-3 missingness table; +MAD and paper-compatible MSLE; corresponding paper LSTM baseline with exact +source; explanation of scope differences. State whether results are better, +worse or incomparable and why. Do not insert fabricated values. If real-data +experiments cannot be completed, honestly report the attempt and limitations; +synthetic wiring evidence cannot be presented as replication performance. + +## 5:00–5:40 — Extension and limitations +Explain that the extension trains with extra missing observations and tests +robustness at three removal rates using shared masks. Decay removal alone +would repeat an existing paper ablation. Describe the findings supplied by A +without extrapolating beyond the tested cohort. End with limitations: reduced +feature set, different model/preprocessing, and limited compute/data scope. + +## Recording and submission checklist +- Fill the results section and update slides; every numerical claim has a source. +- Rehearse once; finish between four and seven minutes. +- Record your own narration; verify audio, screen readability and runtime. +- Upload and test the public video URL in a signed-out browser. +- Include the requested Gradescope link and all group members. +- Each member completes the final Google Form using the Illinois account. diff --git a/project/person_c/checkpoint.py b/project/person_c/checkpoint.py index 11328478df..ee77625199 100644 --- a/project/person_c/checkpoint.py +++ b/project/person_c/checkpoint.py @@ -1,3 +1,6 @@ +# Contributor: Xiao Luo, UIUC NetID xiaoluo6. +# Paper: Temporal Pointwise Convolutional Networks for Length of Stay +# Prediction in the Intensive Care Unit. https://arxiv.org/abs/2007.09483 """Synthetic CSV-to-LSTM checkpoint; no clinical performance claims.""" from pathlib import Path diff --git a/project/person_c/checkpoint_result.json b/project/person_c/checkpoint_result.json index 43c8b13594..3a4951a28c 100644 --- a/project/person_c/checkpoint_result.json +++ b/project/person_c/checkpoint_result.json @@ -22,7 +22,7 @@ "optimizer_steps": 1, "finite_nonzero_gradients": true, "parameters_changed": true, - "training_loss": 0.1641741394996643, - "heldout_loss": 1232.439697265625, + "training_loss": 0.16046194732189178, + "heldout_loss": 1232.579833984375, "interpretation": "Synthetic integration check only; not model performance evidence." } diff --git a/project/person_c/default_validation.txt b/project/person_c/default_validation.txt new file mode 100644 index 0000000000..4d2bf11eec --- /dev/null +++ b/project/person_c/default_validation.txt @@ -0,0 +1,8 @@ +...........................s [100%] +============================= slowest 5 durations ============================== +0.05s call tests/core/test_tpc_eicu.py::test_cohort[4.99-60-False] +0.02s call tests/core/test_tpc_eicu.py::test_static_features +0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0] +0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0.1] +0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0.2] +27 passed, 1 skipped in 21.62s diff --git a/project/person_c/generate_synthetic.py b/project/person_c/generate_synthetic.py index 0fb590ec15..f181b4aff5 100644 --- a/project/person_c/generate_synthetic.py +++ b/project/person_c/generate_synthetic.py @@ -1,3 +1,6 @@ +# Contributor: Xiao Luo, UIUC NetID xiaoluo6. +# Paper: Temporal Pointwise Convolutional Networks for Length of Stay +# Prediction in the Intensive Care Unit. https://arxiv.org/abs/2007.09483 """Write five invented patients in the shipped eICU CSV schema.""" import csv diff --git a/project/person_c/integration_validation.txt b/project/person_c/integration_validation.txt new file mode 100644 index 0000000000..3d097d401d --- /dev/null +++ b/project/person_c/integration_validation.txt @@ -0,0 +1,12 @@ +. [100%] +=============================== warnings summary =============================== +tests/integration/test_tpc_checkpoint.py::test_csv_to_lstm + /Users/luoxiao/.codex/.chatgpt-projects/g-p-6ac07c55e33881918976b24c72891f67/PyHealth/pyhealth/datasets/sample_dataset.py:208: FutureWarning: SequenceProcessorV2 and the 'sequence_v2' processor name are deprecated and will be removed in a future release; use JaggedFeatureProcessor and 'jagged', which behave identically. + return get_processor(spec)(**kwargs) + +-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html +============================= slowest 5 durations ============================== +4.31s call tests/integration/test_tpc_checkpoint.py::test_csv_to_lstm + +(2 durations < 0.005s hidden. Use -vv to show these durations.) +1 passed, 1 warning in 10.62s diff --git a/project/person_c/synthetic_ablation.json b/project/person_c/synthetic_ablation.json new file mode 100644 index 0000000000..6ed7696e8d --- /dev/null +++ b/project/person_c/synthetic_ablation.json @@ -0,0 +1,68 @@ +[ + { + "train_missing_rate": 0.0, + "test_missing_rate": 0.0, + "mad_days": 9.460000805117907, + "log1p_mse_days": 5.254549188824514, + "negative_predictions_clipped_for_log1p": 0, + "prediction_count": 336, + "steps": 3, + "seed": 42, + "data": "synthetic; not evidence of clinical performance" + }, + { + "train_missing_rate": 0.0, + "test_missing_rate": 0.1, + "mad_days": 9.459250288324373, + "log1p_mse_days": 5.251212770591288, + "negative_predictions_clipped_for_log1p": 0, + "prediction_count": 336, + "steps": 3, + "seed": 42, + "data": "synthetic; not evidence of clinical performance" + }, + { + "train_missing_rate": 0.0, + "test_missing_rate": 0.2, + "mad_days": 9.459990731395212, + "log1p_mse_days": 5.254490411380583, + "negative_predictions_clipped_for_log1p": 0, + "prediction_count": 336, + "steps": 3, + "seed": 42, + "data": "synthetic; not evidence of clinical performance" + }, + { + "train_missing_rate": 0.1, + "test_missing_rate": 0.0, + "mad_days": 9.45968699748979, + "log1p_mse_days": 5.253154022093286, + "negative_predictions_clipped_for_log1p": 0, + "prediction_count": 336, + "steps": 3, + "seed": 42, + "data": "synthetic; not evidence of clinical performance" + }, + { + "train_missing_rate": 0.1, + "test_missing_rate": 0.1, + "mad_days": 9.459092536646438, + "log1p_mse_days": 5.250509753547508, + "negative_predictions_clipped_for_log1p": 0, + "prediction_count": 336, + "steps": 3, + "seed": 42, + "data": "synthetic; not evidence of clinical performance" + }, + { + "train_missing_rate": 0.1, + "test_missing_rate": 0.2, + "mad_days": 9.459677495843074, + "log1p_mse_days": 5.253098513868501, + "negative_predictions_clipped_for_log1p": 0, + "prediction_count": 336, + "steps": 3, + "seed": 42, + "data": "synthetic; not evidence of clinical performance" + } +] diff --git a/project/person_c/validation.txt b/project/person_c/validation.txt index 383c9765c7..fb4f9c4d51 100644 --- a/project/person_c/validation.txt +++ b/project/person_c/validation.txt @@ -1,4 +1,4 @@ -........................... [100%] +............................ [100%] =============================== warnings summary =============================== tests/integration/test_tpc_checkpoint.py::test_csv_to_lstm /Users/luoxiao/.codex/.chatgpt-projects/g-p-6ac07c55e33881918976b24c72891f67/PyHealth/pyhealth/datasets/sample_dataset.py:208: FutureWarning: SequenceProcessorV2 and the 'sequence_v2' processor name are deprecated and will be removed in a future release; use JaggedFeatureProcessor and 'jagged', which behave identically. @@ -6,18 +6,19 @@ tests/integration/test_tpc_checkpoint.py::test_csv_to_lstm -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html ============================= slowest 30 durations ============================= -4.47s call tests/integration/test_tpc_checkpoint.py::test_csv_to_lstm -0.05s call tests/core/test_tpc_eicu.py::test_cohort[4.99-60-False] +5.13s call tests/integration/test_tpc_checkpoint.py::test_csv_to_lstm +0.07s call tests/core/test_tpc_eicu.py::test_cohort[4.99-60-False] 0.02s call tests/core/test_tpc_eicu.py::test_static_features -0.01s call tests/core/test_tpc_eicu.py::test_future_observations_do_not_change_earlier_hours -0.01s call tests/core/test_tpc_eicu.py::test_hourly_measurements_and_missing_data -0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0.2] -0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0] -0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[1] +0.02s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0] 0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0.1] -0.01s call tests/core/test_tpc_eicu.py::test_stays_are_isolated +0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[1] +0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0.2] +0.01s call tests/core/test_tpc_eicu.py::test_hourly_measurements_and_missing_data +0.01s call tests/core/test_tpc_eicu.py::test_future_observations_do_not_change_earlier_hours 0.01s call tests/core/test_tpc_eicu.py::test_labels_and_horizon +0.01s call tests/core/test_tpc_eicu.py::test_stays_are_isolated +0.01s call tests/core/test_tpc_eicu.py::test_incomplete_hour_cannot_enter_prediction 0.01s call tests/core/test_tpc_eicu.py::test_cohort[5-18-True] -(18 durations < 0.005s hidden. Use -vv to show these durations.) -27 passed, 1 warning in 11.78s +(17 durations < 0.005s hidden. Use -vv to show these durations.) +28 passed, 1 warning in 13.47s diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py index 85156abe5d..f130f639b4 100644 --- a/pyhealth/tasks/tpc_eicu.py +++ b/pyhealth/tasks/tpc_eicu.py @@ -1,3 +1,11 @@ +"""Hourly remaining-LOS task, contributed by Xiao Luo (Person C). + +UIUC NetID: xiaoluo6. +Paper: Temporal Pointwise Convolutional Networks for Length of Stay +Prediction in the Intensive Care Unit, https://arxiv.org/abs/2007.09483. +Reuses YAIB extraction; adds five-hour cohort, masking and optional decay. +""" + from copy import deepcopy import hashlib from typing import Any, ClassVar @@ -16,6 +24,7 @@ class TPCLengthOfStayEICU(YAIBLengthOfStayEICU): are age, sex (male=1, female=0), admission height and weight, inherited from YAIB. Unknown sex and invalid height/weight remain NaN. Labels are HOURS, from hour 5 through min(floor(LOS), 336), inclusive. + Dynamic timestamps mark completed bins: bin [h-1,h) is available at h. Remaining LOS is not clipped to 14 days. Dynamic values remain raw with NaNs; sequence_v2 processors fit normalization on training patients and forward-fill after observation masking. Optional decay is a separate input. @@ -59,6 +68,14 @@ def _base_cohort( YAIB's six-hour and measurement-density exclusions do not implement this project's cohort. Missing age is excluded conservatively. + + Args: + patient: PyHealth patient containing eICU events. + stays: Parsed stays with stay_id and los_hours columns. + + Returns: + Eligible stays, aggregated measurements, and static features + indexed by stay ID. """ static = self._static(patient, stays) keep = [ @@ -81,6 +98,12 @@ def _decay(values: np.ndarray) -> np.ndarray: first observation, 1 when observed, 1 / (gap * 4/3) afterwards. Source: EmmaRocheteau/TPC-LoS-prediction/eICU_preprocessing/timeseries.py. No forward-looking information or cross-stay state is used. + + Args: + values: Masked hourly matrix, with NaN for absent observations. + + Returns: + A finite matrix of the same shape containing observation recency. """ result = np.zeros_like(values, dtype=float) last = np.full(values.shape[1], -1, dtype=int) @@ -93,7 +116,16 @@ def _decay(values: np.ndarray) -> np.ndarray: return result def _apply_missingness(self, values: np.ndarray, stay_id: Any) -> np.ndarray: - """Randomly hide a fraction of originally observed values.""" + """Randomly hide a fraction of originally observed values. + + Args: + values: Raw hourly matrix, with NaN for missing cells. + stay_id: Stable identifier used to seed this stay's removal mask. + + Returns: + A copy with round(observed_count * missing_rate) cells set to NaN. + The input matrix and originally missing cells are unchanged. + """ values = values.copy() if self.missing_rate == 0.0: @@ -117,7 +149,17 @@ def _apply_missingness(self, values: np.ndarray, stay_id: Any) -> np.ndarray: return values def __call__(self, patient: Any) -> list[dict[str, Any]]: - """Generate hourly ICU samples with uncapped remaining LOS labels.""" + """Generate hourly ICU samples with uncapped remaining LOS labels. + + Args: + patient: PyHealth patient with eICU admission and measurement events. + + Returns: + One dictionary per eligible stay containing patient_id, stay_id, + dynamic, static, los, and optional decay series. Returns an empty + list when no eligible stays exist. Dynamic/decay time marks bin + completion; los time marks the prediction hour. Labels are hours. + """ all_stays = self._stays(patient) if all_stays.height == 0: @@ -135,7 +177,10 @@ def __call__(self, patient: Any) -> list[dict[str, Any]]: last_hour = min(end, self.MAX_HOURS) - dynamic = self._dynamic(hourly, stay_id, last_hour) + # Bin b contains offsets [60*b, 60*(b+1)); it is only + # available at b+1. Never expose an unfinished bin at label h. + dynamic = self._dynamic(hourly, stay_id, last_hour - 1) + dynamic["time"] = [float(h) for h in range(1, last_hour + 1)] # Keep all observations from hour 0 onward. dynamic["values"] = self._apply_missingness(dynamic["values"], stay_id) diff --git a/tests/core/test_tpc_eicu.py b/tests/core/test_tpc_eicu.py index 083fe9740a..dac4f9a663 100644 --- a/tests/core/test_tpc_eicu.py +++ b/tests/core/test_tpc_eicu.py @@ -1,3 +1,6 @@ +# Contributor: Xiao Luo, UIUC NetID xiaoluo6. +# Paper: Temporal Pointwise Convolutional Networks for Length of Stay +# Prediction in the Intensive Care Unit. https://arxiv.org/abs/2007.09483 """Person C: synthetic cohort and hourly-label regression tests. Reference: https://arxiv.org/abs/2007.09483. No clinical records used. @@ -43,7 +46,7 @@ def test_labels_and_horizon(): assert sample["los"]["time"] == list(range(5, 337)) assert _labels(sample["los"])[0] == 395.5 assert _labels(sample["los"])[-1] == 64.5 - assert sample["dynamic"]["values"].shape == (337, 48) + assert sample["dynamic"]["values"].shape == (336, 48) assert _labels(task(_patient(hours=5, hr_hours=[]))[0]["los"]) == [0] @@ -198,3 +201,20 @@ def test_combined_mask_fill_and_decay(rate): else: assert not filled.any() assert not sample["decay"]["values"].any() + + +def test_incomplete_hour_cannot_enter_prediction(): + task = TPCLengthOfStayEICU(include_decay=True) + baseline = task(_patient(hours=8, hr_hours=[]))[0] + changed = task(_patient(hours=8, hr_hours=[], extra=[_lab(359, "potassium", 5)]))[0] + for sample in [baseline, changed]: + assert sample["dynamic"]["time"] == list(range(1, 9)) + assert sample["decay"]["time"] == sample["dynamic"]["time"] + for field in ["dynamic", "decay"]: + times = np.asarray(changed[field]["time"]) + np.testing.assert_equal( + baseline[field]["values"][times <= 5], changed[field]["values"][times <= 5] + ) + k = task.DYNAMIC_FEATURES.index("k") + assert changed["dynamic"]["values"][5, k] == 5 + assert changed["dynamic"]["time"][5] == 6 diff --git a/tests/core/tpc_fixtures.py b/tests/core/tpc_fixtures.py index c9b02bd6f8..b43cb94fa6 100644 --- a/tests/core/tpc_fixtures.py +++ b/tests/core/tpc_fixtures.py @@ -1,3 +1,6 @@ +# Contributor: Xiao Luo, UIUC NetID xiaoluo6. +# Paper: Temporal Pointwise Convolutional Networks for Length of Stay +# Prediction in the Intensive Care Unit. https://arxiv.org/abs/2007.09483 """Small synthetic eICU records; adapted from YAIB regression fixtures.""" from pathlib import Path diff --git a/tests/integration/test_tpc_checkpoint.py b/tests/integration/test_tpc_checkpoint.py index bb71ba67b6..a438a590a6 100644 --- a/tests/integration/test_tpc_checkpoint.py +++ b/tests/integration/test_tpc_checkpoint.py @@ -1,8 +1,20 @@ -"""Actual CSV loader, processors, and LSTM integration on invented patients.""" +# Contributor: Xiao Luo, UIUC NetID xiaoluo6. +# Paper: Temporal Pointwise Convolutional Networks for Length of Stay +# Prediction in the Intensive Care Unit. https://arxiv.org/abs/2007.09483 +"""Opt-in real loader/training smoke check; fast task tests live in core. +Set PYHEALTH_RUN_TPC_INTEGRATION=1 to run this slower local-server check. +""" + +import os +import pytest from project.person_c.checkpoint import run +@pytest.mark.skipif( + os.environ.get("PYHEALTH_RUN_TPC_INTEGRATION") != "1", + reason="Opt-in CSV/Dask/LSTM check; set PYHEALTH_RUN_TPC_INTEGRATION=1", +) def test_csv_to_lstm(tmp_path): result = run(tmp_path) assert result["status"] == "passed" From dca848faa4f4ee8a6577e595dbc223ae52f8a57a Mon Sep 17 00:00:00 2001 From: xiaoluo0916 Date: Tue, 17 Nov 2026 21:24:34 -0800 Subject: [PATCH 14/50] Remove internal project planning notes from contribution --- project/person_c/AI_USAGE.md | 37 ----------- project/person_c/EXPECTED_RESULTS.md | 59 ----------------- project/person_c/INTERFACE.md | 54 ---------------- project/person_c/PR_DRAFT.md | 53 ---------------- project/person_c/README.md | 89 -------------------------- project/person_c/RUBRIC_AUDIT.md | 91 --------------------------- project/person_c/SYNTHETIC_RESULTS.md | 28 --------- project/person_c/VIDEO_SCRIPT.md | 66 ------------------- 8 files changed, 477 deletions(-) delete mode 100644 project/person_c/AI_USAGE.md delete mode 100644 project/person_c/EXPECTED_RESULTS.md delete mode 100644 project/person_c/INTERFACE.md delete mode 100644 project/person_c/PR_DRAFT.md delete mode 100644 project/person_c/README.md delete mode 100644 project/person_c/RUBRIC_AUDIT.md delete mode 100644 project/person_c/SYNTHETIC_RESULTS.md delete mode 100644 project/person_c/VIDEO_SCRIPT.md diff --git a/project/person_c/AI_USAGE.md b/project/person_c/AI_USAGE.md deleted file mode 100644 index f59dd5e06c..0000000000 --- a/project/person_c/AI_USAGE.md +++ /dev/null @@ -1,37 +0,0 @@ -# AI assistance record for Person C - -This is a factual aid for the course form, not a submitted form or a substitute -for the student's own reflection. Preserve this chat for exact prompts and -responses. Review all outputs and write your own evaluation. - -Assistant: Codex. The session supplied GPT-6-family model identifiers that -changed during the conversation; do not invent a single exact version for all -turns. Work performed November 16–17, 2026, America/Los_Angeles. - -Selected exact user prompts: -- "You need to finish these" -- "see if the work distribution is compatible with the original project requirements, and double check if anything needs to be done for person C of the project and can be done right now. Implement them" - -Earlier requests asked for rubric/plan analysis, local deliverables, test -execution instructions, and explanations of test timing and sparse fixtures. -These are excerpts, not a complete prompt count. - -Assistance: document interpretation, repository inspection, synthetic fixture -generation, cohort/label implementation, tests, decay formula lookup, LSTM -smoke execution, documentation and presentation drafting. - -Validation actually performed: independent expected-value assertions; real -CSV loader; known inclusion/exclusion cases; forward fill and decay after -masking; no stay mixing; completed-bin timing; finite loss/gradients; changed -model parameters; reused train-fitted processors on held-out patients. - -Corrections that were necessary: initial CSVs were too sparse, initial status -overstated integration readiness, inherited cohort excluded five-hour stays, -full test startup was slow, and original floor-bin timestamps leaked later -within-hour measurements. The latest audit corrected the timing and documented -scope differences. Synthetic performance is not clinical evidence. - -Student reflection still required: explain which code you reviewed, what you -understand about the task and paper, what assumptions you accepted or changed, -and how the assistant helped or misled you. Do not claim independent authorship -or experiments that were not run. Submit the form using your Illinois account. diff --git a/project/person_c/EXPECTED_RESULTS.md b/project/person_c/EXPECTED_RESULTS.md deleted file mode 100644 index 1733fcfdbd..0000000000 --- a/project/person_c/EXPECTED_RESULTS.md +++ /dev/null @@ -1,59 +0,0 @@ -# Independent synthetic-data oracle - -These numbers were calculated from the invented source records, not emitted -by the task. The CSV generator populates every required measurement table. -Five unique patients cover three eligible stays, a short stay, and a minor. - -| Stay | Age | LOS (hours) | Expected inclusion | Labels | -|---|---|---|---|---| -| 101 | 18 | 12.5 | Yes: ordinary adult | hours 5–12; 7.5, 6.5, …, 0.5 | -| 102 | 60 | 4 | No: shorter than five hours | none | -| 103 | > 89 | 400.5 | Yes: long stay | hours 5–336; final value 64.5 | -| 104 | 17 | 12 | No: minor | none | -| 105 | 45 | 8 | Yes: missing admission height | hours 5–8; 3, 2, 1, 0 | - -## Stay 101 selected raw hourly values - -| Table / feature | Records | Expected result | -|---|---|---| -| vitalPeriodic / HR | minute 10: 80; minute 40: 100 | hour 0 median = 90 | -| vitalPeriodic / HR | minute 120: 110; minute 359: 120 | hours 2 and 5 = 110 and 120 | -| vitalPeriodic / HR | minute -60: 250; minute 900: 200 | excluded from this stay's grid | -| lab / potassium | minute 60: 4; minute 90: 6 | hour 1 median = 5 | -| lab / potassium | minute 240: 3; minute 300: 99 | hour 4 = 3; hour 5 missing (invalid 99) | -| lab / creatinine | minute 150: 1.2 | hour 2 = 1.2 | -| vitalAperiodic / systolic BP | minute 180: 130 | hour 3 = 130 | -| intakeOutput / urine | minute 65: 100; minute 95: 50 | hour 1 sum = 150 | -| respiratoryCharting / FiO2 | minute 180: 40% | hour 3 = 40 | -| nurseCharting / temperature | minute 240: 98.6 F | hour 4 = 37 C | - -Static vector for 101: `[18, 0, 165, 65]`. For 103: `[90, 1, 165, 65]`. -For 105, height remains NaN until the training-fitted processor imputes it. - -## First six hours, before normalization - -- HR raw: `[90, NaN, 110, NaN, NaN, 120]`. -- HR forward-filled: `[90, 90, 110, 110, 110, 120]`. -- HR decay: `[1, .75, 1, .75, .375, 1]`. -- Potassium raw: `[NaN, 5, NaN, NaN, 3, NaN]`. -- Potassium decay: `[0, 1, .75, .375, 1, .75]`. - -Decay uses the authors' formula: zero before first measurement; one on a -measurement; `1 / (gap_hours * 4/3)` after it. Removing all measurements gives -all-zero decay. Imputation is applied AFTER removal. Initial missing feature -values use training statistics, or zero if never observed in training. - -Source for decay only: -https://github.com/EmmaRocheteau/TPC-LoS-prediction/blob/master/eICU_preprocessing/timeseries.py - -Additional tiny unit fixtures cover exactly five hours, unknown age/sex, -invalid height/weight, no measurements, two stays of the same patient, -future-observation invariance and zero/10%/20%/100% removal. - -Timing correction (November 17 audit): array row b represents the interval -[b,b+1) and is timestamped b+1, when that bin is complete. A prediction at -hour 5 uses only bins 0–4. The 336-hour cap yields 336 rows, not 337. -The oracle's hour/bin numbers identify array rows, not availability timestamps. -Exact-boundary observations at minute 300 enter bin 5, available at hour 6. -This conservative floor-bin convention differs from the paper's right-closed -resampling, but prevents sub-hour look-ahead. diff --git a/project/person_c/INTERFACE.md b/project/person_c/INTERFACE.md deleted file mode 100644 index f8a5542b0d..0000000000 --- a/project/person_c/INTERFACE.md +++ /dev/null @@ -1,54 +0,0 @@ -# Tested interface for A and B - -Status: locally implemented and integration-tested against origin/master -`e81a5574cb160798c9040de7b6fa32637913ef74`. This is a concrete proposed contract, -not evidence that teammates have approved it. No newer remote commits were -present when fetched for this revision. - -```python -from pyhealth.tasks import TPCLengthOfStayEICU -# Existing A code remains compatible: -task = TPCLengthOfStayEICU(missing_rate=0.1, seed=42) -# Enable tested decay for the full input: -task = TPCLengthOfStayEICU(missing_rate=0.1, seed=42, include_decay=True) -``` - -One sample per ICU stay: patient_id (unique person), stay_id, dynamic, static, -los, and optional decay. Dynamic is {time: 1..H, values: (H,48)}; static is -{time:[0], values:(1,4)}; los is {time:5..H, values:(H-4,1)}; decay mirrors -dynamic's time and dimensions. H=min(floor(total LOS hours),336). - -- Use RNN_V2 with `rnn_type="LSTM"` explicitly; its default is GRU. -- Add `decay: [{"values": 8}]` to embedding_dim when include_decay=True. -- Raw targets are HOURS. Convert predictions and targets together to days - before paper comparisons. Zero labels at exact discharge are preserved. - The smoke test uses the model's default regression objective; it is not an - MSLE experiment. A must explicitly select a zero-safe metric/loss convention. -- Preserve existing median/floor hourly binning and YAIB features. The paper - uses different mean/right-edge binning; this is a documented partial task - reproduction, not exact original preprocessing. -- Remove observed hourly cells before fitting/imputation. The proposal's raw - observation deletion differs; don't describe these as identical experiments. -- Fit all learned processors on training patients only and reuse for held-out - patients. Split by patient_id, never stay_id. The checkpoint uses patient 101 - for training and 103/105 as held out; it is too small for performance claims. -- Static fields are admission values, not discharge values. Missing age is - excluded; >89 maps to 90. Feature ordering comes from DYNAMIC_FEATURES and - STATIC_FEATURES rather than a separately maintained list. -- Decay is computed locally per stay, after masking. Default False preserves - A's prototype. B can retain this implementation or replace it only if the - expected-value tests still pass or the contract is explicitly revised. - -Integration command (from repository root): -`python -m project.person_c.checkpoint --output project/person_c/checkpoint_result.json` -This generates temporary CSVs, reads actual eICUDataset patients, applies the -actual task and processors, runs a true LSTM optimizer step and evaluates the -held-out batch. All temporary data/cache files are cleaned up. - -Timing correction (November 17 audit): array row b represents the interval -[b,b+1) and is timestamped b+1, when that bin is complete. A prediction at -hour 5 uses only bins 0–4. The 336-hour cap yields 336 rows, not 337. -The oracle's hour/bin numbers identify array rows, not availability timestamps. -Exact-boundary observations at minute 300 enter bin 5, available at hour 6. -This conservative floor-bin convention differs from the paper's right-closed -resampling, but prevents sub-hour look-ahead. diff --git a/project/person_c/PR_DRAFT.md b/project/person_c/PR_DRAFT.md deleted file mode 100644 index 93243952fe..0000000000 --- a/project/person_c/PR_DRAFT.md +++ /dev/null @@ -1,53 +0,0 @@ -# Add an hourly remaining-ICU-LOS task with missingness experiments - -**Contributors:** -- Person C: Xiao Luo — xiaoluo6 -- Person A: ____________________ -- Person B: ____________________ - -Fill the A/B fields before posting; their identities were not supplied. - -**Contribution type:** Standalone task for the existing eICUDataset (Option 3). - -**Paper:** Rocheteau, Liò and Hyland, *Temporal Pointwise Convolutional Networks -for Length of Stay Prediction in the Intensive Care Unit* (CHIL 2021). -https://arxiv.org/abs/2007.09483 - -**Description:** Add hourly remaining-LOS labels from hour 5 through the first -14 days of an adult ICU stay. Reuse YAIB measurement/static extraction with -project-specific eligibility, reproducible removal of hourly observations, -and optional recency-decay inputs. Completed-bin timestamps prevent -within-hour look-ahead. Synthetic examples train PyHealth's existing LSTM; -this contribution does not implement the TPC model. - -**Files to review:** -- pyhealth/tasks/tpc_eicu.py: task, cohort, label generation, masking and decay. -- pyhealth/tasks/__init__.py: public import. -- docs/api/tasks/pyhealth.tasks.tpc_eicu.rst and docs/api/tasks.rst: API/index. -- tests/core/test_tpc_eicu.py and tpc_fixtures.py: fast synthetic coverage. -- tests/integration/test_tpc_checkpoint.py: opt-in actual CSV-to-LSTM check. -- examples/eicu_hourly_los_lstm.py: six-condition synthetic example. -- project/person_c/generate_synthetic.py and checkpoint.py: shared example - support; curate this directory with the team before upstream submission. - -**Validation:** See validation.txt and checkpoint_result.json. Run: -``` -python -m pytest tests/core/test_tpc_eicu.py -q --durations=5 -PYHEALTH_RUN_TPC_INTEGRATION=1 python -m pytest tests/integration/test_tpc_checkpoint.py -q -python -m examples.eicu_hourly_los_lstm --output /tmp/tpc_ablation.json -``` - -**Results:** Synthetic example results are recorded in synthetic_ablation.json -and SYNTHETIC_RESULTS.md, solely to demonstrate executable comparisons. -Insert A's actual eICU/demo experiment setup and findings before final submission. -Do not claim synthetic metrics reproduce the paper or establish robustness. - -**Reproduction differences:** Existing LSTM rather than TPC; YAIB feature set; -median/floor bins with completion-time timestamps; hourly-cell removal; training -z-score imputation/normalization; default MSE rather than paper MSLE. Targets -and activated predictions are in hours; MAD conversion uses days. Example -log1p-MSE is clearly labeled and is not the paper's logarithmic metric. - -**Before posting:** fill contributors; include final evidence; verify upstream -main/master discrepancy; rebase; enable maintainer edits; ensure one team PR; -record PR link in Gradescope with all group members. No PR has been posted. diff --git a/project/person_c/README.md b/project/person_c/README.md deleted file mode 100644 index 205733d2a5..0000000000 --- a/project/person_c/README.md +++ /dev/null @@ -1,89 +0,0 @@ -# Person C checkpoint handoff — November 18 - -## Run locally - -From this checkout, activate the installed environment with -`source ../.venv/bin/activate`. On another machine install the repository and -pytest in a Python 3.12 or 3.13 environment. - -```sh -# Generate all seven populated synthetic CSVs (five invented patients). -python project/person_c/generate_synthetic.py project/person_c/synthetic_eicu -# Fast in-memory task checks; imports still add startup overhead. -python -m pytest tests/core/test_tpc_eicu.py -v --durations=5 -# Real CSV loader + preprocessing + LSTM optimizer step. -PYHEALTH_RUN_TPC_INTEGRATION=1 python -m pytest tests/integration/test_tpc_checkpoint.py -v -# Independently runnable checkpoint, with machine-readable evidence. -python -m project.person_c.checkpoint --output project/person_c/checkpoint_result.json -``` - -## Delivered - -- Five-patient fixtures populate lab, periodic/aperiodic vitals, intake/output, - respiratory and nursing tables; patient CSV defines admission/static fields. -- Adult/five-hour filtering, four static features and hourly remaining-LOS - labels; observations stop at hour 336 without capping remaining LOS. -- Optional decay input recomputed after masking, with the authors' formula. -- Independent numerical oracle: `EXPECTED_RESULTS.md`. -- Proposed team contract and reproduction differences: `INTERFACE.md`. -- Tests cover filtering, empty/missing records, static features, labels, - aggregation/conversions, removal, filling, decay, stay isolation and causality. -- CSV-to-LSTM integration uses actual PyHealth classes. Processors fit only on - training patients; held-out patients reuse them. Tests require finite loss, - correct prediction counts, finite nonzero gradients and parameter changes. -- RST API documentation and task index/public import updated. -- Background/implementation slides and 5:40 video outline prepared in this chat. - -Evidence: `validation.txt` (test results), `checkpoint_result.json` (training -check). Synthetic losses are only diagnostic; they are NOT clinical results. -No real patient data is used. Temporary integration data and caches are removed. - -## Timing - -Fast task assertions are measured separately from the CSV integration test. -The latter intentionally exercises PyHealth's Dask server, file conversion, -processors and model. Full command runtime includes imports and cannot be -represented as sub-second. See recorded timings rather than an estimated claim. - -## Team integration - -Work was based on origin/master e81a557. No newer remote commits were available -at the fetch. Existing calls remain compatible; enable `include_decay=True` -when adding the decay input to A's model. This runs a real LSTM using the public -PyHealth API; A's final training/ablation script is not present in the checkout, -so compatibility with that unseen script cannot be claimed. - -Review INTERFACE.md with A/B: units, discharge-zero policy, floor/median bins, -masking hourly cells rather than raw rows, and the feature list are explicit. -The checkpoint provides a tested integration path, not teammate approval. - -## Remaining scheduled work - -Person C: review the merged A/B code against this contract, update slides with -A's real experiment results, add contributor identities to the final PR draft, -help submit the team PR by November 24, and record the 4–7-minute video by -November 28. Current work follows Option 3 from the work distribution, rather -than the earlier proposal's full TPC model. No upstream PR is submitted here. -Course deadline: November 29, 2026 at 11:59 PM (rubric timezone unspecified). - -Video outline: motivation 0:00–0:20; TPC 0:20–1:10; paper results 1:10–1:45; -our scope 1:45–2:30; implementation/tests 2:30–3:30; A's results 3:30–5:00; -limitations/conclusions 5:00–5:40. - -AI assistance: code, tests and slide draft were produced with Codex. Review -and understand the changes and accurately disclose assistance in the required -course form. Reference: https://arxiv.org/abs/2007.09483. - -## November 17 rubric audit - -Read `RUBRIC_AUDIT.md` for compatibility, `PR_DRAFT.md` for the prepared PR, -`AI_USAGE.md` for an honest assistance record, and `VIDEO_SCRIPT.md` for the -narration plan. The required example now lives at -`examples/eicu_hourly_los_lstm.py`; six measured synthetic configurations are -in `synthetic_ablation.json` and `SYNTHETIC_RESULTS.md`. - -A correctness fix changed dynamic/decay timestamps to **completed-bin times** -1..H (H rows). Labels remain at 5..H. Earlier snapshots timestamped floor bins -at their start, exposing later within-hour measurements. Rerun A's integration -with this revision and do not reuse older cached task samples. -The slow CSV-to-LSTM pytest is opt-in; the standalone checkpoint always runs. diff --git a/project/person_c/RUBRIC_AUDIT.md b/project/person_c/RUBRIC_AUDIT.md deleted file mode 100644 index 86c8ad1cee..0000000000 --- a/project/person_c/RUBRIC_AUDIT.md +++ /dev/null @@ -1,91 +0,0 @@ -# Work-distribution compatibility audit — November 17, 2026 - -## Verdict -The distribution is compatible with **Option 3: standalone task (50 points)**. -The rubric expressly permits partial reproduction using an existing dataset. -Reusing eICUDataset and an existing LSTM is legitimate. The proposal's original -TPC-model scope is reduced; explain that change rather than claiming TPC was -implemented. Existing dataset + task + existing LSTM is not a new model and -does not establish the full-pipeline extra credit. - -This audit uses the supplied rubric (final requirements on PDF pages 7–14), -work distribution (Stages 0–4), project draft, repository code and the sources -below. It is a readiness assessment, not a guaranteed grade. - -## Checklist -| Rubric area | Evidence/status | Owner / next action | -|---|---|---| -| Core task (20) | BaseTask inherited via YAIB; cohort, static fields, hourly labels, schemas, masking, optional decay, validation and docs | B/C review exact feature/timing contract | -| Required files (12) | task, RST, index, tests and examples/eicu_hourly_los_lstm.py now exist | A replace/extend synthetic example with final experiment | -| Tests (11) | Small in-memory core cases; real-loader/LSTM smoke check separately opt-in | C completed available coverage; rerun after B changes | -| Ablation (5) | Runnable 2 training × 3 test missingness configurations and measured synthetic results | A must supply meaningful eICU/demo experiment and findings | -| PR formatting (7) | PR_DRAFT.md contains scope, paper link, file guide, validation, limitations | C fill missing names/NetIDs and actual final results | -| Google Form (15) | AI_USAGE.md records assistance and validation honestly | Each member reviews and submits with Illinois account | -| Video (10) | Background/implementation slides and timed outline exist | C add A's results, record 4–7 minutes, upload public link | - -The five PR subsections shown in the rubric sum to 55 despite the stated -50-point total. Do not normalize or reinterpret that discrepancy; address -all listed requirements and leave scoring to the course staff. - -## Corrections and risks -1. The work distribution's entire-suite-under-one-second target is stricter - than the rubric's milliseconds per test / seconds per suite language. - The rubric also warns about tests >1 second. Core tests are fast; the real - loader/model check is explicitly opt-in, as the contribution guide permits. - Startup/import time is still reported, never hidden as sub-second execution. -2. Stage 0 asks for 2–3 deliberately designed patients; the rubric permits 2–5. - Five invented patients for the rich example are acceptable. Small isolated - unit fixtures cover each boundary; the rich CSV example is not the default - fast test. The contribution guide suggests 5–20 events for tiny tests, so - avoid promoting the full multi-table example to a millisecond unit test. -3. Floor-hour bins previously exposed observations later in the same hour to - that hour's label. Fixed: bin [b,b+1) is available only at b+1; at hour 5, - only completed bins 0–4 are used. Dedicated regression test added. -4. The original paper already ablates decay, diagnoses, temporal/pointwise - components, loss functions, and feature groups. Merely toggling decay is - NOT a novel extension for this assignment. Its documented experiments do - not include the proposed two-training-by-three-test random-cell-removal - grid; this is a defensible proposed extension relative to that paper, not - a claim of novelty across all literature. -5. The proposal describes raw-observation deletion and TPC training; the - current implementation masks aggregated hourly cells and trains LSTM. - Record both changes. Mean/right-edge binning, original features, original - normalization, and original MSLE are not all reproduced here. -6. The smoke test uses MSE on train-scaled targets. The example reports MAD in - days and explicitly named log1p-MSE in days. It is not the paper's log-MSE. - Do not compare those logarithmic metrics numerically as if equivalent. -7. Course PDF says target main; current PyHealth contribution guide says - master. The team fork uses master. Resolve the upstream target with course - staff/current repository before submitting; do not invent a main branch. -8. A team PR must include all names and NetIDs/emails, original paper link, - maintainer edits, current upstream rebase, and Gradescope group membership. - A local branch or a PR only to the team fork is not the final submission. -9. The guide routes files outside approved code/docs/example/test directories - (including project/person_c handoff material) to manual review. That is not - rejection, but curate the upstream diff with B or accept manual review. -10. The current task depends on YAIB helper internals. Rebase against the - actual upstream target and rerun the full task tests before posting. - -## Person C: available work completed in this audit -- Added rubric-to-evidence mapping and explicit remaining dependencies. -- Fixed within-hour look-ahead and added regression coverage. -- Added the required named synthetic ablation example with measured results. -- Marked the heavyweight integration check opt-in while retaining the command - and recorded proof that the real pipeline passes. -- Prepared PR draft, AI-use record, video narration and final submission gate. - -## Cannot be completed honestly right now -- Final real-data ablation conclusions: need A's experiments. -- Verify B's unseen final code or obtain teammate agreement: need their code/review. -- Final public presentation: needs experiment results and recorded narration. -- Individual Google Form answers/submission: require each member's review. -- Publish the Git branch: prior push failed authentication; no new credentials - have been supplied. Local commits and patch remain available. -- Fill A/B contributor identifiers: left blank at the user’s request. C is Xiao Luo, xiaoluo6. - -Sources: -- Supplied Fall26CS598 DL4H Project Instructions and Rubric.pdf, pages 7–14. -- Supplied Work distribution.pdf, Stages 0–4. -- Supplied Fall26CS598 DL4H Final Project Draft.pdf, methodology/extension plan. -- https://pyhealth.readthedocs.io/en/latest/how_to_contribute.html -- https://arxiv.org/html/2007.09483v4 (Sections 6.2, 7.1 and Appendix E). diff --git a/project/person_c/SYNTHETIC_RESULTS.md b/project/person_c/SYNTHETIC_RESULTS.md deleted file mode 100644 index 71439bc29a..0000000000 --- a/project/person_c/SYNTHETIC_RESULTS.md +++ /dev/null @@ -1,28 +0,0 @@ -# Measured synthetic example results - -Run: `python -m examples.eicu_hourly_los_lstm --output /tmp/tpc_ablation.json`. -Five invented patients; one training stay, two held out; three optimizer -steps; fixed seed 42; identical test masks across trained models. These are -wiring checks, not clinical evidence or an estimate of generalization. - -| Train removal | Test removal | MAD (days) | log1p-MSE (days) | -|---|---|---|---| -| 0% | 0% | 9.460001 | 5.254549 | -| 0% | 10% | 9.459250 | 5.251213 | -| 0% | 20% | 9.459991 | 5.254490 | -| 10% | 0% | 9.459687 | 5.253154 | -| 10% | 10% | 9.459093 | 5.250510 | -| 10% | 20% | 9.459677 | 5.253099 | - -All six conditions produced 336 predictions and finite metrics. The errors -are large because the test set includes a 400.5-hour stay while the only -training stay lasts 12.5 hours, and training lasts only three updates. Tiny -differences here do not support the augmentation hypothesis. The long stay -dominates hourly aggregation; a real experiment should specify weighting, -patient-disjoint splits, repeated seeds, and paper-compatible metrics. - -log1p-MSE is explicitly different from the original paper's log-MSE. -Predictions are converted from hours to days; negative predictions, if any, -are clipped only for log1p and counted in the JSON. MAD uses raw predictions. -A must replace these illustrative results with the team's real experiment -before drawing conclusions or comparing numerical scores to the paper. diff --git a/project/person_c/VIDEO_SCRIPT.md b/project/person_c/VIDEO_SCRIPT.md deleted file mode 100644 index 667241aad6..0000000000 --- a/project/person_c/VIDEO_SCRIPT.md +++ /dev/null @@ -1,66 +0,0 @@ -# Person C narration and completion plan - -Target: 5 minutes 40 seconds. This is rehearsal text for the available portions, -not a claim that a final video or clinical-results presentation exists. - -## 0:00–0:20 — Problem -Our project studies hourly prediction of remaining ICU length of stay. This -can help with bed planning, but measurements are irregular, incomplete and -heterogeneous, and the target distribution is strongly skewed. - -## 0:20–1:10 — Paper approach -Rocheteau and colleagues propose temporal pointwise convolutions. Temporal -convolutions learn how individual clinical features evolve, and pointwise -convolutions combine features. Skip connections retain information, while -missingness indicators represent observation recency. The paper also studies -a logarithmic loss and auxiliary mortality prediction. Our contribution focuses -on the hourly prediction task within PyHealth, using an existing LSTM baseline. - -## 1:10–1:45 — Published findings -The paper reports improvements over LSTM and Transformer baselines, with -results depending on dataset and metric. Show the source table alongside the -relevant baseline when discussing a number. These published results are not -our experimental results. We have not implemented the TPC architecture. -Source: https://arxiv.org/html/2007.09483v4, Tables 2–4. - -## 1:45–2:30 — Our contribution -We reuse PyHealth's eICU loader and YAIB feature extraction, keeping adults -with at least five hours in ICU. Each stay has static admission features, -hourly measurements and remaining-stay labels. We cap observation history at -14 days, not the remaining-stay target. We document changes from the original -paper, including the features, aggregation and baseline model. - -## 2:30–3:30 — Implementation and tests -Show the pipeline diagram, a short CSV excerpt and the numerical oracle. -Five invented patients exercise all measurement tables, including missing and -invalid observations. Small tests cover cohort boundaries, static values, -labels, observation removal, forward fill and decay. We found and corrected -a timing bug: an hourly bin must be timestamped when complete so that a -prediction cannot read measurements from later in that hour. The integration -check loads the CSVs, fits processors only on the training patient, and runs -an LSTM update with finite gradients. Synthetic results validate the pipeline; -they do not demonstrate useful medical prediction. - -## 3:30–5:00 — Results section to finish with A -Required inputs: actual dataset/subset size, patient split, seed(s), epochs, -loss, feature list, units and zero-target policy; 2-by-3 missingness table; -MAD and paper-compatible MSLE; corresponding paper LSTM baseline with exact -source; explanation of scope differences. State whether results are better, -worse or incomparable and why. Do not insert fabricated values. If real-data -experiments cannot be completed, honestly report the attempt and limitations; -synthetic wiring evidence cannot be presented as replication performance. - -## 5:00–5:40 — Extension and limitations -Explain that the extension trains with extra missing observations and tests -robustness at three removal rates using shared masks. Decay removal alone -would repeat an existing paper ablation. Describe the findings supplied by A -without extrapolating beyond the tested cohort. End with limitations: reduced -feature set, different model/preprocessing, and limited compute/data scope. - -## Recording and submission checklist -- Fill the results section and update slides; every numerical claim has a source. -- Rehearse once; finish between four and seven minutes. -- Record your own narration; verify audio, screen readability and runtime. -- Upload and test the public video URL in a signed-out browser. -- Include the requested Gradescope link and all group members. -- Each member completes the final Google Form using the Illinois account. From b71e78dd9a2eb531b5eabfcec6bd1a5c4f1e07b1 Mon Sep 17 00:00:00 2001 From: xiaoluo0916 Date: Tue, 17 Nov 2026 21:26:18 -0800 Subject: [PATCH 15/50] Use neutral naming for TPC examples and test support --- docs/api/tasks/pyhealth.tasks.tpc_eicu.rst | 2 +- examples/eicu_hourly_los_lstm.py | 4 ++-- {project/person_c => examples/tpc_support}/checkpoint.py | 4 ++-- .../person_c => examples/tpc_support}/checkpoint_result.json | 0 .../person_c => examples/tpc_support}/default_validation.txt | 0 .../person_c => examples/tpc_support}/generate_synthetic.py | 0 .../tpc_support}/integration_validation.txt | 0 .../person_c => examples/tpc_support}/synthetic_ablation.json | 0 .../tpc_support}/synthetic_eicu/intakeOutput.csv | 0 .../person_c => examples/tpc_support}/synthetic_eicu/lab.csv | 0 .../tpc_support}/synthetic_eicu/nurseCharting.csv | 0 .../tpc_support}/synthetic_eicu/patient.csv | 0 .../tpc_support}/synthetic_eicu/respiratoryCharting.csv | 0 .../tpc_support}/synthetic_eicu/vitalAperiodic.csv | 0 .../tpc_support}/synthetic_eicu/vitalPeriodic.csv | 0 {project/person_c => examples/tpc_support}/validation.txt | 0 pyhealth/tasks/tpc_eicu.py | 2 +- tests/core/test_tpc_eicu.py | 2 +- tests/integration/test_tpc_checkpoint.py | 2 +- 19 files changed, 8 insertions(+), 8 deletions(-) rename {project/person_c => examples/tpc_support}/checkpoint.py (97%) rename {project/person_c => examples/tpc_support}/checkpoint_result.json (100%) rename {project/person_c => examples/tpc_support}/default_validation.txt (100%) rename {project/person_c => examples/tpc_support}/generate_synthetic.py (100%) rename {project/person_c => examples/tpc_support}/integration_validation.txt (100%) rename {project/person_c => examples/tpc_support}/synthetic_ablation.json (100%) rename {project/person_c => examples/tpc_support}/synthetic_eicu/intakeOutput.csv (100%) rename {project/person_c => examples/tpc_support}/synthetic_eicu/lab.csv (100%) rename {project/person_c => examples/tpc_support}/synthetic_eicu/nurseCharting.csv (100%) rename {project/person_c => examples/tpc_support}/synthetic_eicu/patient.csv (100%) rename {project/person_c => examples/tpc_support}/synthetic_eicu/respiratoryCharting.csv (100%) rename {project/person_c => examples/tpc_support}/synthetic_eicu/vitalAperiodic.csv (100%) rename {project/person_c => examples/tpc_support}/synthetic_eicu/vitalPeriodic.csv (100%) rename {project/person_c => examples/tpc_support}/validation.txt (100%) diff --git a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst index 38604fcf13..dcf959e675 100644 --- a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst +++ b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst @@ -40,7 +40,7 @@ It is calculated after observation removal and is not standardized. Add the False for compatibility with the team prototype. The runnable synthetic checkpoint is -``python -m project.person_c.checkpoint``. It exercises CSV loading, task +``python -m examples.tpc_support.checkpoint``. It exercises CSV loading, task processing, train-only processor fitting, an LSTM update, and held-out inference. This is an integration check, not a clinical performance study. diff --git a/examples/eicu_hourly_los_lstm.py b/examples/eicu_hourly_los_lstm.py index a0f9a1f6e8..36b79c3026 100644 --- a/examples/eicu_hourly_los_lstm.py +++ b/examples/eicu_hourly_los_lstm.py @@ -1,6 +1,6 @@ """Synthetic missingness ablation for the hourly LOS task. -Contributor: Xiao Luo (Person C); UIUC NetID: xiaoluo6. +Contributor: Xiao Luo; UIUC NetID: xiaoluo6. Paper: Temporal Pointwise Convolutional Networks for Length of Stay Prediction in the Intensive Care Unit, https://arxiv.org/abs/2007.09483. @@ -25,7 +25,7 @@ from pyhealth.datasets import eICUDataset, create_sample_dataset, get_dataloader from pyhealth.models import RNN_V2 from pyhealth.tasks import TPCLengthOfStayEICU -from project.person_c.generate_synthetic import TABLES, generate +from examples.tpc_support.generate_synthetic import TABLES, generate def run(steps: int = 3) -> list[dict]: diff --git a/project/person_c/checkpoint.py b/examples/tpc_support/checkpoint.py similarity index 97% rename from project/person_c/checkpoint.py rename to examples/tpc_support/checkpoint.py index ee77625199..19aba85839 100644 --- a/project/person_c/checkpoint.py +++ b/examples/tpc_support/checkpoint.py @@ -11,7 +11,7 @@ from pyhealth.datasets import eICUDataset, create_sample_dataset, get_dataloader from pyhealth.models import RNN_V2 from pyhealth.tasks import TPCLengthOfStayEICU -from project.person_c.generate_synthetic import generate, TABLES +from examples.tpc_support.generate_synthetic import generate, TABLES def run(root: Path) -> dict: @@ -140,7 +140,7 @@ def value(hour, name): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path) args = parser.parse_args() - with tempfile.TemporaryDirectory(prefix="person-c-checkpoint-") as tmp: + with tempfile.TemporaryDirectory(prefix="tpc-checkpoint-") as tmp: report = run(Path(tmp)) text = json.dumps(report, indent=2) print(text) diff --git a/project/person_c/checkpoint_result.json b/examples/tpc_support/checkpoint_result.json similarity index 100% rename from project/person_c/checkpoint_result.json rename to examples/tpc_support/checkpoint_result.json diff --git a/project/person_c/default_validation.txt b/examples/tpc_support/default_validation.txt similarity index 100% rename from project/person_c/default_validation.txt rename to examples/tpc_support/default_validation.txt diff --git a/project/person_c/generate_synthetic.py b/examples/tpc_support/generate_synthetic.py similarity index 100% rename from project/person_c/generate_synthetic.py rename to examples/tpc_support/generate_synthetic.py diff --git a/project/person_c/integration_validation.txt b/examples/tpc_support/integration_validation.txt similarity index 100% rename from project/person_c/integration_validation.txt rename to examples/tpc_support/integration_validation.txt diff --git a/project/person_c/synthetic_ablation.json b/examples/tpc_support/synthetic_ablation.json similarity index 100% rename from project/person_c/synthetic_ablation.json rename to examples/tpc_support/synthetic_ablation.json diff --git a/project/person_c/synthetic_eicu/intakeOutput.csv b/examples/tpc_support/synthetic_eicu/intakeOutput.csv similarity index 100% rename from project/person_c/synthetic_eicu/intakeOutput.csv rename to examples/tpc_support/synthetic_eicu/intakeOutput.csv diff --git a/project/person_c/synthetic_eicu/lab.csv b/examples/tpc_support/synthetic_eicu/lab.csv similarity index 100% rename from project/person_c/synthetic_eicu/lab.csv rename to examples/tpc_support/synthetic_eicu/lab.csv diff --git a/project/person_c/synthetic_eicu/nurseCharting.csv b/examples/tpc_support/synthetic_eicu/nurseCharting.csv similarity index 100% rename from project/person_c/synthetic_eicu/nurseCharting.csv rename to examples/tpc_support/synthetic_eicu/nurseCharting.csv diff --git a/project/person_c/synthetic_eicu/patient.csv b/examples/tpc_support/synthetic_eicu/patient.csv similarity index 100% rename from project/person_c/synthetic_eicu/patient.csv rename to examples/tpc_support/synthetic_eicu/patient.csv diff --git a/project/person_c/synthetic_eicu/respiratoryCharting.csv b/examples/tpc_support/synthetic_eicu/respiratoryCharting.csv similarity index 100% rename from project/person_c/synthetic_eicu/respiratoryCharting.csv rename to examples/tpc_support/synthetic_eicu/respiratoryCharting.csv diff --git a/project/person_c/synthetic_eicu/vitalAperiodic.csv b/examples/tpc_support/synthetic_eicu/vitalAperiodic.csv similarity index 100% rename from project/person_c/synthetic_eicu/vitalAperiodic.csv rename to examples/tpc_support/synthetic_eicu/vitalAperiodic.csv diff --git a/project/person_c/synthetic_eicu/vitalPeriodic.csv b/examples/tpc_support/synthetic_eicu/vitalPeriodic.csv similarity index 100% rename from project/person_c/synthetic_eicu/vitalPeriodic.csv rename to examples/tpc_support/synthetic_eicu/vitalPeriodic.csv diff --git a/project/person_c/validation.txt b/examples/tpc_support/validation.txt similarity index 100% rename from project/person_c/validation.txt rename to examples/tpc_support/validation.txt diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py index f130f639b4..cbe9e2fae7 100644 --- a/pyhealth/tasks/tpc_eicu.py +++ b/pyhealth/tasks/tpc_eicu.py @@ -1,4 +1,4 @@ -"""Hourly remaining-LOS task, contributed by Xiao Luo (Person C). +"""Hourly remaining-LOS task, contributed by Xiao Luo. UIUC NetID: xiaoluo6. Paper: Temporal Pointwise Convolutional Networks for Length of Stay diff --git a/tests/core/test_tpc_eicu.py b/tests/core/test_tpc_eicu.py index dac4f9a663..57783359f6 100644 --- a/tests/core/test_tpc_eicu.py +++ b/tests/core/test_tpc_eicu.py @@ -1,7 +1,7 @@ # Contributor: Xiao Luo, UIUC NetID xiaoluo6. # Paper: Temporal Pointwise Convolutional Networks for Length of Stay # Prediction in the Intensive Care Unit. https://arxiv.org/abs/2007.09483 -"""Person C: synthetic cohort and hourly-label regression tests. +"""Synthetic cohort and hourly-label regression tests. Reference: https://arxiv.org/abs/2007.09483. No clinical records used. """ diff --git a/tests/integration/test_tpc_checkpoint.py b/tests/integration/test_tpc_checkpoint.py index a438a590a6..5d4d4622bc 100644 --- a/tests/integration/test_tpc_checkpoint.py +++ b/tests/integration/test_tpc_checkpoint.py @@ -8,7 +8,7 @@ import os import pytest -from project.person_c.checkpoint import run +from examples.tpc_support.checkpoint import run @pytest.mark.skipif( From b902f315f96af634bdeb0b592cebf97c77218a0d Mon Sep 17 00:00:00 2001 From: xiaoluo0916 Date: Tue, 17 Nov 2026 21:28:35 -0800 Subject: [PATCH 16/50] Remove machine-specific paths from validation reports --- examples/tpc_support/integration_validation.txt | 2 +- examples/tpc_support/validation.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/tpc_support/integration_validation.txt b/examples/tpc_support/integration_validation.txt index 3d097d401d..5adba88c98 100644 --- a/examples/tpc_support/integration_validation.txt +++ b/examples/tpc_support/integration_validation.txt @@ -1,7 +1,7 @@ . [100%] =============================== warnings summary =============================== tests/integration/test_tpc_checkpoint.py::test_csv_to_lstm - /Users/luoxiao/.codex/.chatgpt-projects/g-p-6ac07c55e33881918976b24c72891f67/PyHealth/pyhealth/datasets/sample_dataset.py:208: FutureWarning: SequenceProcessorV2 and the 'sequence_v2' processor name are deprecated and will be removed in a future release; use JaggedFeatureProcessor and 'jagged', which behave identically. + pyhealth/datasets/sample_dataset.py:208: FutureWarning: SequenceProcessorV2 and the 'sequence_v2' processor name are deprecated and will be removed in a future release; use JaggedFeatureProcessor and 'jagged', which behave identically. return get_processor(spec)(**kwargs) -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html diff --git a/examples/tpc_support/validation.txt b/examples/tpc_support/validation.txt index fb4f9c4d51..60bfa5a759 100644 --- a/examples/tpc_support/validation.txt +++ b/examples/tpc_support/validation.txt @@ -1,7 +1,7 @@ ............................ [100%] =============================== warnings summary =============================== tests/integration/test_tpc_checkpoint.py::test_csv_to_lstm - /Users/luoxiao/.codex/.chatgpt-projects/g-p-6ac07c55e33881918976b24c72891f67/PyHealth/pyhealth/datasets/sample_dataset.py:208: FutureWarning: SequenceProcessorV2 and the 'sequence_v2' processor name are deprecated and will be removed in a future release; use JaggedFeatureProcessor and 'jagged', which behave identically. + pyhealth/datasets/sample_dataset.py:208: FutureWarning: SequenceProcessorV2 and the 'sequence_v2' processor name are deprecated and will be removed in a future release; use JaggedFeatureProcessor and 'jagged', which behave identically. return get_processor(spec)(**kwargs) -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html From 1156863f5aff967bf67cd2c72a11b4510bd6b2e1 Mon Sep 17 00:00:00 2001 From: xiaoluo0916 Date: Tue, 17 Nov 2026 21:30:02 -0800 Subject: [PATCH 17/50] Document reusable task interface and satisfy PR usage example check --- docs/api/tasks/pyhealth.tasks.tpc_eicu.rst | 60 +++++++++++++++++++++- examples/eicu_hourly_los_lstm.py | 10 +++- pyhealth/tasks/tpc_eicu.py | 8 +++ 3 files changed, 76 insertions(+), 2 deletions(-) diff --git a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst index dcf959e675..1f83a494ff 100644 --- a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst +++ b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst @@ -27,7 +27,7 @@ hourly aggregation, before processor imputation. Forward filling and training normalization are inherited; optional paper-formula decay is described below. Run ``pytest tests/core/test_tpc_eicu.py`` for fast synthetic regression tests; -run ``pytest tests/integration/test_tpc_checkpoint.py`` for CSV-to-LSTM coverage. +run the opt-in command below for CSV-to-LSTM coverage. Optional decay input -------------------- @@ -60,3 +60,61 @@ trains two synthetic LSTM configurations and evaluates each at three removal rates. It reports MAD and explicitly named log1p-MSE in days. The latter is not the original paper's log-MSE. These synthetic results demonstrate execution only. Set ``PYHEALTH_RUN_TPC_INTEGRATION=1`` to enable the slow integration test. + +Reproducing and extending the example +------------------------------------ + +Use a repository checkout and Python 3.12 or 3.13. Install the package and +pytest in an isolated environment, then run these commands from the repository +root (no credentialed data is needed):: + + python -m pip install -e . pytest + python -m pytest tests/core/test_tpc_eicu.py -q --durations=5 + PYHEALTH_RUN_TPC_INTEGRATION=1 python -m pytest tests/integration/test_tpc_checkpoint.py -q + python -m examples.tpc_support.checkpoint --output /tmp/tpc_checkpoint.json + python -m examples.eicu_hourly_los_lstm --steps 3 --output /tmp/tpc_ablation.json + python examples/tpc_support/generate_synthetic.py /tmp/tpc_synthetic + +The synthetic generator, numerical expectations, model update checks, and +sample experiment use ``examples/tpc_support``. The rich CSV integration check +starts a local processing server and is intentionally opt-in. The regular core +checks use in-memory synthetic events. Import time is separate from the small +per-test execution time; the entire process is not guaranteed below one second. + +Input contract for another training script: + +* One sample per stay. Split on ``patient_id`` (unique person), not ``stay_id``. +* ``dynamic`` has ``time=1..H`` and ``values`` of shape ``(H, 48)``; + ``H=min(floor(total stay hours), 336)``. Values are raw with NaN gaps. +* ``static`` has one record at time zero, ordered as age, sex, height, weight. +* ``los`` has times ``5..H`` and values of shape ``(H-4, 1)`` in hours. + Exact-discharge labels may be zero. Remaining LOS is not capped at 336. +* ``decay`` is optional, with the same times and dimensions as dynamic; + enable it with ``include_decay=True`` and include it in model embeddings. +* Use ``RNN_V2(..., rnn_type="LSTM")`` explicitly: its default is GRU. +* Fit processors on training patients and reuse them on validation/test data. + ``set_task(..., split=...)`` is appropriate for the full dataset path. +* The inherited label processor min-max scales targets during training. + Its activated predictions are returned in original hours; do not unscale + ``y_prob`` a second time. Convert both predictions and targets to days when + comparing daily errors. Define a zero-target policy before using log(y), + MAPE or other metrics that cannot accept zero targets. + +The example's ``run`` function implements the two training-removal conditions +and three test-removal conditions. To run a real experiment, replace its +synthetic generation and hard-coded patient IDs with an authorized dataset +and patient-disjoint train/validation/test split. Keep initialization, test +masks and preprocessing policies controlled across conditions. Add repeated +seeds, final training settings and paper-compatible metrics before making +performance claims. The three-step synthetic example is not a final study. + +This task implements the hourly prediction problem rather than the TPC model. +Differences include the YAIB feature set, completed floor bins with median +aggregation, training-fitted z-score preprocessing and default scaled-MSE +training. Missingness is applied to aggregated hourly cells. The proposed +extension is the training/test missingness grid; merely removing decay repeats +an ablation already present in the original paper. + +Cached task samples from versions with start-of-bin timestamps must be +regenerated. Rerun the core and integration checks after changing extraction, +labels, missingness, processor schemas or the model interface. diff --git a/examples/eicu_hourly_los_lstm.py b/examples/eicu_hourly_los_lstm.py index 36b79c3026..dc743c2553 100644 --- a/examples/eicu_hourly_los_lstm.py +++ b/examples/eicu_hourly_los_lstm.py @@ -13,7 +13,15 @@ Default MSE on train-scaled targets, not the paper's logarithmic loss. MAD in days; log1p-MSE in days is explicitly not the paper's log-MSE metric. This runnable example checks experimental wiring only; clinical results and -novelty claims require A's real-data experiment and team review. +novelty claims require a real-data experiment and review. + +Recorded synthetic findings (seed 42, three steps): all six configurations +produced 336 finite predictions; MAD was approximately 9.46 days. Training on +one 12.5-hour stay and testing on a 400.5-hour stay creates severe distribution +shift. These results do not support a robustness conclusion. Detailed values +are in examples/tpc_support/synthetic_ablation.json. Raw activated predictions +are converted to days for MAD; negatives are counted and clipped only for +log1p-MSE. No patient appears in both training and held-out data. """ import argparse diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py index cbe9e2fae7..103a82c2e8 100644 --- a/pyhealth/tasks/tpc_eicu.py +++ b/pyhealth/tasks/tpc_eicu.py @@ -34,6 +34,14 @@ class TPCLengthOfStayEICU(YAIBLengthOfStayEICU): seed: Seed combined with each stay ID for repeatable masking. include_decay: Add a separate 48-channel decay series. Defaults to False for compatibility with the team prototype. + Examples: + >>> from pyhealth.tasks import TPCLengthOfStayEICU + >>> task = TPCLengthOfStayEICU(missing_rate=0.1, include_decay=True) + >>> task.START_HOUR, task.MAX_HOURS + (5, 336) + >>> "decay" in task.input_schema + True + """ task_name: str = "TPCLengthOfStayEICU" From 8bb5ebba37caec5341c206105b993548b9d9ee52 Mon Sep 17 00:00:00 2001 From: xiaoluo0916 Date: Tue, 17 Nov 2026 21:30:15 -0800 Subject: [PATCH 18/50] Apply repository lint rules to hourly task --- pyhealth/tasks/tpc_eicu.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py index 103a82c2e8..7becdadda5 100644 --- a/pyhealth/tasks/tpc_eicu.py +++ b/pyhealth/tasks/tpc_eicu.py @@ -6,14 +6,14 @@ Reuses YAIB extraction; adds five-hour cohort, masking and optional decay. """ -from copy import deepcopy import hashlib +from copy import deepcopy from typing import Any, ClassVar import numpy as np import polars as pl -from .yaib_eicu import YAIBLengthOfStayEICU, _DYNAMIC_FEATURES +from .yaib_eicu import _DYNAMIC_FEATURES, YAIBLengthOfStayEICU class TPCLengthOfStayEICU(YAIBLengthOfStayEICU): @@ -145,7 +145,7 @@ def _apply_missingness(self, values: np.ndarray, stay_id: Any) -> np.ndarray: if n_hide == 0: return values - key = f"{self.seed}:{stay_id}".encode("utf-8") + key = f"{self.seed}:{stay_id}".encode() stay_seed = int.from_bytes(hashlib.sha256(key).digest()[:8], "little") rng = np.random.default_rng(stay_seed) From e2cd976658852610965f8f634e4461c73bc95203 Mon Sep 17 00:00:00 2001 From: xiaoluo0916 Date: Tue, 17 Nov 2026 21:40:30 -0800 Subject: [PATCH 19/50] Leave explicit preprocessing and training extension points --- docs/api/tasks/pyhealth.tasks.tpc_eicu.rst | 174 +++++++----------- examples/eicu_hourly_los_lstm.py | 162 ++++------------ examples/tpc_support/checkpoint.py | 81 +------- examples/tpc_support/checkpoint_result.json | 28 --- examples/tpc_support/default_validation.txt | 8 - .../tpc_support/integration_validation.txt | 12 -- examples/tpc_support/synthetic_ablation.json | 68 ------- examples/tpc_support/validation.txt | 24 --- pyhealth/tasks/tpc_eicu.py | 82 +++------ tests/core/test_tpc_eicu.py | 30 ++- tests/integration/test_tpc_checkpoint.py | 8 +- 11 files changed, 164 insertions(+), 513 deletions(-) delete mode 100644 examples/tpc_support/checkpoint_result.json delete mode 100644 examples/tpc_support/default_validation.txt delete mode 100644 examples/tpc_support/integration_validation.txt delete mode 100644 examples/tpc_support/synthetic_ablation.json delete mode 100644 examples/tpc_support/validation.txt diff --git a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst index 1f83a494ff..83932e604f 100644 --- a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst +++ b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst @@ -5,116 +5,78 @@ Hourly remaining ICU length of stay :members: :show-inheritance: -Use ``TPCLengthOfStayEICU(missing_rate=0.1, seed=42)`` with ``eICUDataset``. -Load lab, vitalperiodic, vitalaperiodic, intakeoutput, respiratorycharting, -and nursecharting. Use ``set_task(task, split=...)`` to fit processors on -training patients only. Use RNN_V2 for sequence_v2 and hourly regression. - -The cohort includes known adults (age >= 18) with ICU stay >= 5 hours. -The privacy-preserving age value ``> 89`` is encoded as 90. Missing age is -excluded. Unknown sex and invalid admission height/weight remain missing. - -The label at hour h is total ICU stay in hours minus h. Prediction times -are 5 through min(floor(total stay hours), 336), inclusive. This explicitly -includes a zero label at exact discharge. The observation horizon is capped; -remaining LOS is not. Convert predictions and targets to days for comparison -with the paper. Never silently mix hourly and daily metrics. - -This task reuses YAIB's 48 dynamic and 4 static features. It is a partial -reproduction of the task in https://arxiv.org/abs/2007.09483, not the full TPC -architecture or exact original feature set. Observation removal occurs after -hourly aggregation, before processor imputation. Forward filling and training -normalization are inherited; optional paper-formula decay is described below. - -Run ``pytest tests/core/test_tpc_eicu.py`` for fast synthetic regression tests; -run the opt-in command below for CSV-to-LSTM coverage. - -Optional decay input --------------------- - -Set ``include_decay=True`` to add a separate ``decay`` sequence with 48 values -per hour. It is zero before any observation, one when observed, and -``1 / (gap_hours * 4/3)`` afterwards, following the authors' decay formula. -It is calculated after observation removal and is not standardized. Add the -``decay`` field to the RNN_V2 embedding configuration. The default remains -False for compatibility with the team prototype. - -The runnable synthetic checkpoint is -``python -m examples.tpc_support.checkpoint``. It exercises CSV loading, task -processing, train-only processor fitting, an LSTM update, and held-out -inference. This is an integration check, not a clinical performance study. - -Timing correction (November 17 audit): array row b represents the interval -[b,b+1) and is timestamped b+1, when that bin is complete. A prediction at -hour 5 uses only bins 0–4. The 336-hour cap yields 336 rows, not 337. -The oracle's hour/bin numbers identify array rows, not availability timestamps. -Exact-boundary observations at minute 300 enter bin 5, available at hour 6. -This conservative floor-bin convention differs from the paper's right-closed -resampling, but prevents sub-hour look-ahead. - -Missingness example +Implementation status +--------------------- + +The baseline implements adult/five-hour eligibility, admission static features, +hourly remaining-LOS labels and synthetic CSV validation. Dynamic extraction +uses existing YAIB helpers provisionally. This is a partial contribution under +active integration, not a final training/ablation implementation. + +``TPCLengthOfStayEICU()`` works with zero observation removal and no decay. +Nonzero ``missing_rate`` and ``include_decay=True`` deliberately raise +``NotImplementedError`` when samples are processed, rather than silently +producing unimplemented results. + +Extension points +---------------- + +* ``TODO(B)`` in ``pyhealth/tasks/tpc_eicu.py``: review dynamic feature coverage + and hourly aggregation, implement reproducible observation removal before + imputation, confirm training-only normalization/forward fill, and implement + decay after removal. Confirm raw-row versus aggregated-cell removal. +* ``TODO(A)`` in ``examples/eicu_hourly_los_lstm.py``: implement explicit LSTM + training, patient-disjoint splits, agreed losses/metrics and the two-training + by three-test missingness study. This file is a scaffold and raises until + implemented. The example filename is present but the rubric's working + ablation requirement is still outstanding. +* Disabled preprocessing contract tests in ``tests/core/test_tpc_eicu.py`` + retain numerical expectations. Enable and revise these after the shared + interface is confirmed. Skipped tests are pending work, not passing coverage. +* Extend the integration check with actual model training when the training + implementation is available. Its current scope ends at CSV-to-task outputs. + +Runnable validation ------------------- -``python -m examples.eicu_hourly_los_lstm --output /tmp/tpc_ablation.json`` -trains two synthetic LSTM configurations and evaluates each at three removal -rates. It reports MAD and explicitly named log1p-MSE in days. The latter is -not the original paper's log-MSE. These synthetic results demonstrate execution -only. Set ``PYHEALTH_RUN_TPC_INTEGRATION=1`` to enable the slow integration test. - -Reproducing and extending the example ------------------------------------- - -Use a repository checkout and Python 3.12 or 3.13. Install the package and -pytest in an isolated environment, then run these commands from the repository -root (no credentialed data is needed):: +From a repository checkout in Python 3.12 or 3.13:: python -m pip install -e . pytest + python examples/tpc_support/generate_synthetic.py /tmp/tpc_synthetic + python -m examples.tpc_support.checkpoint --output /tmp/tpc_checkpoint.json python -m pytest tests/core/test_tpc_eicu.py -q --durations=5 PYHEALTH_RUN_TPC_INTEGRATION=1 python -m pytest tests/integration/test_tpc_checkpoint.py -q - python -m examples.tpc_support.checkpoint --output /tmp/tpc_checkpoint.json - python -m examples.eicu_hourly_los_lstm --steps 3 --output /tmp/tpc_ablation.json - python examples/tpc_support/generate_synthetic.py /tmp/tpc_synthetic - -The synthetic generator, numerical expectations, model update checks, and -sample experiment use ``examples/tpc_support``. The rich CSV integration check -starts a local processing server and is intentionally opt-in. The regular core -checks use in-memory synthetic events. Import time is separate from the small -per-test execution time; the entire process is not guaranteed below one second. - -Input contract for another training script: - -* One sample per stay. Split on ``patient_id`` (unique person), not ``stay_id``. -* ``dynamic`` has ``time=1..H`` and ``values`` of shape ``(H, 48)``; - ``H=min(floor(total stay hours), 336)``. Values are raw with NaN gaps. -* ``static`` has one record at time zero, ordered as age, sex, height, weight. -* ``los`` has times ``5..H`` and values of shape ``(H-4, 1)`` in hours. - Exact-discharge labels may be zero. Remaining LOS is not capped at 336. -* ``decay`` is optional, with the same times and dimensions as dynamic; - enable it with ``include_decay=True`` and include it in model embeddings. -* Use ``RNN_V2(..., rnn_type="LSTM")`` explicitly: its default is GRU. -* Fit processors on training patients and reuse them on validation/test data. - ``set_task(..., split=...)`` is appropriate for the full dataset path. -* The inherited label processor min-max scales targets during training. - Its activated predictions are returned in original hours; do not unscale - ``y_prob`` a second time. Convert both predictions and targets to days when - comparing daily errors. Define a zero-target policy before using log(y), - MAPE or other metrics that cannot accept zero targets. - -The example's ``run`` function implements the two training-removal conditions -and three test-removal conditions. To run a real experiment, replace its -synthetic generation and hard-coded patient IDs with an authorized dataset -and patient-disjoint train/validation/test split. Keep initialization, test -masks and preprocessing policies controlled across conditions. Add repeated -seeds, final training settings and paper-compatible metrics before making -performance claims. The three-step synthetic example is not a final study. - -This task implements the hourly prediction problem rather than the TPC model. -Differences include the YAIB feature set, completed floor bins with median -aggregation, training-fitted z-score preprocessing and default scaled-MSE -training. Missingness is applied to aggregated hourly cells. The proposed -extension is the training/test missingness grid; merely removing decay repeats -an ablation already present in the original paper. -Cached task samples from versions with start-of-bin timestamps must be -regenerated. Rerun the core and integration checks after changing extraction, -labels, missingness, processor schemas or the model interface. +All seven generated CSVs use invented records across five patients. The +checkpoint verifies cohort selection, static values, aggregated measurements +and remaining-LOS labels against independent numerical expectations. It does +not train a model. The real loader check starts a local processing server and +is opt-in. Core assertion execution is fast; imports still add startup time. + +Input/output contract to review +------------------------------ + +Load lab, vitalperiodic, vitalaperiodic, intakeoutput, respiratorycharting and +nursecharting using eICUDataset. One sample is produced per eligible stay: + +* Adults have known age >=18 and total ICU stay >=5 hours; ``> 89`` maps to 90. + Unknown age excludes the stay. Unknown sex or invalid height/weight is NaN. +* Static features are age, sex (male=1, female=0), admission height and weight. +* Dynamic uses 48 YAIB features. For H=min(floor(total LOS hours),336), its + values have shape (H,48), with missing values retained as NaN. +* Bin [b,b+1) becomes available at timestamp b+1. At hour 5 the model may + consume bins 0–4 only. Regenerate older cached samples with start-bin times. +* Labels at hours 5..H have shape (H-4,1) and equal total LOS hours minus h. + Exact-discharge labels may be zero. The observation horizon is capped; + remaining LOS is not capped. +* Planned decay mirrors dynamic dimensions/times. Existing schema wiring is + provisional until preprocessing review. +* Split by patient_id rather than stay_id. Fit learned processors on training + patients only. Existing YAIB label processors min-max scale training targets; + activated predictions return original hours. Avoid double unscaling. + +This reproduces the prediction problem, not the TPC architecture. Existing +median/floor aggregation and YAIB features differ from the paper. Confirm +preprocessing, loss and metric conventions before comparing paper results. +The original paper already ablates decay removal; a decay toggle alone is +not a novel extension for the assignment. diff --git a/examples/eicu_hourly_los_lstm.py b/examples/eicu_hourly_los_lstm.py index dc743c2553..1abb7bd342 100644 --- a/examples/eicu_hourly_los_lstm.py +++ b/examples/eicu_hourly_los_lstm.py @@ -1,139 +1,49 @@ -"""Synthetic missingness ablation for the hourly LOS task. +"""Training and ablation extension points for the hourly ICU LOS task. Contributor: Xiao Luo; UIUC NetID: xiaoluo6. Paper: Temporal Pointwise Convolutional Networks for Length of Stay Prediction in the Intensive Care Unit, https://arxiv.org/abs/2007.09483. -Run from the repository root: - python -m examples.eicu_hourly_los_lstm --output /tmp/tpc_ablation.json +STATUS: scaffold. This file does not yet train a model or report results. +The runnable data/task check is: + python -m examples.tpc_support.checkpoint -Five invented patients; 101 trains, 103/105 test, 102/104 are excluded. -Two LSTMs train on 0%/10% removed hourly cells; both evaluate at 0%/10%/20%. -Shared initialization and test masks; processors fit on each training variant. -Default MSE on train-scaled targets, not the paper's logarithmic loss. -MAD in days; log1p-MSE in days is explicitly not the paper's log-MSE metric. -This runnable example checks experimental wiring only; clinical results and -novelty claims require a real-data experiment and review. - -Recorded synthetic findings (seed 42, three steps): all six configurations -produced 336 finite predictions; MAD was approximately 9.46 days. Training on -one 12.5-hour stay and testing on a 400.5-hour stay creates severe distribution -shift. These results do not support a robustness conclusion. Detailed values -are in examples/tpc_support/synthetic_ablation.json. Raw activated predictions -are converted to days for MAD; negatives are counted and clipped only for -log1p-MSE. No patient appears in both training and held-out data. +TODO(A): implement patient-disjoint splits, training, metrics and the 2x3 +missingness experiment below. Use the fixture generator for smoke checks; +use authorized eICU data for final findings. TODO(B): implement nonzero +missingness and decay in TPCLengthOfStayEICU before enabling those settings. """ -import argparse -import json -from pathlib import Path -import tempfile -import numpy as np -import torch -from pyhealth.datasets import eICUDataset, create_sample_dataset, get_dataloader -from pyhealth.models import RNN_V2 -from pyhealth.tasks import TPCLengthOfStayEICU -from examples.tpc_support.generate_synthetic import TABLES, generate +from typing import Any + + +def train_and_evaluate() -> list[dict[str, Any]]: + """Run the final experiment once the extension points are complete. + + TODO(A): + 1. Load eICUDataset; split unique patient IDs into train/validation/test. + 2. Fit processors on training patients only; reuse on held-out patients. + 3. Explicitly select RNN_V2(rnn_type="LSTM") and agreed input embeddings. + 4. Train with 0% and 10% extra observation removal, keeping other + settings controlled. Evaluate each at 0%, 10%, and 20% removal. + 5. Reuse test masks for both models; use seeded, documented repeats. + 6. Return metrics and experimental settings. Raw targets/activated + predictions are hours; convert together for day-based comparisons. + Specify a zero-target policy and paper-compatible MSLE convention. + 7. Document measured findings and differences from the original paper. + Returns: + One result dictionary per experimental configuration. -def run(steps: int = 3) -> list[dict]: - """Run the six synthetic configurations and return measured metrics.""" - if steps < 1: - raise ValueError("steps must be positive") - torch.set_num_threads(1) - results = [] - with tempfile.TemporaryDirectory(prefix="tpc-ablation-") as temporary: - root = Path(temporary) - generate(root / "csv") - data = eICUDataset( - root=str(root / "csv"), tables=TABLES, cache_dir=root / "cache" - ) - patients = { - sid: data.get_patient(f"synthetic-{sid}") for sid in (101, 103, 105) - } - for train_rate in (0.0, 0.1): - torch.manual_seed(42) - task = TPCLengthOfStayEICU(train_rate, seed=42, include_decay=True) - train = create_sample_dataset( - task(patients[101]), task.input_schema, task.output_schema - ) - model = RNN_V2( - train, - embedding_dim={ - "dynamic": [{"values": 8}], - "static": [{"values": 4}], - "decay": [{"values": 8}], - }, - hidden_dim=8, - rnn_type="LSTM", - mask="concat", - ) - optimizer = torch.optim.Adam(model.parameters(), lr=0.001) - batch = next(iter(get_dataloader(train, batch_size=1, shuffle=False))) - for _ in range(steps): - optimizer.zero_grad() - loss = model(**batch)["loss"] - if not torch.isfinite(loss): - raise RuntimeError("Nonfinite training loss") - loss.backward() - optimizer.step() - model.eval() - for test_rate in (0.0, 0.1, 0.2): - evaluation_task = TPCLengthOfStayEICU( - test_rate, seed=42, include_decay=True - ) - samples = [evaluation_task(patients[sid])[0] for sid in (103, 105)] - evaluation = create_sample_dataset( - samples, - task.input_schema, - task.output_schema, - input_processors=train.input_processors, - output_processors=train.output_processors, - ) - with torch.no_grad(): - out = model( - **next( - iter( - get_dataloader(evaluation, batch_size=2, shuffle=False) - ) - ) - ) - # activation() reverses label normalization; y_prob is in hours. - pred = out["y_prob"].numpy().reshape(-1) / 24 - truth = ( - np.concatenate( - [np.asarray(s["los"]["values"]).ravel() for s in samples] - ) - / 24 - ) - if not np.isfinite(pred).all() or pred.shape != truth.shape: - raise RuntimeError("Invalid predictions") - results.append( - { - "train_missing_rate": train_rate, - "test_missing_rate": test_rate, - "mad_days": float(np.abs(pred - truth).mean()), - "log1p_mse_days": float( - ( - (np.log1p(np.maximum(pred, 0)) - np.log1p(truth)) ** 2 - ).mean() - ), - "negative_predictions_clipped_for_log1p": int((pred < 0).sum()), - "prediction_count": len(truth), - "steps": steps, - "seed": 42, - "data": "synthetic; not evidence of clinical performance", - } - ) - return results + Raises: + NotImplementedError: Until the training implementation is supplied. + """ + raise NotImplementedError( + "TODO(A): implement training and ablations; " + "TODO(B): complete missingness/decay. " + "Run python -m examples.tpc_support.checkpoint for data/task validation." + ) if __name__ == "__main__": - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--steps", type=int, default=3) - parser.add_argument("--output", type=Path, required=True) - args = parser.parse_args() - results = run(args.steps) - args.output.parent.mkdir(parents=True, exist_ok=True) - args.output.write_text(json.dumps(results, indent=2) + "\n") - print(json.dumps(results, indent=2)) + train_and_evaluate() diff --git a/examples/tpc_support/checkpoint.py b/examples/tpc_support/checkpoint.py index 19aba85839..3efaa573e1 100644 --- a/examples/tpc_support/checkpoint.py +++ b/examples/tpc_support/checkpoint.py @@ -1,28 +1,24 @@ # Contributor: Xiao Luo, UIUC NetID xiaoluo6. # Paper: Temporal Pointwise Convolutional Networks for Length of Stay # Prediction in the Intensive Care Unit. https://arxiv.org/abs/2007.09483 -"""Synthetic CSV-to-LSTM checkpoint; no clinical performance claims.""" +"""Synthetic CSV-to-task checkpoint for cohort, static features and labels.""" from pathlib import Path import json import tempfile import numpy as np -import torch -from pyhealth.datasets import eICUDataset, create_sample_dataset, get_dataloader -from pyhealth.models import RNN_V2 +from pyhealth.datasets import eICUDataset from pyhealth.tasks import TPCLengthOfStayEICU from examples.tpc_support.generate_synthetic import generate, TABLES def run(root: Path) -> dict: - """Generate data, check numerical expectations, and train one LSTM step.""" - torch.manual_seed(42) - torch.set_num_threads(1) + """Generate data and validate numerical cohort, feature and label expectations.""" generate(root / "csv") source = eICUDataset( root=str(root / "csv"), tables=TABLES, cache_dir=root / "cache" ) - task = TPCLengthOfStayEICU(include_decay=True) + task = TPCLengthOfStayEICU() samples = {} for sid in (101, 102, 103, 104, 105): out = task(source.get_patient(f"synthetic-{sid}")) @@ -58,79 +54,20 @@ def value(hour, name): np.testing.assert_allclose( short["los"]["values"], [[7.5], [6.5], [5.5], [4.5], [3.5], [2.5], [1.5], [0.5]] ) - np.testing.assert_allclose( - short["decay"]["values"][:6, names.index("hr")], [1, 0.75, 1, 0.75, 0.375, 1] - ) - np.testing.assert_allclose( - short["decay"]["values"][:6, names.index("k")], [0, 1, 0.75, 0.375, 1, 0.75] - ) assert samples[103]["los"]["time"][-1] == 336 assert samples[103]["los"]["values"][-1] == [64.5] assert samples[103]["dynamic"]["values"][0, names.index("hr")] == 100 assert np.isnan(samples[105]["static"]["values"][0][2]) - # Split BEFORE fitting: the high-valued long stay is held out. - train = create_sample_dataset([samples[101]], task.input_schema, task.output_schema) - heldout = create_sample_dataset( - [samples[103], samples[105]], - task.input_schema, - task.output_schema, - input_processors=train.input_processors, - output_processors=train.output_processors, - ) - train_before = train[0]["dynamic"][0].clone() - assert torch.isfinite(heldout[0]["dynamic"][0]).all() - torch.testing.assert_close(train_before, train[0]["dynamic"][0]) - # Same training processors must be reused, not refitted on held-out patients. - assert heldout.input_processors["dynamic"] is train.input_processors["dynamic"] - model = RNN_V2( - train, - embedding_dim={ - "dynamic": [{"values": 8}], - "static": [{"values": 4}], - "decay": [{"values": 8}], - }, - hidden_dim=8, - rnn_type="LSTM", - mask="concat", - ) - assert any(isinstance(m, torch.nn.LSTM) for m in model.modules()) - batch = next(iter(get_dataloader(train, batch_size=1, shuffle=False))) - optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) - before = [p.detach().clone() for p in model.parameters()] - out = model(**batch) - assert out["logit"].shape[0] == 8 - assert torch.isfinite(out["loss"]) - optimizer.zero_grad() - out["loss"].backward() - gradients = [p.grad for p in model.parameters() if p.grad is not None] - assert gradients and all(torch.isfinite(g).all() for g in gradients) - assert any(torch.count_nonzero(g) for g in gradients) - optimizer.step() - assert any(not torch.equal(a, b) for a, b in zip(before, model.parameters())) - model.eval() - with torch.no_grad(): - evaluation = model( - **next(iter(get_dataloader(heldout, batch_size=2, shuffle=False))) - ) - assert torch.isfinite(evaluation["loss"]) - assert evaluation["logit"].shape[0] == 332 + 4 + # TODO(A): downstream model validation belongs in the training + # example once preprocessing and the agreed input interface are complete. return { "status": "passed", + "scope": "CSV loading, cohort, static features, hourly labels", "synthetic_patients": 5, "included_stays": [101, 103, 105], "excluded_stays": [102, 104], - "train_patient": 101, - "heldout_patients": [103, 105], - "training_labels": 8, - "heldout_labels": 336, - "model": "RNN_V2 / LSTM", - "decay_enabled": True, - "optimizer_steps": 1, - "finite_nonzero_gradients": True, - "parameters_changed": True, - "training_loss": float(out["loss"].detach()), - "heldout_loss": float(evaluation["loss"]), - "interpretation": "Synthetic integration check only; not model performance evidence.", + "model_training": "pending training integration", + "missingness_and_decay": "pending preprocessing integration", } diff --git a/examples/tpc_support/checkpoint_result.json b/examples/tpc_support/checkpoint_result.json deleted file mode 100644 index 3a4951a28c..0000000000 --- a/examples/tpc_support/checkpoint_result.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "status": "passed", - "synthetic_patients": 5, - "included_stays": [ - 101, - 103, - 105 - ], - "excluded_stays": [ - 102, - 104 - ], - "train_patient": 101, - "heldout_patients": [ - 103, - 105 - ], - "training_labels": 8, - "heldout_labels": 336, - "model": "RNN_V2 / LSTM", - "decay_enabled": true, - "optimizer_steps": 1, - "finite_nonzero_gradients": true, - "parameters_changed": true, - "training_loss": 0.16046194732189178, - "heldout_loss": 1232.579833984375, - "interpretation": "Synthetic integration check only; not model performance evidence." -} diff --git a/examples/tpc_support/default_validation.txt b/examples/tpc_support/default_validation.txt deleted file mode 100644 index 4d2bf11eec..0000000000 --- a/examples/tpc_support/default_validation.txt +++ /dev/null @@ -1,8 +0,0 @@ -...........................s [100%] -============================= slowest 5 durations ============================== -0.05s call tests/core/test_tpc_eicu.py::test_cohort[4.99-60-False] -0.02s call tests/core/test_tpc_eicu.py::test_static_features -0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0] -0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0.1] -0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0.2] -27 passed, 1 skipped in 21.62s diff --git a/examples/tpc_support/integration_validation.txt b/examples/tpc_support/integration_validation.txt deleted file mode 100644 index 5adba88c98..0000000000 --- a/examples/tpc_support/integration_validation.txt +++ /dev/null @@ -1,12 +0,0 @@ -. [100%] -=============================== warnings summary =============================== -tests/integration/test_tpc_checkpoint.py::test_csv_to_lstm - pyhealth/datasets/sample_dataset.py:208: FutureWarning: SequenceProcessorV2 and the 'sequence_v2' processor name are deprecated and will be removed in a future release; use JaggedFeatureProcessor and 'jagged', which behave identically. - return get_processor(spec)(**kwargs) - --- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html -============================= slowest 5 durations ============================== -4.31s call tests/integration/test_tpc_checkpoint.py::test_csv_to_lstm - -(2 durations < 0.005s hidden. Use -vv to show these durations.) -1 passed, 1 warning in 10.62s diff --git a/examples/tpc_support/synthetic_ablation.json b/examples/tpc_support/synthetic_ablation.json deleted file mode 100644 index 6ed7696e8d..0000000000 --- a/examples/tpc_support/synthetic_ablation.json +++ /dev/null @@ -1,68 +0,0 @@ -[ - { - "train_missing_rate": 0.0, - "test_missing_rate": 0.0, - "mad_days": 9.460000805117907, - "log1p_mse_days": 5.254549188824514, - "negative_predictions_clipped_for_log1p": 0, - "prediction_count": 336, - "steps": 3, - "seed": 42, - "data": "synthetic; not evidence of clinical performance" - }, - { - "train_missing_rate": 0.0, - "test_missing_rate": 0.1, - "mad_days": 9.459250288324373, - "log1p_mse_days": 5.251212770591288, - "negative_predictions_clipped_for_log1p": 0, - "prediction_count": 336, - "steps": 3, - "seed": 42, - "data": "synthetic; not evidence of clinical performance" - }, - { - "train_missing_rate": 0.0, - "test_missing_rate": 0.2, - "mad_days": 9.459990731395212, - "log1p_mse_days": 5.254490411380583, - "negative_predictions_clipped_for_log1p": 0, - "prediction_count": 336, - "steps": 3, - "seed": 42, - "data": "synthetic; not evidence of clinical performance" - }, - { - "train_missing_rate": 0.1, - "test_missing_rate": 0.0, - "mad_days": 9.45968699748979, - "log1p_mse_days": 5.253154022093286, - "negative_predictions_clipped_for_log1p": 0, - "prediction_count": 336, - "steps": 3, - "seed": 42, - "data": "synthetic; not evidence of clinical performance" - }, - { - "train_missing_rate": 0.1, - "test_missing_rate": 0.1, - "mad_days": 9.459092536646438, - "log1p_mse_days": 5.250509753547508, - "negative_predictions_clipped_for_log1p": 0, - "prediction_count": 336, - "steps": 3, - "seed": 42, - "data": "synthetic; not evidence of clinical performance" - }, - { - "train_missing_rate": 0.1, - "test_missing_rate": 0.2, - "mad_days": 9.459677495843074, - "log1p_mse_days": 5.253098513868501, - "negative_predictions_clipped_for_log1p": 0, - "prediction_count": 336, - "steps": 3, - "seed": 42, - "data": "synthetic; not evidence of clinical performance" - } -] diff --git a/examples/tpc_support/validation.txt b/examples/tpc_support/validation.txt deleted file mode 100644 index 60bfa5a759..0000000000 --- a/examples/tpc_support/validation.txt +++ /dev/null @@ -1,24 +0,0 @@ -............................ [100%] -=============================== warnings summary =============================== -tests/integration/test_tpc_checkpoint.py::test_csv_to_lstm - pyhealth/datasets/sample_dataset.py:208: FutureWarning: SequenceProcessorV2 and the 'sequence_v2' processor name are deprecated and will be removed in a future release; use JaggedFeatureProcessor and 'jagged', which behave identically. - return get_processor(spec)(**kwargs) - --- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html -============================= slowest 30 durations ============================= -5.13s call tests/integration/test_tpc_checkpoint.py::test_csv_to_lstm -0.07s call tests/core/test_tpc_eicu.py::test_cohort[4.99-60-False] -0.02s call tests/core/test_tpc_eicu.py::test_static_features -0.02s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0] -0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0.1] -0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[1] -0.01s call tests/core/test_tpc_eicu.py::test_combined_mask_fill_and_decay[0.2] -0.01s call tests/core/test_tpc_eicu.py::test_hourly_measurements_and_missing_data -0.01s call tests/core/test_tpc_eicu.py::test_future_observations_do_not_change_earlier_hours -0.01s call tests/core/test_tpc_eicu.py::test_labels_and_horizon -0.01s call tests/core/test_tpc_eicu.py::test_stays_are_isolated -0.01s call tests/core/test_tpc_eicu.py::test_incomplete_hour_cannot_enter_prediction -0.01s call tests/core/test_tpc_eicu.py::test_cohort[5-18-True] - -(17 durations < 0.005s hidden. Use -vv to show these durations.) -28 passed, 1 warning in 13.47s diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py index 7becdadda5..2199f21daf 100644 --- a/pyhealth/tasks/tpc_eicu.py +++ b/pyhealth/tasks/tpc_eicu.py @@ -3,10 +3,9 @@ UIUC NetID: xiaoluo6. Paper: Temporal Pointwise Convolutional Networks for Length of Stay Prediction in the Intensive Care Unit, https://arxiv.org/abs/2007.09483. -Reuses YAIB extraction; adds five-hour cohort, masking and optional decay. +Implements five-hour cohort and labels; exposes preprocessing extension points. """ -import hashlib from copy import deepcopy from typing import Any, ClassVar @@ -27,20 +26,22 @@ class TPCLengthOfStayEICU(YAIBLengthOfStayEICU): Dynamic timestamps mark completed bins: bin [h-1,h) is available at h. Remaining LOS is not clipped to 14 days. Dynamic values remain raw with NaNs; sequence_v2 processors fit normalization on training patients and - forward-fill after observation masking. Optional decay is a separate input. + forward-fill using inherited YAIB processors. Nonzero missingness and decay + are explicit placeholders pending preprocessing implementation. Args: - missing_rate: Fraction of observed hourly cells hidden, in [0, 1]. + missing_rate: Planned removal fraction in [0, 1]. Only 0 works until + the preprocessing extension point is implemented. seed: Seed combined with each stay ID for repeatable masking. - include_decay: Add a separate 48-channel decay series. Defaults to - False for compatibility with the team prototype. + include_decay: Planned separate 48-channel decay series. Leave False + until the preprocessing extension point is implemented. Examples: >>> from pyhealth.tasks import TPCLengthOfStayEICU - >>> task = TPCLengthOfStayEICU(missing_rate=0.1, include_decay=True) + >>> task = TPCLengthOfStayEICU() >>> task.START_HOUR, task.MAX_HOURS (5, 336) - >>> "decay" in task.input_schema - True + >>> task.missing_rate + 0.0 """ @@ -95,66 +96,33 @@ def _base_cohort( and static[stay_id][0] >= 18 ] stays = stays.filter(pl.col("stay_id").is_in(keep)) + # TODO(B): review feature coverage and aggregation. This + # existing YAIB path is a provisional baseline, not a new implementation. hourly = self._hourly(self._measurements(patient, stays, _DYNAMIC_FEATURES)) return stays, hourly, {key: static[key] for key in keep} @staticmethod def _decay(values: np.ndarray) -> np.ndarray: - """Compute causal observation recency after masking. + """Extension point for observation-recency features. - Reimplements the original TPC preprocessing formula: 0 before the - first observation, 1 when observed, 1 / (gap * 4/3) afterwards. - Source: EmmaRocheteau/TPC-LoS-prediction/eICU_preprocessing/timeseries.py. - No forward-looking information or cross-stay state is used. - - Args: - values: Masked hourly matrix, with NaN for absent observations. - - Returns: - A finite matrix of the same shape containing observation recency. + TODO(B): implement after agreeing on the decay formula. + Expected shape equals values.shape; compute AFTER observation removal, + separately per stay. Do not read future values. """ - result = np.zeros_like(values, dtype=float) - last = np.full(values.shape[1], -1, dtype=int) - for hour, row in enumerate(values): - observed = np.isfinite(row) - last[observed] = hour - seen = last >= 0 - gap = hour - last[seen] - result[hour, seen] = 1.0 / np.maximum(1.0, gap * (4.0 / 3.0)) - return result + raise NotImplementedError( + "TODO(B): implement _decay before include_decay=True." + ) def _apply_missingness(self, values: np.ndarray, stay_id: Any) -> np.ndarray: - """Randomly hide a fraction of originally observed values. + """Extension point for reproducible observation removal. - Args: - values: Raw hourly matrix, with NaN for missing cells. - stay_id: Stable identifier used to seed this stay's removal mask. - - Returns: - A copy with round(observed_count * missing_rate) cells set to NaN. - The input matrix and originally missing cells are unchanged. + TODO(B): implement seeded masking for nonzero rates before + imputation. Agree whether removal applies to raw rows or hourly cells. + The zero-removal baseline returns an independent unchanged copy. """ - values = values.copy() - if self.missing_rate == 0.0: - return values - - observed = np.argwhere(~np.isnan(values)) - n_hide = round(len(observed) * self.missing_rate) - - if n_hide == 0: - return values - - key = f"{self.seed}:{stay_id}".encode() - stay_seed = int.from_bytes(hashlib.sha256(key).digest()[:8], "little") - rng = np.random.default_rng(stay_seed) - - selected = rng.choice(len(observed), size=n_hide, replace=False) - - rows, cols = observed[selected].T - values[rows, cols] = np.nan - - return values + return values.copy() + raise NotImplementedError("TODO(B): implement masking before missing_rate > 0.") def __call__(self, patient: Any) -> list[dict[str, Any]]: """Generate hourly ICU samples with uncapped remaining LOS labels. diff --git a/tests/core/test_tpc_eicu.py b/tests/core/test_tpc_eicu.py index 57783359f6..7eeec856b3 100644 --- a/tests/core/test_tpc_eicu.py +++ b/tests/core/test_tpc_eicu.py @@ -56,6 +56,7 @@ def test_fractional_remaining_hours(): assert _labels(sample["los"]) == [1.5, 0.5] +@pytest.mark.skip(reason="TODO(B): enable after masking/fill/decay integration") def test_missingness_count_repeatability_no_mutation(): values = np.arange(20, dtype=float).reshape(5, 4) values[0, 0] = np.nan @@ -77,6 +78,7 @@ def test_invalid_rate(rate): TPCLengthOfStayEICU(rate) +@pytest.mark.skip(reason="TODO(B): enable after masking/fill/decay integration") def test_hourly_measurements_and_missing_data(): task = TPCLengthOfStayEICU() p = _patient( @@ -93,6 +95,7 @@ def test_hourly_measurements_and_missing_data(): assert masked["static"] == sample["static"] +@pytest.mark.skip(reason="TODO(B): enable after masking/fill/decay integration") def test_forward_fill_after_removal(): from pyhealth.processors import JaggedFeatureProcessor @@ -116,6 +119,7 @@ def test_forward_fill_after_removal(): np.testing.assert_allclose(proc.process(removed)[0].reshape(-1).numpy(), [80] * 4) +@pytest.mark.skip(reason="TODO(B): enable after masking/fill/decay integration") def test_decay_oracle_and_full_removal(): raw = np.array( [[np.nan, 80], [4, np.nan], [np.nan, 100], [np.nan, np.nan], [3, np.nan]], @@ -133,10 +137,10 @@ def test_decay_optional_schema_does_not_mutate_other_instances(): def test_future_observations_do_not_change_earlier_hours(): - task = TPCLengthOfStayEICU(include_decay=True) + task = TPCLengthOfStayEICU() first = task(_patient(hours=12, hr_hours=[0, 2]))[0] future = task(_patient(hours=12, hr_hours=[0, 2, 10]))[0] - for field in ["dynamic", "decay"]: + for field in ["dynamic"]: np.testing.assert_equal( first[field]["values"][:10], future[field]["values"][:10] ) @@ -146,14 +150,13 @@ def test_stays_are_isolated(): from pyhealth.data import Patient from tests.core.tpc_fixtures import _frame, _stay_rows - task = TPCLengthOfStayEICU(include_decay=True) + task = TPCLengthOfStayEICU() rows = _stay_rows(10, 8, hr_hours=[0]) + _stay_rows(11, 8, hr_hours=[]) samples = { s["stay_id"]: s for s in task(Patient(patient_id="same-patient", data_source=_frame(rows))) } - assert samples[10]["decay"]["values"].any() - assert not samples[11]["decay"]["values"].any() + assert np.isfinite(samples[10]["dynamic"]["values"]).any() assert np.isnan(samples[11]["dynamic"]["values"]).all() @@ -167,6 +170,7 @@ def test_empty_patient(): @pytest.mark.parametrize("rate", [0, 0.1, 0.2, 1]) +@pytest.mark.skip(reason="TODO(B): enable after masking/fill/decay integration") def test_combined_mask_fill_and_decay(rate): from pyhealth.processors import JaggedFeatureProcessor @@ -204,13 +208,12 @@ def test_combined_mask_fill_and_decay(rate): def test_incomplete_hour_cannot_enter_prediction(): - task = TPCLengthOfStayEICU(include_decay=True) + task = TPCLengthOfStayEICU() baseline = task(_patient(hours=8, hr_hours=[]))[0] changed = task(_patient(hours=8, hr_hours=[], extra=[_lab(359, "potassium", 5)]))[0] for sample in [baseline, changed]: assert sample["dynamic"]["time"] == list(range(1, 9)) - assert sample["decay"]["time"] == sample["dynamic"]["time"] - for field in ["dynamic", "decay"]: + for field in ["dynamic"]: times = np.asarray(changed[field]["time"]) np.testing.assert_equal( baseline[field]["values"][times <= 5], changed[field]["values"][times <= 5] @@ -218,3 +221,14 @@ def test_incomplete_hour_cannot_enter_prediction(): k = task.DYNAMIC_FEATURES.index("k") assert changed["dynamic"]["values"][5, k] == 5 assert changed["dynamic"]["time"][5] == 6 + + +def test_zero_removal_baseline_and_unfinished_extensions(): + raw = np.array([[80.0, np.nan]]) + result = TPCLengthOfStayEICU()._apply_missingness(raw, 10) + np.testing.assert_equal(raw, result) + assert not np.shares_memory(raw, result) + with pytest.raises(NotImplementedError, match="TODO"): + TPCLengthOfStayEICU(0.1)._apply_missingness(raw, 10) + with pytest.raises(NotImplementedError, match="TODO"): + TPCLengthOfStayEICU._decay(raw) diff --git a/tests/integration/test_tpc_checkpoint.py b/tests/integration/test_tpc_checkpoint.py index 5d4d4622bc..0a86485606 100644 --- a/tests/integration/test_tpc_checkpoint.py +++ b/tests/integration/test_tpc_checkpoint.py @@ -1,7 +1,7 @@ # Contributor: Xiao Luo, UIUC NetID xiaoluo6. # Paper: Temporal Pointwise Convolutional Networks for Length of Stay # Prediction in the Intensive Care Unit. https://arxiv.org/abs/2007.09483 -"""Opt-in real loader/training smoke check; fast task tests live in core. +"""Opt-in real CSV loader/task smoke check; fast task tests live in core. Set PYHEALTH_RUN_TPC_INTEGRATION=1 to run this slower local-server check. """ @@ -13,9 +13,9 @@ @pytest.mark.skipif( os.environ.get("PYHEALTH_RUN_TPC_INTEGRATION") != "1", - reason="Opt-in CSV/Dask/LSTM check; set PYHEALTH_RUN_TPC_INTEGRATION=1", + reason="Opt-in CSV/Dask/task check; set PYHEALTH_RUN_TPC_INTEGRATION=1", ) -def test_csv_to_lstm(tmp_path): +def test_csv_to_task(tmp_path): result = run(tmp_path) assert result["status"] == "passed" - assert result["parameters_changed"] + assert result["scope"] == "CSV loading, cohort, static features, hourly labels" From d6e569cf462e94502d419b89beda0fdb854d34c3 Mon Sep 17 00:00:00 2001 From: xiaoluo0916 Date: Tue, 17 Nov 2026 21:57:22 -0800 Subject: [PATCH 20/50] Clarify placeholders should reuse existing team implementations --- docs/api/tasks/pyhealth.tasks.tpc_eicu.rst | 12 ++++++++---- examples/eicu_hourly_los_lstm.py | 8 +++++--- pyhealth/tasks/tpc_eicu.py | 12 ++++++++---- 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst index 83932e604f..809f3b3b21 100644 --- a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst +++ b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst @@ -22,10 +22,14 @@ Extension points ---------------- * ``TODO(B)`` in ``pyhealth/tasks/tpc_eicu.py``: review dynamic feature coverage - and hourly aggregation, implement reproducible observation removal before - imputation, confirm training-only normalization/forward fill, and implement - decay after removal. Confirm raw-row versus aggregated-cell removal. -* ``TODO(A)`` in ``examples/eicu_hourly_los_lstm.py``: implement explicit LSTM + and hourly aggregation, confirm training-only normalization/forward fill, + and integrate decay after removal. For masking, A/B should reuse the existing + ``_apply_missingness`` in the repository-root ``tpc_eicu.py`` prototype after + checking compatibility. It already implements seeded removal of hourly cells; + this placeholder is an integration boundary, not a request to write it again. + Confirm raw-row versus aggregated-cell removal and rerun the pending tests. +* ``TODO(A)`` in ``examples/eicu_hourly_los_lstm.py``: integrate existing training + work where available and complete explicit LSTM training, patient-disjoint splits, agreed losses/metrics and the two-training by three-test missingness study. This file is a scaffold and raises until implemented. The example filename is present but the rubric's working diff --git a/examples/eicu_hourly_los_lstm.py b/examples/eicu_hourly_los_lstm.py index 1abb7bd342..7a4343734f 100644 --- a/examples/eicu_hourly_los_lstm.py +++ b/examples/eicu_hourly_los_lstm.py @@ -8,10 +8,12 @@ The runnable data/task check is: python -m examples.tpc_support.checkpoint -TODO(A): implement patient-disjoint splits, training, metrics and the 2x3 +TODO(A): integrate existing code for splits, training, metrics and the 2x3 missingness experiment below. Use the fixture generator for smoke checks; -use authorized eICU data for final findings. TODO(B): implement nonzero -missingness and decay in TPCLengthOfStayEICU before enabling those settings. +use authorized eICU data for final findings. TODO(A/B): reuse the masking +implementation in repository-root tpc_eicu.py; integrate preprocessing and +complete decay before enabling those settings. Existing working code should +be merged and validated, not written again. """ from typing import Any diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py index 2199f21daf..d20779dccd 100644 --- a/pyhealth/tasks/tpc_eicu.py +++ b/pyhealth/tasks/tpc_eicu.py @@ -116,13 +116,17 @@ def _decay(values: np.ndarray) -> np.ndarray: def _apply_missingness(self, values: np.ndarray, stay_id: Any) -> np.ndarray: """Extension point for reproducible observation removal. - TODO(B): implement seeded masking for nonzero rates before - imputation. Agree whether removal applies to raw rows or hourly cells. - The zero-removal baseline returns an independent unchanged copy. + TODO(A/B): integrate the existing _apply_missingness implementation + from the repository-root tpc_eicu.py prototype. Do not reimplement + working team code. Confirm its removal unit and seed behavior before + integration; run the pending masking tests afterwards. The zero-removal + baseline returns an independent unchanged copy. """ if self.missing_rate == 0.0: return values.copy() - raise NotImplementedError("TODO(B): implement masking before missing_rate > 0.") + raise NotImplementedError( + "TODO(A/B): integrate existing prototype masking before missing_rate > 0." + ) def __call__(self, patient: Any) -> list[dict[str, Any]]: """Generate hourly ICU samples with uncapped remaining LOS labels. From 8d08fdd3beda9116f087ecc61e4a5462fa6fe01a Mon Sep 17 00:00:00 2001 From: xiaoluo0916 Date: Tue, 17 Nov 2026 22:00:26 -0800 Subject: [PATCH 21/50] Normalize generated CSV line endings for clean diffs --- examples/tpc_support/generate_synthetic.py | 2 +- .../synthetic_eicu/intakeOutput.csv | 22 +++---- examples/tpc_support/synthetic_eicu/lab.csv | 52 ++++++++-------- .../synthetic_eicu/nurseCharting.csv | 12 ++-- .../tpc_support/synthetic_eicu/patient.csv | 12 ++-- .../synthetic_eicu/respiratoryCharting.csv | 12 ++-- .../synthetic_eicu/vitalAperiodic.csv | 12 ++-- .../synthetic_eicu/vitalPeriodic.csv | 62 +++++++++---------- 8 files changed, 93 insertions(+), 93 deletions(-) diff --git a/examples/tpc_support/generate_synthetic.py b/examples/tpc_support/generate_synthetic.py index f181b4aff5..1ed9221146 100644 --- a/examples/tpc_support/generate_synthetic.py +++ b/examples/tpc_support/generate_synthetic.py @@ -134,7 +134,7 @@ def generate(root: Path) -> None: ) ) with (root / cfg["file_path"]).open("w", newline="") as f: - writer = csv.DictWriter(f, fieldnames=fields) + writer = csv.DictWriter(f, fieldnames=fields, lineterminator="\n") writer.writeheader() writer.writerows(values) diff --git a/examples/tpc_support/synthetic_eicu/intakeOutput.csv b/examples/tpc_support/synthetic_eicu/intakeOutput.csv index c9f6b41c50..ab6ccc45dd 100644 --- a/examples/tpc_support/synthetic_eicu/intakeOutput.csv +++ b/examples/tpc_support/synthetic_eicu/intakeOutput.csv @@ -1,11 +1,11 @@ -patientunitstayid,intakeoutputoffset,celllabel,cellvaluenumeric -101,65,Urine,100 -101,95,Urine,50 -102,65,Urine,100 -102,95,Urine,50 -103,65,Urine,100 -103,95,Urine,50 -104,65,Urine,100 -104,95,Urine,50 -105,65,Urine,100 -105,95,Urine,50 +patientunitstayid,intakeoutputoffset,celllabel,cellvaluenumeric +101,65,Urine,100 +101,95,Urine,50 +102,65,Urine,100 +102,95,Urine,50 +103,65,Urine,100 +103,95,Urine,50 +104,65,Urine,100 +104,95,Urine,50 +105,65,Urine,100 +105,95,Urine,50 diff --git a/examples/tpc_support/synthetic_eicu/lab.csv b/examples/tpc_support/synthetic_eicu/lab.csv index cf061d5df8..5ffd9e07b0 100644 --- a/examples/tpc_support/synthetic_eicu/lab.csv +++ b/examples/tpc_support/synthetic_eicu/lab.csv @@ -1,26 +1,26 @@ -patientunitstayid,labresultoffset,labname,labresult,labresulttext,labmeasurenamesystem,labmeasurenameinterface,labtypeid -101,60,potassium,4,,,mmol/L, -101,90,potassium,6,,,mmol/L, -101,240,potassium,3,,,mmol/L, -101,300,potassium,99,,,mmol/L, -101,150,creatinine,1.2,,,mg/dL, -102,60,potassium,4,,,mmol/L, -102,90,potassium,6,,,mmol/L, -102,240,potassium,3,,,mmol/L, -102,300,potassium,99,,,mmol/L, -102,150,creatinine,1.2,,,mg/dL, -103,60,potassium,4,,,mmol/L, -103,90,potassium,6,,,mmol/L, -103,240,potassium,3,,,mmol/L, -103,300,potassium,99,,,mmol/L, -103,150,creatinine,1.2,,,mg/dL, -104,60,potassium,4,,,mmol/L, -104,90,potassium,6,,,mmol/L, -104,240,potassium,3,,,mmol/L, -104,300,potassium,99,,,mmol/L, -104,150,creatinine,1.2,,,mg/dL, -105,60,potassium,4,,,mmol/L, -105,90,potassium,6,,,mmol/L, -105,240,potassium,3,,,mmol/L, -105,300,potassium,99,,,mmol/L, -105,150,creatinine,1.2,,,mg/dL, +patientunitstayid,labresultoffset,labname,labresult,labresulttext,labmeasurenamesystem,labmeasurenameinterface,labtypeid +101,60,potassium,4,,,mmol/L, +101,90,potassium,6,,,mmol/L, +101,240,potassium,3,,,mmol/L, +101,300,potassium,99,,,mmol/L, +101,150,creatinine,1.2,,,mg/dL, +102,60,potassium,4,,,mmol/L, +102,90,potassium,6,,,mmol/L, +102,240,potassium,3,,,mmol/L, +102,300,potassium,99,,,mmol/L, +102,150,creatinine,1.2,,,mg/dL, +103,60,potassium,4,,,mmol/L, +103,90,potassium,6,,,mmol/L, +103,240,potassium,3,,,mmol/L, +103,300,potassium,99,,,mmol/L, +103,150,creatinine,1.2,,,mg/dL, +104,60,potassium,4,,,mmol/L, +104,90,potassium,6,,,mmol/L, +104,240,potassium,3,,,mmol/L, +104,300,potassium,99,,,mmol/L, +104,150,creatinine,1.2,,,mg/dL, +105,60,potassium,4,,,mmol/L, +105,90,potassium,6,,,mmol/L, +105,240,potassium,3,,,mmol/L, +105,300,potassium,99,,,mmol/L, +105,150,creatinine,1.2,,,mg/dL, diff --git a/examples/tpc_support/synthetic_eicu/nurseCharting.csv b/examples/tpc_support/synthetic_eicu/nurseCharting.csv index 528236171d..fc99da8c3b 100644 --- a/examples/tpc_support/synthetic_eicu/nurseCharting.csv +++ b/examples/tpc_support/synthetic_eicu/nurseCharting.csv @@ -1,6 +1,6 @@ -patientunitstayid,nursingchartoffset,nursingchartcelltypevalname,nursingchartvalue -101,240,Temperature (F),98.6 -102,240,Temperature (F),98.6 -103,240,Temperature (F),98.6 -104,240,Temperature (F),98.6 -105,240,Temperature (F),98.6 +patientunitstayid,nursingchartoffset,nursingchartcelltypevalname,nursingchartvalue +101,240,Temperature (F),98.6 +102,240,Temperature (F),98.6 +103,240,Temperature (F),98.6 +104,240,Temperature (F),98.6 +105,240,Temperature (F),98.6 diff --git a/examples/tpc_support/synthetic_eicu/patient.csv b/examples/tpc_support/synthetic_eicu/patient.csv index 150c443681..41e5e67cd9 100644 --- a/examples/tpc_support/synthetic_eicu/patient.csv +++ b/examples/tpc_support/synthetic_eicu/patient.csv @@ -1,6 +1,6 @@ -patientunitstayid,patienthealthsystemstayid,gender,age,ethnicity,hospitalid,wardid,apacheadmissiondx,admissionheight,admissionweight,dischargeweight,hospitaladmittime24,hospitaladmitoffset,hospitaladmitsource,hospitaldischargeyear,hospitaldischargeoffset,hospitaldischargestatus,hospitaldischargetime24,unittype,unitadmittime24,unitadmitsource,unitvisitnumber,unitstaytype,unitdischargeoffset,unitdischargestatus,unitdischargetime24,unitdischargelocation,uniquepid -101,101,Female,18,,1,,,165,65,,,0,,2020,750,Alive,,,,,1,,750,Alive,,,synthetic-101 -102,102,Female,60,,1,,,165,65,,,0,,2020,240,Alive,,,,,1,,240,Alive,,,synthetic-102 -103,103,Male,> 89,,1,,,165,65,,,0,,2020,24030,Alive,,,,,1,,24030,Alive,,,synthetic-103 -104,104,Female,17,,1,,,165,65,,,0,,2020,720,Alive,,,,,1,,720,Alive,,,synthetic-104 -105,105,Female,45,,1,,,,65,,,0,,2020,480,Alive,,,,,1,,480,Alive,,,synthetic-105 +patientunitstayid,patienthealthsystemstayid,gender,age,ethnicity,hospitalid,wardid,apacheadmissiondx,admissionheight,admissionweight,dischargeweight,hospitaladmittime24,hospitaladmitoffset,hospitaladmitsource,hospitaldischargeyear,hospitaldischargeoffset,hospitaldischargestatus,hospitaldischargetime24,unittype,unitadmittime24,unitadmitsource,unitvisitnumber,unitstaytype,unitdischargeoffset,unitdischargestatus,unitdischargetime24,unitdischargelocation,uniquepid +101,101,Female,18,,1,,,165,65,,,0,,2020,750,Alive,,,,,1,,750,Alive,,,synthetic-101 +102,102,Female,60,,1,,,165,65,,,0,,2020,240,Alive,,,,,1,,240,Alive,,,synthetic-102 +103,103,Male,> 89,,1,,,165,65,,,0,,2020,24030,Alive,,,,,1,,24030,Alive,,,synthetic-103 +104,104,Female,17,,1,,,165,65,,,0,,2020,720,Alive,,,,,1,,720,Alive,,,synthetic-104 +105,105,Female,45,,1,,,,65,,,0,,2020,480,Alive,,,,,1,,480,Alive,,,synthetic-105 diff --git a/examples/tpc_support/synthetic_eicu/respiratoryCharting.csv b/examples/tpc_support/synthetic_eicu/respiratoryCharting.csv index 03de0509a2..9cad3d3910 100644 --- a/examples/tpc_support/synthetic_eicu/respiratoryCharting.csv +++ b/examples/tpc_support/synthetic_eicu/respiratoryCharting.csv @@ -1,6 +1,6 @@ -patientunitstayid,respchartoffset,respcharttypecat,respchartvaluelabel,respchartvalue -101,180,,FiO2,40% -102,180,,FiO2,40% -103,180,,FiO2,40% -104,180,,FiO2,40% -105,180,,FiO2,40% +patientunitstayid,respchartoffset,respcharttypecat,respchartvaluelabel,respchartvalue +101,180,,FiO2,40% +102,180,,FiO2,40% +103,180,,FiO2,40% +104,180,,FiO2,40% +105,180,,FiO2,40% diff --git a/examples/tpc_support/synthetic_eicu/vitalAperiodic.csv b/examples/tpc_support/synthetic_eicu/vitalAperiodic.csv index ed2465378d..7fdd26b806 100644 --- a/examples/tpc_support/synthetic_eicu/vitalAperiodic.csv +++ b/examples/tpc_support/synthetic_eicu/vitalAperiodic.csv @@ -1,6 +1,6 @@ -patientunitstayid,observationoffset,noninvasivesystolic,noninvasivediastolic,noninvasivemean -101,180,130,75,90 -102,180,130,75,90 -103,180,130,75,90 -104,180,130,75,90 -105,180,130,75,90 +patientunitstayid,observationoffset,noninvasivesystolic,noninvasivediastolic,noninvasivemean +101,180,130,75,90 +102,180,130,75,90 +103,180,130,75,90 +104,180,130,75,90 +105,180,130,75,90 diff --git a/examples/tpc_support/synthetic_eicu/vitalPeriodic.csv b/examples/tpc_support/synthetic_eicu/vitalPeriodic.csv index 60c895309a..e97a843a8f 100644 --- a/examples/tpc_support/synthetic_eicu/vitalPeriodic.csv +++ b/examples/tpc_support/synthetic_eicu/vitalPeriodic.csv @@ -1,31 +1,31 @@ -patientunitstayid,observationoffset,temperature,sao2,heartrate,respiration,systemicsystolic,systemicdiastolic,systemicmean -101,-60,37,98,250,16,120,70,85 -101,10,37,98,80,16,120,70,85 -101,40,37,98,100,16,120,70,85 -101,120,37,98,110,16,120,70,85 -101,359,37,98,120,16,120,70,85 -101,900,37,98,200,16,120,70,85 -102,-60,37,98,250,16,120,70,85 -102,10,37,98,80,16,120,70,85 -102,40,37,98,100,16,120,70,85 -102,120,37,98,110,16,120,70,85 -102,359,37,98,120,16,120,70,85 -102,900,37,98,200,16,120,70,85 -103,-60,37,98,250,16,120,70,85 -103,10,37,98,90,16,120,70,85 -103,40,37,98,110,16,120,70,85 -103,120,37,98,120,16,120,70,85 -103,359,37,98,130,16,120,70,85 -103,900,37,98,200,16,120,70,85 -104,-60,37,98,250,16,120,70,85 -104,10,37,98,80,16,120,70,85 -104,40,37,98,100,16,120,70,85 -104,120,37,98,110,16,120,70,85 -104,359,37,98,120,16,120,70,85 -104,900,37,98,200,16,120,70,85 -105,-60,37,98,250,16,120,70,85 -105,10,37,98,80,16,120,70,85 -105,40,37,98,100,16,120,70,85 -105,120,37,98,110,16,120,70,85 -105,359,37,98,120,16,120,70,85 -105,900,37,98,200,16,120,70,85 +patientunitstayid,observationoffset,temperature,sao2,heartrate,respiration,systemicsystolic,systemicdiastolic,systemicmean +101,-60,37,98,250,16,120,70,85 +101,10,37,98,80,16,120,70,85 +101,40,37,98,100,16,120,70,85 +101,120,37,98,110,16,120,70,85 +101,359,37,98,120,16,120,70,85 +101,900,37,98,200,16,120,70,85 +102,-60,37,98,250,16,120,70,85 +102,10,37,98,80,16,120,70,85 +102,40,37,98,100,16,120,70,85 +102,120,37,98,110,16,120,70,85 +102,359,37,98,120,16,120,70,85 +102,900,37,98,200,16,120,70,85 +103,-60,37,98,250,16,120,70,85 +103,10,37,98,90,16,120,70,85 +103,40,37,98,110,16,120,70,85 +103,120,37,98,120,16,120,70,85 +103,359,37,98,130,16,120,70,85 +103,900,37,98,200,16,120,70,85 +104,-60,37,98,250,16,120,70,85 +104,10,37,98,80,16,120,70,85 +104,40,37,98,100,16,120,70,85 +104,120,37,98,110,16,120,70,85 +104,359,37,98,120,16,120,70,85 +104,900,37,98,200,16,120,70,85 +105,-60,37,98,250,16,120,70,85 +105,10,37,98,80,16,120,70,85 +105,40,37,98,100,16,120,70,85 +105,120,37,98,110,16,120,70,85 +105,359,37,98,120,16,120,70,85 +105,900,37,98,200,16,120,70,85 From 7f88f5f5efc21ac1868ad2dbbba138b93d049dde Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 14:24:01 -0800 Subject: [PATCH 22/50] Delete tpc_eicu.py --- tpc_eicu.py | 167 ---------------------------------------------------- 1 file changed, 167 deletions(-) delete mode 100644 tpc_eicu.py diff --git a/tpc_eicu.py b/tpc_eicu.py deleted file mode 100644 index 3c7de5ae48..0000000000 --- a/tpc_eicu.py +++ /dev/null @@ -1,167 +0,0 @@ -""" -Author: Manling Tan, Yining Jin, Xiao Luo -NetID: manling4, yining34, xiaoluo6 - -Paper Title: -Temporal Pointwise Convolutional Networks for -Length of Stay Prediction in the Intensive Care Unit - -Paper Authors: -Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) - -Paper URL: -https://arxiv.org/abs/2007.09483 -""" - - -import hashlib -from typing import Any, ClassVar - -import numpy as np - -from .yaib_eicu import YAIBLengthOfStayEICU - - -class TPCLengthOfStayEICU(YAIBLengthOfStayEICU): - """Predict hourly remaining ICU length of stay using eICU data. - - Extends YAIBLengthOfStayEICU to generate hourly remaining - length-of-stay labels and support random observation masking. - - Dynamic observations are retained from hour 0, while predictions - start at hour 5 and continue for up to 14 days. - - Args: - missing_rate (float): Fraction of observed dynamic feature - values to randomly mask. Defaults to 0.0. - seed (int): Random seed for reproducible masking. - Defaults to 42. - """ - - task_name: str = "TPCLengthOfStayEICU" - MAX_HOURS: ClassVar[int] = 14 * 24 - START_HOUR: ClassVar[int] = 5 - - def __init__(self, missing_rate: float = 0.0, seed: int = 42): - """Initialize the task with missingness settings. - - Args: - missing_rate (float): Fraction of observed dynamic feature - values to randomly mask, between 0.0 and 1.0. - Defaults to 0.0. - seed (int): Random seed used for reproducible masking. - Defaults to 42. - - Raises: - ValueError: If missing_rate is outside [0.0, 1.0]. - """ - if not 0.0 <= missing_rate <= 1.0: - raise ValueError("missing_rate must be between 0 and 1.") - - self.missing_rate = missing_rate - self.seed = seed - - def _apply_missingness(self, values: np.ndarray, stay_id: Any) -> np.ndarray: - """Randomly mask a fraction of observed feature values with NaN. - - Masking is deterministic for each ICU stay based on the - configured seed and stay identifier. Originally missing - values are excluded from the masking selection. - - Args: - values (np.ndarray): Array of hourly dynamic feature values. - stay_id (Any): ICU stay identifier used to derive the - random seed. - - Returns: - np.ndarray: A copy of the input array with selected - observed values replaced by NaN. - """ - values = values.copy() - - if self.missing_rate == 0.0: - return values - - observed = np.argwhere(~np.isnan(values)) - n_hide = round(len(observed) * self.missing_rate) - - if n_hide == 0: - return values - - key = f"{self.seed}:{stay_id}".encode("utf-8") - stay_seed = int.from_bytes(hashlib.sha256(key).digest()[:8], "little") - rng = np.random.default_rng(stay_seed) - - selected = rng.choice(len(observed), size=n_hide, replace=False) - - rows, cols = observed[selected].T - values[rows, cols] = np.nan - - return values - - def __call__(self, patient: Any) -> list[dict[str, Any]]: - """Generate hourly ICU length-of-stay prediction samples. - - Extracts hourly dynamic and static features for eligible ICU - stays. Dynamic observations are retained from hour 0, and - random observation masking is applied when configured. - - Remaining length-of-stay labels are generated for each - prediction hour, starting at hour 5 and continuing up to - the maximum observation horizon. - - Args: - patient (Any): PyHealth patient object containing - ICU stay information and associated measurements. - - Returns: - list[dict[str, Any]]: A list of prediction samples. - Each sample contains: - - patient_id: Patient identifier. - - stay_id: ICU stay identifier. - - dynamic: Hourly dynamic feature observations. - - static: Static patient features. - - los: Hourly remaining length-of-stay labels. - - Returns an empty list if no eligible ICU stays exist. - """ - all_stays = self._stays(patient) - - if all_stays.height == 0: - return [] - - stays, hourly, static = self._base_cohort(patient, all_stays) - - samples = [] - - for stay_id, los_hours, end in stays.select( - "stay_id", "los_hours", "end" - ).iter_rows(): - if end < self.START_HOUR: - continue - - last_hour = min(end, self.MAX_HOURS) - - dynamic = self._dynamic(hourly, stay_id, last_hour) - - # Keep all observations from hour 0 onward. - dynamic["values"] = self._apply_missingness(dynamic["values"], stay_id) - - prediction_hours = [ - float(hour) for hour in range(self.START_HOUR, last_hour + 1) - ] - - remaining = [max(0.0, float(los_hours) - hour) for hour in prediction_hours] - - samples.append( - { - "patient_id": patient.patient_id, - "stay_id": stay_id, - "dynamic": dynamic, - "static": self._static_series(static[stay_id]), - "los": self._labels(prediction_hours, remaining), - } - ) - - return samples - From b3b11862bc7df577e8ba3a48b008a41d4ef7869e Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 14:17:28 -0800 Subject: [PATCH 23/50] Update tpc_eicu.py --- pyhealth/tasks/tpc_eicu.py | 191 ++++++++++++++++++++++--------------- 1 file changed, 114 insertions(+), 77 deletions(-) diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py index d20779dccd..73f185ce67 100644 --- a/pyhealth/tasks/tpc_eicu.py +++ b/pyhealth/tasks/tpc_eicu.py @@ -1,11 +1,20 @@ -"""Hourly remaining-LOS task, contributed by Xiao Luo. +"""Hourly remaining ICU length-of-stay task with missingness experiments. -UIUC NetID: xiaoluo6. -Paper: Temporal Pointwise Convolutional Networks for Length of Stay -Prediction in the Intensive Care Unit, https://arxiv.org/abs/2007.09483. -Implements five-hour cohort and labels; exposes preprocessing extension points. +Authors: Manling Tan, Yining Jin, Xiao Luo +NetIDs: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) + +Paper URL: +https://arxiv.org/abs/2007.09483 """ +import hashlib from copy import deepcopy from typing import Any, ClassVar @@ -16,33 +25,22 @@ class TPCLengthOfStayEICU(YAIBLengthOfStayEICU): - """Hourly remaining ICU stay prediction inspired by Rocheteau et al. + """Generate hourly remaining-LOS labels for eICU stays. - Paper: https://arxiv.org/abs/2007.09483. This is a standalone task, not a TPC model implementation. Static features - are age, sex (male=1, female=0), admission height and weight, inherited - from YAIB. Unknown sex and invalid height/weight remain NaN. - Labels are HOURS, from hour 5 through min(floor(LOS), 336), inclusive. - Dynamic timestamps mark completed bins: bin [h-1,h) is available at h. - Remaining LOS is not clipped to 14 days. Dynamic values remain raw with - NaNs; sequence_v2 processors fit normalization on training patients and - forward-fill using inherited YAIB processors. Nonzero missingness and decay - are explicit placeholders pending preprocessing implementation. + are inherited from YAIB. Labels are in hours, starting at hour 5 and + continuing through min(floor(LOS), 336). Dynamic timestamps represent + completed hourly bins: bin [h-1, h) is available at hour h. - Args: - missing_rate: Planned removal fraction in [0, 1]. Only 0 works until - the preprocessing extension point is implemented. - seed: Seed combined with each stay ID for repeatable masking. - include_decay: Planned separate 48-channel decay series. Leave False - until the preprocessing extension point is implemented. - Examples: - >>> from pyhealth.tasks import TPCLengthOfStayEICU - >>> task = TPCLengthOfStayEICU() - >>> task.START_HOUR, task.MAX_HOURS - (5, 336) - >>> task.missing_rate - 0.0 + Dynamic measurements remain raw with NaNs at task creation. Inherited + sequence_v2 processors handle normalization and forward-fill downstream. + Missingness is applied to observed values before those processors; decay + is computed from the post-masking, pre-forward-fill observation matrix. + Args: + missing_rate: Fraction of observed feature cells to mask, in [0, 1]. + seed: Seed combined with stay ID for reproducible masking. + include_decay: Whether to add per-feature observation-recency series. """ task_name: str = "TPCLengthOfStayEICU" @@ -52,7 +50,7 @@ class TPCLengthOfStayEICU(YAIBLengthOfStayEICU): def __init__( self, missing_rate: float = 0.0, seed: int = 42, include_decay: bool = False ) -> None: - """Configure random observation masking.""" + """Configure masking and optional observation-recency features.""" if not 0.0 <= missing_rate <= 1.0: raise ValueError("missing_rate must be between 0 and 1.") @@ -73,18 +71,14 @@ def __init__( def _base_cohort( self, patient: Any, stays: pl.DataFrame ) -> tuple[pl.DataFrame, pl.DataFrame, dict[int, list[float]]]: - """Keep known adults with at least five hours; allow sparse records. - - YAIB's six-hour and measurement-density exclusions do not implement - this project's cohort. Missing age is excluded conservatively. + """Keep known adults with at least five ICU hours and sparse records. Args: - patient: PyHealth patient containing eICU events. - stays: Parsed stays with stay_id and los_hours columns. + patient: PyHealth patient with eICU events. + stays: Parsed stay records with stay_id and los_hours columns. Returns: - Eligible stays, aggregated measurements, and static features - indexed by stay ID. + Eligible stays, hourly measurements, and static features by stay. """ static = self._static(patient, stays) keep = [ @@ -96,49 +90,88 @@ def _base_cohort( and static[stay_id][0] >= 18 ] stays = stays.filter(pl.col("stay_id").is_in(keep)) - # TODO(B): review feature coverage and aggregation. This - # existing YAIB path is a provisional baseline, not a new implementation. + + # TODO: verify Table 16 feature coverage and hourly aggregation + # against the project requirements; this uses the YAIB baseline. hourly = self._hourly(self._measurements(patient, stays, _DYNAMIC_FEATURES)) + return stays, hourly, {key: static[key] for key in keep} @staticmethod def _decay(values: np.ndarray) -> np.ndarray: - """Extension point for observation-recency features. + """Compute elapsed hourly bins since each feature's last observation. + + For an observed cell, decay is zero. Missing cells after an observation + count elapsed hours since that observation. Before the first observed + value, missing cells count 1, 2, 3, ... (a convention to verify with + the team's decay tests). Compute this on masked, non-forward-filled data. - TODO(B): implement after agreeing on the decay formula. - Expected shape equals values.shape; compute AFTER observation removal, - separately per stay. Do not read future values. + Args: + values: Two-dimensional hourly feature array containing NaNs. + + Returns: + Float array of the same shape containing hours since observation. """ - raise NotImplementedError( - "TODO(B): implement _decay before include_decay=True." - ) + if values.ndim != 2: + raise ValueError("values must be a 2D (hours, features) array") + + n_hours, n_features = values.shape + decay = np.zeros((n_hours, n_features), dtype=float) + + for feature in range(n_features): + last_observed = None + + for hour in range(n_hours): + if not np.isnan(values[hour, feature]): + last_observed = hour + elif last_observed is None: + decay[hour, feature] = float(hour + 1) + else: + decay[hour, feature] = float(hour - last_observed) + + return decay def _apply_missingness(self, values: np.ndarray, stay_id: Any) -> np.ndarray: - """Extension point for reproducible observation removal. + """Randomly mask observed feature cells reproducibly for each ICU stay. - TODO(A/B): integrate the existing _apply_missingness implementation - from the repository-root tpc_eicu.py prototype. Do not reimplement - working team code. Confirm its removal unit and seed behavior before - integration; run the pending masking tests afterwards. The zero-removal - baseline returns an independent unchanged copy. + Args: + values: Hourly dynamic feature matrix, with NaNs for missing data. + stay_id: ICU stay identifier used to derive a stable random seed. + + Returns: + Copy of values with selected observed cells replaced by NaN. """ + values = values.copy() + if self.missing_rate == 0.0: - return values.copy() - raise NotImplementedError( - "TODO(A/B): integrate existing prototype masking before missing_rate > 0." - ) + return values + + observed = np.argwhere(~np.isnan(values)) + n_hide = round(len(observed) * self.missing_rate) + + if n_hide == 0: + return values + + key = f"{self.seed}:{stay_id}".encode("utf-8") + stay_seed = int.from_bytes(hashlib.sha256(key).digest()[:8], "little") + rng = np.random.default_rng(stay_seed) + + selected = rng.choice(len(observed), size=n_hide, replace=False) + + rows, cols = observed[selected].T + values[rows, cols] = np.nan + + return values def __call__(self, patient: Any) -> list[dict[str, Any]]: - """Generate hourly ICU samples with uncapped remaining LOS labels. + """Return per-stay hourly dynamic/static inputs and remaining-LOS labels. Args: - patient: PyHealth patient with eICU admission and measurement events. + patient: PyHealth patient containing eICU stays and measurements. Returns: - One dictionary per eligible stay containing patient_id, stay_id, - dynamic, static, los, and optional decay series. Returns an empty - list when no eligible stays exist. Dynamic/decay time marks bin - completion; los time marks the prediction hour. Labels are hours. + Samples containing patient_id, stay_id, dynamic, static, los, + and optionally decay. Returns an empty list for no eligible stays. """ all_stays = self._stays(patient) @@ -157,34 +190,38 @@ def __call__(self, patient: Any) -> list[dict[str, Any]]: last_hour = min(end, self.MAX_HOURS) - # Bin b contains offsets [60*b, 60*(b+1)); it is only - # available at b+1. Never expose an unfinished bin at label h. + # Bin b covers [60*b, 60*(b+1)) and becomes available at b+1. dynamic = self._dynamic(hourly, stay_id, last_hour - 1) dynamic["time"] = [float(h) for h in range(1, last_hour + 1)] - # Keep all observations from hour 0 onward. - dynamic["values"] = self._apply_missingness(dynamic["values"], stay_id) + dynamic["values"] = self._apply_missingness( + dynamic["values"], stay_id + ) prediction_hours = [ float(hour) for hour in range(self.START_HOUR, last_hour + 1) ] - remaining = [max(0.0, float(los_hours) - hour) for hour in prediction_hours] + remaining = [ + max(0.0, float(los_hours) - hour) + for hour in prediction_hours + ] - samples.append( - { - "patient_id": patient.patient_id, - "stay_id": stay_id, - "dynamic": dynamic, - "static": self._static_series(static[stay_id]), - "los": self._labels(prediction_hours, remaining), - } - ) + sample = { + "patient_id": patient.patient_id, + "stay_id": stay_id, + "dynamic": dynamic, + "static": self._static_series(static[stay_id]), + "los": self._labels(prediction_hours, remaining), + } if self.include_decay: - samples[-1]["decay"] = { + sample["decay"] = { "time": list(dynamic["time"]), "values": self._decay(dynamic["values"]), } + samples.append(sample) + return samples + From 4830d49f3cdf3d14d561666b6ae3b28df792c524 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 14:35:32 -0800 Subject: [PATCH 24/50] Update tpc_eicu.py --- pyhealth/tasks/tpc_eicu.py | 229 ++++++++++++++++++++++++++----------- 1 file changed, 162 insertions(+), 67 deletions(-) diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py index 73f185ce67..cf3a6598fb 100644 --- a/pyhealth/tasks/tpc_eicu.py +++ b/pyhealth/tasks/tpc_eicu.py @@ -27,183 +27,272 @@ class TPCLengthOfStayEICU(YAIBLengthOfStayEICU): """Generate hourly remaining-LOS labels for eICU stays. - This is a standalone task, not a TPC model implementation. Static features - are inherited from YAIB. Labels are in hours, starting at hour 5 and - continuing through min(floor(LOS), 336). Dynamic timestamps represent - completed hourly bins: bin [h-1, h) is available at hour h. + This is a standalone task, not a TPC model implementation. - Dynamic measurements remain raw with NaNs at task creation. Inherited - sequence_v2 processors handle normalization and forward-fill downstream. - Missingness is applied to observed values before those processors; decay - is computed from the post-masking, pre-forward-fill observation matrix. + Static features are inherited from YAIB. Labels are in hours, + starting at hour 5 and continuing through min(floor(LOS), 336). + + Dynamic timestamps represent completed hourly bins: + bin [h-1, h) is available at hour h. + + Dynamic measurements remain raw with NaNs at task creation. + Inherited sequence_v2 processors handle normalization and + forward-fill downstream. + + Missingness is applied to observed values before processing. + Decay is computed from the post-masking, pre-forward-fill + observation matrix. Args: - missing_rate: Fraction of observed feature cells to mask, in [0, 1]. + missing_rate: Fraction of observed feature cells to mask, + between 0 and 1. seed: Seed combined with stay ID for reproducible masking. - include_decay: Whether to add per-feature observation-recency series. + include_decay: Whether to add per-feature decay sequences. """ task_name: str = "TPCLengthOfStayEICU" + MAX_HOURS: ClassVar[int] = 14 * 24 START_HOUR: ClassVar[int] = 5 def __init__( - self, missing_rate: float = 0.0, seed: int = 42, include_decay: bool = False + self, + missing_rate: float = 0.0, + seed: int = 42, + include_decay: bool = False, ) -> None: - """Configure masking and optional observation-recency features.""" + """Configure masking and optional decay features.""" + if not 0.0 <= missing_rate <= 1.0: raise ValueError("missing_rate must be between 0 and 1.") self.missing_rate = missing_rate self.seed = seed - self.input_schema = deepcopy(type(self).input_schema) self.include_decay = include_decay + + self.input_schema = deepcopy(type(self).input_schema) + if include_decay: self.input_schema["decay"] = ( "sequence_v2", { "levels": [ - {"ordering": "series", "values": [len(self.DYNAMIC_FEATURES)]} + { + "ordering": "series", + "values": [len(self.DYNAMIC_FEATURES)], + } ] }, ) def _base_cohort( - self, patient: Any, stays: pl.DataFrame + self, + patient: Any, + stays: pl.DataFrame, ) -> tuple[pl.DataFrame, pl.DataFrame, dict[int, list[float]]]: - """Keep known adults with at least five ICU hours and sparse records. + """Select eligible adult ICU stays. Args: patient: PyHealth patient with eICU events. - stays: Parsed stay records with stay_id and los_hours columns. + stays: Parsed ICU stay records. Returns: - Eligible stays, hourly measurements, and static features by stay. + Eligible stays, hourly measurements, and static features. """ + static = self._static(patient, stays) + keep = [ stay_id - for stay_id, hours in stays.select("stay_id", "los_hours").iter_rows() + for stay_id, hours in stays.select( + "stay_id", "los_hours" + ).iter_rows() if np.isfinite(hours) and hours >= self.START_HOUR and np.isfinite(static[stay_id][0]) and static[stay_id][0] >= 18 ] + stays = stays.filter(pl.col("stay_id").is_in(keep)) - # TODO: verify Table 16 feature coverage and hourly aggregation - # against the project requirements; this uses the YAIB baseline. - hourly = self._hourly(self._measurements(patient, stays, _DYNAMIC_FEATURES)) + # TODO: Verify Table 16 feature coverage and hourly + # aggregation against the project requirements. + hourly = self._hourly( + self._measurements( + patient, + stays, + _DYNAMIC_FEATURES, + ) + ) - return stays, hourly, {key: static[key] for key in keep} + return stays, hourly, { + key: static[key] for key in keep + } @staticmethod def _decay(values: np.ndarray) -> np.ndarray: - """Compute elapsed hourly bins since each feature's last observation. + """Compute exponentially decaying observation indicators. + + An observed value resets its decay indicator to 1. + Each subsequent missing hour multiplies the previous + indicator by 0.75. - For an observed cell, decay is zero. Missing cells after an observation - count elapsed hours since that observation. Before the first observed - value, missing cells count 1, 2, 3, ... (a convention to verify with - the team's decay tests). Compute this on masked, non-forward-filled data. + Features with no previous observations remain at 0. + + Decay is computed before forward-fill so that artificially + imputed values do not count as new observations. Args: - values: Two-dimensional hourly feature array containing NaNs. + values: Two-dimensional hourly feature matrix + containing NaNs for missing observations. Returns: - Float array of the same shape containing hours since observation. + Float array of the same shape with decay indicators. """ + if values.ndim != 2: - raise ValueError("values must be a 2D (hours, features) array") + raise ValueError( + "values must be a 2D (hours, features) array" + ) n_hours, n_features = values.shape - decay = np.zeros((n_hours, n_features), dtype=float) - for feature in range(n_features): - last_observed = None + decay = np.zeros( + (n_hours, n_features), + dtype=float, + ) + + for hour in range(n_hours): + observed = ~np.isnan(values[hour]) - for hour in range(n_hours): - if not np.isnan(values[hour, feature]): - last_observed = hour - elif last_observed is None: - decay[hour, feature] = float(hour + 1) - else: - decay[hour, feature] = float(hour - last_observed) + if hour > 0: + decay[hour] = 0.75 * decay[hour - 1] + + decay[hour, observed] = 1.0 return decay - def _apply_missingness(self, values: np.ndarray, stay_id: Any) -> np.ndarray: - """Randomly mask observed feature cells reproducibly for each ICU stay. + def _apply_missingness( + self, + values: np.ndarray, + stay_id: Any, + ) -> np.ndarray: + """Randomly mask observed cells reproducibly for each stay. Args: - values: Hourly dynamic feature matrix, with NaNs for missing data. - stay_id: ICU stay identifier used to derive a stable random seed. + values: Hourly dynamic feature matrix. + stay_id: ICU stay identifier for deterministic masking. Returns: - Copy of values with selected observed cells replaced by NaN. + Copy of values with selected cells replaced by NaN. """ + values = values.copy() if self.missing_rate == 0.0: return values observed = np.argwhere(~np.isnan(values)) - n_hide = round(len(observed) * self.missing_rate) + + n_hide = round( + len(observed) * self.missing_rate + ) if n_hide == 0: return values key = f"{self.seed}:{stay_id}".encode("utf-8") - stay_seed = int.from_bytes(hashlib.sha256(key).digest()[:8], "little") + + stay_seed = int.from_bytes( + hashlib.sha256(key).digest()[:8], + "little", + ) + rng = np.random.default_rng(stay_seed) - selected = rng.choice(len(observed), size=n_hide, replace=False) + selected = rng.choice( + len(observed), + size=n_hide, + replace=False, + ) rows, cols = observed[selected].T + values[rows, cols] = np.nan return values - def __call__(self, patient: Any) -> list[dict[str, Any]]: - """Return per-stay hourly dynamic/static inputs and remaining-LOS labels. + def __call__( + self, + patient: Any, + ) -> list[dict[str, Any]]: + """Create hourly remaining-LOS samples for eligible stays. Args: - patient: PyHealth patient containing eICU stays and measurements. + patient: PyHealth patient with eICU records. Returns: - Samples containing patient_id, stay_id, dynamic, static, los, - and optionally decay. Returns an empty list for no eligible stays. + Per-stay samples containing patient_id, stay_id, + dynamic, static, los, and optionally decay. """ + all_stays = self._stays(patient) if all_stays.height == 0: return [] - stays, hourly, static = self._base_cohort(patient, all_stays) + stays, hourly, static = self._base_cohort( + patient, + all_stays, + ) samples = [] for stay_id, los_hours, end in stays.select( - "stay_id", "los_hours", "end" + "stay_id", + "los_hours", + "end", ).iter_rows(): + if end < self.START_HOUR: continue - last_hour = min(end, self.MAX_HOURS) + last_hour = min( + end, + self.MAX_HOURS, + ) - # Bin b covers [60*b, 60*(b+1)) and becomes available at b+1. - dynamic = self._dynamic(hourly, stay_id, last_hour - 1) - dynamic["time"] = [float(h) for h in range(1, last_hour + 1)] + # Each hourly bin becomes available only after + # the bin is complete, preventing future leakage. + dynamic = self._dynamic( + hourly, + stay_id, + last_hour - 1, + ) + + dynamic["time"] = [ + float(h) + for h in range(1, last_hour + 1) + ] dynamic["values"] = self._apply_missingness( - dynamic["values"], stay_id + dynamic["values"], + stay_id, ) prediction_hours = [ - float(hour) for hour in range(self.START_HOUR, last_hour + 1) + float(hour) + for hour in range( + self.START_HOUR, + last_hour + 1, + ) ] remaining = [ - max(0.0, float(los_hours) - hour) + max( + 0.0, + float(los_hours) - hour, + ) for hour in prediction_hours ] @@ -211,17 +300,23 @@ def __call__(self, patient: Any) -> list[dict[str, Any]]: "patient_id": patient.patient_id, "stay_id": stay_id, "dynamic": dynamic, - "static": self._static_series(static[stay_id]), - "los": self._labels(prediction_hours, remaining), + "static": self._static_series( + static[stay_id] + ), + "los": self._labels( + prediction_hours, + remaining, + ), } if self.include_decay: sample["decay"] = { "time": list(dynamic["time"]), - "values": self._decay(dynamic["values"]), + "values": self._decay( + dynamic["values"] + ), } samples.append(sample) return samples - From bbce4a4307daf873a2226f64c105981a0b9eafeb Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 14:40:26 -0800 Subject: [PATCH 25/50] Update test_tpc_eicu.py Update TPC eICU tests for missingness and decay --- tests/core/test_tpc_eicu.py | 476 +++++++++++++++++++++++++++++------- 1 file changed, 387 insertions(+), 89 deletions(-) diff --git a/tests/core/test_tpc_eicu.py b/tests/core/test_tpc_eicu.py index 7eeec856b3..ecfa307e4f 100644 --- a/tests/core/test_tpc_eicu.py +++ b/tests/core/test_tpc_eicu.py @@ -1,9 +1,25 @@ -# Contributor: Xiao Luo, UIUC NetID xiaoluo6. -# Paper: Temporal Pointwise Convolutional Networks for Length of Stay -# Prediction in the Intensive Care Unit. https://arxiv.org/abs/2007.09483 -"""Synthetic cohort and hourly-label regression tests. +""" +Author: Manling Tan, Yining Jin, Xiao Luo +NetID: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) -Reference: https://arxiv.org/abs/2007.09483. No clinical records used. +Paper URL: +https://arxiv.org/abs/2007.09483 +""" + +"""Synthetic cohort, hourly-label, and preprocessing regression tests. + +Tests for the TPCLengthOfStayEICU task using synthetic patient data. +No real clinical records are used. + +Coverage includes cohort eligibility, hourly LOS labels, truncation, +missingness, decay, temporal leakage prevention, and stay isolation. """ import numpy as np @@ -27,208 +43,490 @@ ], ) def test_cohort(hours, age, eligible): - samples = TPCLengthOfStayEICU()(_patient(hours=hours, age=age, hr_hours=[])) + """Check adult cohort and minimum ICU stay requirements.""" + samples = TPCLengthOfStayEICU()( + _patient(hours=hours, age=age, hr_hours=[]) + ) assert bool(samples) == eligible def test_static_features(): - sample = TPCLengthOfStayEICU()(_patient(hours=5, age="> 89", gender="Female"))[0] + """Verify static features and invalid-value handling.""" + sample = TPCLengthOfStayEICU()( + _patient(hours=5, age="> 89", gender="Female") + )[0] + assert sample["static"]["values"] == [[90, 0, 180, 80]] + missing = TPCLengthOfStayEICU()( - _patient(hours=5, gender="Unknown", height=-1, weight=999) + _patient( + hours=5, + gender="Unknown", + height=-1, + weight=999, + ) )[0] - assert np.isnan(missing["static"]["values"][0][1:]).all() + + assert np.isnan( + missing["static"]["values"][0][1:] + ).all() def test_labels_and_horizon(): + """Verify hourly remaining LOS and 14-day truncation.""" task = TPCLengthOfStayEICU() - sample = task(_patient(hours=400.5, hr_hours=[0, 1]))[0] + + sample = task( + _patient(hours=400.5, hr_hours=[0, 1]) + )[0] + assert sample["los"]["time"] == list(range(5, 337)) assert _labels(sample["los"])[0] == 395.5 assert _labels(sample["los"])[-1] == 64.5 assert sample["dynamic"]["values"].shape == (336, 48) - assert _labels(task(_patient(hours=5, hr_hours=[]))[0]["los"]) == [0] + + short_sample = task( + _patient(hours=5, hr_hours=[]) + )[0] + + assert _labels(short_sample["los"]) == [0] def test_fractional_remaining_hours(): - sample = TPCLengthOfStayEICU()(_patient(hours=6.5, hr_hours=[]))[0] + """Check remaining LOS for fractional stay durations.""" + sample = TPCLengthOfStayEICU()( + _patient(hours=6.5, hr_hours=[]) + )[0] + assert sample["los"]["time"] == [5, 6] assert _labels(sample["los"]) == [1.5, 0.5] -@pytest.mark.skip(reason="TODO(B): enable after masking/fill/decay integration") def test_missingness_count_repeatability_no_mutation(): + """Verify masking fraction, reproducibility, and input safety.""" values = np.arange(20, dtype=float).reshape(5, 4) values[0, 0] = np.nan + original = values.copy() + for rate in [0, 0.1, 0.2, 1]: - task = TPCLengthOfStayEICU(rate) + task = TPCLengthOfStayEICU( + missing_rate=rate + ) + result = task._apply_missingness(values, 10) - assert np.isnan(result).sum() == 1 + round(19 * rate) - np.testing.assert_equal(result, task._apply_missingness(values, 10)) + + assert np.isnan(result).sum() == ( + 1 + round(19 * rate) + ) + + np.testing.assert_equal( + result, + task._apply_missingness(values, 10), + ) + np.testing.assert_equal(values, original) + + assert not np.shares_memory(values, result) + np.testing.assert_equal( - TPCLengthOfStayEICU()._apply_missingness(values, 10), values + TPCLengthOfStayEICU()._apply_missingness( + values, 10 + ), + values, ) -@pytest.mark.parametrize("rate", [-0.1, 1.1, float("nan")]) +@pytest.mark.parametrize( + "rate", + [-0.1, 1.1, float("nan")], +) def test_invalid_rate(rate): + """Reject missingness rates outside the valid interval.""" with pytest.raises(ValueError): - TPCLengthOfStayEICU(rate) + TPCLengthOfStayEICU( + missing_rate=rate + ) -@pytest.mark.skip(reason="TODO(B): enable after masking/fill/decay integration") +@pytest.mark.skip( + reason="Pending verification of hourly aggregation semantics" +) def test_hourly_measurements_and_missing_data(): + """Check hourly lab aggregation and masking.""" task = TPCLengthOfStayEICU() - p = _patient( - hours=6, hr_hours=[], extra=[_lab(60, "potassium", 4), _lab(90, "potassium", 6)] + + patient = _patient( + hours=6, + hr_hours=[], + extra=[ + _lab(60, "potassium", 4), + _lab(90, "potassium", 6), + ], ) - sample = task(p)[0] + + sample = task(patient)[0] k = task.DYNAMIC_FEATURES.index("k") + assert sample["dynamic"]["values"][1, k] == 5 - assert np.isnan(sample["dynamic"]["values"][0, k]) - assert np.isnan(sample["dynamic"]["values"][2, k]) - masked = TPCLengthOfStayEICU(1)(p)[0] - assert np.isnan(masked["dynamic"]["values"]).all() + assert np.isnan( + sample["dynamic"]["values"][0, k] + ) + assert np.isnan( + sample["dynamic"]["values"][2, k] + ) + + masked = TPCLengthOfStayEICU( + missing_rate=1 + )(patient)[0] + + assert np.isnan( + masked["dynamic"]["values"] + ).all() + assert masked["los"] == sample["los"] assert masked["static"] == sample["static"] -@pytest.mark.skip(reason="TODO(B): enable after masking/fill/decay integration") +@pytest.mark.skip( + reason="Pending verification of processor forward-fill integration" +) def test_forward_fill_after_removal(): + """Check forward-fill behavior after missingness removal.""" from pyhealth.processors import JaggedFeatureProcessor values = { "time": [0.0, 1.0, 2.0, 3.0], - "values": [[80.0], [np.nan], [100.0], [np.nan]], + "values": [ + [80.0], + [np.nan], + [100.0], + [np.nan], + ], } + proc = JaggedFeatureProcessor( levels=[ { "ordering": "series", "values": [1], - "impute": [{"method": "forward_fill"}, {"method": "zero"}], + "impute": [ + {"method": "forward_fill"}, + {"method": "zero"}, + ], } ] ) + proc.fit([{"x": values}], "x") + result = proc.process(values) - np.testing.assert_allclose(result[0].reshape(-1).numpy(), [80, 80, 100, 100]) - removed = {"time": values["time"], "values": [[80.0], [np.nan], [np.nan], [np.nan]]} - np.testing.assert_allclose(proc.process(removed)[0].reshape(-1).numpy(), [80] * 4) + + np.testing.assert_allclose( + result[0].reshape(-1).numpy(), + [80, 80, 100, 100], + ) + + removed = { + "time": values["time"], + "values": [ + [80.0], + [np.nan], + [np.nan], + [np.nan], + ], + } + + np.testing.assert_allclose( + proc.process(removed)[0].reshape(-1).numpy(), + [80] * 4, + ) -@pytest.mark.skip(reason="TODO(B): enable after masking/fill/decay integration") def test_decay_oracle_and_full_removal(): + """Verify exponential decay and fully missing features.""" raw = np.array( - [[np.nan, 80], [4, np.nan], [np.nan, 100], [np.nan, np.nan], [3, np.nan]], + [ + [np.nan, 80], + [4, np.nan], + [np.nan, 100], + [np.nan, np.nan], + [3, np.nan], + ], dtype=float, ) - expected = [[0, 1], [1, 0.75], [0.75, 1], [0.375, 0.75], [1, 0.375]] - np.testing.assert_allclose(TPCLengthOfStayEICU._decay(raw), expected) - removed = TPCLengthOfStayEICU(1)._apply_missingness(raw, 10) - assert not TPCLengthOfStayEICU._decay(removed).any() + + expected = [ + [0, 1], + [1, 0.75], + [0.75, 1], + [0.5625, 0.75], + [1, 0.5625], + ] + + np.testing.assert_allclose( + TPCLengthOfStayEICU._decay(raw), + expected, + ) + + removed = TPCLengthOfStayEICU( + missing_rate=1 + )._apply_missingness(raw, 10) + + assert not TPCLengthOfStayEICU._decay( + removed + ).any() def test_decay_optional_schema_does_not_mutate_other_instances(): - assert "decay" in TPCLengthOfStayEICU(include_decay=True).input_schema - assert "decay" not in TPCLengthOfStayEICU().input_schema + """Ensure optional decay does not modify the class schema.""" + assert ( + "decay" + in TPCLengthOfStayEICU( + include_decay=True + ).input_schema + ) + + assert ( + "decay" + not in TPCLengthOfStayEICU().input_schema + ) def test_future_observations_do_not_change_earlier_hours(): + """Ensure future observations do not leak into earlier bins.""" task = TPCLengthOfStayEICU() - first = task(_patient(hours=12, hr_hours=[0, 2]))[0] - future = task(_patient(hours=12, hr_hours=[0, 2, 10]))[0] - for field in ["dynamic"]: - np.testing.assert_equal( - first[field]["values"][:10], future[field]["values"][:10] - ) + + first = task( + _patient(hours=12, hr_hours=[0, 2]) + )[0] + + future = task( + _patient(hours=12, hr_hours=[0, 2, 10]) + )[0] + + np.testing.assert_equal( + first["dynamic"]["values"][:10], + future["dynamic"]["values"][:10], + ) def test_stays_are_isolated(): + """Ensure measurements cannot leak between ICU stays.""" from pyhealth.data import Patient from tests.core.tpc_fixtures import _frame, _stay_rows task = TPCLengthOfStayEICU() - rows = _stay_rows(10, 8, hr_hours=[0]) + _stay_rows(11, 8, hr_hours=[]) + + rows = ( + _stay_rows(10, 8, hr_hours=[0]) + + _stay_rows(11, 8, hr_hours=[]) + ) + samples = { - s["stay_id"]: s - for s in task(Patient(patient_id="same-patient", data_source=_frame(rows))) + sample["stay_id"]: sample + for sample in task( + Patient( + patient_id="same-patient", + data_source=_frame(rows), + ) + ) } - assert np.isfinite(samples[10]["dynamic"]["values"]).any() - assert np.isnan(samples[11]["dynamic"]["values"]).all() + + assert np.isfinite( + samples[10]["dynamic"]["values"] + ).any() + + assert np.isnan( + samples[11]["dynamic"]["values"] + ).all() def test_empty_patient(): + """Return no samples for a patient without admission records.""" from pyhealth.data import Patient from tests.core.tpc_fixtures import _frame, _event - # Patient with no patient-table admission record. - patient = Patient(patient_id="empty", data_source=_frame([_event("lab")])) + patient = Patient( + patient_id="empty", + data_source=_frame([_event("lab")]), + ) + assert TPCLengthOfStayEICU()(patient) == [] -@pytest.mark.parametrize("rate", [0, 0.1, 0.2, 1]) -@pytest.mark.skip(reason="TODO(B): enable after masking/fill/decay integration") +@pytest.mark.parametrize( + "rate", + [0, 0.1, 0.2, 1], +) +@pytest.mark.skip( + reason="Pending verification of combined processor integration" +) def test_combined_mask_fill_and_decay(rate): + """Check masking, forward-fill, and decay together.""" from pyhealth.processors import JaggedFeatureProcessor - patient = _patient(hours=8, hr_hours=[0, 2, 4, 6]) - task = TPCLengthOfStayEICU(missing_rate=rate, include_decay=True) + patient = _patient( + hours=8, + hr_hours=[0, 2, 4, 6], + ) + + task = TPCLengthOfStayEICU( + missing_rate=rate, + include_decay=True, + ) + sample = task(patient)[0] - original = TPCLengthOfStayEICU()(patient)[0]["dynamic"]["values"] + + original = TPCLengthOfStayEICU()( + patient + )[0]["dynamic"]["values"] + raw = sample["dynamic"]["values"] - assert np.isfinite(original).sum() - np.isfinite(raw).sum() == round(4 * rate) - np.testing.assert_equal(raw, task(patient)[0]["dynamic"]["values"]) + + assert ( + np.isfinite(original).sum() + - np.isfinite(raw).sum() + == round(4 * rate) + ) + + np.testing.assert_equal( + raw, + task(patient)[0]["dynamic"]["values"], + ) + proc = JaggedFeatureProcessor( levels=[ { "ordering": "series", "values": [48], - "impute": [{"method": "forward_fill"}, {"method": "zero"}], + "impute": [ + {"method": "forward_fill"}, + {"method": "zero"}, + ], } ] ) - proc.fit([{"x": sample["dynamic"]}], "x") - filled = proc.process(sample["dynamic"])[0].numpy() + + proc.fit( + [{"x": sample["dynamic"]}], + "x", + ) + + filled = proc.process( + sample["dynamic"] + )[0].numpy() + hr = task.DYNAMIC_FEATURES.index("hr") - # A retained value must carry forward until the next retained observation; - # no measurements before the first retained observation may be invented. - retained = np.flatnonzero(np.isfinite(raw[:, hr])) + + retained = np.flatnonzero( + np.isfinite(raw[:, hr]) + ) + if len(retained): - assert not filled[: retained[0], hr].any() - assert not sample["decay"]["values"][: retained[0], hr].any() - for start, end in zip(retained, [*retained[1:], len(raw)]): - np.testing.assert_allclose(filled[start:end, hr], raw[start, hr]) - assert sample["decay"]["values"][start, hr] == 1 + assert not filled[ + :retained[0], hr + ].any() + + assert not sample["decay"]["values"][ + :retained[0], hr + ].any() + + for start, end in zip( + retained, + [*retained[1:], len(raw)], + ): + np.testing.assert_allclose( + filled[start:end, hr], + raw[start, hr], + ) + + assert ( + sample["decay"]["values"][ + start, hr + ] == 1 + ) + else: assert not filled.any() assert not sample["decay"]["values"].any() def test_incomplete_hour_cannot_enter_prediction(): + """Prevent measurements from unfinished bins entering predictions.""" task = TPCLengthOfStayEICU() - baseline = task(_patient(hours=8, hr_hours=[]))[0] - changed = task(_patient(hours=8, hr_hours=[], extra=[_lab(359, "potassium", 5)]))[0] + + baseline = task( + _patient(hours=8, hr_hours=[]) + )[0] + + changed = task( + _patient( + hours=8, + hr_hours=[], + extra=[ + _lab(359, "potassium", 5) + ], + ) + )[0] + for sample in [baseline, changed]: - assert sample["dynamic"]["time"] == list(range(1, 9)) - for field in ["dynamic"]: - times = np.asarray(changed[field]["time"]) - np.testing.assert_equal( - baseline[field]["values"][times <= 5], changed[field]["values"][times <= 5] + assert sample["dynamic"]["time"] == list( + range(1, 9) ) + + times = np.asarray( + changed["dynamic"]["time"] + ) + + np.testing.assert_equal( + baseline["dynamic"]["values"][ + times <= 5 + ], + changed["dynamic"]["values"][ + times <= 5 + ], + ) + k = task.DYNAMIC_FEATURES.index("k") - assert changed["dynamic"]["values"][5, k] == 5 + + assert changed["dynamic"]["values"][ + 5, k + ] == 5 + assert changed["dynamic"]["time"][5] == 6 -def test_zero_removal_baseline_and_unfinished_extensions(): - raw = np.array([[80.0, np.nan]]) - result = TPCLengthOfStayEICU()._apply_missingness(raw, 10) - np.testing.assert_equal(raw, result) - assert not np.shares_memory(raw, result) - with pytest.raises(NotImplementedError, match="TODO"): - TPCLengthOfStayEICU(0.1)._apply_missingness(raw, 10) - with pytest.raises(NotImplementedError, match="TODO"): - TPCLengthOfStayEICU._decay(raw) +def test_zero_removal_baseline_and_completed_extensions(): + """Verify implemented missingness and decay functionality.""" + raw = np.array( + [[80.0, np.nan]] + ) + + result = TPCLengthOfStayEICU( + missing_rate=0 + )._apply_missingness(raw, 10) + + np.testing.assert_equal( + raw, + result, + ) + + assert not np.shares_memory( + raw, + result, + ) + + masked = TPCLengthOfStayEICU( + missing_rate=1.0 + )._apply_missingness(raw, 10) + + assert np.isnan(masked).all() + + decay = TPCLengthOfStayEICU._decay(raw) + + np.testing.assert_allclose( + decay, + [[1.0, 0.0]], + ) + From 71cd188dfc14a017d80aee34ffac5c26ccea47a5 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 14:43:22 -0800 Subject: [PATCH 26/50] Update tpc_fixtures.py Change heading for formatting --- tests/core/tpc_fixtures.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/tests/core/tpc_fixtures.py b/tests/core/tpc_fixtures.py index b43cb94fa6..57abd874b1 100644 --- a/tests/core/tpc_fixtures.py +++ b/tests/core/tpc_fixtures.py @@ -1,6 +1,19 @@ -# Contributor: Xiao Luo, UIUC NetID xiaoluo6. -# Paper: Temporal Pointwise Convolutional Networks for Length of Stay -# Prediction in the Intensive Care Unit. https://arxiv.org/abs/2007.09483 +""" +Author: Manling Tan, Yining Jin, Xiao Luo +NetID: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) + +Paper URL: +https://arxiv.org/abs/2007.09483 +""" + + """Small synthetic eICU records; adapted from YAIB regression fixtures.""" from pathlib import Path From e5348924375b9af92da10ff89b0008b63bf48f59 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 14:45:29 -0800 Subject: [PATCH 27/50] Update checkpoint.py Changed headers --- examples/tpc_support/checkpoint.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/examples/tpc_support/checkpoint.py b/examples/tpc_support/checkpoint.py index 3efaa573e1..28a61df997 100644 --- a/examples/tpc_support/checkpoint.py +++ b/examples/tpc_support/checkpoint.py @@ -1,6 +1,19 @@ -# Contributor: Xiao Luo, UIUC NetID xiaoluo6. -# Paper: Temporal Pointwise Convolutional Networks for Length of Stay -# Prediction in the Intensive Care Unit. https://arxiv.org/abs/2007.09483 +""" +Contributors: Manling Tan, Yining Jin, Xiao Luo +NetID: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) + +Paper URL: +https://arxiv.org/abs/2007.09483 +""" + + """Synthetic CSV-to-task checkpoint for cohort, static features and labels.""" from pathlib import Path From ed655a3836e6dbfecbd93dc50f83c02ec4824cb4 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 14:46:12 -0800 Subject: [PATCH 28/50] Update tpc_fixtures.py Changed headers --- tests/core/tpc_fixtures.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/core/tpc_fixtures.py b/tests/core/tpc_fixtures.py index 57abd874b1..4be5489700 100644 --- a/tests/core/tpc_fixtures.py +++ b/tests/core/tpc_fixtures.py @@ -1,5 +1,5 @@ """ -Author: Manling Tan, Yining Jin, Xiao Luo +Contributors: Manling Tan, Yining Jin, Xiao Luo NetID: manling4, yining34, xiaoluo6 Paper Title: From a2d3ef7e9319ffca6bd8552653c9e156033a4612 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 14:47:08 -0800 Subject: [PATCH 29/50] Update generate_synthetic.py changed headers --- examples/tpc_support/generate_synthetic.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/examples/tpc_support/generate_synthetic.py b/examples/tpc_support/generate_synthetic.py index 1ed9221146..5305d56257 100644 --- a/examples/tpc_support/generate_synthetic.py +++ b/examples/tpc_support/generate_synthetic.py @@ -1,6 +1,19 @@ -# Contributor: Xiao Luo, UIUC NetID xiaoluo6. -# Paper: Temporal Pointwise Convolutional Networks for Length of Stay -# Prediction in the Intensive Care Unit. https://arxiv.org/abs/2007.09483 +""" +Contributors: Manling Tan, Yining Jin, Xiao Luo +NetIDs: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) + +Paper URL: +https://arxiv.org/abs/2007.09483 +""" + + """Write five invented patients in the shipped eICU CSV schema.""" import csv From 212164ae25ee77a2e33ea13004cfd1c4b9477c30 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 14:48:03 -0800 Subject: [PATCH 30/50] Update eicu_hourly_los_lstm.py Changed header --- examples/eicu_hourly_los_lstm.py | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/examples/eicu_hourly_los_lstm.py b/examples/eicu_hourly_los_lstm.py index 7a4343734f..d1e1dcf716 100644 --- a/examples/eicu_hourly_los_lstm.py +++ b/examples/eicu_hourly_los_lstm.py @@ -1,8 +1,21 @@ -"""Training and ablation extension points for the hourly ICU LOS task. -Contributor: Xiao Luo; UIUC NetID: xiaoluo6. -Paper: Temporal Pointwise Convolutional Networks for Length of Stay Prediction -in the Intensive Care Unit, https://arxiv.org/abs/2007.09483. +""" +Contributors: Manling Tan, Yining Jin, Xiao Luo +NetIDs: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) + +Paper URL: +https://arxiv.org/abs/2007.09483 +""" + + +"""Training and ablation extension points for the hourly ICU LOS task. STATUS: scaffold. This file does not yet train a model or report results. The runnable data/task check is: From 736edc5159d7b9c0b6d6d810171a261947bcf01a Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 14:48:48 -0800 Subject: [PATCH 31/50] Update test_tpc_checkpoint.py changed header --- tests/integration/test_tpc_checkpoint.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/tests/integration/test_tpc_checkpoint.py b/tests/integration/test_tpc_checkpoint.py index 0a86485606..a9b857a1fa 100644 --- a/tests/integration/test_tpc_checkpoint.py +++ b/tests/integration/test_tpc_checkpoint.py @@ -1,6 +1,19 @@ -# Contributor: Xiao Luo, UIUC NetID xiaoluo6. -# Paper: Temporal Pointwise Convolutional Networks for Length of Stay -# Prediction in the Intensive Care Unit. https://arxiv.org/abs/2007.09483 +""" +Contributors: Manling Tan, Yining Jin, Xiao Luo +NetIDs: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) + +Paper URL: +https://arxiv.org/abs/2007.09483 +""" + + """Opt-in real CSV loader/task smoke check; fast task tests live in core. Set PYHEALTH_RUN_TPC_INTEGRATION=1 to run this slower local-server check. From 8ae84f6c0f14689ce6806b64147f527b2dbbd36f Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 14:49:49 -0800 Subject: [PATCH 32/50] Update pyhealth.tasks.tpc_eicu.rst added header --- docs/api/tasks/pyhealth.tasks.tpc_eicu.rst | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst index 809f3b3b21..679310a50e 100644 --- a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst +++ b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst @@ -1,3 +1,17 @@ +.. Contributors: Manling Tan, Yining Jin, Xiao Luo +.. NetIDs: manling4, yining34, xiaoluo6 +.. +.. Paper Title: +.. Temporal Pointwise Convolutional Networks for +.. Length of Stay Prediction in the Intensive Care Unit +.. +.. Paper Authors: +.. Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) +.. +.. Paper URL: +.. https://arxiv.org/abs/2007.09483 + + Hourly remaining ICU length of stay ================================== From 4a3ef18e46cc8307a497ce13d6974937066ac593 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 14:56:48 -0800 Subject: [PATCH 33/50] Update pyhealth.tasks.tpc_eicu.rst Updated with new info --- docs/api/tasks/pyhealth.tasks.tpc_eicu.rst | 47 +++++++++++++--------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst index 679310a50e..4ab3d700b5 100644 --- a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst +++ b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst @@ -22,35 +22,39 @@ Hourly remaining ICU length of stay Implementation status --------------------- -The baseline implements adult/five-hour eligibility, admission static features, -hourly remaining-LOS labels and synthetic CSV validation. Dynamic extraction -uses existing YAIB helpers provisionally. This is a partial contribution under -active integration, not a final training/ablation implementation. +The task implements adult/five-hour eligibility, admission static features, +hourly remaining-LOS labels, configurable observation removal, optional +decay features, and synthetic CSV validation. Dynamic extraction uses +existing YAIB helpers provisionally. Model training and ablation +experiments are documented separately. + +``TPCLengthOfStayEICU()`` supports observation removal through +``missing_rate`` values from 0.0 to 1.0. Missing observations +are represented by NaN, with deterministic masking based on +the random seed and stay identifier. + +When ``include_decay=True``, decay features are calculated +after observation removal. Observed values reset decay to +1.0; unobserved values decay by a factor of 0.75 per hour. -``TPCLengthOfStayEICU()`` works with zero observation removal and no decay. -Nonzero ``missing_rate`` and ``include_decay=True`` deliberately raise -``NotImplementedError`` when samples are processed, rather than silently -producing unimplemented results. Extension points ---------------- -* ``TODO(B)`` in ``pyhealth/tasks/tpc_eicu.py``: review dynamic feature coverage - and hourly aggregation, confirm training-only normalization/forward fill, - and integrate decay after removal. For masking, A/B should reuse the existing - ``_apply_missingness`` in the repository-root ``tpc_eicu.py`` prototype after - checking compatibility. It already implements seeded removal of hourly cells; - this placeholder is an integration boundary, not a request to write it again. - Confirm raw-row versus aggregated-cell removal and rerun the pending tests. +* ``pyhealth/tasks/tpc_eicu.py`` implements hourly remaining-LOS + preprocessing, configurable observation removal, and optional + decay features. Observation removal is deterministic and + applied before decay calculation. * ``TODO(A)`` in ``examples/eicu_hourly_los_lstm.py``: integrate existing training work where available and complete explicit LSTM training, patient-disjoint splits, agreed losses/metrics and the two-training by three-test missingness study. This file is a scaffold and raises until implemented. The example filename is present but the rubric's working ablation requirement is still outstanding. -* Disabled preprocessing contract tests in ``tests/core/test_tpc_eicu.py`` - retain numerical expectations. Enable and revise these after the shared - interface is confirmed. Skipped tests are pending work, not passing coverage. +* Preprocessing contract tests in ``tests/core/test_tpc_eicu.py`` + cover observation removal and decay. Some hourly aggregation, + forward-fill, and combined preprocessing tests remain skipped + pending verification. * Extend the integration check with actual model training when the training implementation is available. Its current scope ends at CSV-to-task outputs. @@ -87,8 +91,11 @@ nursecharting using eICUDataset. One sample is produced per eligible stay: * Labels at hours 5..H have shape (H-4,1) and equal total LOS hours minus h. Exact-discharge labels may be zero. The observation horizon is capped; remaining LOS is not capped. -* Planned decay mirrors dynamic dimensions/times. Existing schema wiring is - provisional until preprocessing review. +* ``missing_rate`` controls removal of observed hourly feature cells. + A rate of 0.0 preserves observations; 1.0 removes all observed cells. +* ``include_decay=True`` adds decay features matching the dynamic + feature dimensions. Decay resets to 1.0 upon observation and + decreases by a factor of 0.75 per unobserved hour. * Split by patient_id rather than stay_id. Fit learned processors on training patients only. Existing YAIB label processors min-max scale training targets; activated predictions return original hours. Avoid double unscaling. From 15fd19679d031faab815bea537f824671e9fb5dc Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 14:57:58 -0800 Subject: [PATCH 34/50] Update tpc_eicu.py --- pyhealth/tasks/tpc_eicu.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py index cf3a6598fb..de600dd810 100644 --- a/pyhealth/tasks/tpc_eicu.py +++ b/pyhealth/tasks/tpc_eicu.py @@ -1,6 +1,5 @@ -"""Hourly remaining ICU length-of-stay task with missingness experiments. - -Authors: Manling Tan, Yining Jin, Xiao Luo +""" +Contributors: Manling Tan, Yining Jin, Xiao Luo NetIDs: manling4, yining34, xiaoluo6 Paper Title: @@ -14,6 +13,9 @@ https://arxiv.org/abs/2007.09483 """ + +"""Hourly remaining ICU length-of-stay task with missingness experiments.""" + import hashlib from copy import deepcopy from typing import Any, ClassVar From 99839e4a9a767eb78f5884f7a01a5a2de01927c0 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 14:58:39 -0800 Subject: [PATCH 35/50] Update test_tpc_eicu.py --- tests/core/test_tpc_eicu.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/core/test_tpc_eicu.py b/tests/core/test_tpc_eicu.py index ecfa307e4f..6f39eb4054 100644 --- a/tests/core/test_tpc_eicu.py +++ b/tests/core/test_tpc_eicu.py @@ -1,5 +1,5 @@ """ -Author: Manling Tan, Yining Jin, Xiao Luo +Contributors: Manling Tan, Yining Jin, Xiao Luo NetID: manling4, yining34, xiaoluo6 Paper Title: From 9b0ff210ecfc5f749e2359cd679ee4760a52e3ff Mon Sep 17 00:00:00 2001 From: ah-ling68 Date: Sun, 22 Nov 2026 15:52:54 -0800 Subject: [PATCH 36/50] Apply Black formatting to TPC task and tests --- pyhealth/tasks/tpc_eicu.py | 30 ++---- tests/core/test_tpc_eicu.py | 182 +++++++++--------------------------- 2 files changed, 50 insertions(+), 162 deletions(-) diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py index de600dd810..a32fff617f 100644 --- a/pyhealth/tasks/tpc_eicu.py +++ b/pyhealth/tasks/tpc_eicu.py @@ -13,7 +13,6 @@ https://arxiv.org/abs/2007.09483 """ - """Hourly remaining ICU length-of-stay task with missingness experiments.""" import hashlib @@ -106,9 +105,7 @@ def _base_cohort( keep = [ stay_id - for stay_id, hours in stays.select( - "stay_id", "los_hours" - ).iter_rows() + for stay_id, hours in stays.select("stay_id", "los_hours").iter_rows() if np.isfinite(hours) and hours >= self.START_HOUR and np.isfinite(static[stay_id][0]) @@ -127,9 +124,7 @@ def _base_cohort( ) ) - return stays, hourly, { - key: static[key] for key in keep - } + return stays, hourly, {key: static[key] for key in keep} @staticmethod def _decay(values: np.ndarray) -> np.ndarray: @@ -153,9 +148,7 @@ def _decay(values: np.ndarray) -> np.ndarray: """ if values.ndim != 2: - raise ValueError( - "values must be a 2D (hours, features) array" - ) + raise ValueError("values must be a 2D (hours, features) array") n_hours, n_features = values.shape @@ -196,9 +189,7 @@ def _apply_missingness( observed = np.argwhere(~np.isnan(values)) - n_hide = round( - len(observed) * self.missing_rate - ) + n_hide = round(len(observed) * self.missing_rate) if n_hide == 0: return values @@ -272,10 +263,7 @@ def __call__( last_hour - 1, ) - dynamic["time"] = [ - float(h) - for h in range(1, last_hour + 1) - ] + dynamic["time"] = [float(h) for h in range(1, last_hour + 1)] dynamic["values"] = self._apply_missingness( dynamic["values"], @@ -302,9 +290,7 @@ def __call__( "patient_id": patient.patient_id, "stay_id": stay_id, "dynamic": dynamic, - "static": self._static_series( - static[stay_id] - ), + "static": self._static_series(static[stay_id]), "los": self._labels( prediction_hours, remaining, @@ -314,9 +300,7 @@ def __call__( if self.include_decay: sample["decay"] = { "time": list(dynamic["time"]), - "values": self._decay( - dynamic["values"] - ), + "values": self._decay(dynamic["values"]), } samples.append(sample) diff --git a/tests/core/test_tpc_eicu.py b/tests/core/test_tpc_eicu.py index 6f39eb4054..02eb07c71a 100644 --- a/tests/core/test_tpc_eicu.py +++ b/tests/core/test_tpc_eicu.py @@ -44,17 +44,13 @@ ) def test_cohort(hours, age, eligible): """Check adult cohort and minimum ICU stay requirements.""" - samples = TPCLengthOfStayEICU()( - _patient(hours=hours, age=age, hr_hours=[]) - ) + samples = TPCLengthOfStayEICU()(_patient(hours=hours, age=age, hr_hours=[])) assert bool(samples) == eligible def test_static_features(): """Verify static features and invalid-value handling.""" - sample = TPCLengthOfStayEICU()( - _patient(hours=5, age="> 89", gender="Female") - )[0] + sample = TPCLengthOfStayEICU()(_patient(hours=5, age="> 89", gender="Female"))[0] assert sample["static"]["values"] == [[90, 0, 180, 80]] @@ -67,36 +63,28 @@ def test_static_features(): ) )[0] - assert np.isnan( - missing["static"]["values"][0][1:] - ).all() + assert np.isnan(missing["static"]["values"][0][1:]).all() def test_labels_and_horizon(): """Verify hourly remaining LOS and 14-day truncation.""" task = TPCLengthOfStayEICU() - sample = task( - _patient(hours=400.5, hr_hours=[0, 1]) - )[0] + sample = task(_patient(hours=400.5, hr_hours=[0, 1]))[0] assert sample["los"]["time"] == list(range(5, 337)) assert _labels(sample["los"])[0] == 395.5 assert _labels(sample["los"])[-1] == 64.5 assert sample["dynamic"]["values"].shape == (336, 48) - short_sample = task( - _patient(hours=5, hr_hours=[]) - )[0] + short_sample = task(_patient(hours=5, hr_hours=[]))[0] assert _labels(short_sample["los"]) == [0] def test_fractional_remaining_hours(): """Check remaining LOS for fractional stay durations.""" - sample = TPCLengthOfStayEICU()( - _patient(hours=6.5, hr_hours=[]) - )[0] + sample = TPCLengthOfStayEICU()(_patient(hours=6.5, hr_hours=[]))[0] assert sample["los"]["time"] == [5, 6] assert _labels(sample["los"]) == [1.5, 0.5] @@ -110,15 +98,11 @@ def test_missingness_count_repeatability_no_mutation(): original = values.copy() for rate in [0, 0.1, 0.2, 1]: - task = TPCLengthOfStayEICU( - missing_rate=rate - ) + task = TPCLengthOfStayEICU(missing_rate=rate) result = task._apply_missingness(values, 10) - assert np.isnan(result).sum() == ( - 1 + round(19 * rate) - ) + assert np.isnan(result).sum() == (1 + round(19 * rate)) np.testing.assert_equal( result, @@ -130,9 +114,7 @@ def test_missingness_count_repeatability_no_mutation(): assert not np.shares_memory(values, result) np.testing.assert_equal( - TPCLengthOfStayEICU()._apply_missingness( - values, 10 - ), + TPCLengthOfStayEICU()._apply_missingness(values, 10), values, ) @@ -144,14 +126,10 @@ def test_missingness_count_repeatability_no_mutation(): def test_invalid_rate(rate): """Reject missingness rates outside the valid interval.""" with pytest.raises(ValueError): - TPCLengthOfStayEICU( - missing_rate=rate - ) + TPCLengthOfStayEICU(missing_rate=rate) -@pytest.mark.skip( - reason="Pending verification of hourly aggregation semantics" -) +@pytest.mark.skip(reason="Pending verification of hourly aggregation semantics") def test_hourly_measurements_and_missing_data(): """Check hourly lab aggregation and masking.""" task = TPCLengthOfStayEICU() @@ -169,28 +147,18 @@ def test_hourly_measurements_and_missing_data(): k = task.DYNAMIC_FEATURES.index("k") assert sample["dynamic"]["values"][1, k] == 5 - assert np.isnan( - sample["dynamic"]["values"][0, k] - ) - assert np.isnan( - sample["dynamic"]["values"][2, k] - ) + assert np.isnan(sample["dynamic"]["values"][0, k]) + assert np.isnan(sample["dynamic"]["values"][2, k]) - masked = TPCLengthOfStayEICU( - missing_rate=1 - )(patient)[0] + masked = TPCLengthOfStayEICU(missing_rate=1)(patient)[0] - assert np.isnan( - masked["dynamic"]["values"] - ).all() + assert np.isnan(masked["dynamic"]["values"]).all() assert masked["los"] == sample["los"] assert masked["static"] == sample["static"] -@pytest.mark.skip( - reason="Pending verification of processor forward-fill integration" -) +@pytest.mark.skip(reason="Pending verification of processor forward-fill integration") def test_forward_fill_after_removal(): """Check forward-fill behavior after missingness removal.""" from pyhealth.processors import JaggedFeatureProcessor @@ -269,41 +237,25 @@ def test_decay_oracle_and_full_removal(): expected, ) - removed = TPCLengthOfStayEICU( - missing_rate=1 - )._apply_missingness(raw, 10) + removed = TPCLengthOfStayEICU(missing_rate=1)._apply_missingness(raw, 10) - assert not TPCLengthOfStayEICU._decay( - removed - ).any() + assert not TPCLengthOfStayEICU._decay(removed).any() def test_decay_optional_schema_does_not_mutate_other_instances(): """Ensure optional decay does not modify the class schema.""" - assert ( - "decay" - in TPCLengthOfStayEICU( - include_decay=True - ).input_schema - ) + assert "decay" in TPCLengthOfStayEICU(include_decay=True).input_schema - assert ( - "decay" - not in TPCLengthOfStayEICU().input_schema - ) + assert "decay" not in TPCLengthOfStayEICU().input_schema def test_future_observations_do_not_change_earlier_hours(): """Ensure future observations do not leak into earlier bins.""" task = TPCLengthOfStayEICU() - first = task( - _patient(hours=12, hr_hours=[0, 2]) - )[0] + first = task(_patient(hours=12, hr_hours=[0, 2]))[0] - future = task( - _patient(hours=12, hr_hours=[0, 2, 10]) - )[0] + future = task(_patient(hours=12, hr_hours=[0, 2, 10]))[0] np.testing.assert_equal( first["dynamic"]["values"][:10], @@ -318,10 +270,7 @@ def test_stays_are_isolated(): task = TPCLengthOfStayEICU() - rows = ( - _stay_rows(10, 8, hr_hours=[0]) - + _stay_rows(11, 8, hr_hours=[]) - ) + rows = _stay_rows(10, 8, hr_hours=[0]) + _stay_rows(11, 8, hr_hours=[]) samples = { sample["stay_id"]: sample @@ -333,13 +282,9 @@ def test_stays_are_isolated(): ) } - assert np.isfinite( - samples[10]["dynamic"]["values"] - ).any() + assert np.isfinite(samples[10]["dynamic"]["values"]).any() - assert np.isnan( - samples[11]["dynamic"]["values"] - ).all() + assert np.isnan(samples[11]["dynamic"]["values"]).all() def test_empty_patient(): @@ -359,9 +304,7 @@ def test_empty_patient(): "rate", [0, 0.1, 0.2, 1], ) -@pytest.mark.skip( - reason="Pending verification of combined processor integration" -) +@pytest.mark.skip(reason="Pending verification of combined processor integration") def test_combined_mask_fill_and_decay(rate): """Check masking, forward-fill, and decay together.""" from pyhealth.processors import JaggedFeatureProcessor @@ -378,17 +321,11 @@ def test_combined_mask_fill_and_decay(rate): sample = task(patient)[0] - original = TPCLengthOfStayEICU()( - patient - )[0]["dynamic"]["values"] + original = TPCLengthOfStayEICU()(patient)[0]["dynamic"]["values"] raw = sample["dynamic"]["values"] - assert ( - np.isfinite(original).sum() - - np.isfinite(raw).sum() - == round(4 * rate) - ) + assert np.isfinite(original).sum() - np.isfinite(raw).sum() == round(4 * rate) np.testing.assert_equal( raw, @@ -413,24 +350,16 @@ def test_combined_mask_fill_and_decay(rate): "x", ) - filled = proc.process( - sample["dynamic"] - )[0].numpy() + filled = proc.process(sample["dynamic"])[0].numpy() hr = task.DYNAMIC_FEATURES.index("hr") - retained = np.flatnonzero( - np.isfinite(raw[:, hr]) - ) + retained = np.flatnonzero(np.isfinite(raw[:, hr])) if len(retained): - assert not filled[ - :retained[0], hr - ].any() + assert not filled[: retained[0], hr].any() - assert not sample["decay"]["values"][ - :retained[0], hr - ].any() + assert not sample["decay"]["values"][: retained[0], hr].any() for start, end in zip( retained, @@ -441,11 +370,7 @@ def test_combined_mask_fill_and_decay(rate): raw[start, hr], ) - assert ( - sample["decay"]["values"][ - start, hr - ] == 1 - ) + assert sample["decay"]["values"][start, hr] == 1 else: assert not filled.any() @@ -456,56 +381,38 @@ def test_incomplete_hour_cannot_enter_prediction(): """Prevent measurements from unfinished bins entering predictions.""" task = TPCLengthOfStayEICU() - baseline = task( - _patient(hours=8, hr_hours=[]) - )[0] + baseline = task(_patient(hours=8, hr_hours=[]))[0] changed = task( _patient( hours=8, hr_hours=[], - extra=[ - _lab(359, "potassium", 5) - ], + extra=[_lab(359, "potassium", 5)], ) )[0] for sample in [baseline, changed]: - assert sample["dynamic"]["time"] == list( - range(1, 9) - ) + assert sample["dynamic"]["time"] == list(range(1, 9)) - times = np.asarray( - changed["dynamic"]["time"] - ) + times = np.asarray(changed["dynamic"]["time"]) np.testing.assert_equal( - baseline["dynamic"]["values"][ - times <= 5 - ], - changed["dynamic"]["values"][ - times <= 5 - ], + baseline["dynamic"]["values"][times <= 5], + changed["dynamic"]["values"][times <= 5], ) k = task.DYNAMIC_FEATURES.index("k") - assert changed["dynamic"]["values"][ - 5, k - ] == 5 + assert changed["dynamic"]["values"][5, k] == 5 assert changed["dynamic"]["time"][5] == 6 def test_zero_removal_baseline_and_completed_extensions(): """Verify implemented missingness and decay functionality.""" - raw = np.array( - [[80.0, np.nan]] - ) + raw = np.array([[80.0, np.nan]]) - result = TPCLengthOfStayEICU( - missing_rate=0 - )._apply_missingness(raw, 10) + result = TPCLengthOfStayEICU(missing_rate=0)._apply_missingness(raw, 10) np.testing.assert_equal( raw, @@ -517,9 +424,7 @@ def test_zero_removal_baseline_and_completed_extensions(): result, ) - masked = TPCLengthOfStayEICU( - missing_rate=1.0 - )._apply_missingness(raw, 10) + masked = TPCLengthOfStayEICU(missing_rate=1.0)._apply_missingness(raw, 10) assert np.isnan(masked).all() @@ -529,4 +434,3 @@ def test_zero_removal_baseline_and_completed_extensions(): decay, [[1.0, 0.0]], ) - From 2b05e9b6105f28905faa0a6f25bce076e88e7b61 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 15:57:59 -0800 Subject: [PATCH 37/50] Delete test_hourly.py --- test_hourly.py | 109 ------------------------------------------------- 1 file changed, 109 deletions(-) delete mode 100644 test_hourly.py diff --git a/test_hourly.py b/test_hourly.py deleted file mode 100644 index 7db6488045..0000000000 --- a/test_hourly.py +++ /dev/null @@ -1,109 +0,0 @@ -""" -Author: Manling Tan, Yining Jin, Xiao Luo -NetID: manling4, yining34, xiaoluo6 - -Paper Title: -Temporal Pointwise Convolutional Networks for -Length of Stay Prediction in the Intensive Care Unit - -Paper Authors: -Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) - -Paper URL: -https://arxiv.org/abs/2007.09483 -""" - - -"""Test hourly binning, forward filling, and ICU LOS label generation. - -Uses synthetic heart rate measurements to demonstrate hourly -aggregation, missing-value handling, time since last observation, -and remaining ICU length-of-stay label generation. -""" - -import pandas as pd - - -def main() -> None: - """Run synthetic hourly preprocessing and LOS label checks. - - Creates sample heart rate measurements, aggregates them into - hourly bins, and forward-fills missing values. - - Calculates the elapsed time since the most recent observation - and generates remaining ICU LOS labels starting at hour 5 - for a simulated 30-hour ICU stay. - """ - # Create sample heart rate measurements for an ICU patient. - data = pd.DataFrame( - { - "hour": [0.17, 0.67, 1.33], - "heart_rate": [80, 90, 100], - } - ) - - # Assign each measurement to an hourly time bin. - data["hour_bin"] = data["hour"].astype(int) - - # Calculate the average heart rate for each hour. - hourly = data.groupby("hour_bin")["heart_rate"].mean() - - # Include hours with no recorded measurements. - hourly = hourly.reindex(range(5)) - - # Display the hourly heart rate data. - print(hourly) - - # Forward-fill missing values using the most recent observation. - hourly_filled = hourly.ffill() - - print("\nAfter forward fill:") - print(hourly_filled) - - # Track the time elapsed since the most recent measurement. - last_observed_hour = None - hours_since_observed = [] - - for hour, value in hourly.items(): - if pd.notna(value): - last_observed_hour = hour - - if last_observed_hour is None: - hours_since_observed.append(float("nan")) - else: - hours_since_observed.append(hour - last_observed_hour) - - # Combine the results into one table. - result = pd.DataFrame( - { - "heart_rate_original": hourly, - "heart_rate_filled": hourly_filled, - "hours_since_observed": hours_since_observed, - } - ) - - print("\nHourly data with time information:") - print(result) - - # Define the total ICU length of stay in hours. - total_los_hours = 30 - - # Generate remaining LOS labels for each prediction hour. - prediction_hours = range(5, total_los_hours) - - los_labels = pd.DataFrame( - { - "hour": list(prediction_hours), - "remaining_los_hours": [ - total_los_hours - hour for hour in prediction_hours - ], - } - ) - - print("\nRemaining ICU LOS labels:") - print(los_labels.head(10)) - - -if __name__ == "__main__": - main() - From 9ad227cde48e1a8f9c8d209ba1af85a89c1b7288 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 15:58:49 -0800 Subject: [PATCH 38/50] Rename test_tpc_real.py to tests/integration/test_tpc_real.py --- test_tpc_real.py => tests/integration/test_tpc_real.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename test_tpc_real.py => tests/integration/test_tpc_real.py (100%) diff --git a/test_tpc_real.py b/tests/integration/test_tpc_real.py similarity index 100% rename from test_tpc_real.py rename to tests/integration/test_tpc_real.py From d6a2d67721786fc0631d2dfbfe3c18da04de5f8a Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 15:03:42 -0800 Subject: [PATCH 39/50] Update test_tpc_real.py updated header --- tests/integration/test_tpc_real.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/integration/test_tpc_real.py b/tests/integration/test_tpc_real.py index ee0d422e29..e044ad202e 100644 --- a/tests/integration/test_tpc_real.py +++ b/tests/integration/test_tpc_real.py @@ -1,5 +1,5 @@ """ -Author: Manling Tan, Yining Jin, Xiao Luo +Contributors: Manling Tan, Yining Jin, Xiao Luo NetID: manling4, yining34, xiaoluo6 Paper Title: From 92cf1da5d0a925c3111081cb2f0ddd004485f311 Mon Sep 17 00:00:00 2001 From: manlingtan Date: Sun, 22 Nov 2026 16:03:37 -0800 Subject: [PATCH 40/50] Update pyhealth.tasks.tpc_eicu.rst --- docs/api/tasks/pyhealth.tasks.tpc_eicu.rst | 54 +++++++++++----------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst index 4ab3d700b5..b9c8962b72 100644 --- a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst +++ b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst @@ -22,41 +22,41 @@ Hourly remaining ICU length of stay Implementation status --------------------- -The task implements adult/five-hour eligibility, admission static features, -hourly remaining-LOS labels, configurable observation removal, optional -decay features, and synthetic CSV validation. Dynamic extraction uses -existing YAIB helpers provisionally. Model training and ablation -experiments are documented separately. +The task implements adult cohort selection, hourly dynamic feature +extraction, admission static features, and hourly remaining-LOS labels. +The observation horizon is capped at 336 hours. -``TPCLengthOfStayEICU()`` supports observation removal through -``missing_rate`` values from 0.0 to 1.0. Missing observations -are represented by NaN, with deterministic masking based on -the random seed and stay identifier. +Observation removal is controlled by ``missing_rate`` (0.0 to 1.0). +Removal is deterministic for a given seed and stay identifier. +A rate of 0.0 preserves all observed values, while a rate of 1.0 +removes all observed feature cells. -When ``include_decay=True``, decay features are calculated -after observation removal. Observed values reset decay to -1.0; unobserved values decay by a factor of 0.75 per hour. +When ``include_decay=True``, decay features are calculated after +observation removal. Observed values reset to 1.0, and unobserved +values decay by a factor of 0.75 per hour. + +Missing dynamic values remain NaN in the task output. Forward filling +and normalization are handled by the configured YAIB preprocessing +pipeline. Extension points ---------------- * ``pyhealth/tasks/tpc_eicu.py`` implements hourly remaining-LOS - preprocessing, configurable observation removal, and optional - decay features. Observation removal is deterministic and - applied before decay calculation. -* ``TODO(A)`` in ``examples/eicu_hourly_los_lstm.py``: integrate existing training - work where available and complete explicit LSTM - training, patient-disjoint splits, agreed losses/metrics and the two-training - by three-test missingness study. This file is a scaffold and raises until - implemented. The example filename is present but the rubric's working - ablation requirement is still outstanding. -* Preprocessing contract tests in ``tests/core/test_tpc_eicu.py`` - cover observation removal and decay. Some hourly aggregation, - forward-fill, and combined preprocessing tests remain skipped - pending verification. -* Extend the integration check with actual model training when the training - implementation is available. Its current scope ends at CSV-to-task outputs. + preprocessing, deterministic observation removal, and optional + decay features. +* ``tests/core/test_tpc_eicu.py`` covers cohort selection, static + features, LOS labels, observation removal, decay, and temporal + consistency. Some hourly aggregation, forward-fill, and combined + preprocessing tests remain skipped pending verification. +* ``examples/eicu_hourly_los_lstm.py`` is the model-training and + missingness-ablation integration point. Complete and validate + model training, patient-disjoint splits, evaluation metrics, + and the two-training by three-test missingness study. +* The integration checkpoint currently validates synthetic + CSV-to-task outputs. It does not replace actual model training + or final experimental evaluation. Runnable validation ------------------- From 0ba13066e2e9700d0926515356925607373f4885 Mon Sep 17 00:00:00 2001 From: Yining Jin <52183621+EmilyJYN@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:05:37 -0600 Subject: [PATCH 41/50] Add RNN_V2 LSTM training, 6 metrics, and 2x3 missingness ablation --- examples/eicu_hourly_los_lstm.py | 542 +++++++++++++++++++++++++++++-- 1 file changed, 509 insertions(+), 33 deletions(-) diff --git a/examples/eicu_hourly_los_lstm.py b/examples/eicu_hourly_los_lstm.py index d1e1dcf716..5b526387c2 100644 --- a/examples/eicu_hourly_los_lstm.py +++ b/examples/eicu_hourly_los_lstm.py @@ -1,4 +1,3 @@ - """ Contributors: Manling Tan, Yining Jin, Xiao Luo NetIDs: manling4, yining34, xiaoluo6 @@ -14,51 +13,528 @@ https://arxiv.org/abs/2007.09483 """ +"""Hourly remaining ICU length-of-stay training and 2x3 missingness ablation. + +Trains PyHealth ``RNN_V2(rnn_type="LSTM")`` on ``TPCLengthOfStayEICU`` using +patient-disjoint splits (70% train / 15% validation / 15% test) and evaluates +the six paper metrics (MAD, MAPE, MSE, MSLE, R^2, and Cohen's linear weighted +Kappa) plus training-set mean/median baselines. + +Novel Missingness Robustness Ablation (2 x 3 design): + * Two training conditions with identical model architecture and splits: + Model A (0% extra observation removal) and Model B (10% extra random + observation removal before forward-fill). + * Three held-out test conditions (0%, 10%, 20% extra observation removal), + evaluated with deterministic per-stay seeds so both models see the exact + same masked test cells, while reusing each model's own training-fitted + imputation/normalization processors. + +Metric conventions (Section 5.3.1 & Appendix A/D of Rocheteau et al.): + * Targets and predictions are converted together from hours to days + (divided by 24.0) before scoring. + * MAPE clamps the true denominator below at 4/24 days (4 hours) to + prevent explosion near discharge. + * Zero-target policy & MSLE: exact-discharge labels from + ``TPCLengthOfStayEICU`` can equal 0.0 hours. Following Appendix A + of the paper (HardTanh bounds ``[1/48, 100]`` days), both targets + and predictions are clipped to ``[1/48, 100.0]`` days before taking + the natural logarithm for MSLE. + * Cohen's linear weighted Kappa discretizes days into 10 ordered bins: + ``[0-1, 1-2, 2-3, 3-4, 4-5, 5-6, 6-7, 7-8, 8-14, 14+]``. -"""Training and ablation extension points for the hourly ICU LOS task. +Examples: + Smoke check on five synthetic patients:: -STATUS: scaffold. This file does not yet train a model or report results. -The runnable data/task check is: - python -m examples.tpc_support.checkpoint + python examples/eicu_hourly_los_lstm.py --synthetic --epochs 2 -TODO(A): integrate existing code for splits, training, metrics and the 2x3 -missingness experiment below. Use the fixture generator for smoke checks; -use authorized eICU data for final findings. TODO(A/B): reuse the masking -implementation in repository-root tpc_eicu.py; integrate preprocessing and -complete decay before enabling those settings. Existing working code should -be merged and validated, not written again. + Run full 2x3 ablation on a local eICU-CRD or eICU Demo directory:: + + python examples/eicu_hourly_los_lstm.py --root /path/to/eicu-crd """ +import argparse +import gc +import json +import os +import tempfile +from pathlib import Path from typing import Any +# Bound native thread pools on Windows before importing torch/polars. +for _var in ("POLARS_MAX_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"): + os.environ.setdefault(_var, "4") -def train_and_evaluate() -> list[dict[str, Any]]: - """Run the final experiment once the extension points are complete. +import numpy as np +import torch +from sklearn.metrics import cohen_kappa_score, r2_score - TODO(A): - 1. Load eICUDataset; split unique patient IDs into train/validation/test. - 2. Fit processors on training patients only; reuse on held-out patients. - 3. Explicitly select RNN_V2(rnn_type="LSTM") and agreed input embeddings. - 4. Train with 0% and 10% extra observation removal, keeping other - settings controlled. Evaluate each at 0%, 10%, and 20% removal. - 5. Reuse test masks for both models; use seeded, documented repeats. - 6. Return metrics and experimental settings. Raw targets/activated - predictions are hours; convert together for day-based comparisons. - Specify a zero-target policy and paper-compatible MSLE convention. - 7. Document measured findings and differences from the original paper. +from examples.tpc_support.generate_synthetic import TABLES, generate +from pyhealth.datasets import PatientSplit, eICUDataset, get_dataloader +from pyhealth.models import RNN_V2 +from pyhealth.tasks import TPCLengthOfStayEICU +from pyhealth.trainer import Trainer +from pyhealth.utils import set_seed + +HOURS_PER_DAY = 24.0 +MAPE_FLOOR_DAYS = 4.0 / 24.0 +MIN_LOS_DAYS = 1.0 / 48.0 +MAX_LOS_DAYS = 100.0 +KAPPA_BIN_EDGES = (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 14.0) +KAPPA_LABELS = list(range(len(KAPPA_BIN_EDGES) + 1)) + +DEFAULT_TRAIN_RATES = (0.0, 0.1) +DEFAULT_TEST_RATES = (0.0, 0.1, 0.2) - Returns: - One result dictionary per experimental configuration. - Raises: - NotImplementedError: Until the training implementation is supplied. +def compute_los_metrics( + y_true_hours: np.ndarray, + y_pred_hours: np.ndarray, +) -> dict[str, float]: + """Compute the 6 paper LoS evaluation metrics in days. + + Args: + y_true_hours: 1D array of ground-truth remaining LoS in hours. + y_pred_hours: 1D array of predicted remaining LoS in hours. + + Returns: + Dictionary with keys ``mad``, ``mape``, ``mse``, ``msle``, ``r2``, + and ``kappa``. """ - raise NotImplementedError( - "TODO(A): implement training and ablations; " - "TODO(B): complete missingness/decay. " - "Run python -m examples.tpc_support.checkpoint for data/task validation." + y_true = np.asarray(y_true_hours, dtype=np.float64).reshape(-1) / HOURS_PER_DAY + y_pred = np.asarray(y_pred_hours, dtype=np.float64).reshape(-1) / HOURS_PER_DAY + if y_true.shape != y_pred.shape or y_true.size == 0: + raise ValueError( + f"Expected non-empty matching shapes, got {y_true.shape} and {y_pred.shape}." + ) + + abs_err = np.abs(y_true - y_pred) + mad = float(np.mean(abs_err)) + mape = float(np.mean(abs_err / np.maximum(y_true, MAPE_FLOOR_DAYS)) * 100.0) + mse = float(np.mean((y_true - y_pred) ** 2)) + + # Clip both targets and predictions to [1/48, 100] days for log-space MSLE. + log_true = np.log(np.clip(y_true, MIN_LOS_DAYS, MAX_LOS_DAYS)) + log_pred = np.log(np.clip(y_pred, MIN_LOS_DAYS, MAX_LOS_DAYS)) + msle = float(np.mean((log_true - log_pred) ** 2)) + + r2 = float(r2_score(y_true, y_pred)) if y_true.size >= 2 else float("nan") + + true_bins = np.digitize(y_true, KAPPA_BIN_EDGES, right=False) + pred_bins = np.digitize(y_pred, KAPPA_BIN_EDGES, right=False) + if len(np.unique(np.concatenate([true_bins, pred_bins]))) < 2: + kappa = 0.0 + else: + kappa = float( + cohen_kappa_score( + true_bins, + pred_bins, + labels=KAPPA_LABELS, + weights="linear", + ) + ) + if np.isnan(kappa): + kappa = 0.0 + + return { + "mad": mad, + "mape": mape, + "mse": mse, + "msle": msle, + "r2": r2, + "kappa": kappa, + } + + +def _extract_target_hours(dataset: Any, batch_size: int) -> np.ndarray: + """Extract unscaled ground-truth hourly targets from a SampleDataset.""" + label_proc = dataset.output_processors["los"] + loader = get_dataloader( + dataset, + batch_size=min(batch_size, len(dataset)), + shuffle=False, + ) + parts: list[np.ndarray] = [] + for batch in loader: + true_list, _ = label_proc.to_numpy(batch["los"], batch["los"][0]) + parts.extend(true_list) + return np.concatenate(parts, axis=0) + + +def compute_constant_baselines( + train_true_hours: np.ndarray, + test_true_hours: np.ndarray, +) -> dict[str, dict[str, float]]: + """Evaluate training-set mean and median baselines on test targets.""" + mean_hours = float(np.mean(train_true_hours)) + median_hours = float(np.median(train_true_hours)) + return { + "mean_baseline": compute_los_metrics( + test_true_hours, + np.full_like(test_true_hours, mean_hours, dtype=np.float64), + ), + "median_baseline": compute_los_metrics( + test_true_hours, + np.full_like(test_true_hours, median_hours, dtype=np.float64), + ), + } + + +def _build_embedding_dim( + embedding_dim: int, + include_decay: bool, +) -> dict[str, list[dict[str, int]]]: + """Build per-field LevelEmbedding config matching TPCLengthOfStayEICU.""" + config: dict[str, list[dict[str, int]]] = { + "dynamic": [{"values": embedding_dim}], + "static": [{"values": embedding_dim}], + } + if include_decay: + config["decay"] = [{"values": embedding_dim}] + return config + + +def _train_single_model( + base_dataset: eICUDataset, + *, + train_missing_rate: float, + include_decay: bool, + split: PatientSplit, + epochs: int, + batch_size: int, + lr: float, + embedding_dim: int, + hidden_dim: int, + num_layers: int, + dropout: float, + seed: int, + num_workers: int, + device: str, +) -> tuple[RNN_V2, Trainer, Any, Any, dict[int, Any], np.ndarray, dict[str, int]]: + """Train one LSTM model at ``train_missing_rate`` using training-only stats.""" + set_seed(seed) + train_task = TPCLengthOfStayEICU( + missing_rate=train_missing_rate, + seed=seed, + include_decay=include_decay, + ) + train_data, val_data, test_data = base_dataset.set_task( + train_task, + split=split, + num_workers=num_workers, + ) + sizes = { + "train": len(train_data), + "val": len(val_data), + "test": len(test_data), + } + if not all(sizes.values()): + raise ValueError(f"Empty dataset split encountered: {sizes}") + + train_loader = get_dataloader( + train_data, + batch_size=min(batch_size, len(train_data)), + shuffle=True, + seed=seed, + ) + val_loader = get_dataloader( + val_data, + batch_size=min(batch_size, len(val_data)), + shuffle=False, + ) + + model = RNN_V2( + dataset=train_data, + embedding_dim=_build_embedding_dim(embedding_dim, include_decay), + hidden_dim=hidden_dim, + rnn_type="LSTM", + num_layers=num_layers, + dropout=dropout, + bidirectional=False, + mask="concat", ) + trainer = Trainer( + model=model, + metrics=["mae", "mse"], + device=device, + enable_logging=False, + ) + trainer.train( + train_dataloader=train_loader, + val_dataloader=val_loader, + epochs=epochs, + optimizer_params={"lr": lr}, + monitor="loss", + monitor_criterion="min", + load_best_model_at_last=True, + max_grad_norm=5.0, + ) + + train_true_hours = _extract_target_hours(train_data, batch_size) + processors = (train_data.input_processors, train_data.output_processors) + # Free training/validation loader references while keeping fitted processors. + del train_loader, val_loader, train_data, val_data + return model, trainer, processors[0], processors[1], {0: test_data}, train_true_hours, sizes + + +def _format_results_table(rows: list[dict[str, Any]]) -> str: + """Format experiment results into a readable Markdown comparison table.""" + header = ( + "| Model / Condition | Train Drop | Test Drop | " + "MAD ↓ | MAPE (%) ↓ | MSE ↓ | MSLE ↓ | R^2 ↑ | Kappa ↑ |" + ) + sep = ( + "| :--- | :---: | :---: | " + ":---: | :---: | :---: | :---: | :---: | :---: |" + ) + lines = [header, sep] + for row in rows: + m = row["metrics"] + lines.append( + f"| {row['label']} | {row['train_missing_rate']:.0%} | " + f"{row['test_missing_rate']:.0%} | " + f"{m['mad']:.3f} | {m['mape']:.1f} | {m['mse']:.2f} | " + f"{m['msle']:.3f} | {m['r2']:.3f} | {m['kappa']:.3f} |" + ) + return "\n".join(lines) + + +def train_and_evaluate( + root: str | Path | None = None, + *, + synthetic: bool = False, + train_rates: tuple[float, ...] = DEFAULT_TRAIN_RATES, + test_rates: tuple[float, ...] = DEFAULT_TEST_RATES, + include_decay: bool = True, + epochs: int = 8, + batch_size: int = 64, + lr: float = 0.00129, + embedding_dim: int = 64, + hidden_dim: int = 128, + num_layers: int = 2, + dropout: float = 0.2, + seed: int = 42, + num_workers: int = 1, + device: str | None = None, + cache_dir: str | Path | None = None, +) -> list[dict[str, Any]]: + """Run the 2x3 missingness ablation study and return all metric rows.""" + if not synthetic and root is None: + raise ValueError("Provide --root or pass --synthetic.") + + chosen_device = device or ("cuda" if torch.cuda.is_available() else "cpu") + + def _run_with_root( + data_root: Path, + effective_cache: Path | None, + split_ratios: tuple[float, float, float], + ) -> list[dict[str, Any]]: + dataset_kwargs: dict[str, Any] = { + "root": str(data_root), + "tables": list(TABLES), + "num_workers": num_workers, + } + if effective_cache is not None: + dataset_kwargs["cache_dir"] = str(effective_cache) + + base_dataset = eICUDataset(**dataset_kwargs) + split = PatientSplit(ratios=split_ratios, seed=seed) + results: list[dict[str, Any]] = [] + baselines_recorded = False + + for train_rate in train_rates: + ( + model, + trainer, + in_procs, + out_procs, + cached_test_by_rate, + train_true_hours, + sizes, + ) = _train_single_model( + base_dataset, + train_missing_rate=train_rate, + include_decay=include_decay, + split=split, + epochs=epochs, + batch_size=batch_size, + lr=lr, + embedding_dim=embedding_dim, + hidden_dim=hidden_dim, + num_layers=num_layers, + dropout=dropout, + seed=seed, + num_workers=num_workers, + device=chosen_device, + ) + + model_label = f"LSTM (Train {train_rate:.0%} drop)" + for test_rate in test_rates: + if np.isclose(test_rate, train_rate): + test_data = cached_test_by_rate[0] + else: + test_task = TPCLengthOfStayEICU( + missing_rate=test_rate, + seed=seed, + include_decay=include_decay, + ) + # Reuse training-fitted processors so test stats never leak. + _, _, test_data = base_dataset.set_task( + test_task, + input_processors=in_procs, + output_processors=out_procs, + split=split, + num_workers=num_workers, + ) + + test_loader = get_dataloader( + test_data, + batch_size=min(batch_size, len(test_data)), + shuffle=False, + ) + y_true_stays, y_pred_stays, test_loss = trainer.inference(test_loader) + test_true_hours = np.concatenate(y_true_stays, axis=0) + test_pred_hours = np.concatenate(y_pred_stays, axis=0) + metrics = compute_los_metrics(test_true_hours, test_pred_hours) + + if not baselines_recorded and np.isclose(test_rate, 0.0): + baselines = compute_constant_baselines( + train_true_hours, test_true_hours + ) + for base_name, base_label in ( + ("mean_baseline", "Mean Baseline"), + ("median_baseline", "Median Baseline"), + ): + results.append( + { + "label": base_label, + "train_missing_rate": 0.0, + "test_missing_rate": test_rate, + "include_decay": include_decay, + "splits": sizes, + "n_test_hours": int(len(test_true_hours)), + "metrics": baselines[base_name], + } + ) + baselines_recorded = True + + results.append( + { + "label": model_label, + "train_missing_rate": float(train_rate), + "test_missing_rate": float(test_rate), + "include_decay": include_decay, + "splits": sizes, + "test_loss_scaled_mse": float(test_loss), + "n_test_hours": int(len(test_true_hours)), + "metrics": metrics, + } + ) + del test_loader, test_data + + del trainer, model, in_procs, out_procs, cached_test_by_rate + gc.collect() + if torch.device(chosen_device).type == "cuda": + torch.cuda.empty_cache() + + del base_dataset + gc.collect() + return results + + if synthetic: + with tempfile.TemporaryDirectory( + prefix="tpc-lstm-ablation-", ignore_cleanup_errors=True + ) as tmp: + tmp_path = Path(tmp) + csv_dir = tmp_path / "csv" + generate(csv_dir) + # Only 3 of the 5 synthetic stays pass cohort criteria; + # (0.4, 0.3, 0.3) guarantees 1 train / 1 val / 1 test patient. + return _run_with_root(csv_dir, tmp_path / "cache", (0.4, 0.3, 0.3)) + + assert root is not None + data_root = Path(root).expanduser().resolve() + effective_cache = ( + Path(cache_dir).expanduser().resolve() if cache_dir is not None else None + ) + return _run_with_root(data_root, effective_cache, (0.7, 0.15, 0.15)) + + +def _parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--root", + type=Path, + default=None, + help="Path to eICU-CRD or eICU Demo CSV directory.", + ) + parser.add_argument( + "--synthetic", + action="store_true", + help="Run a fast smoke ablation on generated synthetic patients.", + ) + parser.add_argument( + "--train-rates", + type=float, + nargs="+", + default=list(DEFAULT_TRAIN_RATES), + help="Training missingness rates (default: 0.0 0.1).", + ) + parser.add_argument( + "--test-rates", + type=float, + nargs="+", + default=list(DEFAULT_TEST_RATES), + help="Test missingness rates (default: 0.0 0.1 0.2).", + ) + parser.add_argument( + "--no-decay", + dest="include_decay", + action="store_false", + help="Disable exponential decay indicators (0.75^hours_since_obs).", + ) + parser.set_defaults(include_decay=True) + parser.add_argument("--epochs", type=int, default=8) + parser.add_argument("--batch-size", type=int, default=64) + parser.add_argument("--lr", type=float, default=0.00129) + parser.add_argument("--embedding-dim", type=int, default=64) + parser.add_argument("--hidden-dim", type=int, default=128) + parser.add_argument("--num-layers", type=int, default=2) + parser.add_argument("--dropout", type=float, default=0.2) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--num-workers", type=int, default=1) + parser.add_argument("--device", type=str, default=None) + parser.add_argument("--cache-dir", type=Path, default=None) + parser.add_argument( + "--output-json", + type=Path, + default=None, + help="Optional path to save full JSON metrics.", + ) + return parser.parse_args() if __name__ == "__main__": - train_and_evaluate() + args = _parse_args() + rows = train_and_evaluate( + root=args.root, + synthetic=args.synthetic, + train_rates=tuple(args.train_rates), + test_rates=tuple(args.test_rates), + include_decay=args.include_decay, + epochs=args.epochs, + batch_size=args.batch_size, + lr=args.lr, + embedding_dim=args.embedding_dim, + hidden_dim=args.hidden_dim, + num_layers=args.num_layers, + dropout=args.dropout, + seed=args.seed, + num_workers=args.num_workers, + device=args.device, + cache_dir=args.cache_dir, + ) + print("\n=== Hourly Remaining ICU LoS (2x3 Missingness Ablation) ===") + print(_format_results_table(rows)) + if args.output_json is not None: + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(rows, indent=2), encoding="utf-8") From 47f03a58ae3caf3665b0381f4e8bc69475579166 Mon Sep 17 00:00:00 2001 From: Yining Jin <52183621+EmilyJYN@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:38:10 -0600 Subject: [PATCH 42/50] Complete TPC eICU LoS example results, PR rules, docs, and tests --- docs/api/tasks/pyhealth.tasks.tpc_eicu.rst | 26 +++---- examples/eicu_hourly_los_lstm.py | 73 +++++++++++++++--- examples/tpc_support/checkpoint.py | 14 ++-- examples/tpc_support/generate_synthetic.py | 1 + pyhealth/tasks/tpc_eicu.py | 29 +++++-- tests/core/test_tpc_eicu.py | 7 +- tests/core/tpc_fixtures.py | 2 + tests/integration/test_tpc_checkpoint.py | 2 + tests/integration/test_tpc_real.py | 89 ---------------------- 9 files changed, 112 insertions(+), 131 deletions(-) delete mode 100644 tests/integration/test_tpc_real.py diff --git a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst index b9c8962b72..ed5b289fbd 100644 --- a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst +++ b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst @@ -40,23 +40,21 @@ and normalization are handled by the configured YAIB preprocessing pipeline. -Extension points ----------------- +Implementation summary +---------------------- * ``pyhealth/tasks/tpc_eicu.py`` implements hourly remaining-LOS preprocessing, deterministic observation removal, and optional decay features. * ``tests/core/test_tpc_eicu.py`` covers cohort selection, static - features, LOS labels, observation removal, decay, and temporal - consistency. Some hourly aggregation, forward-fill, and combined - preprocessing tests remain skipped pending verification. -* ``examples/eicu_hourly_los_lstm.py`` is the model-training and - missingness-ablation integration point. Complete and validate - model training, patient-disjoint splits, evaluation metrics, - and the two-training by three-test missingness study. -* The integration checkpoint currently validates synthetic - CSV-to-task outputs. It does not replace actual model training - or final experimental evaluation. + features, LOS labels, observation removal, decay, forward-fill + integration, and temporal consistency using synthetic patients. +* ``examples/eicu_hourly_los_lstm.py`` implements end-to-end + ``RNN_V2(rnn_type="LSTM")`` training, all six paper metrics + (MAD, MAPE, MSE, MSLE, R^2, and Cohen's linear weighted Kappa), + and the 2x3 missingness robustness ablation study. +* ``tests/integration/test_tpc_checkpoint.py`` provides an opt-in + synthetic CSV-to-task loader check. Runnable validation ------------------- @@ -67,7 +65,9 @@ From a repository checkout in Python 3.12 or 3.13:: python examples/tpc_support/generate_synthetic.py /tmp/tpc_synthetic python -m examples.tpc_support.checkpoint --output /tmp/tpc_checkpoint.json python -m pytest tests/core/test_tpc_eicu.py -q --durations=5 - PYHEALTH_RUN_TPC_INTEGRATION=1 python -m pytest tests/integration/test_tpc_checkpoint.py -q + PYHEALTH_RUN_TPC_INTEGRATION=1 python -m pytest \ + tests/integration/test_tpc_checkpoint.py -q + python examples/eicu_hourly_los_lstm.py --synthetic --epochs 2 All seven generated CSVs use invented records across five patients. The checkpoint verifies cohort selection, static values, aggregated measurements diff --git a/examples/eicu_hourly_los_lstm.py b/examples/eicu_hourly_los_lstm.py index 5b526387c2..db893cb0e0 100644 --- a/examples/eicu_hourly_los_lstm.py +++ b/examples/eicu_hourly_los_lstm.py @@ -11,9 +11,8 @@ Paper URL: https://arxiv.org/abs/2007.09483 -""" -"""Hourly remaining ICU length-of-stay training and 2x3 missingness ablation. +Hourly remaining ICU length-of-stay training and 2x3 missingness ablation. Trains PyHealth ``RNN_V2(rnn_type="LSTM")`` on ``TPCLengthOfStayEICU`` using patient-disjoint splits (70% train / 15% validation / 15% test) and evaluates @@ -42,6 +41,50 @@ * Cohen's linear weighted Kappa discretizes days into 10 ordered bins: ``[0-1, 1-2, 2-3, 3-4, 4-5, 5-6, 6-7, 7-8, 8-14, 14+]``. +Experimental Setup & Measured Results (15,000-patient eICU-CRD subset): + * Subset & split: 15,000 unique patients sampled uniformly at random + (seed=42), split 70% / 15% / 15% by ``patient_id``. + * Model & training: ``RNN_V2(rnn_type="LSTM")``, ``embedding_dim=64``, + ``hidden_dim=128``, ``num_layers=2``, ``dropout=0.2``, ``mask="concat"``, + ``include_decay=True``, ``lr=0.00129``, ``batch_size=128``, ``epochs=8``, + MSE loss on min-max normalized hours (PyHealth default for + ``timeseries_regression``). + * Results (in days): + + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + | Model / Condition | Train Drop | Test Drop | MAD ↓ | MAPE (%) | MSE ↓ | MSLE | R^2 ↑ | Kappa ↑ | + +=======================+============+===========+=======+==========+=======+=======+========+=========+ + | Mean Baseline | 0% | 0% | 3.336 | 413.3 | 28.24 | 2.750 | -0.002 | 0.000 | + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + | Median Baseline | 0% | 0% | 2.837 | 187.8 | 31.32 | 2.008 | -0.111 | 0.000 | + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + | LSTM (Train 0% drop) | 0% | 0% | 2.859 | 260.7 | 24.72 | 2.266 | 0.123 | 0.253 | + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + | LSTM (Train 0% drop) | 0% | 10% | 2.839 | 255.6 | 24.79 | 2.256 | 0.120 | 0.247 | + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + | LSTM (Train 0% drop) | 0% | 20% | 2.819 | 251.1 | 24.84 | 2.223 | 0.118 | 0.243 | + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + | LSTM (Train 10% drop) | 10% | 0% | 2.893 | 271.6 | 24.74 | 2.205 | 0.122 | 0.252 | + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + | LSTM (Train 10% drop) | 10% | 10% | 2.869 | 266.3 | 24.76 | 2.189 | 0.121 | 0.247 | + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + | LSTM (Train 10% drop) | 10% | 20% | 2.844 | 261.1 | 24.77 | 2.153 | 0.121 | 0.243 | + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + + * Findings: + 1. Baseline alignment: our 15k subset baselines closely match the full + eICU paper baselines (Table 2: Mean MAD 3.21 / MSE 29.5; Median MAD + 2.76 / MSE 32.6), and ``LSTM (Train 0% drop)`` at 0% test drop + closely tracks the paper's ``Standard LSTM (MSE)`` (MSE 24.72 vs + 24.5, Kappa 0.253 vs 0.28). Remaining gaps reflect using ~10% of + patients, 48 YAIB dynamic + 4 static features (vs 87 + 17), and + MSE loss rather than log-space MSLE loss. + 2. Robustness ablation: as test missingness increases from 0% to 20%, + Model A (0% train drop) degrades by +0.12 MSE and -0.005 R^2, whereas + Model B (10% train drop) degrades by only +0.03 MSE and -0.001 R^2, + outperforming Model A on MSE, R^2, and MSLE under 10% and 20% + missingness. + Examples: Smoke check on five synthetic patients:: @@ -273,7 +316,15 @@ def _train_single_model( processors = (train_data.input_processors, train_data.output_processors) # Free training/validation loader references while keeping fitted processors. del train_loader, val_loader, train_data, val_data - return model, trainer, processors[0], processors[1], {0: test_data}, train_true_hours, sizes + return ( + model, + trainer, + processors[0], + processors[1], + {0: test_data}, + train_true_hours, + sizes, + ) def _format_results_table(rows: list[dict[str, Any]]) -> str: @@ -282,10 +333,7 @@ def _format_results_table(rows: list[dict[str, Any]]) -> str: "| Model / Condition | Train Drop | Test Drop | " "MAD ↓ | MAPE (%) ↓ | MSE ↓ | MSLE ↓ | R^2 ↑ | Kappa ↑ |" ) - sep = ( - "| :--- | :---: | :---: | " - ":---: | :---: | :---: | :---: | :---: | :---: |" - ) + sep = "| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |" lines = [header, sep] for row in rows: m = row["metrics"] @@ -411,7 +459,7 @@ def _run_with_root( "test_missing_rate": test_rate, "include_decay": include_decay, "splits": sizes, - "n_test_hours": int(len(test_true_hours)), + "n_test_hours": len(test_true_hours), "metrics": baselines[base_name], } ) @@ -425,7 +473,7 @@ def _run_with_root( "include_decay": include_decay, "splits": sizes, "test_loss_scaled_mse": float(test_loss), - "n_test_hours": int(len(test_true_hours)), + "n_test_hours": len(test_true_hours), "metrics": metrics, } ) @@ -536,5 +584,8 @@ def _parse_args() -> argparse.Namespace: print("\n=== Hourly Remaining ICU LoS (2x3 Missingness Ablation) ===") print(_format_results_table(rows)) if args.output_json is not None: - args.output_json.parent.mkdir(parents=True, exist_ok=True) - args.output_json.write_text(json.dumps(rows, indent=2), encoding="utf-8") + out_path = args.output_json + if out_path.is_dir(): + out_path = out_path / "results.json" + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text(json.dumps(rows, indent=2), encoding="utf-8") diff --git a/examples/tpc_support/checkpoint.py b/examples/tpc_support/checkpoint.py index 28a61df997..224a7ef809 100644 --- a/examples/tpc_support/checkpoint.py +++ b/examples/tpc_support/checkpoint.py @@ -13,16 +13,17 @@ https://arxiv.org/abs/2007.09483 """ - """Synthetic CSV-to-task checkpoint for cohort, static features and labels.""" -from pathlib import Path import json import tempfile +from pathlib import Path + import numpy as np + +from examples.tpc_support.generate_synthetic import TABLES, generate from pyhealth.datasets import eICUDataset from pyhealth.tasks import TPCLengthOfStayEICU -from examples.tpc_support.generate_synthetic import generate, TABLES def run(root: Path) -> dict: @@ -71,16 +72,15 @@ def value(hour, name): assert samples[103]["los"]["values"][-1] == [64.5] assert samples[103]["dynamic"]["values"][0, names.index("hr")] == 100 assert np.isnan(samples[105]["static"]["values"][0][2]) - # TODO(A): downstream model validation belongs in the training - # example once preprocessing and the agreed input interface are complete. + # Downstream model training and ablation live in examples/eicu_hourly_los_lstm.py. return { "status": "passed", "scope": "CSV loading, cohort, static features, hourly labels", "synthetic_patients": 5, "included_stays": [101, 103, 105], "excluded_stays": [102, 104], - "model_training": "pending training integration", - "missingness_and_decay": "pending preprocessing integration", + "model_training": "implemented in examples/eicu_hourly_los_lstm.py", + "missingness_and_decay": "implemented in TPCLengthOfStayEICU", } diff --git a/examples/tpc_support/generate_synthetic.py b/examples/tpc_support/generate_synthetic.py index 5305d56257..33797699cc 100644 --- a/examples/tpc_support/generate_synthetic.py +++ b/examples/tpc_support/generate_synthetic.py @@ -18,6 +18,7 @@ import csv from pathlib import Path + import yaml TABLES = [ diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py index a32fff617f..b0c4b94e7c 100644 --- a/pyhealth/tasks/tpc_eicu.py +++ b/pyhealth/tasks/tpc_eicu.py @@ -11,9 +11,9 @@ Paper URL: https://arxiv.org/abs/2007.09483 -""" -"""Hourly remaining ICU length-of-stay task with missingness experiments.""" +Hourly remaining ICU length-of-stay task with missingness experiments. +""" import hashlib from copy import deepcopy @@ -49,6 +49,25 @@ class TPCLengthOfStayEICU(YAIBLengthOfStayEICU): between 0 and 1. seed: Seed combined with stay ID for reproducible masking. include_decay: Whether to add per-feature decay sequences. + + Examples: + >>> from pyhealth.datasets import eICUDataset + >>> from pyhealth.tasks import TPCLengthOfStayEICU + >>> task = TPCLengthOfStayEICU(missing_rate=0.1, include_decay=True) + >>> task.task_name + 'TPCLengthOfStayEICU' + >>> dataset = eICUDataset( # doctest: +SKIP + ... root="/path/to/eicu-crd/2.0", + ... tables=[ + ... "lab", + ... "vitalperiodic", + ... "vitalaperiodic", + ... "intakeoutput", + ... "respiratorycharting", + ... "nursecharting", + ... ], + ... ) + >>> samples = dataset.set_task(task) # doctest: +SKIP """ task_name: str = "TPCLengthOfStayEICU" @@ -114,8 +133,7 @@ def _base_cohort( stays = stays.filter(pl.col("stay_id").is_in(keep)) - # TODO: Verify Table 16 feature coverage and hourly - # aggregation against the project requirements. + # Extract the 48 hourly YAIB dynamic features for eligible adult stays. hourly = self._hourly( self._measurements( patient, @@ -194,7 +212,7 @@ def _apply_missingness( if n_hide == 0: return values - key = f"{self.seed}:{stay_id}".encode("utf-8") + key = f"{self.seed}:{stay_id}".encode() stay_seed = int.from_bytes( hashlib.sha256(key).digest()[:8], @@ -246,7 +264,6 @@ def __call__( "los_hours", "end", ).iter_rows(): - if end < self.START_HOUR: continue diff --git a/tests/core/test_tpc_eicu.py b/tests/core/test_tpc_eicu.py index 02eb07c71a..3ce31a9e55 100644 --- a/tests/core/test_tpc_eicu.py +++ b/tests/core/test_tpc_eicu.py @@ -26,7 +26,7 @@ import pytest from pyhealth.tasks import TPCLengthOfStayEICU -from tests.core.tpc_fixtures import _patient, _labels, _lab +from tests.core.tpc_fixtures import _lab, _labels, _patient @pytest.mark.parametrize( @@ -129,7 +129,6 @@ def test_invalid_rate(rate): TPCLengthOfStayEICU(missing_rate=rate) -@pytest.mark.skip(reason="Pending verification of hourly aggregation semantics") def test_hourly_measurements_and_missing_data(): """Check hourly lab aggregation and masking.""" task = TPCLengthOfStayEICU() @@ -158,7 +157,6 @@ def test_hourly_measurements_and_missing_data(): assert masked["static"] == sample["static"] -@pytest.mark.skip(reason="Pending verification of processor forward-fill integration") def test_forward_fill_after_removal(): """Check forward-fill behavior after missingness removal.""" from pyhealth.processors import JaggedFeatureProcessor @@ -290,7 +288,7 @@ def test_stays_are_isolated(): def test_empty_patient(): """Return no samples for a patient without admission records.""" from pyhealth.data import Patient - from tests.core.tpc_fixtures import _frame, _event + from tests.core.tpc_fixtures import _event, _frame patient = Patient( patient_id="empty", @@ -304,7 +302,6 @@ def test_empty_patient(): "rate", [0, 0.1, 0.2, 1], ) -@pytest.mark.skip(reason="Pending verification of combined processor integration") def test_combined_mask_fill_and_decay(rate): """Check masking, forward-fill, and decay together.""" from pyhealth.processors import JaggedFeatureProcessor diff --git a/tests/core/tpc_fixtures.py b/tests/core/tpc_fixtures.py index 4be5489700..4616adf0a7 100644 --- a/tests/core/tpc_fixtures.py +++ b/tests/core/tpc_fixtures.py @@ -17,8 +17,10 @@ """Small synthetic eICU records; adapted from YAIB regression fixtures.""" from pathlib import Path + import polars as pl import yaml + from pyhealth.data import Patient # Every column of the eICU config, as in the dataset's event dataframe. diff --git a/tests/integration/test_tpc_checkpoint.py b/tests/integration/test_tpc_checkpoint.py index a9b857a1fa..61e97037a6 100644 --- a/tests/integration/test_tpc_checkpoint.py +++ b/tests/integration/test_tpc_checkpoint.py @@ -20,7 +20,9 @@ """ import os + import pytest + from examples.tpc_support.checkpoint import run diff --git a/tests/integration/test_tpc_real.py b/tests/integration/test_tpc_real.py deleted file mode 100644 index e044ad202e..0000000000 --- a/tests/integration/test_tpc_real.py +++ /dev/null @@ -1,89 +0,0 @@ -""" -Contributors: Manling Tan, Yining Jin, Xiao Luo -NetID: manling4, yining34, xiaoluo6 - -Paper Title: -Temporal Pointwise Convolutional Networks for -Length of Stay Prediction in the Intensive Care Unit - -Paper Authors: -Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) - -Paper URL: -https://arxiv.org/abs/2007.09483 -""" - - -"""Integration test for TPC hourly ICU length-of-stay prediction. - -Loads real eICU data and inspects generated task samples -under different missing-data rates. -""" - -from multiprocessing import freeze_support - -from pyhealth.datasets import eICUDataset -from pyhealth.tasks.tpc_eicu import TPCLengthOfStayEICU - - -def main() -> None: - """Test TPC task processing on real eICU data. - - Loads the eICU dataset and generates task samples using - missing rates of 0%, 10%, and 20%. - - Prints the number of generated samples and the structure - of dynamic features and LOS labels for each missing rate. - """ - root = "eicu-crd-2.0" - - dataset = eICUDataset( - root=root, - tables=[ - "lab", - "vitalperiodic", - "vitalaperiodic", - "intakeoutput", - "respiratorycharting", - "nursecharting", - ], - ) - - print("Dataset loaded successfully.") - - for rate in [0.0, 0.1, 0.2]: - print(f"\nTesting missing rate: {rate:.0%}") - - task = TPCLengthOfStayEICU( - missing_rate=rate, - seed=42, - ) - - samples = dataset.set_task( - task=task, - num_workers=1, - ) - - print("Number of samples:", len(samples)) - - if len(samples) > 0: - sample = samples[0] - - print("Dynamic type:", type(sample["dynamic"])) - print( - "Dynamic structure:", - [getattr(x, "shape", type(x).__name__) for x in sample["dynamic"]], - ) - - print("LOS type:", type(sample["los"])) - print( - "LOS structure:", - [getattr(x, "shape", type(x).__name__) for x in sample["los"]], - ) - - print("\nIntegration test finished.") - - -if __name__ == "__main__": - freeze_support() - main() From 4af6fe2c2b7854683939c23352f713c0932cfb17 Mon Sep 17 00:00:00 2001 From: ah-ling68 Date: Thu, 26 Nov 2026 16:17:21 -0800 Subject: [PATCH 43/50] Adapt TPC eICU task to updated YAIB and RNN_V2 APIs --- pyhealth/tasks/tpc_eicu.py | 5 +++-- tests/core/test_tpc_eicu.py | 12 ++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py index b0c4b94e7c..fd38abdb47 100644 --- a/pyhealth/tasks/tpc_eicu.py +++ b/pyhealth/tasks/tpc_eicu.py @@ -89,8 +89,8 @@ def __init__( self.missing_rate = missing_rate self.seed = seed self.include_decay = include_decay - self.input_schema = deepcopy(type(self).input_schema) + self.output_schema = deepcopy(type(self).output_schema) if include_decay: self.input_schema["decay"] = ( @@ -104,6 +104,7 @@ def __init__( ] }, ) + self.output_schema["los"][1]["timeline"].append("decay") def _base_cohort( self, @@ -307,7 +308,7 @@ def __call__( "patient_id": patient.patient_id, "stay_id": stay_id, "dynamic": dynamic, - "static": self._static_series(static[stay_id]), + "static": self._static_record(static[stay_id]), "los": self._labels( prediction_hours, remaining, diff --git a/tests/core/test_tpc_eicu.py b/tests/core/test_tpc_eicu.py index 3ce31a9e55..03543ee65c 100644 --- a/tests/core/test_tpc_eicu.py +++ b/tests/core/test_tpc_eicu.py @@ -431,3 +431,15 @@ def test_zero_removal_baseline_and_completed_extensions(): decay, [[1.0, 0.0]], ) + + +def test_output_timeline_with_optional_decay(): + """Ensure temporal features use the correct prediction timeline.""" + with_decay = TPCLengthOfStayEICU(include_decay=True) + without_decay = TPCLengthOfStayEICU(include_decay=False) + + assert with_decay.output_schema["los"][1]["timeline"] == [ + "dynamic", + "decay", + ] + assert without_decay.output_schema["los"][1]["timeline"] == ["dynamic"] From d7f644f541ebd6892cbff6c5735a528ec5bcfb1f Mon Sep 17 00:00:00 2001 From: ah-ling68 Date: Thu, 26 Nov 2026 17:35:24 -0800 Subject: [PATCH 44/50] Align default batch size with reported experimental settings --- examples/eicu_hourly_los_lstm.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/eicu_hourly_los_lstm.py b/examples/eicu_hourly_los_lstm.py index db893cb0e0..105bf3d208 100644 --- a/examples/eicu_hourly_los_lstm.py +++ b/examples/eicu_hourly_los_lstm.py @@ -354,7 +354,7 @@ def train_and_evaluate( test_rates: tuple[float, ...] = DEFAULT_TEST_RATES, include_decay: bool = True, epochs: int = 8, - batch_size: int = 64, + batch_size: int = 128, lr: float = 0.00129, embedding_dim: int = 64, hidden_dim: int = 128, @@ -542,7 +542,7 @@ def _parse_args() -> argparse.Namespace: ) parser.set_defaults(include_decay=True) parser.add_argument("--epochs", type=int, default=8) - parser.add_argument("--batch-size", type=int, default=64) + parser.add_argument("--batch-size", type=int, default=128) parser.add_argument("--lr", type=float, default=0.00129) parser.add_argument("--embedding-dim", type=int, default=64) parser.add_argument("--hidden-dim", type=int, default=128) From 5ab8a04e211d25a50ccb11d967d2549f405910b1 Mon Sep 17 00:00:00 2001 From: Yining Jin <52183621+EmilyJYN@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:47:54 -0600 Subject: [PATCH 45/50] Address AI review feedback on metrics tests, pre-rebase notes, and docs --- docs/api/tasks/pyhealth.tasks.tpc_eicu.rst | 51 ++++++++--------- examples/eicu_hourly_los_lstm.py | 49 ++++++++++------ pyhealth/tasks/tpc_eicu.py | 4 +- tests/core/test_tpc_eicu.py | 65 ++++++++++++++++++++++ 4 files changed, 126 insertions(+), 43 deletions(-) diff --git a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst index ed5b289fbd..7d1b8631f2 100644 --- a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst +++ b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst @@ -27,9 +27,10 @@ extraction, admission static features, and hourly remaining-LOS labels. The observation horizon is capped at 336 hours. Observation removal is controlled by ``missing_rate`` (0.0 to 1.0). -Removal is deterministic for a given seed and stay identifier. -A rate of 0.0 preserves all observed values, while a rate of 1.0 -removes all observed feature cells. +Removal uses one deterministic mask per stay for a given seed and stay +identifier, so repeated training epochs over the same dataset see the same +masked observations. A rate of 0.0 preserves all observed values, while a rate +of 1.0 removes all observed feature cells. When ``include_decay=True``, decay features are calculated after observation removal. Observed values reset to 1.0, and unobserved @@ -56,8 +57,8 @@ Implementation summary * ``tests/integration/test_tpc_checkpoint.py`` provides an opt-in synthetic CSV-to-task loader check. -Runnable validation -------------------- +Usage and validation +-------------------- From a repository checkout in Python 3.12 or 3.13:: @@ -69,17 +70,18 @@ From a repository checkout in Python 3.12 or 3.13:: tests/integration/test_tpc_checkpoint.py -q python examples/eicu_hourly_los_lstm.py --synthetic --epochs 2 -All seven generated CSVs use invented records across five patients. The -checkpoint verifies cohort selection, static values, aggregated measurements -and remaining-LOS labels against independent numerical expectations. It does -not train a model. The real loader check starts a local processing server and -is opt-in. Core assertion execution is fast; imports still add startup time. +The synthetic CSV generator produces invented records across five patients. +The checkpoint script validates cohort selection, static values, aggregated +measurements, and remaining-LOS labels against independent numerical +expectations without training a model. The CSV integration test is opt-in to +keep routine unit test runs fast. -Input/output contract to review +Input and output specification ------------------------------ -Load lab, vitalperiodic, vitalaperiodic, intakeoutput, respiratorycharting and -nursecharting using eICUDataset. One sample is produced per eligible stay: +Load ``lab``, ``vitalperiodic``, ``vitalaperiodic``, ``intakeoutput``, +``respiratorycharting``, and ``nursecharting`` using :class:`~pyhealth.datasets.eICUDataset`. +One sample is produced per eligible stay: * Adults have known age >=18 and total ICU stay >=5 hours; ``> 89`` maps to 90. Unknown age excludes the stay. Unknown sex or invalid height/weight is NaN. @@ -87,21 +89,20 @@ nursecharting using eICUDataset. One sample is produced per eligible stay: * Dynamic uses 48 YAIB features. For H=min(floor(total LOS hours),336), its values have shape (H,48), with missing values retained as NaN. * Bin [b,b+1) becomes available at timestamp b+1. At hour 5 the model may - consume bins 0–4 only. Regenerate older cached samples with start-bin times. + consume bins 0–4 only. * Labels at hours 5..H have shape (H-4,1) and equal total LOS hours minus h. Exact-discharge labels may be zero. The observation horizon is capped; remaining LOS is not capped. -* ``missing_rate`` controls removal of observed hourly feature cells. - A rate of 0.0 preserves observations; 1.0 removes all observed cells. +* ``missing_rate`` controls deterministic per-stay removal of observed hourly + feature cells prior to forward-fill. A rate of 0.0 preserves observations; + 1.0 removes all observed cells. * ``include_decay=True`` adds decay features matching the dynamic feature dimensions. Decay resets to 1.0 upon observation and decreases by a factor of 0.75 per unobserved hour. -* Split by patient_id rather than stay_id. Fit learned processors on training - patients only. Existing YAIB label processors min-max scale training targets; - activated predictions return original hours. Avoid double unscaling. - -This reproduces the prediction problem, not the TPC architecture. Existing -median/floor aggregation and YAIB features differ from the paper. Confirm -preprocessing, loss and metric conventions before comparing paper results. -The original paper already ablates decay removal; a decay toggle alone is -not a novel extension for the assignment. +* Split by ``patient_id`` rather than ``stay_id``, and fit learned processors + on training patients only. Existing YAIB label processors min-max scale + training targets, while inference returns unscaled predictions in hours. + +This task reproduces the hourly remaining-LOS prediction formulation from the +paper using YAIB feature extraction and PyHealth's existing preprocessing +pipeline, rather than re-implementing the TPC model architecture. diff --git a/examples/eicu_hourly_los_lstm.py b/examples/eicu_hourly_los_lstm.py index 105bf3d208..5871baa6dd 100644 --- a/examples/eicu_hourly_los_lstm.py +++ b/examples/eicu_hourly_los_lstm.py @@ -41,7 +41,10 @@ * Cohen's linear weighted Kappa discretizes days into 10 ordered bins: ``[0-1, 1-2, 2-3, 3-4, 4-5, 5-6, 6-7, 7-8, 8-14, 14+]``. -Experimental Setup & Measured Results (15,000-patient eICU-CRD subset): +Pre-Rebase Experimental Setup & Results (15,000-patient eICU-CRD subset): + * Note: These single-seed (``seed=42``) numerical results were measured + prior to rebasing onto upstream PyHealth ``master`` and have not been + rerun after the rebase. * Subset & split: 15,000 unique patients sampled uniformly at random (seed=42), split 70% / 15% / 15% by ``patient_id``. * Model & training: ``RNN_V2(rnn_type="LSTM")``, ``embedding_dim=64``, @@ -49,7 +52,7 @@ ``include_decay=True``, ``lr=0.00129``, ``batch_size=128``, ``epochs=8``, MSE loss on min-max normalized hours (PyHealth default for ``timeseries_regression``). - * Results (in days): + * Results (in days, pre-rebase, ``seed=42``): +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ | Model / Condition | Train Drop | Test Drop | MAD ↓ | MAPE (%) | MSE ↓ | MSLE | R^2 ↑ | Kappa ↑ | @@ -79,10 +82,11 @@ 24.5, Kappa 0.253 vs 0.28). Remaining gaps reflect using ~10% of patients, 48 YAIB dynamic + 4 static features (vs 87 + 17), and MSE loss rather than log-space MSLE loss. - 2. Robustness ablation: as test missingness increases from 0% to 20%, - Model A (0% train drop) degrades by +0.12 MSE and -0.005 R^2, whereas - Model B (10% train drop) degrades by only +0.03 MSE and -0.001 R^2, - outperforming Model A on MSE, R^2, and MSLE under 10% and 20% + 2. Robustness ablation: in this single-seed (``seed=42``) evaluation, as + test missingness increases from 0% to 20%, Model A (0% train drop) + degrades by +0.12 MSE and -0.005 R^2, whereas Model B (10% train drop) + degrades by only +0.03 MSE and -0.001 R^2, achieving lower MSE and + MSLE and slightly higher R^2 than Model A under 10% and 20% missingness. Examples: @@ -101,22 +105,19 @@ import os import tempfile from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any # Bound native thread pools on Windows before importing torch/polars. for _var in ("POLARS_MAX_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"): os.environ.setdefault(_var, "4") import numpy as np -import torch from sklearn.metrics import cohen_kappa_score, r2_score -from examples.tpc_support.generate_synthetic import TABLES, generate -from pyhealth.datasets import PatientSplit, eICUDataset, get_dataloader -from pyhealth.models import RNN_V2 -from pyhealth.tasks import TPCLengthOfStayEICU -from pyhealth.trainer import Trainer -from pyhealth.utils import set_seed +if TYPE_CHECKING: + from pyhealth.datasets import PatientSplit, eICUDataset + from pyhealth.models import RNN_V2 + from pyhealth.trainer import Trainer HOURS_PER_DAY = 24.0 MAPE_FLOOR_DAYS = 4.0 / 24.0 @@ -190,6 +191,8 @@ def compute_los_metrics( def _extract_target_hours(dataset: Any, batch_size: int) -> np.ndarray: """Extract unscaled ground-truth hourly targets from a SampleDataset.""" + from pyhealth.datasets import get_dataloader + label_proc = dataset.output_processors["los"] loader = get_dataloader( dataset, @@ -237,11 +240,11 @@ def _build_embedding_dim( def _train_single_model( - base_dataset: eICUDataset, + base_dataset: "eICUDataset", *, train_missing_rate: float, include_decay: bool, - split: PatientSplit, + split: "PatientSplit", epochs: int, batch_size: int, lr: float, @@ -252,8 +255,14 @@ def _train_single_model( seed: int, num_workers: int, device: str, -) -> tuple[RNN_V2, Trainer, Any, Any, dict[int, Any], np.ndarray, dict[str, int]]: +) -> tuple["RNN_V2", "Trainer", Any, Any, dict[int, Any], np.ndarray, dict[str, int]]: """Train one LSTM model at ``train_missing_rate`` using training-only stats.""" + from pyhealth.datasets import get_dataloader + from pyhealth.models import RNN_V2 + from pyhealth.tasks import TPCLengthOfStayEICU + from pyhealth.trainer import Trainer + from pyhealth.utils import set_seed + set_seed(seed) train_task = TPCLengthOfStayEICU( missing_rate=train_missing_rate, @@ -369,6 +378,12 @@ def train_and_evaluate( if not synthetic and root is None: raise ValueError("Provide --root or pass --synthetic.") + import torch + + from examples.tpc_support.generate_synthetic import TABLES, generate + from pyhealth.datasets import PatientSplit, eICUDataset, get_dataloader + from pyhealth.tasks import TPCLengthOfStayEICU + chosen_device = device or ("cuda" if torch.cuda.is_available() else "cpu") def _run_with_root( diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py index fd38abdb47..1ad328aa6d 100644 --- a/pyhealth/tasks/tpc_eicu.py +++ b/pyhealth/tasks/tpc_eicu.py @@ -40,7 +40,9 @@ class TPCLengthOfStayEICU(YAIBLengthOfStayEICU): Inherited sequence_v2 processors handle normalization and forward-fill downstream. - Missingness is applied to observed values before processing. + Missingness is applied to observed values before processing using one + deterministic mask per stay (derived from ``seed`` and ``stay_id``), + so every training epoch sees the same masked matrix for a given stay. Decay is computed from the post-masking, pre-forward-fill observation matrix. diff --git a/tests/core/test_tpc_eicu.py b/tests/core/test_tpc_eicu.py index 03543ee65c..9ab3d8f93a 100644 --- a/tests/core/test_tpc_eicu.py +++ b/tests/core/test_tpc_eicu.py @@ -22,9 +22,15 @@ missingness, decay, temporal leakage prevention, and stay isolation. """ +import math + import numpy as np import pytest +from examples.eicu_hourly_los_lstm import ( + compute_constant_baselines, + compute_los_metrics, +) from pyhealth.tasks import TPCLengthOfStayEICU from tests.core.tpc_fixtures import _lab, _labels, _patient @@ -443,3 +449,62 @@ def test_output_timeline_with_optional_decay(): "decay", ] assert without_decay.output_schema["los"][1]["timeline"] == ["dynamic"] + + +def test_compute_los_metrics_conventions(): + """Verify day conversion, 4h MAPE floor, MSLE clipping, R^2, and Kappa.""" + # Targets: [0h, 24h, 48h] -> [0, 1, 2] days; + # Preds: [2h, 24h, 72h] -> [1/12, 1, 3] days. + metrics = compute_los_metrics( + np.array([0.0, 24.0, 48.0]), + np.array([2.0, 24.0, 72.0]), + ) + + expected_mad = (2.0 / 24.0 + 0.0 + 1.0) / 3.0 + expected_mape = ((2.0 / 24.0) / (4.0 / 24.0) + 0.0 + 1.0 / 2.0) / 3.0 * 100.0 + expected_mse = ((2.0 / 24.0) ** 2 + 0.0 + 1.0) / 3.0 + expected_msle = ( + (math.log(2.0 / 24.0) - math.log(1.0 / 48.0)) ** 2 + + 0.0 + + (math.log(3.0) - math.log(2.0)) ** 2 + ) / 3.0 + + assert math.isclose(metrics["mad"], expected_mad, rel_tol=1e-9) + assert math.isclose(metrics["mape"], expected_mape, rel_tol=1e-9) + assert math.isclose(metrics["mse"], expected_mse, rel_tol=1e-9) + assert math.isclose(metrics["msle"], expected_msle, rel_tol=1e-9) + assert math.isclose(metrics["r2"], 1.0 - (3.0 * expected_mse) / 2.0, rel_tol=1e-9) + assert 0.0 <= metrics["kappa"] <= 1.0 + + # Negative predictions must be safely clipped for MSLE without NaNs. + neg_metrics = compute_los_metrics( + np.array([24.0, 48.0]), + np.array([-5.0, 48.0]), + ) + assert np.isfinite(neg_metrics["msle"]) + + +def test_compute_los_metrics_single_bin_and_validation(): + """Verify degenerate single-bin Kappa fallback and input validation.""" + single_bin = compute_los_metrics( + np.array([1.0, 2.0, 3.0]), + np.array([4.0, 5.0, 6.0]), + ) + assert single_bin["kappa"] == 0.0 + + with pytest.raises(ValueError): + compute_los_metrics(np.array([1.0, 2.0]), np.array([1.0])) + with pytest.raises(ValueError): + compute_los_metrics(np.array([]), np.array([])) + + +def test_compute_constant_baselines(): + """Verify training-set mean and median baselines score test targets.""" + baselines = compute_constant_baselines( + np.array([24.0, 24.0, 72.0]), + np.array([24.0, 72.0]), + ) + # Train mean = 40h (5/3 days), train median = 24h (1 day). + assert math.isclose(baselines["mean_baseline"]["mad"], 1.0, rel_tol=1e-9) + assert math.isclose(baselines["median_baseline"]["mad"], 1.0, rel_tol=1e-9) + assert baselines["mean_baseline"]["mse"] < baselines["median_baseline"]["mse"] From ba14b3f2041a2b46930b8ba76a6bcf17567c128d Mon Sep 17 00:00:00 2001 From: Yining Jin <52183621+EmilyJYN@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:50:31 -0600 Subject: [PATCH 46/50] Fix direct script import path, add synthetic ablation test, use jagged processor, and fix RST heading --- docs/api/tasks/pyhealth.tasks.tpc_eicu.rst | 2 +- examples/eicu_hourly_los_lstm.py | 5 ++++ pyhealth/tasks/tpc_eicu.py | 2 +- tests/core/test_tpc_eicu.py | 28 ++++++++++++++++++++++ 4 files changed, 35 insertions(+), 2 deletions(-) diff --git a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst index 7d1b8631f2..e6ae1e906d 100644 --- a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst +++ b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst @@ -13,7 +13,7 @@ Hourly remaining ICU length of stay -================================== +=================================== .. automodule:: pyhealth.tasks.tpc_eicu :members: diff --git a/examples/eicu_hourly_los_lstm.py b/examples/eicu_hourly_los_lstm.py index 5871baa6dd..b16b1e51b8 100644 --- a/examples/eicu_hourly_los_lstm.py +++ b/examples/eicu_hourly_los_lstm.py @@ -103,10 +103,15 @@ import gc import json import os +import sys import tempfile from pathlib import Path from typing import TYPE_CHECKING, Any +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + # Bound native thread pools on Windows before importing torch/polars. for _var in ("POLARS_MAX_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"): os.environ.setdefault(_var, "4") diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py index 1ad328aa6d..115da59210 100644 --- a/pyhealth/tasks/tpc_eicu.py +++ b/pyhealth/tasks/tpc_eicu.py @@ -96,7 +96,7 @@ def __init__( if include_decay: self.input_schema["decay"] = ( - "sequence_v2", + "jagged", { "levels": [ { diff --git a/tests/core/test_tpc_eicu.py b/tests/core/test_tpc_eicu.py index 9ab3d8f93a..097f0c57d8 100644 --- a/tests/core/test_tpc_eicu.py +++ b/tests/core/test_tpc_eicu.py @@ -30,6 +30,7 @@ from examples.eicu_hourly_los_lstm import ( compute_constant_baselines, compute_los_metrics, + train_and_evaluate, ) from pyhealth.tasks import TPCLengthOfStayEICU from tests.core.tpc_fixtures import _lab, _labels, _patient @@ -508,3 +509,30 @@ def test_compute_constant_baselines(): assert math.isclose(baselines["mean_baseline"]["mad"], 1.0, rel_tol=1e-9) assert math.isclose(baselines["median_baseline"]["mad"], 1.0, rel_tol=1e-9) assert baselines["mean_baseline"]["mse"] < baselines["median_baseline"]["mse"] + + +def test_train_and_evaluate_synthetic_smoke(): + """Verify train_and_evaluate runs end-to-end on synthetic patients.""" + rows = train_and_evaluate( + synthetic=True, + epochs=1, + test_rates=(0.0, 0.1), + batch_size=2, + embedding_dim=8, + hidden_dim=16, + num_layers=1, + device="cpu", + ) + + assert len(rows) == 6 + labels = [row["label"] for row in rows] + assert "Mean Baseline" in labels + assert "Median Baseline" in labels + assert labels.count("LSTM (Train 0% drop)") == 2 + assert labels.count("LSTM (Train 10% drop)") == 2 + + metric_names = ("mad", "mape", "mse", "msle", "r2", "kappa") + for row in rows: + assert row["n_test_hours"] > 0 + for name in metric_names: + assert math.isfinite(row["metrics"][name]) From daa9bcd5a127f3a3601127ee9901dffe23307c6a Mon Sep 17 00:00:00 2001 From: ah-ling68 Date: Sat, 28 Nov 2026 11:51:52 -0800 Subject: [PATCH 47/50] Clarify external patient subset preparation --- examples/eicu_hourly_los_lstm.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/examples/eicu_hourly_los_lstm.py b/examples/eicu_hourly_los_lstm.py index b16b1e51b8..20e40e88ab 100644 --- a/examples/eicu_hourly_los_lstm.py +++ b/examples/eicu_hourly_los_lstm.py @@ -41,12 +41,16 @@ * Cohen's linear weighted Kappa discretizes days into 10 ordered bins: ``[0-1, 1-2, 2-3, 3-4, 4-5, 5-6, 6-7, 7-8, 8-14, 14+]``. -Pre-Rebase Experimental Setup & Results (15,000-patient eICU-CRD subset): +Pre-Rebase Experimental Setup & Results (eICU-CRD subset): * Note: These single-seed (``seed=42``) numerical results were measured prior to rebasing onto upstream PyHealth ``master`` and have not been rerun after the rebase. - * Subset & split: 15,000 unique patients sampled uniformly at random - (seed=42), split 70% / 15% / 15% by ``patient_id``. + * Subset & split: The reported pre-rebase experiments used a subset + of 15,000 eICU-CRD patients. The current script does not perform + patient subsampling automatically. To reproduce the reported + results, the corresponding subset must be prepared externally + and provided through ``--root``. + Patients are split 70% / 15% / 15% by ``patient_id`` (seed=42). * Model & training: ``RNN_V2(rnn_type="LSTM")``, ``embedding_dim=64``, ``hidden_dim=128``, ``num_layers=2``, ``dropout=0.2``, ``mask="concat"``, ``include_decay=True``, ``lr=0.00129``, ``batch_size=128``, ``epochs=8``, @@ -75,13 +79,13 @@ +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ * Findings: - 1. Baseline alignment: our 15k subset baselines closely match the full + 1. Baseline alignment: our experimental subset baselines closely match the full eICU paper baselines (Table 2: Mean MAD 3.21 / MSE 29.5; Median MAD 2.76 / MSE 32.6), and ``LSTM (Train 0% drop)`` at 0% test drop closely tracks the paper's ``Standard LSTM (MSE)`` (MSE 24.72 vs - 24.5, Kappa 0.253 vs 0.28). Remaining gaps reflect using ~10% of - patients, 48 YAIB dynamic + 4 static features (vs 87 + 17), and - MSE loss rather than log-space MSLE loss. + 24.5, Kappa 0.253 vs 0.28). Remaining gaps may reflect differences in cohort + size, 48 YAIB dynamic + 4 static features (vs 87 + 17), and MSE loss rather + than log-space MSLE loss. 2. Robustness ablation: in this single-seed (``seed=42``) evaluation, as test missingness increases from 0% to 20%, Model A (0% train drop) degrades by +0.12 MSE and -0.005 R^2, whereas Model B (10% train drop) From 4d747aaf3f5d655d7de134fc3a7fa8ba28d3f3cb Mon Sep 17 00:00:00 2001 From: ah-ling68 Date: Sat, 28 Nov 2026 13:31:54 -0800 Subject: [PATCH 48/50] Clamp LOS labels and support optional label normalization --- docs/api/tasks/pyhealth.tasks.tpc_eicu.rst | 30 +++++++++++++++--- pyhealth/tasks/tpc_eicu.py | 13 ++++++-- tests/core/test_tpc_eicu.py | 36 +++++++++++++++++++++- 3 files changed, 71 insertions(+), 8 deletions(-) diff --git a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst index e6ae1e906d..f2a219345f 100644 --- a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst +++ b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst @@ -26,6 +26,14 @@ The task implements adult cohort selection, hourly dynamic feature extraction, admission static features, and hourly remaining-LOS labels. The observation horizon is capped at 336 hours. +Remaining LOS labels are clamped to a minimum of 0.5 hours +(1/48 day). + +Label normalization is controlled by ``normalize_labels``. +The default is ``True``, which preserves YAIB's min-max label +normalization. Set ``normalize_labels=False`` to preserve raw +remaining-LOS labels in hours for MSLE-based models. + Observation removal is controlled by ``missing_rate`` (0.0 to 1.0). Removal uses one deterministic mask per stay for a given seed and stay identifier, so repeated training epochs over the same dataset see the same @@ -90,9 +98,10 @@ One sample is produced per eligible stay: values have shape (H,48), with missing values retained as NaN. * Bin [b,b+1) becomes available at timestamp b+1. At hour 5 the model may consume bins 0–4 only. -* Labels at hours 5..H have shape (H-4,1) and equal total LOS hours minus h. - Exact-discharge labels may be zero. The observation horizon is capped; - remaining LOS is not capped. +* Labels at hours 5..H have shape (H-4,1) and equal + max(0.5, total LOS hours - h). All raw labels are at least + 0.5 hours, including exact-discharge labels. The observation + horizon is capped; remaining LOS is not capped. * ``missing_rate`` controls deterministic per-stay removal of observed hourly feature cells prior to forward-fill. A rate of 0.0 preserves observations; 1.0 removes all observed cells. @@ -100,8 +109,19 @@ One sample is produced per eligible stay: feature dimensions. Decay resets to 1.0 upon observation and decreases by a factor of 0.75 per unobserved hour. * Split by ``patient_id`` rather than ``stay_id``, and fit learned processors - on training patients only. Existing YAIB label processors min-max scale - training targets, while inference returns unscaled predictions in hours. + on training patients only. By default, YAIB label processors min-max scale + training targets. Set ``normalize_labels=False`` to disable label + normalization and retain raw LOS targets in hours for MSLE-based models. + +For models requiring unnormalized LOS targets:: + + from pyhealth.tasks import TPCLengthOfStayEICU + + task = TPCLengthOfStayEICU( + missing_rate=0.1, + include_decay=True, + normalize_labels=False, + ) This task reproduces the hourly remaining-LOS prediction formulation from the paper using YAIB feature extraction and PyHealth's existing preprocessing diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py index 115da59210..33159b1cb3 100644 --- a/pyhealth/tasks/tpc_eicu.py +++ b/pyhealth/tasks/tpc_eicu.py @@ -32,6 +32,7 @@ class TPCLengthOfStayEICU(YAIBLengthOfStayEICU): Static features are inherited from YAIB. Labels are in hours, starting at hour 5 and continuing through min(floor(LOS), 336). + Remaining LOS labels are clamped to a minimum of 0.5 hours. Dynamic timestamps represent completed hourly bins: bin [h-1, h) is available at hour h. @@ -51,6 +52,9 @@ class TPCLengthOfStayEICU(YAIBLengthOfStayEICU): between 0 and 1. seed: Seed combined with stay ID for reproducible masking. include_decay: Whether to add per-feature decay sequences. + normalize_labels: Whether to apply min-max normalization to LOS + labels during processing. Defaults to True. Set to False + to preserve raw LOS labels in hours. Examples: >>> from pyhealth.datasets import eICUDataset @@ -82,8 +86,9 @@ def __init__( missing_rate: float = 0.0, seed: int = 42, include_decay: bool = False, + normalize_labels: bool = True, ) -> None: - """Configure masking and optional decay features.""" + """Configure masking, decay features, and label normalization.""" if not 0.0 <= missing_rate <= 1.0: raise ValueError("missing_rate must be between 0 and 1.") @@ -94,6 +99,9 @@ def __init__( self.input_schema = deepcopy(type(self).input_schema) self.output_schema = deepcopy(type(self).output_schema) + if not normalize_labels: + self.output_schema["los"][1]["normalization"] = None + if include_decay: self.input_schema["decay"] = ( "jagged", @@ -298,9 +306,10 @@ def __call__( ) ] + # Clamp remaining LOS to 0.5 hours for MSLE compatibility. remaining = [ max( - 0.0, + 0.5, float(los_hours) - hour, ) for hour in prediction_hours diff --git a/tests/core/test_tpc_eicu.py b/tests/core/test_tpc_eicu.py index 097f0c57d8..b3013a1fa6 100644 --- a/tests/core/test_tpc_eicu.py +++ b/tests/core/test_tpc_eicu.py @@ -86,7 +86,7 @@ def test_labels_and_horizon(): short_sample = task(_patient(hours=5, hr_hours=[]))[0] - assert _labels(short_sample["los"]) == [0] + assert _labels(short_sample["los"]) == [0.5] def test_fractional_remaining_hours(): @@ -97,6 +97,40 @@ def test_fractional_remaining_hours(): assert _labels(sample["los"]) == [1.5, 0.5] +def test_minimum_remaining_los(): + """Ensure remaining LOS labels are at least 0.5 hours.""" + sample = TPCLengthOfStayEICU()(_patient(hours=6.25, hr_hours=[]))[0] + + assert sample["los"]["time"] == [5, 6] + assert _labels(sample["los"]) == [1.25, 0.5] + + +def test_optional_label_normalization(): + """Verify optional LOS normalization and schema isolation.""" + from pyhealth.processors import TimeseriesRegressionLabelProcessor + + normalized = TPCLengthOfStayEICU() + raw = TPCLengthOfStayEICU(normalize_labels=False) + + assert normalized.output_schema["los"][1]["normalization"] == "minmax" + assert raw.output_schema["los"][1]["normalization"] is None + + default_task = TPCLengthOfStayEICU() + assert default_task.output_schema["los"][1]["normalization"] == "minmax" + + sample = raw(_patient(hours=6.25, hr_hours=[]))[0] + + processor = TimeseriesRegressionLabelProcessor(**raw.output_schema["los"][1]) + processor.fit([sample], "los") + + values, times = processor.process(sample["los"]) + + np.testing.assert_allclose( + values.reshape(-1).numpy(), + [1.25, 0.5], + ) + + def test_missingness_count_repeatability_no_mutation(): """Verify masking fraction, reproducibility, and input safety.""" values = np.arange(20, dtype=float).reshape(5, 4) From 53bbffbeaf2c639a0bdf751079655d85722c4044 Mon Sep 17 00:00:00 2001 From: ah-ling68 Date: Sat, 28 Nov 2026 13:43:11 -0800 Subject: [PATCH 49/50] Document synthetic CSVs and move checkpoint test into CI suite --- docs/api/tasks/pyhealth.tasks.tpc_eicu.rst | 16 ++++++++++------ .../{integration => core}/test_tpc_checkpoint.py | 14 +------------- 2 files changed, 11 insertions(+), 19 deletions(-) rename tests/{integration => core}/test_tpc_checkpoint.py (62%) diff --git a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst index f2a219345f..d8f5211ace 100644 --- a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst +++ b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst @@ -62,8 +62,8 @@ Implementation summary ``RNN_V2(rnn_type="LSTM")`` training, all six paper metrics (MAD, MAPE, MSE, MSLE, R^2, and Cohen's linear weighted Kappa), and the 2x3 missingness robustness ablation study. -* ``tests/integration/test_tpc_checkpoint.py`` provides an opt-in - synthetic CSV-to-task loader check. +* ``tests/core/test_tpc_checkpoint.py`` provides a synthetic + CSV-to-task loader check that runs as part of the core test suite. Usage and validation -------------------- @@ -74,15 +74,19 @@ From a repository checkout in Python 3.12 or 3.13:: python examples/tpc_support/generate_synthetic.py /tmp/tpc_synthetic python -m examples.tpc_support.checkpoint --output /tmp/tpc_checkpoint.json python -m pytest tests/core/test_tpc_eicu.py -q --durations=5 - PYHEALTH_RUN_TPC_INTEGRATION=1 python -m pytest \ - tests/integration/test_tpc_checkpoint.py -q + python -m pytest tests/core/test_tpc_checkpoint.py -q python examples/eicu_hourly_los_lstm.py --synthetic --epochs 2 The synthetic CSV generator produces invented records across five patients. +The committed CSV files in ``examples/tpc_support/synthetic_eicu/`` +serve as illustrative examples of the expected eICU data format for +manual inspection. They are not required at runtime. The synthetic +generator creates fresh CSV files for the example and checkpoint scripts. + The checkpoint script validates cohort selection, static values, aggregated measurements, and remaining-LOS labels against independent numerical -expectations without training a model. The CSV integration test is opt-in to -keep routine unit test runs fast. +expectations without training a model. The CSV-to-task checkpoint test +is included in the core test suite. Input and output specification ------------------------------ diff --git a/tests/integration/test_tpc_checkpoint.py b/tests/core/test_tpc_checkpoint.py similarity index 62% rename from tests/integration/test_tpc_checkpoint.py rename to tests/core/test_tpc_checkpoint.py index 61e97037a6..efd7fafbf9 100644 --- a/tests/integration/test_tpc_checkpoint.py +++ b/tests/core/test_tpc_checkpoint.py @@ -13,23 +13,11 @@ https://arxiv.org/abs/2007.09483 """ - -"""Opt-in real CSV loader/task smoke check; fast task tests live in core. - -Set PYHEALTH_RUN_TPC_INTEGRATION=1 to run this slower local-server check. -""" - -import os - -import pytest +"""Synthetic CSV loader and task smoke test.""" from examples.tpc_support.checkpoint import run -@pytest.mark.skipif( - os.environ.get("PYHEALTH_RUN_TPC_INTEGRATION") != "1", - reason="Opt-in CSV/Dask/task check; set PYHEALTH_RUN_TPC_INTEGRATION=1", -) def test_csv_to_task(tmp_path): result = run(tmp_path) assert result["status"] == "passed" From 403ad23c0573a8d3457bb346a7e5d1f71136fb15 Mon Sep 17 00:00:00 2001 From: ah-ling68 Date: Sat, 28 Nov 2026 20:05:34 -0800 Subject: [PATCH 50/50] Address AI review feedback on TPC task and example --- docs/api/tasks/pyhealth.tasks.tpc_eicu.rst | 16 ------------ examples/eicu_hourly_los_lstm.py | 30 ++++++++++++---------- examples/tpc_support/checkpoint.py | 4 +-- examples/tpc_support/generate_synthetic.py | 5 ++-- pyhealth/tasks/__init__.py | 6 ++--- tests/core/test_tpc_checkpoint.py | 4 +-- tests/core/test_tpc_eicu.py | 16 +++++++----- tests/core/tpc_fixtures.py | 7 +++-- 8 files changed, 38 insertions(+), 50 deletions(-) diff --git a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst index d8f5211ace..7acff7904c 100644 --- a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst +++ b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst @@ -49,22 +49,6 @@ and normalization are handled by the configured YAIB preprocessing pipeline. -Implementation summary ----------------------- - -* ``pyhealth/tasks/tpc_eicu.py`` implements hourly remaining-LOS - preprocessing, deterministic observation removal, and optional - decay features. -* ``tests/core/test_tpc_eicu.py`` covers cohort selection, static - features, LOS labels, observation removal, decay, forward-fill - integration, and temporal consistency using synthetic patients. -* ``examples/eicu_hourly_los_lstm.py`` implements end-to-end - ``RNN_V2(rnn_type="LSTM")`` training, all six paper metrics - (MAD, MAPE, MSE, MSLE, R^2, and Cohen's linear weighted Kappa), - and the 2x3 missingness robustness ablation study. -* ``tests/core/test_tpc_checkpoint.py`` provides a synthetic - CSV-to-task loader check that runs as part of the core test suite. - Usage and validation -------------------- diff --git a/examples/eicu_hourly_los_lstm.py b/examples/eicu_hourly_los_lstm.py index 20e40e88ab..f93eb39b55 100644 --- a/examples/eicu_hourly_los_lstm.py +++ b/examples/eicu_hourly_los_lstm.py @@ -33,11 +33,12 @@ (divided by 24.0) before scoring. * MAPE clamps the true denominator below at 4/24 days (4 hours) to prevent explosion near discharge. - * Zero-target policy & MSLE: exact-discharge labels from - ``TPCLengthOfStayEICU`` can equal 0.0 hours. Following Appendix A - of the paper (HardTanh bounds ``[1/48, 100]`` days), both targets - and predictions are clipped to ``[1/48, 100.0]`` days before taking - the natural logarithm for MSLE. + * Minimum-target policy & MSLE: raw remaining-LOS labels from + ``TPCLengthOfStayEICU`` are clamped to a minimum of 0.5 hours. + Following Appendix A of the paper (HardTanh bounds + ``[1/48, 100]`` days), both targets and predictions are clipped + to ``[1/48, 100.0]`` days before taking the natural logarithm + for MSLE. * Cohen's linear weighted Kappa discretizes days into 10 ordered bins: ``[0-1, 1-2, 2-3, 3-4, 4-5, 5-6, 6-7, 7-8, 8-14, 14+]``. @@ -112,13 +113,14 @@ from pathlib import Path from typing import TYPE_CHECKING, Any -REPO_ROOT = Path(__file__).resolve().parents[1] -if str(REPO_ROOT) not in sys.path: - sys.path.insert(0, str(REPO_ROOT)) +if __name__ == "__main__": + REPO_ROOT = Path(__file__).resolve().parents[1] + if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) -# Bound native thread pools on Windows before importing torch/polars. -for _var in ("POLARS_MAX_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"): - os.environ.setdefault(_var, "4") + # Bound native thread pools before importing numerical libraries. + for _var in ("POLARS_MAX_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"): + os.environ.setdefault(_var, "4") import numpy as np from sklearn.metrics import cohen_kappa_score, r2_score @@ -468,7 +470,7 @@ def _run_with_root( test_pred_hours = np.concatenate(y_pred_stays, axis=0) metrics = compute_los_metrics(test_true_hours, test_pred_hours) - if not baselines_recorded and np.isclose(test_rate, 0.0): + if not baselines_recorded: baselines = compute_constant_baselines( train_true_hours, test_true_hours ) @@ -479,8 +481,8 @@ def _run_with_root( results.append( { "label": base_label, - "train_missing_rate": 0.0, - "test_missing_rate": test_rate, + "train_missing_rate": float(train_rate), + "test_missing_rate": float(test_rate), "include_decay": include_decay, "splits": sizes, "n_test_hours": len(test_true_hours), diff --git a/examples/tpc_support/checkpoint.py b/examples/tpc_support/checkpoint.py index 224a7ef809..bc7f6c9310 100644 --- a/examples/tpc_support/checkpoint.py +++ b/examples/tpc_support/checkpoint.py @@ -11,9 +11,9 @@ Paper URL: https://arxiv.org/abs/2007.09483 -""" -"""Synthetic CSV-to-task checkpoint for cohort, static features and labels.""" +Synthetic CSV-to-task checkpoint for cohort, static features and labels. +""" import json import tempfile diff --git a/examples/tpc_support/generate_synthetic.py b/examples/tpc_support/generate_synthetic.py index 33797699cc..a5d68e34ef 100644 --- a/examples/tpc_support/generate_synthetic.py +++ b/examples/tpc_support/generate_synthetic.py @@ -11,10 +11,9 @@ Paper URL: https://arxiv.org/abs/2007.09483 -""" - -"""Write five invented patients in the shipped eICU CSV schema.""" +Write five invented patients in the shipped eICU CSV schema. +""" import csv from pathlib import Path diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index 737e9b6d9b..18db1f83d5 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -334,6 +334,8 @@ YAIBMortalityEICU as YAIBMortalityEICU, YAIBSepsisEICU as YAIBSepsisEICU, ) + +from .tpc_eicu import TPCLengthOfStayEICU as TPCLengthOfStayEICU from .tcga_survival_prediction import TCGASurvivalPrediction as TCGASurvivalPrediction from .query_focused_ehr import QueryFocusedEHRTask as QueryFocusedEHRTask @@ -346,6 +348,4 @@ def __getattr__(name: str): from .ptbxl import PTBXLSuperclassClassification return PTBXLSuperclassClassification - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - -from .tpc_eicu import TPCLengthOfStayEICU as TPCLengthOfStayEICU + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") \ No newline at end of file diff --git a/tests/core/test_tpc_checkpoint.py b/tests/core/test_tpc_checkpoint.py index efd7fafbf9..c4195b9e21 100644 --- a/tests/core/test_tpc_checkpoint.py +++ b/tests/core/test_tpc_checkpoint.py @@ -11,9 +11,9 @@ Paper URL: https://arxiv.org/abs/2007.09483 -""" -"""Synthetic CSV loader and task smoke test.""" +Synthetic CSV loader and task smoke test. +""" from examples.tpc_support.checkpoint import run diff --git a/tests/core/test_tpc_eicu.py b/tests/core/test_tpc_eicu.py index b3013a1fa6..ee5915b050 100644 --- a/tests/core/test_tpc_eicu.py +++ b/tests/core/test_tpc_eicu.py @@ -11,9 +11,8 @@ Paper URL: https://arxiv.org/abs/2007.09483 -""" -"""Synthetic cohort, hourly-label, and preprocessing regression tests. +Synthetic cohort, hourly-label, and preprocessing regression tests. Tests for the TPCLengthOfStayEICU task using synthetic patient data. No real clinical records are used. @@ -546,11 +545,11 @@ def test_compute_constant_baselines(): def test_train_and_evaluate_synthetic_smoke(): - """Verify train_and_evaluate runs end-to-end on synthetic patients.""" + """Verify synthetic training and baselines without a zero test rate.""" rows = train_and_evaluate( synthetic=True, epochs=1, - test_rates=(0.0, 0.1), + test_rates=(0.1, 0.2), batch_size=2, embedding_dim=8, hidden_dim=16, @@ -560,11 +559,16 @@ def test_train_and_evaluate_synthetic_smoke(): assert len(rows) == 6 labels = [row["label"] for row in rows] - assert "Mean Baseline" in labels - assert "Median Baseline" in labels + assert labels.count("Mean Baseline") == 1 + assert labels.count("Median Baseline") == 1 assert labels.count("LSTM (Train 0% drop)") == 2 assert labels.count("LSTM (Train 10% drop)") == 2 + for row in rows: + if row["label"] in ("Mean Baseline", "Median Baseline"): + assert row["train_missing_rate"] == 0.0 + assert row["test_missing_rate"] == 0.1 + metric_names = ("mad", "mape", "mse", "msle", "r2", "kappa") for row in rows: assert row["n_test_hours"] > 0 diff --git a/tests/core/tpc_fixtures.py b/tests/core/tpc_fixtures.py index 4616adf0a7..aa9ee844de 100644 --- a/tests/core/tpc_fixtures.py +++ b/tests/core/tpc_fixtures.py @@ -1,6 +1,6 @@ """ Contributors: Manling Tan, Yining Jin, Xiao Luo -NetID: manling4, yining34, xiaoluo6 +NetIDs: manling4, yining34, xiaoluo6 Paper Title: Temporal Pointwise Convolutional Networks for @@ -11,10 +11,9 @@ Paper URL: https://arxiv.org/abs/2007.09483 -""" - -"""Small synthetic eICU records; adapted from YAIB regression fixtures.""" +Small synthetic eICU records; adapted from YAIB regression fixtures. +""" from pathlib import Path