Skip to main content

observation

Criteria on a patient's observations (FHIR Observation), and supplied readings.

The observation leaf (ObservationCriterion): an observation of a matching code or text is recorded for the patient, in its date window and for its eye, and its value meets the leaf's bounds (CodeValueBound): a number or quantity with a unit, a comparator such as <5, a coded value, or a string. The leaf reads the EHR's observations and the observation-shaped readings supplied in an enrichment file (for example a BCVA export); _observation_provenance_column says which source decided a row. The evidence and findings are the readings it decided on.

Module​

Functions​

observation_leaf_filter​

def observation_leaf_filter(    criterion: ObservationCriterion, ctx: FilterBuildContext,) ‑> MethodFilter:

Build a MethodFilter for an ObservationCriterion criteria_tree leaf.

Mirrors code_leaf_filter's code/date/laterality/selector handling exactly (see its docstring), against OBSERVATIONS_COLUMN and SUPPLIED_OBSERVATIONS_COLUMN together rather than a resource-keyed single column. ObservationCriterion has no condition-vs-procedure resource choice to make. A qualifying entry may come from either column. Additionally, when criterion.value_bounds is non-empty, _select_matching_candidates checks every bound (_observation_entry_matches_bounds) against each code/date/ laterality-qualifying entry as selector reduces them, rather than pre-filtering candidates by it.

Arguments

  • criterion: The leaf to compile.
  • ctx: What the filter builders share. Its reference_date is "today", for resolving date_range. Its column_provenance gives the single observation column this filter's provenance is read from (see _observation_provenance_column).

Returns A MethodFilter degrading to unknown when neither observation column is present in the row, or both present cells are unreadable — the same missing-data convention code_leaf_filter uses, extended across both columns. A fail is also unknown when the patient's EHR observations were expected but could not be read (see _ehr_observations_expected): the supplied data alone cannot show that no qualifying observation exists. A leaf that reads derived BCVA is unknown when the patient's CCD search failed (see _bcva_documents_unavailable), unless it passed on the supplied readings alone.

Classes​

CodeValueBound​

class CodeValueBound(**data: Any):

A comparison against an observation entry's own resolved value.

Six of FHIR's eleven Observation.value[x] shapes resolve to a shape this class can compare against:

  • valueQuantity. A number with a unit.
  • valueBoolean.
  • valueInteger.
  • valueString. valueTime resolves the same way. A time string compares the same way as any other string.
  • valueCodeableConcept. Matched structurally, through CodeableConceptBound (see value below).

The remaining shapes never resolve: valueRange, valueRatio, valuePeriod, valueDateTime, and valueSampledData. An entry carrying one of these never qualifies against a CodeValueBound. These shapes are not yet supported.

Arguments

  • op: The comparison operator. Reuses ColumnCriterion.op's exact symbol set, from the same OPERATOR_SPECS table (bitfount.steps.types.operators). Also reuses that table's per-dtype legality rule. For example, an ordering operator is illegal against a str or bool value. The rule is checked per entry at match time, not once at parse time. A ColumnCriterion knows its column's dtype up front. An entry's own resolved value shape is only known once matching starts.

Which comparisons op allows depends on value's shape:

  • Against a valueString, "==", "!=", "in", and "not in" match value as a glob rather than by plain equality. Only * acts as a wildcard, matched with fullmatch. CodeCriterion.code already uses this convention. A target with no * behaves as plain equality. So a compound free-text value can match on one part of it. For example, the BCVA reading "20/60 (30.0) 0.67pt 0.18M -1" matches value="*20/60*" without matching the whole string.
  • Against a CodeableConceptBound value, only "==" and "!=" are legal. Ordering and membership do not apply to a structural match.
  • value: The threshold or target value, or a CodeableConceptBound that matches a valueCodeableConcept entry structurally.
  • unit: A bound on the entry's own unit, via UnitBound (see its own docstring for why this needs to be an object rather than a bare str | None). Absent: unit checking is skipped entirely, so a valueQuantity entry qualifies on its number alone, whatever unit it does or does not state. UnitBound(value=None) (i.e. unit: {}): the entry must itself state no unit at all — the safer, opt-in alternative to leaving unit unset. UnitBound(value="mg"): the entry's own unit must equal "mg" exactly. Must be unset when value is a boolean or a string, since neither carries a unit of its own. An integer value may carry a unit: a whole-number quantity, like 1 logMAR, is a legal valueQuantity, and JSON gives no way to tell it from a valueInteger. Must also be unset when value is a CodeableConceptBound.

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 op : Literal['>', '>=', '<', '<=', '==', '!=', 'in', 'not in']
  • static value : bool | int | float | str | list[str | int | float] | CodeableConceptBound

CodeableConceptBound​

class CodeableConceptBound(**data: Any):

A bound on an observation entry's valueCodeableConcept.

Mirrors the real FHIR CodeableConcept shape (see hl7.org/fhir/R4/datatypes.html#CodeableConcept): a concept expressed as a coding (system/code/display) and/or free-text text. Each field you set narrows the match. Each field left unset adds no constraint.

Arguments

  • coding: An optional bound on the entry's system/code/display (see CodingBound). Unset imposes no constraint on coding.
  • text: Match against the entry's own free-text text, as a *-glob.

Variables​

  • static model_config
  • static text : str | None

CodingBound​

class CodingBound(**data: Any):

A bound on one CodeableConcept.coding entry.

Every field left unset imposes no constraint; each field that is set narrows the match further — the fields are AND'd together, not OR'd.

Arguments

  • system: Exact match against the coding's system URI. Not glob-capable — a system is an identifier, not free text.
  • code: Match against the coding's code, as a *-glob (the same convention CodeCriterion.code uses), e.g. code="8302-*". A target with no * behaves as plain equality.
  • display: Match against the coding's display, as a *-glob.

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 | None
  • static display : str | None
  • static model_config
  • static system : str | None

ObservationCriterion​

class ObservationCriterion(**data: Any):

An EHR observation code, optionally bounded by its own resolved value.

Arguments

  • node: Discriminator identifying this as an observation-type criteria_tree node.
  • code: As _BareCodeAddressedLeaf.code; omit it for a text-only criterion.
  • text: Free text matched against the strings naming the observation, glob-capable the same way code is (e.g. "*haemoglobin a1c*"), or a list of alternatives. Matched case-insensitively, unlike code, since the casing of a test name depends on which backend answered. Matched against the whole string, so a bare "troponin" does not match "Troponin I, high sensitivity" — wrap it in * to match within. Searched across code_text and every codings[].display; see _code_text_candidates.

It exists because a lab result need not be coded at all: a NextGen result carries a loincCode only when the interface populated one, and a manually entered result generally has none, leaving the test name as the only thing to match on.

  • value: An optional bound on the observation's own value (see CodeValueBound), or a list of bounds every one of which the same entry must satisfy. When set, a matching code entry additionally qualifies only if its value satisfies the bound(s). When unset, behaves exactly like CodeCriterion: presence/date/laterality only, value ignored.

A list is how a two-sided window is expressed, and expressing one as two sibling leaves under an AndGroup does not work. Every selector except CountSelector reduces to "at least one candidate entry qualifies" (see code_leaf_filter), so two leaves ask whether some entry cleared the lower bound and whether some entry cleared the upper — satisfiable by two different readings on different dates. A patient whose study eye read 0.18 logMAR once and 1.40 logMAR another time passes both halves of a >= 0.30/<= 1.00 window without ever having had a reading inside it. Listing both bounds on one leaf checks them against a single entry, which is what "a measurement in this range" means.

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 criterion_noun : ClassVar[str]
  • static model_config
  • static node : Literal['observation']
  • value_bounds : list[CodeValueBound] - value, normalized to the list of bounds ANDed against one entry.

    Empty when no value bound is configured, so a caller can iterate unconditionally rather than branching on None.

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.