appointment
Criteria on a patient's appointments and encounters (FHIR Appointment, Encounter).
- The
appointmentleaf (AppointmentWindowCriterion): at least one, or at leastcount, appointments or encounters in a date window, in total or in every period of it. Its findings are the records that meet the bound. - The flat config fields
appointment_history(AppointmentHistoryCriterion) andcurrent_patient_months.
The records are read from the "Previous Appointments Info" and "Previous
Encounters Info" columns. A fail drawn from history that was not fully
fetched, or not fully readable, is unknown.
Module
Functions
appointment_filters
def appointment_filters( config: CriteriaMatchConfig, ctx: FilterBuildContext,) ‑> list[ColumnFilter | MethodFilter]:Build the appointment-history filters.
Arguments
config: The criteria-matching config.ctx: What the filter builders share.
Returns One filter for each of these fields that the config sets.
appointment_history_filter
def appointment_history_filter( row: pd.Series[Any], *, years_of_history: int, min_appointments_per_year: int, today: date, appointments_col: str = 'Previous Appointments Info', encounters_col: str = 'Previous Encounters Info',) ‑> tuple[bool | None, str | None]:Check the patient's appointment history spans the required window.
UNKNOWN (None) when neither appointment column holds a list — the history
was never fetched, so there is nothing to judge. FAILs when the history is
present but no appointment falls on or before the years_of_history
cutoff; otherwise defers to check_min_appointments_per_year over the dates
from the cutoff onward.
A FAIL drawn from an incomplete history — only one source column fetched, or
a record that could not be read — is reported as UNKNOWN instead, since the
missing records could have satisfied the criterion. See
_resolve_appointment_verdict.
Arguments
row: The patient row (appointment/encounter columns read viacombine_appointment_dates).years_of_history: Required length of history, in years.min_appointments_per_year: Minimum appointments required per year of the window.today: Reference "now".appointments_col: Column holding the previous-appointments records.encounters_col: Column holding the previous-encounters records.
Returns
(eligible, reason) — eligible is None for UNKNOWN, and reason
names the failure when ineligible.
appointment_leaf_filter
def appointment_leaf_filter( criterion: AppointmentWindowCriterion, ctx: FilterBuildContext,) ‑> MethodFilter:Build a MethodFilter for an AppointmentWindowCriterion criteria_tree leaf.
Reuses the flat appointment_history/current_patient_months fields'
UNKNOWN/incomplete-history handling exactly (see
_resolve_appointment_verdict): a FAIL drawn from history that was
never fetched, or only partly read, downgrades to UNKNOWN instead.
date_range is resolved once via _code_date_bounds, the same as
every other leaf's date_range. A bucketed bounds.period anchors at
date_range's resolved end, or reference_date when that's unset.
Arguments
criterion: The leaf to compile.ctx: What the filter builders share. Itsreference_dateis "today": used to resolvedate_range, and as the bucket anchor for a bucketedboundswhendate_range.endis unset.
Returns
A MethodFilter reporting unknown when no appointment data was
fetched, or when a FAIL verdict was drawn from incomplete history.
check_min_appointments_per_period
def check_min_appointments_per_period( appointment_dates: list[date], min_date: date, anchor_date: date, period: "Literal['d', 'w', 'm', 'y']", min_count: int,) ‑> bool:Check every whole period-bucket of [min_date, anchor_date] meets min_count.
Generalizes check_min_appointments_per_year from a hardcoded "whole
years back from today" to day/week/month/year, anchored at any date
(not only date.today()), over a window of any length (not only a
whole number of years).
Buckets are anchored at anchor_date, walking backward: bucket 0 is
the most recent whole period ending at anchor_date, bucket 1 the
one before it, and so on. The number of required buckets is
_periods_ago(anchor_date, min_date, period) — the whole periods that
fit between min_date and anchor_date, computed with the same
arithmetic used to bucket each date, so the two can never disagree by
one. A window whose length is not an exact multiple of period (e.g. a
30-month window bucketed by year) has a partial leftover bucket nearest
min_date; dates falling there (or further back) are excluded from
every count — the partial bucket is never itself required to meet
min_count. Future-dated appointments (after anchor_date) are
excluded outright, the same as check_min_appointments_per_year always
excluded appointments after today.
Reproduces check_min_appointments_per_year's exact trailing behavior
as the special case period="y", min_date=today - relativedelta( years=years_of_history), anchor_date=today.
Arguments
appointment_dates: Candidate appointment/encounter dates (any history; dates outside the required buckets, or afteranchor_date, are ignored).min_date: The window's start. Together withanchor_date, this date's own "periods ago" value is the number of buckets checked.anchor_date: The window's end, and the point buckets are counted back from.period: The bucket granularity.min_count: The minimum required in every whole bucket.
Returns
True only when every whole bucket in the window holds at least
min_count. Vacuously True when the window contains no whole
bucket at all (min_date no further than one period before
anchor_date) — callers with a business rule against a vacuous
window (see appointment_leaf_filter) must guard for that
themselves; this function stays a pure bucket-counting primitive.
check_min_appointments_per_year
def check_min_appointments_per_year( appointment_dates_within_history: list[date], years_of_history: int, min_appointments_per_year: int, today: date,) ‑> bool:Check every year of the history window meets the per-year minimum.
Buckets each date by whole years-ago from today and requires each year in
range(years_of_history) (the trailing years_of_history years) to hold at
least min_appointments_per_year appointments. Future-dated appointments are
excluded. A thin wrapper over check_min_appointments_per_period (kept as
its own function since it's imported directly by existing callers/tests).
Arguments
appointment_dates_within_history: Candidate appointment/encounter dates.years_of_history: Number of trailing years, each of which must meet the minimum.min_appointments_per_year: Minimum appointments required in every such year.today: Reference "now".
Returns
True only when every year in the window meets the minimum.
combine_appointment_dates
def combine_appointment_dates( row: pd.Series[Any], prev_appointments_col: str = 'Previous Appointments Info', prev_encounters_col: str = 'Previous Encounters Info',) ‑> list[date]:Combine appointment and encounter dates from EHR data in a row.
Arguments
row: The patient row.prev_appointments_col: Column holding the previous-appointments JSON records.prev_encounters_col: Column holding the previous-encounters JSON records.
Returns The merged appointment + encounter dates, ascending; empty when both columns are absent/empty.
Extracted from
BaseGATrialInclusionWorkerAlgorithmSingleEye._combine_appointment_dates.
convert_appointment_dates
def convert_appointment_dates( list_appt_enct: list[Mapping[str, str]],) ‑> list[datetime.date]:Convert appointment JSON records to a sorted list of dates.
Date strings are parsed with datetime.fromisoformat, which handles
both "YYYY-MM-DDTHH:MM:SS" and sub-second variants such as
"YYYY-MM-DDTHH:MM:SS.fff" that are common in EHR exports. Records that
cannot be read at all are skipped with a warning; use
_convert_appointment_dates_lossy where that distinction matters.
Arguments
list_appt_enct: Appointment/encounter JSON records, each an{"Appointment Date": "<iso datetime>", ...}mapping. A record with no/empty"Appointment Date"is skipped.
Returns The parsed dates, ascending; empty when no record carries a date.
Extracted from
BaseGATrialInclusionWorkerAlgorithmSingleEye._convert_appointment_dates.
current_patient_filter
def current_patient_filter( row: pd.Series[Any], *, months_threshold: int, today: date, appointments_col: str = 'Previous Appointments Info', encounters_col: str = 'Previous Encounters Info',) ‑> tuple[bool | None, str | None]:Check the patient has an appointment within the last months_threshold.
UNKNOWN (None) when neither appointment column holds a list — the history
was never fetched, so there is nothing to judge — and also when the history
on hand is incomplete and does not show a qualifying appointment, since a
missing record could have been the recent one. See
_resolve_appointment_verdict.
Arguments
row: The patient row (appointment/encounter columns read viacombine_appointment_dates).months_threshold: Recency window in months; an appointment on or aftertoday - months_thresholdqualifies.today: Reference "now".appointments_col: Column holding the previous-appointments records.encounters_col: Column holding the previous-encounters records.
Returns
(is_current, reason) — is_current is None for UNKNOWN, True when
any appointment falls in the window, and False when there is none.
make_appointment_history_filter
def make_appointment_history_filter( *, years: int, min_per_year: int, today: date, appointments_col: str, encounters_col: str,) ‑> Callable[[pd.Series[Any]], tuple[bool | None, str | None]]:Build the appointment-history filter with its bounds and date bound in.
today is fixed at build time rather than read per row so every patient in
a run is judged against the same reference date, including a run that
straddles midnight.
Arguments
years: Required length of history, in years.min_per_year: Minimum appointments required in each year of the window.today: Reference "now" for the whole run.appointments_col: Column holding the previous-appointments records.encounters_col: Column holding the previous-encounters records.
Returns
A row predicate returning (state, context) where state is
True/False/None (PASS/FAIL/UNKNOWN).
make_current_patient_filter
def make_current_patient_filter( *, months: int, today: date, appointments_col: str, encounters_col: str,) ‑> Callable[[pd.Series[Any]], tuple[bool | None, str | None]]:Build the current-patient filter with its window and date bound in.
today is fixed at build time rather than read per row so every patient in
a run is judged against the same reference date.
Arguments
months: Recency window in months.today: Reference "now" for the whole run.appointments_col: Column holding the previous-appointments records.encounters_col: Column holding the previous-encounters records.
Returns
A row predicate returning (state, context) where state is
True/False/None (PASS/FAIL/UNKNOWN).
Classes
AppointmentCountBound
class AppointmentCountBound(**data: Any):A minimum-count requirement on an AppointmentWindowCriterion's entries.
Arguments
count: The minimum number of qualifying appointments/encounters required. Withperiodunset, this is a plain total over the wholedate_rangewindow. Withperiodset, this is the minimum required in every whole bucket of that period within the window (seeAppointmentWindowCriterion.minimum's own docstring for exactly how buckets are aligned and counted).period: The bucket granularitycountis measured over —"d"/"w"/"m"/"y"(day/week/month/year) — orNonefor a plain total across the whole window, not bucketed at all.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
Variables
- static
count : int
- static
model_config
- static
period : Literal['d', 'w', 'm', 'y'] | None
AppointmentHistoryCriterion
class AppointmentHistoryCriterion(**data: Any):The compound appointment-history criterion.
A patient qualifies when their appointment/encounter history spans at least
years years and every one of those years holds at least
min_per_year appointments. The two bounds are one criterion, not two:
a length with no density, or a density with no length, does not describe
anything checkable, so a half-specified criterion is rejected.
Both fields None means the criterion is not configured. That spelling is
load-bearing: a task template renders this mapping unconditionally, so two
blank modeller variables arrive here as {years: None, min_per_year: None}
rather than as an absent key.
Arguments
years: Required length of history, in years.min_per_year: Minimum appointments required in each year of the window.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
Variables
- static
min_per_year : int | None
- static
model_config
- static
years : int | None
is_configured : bool- Whether both bounds are set, so a filter should be emitted.
AppointmentWindowCriterion
class AppointmentWindowCriterion(**data: Any):A patient's appointment/encounter history: presence, count, or density.
Reads the combined appointment+encounter history
(PREV_APPOINTMENTS_COL/PREV_ENCOUNTERS_COL). A FAIL drawn from
history that was never fetched, or only partly read, reports UNKNOWN
instead — the missing records could have satisfied the criterion.
Arguments
-
node: Discriminator identifying this as anappointment-typecriteria_treenode. -
date_range: The window appointments/encounters are counted within. -
Required: a window-less appointment criterion has nothing to count over. -
bounds: The requirement placed on entries falling withindate_range: -
None(default) — a bare presence check: at least one appointment/encounter falls withindate_range. -
AppointmentCountBound(count=N, period=None)— at leastNappointments/encounters across the wholedate_rangewindow, not bucketed. -
AppointmentCountBound(count=N, period="y"/"m"/"w"/"d")— every whole bucket of that period withindate_rangemust hold at leastNentries. Buckets are anchored atdate_range's own resolved end when set, else the match run's reference date ("today").
A bucketed bounds requires date_range.start to resolve to a concrete date — an open-ended date_range (no start) is only valid with bounds=None or bounds.period is None.
on_no_match: The state when the history was read in full and no appointment/encounter falls withindate_range."fail"(the default) or"unknown". Some appointments in the window that fall short ofboundsstill fail.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
Variables
- static
bounds : AppointmentCountBound | None
- static
date_range : DateWindow
- static
model_config
- static
node : Literal['appointment']
- static
on_no_match : Literal['fail', 'unknown']
Methods
model_post_init
def model_post_init(self: BaseModel, context: Any, /) ‑> None:This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that's what pydantic-core passes when calling it.
Arguments
self: The BaseModel instance.context: The context.