EventsToTimeRange
EventsToTimeRange
Bases: DerivedTable
EventsToTimeRange converts individual code events into time ranges with start and end dates.
This derived table takes a codelist (e.g. medication prescriptions) and creates a time range for each event. The start date is the event date, and the end date is calculated by adding a specified number of days to the start date. Adjacent or overlapping periods are combined into single continuous periods.
This is particularly useful for identifying medication discontinuation when only prescription dates (not durations) are available. For example, discontinuation may be defined as a gap of ≥180 days between prescriptions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
domain
|
str
|
The source domain containing event data. |
required |
codelist
|
Optional[Codelist]
|
The codelist used to filter events. |
None
|
max_days
|
Optional[int]
|
Fixed integer number of days used to compute the end date. Used for every row
when |
None
|
days_columnname
|
Optional[str]
|
Name of a column in the source table whose integer value is used to
compute the end date for that row, allowing a different duration per row.
When the column value is null, |
None
|
operator
|
str
|
Comparison operator applied to the day count. Use |
'<='
|
gap_period
|
int
|
Additional days appended to the computed day count before deriving the end
date. For example, with |
0
|
exit_domain
|
Optional[str]
|
Name of a domain table containing events that should terminate a period
early, e.g. an observation that contradicts the state represented by
|
None
|
exit_codelist
|
Optional[Codelist]
|
Optional codelist used to filter |
None
|
name
|
Optional name for the derived table. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
domain |
The domain of events to process. |
|
codelist |
The codelist used for filtering events. |
|
max_days |
Fixed day count fallback. |
|
days_columnname |
Column name providing per-row day counts (when used). |
|
operator |
The comparison operator ( |
|
gap_period |
Additional days added to each day count before computing the end date. |
|
exit_domain |
Domain of events that end a period early. |
|
exit_codelist |
Codelist used to filter |
Examples:
Identifying medication discontinuation
from phenex.derived_tables import EventsToTimeRange
from phenex.phenotypes import TimeRangePhenotype
from phenex.codelists import Codelist
from phenex.filters.value import LessThanOrEqualTo
from phenex.filters import RelativeTimeRangeFilter
# Create a derived table for medication coverage periods
et_codelist = Codelist(["RX12345", "RX12346"])
derived_table = EventsToTimeRange(
name = 'ET_USAGE',
domain = 'DRUG_EXPOSURE',
codelist = et_codelist,
max_days = 180,
)
# Return the persons that discontinue post index
# EVENT_DATE column will be the date of discontinuation
# VALUE will be the number of days from index to discontinuation date
pt_et_discontinuation = TimeRangePhenotype(
domain = 'ET_USAGE',
relative_time_range = RelativeTimeRangeFilter(
when = 'after',
)
)
# Execute the derived table with your data
et_periods = derived_table.execute(tables)
Ending a state early on a contradictory observation
from phenex.derived_tables import EventsToTimeRange, LoadTable
# domain of abnormal LVEF observations (VALUE <= 35)
lvef_low = LoadTable(
name="LVEF_LOW",
table_name="LVEF_ALL_PATIENTS",
database=SNOWFLAKE_DEST_DATABASE,
function=aggregate_lvef_low,
)
# domain of normal LVEF observations (VALUE > 35), used only to end periods early
lvef_normal = LoadTable(
name="LVEF_NORMAL",
table_name="LVEF_ALL_PATIENTS",
database=SNOWFLAKE_DEST_DATABASE,
function=aggregate_lvef_normal,
)
lvef_as_time_ranges = EventsToTimeRange(
name="LVEF_TIME_RANGE",
domain="LVEF_LOW",
max_days=90,
exit_domain="LVEF_NORMAL",
)
Source code in phenex/derived_tables/events_to_time_range.py
15 16 17 18 19 20 21 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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 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 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 | |
dependencies
property
Recursively collect all dependencies of a node (including dependencies of dependencies).
Returns:
| Type | Description |
|---|---|
Set[Node]
|
List[Node]: A list of Node objects on which this Node depends. |
dependency_graph
property
execution_metadata
property
Retrieve the execution metadata rows for this node from phenex.db.
Returns:
| Type | Description |
|---|---|
|
pandas.DataFrame: One row per database the node ran against, or None if it has never been executed. Columns: NODE_NAME (its table name), NODE_HASH (fingerprint of the node's settings), EXECUTION_PARAMS (where it ran: connector type, source and destination database), EXECUTION_ID, EXECUTION_START_TIME, EXECUTION_END_TIME, EXECUTION_DURATION, NODE_SQL (the query that built its table). |
reverse_dependency_graph
property
table = None
instance-attribute
property
writable
This step's result table. After load(), the first read fetches it from the database and keeps it.
unique_name
property
The name of this node's table. A Cohort sets it to the phenotype's
place, e.g. OUTCOMES__BLEEDING__CHILD_1. Otherwise it is name.
attach_lazy_table(con, db_name)
Note where this step's saved table lives, without reading it.
The first read of table fetches it. Used by load().
Source code in phenex/node.py
clear_cache(con=None, recursive=False)
Clear the cached state for this node, forcing re-execution on the next call to execute().
This method removes the node's hash from the node states table and optionally drops the materialized table from the database. After calling this method, the node will be treated as if it has never been executed before.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
con
|
Optional[object]
|
Database connector. If provided, clears only runs with matching execution context and drops the materialized table. If None, clears all runs for the node. |
None
|
recursive
|
bool
|
If True, also clear the cache for all child nodes recursively. Defaults to False. |
False
|
Example
Source code in phenex/node.py
copy()
Return a deep copy of this node with _table_name_prefix cleared on all nodes.
delete_table(con, table_name_prefix=None)
Delete this node's materialized table from the destination database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
con
|
Database connector. |
required | |
table_name_prefix
|
Optional[str]
|
Optional prefix. If None, uses the prefix from the last execution. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the table was dropped, False if it didn't exist. |
Source code in phenex/node.py
execute(tables=None, con=None, overwrite=False, lazy_execution=False, n_threads=1, table_name_prefix=None)
Executes the Node computation for the current node and its dependencies.
Lazy Execution
When lazy_execution=True, nodes are only recomputed if changes are detected. The system tracks: 1. Node definition changes: Detected by hashing the node's parameters (from to_dict()) and class name 2. Execution environment changes: Detected by tracking source/destination database configurations
A node will be rerun if either: - The node's defining parameters have changed (different hash than last execution) - The database connector's source or destination databases have changed - The node has never been executed before
If no changes are detected, the node uses its cached result from the database instead of recomputing.
Requirements for lazy execution: - A database connector (con) must be provided to store and retrieve cached results - overwrite=True must be set to allow updating existing cached tables
State tracking is maintained in a local DuckDB database (__PHENEX_META__NODE_STATES table) that stores: - Node hashes, parameters, and execution metadata - Database connector configuration used during execution - Execution timing information
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tables
|
Dict[str, Table]
|
A dictionary mapping domains to Table objects. |
None
|
con
|
Optional[object]
|
Connection to database for materializing outputs. If provided, outputs from the node and all children nodes will be materialized (written) to the database using the connector. Required for lazy_execution. |
None
|
overwrite
|
bool
|
If True, will overwrite any existing tables found in the database while writing. If False, will throw an error when an existing table is found. Has no effect if con is not passed. Must be True when using lazy_execution. |
False
|
lazy_execution
|
bool
|
If True, only re-executes nodes when changes are detected in either the node definition or execution environment. Defaults to False. Requires con to be provided. |
False
|
n_threads
|
int
|
Max number of Node's to execute simultaneously when this node has multiple children. |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
Table |
Table
|
The resulting table for this node. Also accessible through self.table after calling self.execute(). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If lazy_execution=True but overwrite=False or con=None. |
Source code in phenex/node.py
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 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 | |
get_sql_filename()
Filesystem-safe .sql filename for this node's table.
<>:"/\|?* become _, plus a short hash when that changed the name so two
names that clean up alike never collide. Filenames longer than 250 characters
(including .sql) are truncated with the same hash suffix, staying below the
common 255-character per-filename filesystem limit. Only the filename changes,
not the SQL.
Source code in phenex/node.py
get_table_name(table_name_prefix=None)
Get the table name used in the destination database for this node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table_name_prefix
|
Optional[str]
|
Optional prefix. If None, uses the prefix from the last execution. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The table name in the destination database. |
Source code in phenex/node.py
to_dict()
Return a dictionary representation of the Node. The dictionary must contain all dependencies of the Node such that if anything in self.to_dict() changes, the Node must be recomputed.
to_sql(sql_dir='./sql', connector=None)
Return the SQL that produces this node's table, read-only (execute() writes it).
Returns the first source available, in order: the in-memory expression (this
session), the saved {sql_dir}/{name}.sql file, the phenex.db cache, or a
recompile from dependency tables. Pass connector to pin the dialect.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If required upstream tables are missing, call |
Source code in phenex/node.py
visualize_dependencies()
Create a text visualization of the dependency graph for this node and its dependencies.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A text representation of the dependency graph |