relative_time_helpers — Helpers for Relative Time Operations

Helper classes and functions for working with relative time dimensions and sequences.

Constants

class xplain.relative_time_helpers.TimeUnit

Time unit constants for relative time calculations and duration expressions.

Available Units:

NANOSECOND = "NANOSECOND"
MILLISECOND = "MILLISECOND"
SECOND = "SECOND"
MINUTE = "MINUTE"
HOUR = "HOUR"
DAY = "DAY"
WEEK = "WEEK"
MONTH = "MONTH"
QUARTER = "QUARTER"
HALFYEAR = "HALFYEAR"
YEAR = "YEAR"
DECADE = "DECADE"
CENTURY = "CENTURY"

Example:

from xplain.relative_time_helpers import TimeUnit

# Use in relative time calculations
client.calculate_time_since(
    event_dimension=("Prescriptions", "Date"),
    reference=("Diagnoses", "DiagDate"),
    unit=TimeUnit.DAY,
)
class xplain.relative_time_helpers.RelativeTimeType

Reference event selection type constants for relative time dimensions.

Available Types:

TO_FIRST = "TO_FIRST"

Time relative to the first matching reference event. Common use: “days since first diagnosis”.

TO_LAST = "TO_LAST"

Time relative to the last matching reference event. Common use: “days since last hospitalization”.

TO_NEAREST = "TO_NEAREST"

Time relative to the nearest reference event (either direction). Common use: “days to nearest treatment”.

TO_NEXT = "TO_NEXT"

Time relative to the next (future) reference event. Common use: “days until next appointment”.

TO_PREVIOUS = "TO_PREVIOUS"

Time relative to the previous (past) reference event. Common use: “days since previous visit”.

Example:

from xplain.relative_time_helpers import RelativeTimeType

# Days since first diagnosis
client.add_relative_time_dimensions(
    ...,
    relative_time_type=RelativeTimeType.TO_FIRST,
)

# Or use string shorthand in convenience method
client.calculate_time_since(
    ...,
    since="first",
)
class xplain.relative_time_helpers.FixExplicitSelections

Selection fixing behavior constants for relative time dimensions.

Available Options:

NONE = "none"

Keep selections as-is. Resulting dimension may have floating semantics if selections refer to dimensions with floating semantics.

ALL = "all"

Fix all semantics recursively. All floating references are replaced with their fixed counterparts.

ONLY_PROPAGATE_UPWARD = "only_propagate_upward"

Only fix propagate upward dimensions. Non-recursive fix.

Example:

from xplain.relative_time_helpers import FixExplicitSelections

client.add_relative_time_dimensions(
    ...,
    fix_explicit_selections=FixExplicitSelections.ALL,
)

Functions

xplain.relative_time_helpers.normalize_element_path(path)

Normalize a dimension path to the standard dict format.

Accepts:
  • Dict: {“object”: “Prescriptions”, “dimension”: “Date”}

  • Tuple: (“Prescriptions”, “Date”)

  • String: “Prescriptions.Date” (splits on first dot)

Returns

{“object”: “…”, “dimension”: “…”}

Return type

  • Dict

Raises

- ValueError if format is invalid

Parameters

path (Union[Dict, Tuple, str]) –

Normalize a dimension path to the standard dict format.

Accepts dimension paths in multiple formats and returns a consistent dict format with “object” and “dimension” keys.

Supported Formats:

  • Dict: {"object": "Prescriptions", "dimension": "Date"}

  • Tuple: ("Prescriptions", "Date")

  • String: "Prescriptions.Date"

Example:

from xplain.relative_time_helpers import normalize_element_path

# All these produce the same result
normalize_element_path({"object": "Prescriptions", "dimension": "Date"})
normalize_element_path(("Prescriptions", "Date"))
normalize_element_path("Prescriptions.Date")
# Returns: {"object": "Prescriptions", "dimension": "Date"}
Parameters

path (dict | tuple | str) – Dimension path in dict, tuple, or string format

Returns

Normalized dict with “object” and “dimension” keys

Return type

dict

Raises

ValueError – If path format is invalid

xplain.relative_time_helpers.normalize_element_paths(paths)

Normalize a list of dimension paths.

Normalize a list of dimension paths.

Applies normalize_element_path() to each path in a list.

Example:

from xplain.relative_time_helpers import normalize_element_paths

paths = [
    ("Prescriptions", "Date"),
    "Diagnoses.DiagDate",
    {"object": "Hospitalizations", "dimension": "DateFrom"},
]
normalized = normalize_element_paths(paths)
# All paths converted to dict format
Parameters

paths (list[dict | tuple | str] | None) – List of dimension paths

Returns

List of normalized dicts, or None if input is None

Return type

list[dict] | None

Raises

ValueError – If any path format is invalid

xplain.relative_time_helpers.validate_relative_time_params(time_dimensions, names, relative_time_type=None, time_unit=None)

Validate common parameter combinations for add_relative_time_dimensions.

Raises

- ValueError if validation fails

Parameters
  • time_dimensions (List) –

  • names (List[str]) –

  • relative_time_type (str) –

  • time_unit (str) –

Return type

None

Validate parameter combinations for add_relative_time_dimensions().

Checks: - Cardinality: number of names matches number of time_dimensions - Enum values: relative_time_type and time_unit are valid values

Example:

from xplain.relative_time_helpers import validate_relative_time_params

# Validates before sending to server
try:
    validate_relative_time_params(
        time_dimensions=[dim1, dim2],
        names=["OnlyOne"],  # Cardinality mismatch!
        relative_time_type="TO_FIRST",
        time_unit="DAY",
    )
except ValueError as e:
    print(e)  # "names cardinality mismatch..."
Parameters
  • time_dimensions (list | None) – List of dimension paths

  • names (list[str] | None) – List of dimension names

  • relative_time_type (str | None) – Reference type (TO_FIRST, TO_LAST, etc.)

  • time_unit (str | None) – Time unit (DAY, MONTH, YEAR, etc.)

Raises

ValueError – If validation fails

Return type

None

xplain.relative_time_helpers.validate_build_sorted_sequence_params(ranks=None, names=None, dimensions_to_replicate=None)

Validate parameter combinations for build_sorted_sequence.

Raises

- ValueError if validation fails

Parameters
  • ranks (List[int]) –

  • names (List[List[str]]) –

  • dimensions_to_replicate (List) –

Return type

None

Validate parameter combinations for build_sorted_sequence().

Checks: - Outer cardinality: names and dimensions_to_replicate have same length - Inner cardinality: each names sublist matches ranks length

Example:

from xplain.relative_time_helpers import validate_build_sorted_sequence_params

try:
    validate_build_sorted_sequence_params(
        ranks=[1, 2, 3],
        names=[["Name1", "Name2"]],  # 1 sub-list but 3 names needed
        dimensions_to_replicate=[dim1],
    )
except ValueError as e:
    print(e)  # "names[0] cardinality mismatch..."
Parameters
  • ranks (list[int] | None) – List of rank numbers

  • names (list[list[str]] | None) – List of name lists (one per dimension_to_replicate)

  • dimensions_to_replicate (list | None) – List of dimension paths

Raises

ValueError – If validation fails

Return type

None

Usage Examples

Using constants for IDE autocomplete:

from xplain.relative_time_helpers import TimeUnit, RelativeTimeType

# IDE autocomplete guides valid values
client.calculate_time_since(
    event_dimension=("Prescriptions", "Date"),
    reference=("Diagnoses", "DiagDate"),
    name="DaysSinceDiag",
    since=RelativeTimeType.TO_FIRST,  # Autocomplete!
    unit=TimeUnit.DAY,                # Autocomplete!
)

Path normalization:

from xplain.relative_time_helpers import normalize_element_path

# Accept any format, normalize internally
dict_format = {"object": "Prescriptions", "dimension": "Date"}
tuple_format = ("Prescriptions", "Date")
string_format = "Prescriptions.Date"

assert normalize_element_path(dict_format) == \
       normalize_element_path(tuple_format) == \
       normalize_element_path(string_format)

Early validation:

from xplain.relative_time_helpers import validate_relative_time_params

# Validate before sending to server
try:
    validate_relative_time_params(
        time_dimensions=[dim1, dim2],
        names=["OnlyOne"],
        time_unit="INVALID",
    )
except ValueError as e:
    print(e)
    # Immediately shows both issues:
    # - names cardinality mismatch
    # - invalid time_unit value

See Also