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. Itsreference_dateis "today", for resolvingdate_range. Itscolumn_provenancegives 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 aunit.valueBoolean.valueInteger.valueString.valueTimeresolves the same way. A time string compares the same way as any other string.valueCodeableConcept. Matched structurally, throughCodeableConceptBound(seevaluebelow).
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. ReusesColumnCriterion.op's exact symbol set, from the sameOPERATOR_SPECStable (bitfount.steps.types.operators). Also reuses that table's per-dtype legality rule. For example, an ordering operator is illegal against astrorboolvalue. The rule is checked per entry at match time, not once at parse time. AColumnCriterionknows 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"matchvalueas a glob rather than by plain equality. Only*acts as a wildcard, matched withfullmatch.CodeCriterion.codealready 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"matchesvalue="*20/60*"without matching the whole string. - Against a
CodeableConceptBoundvalue, only"=="and"!="are legal. Ordering and membership do not apply to a structural match. value: The threshold or target value, or aCodeableConceptBoundthat matches avalueCodeableConceptentry structurally.unit: A bound on the entry's ownunit, viaUnitBound(see its own docstring for why this needs to be an object rather than a barestr | None). Absent: unit checking is skipped entirely, so avalueQuantityentry 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 leavingunitunset.UnitBound(value="mg"): the entry's ownunitmust equal"mg"exactly. Must be unset whenvalueis a boolean or a string, since neither carries a unit of its own. An integervaluemay carry a unit: a whole-number quantity, like1 logMAR, is a legalvalueQuantity, and JSON gives no way to tell it from avalueInteger. Must also be unset whenvalueis aCodeableConceptBound.
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
unit : UnitBound | None
- 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'ssystem/code/display(seeCodingBound). Unset imposes no constraint on coding.text: Match against the entry's own free-texttext, as a*-glob.
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'ssystemURI. Not glob-capable — asystemis an identifier, not free text.code: Match against the coding'scode, as a*-glob (the same conventionCodeCriterion.codeuses), e.g.code="8302-*". A target with no*behaves as plain equality.display: Match against the coding'sdisplay, 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 anobservation-typecriteria_treenode.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 waycodeis (e.g."*haemoglobin a1c*"), or a list of alternatives. Matched case-insensitively, unlikecode, 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 acrosscode_textand everycodings[].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 (seeCodeValueBound), 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 likeCodeCriterion: 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']
- static
value : CodeValueBound | list[CodeValueBound] | None
-
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.