meds-algorithm-curiosity 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,684 @@
1
+ """Curiosity-0826 event tokenization (arXiv 2611.15710 Sec. 2; unchanged parts from 2508.12104v3 Sec. 5.2), fitted on
2
+ the training split only.
3
+
4
+ Preprocessing stores *events*, not sequences: one row per event with its token ids, plus per-subject demographics.
5
+ :func:`sequences` turns them into token sequences at a cutoff. Without a cutoff it gives the training sequence; with
6
+ the prediction time ``T`` it gives the prompt, which depends only on what is recorded at or before ``T``:
7
+
8
+ ``[BOS] [sex/static] [race] [age at start] [year at start]`` then the visible events in time order, with ETHOS time
9
+ tokens before each new timestamp, then (training only) ``[EOS]`` after a death or six-month padding tokens up to the
10
+ right-censoring time; a prompt instead ends with the time tokens of the elapsed gap to ``T``.
11
+
12
+ Everything that could depend on the future is evaluated at the cutoff: the start of the timeline (age and year
13
+ tokens), race (the first race recorded by then), and vital downsampling (a vital is dropped only once the later value
14
+ of its 6-hour window is itself visible). Padding never enters a prompt.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import math
21
+ import re
22
+ from collections.abc import Mapping
23
+ from dataclasses import dataclass
24
+ from datetime import datetime, timedelta
25
+ from pathlib import Path
26
+ from statistics import NormalDist
27
+ from typing import Any
28
+
29
+ import numpy as np
30
+ import polars as pl
31
+ from aces.config import PlainPredicateConfig
32
+
33
+ from .config import CATEGORIES, CuriosityConfig
34
+
35
+ PAD, BOS, EOS, UNK = "[PAD]", "[BOS]", "[EOS]", "[UNK]"
36
+ END_CAUSE_OF_DEATH = "DEATH//END_PRELIMINARY_CAUSE"
37
+ REPORTED_FLAG = "MED//PATIENT_REPORTED"
38
+ _MINUTE, _DAY = 60.0, 86400.0
39
+ # ETHOS buckets (ethos-paper special_tokens.py, 30-day months) with the 0226 paper's extra "1-5 minutes" bucket;
40
+ # unchanged in 0826.
41
+ TIME_BUCKETS = (
42
+ ("1m-5m", 1 * _MINUTE, 5 * _MINUTE),
43
+ ("5m-15m", 5 * _MINUTE, 15 * _MINUTE),
44
+ ("15m-1h", 15 * _MINUTE, 60 * _MINUTE),
45
+ ("1h-2h", 60 * _MINUTE, 120 * _MINUTE),
46
+ ("2h-6h", 2 * 3600.0, 6 * 3600.0),
47
+ ("6h-12h", 6 * 3600.0, 12 * 3600.0),
48
+ ("12h-1d", 12 * 3600.0, _DAY),
49
+ ("1d-3d", _DAY, 3 * _DAY),
50
+ ("3d-1w", 3 * _DAY, 7 * _DAY),
51
+ ("1w-2w", 7 * _DAY, 14 * _DAY),
52
+ ("2w-1mt", 14 * _DAY, 30 * _DAY),
53
+ ("1mt-3mt", 30 * _DAY, 90 * _DAY),
54
+ ("3mt-6mt", 90 * _DAY, 180 * _DAY),
55
+ )
56
+ SIX_MONTHS = 180 * _DAY
57
+ NEVER = datetime(9999, 12, 31) # time of padding tokens: after every cutoff, so no prompt contains them
58
+
59
+ # Lab value buckets (Sec. 2.3.4): two 0.1% tails and 28 interior buckets whose edges are equal-width in z between the
60
+ # 0.1st and 99.9th percentiles, converted to percentile levels shared by every lab.
61
+ _Z = NormalDist().inv_cdf(0.001)
62
+ LAB_LEVELS = tuple(NormalDist().cdf(_Z + i * (-2 * _Z) / 28) for i in range(29))
63
+ LAB_BUCKETS = len(LAB_LEVELS) + 1 # 30
64
+
65
+ # Vital bins (Table 2): thresholds, left-edge exclusive, with a catch-all below the first and above the last.
66
+ # Plausibility bounds (Sec. 2.4) remove values outside (0, upper].
67
+ VITALS = {
68
+ "SBP": ((0, *range(80, 141, 10), 160, 180, 200, 370), 370.0),
69
+ "DBP": ((0, *range(50, 121, 10), 360), 360.0),
70
+ "HEIGHT": ((0, 10, *range(15, 101, 5), 108), 108.0),
71
+ "WEIGHT": ((*range(0, 51), *range(52, 101, 2), *range(103, 161, 3), *range(165, 261, 5), *range(270, 301, 10),
72
+ *range(320, 481, 20)), 1400.0),
73
+ "BMI": ((0, 18, *range(19, 41), 204), 204.0),
74
+ }
75
+ # category -> (vital, factor to the paper's unit)
76
+ VITAL_CATEGORIES = {
77
+ "vital_sbp_mmhg": ("SBP", 1.0), "vital_dbp_mmhg": ("DBP", 1.0), "vital_height_in": ("HEIGHT", 1.0),
78
+ "vital_height_cm": ("HEIGHT", 1 / 2.54), "vital_weight_lb": ("WEIGHT", 1.0),
79
+ "vital_weight_kg": ("WEIGHT", 2.20462262185), "vital_bmi": ("BMI", 1.0),
80
+ }
81
+ VITAL_WINDOW_US = 6 * 3600 * 1_000_000 # latest value per vital type in each 6-hour window
82
+ MEDICATION_ATTRIBUTES = ("route", "dose", "frequency") # optional MEDS columns -> Route_Form, Dose, Frequency tokens
83
+ _ATC = re.compile(r"^[A-Z]\d\d[A-Z]{2}\d{2}$")
84
+ _RANK = {"birth": 0, "gestational_age": 1, "birth_weight": 2} # birth tokens lead their instant (Sec. 2.1)
85
+ _EVENT_COLUMNS = ["subject_id", "time", "code", "numeric_value", "text_value", *MEDICATION_ATTRIBUTES]
86
+
87
+
88
+ def _time_token(name: str) -> str:
89
+ return f"TIME//{name}"
90
+
91
+
92
+ def gap_tokens(seconds: float) -> list[str]:
93
+ """Time tokens for a gap between consecutive timestamps (none below one minute)."""
94
+ if seconds >= SIX_MONTHS:
95
+ return [_time_token("6mt")] * max(1, round(seconds / SIX_MONTHS))
96
+ for name, low, high in TIME_BUCKETS:
97
+ if low <= seconds < high:
98
+ return [_time_token(name)]
99
+ return []
100
+
101
+
102
+ def _token_seconds(name: str) -> float:
103
+ if name == _time_token("6mt"):
104
+ return SIX_MONTHS
105
+ low, high = next((low, high) for bucket, low, high in TIME_BUCKETS if _time_token(bucket) == name)
106
+ return math.sqrt(low * high)
107
+
108
+
109
+ def age_token(days: float) -> str:
110
+ """Age at the start of the timeline (Sec. 2.1): days in week 1, weeks to 4 weeks, 4-week steps to 1 year,
111
+ 6-month steps to 5 years, then years (up to 120)."""
112
+ days = max(days, 0.0)
113
+ if days < 7:
114
+ return f"AGE//{int(days)}d"
115
+ if days < 28:
116
+ return f"AGE//{int(days // 7)}w"
117
+ if days < 365.25:
118
+ return f"AGE//{4 * int(days // 28)}w"
119
+ years = days / 365.25
120
+ if years < 5:
121
+ return f"AGE//{6 * int(years * 2)}mo"
122
+ return f"AGE//{min(int(years), 120)}y"
123
+
124
+
125
+ AGE_TOKENS = tuple(dict.fromkeys(age_token(d) for d in (*range(0, 365), *np.arange(365.25, 121 * 365.25, 30.0))))
126
+
127
+
128
+ def year_token(year: int) -> str:
129
+ low = year // 5 * 5
130
+ return f"YEAR//{low}-{low + 4}"
131
+
132
+
133
+ def gestational_age_token(weeks: float) -> str:
134
+ """Completed weeks with edge buckets (Sec. 2.1)."""
135
+ if weeks < 22:
136
+ return "BIRTH//GA//lt22w"
137
+ if weeks > 44:
138
+ return "BIRTH//GA//gt44w"
139
+ return f"BIRTH//GA//{int(weeks)}w"
140
+
141
+
142
+ GESTATIONAL_TOKENS = ("BIRTH//GA//lt22w", *(f"BIRTH//GA//{w}w" for w in range(22, 45)), "BIRTH//GA//gt44w")
143
+
144
+
145
+ def _split(code: str, atc: bool) -> tuple[str, str, str]:
146
+ """``<prefix>//E1165`` -> ``<prefix>//E11``, ``65``, ``""`` (ICD 3/2/2; ATC 3/2/rest)."""
147
+ prefix, _, value = code.rpartition("//")
148
+ return f"{prefix}//{value[:3]}", value[3:5], value[5:] if atc else value[5:7]
149
+
150
+
151
+ def _sub_token(kind: str, position: int, part: str) -> str:
152
+ return f"{kind}//{'4-5' if position == 1 else '6-'}//{part}"
153
+
154
+
155
+ def category_predicates(predicates: Mapping[str, Any]) -> tuple[tuple[str, dict], ...]:
156
+ """``(category, ACES plain-predicate spec)`` in matching order from a dataset category file. A category the dataset
157
+ does not record is omitted (core rejects empty predicates); an unknown ``curiosity_*`` name is an error, so a typo
158
+ cannot silently drop a category."""
159
+ known = {f"curiosity_{c}" for c in CATEGORIES}
160
+ unknown = sorted(name for name in predicates if name.startswith("curiosity_") and name not in known)
161
+ if unknown:
162
+ raise ValueError(f"Unknown Curiosity categories {unknown}; expected names among {sorted(known)}")
163
+ if not known & predicates.keys():
164
+ raise ValueError("The dataset category file defines no curiosity_* category")
165
+ selected = []
166
+ for category in CATEGORIES:
167
+ spec = predicates.get(f"curiosity_{category}")
168
+ if spec is None:
169
+ continue
170
+ spec = dict(spec)
171
+ if "code" not in spec or "expr" in spec or spec.get("other_cols"):
172
+ raise ValueError(f"curiosity_{category} must be an ACES plain predicate on code/numeric_value")
173
+ PlainPredicateConfig(**spec).MEDS_eval_expr() # rejects malformed code fields early
174
+ selected.append((category, spec))
175
+ return tuple(selected)
176
+
177
+
178
+ def _with_columns(frame: pl.LazyFrame) -> pl.LazyFrame:
179
+ schema = frame.collect_schema()
180
+ missing = [pl.lit(None, dtype=pl.String).alias(c) for c in _EVENT_COLUMNS if c not in schema]
181
+ return frame.with_columns(missing).select(
182
+ pl.col("subject_id").cast(pl.Int64), pl.col("time").cast(pl.Datetime("us")), pl.col("code").cast(pl.String),
183
+ pl.col("numeric_value").cast(pl.Float64), pl.col("text_value").cast(pl.String),
184
+ *(pl.col(c).cast(pl.String) for c in MEDICATION_ATTRIBUTES),
185
+ )
186
+
187
+
188
+ def _categorized(frame: pl.LazyFrame, categories: tuple[tuple[str, dict], ...]) -> pl.LazyFrame:
189
+ category = pl.lit(None, dtype=pl.String)
190
+ for name, spec in reversed(categories):
191
+ category = pl.when(PlainPredicateConfig(**spec).MEDS_eval_expr()).then(pl.lit(name)).otherwise(category)
192
+ return _with_columns(frame).with_row_index("_order").with_columns(category.alias("category")).filter(
193
+ pl.col("category").is_not_null()
194
+ )
195
+
196
+
197
+ def _vital_values(frame: pl.LazyFrame) -> pl.LazyFrame:
198
+ """Vital rows in the paper's units: numeric_value, else a number in text_value; a ``S/D`` text blood pressure
199
+ (MIMIC-IV OMR before MIMIC-IV-MEDS 0.2) is not split here and is dropped. Implausible values are removed."""
200
+ factor = pl.col("category").replace_strict({c: f for c, (_, f) in VITAL_CATEGORIES.items()}, default=None,
201
+ return_dtype=pl.Float64)
202
+ vital = pl.col("category").replace_strict({c: v for c, (v, _) in VITAL_CATEGORIES.items()}, default=None,
203
+ return_dtype=pl.String)
204
+ upper = vital.replace_strict({v: u for v, (_, u) in VITALS.items()}, default=None, return_dtype=pl.Float64)
205
+ value = pl.coalesce(pl.col("numeric_value"), pl.col("text_value").str.strip_chars().cast(pl.Float64, strict=False))
206
+ return (
207
+ frame.filter(pl.col("category").is_in(list(VITAL_CATEGORIES)))
208
+ .with_columns(vital.alias("vital"), (value * factor).alias("value"))
209
+ .filter((pl.col("value") > 0) & (pl.col("value") <= upper))
210
+ )
211
+
212
+
213
+ def _races(kept: pl.DataFrame, column: pl.DataFrame | None) -> pl.DataFrame:
214
+ """First recorded race per subject and its time (null for a static record): from ``race`` category events
215
+ (``RACE//<value>`` codes, MIMIC-IV-MEDS >= 0.2) and from a race column (MIMIC-IV-MEDS 0.1.0 admission rows)."""
216
+ schema = {"subject_id": pl.Int64, "race": pl.String, "time": pl.Datetime("us")}
217
+ rows = [kept.filter(pl.col("category") == "race").select(
218
+ "subject_id", pl.col("code").str.strip_prefix("RACE//").alias("race"), "time")]
219
+ if column is not None and column.height:
220
+ rows.append(column.select(pl.col("subject_id").cast(pl.Int64), pl.col("race").cast(pl.String),
221
+ pl.col("time").cast(pl.Datetime("us"))))
222
+ frame = pl.concat([r.cast(schema) for r in rows]).filter(pl.col("race").is_not_null())
223
+ return frame.sort("subject_id", "time", "race", nulls_last=False).group_by("subject_id", maintain_order=True).first()
224
+
225
+
226
+ @dataclass(frozen=True)
227
+ class _Vocabulary:
228
+ """Fitted tokenizer state (training split only)."""
229
+
230
+ categories: tuple[tuple[str, dict], ...]
231
+ tokens: tuple[str, ...]
232
+ quantiles: dict[str, tuple[float, ...]] # code -> (min, q(levels)..., max): lab and birth-weight buckets
233
+ text_labs: tuple[str, ...] # lab codes whose text results get result tokens
234
+ split_codes: dict[str, str] # training code -> "ICD" | "ATC" split into sub-tokens
235
+ vital_codes: dict[str, tuple[str, float]] # vital -> (MEDS code generated for it, factor to the paper unit)
236
+ gestational_code: str | None
237
+ cutoff: str # latest training time (ISO): right-censoring bound
238
+
239
+ # ---- fitting -----------------------------------------------------------------------------------------------
240
+ @classmethod
241
+ def fit(cls, train: pl.LazyFrame, config: CuriosityConfig, categories: tuple[tuple[str, dict], ...],
242
+ race: pl.LazyFrame | None) -> _Vocabulary:
243
+ kept = _categorized(train, categories).collect()
244
+ timed = kept.filter(pl.col("time").is_not_null())
245
+
246
+ def counts(frame: pl.DataFrame) -> list[tuple[str, int]]:
247
+ ranked = frame.group_by("code").agg(pl.len().alias("n")).sort(["n", "code"], descending=[True, False])
248
+ return list(ranked.iter_rows())
249
+
250
+ def share_kept(frame: pl.DataFrame, share: float, minimum: int = 1) -> list[str]:
251
+ total = frame.height
252
+ return sorted(code for code, n in counts(frame) if n >= minimum and n >= share * total)
253
+
254
+ by = {name: kept.filter(pl.col("category") == name) for name, _ in categories}
255
+ empty = kept.clear()
256
+ get = lambda name: by.get(name, empty) # noqa: E731
257
+ whole, split_codes = [], {}
258
+ for name in ("sex", "birth", "death", "cause_of_death", "encounter"):
259
+ whole += sorted(get(name)["code"].unique().to_list())
260
+ for code in sorted(get("diagnosis")["code"].unique().to_list()):
261
+ split_codes[code] = "ICD"
262
+ for name in ("medication", "reported_medication"):
263
+ for code in sorted(get(name)["code"].unique().to_list()):
264
+ if _ATC.match(code.rpartition("//")[2]):
265
+ split_codes[code] = "ATC"
266
+ else:
267
+ whole.append(code)
268
+ whole += share_kept(get("procedure"), config.procedure_min_share)
269
+
270
+ # Labs (Sec. 2.3): numeric labs bucketed per code; non-numeric labs with result tokens; value-less rows
271
+ # (collection markers emitted by the ETL, e.g. MIMIC-IV-MEDS LAB//SPECIMEN_COLLECTED) as plain components.
272
+ labs = get("lab")
273
+ numeric = labs.filter(pl.col("numeric_value").is_not_null() & pl.col("numeric_value").is_finite())
274
+ text = labs.filter(pl.col("numeric_value").is_null() & pl.col("text_value").is_not_null())
275
+ bare = labs.filter(pl.col("numeric_value").is_null() & pl.col("text_value").is_null())
276
+ numeric_labs = share_kept(numeric, config.lab_numeric_min_share, config.lab_min_bucket_observations)
277
+ text_labs = share_kept(text, config.lab_text_min_share)
278
+ bare_labs = share_kept(bare, config.lab_numeric_min_share)
279
+ text_values = share_kept(text.filter(pl.col("code").is_in(text_labs)).select(pl.col("text_value").alias("code")),
280
+ config.lab_text_value_min_share)
281
+ birth_weight = get("birth_weight").filter(pl.col("numeric_value").is_not_null())
282
+ weight_codes = share_kept(birth_weight, 0.0, config.lab_min_bucket_observations)
283
+ whole += sorted(set(numeric_labs) | set(text_labs) | set(bare_labs) | set(weight_codes))
284
+ quantiles = {}
285
+ bucketed = pl.concat([numeric.filter(pl.col("code").is_in(numeric_labs)),
286
+ birth_weight.filter(pl.col("code").is_in(weight_codes))])
287
+ if bucketed.height:
288
+ stats = bucketed.group_by("code").agg(
289
+ pl.col("numeric_value").min().alias("min"),
290
+ *(pl.col("numeric_value").quantile(level, "linear").alias(f"q{i}") for i, level in enumerate(LAB_LEVELS)),
291
+ pl.col("numeric_value").max().alias("max"),
292
+ )
293
+ columns = ["min", *(f"q{i}" for i in range(len(LAB_LEVELS))), "max"]
294
+ quantiles = {row["code"]: tuple(float(row[c]) for c in columns) for row in stats.iter_rows(named=True)}
295
+
296
+ # Medication attributes (Sec. 2.6): values below the floor are null (no token).
297
+ meds = pl.concat([get("medication"), get("reported_medication")])
298
+ attributes = []
299
+ for column in MEDICATION_ATTRIBUTES:
300
+ values = meds.filter(pl.col(column).is_not_null()).select(pl.col(column).alias("code"))
301
+ attributes += [f"MED//{column.upper()}//{v}" for v in share_kept(values, config.medication_attribute_min_share)]
302
+
303
+ # Vitals: the most frequent training code of each vital is the one generated futures use.
304
+ vital_codes = {}
305
+ vitals = _vital_values(kept.lazy()).collect()
306
+ for vital in VITALS:
307
+ ranked = counts(vitals.filter(pl.col("vital") == vital))
308
+ if ranked:
309
+ category = vitals.filter(pl.col("code") == ranked[0][0])["category"][0]
310
+ vital_codes[vital] = (ranked[0][0], VITAL_CATEGORIES[category][1])
311
+ gestational = counts(get("gestational_age"))
312
+
313
+ heads, subs = set(), set()
314
+ for code, kind in split_codes.items():
315
+ head, *parts = _split(code, kind == "ATC")
316
+ heads.add(head)
317
+ subs.update(_sub_token(kind, position, part) for position, part in enumerate(parts, 1) if part)
318
+ races = sorted(_races(kept, race.collect() if race is not None else None)["race"].unique().to_list())
319
+ starts = timed.group_by("subject_id").agg(pl.col("time").min())["time"].dt.year()
320
+ years = sorted({year_token(y) for y in range(int(starts.min()), int(starts.max()) + 1)}) if len(starts) else []
321
+ tokens = (
322
+ PAD, BOS, EOS, UNK, END_CAUSE_OF_DEATH, REPORTED_FLAG,
323
+ *(_time_token(name) for name, _, _ in TIME_BUCKETS), _time_token("6mt"),
324
+ *AGE_TOKENS, *years, *(f"RACE//{value}" for value in races),
325
+ *(f"LABQ//{i}" for i in range(1, LAB_BUCKETS + 1)),
326
+ *(f"RESULT//{v}" for v in text_values), "RESULT//[OTHER]", "RESULT//[MISSING]",
327
+ *(f"VITAL//{vital}//{i}" for vital, (edges, _) in VITALS.items() if vital in vital_codes
328
+ for i in range(len(edges) + 1)),
329
+ *(GESTATIONAL_TOKENS if gestational else ()),
330
+ *attributes,
331
+ *(f"CODE//{code}" for code in sorted(set(whole))),
332
+ *(f"CODE//{head}" for head in sorted(heads - {f"{c}" for c in whole})),
333
+ *sorted(subs),
334
+ )
335
+ cutoff = timed["time"].max()
336
+ return cls(categories, tuple(dict.fromkeys(tokens)), quantiles, tuple(text_labs), split_codes, vital_codes,
337
+ gestational[0][0] if gestational else None, (cutoff or datetime(1970, 1, 1)).isoformat())
338
+
339
+ # ---- persistence ---------------------------------------------------------------------------------------------
340
+ def save(self, path: Path) -> None:
341
+ path.write_text(json.dumps({
342
+ "categories": [[name, spec] for name, spec in self.categories],
343
+ "tokens": list(self.tokens),
344
+ "quantiles": {code: list(edges) for code, edges in self.quantiles.items()},
345
+ "text_labs": list(self.text_labs),
346
+ "split_codes": self.split_codes,
347
+ "vital_codes": {k: list(v) for k, v in self.vital_codes.items()},
348
+ "gestational_code": self.gestational_code,
349
+ "cutoff": self.cutoff,
350
+ }, sort_keys=True))
351
+
352
+ @classmethod
353
+ def load(cls, path: Path) -> _Vocabulary:
354
+ v = json.loads(path.read_text())
355
+ return cls(tuple((name, spec) for name, spec in v["categories"]), tuple(v["tokens"]),
356
+ {code: tuple(edges) for code, edges in v["quantiles"].items()}, tuple(v["text_labs"]),
357
+ v["split_codes"], {k: tuple(x) for k, x in v["vital_codes"].items()}, v["gestational_code"],
358
+ v["cutoff"])
359
+
360
+ # ---- lookups -------------------------------------------------------------------------------------------------
361
+ @property
362
+ def ids(self) -> dict[str, int]:
363
+ return {token: index for index, token in enumerate(self.tokens)}
364
+
365
+ def codes(self) -> set[str]:
366
+ """Every MEDS code the tokenizer fitted (a token, a split, bucket statistics or a generated vital code)."""
367
+ heads = {_split(code, kind == "ATC")[0] for code, kind in self.split_codes.items()}
368
+ whole = {t[6:] for t in self.tokens if t.startswith("CODE//")} - (heads - set(self.split_codes))
369
+ return whole | set(self.split_codes) | set(self.quantiles) | {c for c, _ in self.vital_codes.values()} | (
370
+ {self.gestational_code} if self.gestational_code else set())
371
+
372
+ def _code_tokens(self) -> dict[str, list[int]]:
373
+ ids = self.ids
374
+ mapping = {token[6:]: [index] for token, index in ids.items() if token.startswith("CODE//")}
375
+ for code, kind in self.split_codes.items():
376
+ head, *parts = _split(code, kind == "ATC")
377
+ mapping[code] = [ids[f"CODE//{head}"]] + [
378
+ ids[_sub_token(kind, position, part)] for position, part in enumerate(parts, 1) if part
379
+ ]
380
+ return mapping
381
+
382
+ # ---- events --------------------------------------------------------------------------------------------------
383
+ def events(self, frame: pl.DataFrame, race: pl.DataFrame | None, config: CuriosityConfig) -> tuple[pl.DataFrame, pl.DataFrame]:
384
+ """``(events, subjects)`` for one shard.
385
+
386
+ ``events``: ``subject_id, time, rank, order, tokens, superseded`` (one row per event; ``superseded`` is the
387
+ time of the later vital of the same 6-hour window, which hides this one once visible).
388
+ ``subjects``: ``subject_id, static, race, race_time, birth, censor`` (``censor`` is null after a death).
389
+ """
390
+ ids = self.ids
391
+ code_tokens = self._code_tokens()
392
+ unk = ids[UNK]
393
+ kept = _categorized(frame.lazy(), self.categories).collect()
394
+ code_map = pl.DataFrame({"code": list(code_tokens), "_code": list(code_tokens.values())},
395
+ schema={"code": pl.String, "_code": pl.List(pl.Int32)})
396
+ kept = kept.join(code_map, on="code", how="left")
397
+ code = pl.col("_code").fill_null(pl.lit([unk], dtype=pl.List(pl.Int32)))
398
+ timed = kept.filter(pl.col("time").is_not_null())
399
+ parts = []
400
+
401
+ def add(rows: pl.DataFrame, tokens: pl.Expr) -> None:
402
+ parts.append(rows.select(
403
+ "subject_id", "time", pl.col("category").replace_strict(_RANK, default=3, return_dtype=pl.Int32).alias("rank"),
404
+ pl.col("_order").cast(pl.Float64).alias("order"), tokens.alias("tokens"),
405
+ pl.lit(None, dtype=pl.Datetime("us")).alias("superseded"),
406
+ ))
407
+
408
+ add(timed.filter(pl.col("category").is_in(["birth", "encounter", "diagnosis", "procedure"])), code)
409
+
410
+ # Labs and birth weight: component, then a bucket, a result token, or nothing (collection marker).
411
+ q = len(LAB_LEVELS)
412
+ cuts = pl.DataFrame(
413
+ {"code": list(self.quantiles), **{f"q{i}": [edges[i + 1] for edges in self.quantiles.values()] for i in range(q)}},
414
+ schema={"code": pl.String, **{f"q{i}": pl.Float64 for i in range(q)}},
415
+ )
416
+ results = {t[8:]: i for t, i in ids.items() if t.startswith("RESULT//")}
417
+ labs = timed.filter(pl.col("category").is_in(["lab", "birth_weight"])).join(cuts, on="code", how="left")
418
+ bucket = 1 + pl.sum_horizontal([(pl.col("numeric_value") > pl.col(f"q{i}")).cast(pl.Int32) for i in range(q)])
419
+ value = (
420
+ pl.when(pl.col("q0").is_not_null() & pl.col("numeric_value").is_not_null())
421
+ .then(pl.concat_list(bucket.replace_strict(range(1, LAB_BUCKETS + 1),
422
+ [ids[f"LABQ//{i}"] for i in range(1, LAB_BUCKETS + 1)],
423
+ return_dtype=pl.Int32)))
424
+ .when(pl.col("code").is_in(list(self.text_labs)) & pl.col("numeric_value").is_null())
425
+ .then(pl.concat_list(
426
+ pl.when(pl.col("text_value").is_null()).then(pl.lit(results["[MISSING]"], dtype=pl.Int32))
427
+ .otherwise(pl.col("text_value").replace_strict(
428
+ list(results), list(results.values()), default=results["[OTHER]"], return_dtype=pl.Int32))
429
+ ))
430
+ .otherwise(pl.lit([], dtype=pl.List(pl.Int32)))
431
+ )
432
+ add(labs, pl.concat_list(code, value))
433
+
434
+ # Gestational age: one token at its time.
435
+ if "BIRTH//GA//22w" in ids:
436
+ weeks = timed.filter((pl.col("category") == "gestational_age") & pl.col("numeric_value").is_not_null())
437
+ add(weeks, pl.concat_list(pl.col("numeric_value").map_elements(
438
+ lambda w: ids[gestational_age_token(w)], return_dtype=pl.Int32)))
439
+
440
+ # Medications: code (ATC 3/2/rest), attribute tokens; a flag after each block of reported medications.
441
+ attributes = [
442
+ pl.col(column).map_elements(lambda v, c=column: ids.get(f"MED//{c.upper()}//{v}"), return_dtype=pl.Int32)
443
+ for column in MEDICATION_ATTRIBUTES
444
+ ]
445
+ meds = timed.filter(pl.col("category").is_in(["medication", "reported_medication"]))
446
+ add(meds, pl.concat_list(code, *attributes).list.drop_nulls())
447
+ reported = meds.filter(pl.col("category") == "reported_medication")
448
+ if reported.height:
449
+ flags = reported.group_by("subject_id", "time").agg(pl.col("_order").max())
450
+ parts.append(flags.select(
451
+ "subject_id", "time", pl.lit(3, dtype=pl.Int32).alias("rank"),
452
+ (pl.col("_order").cast(pl.Float64) + 0.5).alias("order"),
453
+ pl.lit([ids[REPORTED_FLAG]], dtype=pl.List(pl.Int32)).alias("tokens"),
454
+ pl.lit(None, dtype=pl.Datetime("us")).alias("superseded"),
455
+ ))
456
+
457
+ # Vitals: one binned token; latest value per type in each 6-hour window (Sec. 2.4).
458
+ vitals = _vital_values(timed.lazy()).filter(pl.col("vital").is_in(list(self.vital_codes))).collect()
459
+ if vitals.height:
460
+ vitals = vitals.with_columns(
461
+ pl.struct("vital", "value").map_elements(
462
+ lambda r: ids[f"VITAL//{r['vital']}//{sum(t < r['value'] for t in VITALS[r['vital']][0])}"],
463
+ return_dtype=pl.Int32).alias("_vital_id"),
464
+ (pl.col("time").dt.epoch("us") // VITAL_WINDOW_US).alias("_window"),
465
+ ).sort("subject_id", "vital", "time", "_order").with_columns(
466
+ pl.when(pl.col("_window").shift(-1).over("subject_id", "vital") == pl.col("_window"))
467
+ .then(pl.col("time").shift(-1).over("subject_id", "vital")).alias("_superseded")
468
+ )
469
+ parts.append(vitals.select(
470
+ "subject_id", "time", pl.lit(3, dtype=pl.Int32).alias("rank"),
471
+ pl.col("_order").cast(pl.Float64).alias("order"), pl.concat_list("_vital_id").alias("tokens"),
472
+ pl.col("_superseded").alias("superseded"),
473
+ ))
474
+
475
+ # Death (Sec. 2.2.2): at the last instant of the recorded date, followed by the preliminary causes of death,
476
+ # their closing token and EOS. Later events are dropped; a record without death is right-censored.
477
+ deaths = timed.filter(pl.col("category") == "death").group_by("subject_id").agg(
478
+ pl.col("time").min().dt.date().cast(pl.Datetime("us")).add(pl.duration(days=1, microseconds=-1)).alias("death"),
479
+ pl.col("_code").sort_by("time").first().fill_null(pl.lit([unk], dtype=pl.List(pl.Int32))).alias("_death_code"),
480
+ )
481
+ causes = kept.filter(pl.col("category") == "cause_of_death").group_by("subject_id", maintain_order=True).agg(
482
+ code.explode(keep_nulls=False, empty_as_null=False).alias("_causes"))
483
+ death_rows = deaths.join(causes, on="subject_id", how="left").with_columns(
484
+ pl.concat_list(
485
+ "_death_code",
486
+ pl.when(pl.col("_causes").is_not_null())
487
+ .then(pl.concat_list("_causes", pl.lit([ids[END_CAUSE_OF_DEATH]], dtype=pl.List(pl.Int32))))
488
+ .otherwise(pl.lit([], dtype=pl.List(pl.Int32))),
489
+ pl.lit([ids[EOS]], dtype=pl.List(pl.Int32)),
490
+ ).alias("tokens")
491
+ )
492
+ parts.append(death_rows.select(
493
+ "subject_id", pl.col("death").alias("time"), pl.lit(9, dtype=pl.Int32).alias("rank"),
494
+ pl.lit(0.0).alias("order"), "tokens", pl.lit(None, dtype=pl.Datetime("us")).alias("superseded"),
495
+ ))
496
+ events = (
497
+ pl.concat(parts)
498
+ .join(deaths.select("subject_id", "death"), on="subject_id", how="left")
499
+ .filter(pl.col("death").is_null() | (pl.col("time") <= pl.col("death")))
500
+ .drop("death")
501
+ .sort("subject_id", "time", "rank", "order")
502
+ )
503
+
504
+ # Subjects: static tokens, race and its first recorded time, birth, right-censoring time.
505
+ subjects = frame.select(pl.col("subject_id").cast(pl.Int64).unique().sort())
506
+ static = kept.filter(pl.col("time").is_null() & (pl.col("category") != "race")).group_by("subject_id", maintain_order=True).agg(
507
+ code.explode(keep_nulls=False, empty_as_null=False).alias("static"))
508
+ births = frame.lazy().filter(pl.col("code") == "MEDS_BIRTH").group_by("subject_id").agg(
509
+ pl.col("time").min().cast(pl.Datetime("us")).alias("birth")).with_columns(pl.col("subject_id").cast(pl.Int64)).collect()
510
+ last = events.group_by("subject_id").agg(pl.col("time").max().alias("last"))
511
+ cutoff = datetime.fromisoformat(self.cutoff)
512
+ subjects = (
513
+ subjects.join(static, on="subject_id", how="left").join(births, on="subject_id", how="left")
514
+ .join(last, on="subject_id", how="left").join(deaths.select("subject_id", "death"), on="subject_id", how="left")
515
+ .with_columns(
516
+ pl.when(pl.col("death").is_null() & pl.col("last").is_not_null())
517
+ .then(pl.min_horizontal(pl.col("last") + pl.duration(days=config.follow_up_days),
518
+ pl.max_horizontal(pl.lit(cutoff), pl.col("last"))))
519
+ .alias("censor"),
520
+ pl.col("static").fill_null(pl.lit([], dtype=pl.List(pl.Int32))),
521
+ )
522
+ )
523
+ race_ids = {t[6:]: i for t, i in ids.items() if t.startswith("RACE//")}
524
+ subjects = subjects.join(_races(kept, race).select(
525
+ "subject_id",
526
+ pl.col("race").replace_strict(race_ids, default=None, return_dtype=pl.Int32),
527
+ pl.col("time").alias("race_time"),
528
+ ), on="subject_id", how="left")
529
+ return events, subjects.select("subject_id", "static", "race", "race_time", "birth", "censor")
530
+
531
+ # ---- sequences -----------------------------------------------------------------------------------------------
532
+ def sequences(self, events: pl.DataFrame, subjects: pl.DataFrame, cutoffs: pl.DataFrame | None = None) -> pl.DataFrame:
533
+ """Token sequences. Without ``cutoffs``: one training sequence per subject (all events, superseded vitals
534
+ dropped, then EOS or padding). With ``cutoffs`` (``subject_id, prediction_time``): one prompt per row, built
535
+ only from what is recorded at or before ``prediction_time`` and ending with the elapsed-gap time tokens."""
536
+ ids = self.ids
537
+ training = cutoffs is None
538
+ if training:
539
+ cutoffs = subjects.select("subject_id", pl.lit(None, dtype=pl.Datetime("us")).alias("prediction_time"))
540
+ keys = cutoffs.select(pl.col("subject_id").cast(pl.Int64), pl.col("prediction_time").cast(pl.Datetime("us")))
541
+ keys = keys.with_row_index("_key")
542
+ cut = pl.col("prediction_time")
543
+ visible = (
544
+ keys.join(events, on="subject_id", how="inner")
545
+ .filter(
546
+ pl.when(cut.is_null()).then(pl.col("superseded").is_null())
547
+ .otherwise((pl.col("time") <= cut) & (pl.col("superseded").is_null() | (pl.col("superseded") > cut)))
548
+ )
549
+ .sort("_key", "time", "rank", "order")
550
+ )
551
+ bucket_ids = [ids[_time_token(name)] for name, _, _ in TIME_BUCKETS]
552
+ six = ids[_time_token("6mt")]
553
+
554
+ def gap_expr(seconds: pl.Expr) -> pl.Expr:
555
+ bucket = pl.sum_horizontal([(seconds >= low).cast(pl.Int32) for _, low, _ in TIME_BUCKETS])
556
+ return (
557
+ pl.when(seconds >= SIX_MONTHS)
558
+ .then(pl.lit(six, dtype=pl.Int32).repeat_by((seconds / SIX_MONTHS).round().cast(pl.Int64).clip(lower_bound=1)))
559
+ .when(seconds.is_not_null() & (bucket > 0))
560
+ .then(pl.concat_list(bucket.replace_strict(range(1, len(bucket_ids) + 1), bucket_ids, default=None,
561
+ return_dtype=pl.Int32)))
562
+ .otherwise(pl.lit([], dtype=pl.List(pl.Int32)))
563
+ )
564
+
565
+ previous = pl.col("time").shift(1).over("_key")
566
+ gap = pl.when(pl.col("time") != previous).then((pl.col("time") - previous).dt.total_microseconds() / 1e6)
567
+ body = (
568
+ visible.with_columns(pl.concat_list(gap_expr(gap), "tokens").alias("_tokens"))
569
+ .group_by("_key", maintain_order=True)
570
+ .agg(pl.col("_tokens").explode(keep_nulls=False, empty_as_null=False).alias("_body"), pl.col("time").min().alias("_start"),
571
+ pl.col("time").max().alias("_last"))
572
+ )
573
+ out = keys.join(subjects, on="subject_id", how="left").join(body, on="_key", how="left")
574
+ start = pl.coalesce("_start", cut)
575
+ age_days = (start - pl.col("birth")).dt.total_seconds() / 86400.0
576
+ age_ids = {t: i for t, i in ids.items() if t.startswith("AGE//")}
577
+ year_ids = {t: i for t, i in ids.items() if t.startswith("YEAR//")}
578
+ years = sorted(year_ids)
579
+
580
+ def year_id(year):
581
+ if year is None or not years:
582
+ return None
583
+ token = year_token(int(year))
584
+ return year_ids.get(token, year_ids[years[0]] if token < years[0] else year_ids[years[-1]])
585
+
586
+ empty = pl.lit([], dtype=pl.List(pl.Int32))
587
+ out = out.with_columns(
588
+ pl.when(age_days.is_not_null()).then(pl.concat_list(age_days.map_elements(
589
+ lambda d: age_ids[age_token(d)], return_dtype=pl.Int32))).otherwise(empty).alias("_age"),
590
+ pl.when(start.is_not_null()).then(pl.concat_list(start.dt.year().map_elements(year_id, return_dtype=pl.Int32)))
591
+ .otherwise(empty).list.drop_nulls().alias("_year"),
592
+ pl.when(pl.col("race").is_not_null() & (pl.col("race_time").is_null() | cut.is_null() | (pl.col("race_time") <= cut)))
593
+ .then(pl.concat_list("race")).otherwise(empty).alias("_race"),
594
+ pl.col("_body").fill_null(empty),
595
+ )
596
+ if training:
597
+ padding = (pl.col("censor") - pl.col("_last")).dt.total_seconds() / SIX_MONTHS
598
+ tail = pl.when(pl.col("censor").is_not_null()).then(
599
+ pl.lit(six, dtype=pl.Int32).repeat_by(padding.round().cast(pl.Int64).clip(lower_bound=0))).otherwise(empty)
600
+ else:
601
+ elapsed = (cut - pl.col("_last")).dt.total_microseconds() / 1e6
602
+ tail = pl.when(pl.col("_last").is_not_null()).then(gap_expr(elapsed)).otherwise(empty)
603
+ return out.select(
604
+ "subject_id", "prediction_time",
605
+ pl.concat_list(pl.lit([ids[BOS]], dtype=pl.List(pl.Int32)), "static", "_race", "_age", "_year", "_body",
606
+ tail.alias("_tail")).alias("tokens"),
607
+ ).sort("subject_id", "prediction_time")
608
+
609
+ # ---- generation ----------------------------------------------------------------------------------------------
610
+ def decode(self, tokens: list[int], prediction_time: datetime, uniforms: np.ndarray) -> tuple[list[tuple], datetime, int]:
611
+ """Generated ids -> (``(time, code, numeric_value, text_value)`` events, final clock, invalid-token count).
612
+
613
+ The clock starts at the prediction time (the prompt ends with the real elapsed gap); generated events sharing
614
+ it are placed one microsecond later. A bucket token draws its value uniformly within the bucket (0226 App. G).
615
+ Attribute, flag and closing tokens carry no event; BOS or EOS ends the record.
616
+ """
617
+ splits = {}
618
+ for code, kind in self.split_codes.items():
619
+ head, *_ = _split(code, kind == "ATC")
620
+ splits[head] = kind
621
+ clock, events, invalid = prediction_time, [], 0
622
+ future = prediction_time + timedelta(microseconds=1)
623
+ code = value = text = None
624
+ split_kind, split_length = None, None
625
+
626
+ def flush():
627
+ nonlocal code, value, text, split_kind, split_length
628
+ if code is not None:
629
+ events.append((max(clock, future), code, value, text))
630
+ code = value = text = split_kind = split_length = None
631
+
632
+ for position, index in enumerate(tokens):
633
+ token = self.tokens[index]
634
+ kind, _, rest = token.partition("//")
635
+ if token in (BOS, EOS):
636
+ flush()
637
+ break
638
+ if kind == "TIME":
639
+ flush()
640
+ clock += timedelta(seconds=_token_seconds(token))
641
+ elif kind == "CODE":
642
+ flush()
643
+ code = rest
644
+ split_kind = splits.get(code)
645
+ split_length = 3 if split_kind else None
646
+ elif kind in ("ICD", "ATC"):
647
+ where, _, part = rest.partition("//")
648
+ expected = 3 if where == "4-5" else 5
649
+ if split_kind == kind and split_length == expected:
650
+ code, split_length = code + part, split_length + len(part)
651
+ else:
652
+ invalid += 1
653
+ elif kind == "LABQ":
654
+ if code in self.quantiles and value is None:
655
+ edges, bucket = self.quantiles[code], int(rest)
656
+ value = float(edges[bucket - 1] + uniforms[position] * (edges[bucket] - edges[bucket - 1]))
657
+ else:
658
+ invalid += 1
659
+ elif kind == "RESULT":
660
+ if code is not None and code in self.text_labs and text is None:
661
+ text = None if rest in ("[OTHER]", "[MISSING]") else rest
662
+ else:
663
+ invalid += 1
664
+ elif kind == "VITAL":
665
+ flush()
666
+ vital, _, bin_ = rest.partition("//")
667
+ edges, upper = VITALS[vital]
668
+ b = int(bin_)
669
+ low = edges[b - 1] if b > 0 else 0.0
670
+ high = edges[b] if b < len(edges) else upper
671
+ vital_code, factor = self.vital_codes[vital]
672
+ events.append((max(clock, future), vital_code, float(low + uniforms[position] * (high - low)) / factor, None))
673
+ elif kind == "BIRTH" and token in GESTATIONAL_TOKENS:
674
+ flush()
675
+ weeks = {"lt22w": 21.5, "gt44w": 44.5}.get(rest[4:], None)
676
+ weeks = weeks if weeks is not None else int(rest[4:-1]) + 0.5
677
+ events.append((max(clock, future), self.gestational_code, weeks, None))
678
+ elif kind == "MED" or token == END_CAUSE_OF_DEATH:
679
+ continue # attributes and flags qualify the preceding medication; the closing token has no event
680
+ else: # PAD, UNK, demographic tokens
681
+ flush()
682
+ invalid += token != UNK
683
+ flush()
684
+ return events, clock, invalid