meds-algorithm-curiosity 0.1.0__tar.gz → 0.1.2__tar.gz

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.
Files changed (34) hide show
  1. meds_algorithm_curiosity-0.1.2/CHANGELOG.md +36 -0
  2. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/PKG-INFO +1 -1
  3. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/pyproject.toml +1 -1
  4. meds_algorithm_curiosity-0.1.2/src/curiosity_meds/_tokenizer.py +587 -0
  5. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/src/curiosity_meds/config.py +23 -47
  6. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/src/curiosity_meds/curiosity_meds.py +14 -33
  7. meds_algorithm_curiosity-0.1.2/src/curiosity_meds/hierarchies/MIMIC-IV.yaml +21 -0
  8. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/tests/conftest.py +2 -2
  9. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/tests/e2e.py +4 -4
  10. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/tests/test_curiosity.py +175 -197
  11. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/tests/wheel_smoke.py +10 -7
  12. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/uv.lock +1 -1
  13. meds_algorithm_curiosity-0.1.0/CHANGELOG.md +0 -16
  14. meds_algorithm_curiosity-0.1.0/src/curiosity_meds/_tokenizer.py +0 -684
  15. meds_algorithm_curiosity-0.1.0/src/curiosity_meds/datasets/MIMIC-IV.yaml +0 -54
  16. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/.gitignore +0 -0
  17. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/LICENSE +0 -0
  18. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/README.md +0 -0
  19. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/RELEASING.md +0 -0
  20. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/algorithms/zero_shot_materialized/model.yaml +0 -0
  21. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/configs/runs/run.yaml +0 -0
  22. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/docs/IMPLEMENTATION_GUIDE.md +0 -0
  23. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/docs/TESTING.md +0 -0
  24. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/scripts/check_distribution.sh +0 -0
  25. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/scripts/check_release.py +0 -0
  26. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/scripts/github-sync.sh +0 -0
  27. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/src/curiosity_meds/__init__.py +0 -0
  28. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/src/curiosity_meds/__main__.py +0 -0
  29. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/src/curiosity_meds/_model.py +0 -0
  30. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/tests/__init__.py +0 -0
  31. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/tests/fixtures/in_icu_mortality.yaml +0 -0
  32. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/tests/fixtures/predicates.yaml +0 -0
  33. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/tests/test_conformance.py +0 -0
  34. {meds_algorithm_curiosity-0.1.0 → meds_algorithm_curiosity-0.1.2}/tests/test_primary_behavior.py +0 -0
@@ -0,0 +1,36 @@
1
+ # Changes
2
+
3
+ ## 0.1.2 (2026-11-24)
4
+
5
+ - 100 sampled futures per prediction time by default (`n_samples`; was 60, the paper's 365-day mortality setting).
6
+
7
+ ## 0.1.1 (2026-11-24)
8
+
9
+ - Dataset-agnostic tokenization (a documented adaptation of the papers): every MEDS code is one whole-code token, with
10
+ no event categories, category files or ICD/ATC hierarchy split. A code with at least `min_bucket_observations`
11
+ numeric values gets the 30 shared value-bucket tokens; codes with text values get result tokens; the optional
12
+ `route`, `dose`, `frequency` columns give attribute tokens on any row. One frequency threshold
13
+ (`min_code_count`, `min_code_share`) for every code: rarer codes become `[UNK]`. The latest value of each numeric
14
+ code in each 6-hour window is kept (`downsample_hours`). `MEDS_BIRTH` and `MEDS_DEATH` remain special.
15
+ - Optional `hierarchy_file`: YAML rules (a code regex, then a `separator` or character `widths`) split matching codes
16
+ after the matched prefix into a head token and depth-tagged sub-tokens, so rare codes share their ancestors' tokens.
17
+ Example shipped: `curiosity_meds/hierarchies/MIMIC-IV.yaml` (ICD diagnoses 3/2/2).
18
+ - Predictions include `predicted_boolean_value` (probability ≥ 0.5) next to the probability: MEDS-DEV's evaluation
19
+ (meds-evaluation) requires it, so 0.1.0 predictions could not be evaluated there.
20
+ - Any MEDS dataset runs without per-dataset configuration, and any task whose codes occur in training can be
21
+ answered (e.g. MEDS-DEV's hypotension task on mean arterial pressure).
22
+
23
+ ## 0.1.0 (2026-11-24)
24
+
25
+ - Curiosity-0826 (arXiv 2611.15710) as a `zero_shot_materialized` MEDS algorithm, replacing the earlier
26
+ Curiosity-0226 port: BOS-first sequences, age/year at start of timeline with pediatric buckets, birth,
27
+ gestational age and birth weight, death with causes and EOS, right-censoring padding, lab collection markers,
28
+ 30-bucket labs, non-numeric labs, binned vitals, ATC-split medications with attributes and a patient-reported
29
+ flag, and two-stage context extension to 16,384 tokens with unscaled RoPE.
30
+ - Prompts are built from what is recorded at or before each prediction time; prompt-level temporal-invariance
31
+ tests complement the shared future-blind conformance rerun.
32
+ - Model size presets (`size`: small, medium, large, xlarge): Curiosity-0226 S/M/L and a 40-layer ~4.2B model for
33
+ Curiosity-0826-4B.
34
+ - MIMIC-IV category file matches MIMIC-IV-MEDS 0.4.0 (MEDS-DEV's current build) and 0.1.0; race also comes from
35
+ `RACE//` events.
36
+ - `aces-relaxations` from PyPI (0.1.0); `meds-algorithm` with the temporal-leakage conformance (0.4.0a6).
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: meds-algorithm-curiosity
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: Curiosity-0826 generative medical event model: Qwen2 decoder pretrained on tokenized MEDS timelines, zero-shot task prediction by Monte Carlo generation of future timelines.
5
5
  Project-URL: Repository, https://github.com/florian6973/meds-algo-curiosity
6
6
  Author-email: Florent Pollet <flo1.raymond@gmail.com>
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "meds-algorithm-curiosity"
7
- version = "0.1.0"
7
+ version = "0.1.2"
8
8
  description = "Curiosity-0826 generative medical event model: Qwen2 decoder pretrained on tokenized MEDS timelines, zero-shot task prediction by Monte Carlo generation of future timelines."
9
9
  readme = "README.md"
10
10
  authors = [{name = "Florent Pollet", email = "flo1.raymond@gmail.com"}]
@@ -0,0 +1,587 @@
1
+ """Curiosity event tokenization, dataset-agnostic (arXiv 2611.15710 Sec. 2 and 2508.12104v3 Sec. 5.2, adapted: see
2
+ IMPLEMENTATION_REPORT.md), fitted on the training split only.
3
+
4
+ Every MEDS code is one whole-code token: no event categories and no per-dataset mapping. Optionally, a hierarchy file
5
+ (``hierarchy_file``) splits the codes its rules match into a head token and depth-tagged sub-tokens (e.g. ICD codes
6
+ 3/2/2, as in the 0226 paper), so a rare code shares its ancestors' tokens. A code with enough numeric values is followed by one of 30 shared percentile-bucket tokens (the paper's lab buckets); a
7
+ value-less row of a code with text values by a result token; a row carrying the optional ``route``, ``dose`` or
8
+ ``frequency`` columns by attribute tokens. Codes below one frequency threshold become ``[UNK]``, as in the paper;
9
+ rarer result and attribute values become ``RESULT//[OTHER]`` or are dropped. Only MEDS standard codes are special:
10
+ ``MEDS_BIRTH`` dates the age token and ``MEDS_DEATH`` is placed at the end of its date and closes the record with
11
+ ``[EOS]``.
12
+
13
+ Preprocessing stores *events*, not sequences: one row per event with its token ids, plus per-subject demographics.
14
+ :func:`_Vocabulary.sequences` turns them into token sequences at a cutoff. Without a cutoff it gives the training
15
+ sequence; with the prediction time ``T`` it gives the prompt, which depends only on what is recorded at or before T:
16
+
17
+ ``[BOS] [static codes] [race] [age at start] [year at start]`` then the visible events in time order, with ETHOS time
18
+ tokens before each new timestamp, then (training only) ``[EOS]`` after a death or six-month padding tokens up to the
19
+ right-censoring time; a prompt instead ends with the time tokens of the elapsed gap to ``T``.
20
+
21
+ Everything that could depend on the future is evaluated at the cutoff: the start of the timeline (age and year
22
+ tokens), race (the first race recorded by then), and the downsampling of numeric codes (a value is dropped only once
23
+ the later value of its window is itself visible). Padding never enters a prompt.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import json
29
+ import math
30
+ import re
31
+ from dataclasses import dataclass
32
+ from datetime import datetime, timedelta
33
+ from pathlib import Path
34
+ from statistics import NormalDist
35
+
36
+ import numpy as np
37
+ import polars as pl
38
+ import yaml
39
+
40
+ from .config import CuriosityConfig
41
+
42
+ PAD, BOS, EOS, UNK = "[PAD]", "[BOS]", "[EOS]", "[UNK]"
43
+ BIRTH_CODE, DEATH_CODE = "MEDS_BIRTH", "MEDS_DEATH"
44
+ _MINUTE, _DAY = 60.0, 86400.0
45
+ # ETHOS buckets (ethos-paper special_tokens.py, 30-day months) with the 0226 paper's extra "1-5 minutes" bucket;
46
+ # unchanged in 0826.
47
+ TIME_BUCKETS = (
48
+ ("1m-5m", 1 * _MINUTE, 5 * _MINUTE),
49
+ ("5m-15m", 5 * _MINUTE, 15 * _MINUTE),
50
+ ("15m-1h", 15 * _MINUTE, 60 * _MINUTE),
51
+ ("1h-2h", 60 * _MINUTE, 120 * _MINUTE),
52
+ ("2h-6h", 2 * 3600.0, 6 * 3600.0),
53
+ ("6h-12h", 6 * 3600.0, 12 * 3600.0),
54
+ ("12h-1d", 12 * 3600.0, _DAY),
55
+ ("1d-3d", _DAY, 3 * _DAY),
56
+ ("3d-1w", 3 * _DAY, 7 * _DAY),
57
+ ("1w-2w", 7 * _DAY, 14 * _DAY),
58
+ ("2w-1mt", 14 * _DAY, 30 * _DAY),
59
+ ("1mt-3mt", 30 * _DAY, 90 * _DAY),
60
+ ("3mt-6mt", 90 * _DAY, 180 * _DAY),
61
+ )
62
+ SIX_MONTHS = 180 * _DAY
63
+
64
+ # Value buckets (0826 Sec. 2.3.4): two 0.1% tails and 28 interior buckets whose edges are equal-width in z between the
65
+ # 0.1st and 99.9th percentiles, converted to percentile levels shared by every code.
66
+ _Z = NormalDist().inv_cdf(0.001)
67
+ LAB_LEVELS = tuple(NormalDist().cdf(_Z + i * (-2 * _Z) / 28) for i in range(29))
68
+ LAB_BUCKETS = len(LAB_LEVELS) + 1 # 30
69
+ ATTRIBUTES = ("route", "dose", "frequency") # optional MEDS columns -> attribute tokens (0826 Sec. 2.6)
70
+ _EVENT_COLUMNS = ["subject_id", "time", "code", "numeric_value", "text_value", *ATTRIBUTES]
71
+
72
+
73
+ def _time_token(name: str) -> str:
74
+ return f"TIME//{name}"
75
+
76
+
77
+ def gap_tokens(seconds: float) -> list[str]:
78
+ """Time tokens for a gap between consecutive timestamps (none below one minute)."""
79
+ if seconds >= SIX_MONTHS:
80
+ return [_time_token("6mt")] * max(1, round(seconds / SIX_MONTHS))
81
+ for name, low, high in TIME_BUCKETS:
82
+ if low <= seconds < high:
83
+ return [_time_token(name)]
84
+ return []
85
+
86
+
87
+ def _token_seconds(name: str) -> float:
88
+ if name == _time_token("6mt"):
89
+ return SIX_MONTHS
90
+ low, high = next((low, high) for bucket, low, high in TIME_BUCKETS if _time_token(bucket) == name)
91
+ return math.sqrt(low * high)
92
+
93
+
94
+ def age_token(days: float) -> str:
95
+ """Age at the start of the timeline (0826 Sec. 2.1): days in week 1, weeks to 4 weeks, 4-week steps to 1 year,
96
+ 6-month steps to 5 years, then years (up to 120)."""
97
+ days = max(days, 0.0)
98
+ if days < 7:
99
+ return f"AGE//{int(days)}d"
100
+ if days < 28:
101
+ return f"AGE//{int(days // 7)}w"
102
+ if days < 365.25:
103
+ return f"AGE//{4 * int(days // 28)}w"
104
+ years = days / 365.25
105
+ if years < 5:
106
+ return f"AGE//{6 * int(years * 2)}mo"
107
+ return f"AGE//{min(int(years), 120)}y"
108
+
109
+
110
+ AGE_TOKENS = tuple(dict.fromkeys(age_token(d) for d in (*range(0, 365), *np.arange(365.25, 121 * 365.25, 30.0))))
111
+
112
+
113
+ def year_token(year: int) -> str:
114
+ low = year // 5 * 5
115
+ return f"YEAR//{low}-{low + 4}"
116
+
117
+
118
+ EXAMPLE_HIERARCHIES = Path(__file__).parent / "hierarchies" # shipped example hierarchy files
119
+
120
+
121
+ def load_hierarchy(path: Path | str) -> tuple[dict, ...]:
122
+ """Validated hierarchy rules from a YAML file: ``hierarchy: [{code: {regex: ...}, separator: ...}, ...]``.
123
+
124
+ Each rule's regex is matched at the start of a code; the matched prefix stays in the head token and the rest of
125
+ the code is split, either on ``separator`` or into parts of the given character ``widths`` (any remainder is a
126
+ last part). The first matching rule applies; codes no rule matches stay whole.
127
+ """
128
+ data = yaml.safe_load(Path(path).read_text(encoding="utf-8")) or {}
129
+ rules = data.get("hierarchy") if isinstance(data, dict) else None
130
+ if not isinstance(rules, list) or not rules:
131
+ raise ValueError(f"{path} must define a non-empty 'hierarchy' list")
132
+ out = []
133
+ for i, rule in enumerate(rules):
134
+ if not isinstance(rule, dict) or set(rule) - {"code", "separator", "widths"}:
135
+ raise ValueError(f"{path}: rule {i} may only have code, separator and widths")
136
+ regex = rule.get("code", {}).get("regex") if isinstance(rule.get("code"), dict) else None
137
+ if not isinstance(regex, str) or not regex:
138
+ raise ValueError(f"{path}: rule {i} needs code: {{regex: ...}}")
139
+ re.compile(regex)
140
+ separator, widths = rule.get("separator"), rule.get("widths")
141
+ if (separator is None) == (widths is None):
142
+ raise ValueError(f"{path}: rule {i} needs exactly one of separator and widths")
143
+ if separator is not None and (not isinstance(separator, str) or not separator):
144
+ raise ValueError(f"{path}: rule {i} separator must be a non-empty string")
145
+ if widths is not None and (not isinstance(widths, list) or not widths
146
+ or not all(isinstance(w, int) and w > 0 for w in widths)):
147
+ raise ValueError(f"{path}: rule {i} widths must be a non-empty list of positive integers")
148
+ out.append({"regex": regex, "separator": separator, "widths": widths})
149
+ return tuple(out)
150
+
151
+
152
+ def split_code(code: str, rules: tuple[dict, ...]) -> tuple[str, tuple[str, ...], str] | None:
153
+ """``(head, sub-parts, joiner)`` for the first rule matching ``code`` with something after its prefix, or None.
154
+ ``head + joiner.join(...)`` of the parts gives back the code exactly."""
155
+ for rule in rules:
156
+ match = re.match(rule["regex"], code)
157
+ if match is None or match.end() >= len(code):
158
+ continue
159
+ prefix, rest = code[: match.end()], code[match.end():]
160
+ if rule["separator"] is not None:
161
+ parts, joiner = rest.split(rule["separator"]), rule["separator"]
162
+ else:
163
+ parts, start = [], 0
164
+ for width in rule["widths"]:
165
+ parts.append(rest[start: start + width])
166
+ start += width
167
+ parts = [part for part in [*parts, rest[start:]] if part]
168
+ joiner = ""
169
+ return prefix + parts[0], tuple(parts[1:]), joiner
170
+ return None
171
+
172
+
173
+ def _sub_token(depth: int, part: str) -> str:
174
+ return f"SUB//{depth}//{part}"
175
+
176
+
177
+ def _with_columns(frame: pl.LazyFrame) -> pl.LazyFrame:
178
+ schema = frame.collect_schema()
179
+ missing = [pl.lit(None, dtype=pl.String).alias(c) for c in _EVENT_COLUMNS if c not in schema]
180
+ return frame.with_columns(missing).select(
181
+ pl.col("subject_id").cast(pl.Int64), pl.col("time").cast(pl.Datetime("us")), pl.col("code").cast(pl.String),
182
+ pl.col("numeric_value").cast(pl.Float64), pl.col("text_value").cast(pl.String),
183
+ *(pl.col(c).cast(pl.String) for c in ATTRIBUTES),
184
+ ).with_row_index("_order")
185
+
186
+
187
+ def _numeric() -> pl.Expr:
188
+ return pl.col("numeric_value").is_not_null() & pl.col("numeric_value").is_finite()
189
+
190
+
191
+ def _supersede(frame: pl.DataFrame, key: str, window_us: int | None) -> pl.DataFrame:
192
+ """``_superseded``: the time of the next value of the same ``key`` in the same clock-aligned window, if any.
193
+
194
+ A value is dropped from a sequence only once that later value is visible (at or before the cutoff), so the
195
+ latest value per window is kept without ever looking past the cutoff. ``None`` disables downsampling.
196
+ """
197
+ if not window_us:
198
+ return frame.with_columns(pl.lit(None, dtype=pl.Datetime("us")).alias("_superseded"))
199
+ return (
200
+ frame.with_columns((pl.col("time").dt.epoch("us") // window_us).alias("_window"))
201
+ .sort("subject_id", key, "time", "_order")
202
+ .with_columns(
203
+ pl.when(pl.col("_window").shift(-1).over("subject_id", key) == pl.col("_window"))
204
+ .then(pl.col("time").shift(-1).over("subject_id", key)).alias("_superseded")
205
+ )
206
+ )
207
+
208
+
209
+ def _races(column: pl.DataFrame | None) -> pl.DataFrame:
210
+ """First recorded race per subject and its time (null for a static record), from an optional race column
211
+ (MIMIC-IV-MEDS 0.1.0 admission rows). Race recorded as codes (``RACE//<race>``) is an ordinary event."""
212
+ schema = {"subject_id": pl.Int64, "race": pl.String, "time": pl.Datetime("us")}
213
+ if column is None or not column.height:
214
+ return pl.DataFrame(schema=schema)
215
+ frame = column.select(pl.col("subject_id").cast(pl.Int64), pl.col("race").cast(pl.String),
216
+ pl.col("time").cast(pl.Datetime("us"))).filter(pl.col("race").is_not_null())
217
+ return frame.sort("subject_id", "time", "race", nulls_last=False).group_by("subject_id", maintain_order=True).first()
218
+
219
+
220
+ @dataclass(frozen=True)
221
+ class _Vocabulary:
222
+ """Fitted tokenizer state (training split only)."""
223
+
224
+ tokens: tuple[str, ...]
225
+ quantiles: dict[str, tuple[float, ...]] # code -> (min, q(levels)..., max): value buckets
226
+ text_codes: tuple[str, ...] # codes whose value-less rows get result tokens
227
+ cutoff: str # latest training time (ISO): right-censoring bound
228
+ hierarchy: tuple[dict, ...] = () # rules of the hierarchy file (frozen here, so later steps need no file)
229
+ joiners: dict[str, str] | None = None # head token text -> joiner of its sub-parts (decoding)
230
+ split_codes: tuple[str, ...] = () # training codes split into parts that are all in the vocabulary
231
+
232
+ # ---- fitting -----------------------------------------------------------------------------------------------
233
+ @classmethod
234
+ def fit(cls, train: pl.LazyFrame, config: CuriosityConfig, race: pl.LazyFrame | None,
235
+ hierarchy: tuple[dict, ...] = ()) -> _Vocabulary:
236
+ rows = _with_columns(train).filter(pl.col("code") != BIRTH_CODE).collect()
237
+ timed = rows.filter(pl.col("time").is_not_null())
238
+ floor = max(config.min_code_count, config.min_code_share * timed.height)
239
+
240
+ def kept(values: pl.Series) -> list[str]:
241
+ """Values seen at least ``floor`` times (one threshold for codes, result and attribute values)."""
242
+ counts = values.drop_nulls().value_counts()
243
+ return sorted(counts.filter(pl.col("count") >= floor)[values.name].to_list())
244
+
245
+ # Whole codes, or (hierarchy) heads and depth-tagged sub-parts, each kept by the same threshold.
246
+ code_counts = dict(rows["code"].value_counts().iter_rows())
247
+ splits = {code: split_code(code, hierarchy) for code in code_counts} if hierarchy else {}
248
+ whole, heads, subs, joiners = {}, {}, {}, {}
249
+ for code, n in code_counts.items():
250
+ split = splits.get(code)
251
+ if split is None:
252
+ whole[code] = n
253
+ continue
254
+ head, parts, joiner = split
255
+ heads[head] = heads.get(head, 0) + n
256
+ joiners[head] = joiner
257
+ for depth, part in enumerate(parts, 1):
258
+ subs[(depth, part)] = subs.get((depth, part), 0) + n
259
+ codes = sorted(code for code, n in whole.items() if n >= floor)
260
+ kept_heads = sorted(head for head, n in heads.items() if n >= floor)
261
+ kept_subs = sorted(key for key, n in subs.items() if n >= floor)
262
+ known_heads, known_subs = set(kept_heads), set(kept_subs)
263
+ split_known = [code for code, split in splits.items() if split is not None and split[0] in known_heads]
264
+ split_codes = sorted(code for code in split_known
265
+ if all((depth, part) in known_subs for depth, part in enumerate(splits[code][1], 1)))
266
+ in_vocabulary = rows.filter(pl.col("code").is_in([*codes, *split_known]))
267
+ numeric = in_vocabulary.filter(_numeric())
268
+ bucketed = numeric.group_by("code").len().filter(pl.col("len") >= config.min_bucket_observations)["code"]
269
+ text = in_vocabulary.filter(pl.col("numeric_value").is_null() & pl.col("text_value").is_not_null())
270
+ text_codes = kept(text["code"])
271
+ results = kept(text.filter(pl.col("code").is_in(text_codes))["text_value"])
272
+ attributes = [f"ATTR//{c.upper()}//{v}" for c in ATTRIBUTES for v in kept(in_vocabulary[c])]
273
+ quantiles = {}
274
+ if len(bucketed):
275
+ stats = numeric.filter(pl.col("code").is_in(bucketed.implode())).group_by("code").agg(
276
+ pl.col("numeric_value").min().alias("min"),
277
+ *(pl.col("numeric_value").quantile(level, "linear").alias(f"q{i}") for i, level in enumerate(LAB_LEVELS)),
278
+ pl.col("numeric_value").max().alias("max"),
279
+ )
280
+ columns = ["min", *(f"q{i}" for i in range(len(LAB_LEVELS))), "max"]
281
+ quantiles = {row["code"]: tuple(float(row[c]) for c in columns) for row in stats.iter_rows(named=True)}
282
+ races = sorted(_races(race.collect() if race is not None else None)["race"].unique().to_list())
283
+ starts = timed.group_by("subject_id").agg(pl.col("time").min())["time"].dt.year()
284
+ years = sorted({year_token(y) for y in range(int(starts.min()), int(starts.max()) + 1)}) if len(starts) else []
285
+ tokens = (
286
+ PAD, BOS, EOS, UNK,
287
+ *(_time_token(name) for name, _, _ in TIME_BUCKETS), _time_token("6mt"),
288
+ *AGE_TOKENS, *years, *(f"RACE//{value}" for value in races),
289
+ *(f"LABQ//{i}" for i in range(1, LAB_BUCKETS + 1)),
290
+ *(f"RESULT//{v}" for v in results), "RESULT//[OTHER]", "RESULT//[MISSING]",
291
+ *attributes,
292
+ *(f"CODE//{code}" for code in codes),
293
+ *(f"CODE//{head}" for head in kept_heads),
294
+ *(_sub_token(depth, part) for depth, part in kept_subs),
295
+ )
296
+ cutoff = timed["time"].max()
297
+ return cls(tuple(dict.fromkeys(tokens)), quantiles, tuple(text_codes),
298
+ (cutoff or datetime(1970, 1, 1)).isoformat(), tuple(hierarchy),
299
+ {head: joiners[head] for head in kept_heads}, tuple(split_codes))
300
+
301
+ # ---- persistence ---------------------------------------------------------------------------------------------
302
+ def save(self, path: Path) -> None:
303
+ path.write_text(json.dumps({
304
+ "tokens": list(self.tokens),
305
+ "quantiles": {code: list(edges) for code, edges in self.quantiles.items()},
306
+ "text_codes": list(self.text_codes),
307
+ "cutoff": self.cutoff,
308
+ "hierarchy": list(self.hierarchy),
309
+ "joiners": self.joiners or {},
310
+ "split_codes": list(self.split_codes),
311
+ }, sort_keys=True))
312
+
313
+ @classmethod
314
+ def load(cls, path: Path) -> _Vocabulary:
315
+ v = json.loads(path.read_text())
316
+ return cls(tuple(v["tokens"]), {code: tuple(edges) for code, edges in v["quantiles"].items()},
317
+ tuple(v["text_codes"]), v["cutoff"], tuple(v.get("hierarchy", ())), v.get("joiners") or {},
318
+ tuple(v.get("split_codes", ())))
319
+
320
+ # ---- lookups -------------------------------------------------------------------------------------------------
321
+ @property
322
+ def ids(self) -> dict[str, int]:
323
+ return {token: index for index, token in enumerate(self.tokens)}
324
+
325
+ def codes(self) -> set[str]:
326
+ """Every MEDS code the vocabulary can generate: whole-code and head tokens, and the training codes whose
327
+ hierarchy parts are all in the vocabulary."""
328
+ return {token[6:] for token in self.tokens if token.startswith("CODE//")} | set(self.split_codes)
329
+
330
+ def _code_tokens(self, codes: list[str]) -> dict[str, list[int]]:
331
+ """Token ids of each code: a whole-code token; or a head token and its sub-tokens up to the first rare part
332
+ (the code is then represented by its known ancestor); ``[UNK]`` for a rare code or head."""
333
+ ids, out = self.ids, {}
334
+ for code in codes:
335
+ split = split_code(code, self.hierarchy) if self.hierarchy else None
336
+ if split is None:
337
+ out[code] = [ids.get(f"CODE//{code}", ids[UNK])]
338
+ continue
339
+ head, parts, _ = split
340
+ if f"CODE//{head}" not in ids:
341
+ out[code] = [ids[UNK]]
342
+ continue
343
+ tokens = [ids[f"CODE//{head}"]]
344
+ for depth, part in enumerate(parts, 1):
345
+ if _sub_token(depth, part) not in ids:
346
+ break
347
+ tokens.append(ids[_sub_token(depth, part)])
348
+ out[code] = tokens
349
+ return out
350
+
351
+ # ---- events --------------------------------------------------------------------------------------------------
352
+ def events(self, frame: pl.DataFrame, race: pl.DataFrame | None, config: CuriosityConfig) -> tuple[pl.DataFrame, pl.DataFrame]:
353
+ """``(events, subjects)`` for one shard.
354
+
355
+ ``events``: ``subject_id, time, order, tokens, superseded`` (one row per event; ``superseded`` is the time of
356
+ the later value of the same numeric code in the same window, which hides this one once visible).
357
+ ``subjects``: ``subject_id, static, race, race_time, birth, censor`` (``censor`` is null after a death).
358
+ """
359
+ ids = self.ids
360
+ rows = _with_columns(frame.lazy()).collect()
361
+ mapping = self._code_tokens(rows["code"].unique().drop_nulls().to_list())
362
+ code_ids = pl.DataFrame({"code": list(mapping), "_code": list(mapping.values())},
363
+ schema={"code": pl.String, "_code": pl.List(pl.Int32)})
364
+ rows = rows.join(code_ids, on="code", how="left").with_columns(
365
+ pl.col("_code").fill_null(pl.lit([ids[UNK]], dtype=pl.List(pl.Int32))))
366
+ code = pl.col("_code")
367
+ timed = rows.filter(pl.col("time").is_not_null() & ~pl.col("code").is_in([BIRTH_CODE, DEATH_CODE]))
368
+
369
+ # Value token: a percentile bucket, a result token (value-less rows of text codes), or nothing.
370
+ q = len(LAB_LEVELS)
371
+ cuts = pl.DataFrame(
372
+ {"code": list(self.quantiles), **{f"q{i}": [edges[i + 1] for edges in self.quantiles.values()] for i in range(q)}},
373
+ schema={"code": pl.String, **{f"q{i}": pl.Float64 for i in range(q)}},
374
+ )
375
+ results = {t[8:]: i for t, i in ids.items() if t.startswith("RESULT//")}
376
+ bucket = 1 + pl.sum_horizontal([(pl.col("numeric_value") > pl.col(f"q{i}")).cast(pl.Int32) for i in range(q)])
377
+ value = (
378
+ pl.when(pl.col("q0").is_not_null() & _numeric())
379
+ .then(pl.concat_list(bucket.replace_strict(range(1, LAB_BUCKETS + 1),
380
+ [ids[f"LABQ//{i}"] for i in range(1, LAB_BUCKETS + 1)],
381
+ return_dtype=pl.Int32)))
382
+ .when(pl.col("code").is_in(list(self.text_codes)) & pl.col("numeric_value").is_null())
383
+ .then(pl.concat_list(
384
+ pl.when(pl.col("text_value").is_null()).then(pl.lit(results["[MISSING]"], dtype=pl.Int32))
385
+ .otherwise(pl.col("text_value").replace_strict(
386
+ list(results), list(results.values()), default=results["[OTHER]"], return_dtype=pl.Int32))
387
+ ))
388
+ .otherwise(pl.lit([], dtype=pl.List(pl.Int32)))
389
+ )
390
+ attributes = [
391
+ pl.col(column).replace_strict(
392
+ [t.split("//", 2)[2] for t in self.tokens if t.startswith(f"ATTR//{column.upper()}//")],
393
+ [ids[t] for t in self.tokens if t.startswith(f"ATTR//{column.upper()}//")],
394
+ default=None, return_dtype=pl.Int32)
395
+ for column in ATTRIBUTES
396
+ ]
397
+ window = int(config.downsample_hours * 3600 * 1_000_000) if config.downsample_hours else None
398
+ timed = timed.join(cuts, on="code", how="left")
399
+ # Downsampling (0826 Sec. 2.4, applied to every numeric code): latest value per code in each window.
400
+ numeric = _supersede(timed.filter(_numeric()), "code", window)
401
+ others = timed.filter(~_numeric()).with_columns(pl.lit(None, dtype=pl.Datetime("us")).alias("_superseded"))
402
+ columns = ["subject_id", "time", pl.col("_order").cast(pl.Float64).alias("order"),
403
+ pl.concat_list(code, value, *attributes).list.drop_nulls().alias("tokens"),
404
+ pl.col("_superseded").alias("superseded")]
405
+ parts = [numeric.select(columns), others.select(columns)]
406
+
407
+ # Death (0826 Sec. 2.2.2): MEDS_DEATH at the last instant of its date, then EOS; later events are dropped and a
408
+ # record without death is right-censored.
409
+ deaths = rows.filter((pl.col("code") == DEATH_CODE) & pl.col("time").is_not_null()).group_by("subject_id").agg(
410
+ pl.col("time").min().dt.date().cast(pl.Datetime("us")).add(pl.duration(days=1, microseconds=-1)).alias("death"),
411
+ pl.col("_code").first(),
412
+ )
413
+ parts.append(deaths.select(
414
+ "subject_id", pl.col("death").alias("time"), pl.lit(float("inf")).alias("order"),
415
+ pl.concat_list("_code", pl.lit(ids[EOS], dtype=pl.Int32)).alias("tokens"),
416
+ pl.lit(None, dtype=pl.Datetime("us")).alias("superseded"),
417
+ ))
418
+ events = (
419
+ pl.concat(parts)
420
+ .join(deaths.select("subject_id", "death"), on="subject_id", how="left")
421
+ .filter(pl.col("death").is_null() | (pl.col("time") <= pl.col("death")))
422
+ .drop("death")
423
+ .sort("subject_id", "time", "order")
424
+ )
425
+
426
+ # Subjects: static codes, race and its first recorded time, birth, right-censoring time.
427
+ subjects = rows.select("subject_id").unique().sort("subject_id")
428
+ static = rows.filter(pl.col("time").is_null() & (pl.col("code") != BIRTH_CODE)).group_by(
429
+ "subject_id", maintain_order=True).agg(code.explode(keep_nulls=False, empty_as_null=False).alias("static"))
430
+ births = rows.filter((pl.col("code") == BIRTH_CODE) & pl.col("time").is_not_null()).group_by("subject_id").agg(
431
+ pl.col("time").min().alias("birth"))
432
+ last = events.group_by("subject_id").agg(pl.col("time").max().alias("last"))
433
+ cutoff = datetime.fromisoformat(self.cutoff)
434
+ subjects = (
435
+ subjects.join(static, on="subject_id", how="left").join(births, on="subject_id", how="left")
436
+ .join(last, on="subject_id", how="left").join(deaths.select("subject_id", "death"), on="subject_id", how="left")
437
+ .with_columns(
438
+ pl.when(pl.col("death").is_null() & pl.col("last").is_not_null())
439
+ .then(pl.min_horizontal(pl.col("last") + pl.duration(days=config.follow_up_days),
440
+ pl.max_horizontal(pl.lit(cutoff), pl.col("last"))))
441
+ .alias("censor"),
442
+ pl.col("static").fill_null(pl.lit([], dtype=pl.List(pl.Int32))),
443
+ )
444
+ )
445
+ race_ids = {t[6:]: i for t, i in ids.items() if t.startswith("RACE//")}
446
+ subjects = subjects.join(_races(race).select(
447
+ "subject_id",
448
+ pl.col("race").replace_strict(race_ids, default=None, return_dtype=pl.Int32),
449
+ pl.col("time").alias("race_time"),
450
+ ), on="subject_id", how="left")
451
+ return events, subjects.select("subject_id", "static", "race", "race_time", "birth", "censor")
452
+
453
+ # ---- sequences -----------------------------------------------------------------------------------------------
454
+ def sequences(self, events: pl.DataFrame, subjects: pl.DataFrame, cutoffs: pl.DataFrame | None = None) -> pl.DataFrame:
455
+ """Token sequences. Without ``cutoffs``: one training sequence per subject (all events, superseded values
456
+ dropped, then EOS or padding). With ``cutoffs`` (``subject_id, prediction_time``): one prompt per row, built
457
+ only from what is recorded at or before ``prediction_time`` and ending with the elapsed-gap time tokens."""
458
+ ids = self.ids
459
+ training = cutoffs is None
460
+ if training:
461
+ cutoffs = subjects.select("subject_id", pl.lit(None, dtype=pl.Datetime("us")).alias("prediction_time"))
462
+ keys = cutoffs.select(pl.col("subject_id").cast(pl.Int64), pl.col("prediction_time").cast(pl.Datetime("us")))
463
+ keys = keys.with_row_index("_key")
464
+ cut = pl.col("prediction_time")
465
+ visible = (
466
+ keys.join(events, on="subject_id", how="inner")
467
+ .filter(
468
+ pl.when(cut.is_null()).then(pl.col("superseded").is_null())
469
+ .otherwise((pl.col("time") <= cut) & (pl.col("superseded").is_null() | (pl.col("superseded") > cut)))
470
+ )
471
+ .sort("_key", "time", "order")
472
+ )
473
+ bucket_ids = [ids[_time_token(name)] for name, _, _ in TIME_BUCKETS]
474
+ six = ids[_time_token("6mt")]
475
+
476
+ def gap_expr(seconds: pl.Expr) -> pl.Expr:
477
+ bucket = pl.sum_horizontal([(seconds >= low).cast(pl.Int32) for _, low, _ in TIME_BUCKETS])
478
+ return (
479
+ pl.when(seconds >= SIX_MONTHS)
480
+ .then(pl.lit(six, dtype=pl.Int32).repeat_by((seconds / SIX_MONTHS).round().cast(pl.Int64).clip(lower_bound=1)))
481
+ .when(seconds.is_not_null() & (bucket > 0))
482
+ .then(pl.concat_list(bucket.replace_strict(range(1, len(bucket_ids) + 1), bucket_ids, default=None,
483
+ return_dtype=pl.Int32)))
484
+ .otherwise(pl.lit([], dtype=pl.List(pl.Int32)))
485
+ )
486
+
487
+ previous = pl.col("time").shift(1).over("_key")
488
+ gap = pl.when(pl.col("time") != previous).then((pl.col("time") - previous).dt.total_microseconds() / 1e6)
489
+ body = (
490
+ visible.with_columns(pl.concat_list(gap_expr(gap), "tokens").alias("_tokens"))
491
+ .group_by("_key", maintain_order=True)
492
+ .agg(pl.col("_tokens").explode(keep_nulls=False, empty_as_null=False).alias("_body"),
493
+ pl.col("time").min().alias("_start"), pl.col("time").max().alias("_last"))
494
+ )
495
+ out = keys.join(subjects, on="subject_id", how="left").join(body, on="_key", how="left")
496
+ start = pl.coalesce("_start", cut)
497
+ age_days = (start - pl.col("birth")).dt.total_seconds() / 86400.0
498
+ age_ids = {t: i for t, i in ids.items() if t.startswith("AGE//")}
499
+ year_ids = {t: i for t, i in ids.items() if t.startswith("YEAR//")}
500
+ years = sorted(year_ids)
501
+
502
+ def year_id(year):
503
+ if year is None or not years:
504
+ return None
505
+ token = year_token(int(year))
506
+ return year_ids.get(token, year_ids[years[0]] if token < years[0] else year_ids[years[-1]])
507
+
508
+ empty = pl.lit([], dtype=pl.List(pl.Int32))
509
+ out = out.with_columns(
510
+ pl.when(age_days.is_not_null()).then(pl.concat_list(age_days.map_elements(
511
+ lambda d: age_ids[age_token(d)], return_dtype=pl.Int32))).otherwise(empty).alias("_age"),
512
+ pl.when(start.is_not_null()).then(pl.concat_list(start.dt.year().map_elements(year_id, return_dtype=pl.Int32)))
513
+ .otherwise(empty).list.drop_nulls().alias("_year"),
514
+ pl.when(pl.col("race").is_not_null() & (pl.col("race_time").is_null() | cut.is_null() | (pl.col("race_time") <= cut)))
515
+ .then(pl.concat_list("race")).otherwise(empty).alias("_race"),
516
+ pl.col("_body").fill_null(empty),
517
+ )
518
+ if training:
519
+ padding = (pl.col("censor") - pl.col("_last")).dt.total_seconds() / SIX_MONTHS
520
+ tail = pl.when(pl.col("censor").is_not_null()).then(
521
+ pl.lit(six, dtype=pl.Int32).repeat_by(padding.round().cast(pl.Int64).clip(lower_bound=0))).otherwise(empty)
522
+ else:
523
+ elapsed = (cut - pl.col("_last")).dt.total_microseconds() / 1e6
524
+ tail = pl.when(pl.col("_last").is_not_null()).then(gap_expr(elapsed)).otherwise(empty)
525
+ return out.select(
526
+ "subject_id", "prediction_time",
527
+ pl.concat_list(pl.lit([ids[BOS]], dtype=pl.List(pl.Int32)), "static", "_race", "_age", "_year", "_body",
528
+ tail.alias("_tail")).alias("tokens"),
529
+ ).sort("subject_id", "prediction_time")
530
+
531
+ # ---- generation ----------------------------------------------------------------------------------------------
532
+ def decode(self, tokens: list[int], prediction_time: datetime, uniforms: np.ndarray) -> tuple[list[tuple], datetime, int]:
533
+ """Generated ids -> (``(time, code, numeric_value, text_value)`` events, final clock, invalid-token count).
534
+
535
+ The clock starts at the prediction time (the prompt ends with the real elapsed gap); generated events sharing
536
+ it are placed one microsecond later. A bucket token draws its value uniformly within the bucket (0226 App. G).
537
+ Attribute tokens carry no event; BOS or EOS ends the record.
538
+ """
539
+ clock, events, invalid = prediction_time, [], 0
540
+ future = prediction_time + timedelta(microseconds=1)
541
+ joiners = self.joiners or {}
542
+ code = value = text = joiner = None
543
+ depth = 0
544
+
545
+ def flush():
546
+ nonlocal code, value, text, joiner, depth
547
+ if code is not None:
548
+ events.append((max(clock, future), code, value, text))
549
+ code = value = text = joiner = None
550
+ depth = 0
551
+
552
+ for position, index in enumerate(tokens):
553
+ token = self.tokens[index]
554
+ kind, _, rest = token.partition("//")
555
+ if token in (BOS, EOS):
556
+ flush()
557
+ break
558
+ if kind == "TIME":
559
+ flush()
560
+ clock += timedelta(seconds=_token_seconds(token))
561
+ elif kind == "CODE":
562
+ flush()
563
+ code, joiner = rest, joiners.get(rest)
564
+ elif kind == "SUB":
565
+ level, _, part = rest.partition("//")
566
+ if joiner is not None and value is None and text is None and int(level) == depth + 1:
567
+ code, depth = code + joiner + part, depth + 1
568
+ else:
569
+ invalid += 1
570
+ elif kind == "LABQ":
571
+ if code in self.quantiles and value is None:
572
+ edges, bucket = self.quantiles[code], int(rest)
573
+ value = float(edges[bucket - 1] + uniforms[position] * (edges[bucket] - edges[bucket - 1]))
574
+ else:
575
+ invalid += 1
576
+ elif kind == "RESULT":
577
+ if code is not None and code in self.text_codes and text is None:
578
+ text = None if rest in ("[OTHER]", "[MISSING]") else rest
579
+ else:
580
+ invalid += 1
581
+ elif kind == "ATTR":
582
+ continue # attributes qualify the preceding code
583
+ else: # PAD, UNK, demographic tokens: no event
584
+ flush()
585
+ invalid += token != UNK
586
+ flush()
587
+ return events, clock, invalid