Skip to main content

condition_procedure

Criteria on a patient's conditions and procedures (FHIR Condition, Procedure).

  • The code leaf (CodeCriterion): a condition or procedure (its resource) of a matching code or text is recorded for the patient, in its date window and for its eye.
  • The flat config fields conditions_inclusion, conditions_exclusion, procedures_inclusion and procedures_exclusion: code lists, with an optional time window for an exclusion, and a study-eye variant.

One module for both resources, because one leaf and one set of flat filters serve both.

Module​

Functions​

code_leaf_filter​

def code_leaf_filter(criterion: CodeCriterion, ctx: FilterBuildContext) ‑> MethodFilter:

Build a MethodFilter for a CodeCriterion criteria_tree leaf.

criterion.code may be a single glob-capable code, a CodeSpec (a code pinned to its own system), or a list mixing either shape — normalized via criterion.codes into one CodeSpec per code, each with its own resolved code_system. An entry matches if it matches any one spec's code and system (OR semantics, the same as code_system-less code lists elsewhere in this module) — so codes spanning more than one system are expressible in one leaf, unlike a single leaf-level code_system applied uniformly.

CodeCriterion has no value/dose field, so every code/date/ laterality-filtered candidate entry trivially qualifies (see _reduce_candidates_by_selector). "any" and "all" therefore both reduce to "at least one candidate exists," with nothing per-entry left to distinguish them. "latest"/"earliest" narrow further, to only the candidates with a resolvable date_field, then check that the single most/least recent one exists. CountSelector differs from all four, requiring its own min_count. Zero candidates is a confirmed fail once the source data was actually readable — an empty entry list or a real list with nothing matching the code/date/laterality filters both mean the code was checked for and not found, the same as a CountSelector shortfall. Only a genuinely absent data source (see Returns below) resolves unknown instead.

Each row reports the codes that decided it as CodeMatchEvidence. With a date_range, an entry matching the codes but carrying no readable date cannot qualify, and its code is reported under pending_date_review instead; the verdict is unchanged by it.

Arguments

  • criterion: The leaf to compile.
  • ctx: What the filter builders share. Its reference_date is "today", for resolving date_range.

Returns A MethodFilter degrading to unknown when the source *_codes_json column is absent from the row, or the row's cell is unreadable (via required_columns/iter_code_entries, the same missing-data convention every other filter uses) — genuinely not knowing, as opposed to having checked and found nothing.

code_list_filters​

def code_list_filters(    config: CriteriaMatchConfig, ctx: FilterBuildContext,) ‑> list[ColumnFilter | MethodFilter]:

Build the filters of the flat condition and procedure code lists.

Arguments

  • config: The criteria-matching config.
  • ctx: What the filter builders share.

Returns One filter for each of these fields that the config sets.

condition_end_unknown​

def condition_end_unknown(entry: Any) ‑> bool:

Whether a condition has no abatement date but is not known to be ongoing.

It is ongoing with an ongoing status (active, recurrence, relapse), or with no status from a source that records one: FHIR says to assume such a condition is still valid. Any other status (an ended one, or one that is not a FHIR code), or a blank status from a source that never records one (a NextGen billed diagnosis), leaves its end unknown.

Arguments

  • entry: A cached condition, as a dict or a Condition.

Returns False when the condition has an abatement date or is ongoing.

entry_matches_clinical_status​

def entry_matches_clinical_status(    entry: Any, allowed: frozenset[ClinicalStatusCriterion],) ‑> bool:

Whether a cached condition's status is one of the allowed statuses.

Arguments

  • entry: A cached condition, as a dict or a Condition.
  • allowed: The accepted FHIR clinical status codes; NO_STATUS_RECORDED accepts an entry with no recorded status.

Returns False for a status that is recorded but is not a FHIR code, and for a blank status from a source that never records one (an entry without records_clinical_status reads as one that does); else whether its code, or NO_STATUS_RECORDED for a blank status, is in allowed. A blank status with an abatement date reads as resolved: FHIR requires an abated condition's status to be inactive, resolved or remission (invariant con-4), so the condition has ended.

make_code_list_filter​

def make_code_list_filter(    *, column: str, codes: list[str], inclusion: bool,) ‑> Callable[[pd.Series[Any]], tuple[bool | None, str | None]]:

Build a MethodFilter-compatible callable matching EHR code lists.

The EHR-specific specialisation of collection membership: the cell holds a collection of code-bearing objects (e.g. Condition / Procedure), and matching reads a code_code attribute off each member rather than the member itself. codes are matched literally or as * glob wildcards.

Arguments

  • column: Name of the column holding the patient's code objects.
  • codes: Codes to match against; a single match is sufficient.
  • inclusion: If True build an inclusion filter (a match makes the patient eligible); if False build an exclusion filter (a match makes the patient ineligible).

Returns A callable taking a row and returning (eligible, context), where eligible is None when the patient's code data is absent (unknown).

make_exclusion_code_filter​

def make_exclusion_code_filter(    *,    column: str,    any_eye_codes: list[str] | None,    study_eye_codes: list[str] | None,    laterality_column: str,    lat_unknown_eligible: bool,    time_windows: Mapping[str, Mapping[str, int]] | None,    date_field: str,    laterality_targets: Callable[[Any], set[str] | None],    reference_date: date,) ‑> Callable[[pd.Series[Any]], MethodOutcome]:

Build an exclusion code filter matching the v8 laterality+recency logic.

A matching any-eye code (checked first, mutually exclusive with study-eye) disqualifies the patient unless a configured recency window excludes the event by date. Study-eye codes disqualify only when the scan laterality is known and the code's laterality includes the scan eye. Study-eye matches whose laterality is indeterminate are kept eligible per lat_unknown_eligible and flagged; windowed matches with no event date are always kept eligible and flagged.

Arguments

  • column: Column holding the patient's code entries.
  • any_eye_codes: Exclusion codes for either eye.
  • study_eye_codes: Exclusion codes for the study eye only.
  • laterality_column: Column holding the scan laterality.
  • lat_unknown_eligible: Eligibility when a study-eye code's laterality is indeterminate.
  • time_windows: Optional per-code recency windows.
  • date_field: Entry attribute/key holding the event date (onset_datetime for conditions, performed_datetime for procedures).
  • laterality_targets: Scope-appropriate laterality inference callable (condition_laterality_targets or procedure_laterality_targets).
  • reference_date: The date recency windows count back from, fixed for the run (see FilterBuildContext.reference_date).

Returns A MethodFilter-compatible callable returning a MethodOutcome whose code_match names the disqualifying code (or the codes awaiting laterality / event-date review).

make_inclusion_code_filter​

def make_inclusion_code_filter(    *,    column: str,    any_eye_codes: list[str] | None,    study_eye_codes: list[str] | None,    laterality_column: str,    lat_unknown_eligible: bool,    laterality_targets: Callable[[Any], set[str] | None],) ‑> Callable[[pd.Series[Any]], MethodOutcome]:

Build an inclusion code filter matching the v8 3-tier logic.

A patient is included if any any-eye code matches (checked first), or a study-eye code matches and the scan laterality is known and the code's inferred laterality includes the scan eye. When a study-eye code matches but its own laterality is indeterminate (scan laterality known), the verdict is lat_unknown_eligible. Study-eye codes are skipped entirely when scan laterality is unknown.

Arguments

  • column: Column holding the patient's code entries.
  • any_eye_codes: Codes qualifying for either eye.
  • study_eye_codes: Codes qualifying only for the study eye.
  • laterality_column: Column holding the scan laterality.
  • lat_unknown_eligible: Verdict when a study-eye code matches but its laterality is indeterminate.
  • laterality_targets: Scope-appropriate laterality inference callable (condition_laterality_targets or procedure_laterality_targets).

Returns A MethodFilter-compatible callable returning a MethodOutcome whose code_match names the qualifying code (or the codes awaiting laterality review).

Global variables​

  • ClinicalStatusCriterion - One value of a clinical_status list: a FHIR code or NO_STATUS_RECORDED.
  • NO_STATUS_RECORDED - The clinical_status value that matches a condition with no status recorded.

Classes​

CodeCriterion​

class CodeCriterion(**data: Any):

A condition or procedure, matched by code or text, presence/date/count.

Arguments

  • resource: Which resource code and text are matched against.
  • node: Discriminator identifying this as a code-type criteria_tree node.
  • code: As _BareCodeAddressedLeaf.code; omit it for a text-only criterion.
  • text: As _TextAddressedLeaf.text, searched across the entry's code_text and every codings[].display. A condition or procedure is not always coded — a NextGen problem recorded as free text carries a description and no code — so the name is then the only thing left to match on.
  • date_match: A condition only, and only with a date_range: which of the condition's dates the window tests. onset (the default): it started in the window. ended: its abatement date is in the window. active: the period from its onset to its abatement date overlaps the window; a condition with no abatement date that is ongoing runs to today, and one whose end is unknown (condition_end_unknown) is in effect only at its onset.
  • clinical_status: A condition only. The FHIR clinical statuses that a condition may have; no_status_recorded accepts a condition with no recorded status. A status that is recorded but maps to no FHIR code never matches. Narrows the candidates before selector. Not empty.

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 date_match : Literal['onset', 'ended', 'active']
  • static model_config
  • static node : Literal['code']
  • static resource : Literal['condition', 'procedure']

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.