custom_time_token
Transformations for adding time-derived measurements (e.g., a subject’s age) to a MEDS dataset.
add_new_events_fntr(fn)
Creates a “meta” functor that computes the input functor on a MEDS shard then combines both dataframes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn |
Callable[[DataFrame], DataFrame]
|
The function that computes the new events. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[DataFrame], DataFrame]
|
A function that computes the new events and combines them with the original DataFrame, returning a |
Callable[[DataFrame], DataFrame]
|
result in proper MEDS sorted order. |
Examples:
>>> from datetime import datetime
>>> df = pl.DataFrame(
... {
... "subject_id": [1, 1, 1, 1, 2, 2, 3, 3],
... "time": [
... None,
... datetime(1990, 1, 1),
... datetime(2021, 1, 1),
... datetime(2021, 1, 1),
... datetime(1988, 1, 2),
... datetime(2023, 1, 3),
... datetime(2022, 1, 1),
... datetime(2022, 1, 1),
... ],
... "code": ["static", "DOB", "lab//A", "lab//B", "DOB", "lab//A", "lab//B", "dx//1"],
... },
... schema={"subject_id": pl.UInt32, "time": pl.Datetime, "code": pl.Utf8},
... )
>>> df
shape: (8, 3)
┌────────────┬─────────────────────┬────────┐
│ subject_id ┆ time ┆ code │
│ --- ┆ --- ┆ --- │
│ u32 ┆ datetime[μs] ┆ str │
╞════════════╪═════════════════════╪════════╡
│ 1 ┆ null ┆ static │
│ 1 ┆ 1990-01-01 00:00:00 ┆ DOB │
│ 1 ┆ 2021-01-01 00:00:00 ┆ lab//A │
│ 1 ┆ 2021-01-01 00:00:00 ┆ lab//B │
│ 2 ┆ 1988-01-02 00:00:00 ┆ DOB │
│ 2 ┆ 2023-01-03 00:00:00 ┆ lab//A │
│ 3 ┆ 2022-01-01 00:00:00 ┆ lab//B │
│ 3 ┆ 2022-01-01 00:00:00 ┆ dx//1 │
└────────────┴─────────────────────┴────────┘
>>> # As an example, we'll use the age functor defined elsewhere in this module.
>>> age_cfg = DictConfig({"DOB_code": "DOB", "age_code": "AGE", "age_unit": "years"})
>>> age_fn = age_fntr(age_cfg)
>>> age_fn(df)
shape: (2, 4)
┌────────────┬─────────────────────┬──────┬───────────────┐
│ subject_id ┆ time ┆ code ┆ numeric_value │
│ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ datetime[μs] ┆ str ┆ f32 │
╞════════════╪═════════════════════╪══════╪═══════════════╡
│ 1 ┆ 2021-01-01 00:00:00 ┆ AGE ┆ 31.001347 │
│ 2 ┆ 2023-01-03 00:00:00 ┆ AGE ┆ 35.004169 │
└────────────┴─────────────────────┴──────┴───────────────┘
>>> # Now, we'll use the add_new_events functor to add these age events to the original DataFrame.
>>> add_age_fn = add_new_events_fntr(age_fn)
>>> add_age_fn(df)
shape: (10, 4)
┌────────────┬─────────────────────┬────────┬───────────────┐
│ subject_id ┆ time ┆ code ┆ numeric_value │
│ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ datetime[μs] ┆ str ┆ f32 │
╞════════════╪═════════════════════╪════════╪═══════════════╡
│ 1 ┆ null ┆ static ┆ null │
│ 1 ┆ 1990-01-01 00:00:00 ┆ DOB ┆ null │
│ 1 ┆ 2021-01-01 00:00:00 ┆ AGE ┆ 31.001347 │
│ 1 ┆ 2021-01-01 00:00:00 ┆ lab//A ┆ null │
│ 1 ┆ 2021-01-01 00:00:00 ┆ lab//B ┆ null │
│ 2 ┆ 1988-01-02 00:00:00 ┆ DOB ┆ null │
│ 2 ┆ 2023-01-03 00:00:00 ┆ AGE ┆ 35.004169 │
│ 2 ┆ 2023-01-03 00:00:00 ┆ lab//A ┆ null │
│ 3 ┆ 2022-01-01 00:00:00 ┆ lab//B ┆ null │
│ 3 ┆ 2022-01-01 00:00:00 ┆ dx//1 ┆ null │
└────────────┴─────────────────────┴────────┴───────────────┘
Source code in meds_torch/utils/custom_time_token.py
age_fntr(cfg)
Create a function that adds a subject’s age to a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg |
DictConfig
|
The configuration for the age function. This must contain the following mandatory keys: - “DOB_code”: The code for the date of birth event in the raw data. - “age_code”: The code for the age event in the output data. - “age_unit”: The unit for the age event when converted to a numeric value in the output data. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[DataFrame], DataFrame]
|
A function that returns the to-be-added “age” events with the subject’s age for all input events with |
Callable[[DataFrame], DataFrame]
|
unique, non-null times in the data, for all subjects who have an observed date of birth. It does |
Callable[[DataFrame], DataFrame]
|
not add an event for times that are equal to the date of birth. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input unit is not recognized. |
Examples:
>>> from datetime import datetime
>>> df = pl.DataFrame(
... {
... "subject_id": [1, 1, 1, 1, 1, 2, 2, 3, 3],
... "time": [
... None,
... datetime(1990, 1, 1),
... datetime(2021, 1, 1),
... datetime(2021, 1, 1),
... datetime(2021, 1, 2),
... datetime(1988, 1, 2),
... datetime(2023, 1, 3),
... datetime(2022, 1, 1),
... datetime(2022, 1, 1),
... ],
... "code": ["static", "DOB", "lab//A", "lab//B", "rx", "DOB", "lab//A", "lab//B", "dx//1"],
... },
... schema={"subject_id": pl.UInt32, "time": pl.Datetime, "code": pl.Utf8},
... )
>>> df
shape: (9, 3)
┌────────────┬─────────────────────┬────────┐
│ subject_id ┆ time ┆ code │
│ --- ┆ --- ┆ --- │
│ u32 ┆ datetime[μs] ┆ str │
╞════════════╪═════════════════════╪════════╡
│ 1 ┆ null ┆ static │
│ 1 ┆ 1990-01-01 00:00:00 ┆ DOB │
│ 1 ┆ 2021-01-01 00:00:00 ┆ lab//A │
│ 1 ┆ 2021-01-01 00:00:00 ┆ lab//B │
│ 1 ┆ 2021-01-02 00:00:00 ┆ rx │
│ 2 ┆ 1988-01-02 00:00:00 ┆ DOB │
│ 2 ┆ 2023-01-03 00:00:00 ┆ lab//A │
│ 3 ┆ 2022-01-01 00:00:00 ┆ lab//B │
│ 3 ┆ 2022-01-01 00:00:00 ┆ dx//1 │
└────────────┴─────────────────────┴────────┘
>>> age_cfg = DictConfig({"DOB_code": "DOB", "age_code": "AGE", "age_unit": "years"})
>>> age_fn = age_fntr(age_cfg)
>>> age_fn(df)
shape: (3, 4)
┌────────────┬─────────────────────┬──────┬───────────────┐
│ subject_id ┆ time ┆ code ┆ numeric_value │
│ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ datetime[μs] ┆ str ┆ f32 │
╞════════════╪═════════════════════╪══════╪═══════════════╡
│ 1 ┆ 2021-01-01 00:00:00 ┆ AGE ┆ 31.001347 │
│ 1 ┆ 2021-01-02 00:00:00 ┆ AGE ┆ 31.004084 │
│ 2 ┆ 2023-01-03 00:00:00 ┆ AGE ┆ 35.004169 │
└────────────┴─────────────────────┴──────┴───────────────┘
>>> age_cfg = DictConfig({"DOB_code": "DOB", "age_code": "AGE", "age_unit": "scores"})
>>> import pytest
>>> with pytest.raises(ValueError):
... age_fntr(age_cfg)
Source code in meds_torch/utils/custom_time_token.py
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | |
main(cfg)
Adds time-derived measurements to a MEDS cohort as separate observations at each unique time.
Source code in meds_torch/utils/custom_time_token.py
normalize_time_unit(unit)
Normalize a time unit string to a canonical form and return the number of seconds in that unit.
Note that this function is designed for computing approximate time durations over long periods, not canonical, local calendar time durations. E.g., a “month” is not a fixed number of seconds, but this function will return the average number of seconds in a month, accounting for leap years.
TODO: consider replacing this function with the use of https://github.com/wroberts/pytimeparse
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unit |
str
|
The input unit to normalize. |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, float]
|
A tuple containing the canonical unit and the number of seconds in that unit. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input unit is not recognized. |
Examples:
>>> normalize_time_unit("s")
('seconds', 1)
>>> normalize_time_unit("min")
('minutes', 60)
>>> normalize_time_unit("hours")
('hours', 3600)
>>> normalize_time_unit("day")
('days', 86400)
>>> normalize_time_unit("wks")
('weeks', 604800)
>>> normalize_time_unit("month")
('months', 2629746.0)
>>> normalize_time_unit("years")
('years', 31556926.080000002)
>>> normalize_time_unit("fortnight")
Traceback (most recent call last):
...
ValueError: Unknown time unit 'fortnight'. Valid units include:
* seconds: s, sec, secs, second, seconds
* minutes: m, min, mins, minute, minutes
* hours: h, hr, hrs, hour, hours
* days: d, day, days
* weeks: w, wk, wks, week, weeks
* months: mo, mos, month, months
* years: y, yr, yrs, year, years
Source code in meds_torch/utils/custom_time_token.py
time_delta_fntr(cfg)
Create a function that adds time_delta event rows to a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg |
DictConfig
|
The configuration for the age function. This must contain the following mandatory keys: - “quantile_fp”: The path to a parquet file with pre-defined time delta quantiles. Should have a quantile column of type Int64 and a value column of type Float64 indicating the numerical value for the quantile. - “max_length”: The maximum number of time_delta qunatile tokens to use to approximate the continuous value. - “time_unit”: The unit for the time deltas when dates are converted to a numeric value in the output data. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[DataFrame], DataFrame]
|
A function that returns the to-be-added “time_delta” events with the quantile of the time delta |
Callable[[DataFrame], DataFrame]
|
for all input events with unique, non-null times in the data. The very first event for a subject |
Callable[[DataFrame], DataFrame]
|
has a null time_delta, so it is imputed with a special time start token. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input unit is not recognized. |
Examples:
>>> from datetime import datetime
>>> df = pl.DataFrame(
... {
... "subject_id": [1, 1, 1, 1, 1, 2, 2, 3, 3],
... "time": [
... None,
... datetime(1990, 1, 1),
... datetime(2021, 1, 1),
... datetime(2021, 1, 1),
... datetime(2021, 1, 2),
... datetime(1988, 1, 2),
... datetime(2023, 1, 3),
... datetime(2022, 1, 1),
... datetime(2022, 1, 1),
... ],
... "code": ["static", "DOB", "lab//A", "lab//B", "rx", "DOB", "lab//A", "lab//B", "dx//1"],
... },
... schema={"subject_id": pl.UInt32, "time": pl.Datetime, "code": pl.Utf8},
... )
>>> df
shape: (9, 3)
┌────────────┬─────────────────────┬────────┐
│ subject_id ┆ time ┆ code │
│ --- ┆ --- ┆ --- │
│ u32 ┆ datetime[μs] ┆ str │
╞════════════╪═════════════════════╪════════╡
│ 1 ┆ null ┆ static │
│ 1 ┆ 1990-01-01 00:00:00 ┆ DOB │
│ 1 ┆ 2021-01-01 00:00:00 ┆ lab//A │
│ 1 ┆ 2021-01-01 00:00:00 ┆ lab//B │
│ 1 ┆ 2021-01-02 00:00:00 ┆ rx │
│ 2 ┆ 1988-01-02 00:00:00 ┆ DOB │
│ 2 ┆ 2023-01-03 00:00:00 ┆ lab//A │
│ 3 ┆ 2022-01-01 00:00:00 ┆ lab//B │
│ 3 ┆ 2022-01-01 00:00:00 ┆ dx//1 │
└────────────┴─────────────────────┴────────┘
>>> import tempfile
>>> with tempfile.TemporaryDirectory() as tmpdir:
... fp = f"{tmpdir}/quantile.parquet"
... pl.DataFrame({"quantile": [25, 50, 75], "value": [1,2,3]}).write_parquet(fp)
... time_delta_cfg = DictConfig({"quantile_fp": fp, "time_unit": "days", "max_length": 3})
... time_delta_fn = time_delta_fntr(time_delta_cfg)
... time_delta_fn(df)
shape: (6, 4)
┌────────────┬─────────────────────┬───────────────┬────────────────────┐
│ subject_id ┆ time ┆ numeric_value ┆ code │
│ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ datetime[μs] ┆ f32 ┆ str │
╞════════════╪═════════════════════╪═══════════════╪════════════════════╡
│ 1 ┆ 1990-01-01 00:00:00 ┆ null ┆ TIME//START//TOKEN │
│ 1 ┆ 2021-01-01 00:00:00 ┆ 11323.0 ┆ TIME//DELTA//TOKEN │
│ 1 ┆ 2021-01-02 00:00:00 ┆ 1.0 ┆ TIME//DELTA//TOKEN │
│ 2 ┆ 1988-01-02 00:00:00 ┆ null ┆ TIME//START//TOKEN │
│ 2 ┆ 2023-01-03 00:00:00 ┆ 12785.0 ┆ TIME//DELTA//TOKEN │
│ 3 ┆ 2022-01-01 00:00:00 ┆ null ┆ TIME//START//TOKEN │
└────────────┴─────────────────────┴───────────────┴────────────────────┘
Source code in meds_torch/utils/custom_time_token.py
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 | |