Skip to main content

codes

Matching that every code-addressed criteria_tree leaf shares.

A code-addressed leaf (code, observation, medication, allergy, device) finds the EHR entries whose code or text matches it, in its date window and for its eye, and keeps the ones its selector picks. This module has the parts those leaves share:

  • the base classes and models of the leaves: _BareCodeAddressedLeaf and its subclasses, CodeSpec, CodeLaterality, CountSelector, DateWindow, RelativeDate;
  • glob and text matching, and reading the entries and codings of a cell;
  • RowCodeIndex, the code entries of one row, read once for all its leaves;
  • event dates, date windows and the searched window (_checked_window);
  • laterality, matchers and selectors;
  • the evidence of a leaf (CodeMatchEvidence) and the findings made from it.

It imports core only, of the criteria-matching modules.

Module​

Functions​

entry_codings​

def entry_codings(entry: Any) ‑> list[tuple[str | None, str | None]]:

Every (code, system) pair on entry's own code.

Reads entry.codings (see Coding's docstring) when present and non-empty. Falls back to the single flattened (code_code, code_system) pair when codings is absent or empty: a resource with only one coding to begin with, or a row cached before this field existed.

system is resolved the same way a criterion's own code_system is (see _resolve_code_system): defence in depth against a querier that ever emits a short form directly, on an entry a caller never round-trips through a validated model.

iter_code_entries​

def iter_code_entries(cell: Any, column: str | None = None) ‑> list[typing.Any] | None:

Normalize a code cell to a list of entries, or None if absent/unreadable.

A scalar NaN/None (a patient with no matching EHR row) and an uninterpretable non-list scalar both return None (unknown); a genuine list/tuple/set/array or single dict returns a concrete list. The two None cases are distinguished for observability: absent data is silent, but a present-yet-uninterpretable cell logs a warning (it usually signals an upstream schema mismatch, not a genuinely code-less patient).

Arguments

  • cell: The raw code-column cell for one row.
  • column: The column name, used only to name the source in the unexpected-cell warning.

Returns The normalized entry list, or None (unknown) for absent/unreadable data.

matches_literal_or_regex​

def matches_literal_or_regex(    *, code: str | None, literal_codes: set[str], regex_pattern: re.Pattern[str] | None,) ‑> bool:

Return whether code matches configured literals or regex.

Extracted from CodeFilterMixIn._matches_literal_or_regex. Uses fullmatch (not v8's prefix match): a glob such as "E11*" must match the whole code, so "E11" does not spuriously match "E110". This is a deliberate tightening over v8 — for the trailing-* globs configs use in practice the two are equivalent, and it only diverges on the (unusual) mid-string wildcard, where full-string matching is the safer reading.

reset_unparseable_date_warnings​

def reset_unparseable_date_warnings() ‑> None:

Clear the warn-once-per-field state kept by _coerce_event_datetime.

Call once at the start of a criteria_matching_task run so an unparseable date format already warned about on a previous run is still reported, rather than silenced forever within a long-lived process.

split_literal_and_regex_patterns​

def split_literal_and_regex_patterns(    list_of_codes: list[str] | None,) ‑> tuple[set[str], re.Pattern[str] | None]:

Split wildcard code config into a literal set and a compiled regex.

Only * is treated as a wildcard (glob-style); all other characters, including ? and [, are matched literally.

Extracted from CodeFilterMixIn._split_literal_and_regex_codes.

Global variables​

  • OnNoMatch - The state of a leaf whose records were read and none matched.

Classes​

CodeLaterality​

class CodeLaterality(**data: Any):

Scopes a code-addressed leaf's match to one side, and how to treat unknowns.

Arguments

  • side: Which side of a paired structure, relative to the row's own SubjectIdentity.laterality — "index" (the study side), "contralateral" (the opposite side), or "either" (no filtering; the default).
  • is_unknown_ehr_resource_laterality_eligible: Whether an entry qualifies against side when its own recorded side cannot be inferred — as opposed to the row's own scan laterality being unresolved, which fail_on_unknown_scan_laterality governs instead (see "Matching laterality" in the design notes). False (the default) means such an entry does not qualify, the conservative choice.
  • fail_on_unknown_scan_laterality: The verdict for the whole leaf when the row's own scan laterality cannot be resolved at all, so side cannot be evaluated against anything. False (the default) resolves to unknown, genuinely not knowing; True resolves to a definite fail instead, letting a sibling any-eye leaf in an OrGroup decide the group's outcome rather than the unresolved side dragging the whole group to unknown. Both flags are only valid when side is not "either" — with "either" neither the entry-level nor the scan-level unresolved case can ever arise.

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 fail_on_unknown_scan_laterality : bool
  • static is_unknown_ehr_resource_laterality_eligible : bool
  • static model_config
  • static side : Literal['index', 'contralateral', 'either']

CodeSpec​

class CodeSpec(**data: Any):

One glob-capable code, optionally pinned to its own code system.

Lets a _CodeAddressedLeaf's code list mix codes from more than one system — e.g. an ICD-10 code alongside a SNOMED one — which a single leaf-level code_system shared across every code cannot express.

Arguments

  • code: The code to match, glob-capable (e.g. "E11*").
  • code_system: This code's own system (e.g. "icd10", "snomed"), or None to fall back to the leaf's own code_system default (see _CodeAddressedLeaf.codes). A short form is resolved to its canonical URI (see _resolve_code_system).

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 code : str
  • static code_system : str | None
  • static model_config

ColumnCodeIndex​

class ColumnCodeIndex(entries: list[Any]):

The entries of one code column of a row, and the codings they carry.

The codings are read when a leaf first matches on them, then kept for the other leaves that read the column.

Arguments

  • entries: The entries of the column, as iter_code_entries reads them. Shared by every leaf that reads the column, so read-only.

Variables​

  • entries : None

Methods​


matching​

def matching(self, matcher: _CodeDateMatcher) ‑> list[typing.Any]:

The entries that matcher matches by code.

Tests each distinct coding of the column once, rather than each coding of each entry: an entry matches when one of its codings passes matcher.coding_matches, as matcher.entry_matches_code decides it.

Arguments

  • matcher: A leaf's compiled matcher.

Returns The entries that matcher.entry_matches_code passes, in their order, as a new list.

CountSelector​

class CountSelector(**data: Any):

Reduce candidate entries by requiring at least min_count of them.

Arguments

  • min_count: The minimum number of qualifying entries required.

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_count : int
  • static mode : Literal['count']
  • static model_config

DateWindow​

class DateWindow(**data: Any):

A window a matching event's date must fall within.

Each bound is independent and optional: a literal date pins it exactly; a RelativeDate pins it relative to the task's own reference date at match time (see _code_date_bounds); None leaves that side open (start unset means all history; end unset means no upper bound). Named after FHIR's own Period datatype (start/end), which this plays the same role for.

Each of start/end can independently be absolute or relative, so e.g. "between 2 years ago and 6 months ago", or "more than 4 weeks ago" (end a RelativeDate, start left as all history), are both expressible.

Arguments

  • start: The window's start.
  • end: The window's end.

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 model_config

RelativeDate​

class RelativeDate(**data: Any):

A date expressed relative to another instant — this many units before/after it.

Arguments

  • unit: The unit time is measured in.
  • time: How many of unit. Must be positive.
  • direction: Which way this points relative to the instant it's resolved against — "past" (before it) or "future" (after it). Defaults to "past".

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 direction : Literal['past', 'future']
  • static model_config
  • static time : int
  • static unit : Literal['d', 'w', 'm', 'y']

RowCodeIndex​

class RowCodeIndex(row: pd.Series[Any]):

The code entries of one row, read once for every leaf that matches on them.

A tree can hold dozens of code-addressed leaves, and each reads the same few columns of the same row. Each column is read, and its codings indexed (ColumnCodeIndex), when a leaf first asks for it; the other leaves reuse it. build_criterion_outcomes makes one for each row and drops it once the row is evaluated, so nothing is kept from one patient to the next.

Arguments

  • row: The row whose entries this reads.

Variables​

  • row : None

Static methods​


of​

def of(row: pd.Series[Any], index: RowCodeIndex | None):

Get index if it reads row, else a new index of row.

Arguments

  • row: The row being evaluated.
  • index: The index shared by the leaves evaluating row, or None when a leaf is evaluated on its own.

Returns An index of row.

Methods​


column​

def column(    self, column: str,) ‑> ColumnCodeIndex | None:

Get the entries of column, read once for the row.

Arguments

  • column: The code column.

Returns The column's entries, or None when the cell is absent or unreadable (see iter_code_entries). That is read again on each call, so each leaf logs an unreadable cell as it always has.

UnitBound​

class UnitBound(**data: Any):

The unit a valueQuantity entry's own unit must equal, or lack.

A bare str | None cannot tell "don't care about unit" apart from "the entry must itself carry no unit": both would read as None. This object gives the two states distinct shapes instead: absent on CodeValueBound.unit means "don't care"; present, with value unset, means "the entry's own unit must be unset too."

Arguments

  • value: The exact unit the entry's own unit must equal, or None to require that the entry itself states no unit 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 model_config
  • static value : str | None