"""Load aligned RealICU inputs and reference labels without the experiment code.""" from __future__ import annotations import argparse import json import math from collections.abc import Collection from pathlib import Path from typing import Any import pandas as pd EVENT_COLUMNS = [ "time", "code", "code_specifics", "numeric_value", "text_value", "source_event_index", "icu_event_index", ] class RealICULoader: """Read one stay once, then select any of its published label windows.""" def __init__(self, root: str | Path, label_set: str, stay_id: str) -> None: if label_set not in {"gold", "scale"}: raise ValueError("label_set must be 'gold' or 'scale'") root = Path(root) stays = pd.read_parquet( root / "trajectories/icu_stay.parquet", filters=[("stay_id", "==", stay_id)], columns=["stay_id", "enter_time", "leave_time"], ) if len(stays) != 1: raise ValueError(f"Expected one ICU stay for {stay_id}, found {len(stays)}") with (root / label_set / "labels" / f"{stay_id}.json").open(encoding="utf-8") as handle: payload = json.load(handle) if payload["stay_id"] != stay_id: raise ValueError(f"Label stay_id does not match {stay_id}") self._windows = {window["window_index"]: window for window in payload["window_outputs"]} if not self._windows or len(self._windows) != len(payload["window_outputs"]): raise ValueError(f"Empty or duplicate label windows for {stay_id}") self.stay_id = stay_id self.enter_time = pd.Timestamp(stays.iloc[0]["enter_time"]) self.leave_time = pd.Timestamp(stays.iloc[0]["leave_time"]) self.window_indices = tuple(sorted(self._windows)) self._events = pd.read_parquet( root / "trajectories/events.parquet", filters=[("stay_id", "==", stay_id)], columns=EVENT_COLUMNS, ).sort_values(["time", "source_event_index"], kind="stable").reset_index(drop=True) @staticmethod def _history_start(anchor: pd.Timestamp, hours: float | None) -> pd.Timestamp | None: if hours is None: return None if not math.isfinite(hours) or hours < 0: raise ValueError("History hours must be finite and nonnegative, or None for all available history") return anchor - pd.Timedelta(hours=hours) def _slice_events( self, start: pd.Timestamp | None, end: pd.Timestamp, excluded_event_codes: Collection[str], ) -> pd.DataFrame: times = self._events["time"] left = 0 if start is None else times.searchsorted(start, side="left") right = times.searchsorted(end, side="left") events = self._events.iloc[left:right] return events.loc[~events["code"].isin(excluded_event_codes)].copy().reset_index(drop=True) def load_window( self, window_index: int, *, icu_history_hours: float | None, pre_icu_history_hours: float | None, excluded_event_codes: Collection[str], ) -> dict[str, Any]: """Return input event tables and labels; None selects all history, zero selects none.""" window = self._windows[window_index] metadata = window["window_metadata"] start = pd.Timestamp(metadata["window_start_time"]) end = pd.Timestamp(metadata["window_end_time"]) if not self.enter_time <= start < end <= self.leave_time: raise ValueError(f"Window {window_index} lies outside ICU stay {self.stay_id}") history_start = self._history_start(start, icu_history_hours) if history_start is None or history_start < self.enter_time: history_start = self.enter_time pre_icu_start = self._history_start(self.enter_time, pre_icu_history_hours) return { "input": { "sample_id": window["sample_id"], "stay_id": self.stay_id, "window_start_time": start, "window_end_time": end, "pre_icu_events": self._slice_events(pre_icu_start, self.enter_time, excluded_event_codes), "history_events": self._slice_events(history_start, start, excluded_event_codes), "current_events": self._slice_events(start, end, excluded_event_codes), }, "labels": { "reference_labels": window["reference_labels"], "label_availability": window["label_availability"], }, } def _parse_history_hours(value: str) -> float | None: if value == "all": return None try: hours = float(value) except ValueError as error: raise argparse.ArgumentTypeError("Use 'all' or a nonnegative number of hours") from error if not math.isfinite(hours) or hours < 0: raise argparse.ArgumentTypeError("Use 'all' or a finite, nonnegative number of hours") return hours def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, required=True) parser.add_argument("--label-set", choices=["gold", "scale"], required=True) parser.add_argument("--stay-id", required=True) parser.add_argument("--window-index", type=int, required=True) parser.add_argument("--icu-history-hours", type=_parse_history_hours, required=True) parser.add_argument("--pre-icu-history-hours", type=_parse_history_hours, required=True) parser.add_argument("--excluded-event-codes", nargs="*", required=True) args = parser.parse_args() loader = RealICULoader(args.root, args.label_set, args.stay_id) sample = loader.load_window( args.window_index, icu_history_hours=args.icu_history_hours, pre_icu_history_hours=args.pre_icu_history_hours, excluded_event_codes=args.excluded_event_codes, ) model_input = sample["input"] print(json.dumps({ "sample_id": model_input["sample_id"], "window_start_time": model_input["window_start_time"].isoformat(), "window_end_time": model_input["window_end_time"].isoformat(), "event_counts": { key: len(model_input[key]) for key in ("pre_icu_events", "history_events", "current_events") }, "label_availability": sample["labels"]["label_availability"], }, indent=2)) if __name__ == "__main__": main()