TimeRangePhenotype
Bases: Phenotype
As the name implies, TimeRangePhenotype is designed for working with time ranges. If the input data has a start and an end date, use TimeRangePhenotype to identify other events (or patients) that occur within this time range. The most common use case of this is working with 'health insurance coverage' data i.e. on 'OBSERVATION_PERIOD' table. These tables have one or many rows per patient with the start of coverage and end of coverage i.e. domains compatible with TimeRangePhenotype require a START_DATE and an END_DATE column. At it's simplest, TimeRangePhenotype identifies patients who have their INDEX_DATE (or other anchor date of interest) within this time range. Additionally, a minimum or maximum number of days from the anchor date to the beginning/end of the time range can be defined. The returned Phenotype has the following interpretation:
DATE: If relative_time_range.when='before', then DATE is the beginning of the coverage period containing the anchor phenotype. If relative_time_range.when='after', then DATE is the end of the coverage period containing the anchor date. VALUE: Coverage (in days) relative to the anchor date. By convention, always non-negative.
There are two primary use cases for TimeRangePhenotype
- Identify patients with some minimum duration of coverage prior to anchor_phenotype date e.g. "identify patients with 1 year of continuous coverage prior to index date"
- Determine the date of loss to followup (right censoring) i.e. the duration of coverage after the anchor_phenotype event
Data for TimeRangePhenotype
This phenotype requires a table with PersonID and a coverage start date and end date. Depending on the datasource used, this information is a separate ObservationPeriod table or found in the PersonTable. Use an PhenexObservationPeriodTable to map required coverage start and end date columns. For tables with overlapping time ranges, use the CombineOverlappingPeriods derived table to combine time ranges into a single time range.
| PersonID | startDate | endDate |
|---|---|---|
| 1 | 2009-01-01 | 2010-01-01 |
| 2 | 2008-01-01 | 2010-01-02 |
One assumption that is made by TimeRangePhenotype is that there are NO overlapping coverage periods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
Optional[str]
|
The name of the phenotype. |
'TIME_RANGE'
|
domain
|
Optional[str]
|
The domain of the phenotype. Default is 'observation_period'. |
'OBSERVATION_PERIOD'
|
date_range
|
Optional[DateFilter]
|
A DateFilter to apply. min_date clips START_DATE (periods starting before min_date are trimmed to min_date); max_date clips END_DATE (periods ending after max_date are trimmed to max_date). Periods entirely outside the range are excluded. VALUE is then computed on the clipped period. |
None
|
relative_time_range
|
Optional[RelativeTimeRangeFilter]
|
Filter returned persons based on the duration of coverage in days. The relative_time_range.anchor_phenotype defines the reference date with respect to calculate coverage. In typical applications, the anchor phenotype will be the entry criterion. The relative_time_range.when 'before', 'after'. If before, the return date is the start of the coverage period containing the anchor_phenotype. If after, the return date is the end of the coverage period containing the anchor_phenotype. |
None
|
allow_null_end_date
|
bool
|
TimeRangePhenotype checks that anchor date is within the time range of interest. This requires that the start date is not null, and the end date is either null or after the anchor date. If you want to require that the end date is not null, set allow_null_end_date to False. |
True
|
Example:
# make sure to create an entry phenotype, for example 'atrial fibrillation diagnosis'
entry_phenotype = CodelistPhenotype(...)
# one year continuous coverage prior to index
one_year_coverage = TimeRangePhenotype(
relative_time_range = RelativeTimeRangeFilter(
min_days=GreaterThanOrEqualTo(365),
anchor_phenotype = entry_phenotype,
when = 'before',
),
)
# determine the date of loss to followup
loss_to_followup = TimeRangePhenotype(
relative_time_range = RelativeTimeRangeFilter(
anchor_phenotype = entry_phenotype
when = 'after',
)
)
# determine the date when a drug was discontinued
drug_discontinuation = TimeRangePhenotype(
relative_time_range = RelativeTimeRangeFilter(
anchor_phenotype = entry_phenotype
when = 'after',
)
)
Source code in phenex/phenotypes/time_range_phenotype.py
11 12 13 14 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 | |
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). |
namespaced_table
property
A PhenotypeTable has generic column names 'person_id', 'boolean', 'event_date', and 'value'. The namespaced_table prepends the phenotype name to all of these columns. This is useful when joining multiple phenotype tables together.
Returns:
| Name | Type | Description |
|---|---|---|
table |
Table
|
The namespaced table for the current phenotype. |
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_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 |