multiwindow_pytorch_dataset
DummyMultiWindowConfig
dataclass
Bases: DummyConfig
Configuration for MultiWindow dataset
Source code in meds_torch/data/components/multiwindow_pytorch_dataset.py
MultiWindowPytorchDataset
Bases: SeedableMixin, Dataset
A Multi-Window PyTorch Dataset class for contrastive learning pretraining.
This class extends the functionality of a standard PyTorch Dataset to support multiple time windows for each subject. It’s designed to work with medical event data, where each subject may have multiple relevant time windows for analysis.
The dataset can be configured to sample at the subject level or at the window level, allowing for flexible data loading strategies in contrastive learning scenarios.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg |
DictConfig
|
Configuration options for the dataset. |
required |
split |
str
|
The data split to use (e.g., ‘train’, ‘validation’, ‘test’). |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
config |
DictConfig
|
The configuration object for the dataset. |
split |
str
|
The current data split being used. |
pytorch_dataset |
PytorchDataset
|
The underlying PyTorch dataset. |
window_cols |
list
|
List of window column names. |
index |
list
|
List of dictionaries, each representing a subject or a window, depending on the sampling strategy. |
Example:
import tempfile from pathlib import Path import torch import polars as pl from omegaconf import OmegaConf
Create dummy dataset in a temporary directory
with tempfile.TemporaryDirectory() as tmp_dir: … # Generate dummy config with sample data … config = create_dummy_multiwindow_dataset(tmp_dir) … cfg = config … … # Initialize the dataset … dataset = MultiWindowPytorchDataset(cfg, split=”train”) … … # Check the available windows … print(f”Window columns: {dataset.window_cols}”) … … # Get a sample item … sample = dataset[0] … … # Examine the structure of the first window … window_name = dataset.window_cols[0] … print(f”\nStructure of {window_name} window:”) … for key, value in sample[window_name].items(): … if isinstance(value, dict): … print(f”{key}:”) … for subkey, subvalue in value.items(): … print(f” {subkey}: {type(subvalue)}”) … else: … print(f”{key}: {type(value)}”) … … # Create a dataloader and get a batch … dataloader = torch.utils.data.DataLoader( … dataset, … batch_size=2, … collate_fn=dataset.collate … ) … batch = next(iter(dataloader)) Window columns: [‘window_1_summary’, ‘window_2_summary’]
Structure of window_1_summary window: static_indices: static_values: start_idx: end_idx: dynamic: start_time: end_time:
Source code in meds_torch/data/components/multiwindow_pytorch_dataset.py
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 | |
__getitem__(idx)
Get a single item from the dataset.
This method retrieves data for a single subject, returning a dictionary where each key represents a window, and the corresponding value is the output of PytorchDataset.getitem for that window.
Args: idx (int): The index of the item to retrieve.
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
dict[str, dict]: A dictionary where keys are window names (e.g., ‘pre’, ‘post’) and values are dictionaries containing the data for each window. The structure of each window’s data typically includes: - ‘static_indices’: List of static categorical metadata elements. - ‘static_values’: List of static numerical metadata elements. - ‘dynamic’: Dictionary containing: - ‘time_delta_days’: List of time deltas between events. - ‘dim1/code’: List of dynamic categorical metadata elements. - ‘dim1/numeric_value’: List of dynamic numerical metadata elements. |
Source code in meds_torch/data/components/multiwindow_pytorch_dataset.py
__init__(cfg, split)
Initialize the MultiWindowPytorchDataset.
This method sets up the dataset by loading or creating cached window indexes, initializing the underlying PytorchDataset, and preparing the index based on the specified sampling strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg |
DictConfig
|
Configuration options for the dataset. |
required |
split |
str
|
The data split to use (e.g., ‘train’, ‘validation’, ‘test’). |
required |
Source code in meds_torch/data/components/multiwindow_pytorch_dataset.py
collate(batch)
Collate a batch of data samples into a single batch.
This method is responsible for combining multiple data samples into a single batch that can be processed by a PyTorch model. It handles both window-specific data and any additional data that might be present.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch |
dict[str, array]
|
A dictionary of arrays, each representing a batch of data for a specific feature. |
required |
Returns:
| Type | Description |
|---|---|
dict[str:Tensor]
|
dict[str, torch.Tensor]: A dictionary of tensors, representing the collated batch data. |
Source code in meds_torch/data/components/multiwindow_pytorch_dataset.py
filter_invalid_window(window_df)
Filter out invalid windows if st index >= end index.
Source code in meds_torch/data/components/multiwindow_pytorch_dataset.py
MultiWindowSamplingStrategy
Bases: StrEnum
Enumeration of sampling strategies for multi-window datasets.
Attributes:
| Name | Type | Description |
|---|---|---|
RANDOM |
Randomly sample and window from the dataset, partitioning it into separate subwindows. |
|
PREDEFINED |
Use predefined windows around events to sample from the dataset. |
Source code in meds_torch/data/components/multiwindow_pytorch_dataset.py
cache_window_indexes(cfg, split, static_dfs)
Caches window indexes for the given split of the dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg |
DictConfig
|
description |
required |
split |
str
|
description |
required |
static_dfs |
_type_
|
description |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: description |
Example:
import tempfile import pprint with tempfile.TemporaryDirectory() as tmpdir: … config = create_dummy_multiwindow_dataset(tmpdir) … static_df = pl.read_parquet(Path(config.data_dir) / “schema/train/shard_0.parquet”) … raw_windows_df = pl.read_parquet(Path(config.data_dir) / “raw_windows.parquet”) … cache_window_indexes(config, “train”, {“shard_0”: static_df}) … cached_window_df = pl.read_parquet(Path(config.cache_dir) / “train.parquet”).sort(“subject_id”) pprint.pprint({k: v.to_list() for k,v in cached_window_df.to_dict().items()}) {‘subject_id’: [0, 1, 2], ‘window_1_summary.end_idx’: [[3], [3], [3]], ‘window_1_summary.start_idx’: [[0], [0], [0]], ‘window_2_summary.end_idx’: [[4], [4], [4]], ‘window_2_summary.start_idx’: [[3], [3], [3]]}
Source code in meds_torch/data/components/multiwindow_pytorch_dataset.py
create_dummy_multiwindow_dataset(base_dir, n_subjects=3, split='train', seed=42)
Creates a dummy MultiWindow dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_dir |
str | Path
|
directory to store the dataset in. |
required |
n_subjects |
int
|
Number of subjects to generate. |
3
|
split |
str
|
Is the dataset split. Defaults to “train”. |
'train'
|
seed |
int | None
|
Seed used for rng when making the dataset. Defaults to 42. |
42
|
Returns:
| Name | Type | Description |
|---|---|---|
DummyMultiWindowConfig |
DummyMultiWindowConfig
|
dataset config that can be used to create a MultiWindow dataset. |
Example:
import tempfile _ = pl.Config.set_tbl_width_chars(106) with tempfile.TemporaryDirectory() as tmp_dir: … config = create_dummy_multiwindow_dataset(tmp_dir) … task_df = pl.read_parquet(Path(config.data_dir) / “task_labels.parquet”) … print(task_df) … raw_windows_df = pl.read_parquet(Path(config.data_dir) / “raw_windows.parquet”) … print(raw_windows_df.sort(“subject_id”)) shape: (3, 3) ┌────────────┬─────────────────────┬───────────────┐ │ subject_id ┆ prediction_time ┆ boolean_value │ │ — ┆ — ┆ — │ │ i64 ┆ datetime[μs] ┆ i64 │ ╞════════════╪═════════════════════╪═══════════════╡ │ 0 ┆ 1998-01-01 00:00:00 ┆ 0 │ │ 1 ┆ 1998-01-01 00:00:00 ┆ 1 │ │ 2 ┆ 1998-01-01 00:00:00 ┆ 0 │ └────────────┴─────────────────────┴───────────────┘ shape: (3, 4) ┌────────────┬─────────────────────┬─────────────────────────────────┬─────────────────────────────────┐ │ subject_id ┆ trigger ┆ window_1_summary ┆ window_2_summary │ │ — ┆ — ┆ — ┆ — │ │ i64 ┆ datetime[μs] ┆ struct[4] ┆ struct[4] │ ╞════════════╪═════════════════════╪═════════════════════════════════╪═════════════════════════════════╡ │ 0 ┆ 1998-01-01 00:00:00 ┆ {0,1998-01-01 00:00:00,1995-01… ┆ {0,1998-01-01 00:00:00,1998-01… │ │ 1 ┆ 1998-01-01 00:00:00 ┆ {1,1998-01-01 00:00:00,1995-01… ┆ {1,1998-01-01 00:00:00,1998-01… │ │ 2 ┆ 1998-01-01 00:00:00 ┆ {2,1998-01-01 00:00:00,1995-01… ┆ {2,1998-01-01 00:00:00,1998-01… │ └────────────┴─────────────────────┴─────────────────────────────────┴─────────────────────────────────┘
Source code in meds_torch/data/components/multiwindow_pytorch_dataset.py
fuse_window_data(windows_data, windows_to_fuse, fused_window_name)
Fuse multiple windows into a single window, tracking the lengths of original windows.
Warning
- This function assumes that the static data is not prepended to the dynamic data
- We also assume that static data is the same for all time windows, as it is invariant to time windows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
windows_data |
dict
|
Dictionary containing data from multiple windows to be fused |
required |
windows_to_fuse |
list[str]
|
List of window names to fuse in specified order |
required |
fused_window_name |
str
|
Name for the resulting fused window |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Fused window data with length tracking information |
Raises:
| Type | Description |
|---|---|
ValueError
|
If fusion configuration is invalid or data type is unsupported |
Example:
import torch
Create mock data with different types
windows_data = { … “pre”: { … # 1D tensor … “static_values”: torch.tensor([1.0, 2.0]), … # 2D tensor (batch_size=2, seq_len=3, features=2) … “embeddings”: torch.ones(2, 3, 2), … # List … “codes”: [“A”, “B”, “C”], … }, … “post”: { … “static_values”: torch.tensor([3.0, 4.0]), … “embeddings”: torch.ones(2, 2, 2) * 2, … “codes”: [“D”, “E”], … } … }
Fuse windows
fused = fuse_window_data( … windows_data, … windows_to_fuse=[“pre”, “post”], … fused_window_name=”fused” … ) Traceback (most recent call last): … ValueError: Unsupported data type
for key codes Remove the list keys
del windows_data[‘pre’]['codes'] del windows_data[‘post’]['codes'] fused = fuse_window_data( … windows_data, … windows_to_fuse=[“pre”, “post”], … fused_window_name=”fused” … )
Check lengths tracking
fused[“LENGTHS//static_values”] # Two windows should select just the first one [2, 2] fused[“LENGTHS//embeddings”] # Two windows with sequence lengths 3 and 2 [3, 2]
Check only first window’s static values (as static data is the same across all windows)
torch.equal(fused[“static_values”], torch.tensor([1.0, 2.0])) True
Check 2D tensor concatenation along sequence dimension
torch.equal(fused[“embeddings”], … torch.cat([torch.ones(2, 3, 2), … torch.ones(2, 2, 2) * 2], dim=1)) True
Test error handling
fuse_window_data(windows_data, [“nonexistent”], “fused”) Traceback (most recent call last): … ValueError: Window nonexistent specified in windows_to_fuse not found in data
Test error when no fused_window_name
fuse_window_data(windows_data, [“pre”, “post”], None) Traceback (most recent call last): … ValueError: fused_window_name must not be empty
Source code in meds_torch/data/components/multiwindow_pytorch_dataset.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | |
get_window_indexes(static_df, windows_df)
Computes the start and end indexes of time windows for each entry in the provided DataFrame. This
function assumes that the “time” in timestamps_series is sorted. It finds the index of timestamps that
fall between ‘start’ and ‘end’ times specified in windows_df.
Parameters: - static_df (pl.Series): A Polars dataframe containing sorted datetime values for each subject. - windows_df (pl.DataFrame): A DataFrame with columns ‘name’, ‘start’, and ‘end’ specifying the time windows.
- pl.DataFrame: A DataFrame with the original columns of
windows_dfplus for each.start and .end in windows_df, the column ‘ .start_idx’ and ‘ .end_idx’ indicating the inclusive index range of timestamps within each window is added.
Example:
import pprint _ = pl.Config.set_tbl_width_chars(106) timeseries_df = pl.DataFrame({ … “subject_id”: [1, 2], … “time”: [ … pl.Series([“1978-03-09 00:00:00”, “2010-05-26 02:30:56”, “2010-05-26 04:51:52”] … ).str.strptime(pl.Datetime), … pl.Series([“1970-03-09 00:00:00”, “1972-05-26 02:30:56”, “1975-05-26 04:51:52”] … ).str.strptime(pl.Datetime) … ] … }) windows_df = pl.DataFrame({ … “subject_id”: [1, 2], … “pre.start”: [[“1978-03-09 00:00:00”, “2010-05-26 02:30:56”], [“1969-05-26 02:30:56”]], … “pre.end”: [[“2010-05-26 02:30:56”, “2010-05-26 04:51:52”], [“1971-05-26 04:51:52”]], … “post.start”: [[“1978-03-09 00:00:00”, “2010-05-26 02:30:56”], [“1971-05-26 02:30:56”]], … “post.end”: [[“2010-05-26 02:30:56”, “2010-05-26 04:51:52”], [“1980-05-26 04:51:52”]], … }).with_columns([ … pl.col(“pre.start”).list.eval(pl.element().str.to_datetime()), … pl.col(“pre.end”).list.eval(pl.element().str.to_datetime()), … pl.col(“post.start”).list.eval(pl.element().str.to_datetime()), … pl.col(“post.end”).list.eval(pl.element().str.to_datetime()), … ]) timeseries_df shape: (2, 2) ┌────────────┬─────────────────────────────────┐ │ subject_id ┆ time │ │ — ┆ — │ │ i64 ┆ list[datetime[μs]] │ ╞════════════╪═════════════════════════════════╡ │ 1 ┆ [1978-03-09 00:00:00, 2010-05-… │ │ 2 ┆ [1970-03-09 00:00:00, 1972-05-… │ └────────────┴─────────────────────────────────┘ windows_df.shape (2, 5) get_window_indexes( … timeseries_df, windows_df).select(“subject_id”, pl.col(“^.*_idx\(")).sort("subject_id") shape: (2, 5) ┌────────────┬───────────────┬─────────────┬────────────────┬──────────────┐ │ subject_id ┆ pre.start_idx ┆ pre.end_idx ┆ post.start_idx ┆ post.end_idx │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ list[u32] ┆ list[u32] ┆ list[u32] ┆ list[u32] │ ╞════════════╪═══════════════╪═════════════╪════════════════╪══════════════╡ │ 1 ┆ [0, 1] ┆ [1, 2] ┆ [0, 1] ┆ [1, 2] │ │ 2 ┆ [0] ┆ [1] ┆ [1] ┆ [3] │ └────────────┴───────────────┴─────────────┴────────────────┴──────────────┘ single_event_per_subject_window_df = (windows_df ... .explode(pl.exclude("subject_id")) ... .group_by("subject_id").first() ... .group_by("subject_id").agg(pl.all())) pprint.pprint({k: v.to_list() for k,v in single_event_per_subject_window_df ... .sort("subject_id").to_dict().items()}) {'post.end': [[datetime.datetime(2010, 5, 26, 2, 30, 56)], [datetime.datetime(1980, 5, 26, 4, 51, 52)]], 'post.start': [[datetime.datetime(1978, 3, 9, 0, 0)], [datetime.datetime(1971, 5, 26, 2, 30, 56)]], 'pre.end': [[datetime.datetime(2010, 5, 26, 2, 30, 56)], [datetime.datetime(1971, 5, 26, 4, 51, 52)]], 'pre.start': [[datetime.datetime(1978, 3, 9, 0, 0)], [datetime.datetime(1969, 5, 26, 2, 30, 56)]], 'subject_id': [1, 2]} get_window_indexes( ... timeseries_df, single_event_per_subject_window_df ... ).select("subject_id", pl.col("^.*_idx\)”)).sort(“subject_id”) shape: (2, 5) ┌────────────┬───────────────┬─────────────┬────────────────┬──────────────┐ │ subject_id ┆ pre.start_idx ┆ pre.end_idx ┆ post.start_idx ┆ post.end_idx │ │ — ┆ — ┆ — ┆ — ┆ — │ │ i64 ┆ list[u32] ┆ list[u32] ┆ list[u32] ┆ list[u32] │ ╞════════════╪═══════════════╪═════════════╪════════════════╪══════════════╡ │ 1 ┆ [0] ┆ [1] ┆ [0] ┆ [1] │ │ 2 ┆ [0] ┆ [1] ┆ [1] ┆ [3] │ └────────────┴───────────────┴─────────────┴────────────────┴──────────────┘
Source code in meds_torch/data/components/multiwindow_pytorch_dataset.py
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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 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 | |