Skip to main content

bcva

Derive a canonical logMAR BCVA entry from the readings an EHR served.

Best-corrected visual acuity reaches criteria matching in whichever representation a site's EHR happens to use: an ETDRS letter count, a Snellen fraction, or a logMAR number under one of several unit spellings. A criterion's value bounds are ANDed against a single entry and shared by every candidate, so one leaf cannot hold a window per representation — a logMAR window would fail every reading at a letters-serving site, and fail it as a definite FAIL rather than as unknown.

This module absorbs that variance at the point the ehr_data row is built. For every BCVA observation whose scale can be established, it appends one derived entry stamped with DERIVED_CODE_SYSTEM / DERIVED_BCVA_LOGMAR_CODE and a logMAR reading. The served entries are left exactly as they were: a derived entry is an addition, never a rewrite, so nothing that reads the original observation sees a converted number in its place.

Scale is established from the observation's unit, then from its own code, and never from the magnitude of the number. 0.5 is a decimal visual acuity to one site (0.301 logMAR) and an already-logMAR reading to another, with nothing in the value to say which — the same ambiguity snellen_to_logmar refuses a bare number for. A reading whose scale cannot be established is kept as text and reported, rather than being converted on a guess.

Laterality is carried, not inferred. The derived entry states one coding of its own, so it cannot also carry the source's displays; instead the source's resolved laterality is normalised into a SNOMED body-site code, the same encoding _bodysite_for gives a supplied row's eye column on the enrichment route. A derived entry therefore resolves to the same eye as the reading it came from, however that eye was stated. A bilateral reading produces one entry stamped with SNOMED "Structure of both eyes", which the laterality inference resolves to both eyes — the same encoding the enrichment route gives a row whose eye is OU.

Where the source states no eye in its display, text or bodySite, the eye its own code names is used instead: most of these LOINC codes come in a verified left/right pair, as do the per-eye SNOMED low-vision findings. An eye stated explicitly always wins over the code's; a disagreement is counted.

The reading's own text may state an eye too (OD 20/40). It places the reading only when the observation states no eye by any of those means. When the observation does resolve to an eye, the text must name the same one: a reading whose text names another eye, or one eye of a bilateral observation, derives nothing, since nothing says which of the two is right.

A low-vision category (CF, HM, LP, NLP) is not a chart reading: it records that the eye could not complete a BCVA test. It is treated as comparable to one and mapped onto logMAR, since correction cannot lift such an eye onto the chart. So it derives from any visual acuity code, corrected or not, and from a SNOMED low-vision finding code; a chart reading derives from a best-corrected code, or from an estimate of one where that eye has no best-corrected reading that day. The estimates are distance acuity with the patient's own correction and pinhole acuity; uncorrected and near acuity never estimate BCVA.

A reading parsed from a CCD document carries the CCD_ACUITY_SYSTEM marker coding, and some rules apply to it alone, so another source's reading under the same code is never reinterpreted. Its text is split at ; (OD: 20/30+2; NI;). The first field is the reading. A later field that is a correction, near or binocular label (cc, sc, pinhole, near, OU) is read as a label, NI and an empty field add nothing, and any other field is counted by its masked shape and not read. Its labels include the reading text and those label fields, so OD 20/40 sc is uncorrected.

A CCD reading under a best-corrected or estimate code derives as any reading under that code does. One under any other code is read by the CCD rule, unless that code already says what the reading is: uncorrected, corrected acuity that a near label kept from estimating, or a low-vision finding. A reading under one of those derives as any reading under that code does too. A CCD files most acuity under 28631-0 "Visual acuity study" or a generic code that states no correction, so the CCD rule reads it as an estimate unless its label says otherwise. Uncorrected, without corrected or pinhole, makes it low-vision-only. Near or binocular (OU) derives nothing, as does a reading placed in both eyes: binocular acuity is neither eye's BCVA. The CCD parser takes any observation whose display reads like acuity, so an entry the CCD rule reads whose text would not convert is a reading only if the text carries an acuity token (_states_acuity). One that does not (a method, a correction, an assessment) derives nothing.

A reading that is present but cannot be converted derives an entry carrying its text and no number (an entry the CCD rule reads, only when its text states acuity). It stays the latest reading and fails every numeric bound, rather than letting an older convertible reading decide the criterion. Several readings of one eye on one day resolve to the best of them.

Module​

Functions​

best_corrected_bcva_dates​

def best_corrected_bcva_dates(    observations: list[ObservationRow],) ‑> dict[typing.Literal['L', 'R'], datetime.date]:

The date of each eye's newest best-corrected reading in observations.

Only an observation whose own code classifies it as best-corrected (_reading_source) counts. An estimate, a low-vision-only code, a finding and a reading the CCD rule reads do not, as a reading of another source may outrank them on the same day. The best-corrected observations are derived as with_derived_bcva derives them, without counting or logging, and each derived entry places its eye by its bodysite. A reading kept as text counts. An entry for both eyes places neither eye, and an undated entry gives no date, as no day-based selector reads it.

Arguments

  • observations: The observation entries, in the asdict-ed shape the row stores, dated by datetime or by string.

Returns The calendar date of each eye's newest best-corrected reading; an eye with no dated best-corrected reading is absent.

collecting_bcva_counts​

def collecting_bcva_counts(    ,) ‑> Iterator[collections.Counter[typing.Literal['chart', 'low_vision_coded', 'low_vision_text', 'finding', 'unreadable_scale_unstated', 'unreadable_unparsed_text', 'unreadable_unmapped_coded', 'unreadable_out_of_range', 'finding_negated', 'finding_conflict', 'eye_from_code', 'eye_conflict', 'eye_from_text', 'text_eye_conflict', 'patients_observations_unanswered', 'patients_observations_empty', 'patients_without_acuity', 'patients_with_acuity', 'observations', 'estimate_readings', 'derived_best_corrected', 'derived_estimate', 'derived_low_vision_only', 'derived_unconverted', 'patients_bcva_best_corrected', 'patients_bcva_estimated', 'ccd_estimate', 'ccd_low_vision_only', 'ccd_near_skipped', 'ccd_binocular_skipped', 'ccd_non_reading_skipped', 'ccd_extra_text_field', 'non_reading_skipped']]]:

Collect what every with_derived_bcva call inside the block counted.

collecting_ccd_extra_field_shapes​

def collecting_ccd_extra_field_shapes() ‑> Iterator[collections.Counter[str]]:

Collect the masked shapes of the CCD text no rule reads.

Keyed by acuity_text_shape, one count per field counted as ccd_extra_text_field: a ;-separated field after a CCD reading that is neither empty, NI, nor a label (_CCD_FIELD_LABELS). The text of an entry counted as ccd_non_reading_skipped is keyed the same way, behind non_reading:. A shape keeps the format of the text and none of its content, so it is safe to report; it is what shows what a CCD puts after the reading, and what it files as acuity that is not a reading.

collecting_estimate_codes​

def collecting_estimate_codes() ‑> Iterator[collections.Counter[str]]:

Collect the codes estimated readings were taken from.

Keyed "<system>|<code>", one count per reading taken from an estimate (_ESTIMATE_CODES_BY_SYSTEM or a labelled generic code), so a run says which corrected or pinhole codes stood in for best-corrected acuity. A CCD estimate counts once under its marker (CCD_ACUITY_SYSTEM) and once under each LOINC or SNOMED code it carries, so a run says how many rest on an unlabelled CCD reading and which codes those were filed under.

collecting_non_acuity_codes​

def collecting_non_acuity_codes() ‑> Iterator[collections.Counter[str]]:

Collect the codes of served observations no acuity reading came from.

Keyed "<system>|<code>", one count per entry. A code is a terminology identifier, never a value, a display or a patient, so it is safe to report; it is what shows which code a site files acuity under when this module reads none of them.

collecting_unparsed_text_shapes​

def collecting_unparsed_text_shapes() ‑> Iterator[collections.Counter[str]]:

Collect the masked shapes of acuity text that would not convert.

Keyed by acuity_text_shape, one count per reading counted as unreadable_unparsed_text. A shape keeps the format of the text (99/99 a) and none of its content, so it is safe to report; it is what shows how a site writes the acuity this module cannot read.

derived_bcva_eyes​

def derived_bcva_eyes(    observations: list[ObservationRow],) ‑> frozenset[typing.Literal['L', 'R']]:

The eyes the BCVA derivation finds a reading for in observations.

Runs with_derived_bcva without counting or logging, so no run counter or tally moves and the readings are not logged twice, and reads the eye of each derived entry from its bodysite. Any derived entry counts, a reading kept as text included: it is a reading the source served. An entry for both eyes covers neither, as a binocular reading in a CCD does not.

The entries may be dated by datetime (as asdict leaves an Observation) or by string (as the stored row holds them).

Arguments

  • observations: The observation entries, in the asdict-ed shape the row stores.

Returns "L", "R", both or neither.

with_derived_bcva​

def with_derived_bcva(    observations: list[ObservationRow] | None,    *,    patient_id: str | None = None,    count: bool = True,    log: bool = True,) ‑> list[dict[str, str | None | datetime.datetime | float | bool | int | dict[str, typing.Any] | list[dict[str, typing.Any]]]] | None:

Append a canonical logMAR entry per BCVA reading.

None passes through as None rather than becoming a list. The two mean different things to the criteria — None is "not retrieved", resolving UNKNOWN, and [] is a confirmed negative — and _safe_observation_list exists to keep that distinction (see its docstring). An empty list passes through empty for the same reason: there is nothing to derive from, and nothing derived to add.

A reading that would not convert warns rather than reporting at info: it is stored as text, which fails every numeric bound, so the patient is excluded on a reading this code could not interpret. That has to be visible in the log. Text that would not convert is named by its masked shape (acuity_text_shape), never by the text, which can carry patient details. What was counted is also added to the run's counters when they are being collected (collecting_bcva_counts, collecting_unparsed_text_shapes, collecting_ccd_extra_field_shapes), unless count is False. Neither line is logged when log is False.

Arguments

  • observations: The patient's served observation entries, or None when the fetch did not answer.
  • patient_id: The patient the readings belong to, for the log line only.
  • count: Whether to add what was counted to the run's counters and tallies. False for readings a run has counted already, such as those carry_forward_ccd_acuity carries from a stored row.
  • log: Whether to log what was derived and what would not convert. False for a derivation whose readings the run logs elsewhere, such as one that only asks which eyes have a reading.

Returns The served entries followed by one derived entry per BCVA reading, de-duplicated and reduced to the best per eye per day; observations unchanged when nothing derived.

Global variables​

  • BCVACount - What with_derived_bcva counts, per run, for telemetry.

    The first four are derived readings by how they were read; the unreadable_* ones are readings stored as text; then findings that derived nothing and how each derived entry's eye was settled. eye_conflict counts a reading kept under its stated eye although its code names the other one; text_eye_conflict counts a reading dropped because its own text names an eye the observation does not resolve to, and eye_from_text one placed by its text because the observation states no eye at all.

    The patients_* ones say what each patient's observations held before any reading was attempted: not answered (None), answered with nothing ([]), answered with no entry under an acuity code, or with at least one. observations counts the entries served. Together they tell a site whose EHR never answered for observations from one that answered under codes this module does not read, which the reading counts alone cannot: both read zero.

    The seven from estimate_readings to patients_bcva_estimated say how much of the derived BCVA is estimated: readings taken from an estimate code or read as an estimate by the CCD rule (estimate_readings), the converted derived entries kept after the best-of-day reduction by where they came from (derived_best_corrected, derived_estimate, derived_low_vision_only), the kept entries carrying unconverted text instead (derived_unconverted), and the patients holding at least one converted best-corrected or estimated entry.

    The ccd_* ones are about readings parsed from a CCD document. The first four say how the CCD rule (_ccd_rule_source) decided each CCD reading it applied to: an estimate, low-vision-only because its label says uncorrected, or nothing because it says near or binocular. Each counts the rule's decision per entry, before the value is read, so an entry with no reading counts too. A CCD estimate is also counted in estimate_readings once read. ccd_non_reading_skipped counts the entries the CCD rule read whose text would not convert and carries no acuity token (_states_acuity), so derives nothing. ccd_extra_text_field counts the fields after a CCD reading that no rule reads (_ccd_text), whatever the reading's code.

    non_reading_skipped counts the readings outside the CCD rule whose text records that no reading was taken (states_no_reading: Not tested, Other, None), which derive nothing so the eye's previous reading decides.

  • BCVA_FETCH_CODES : Final[tuple[tuple[str, str], ...]] - Every code a BCVA reading can arrive under, as (short_system, code).

    The system is the short name get_patient_observations takes, which looks it up in CODE_SYSTEM_TO_IDENTIFIER and raises on a full URI.

    Searched by code as well as by category, since a site need not file its acuity observations under any core observation category.

  • CCD_ACUITY_CODINGS : Final[frozenset[tuple[str, str]]] - Every (system URI, code) a reading from a CCD, or BCVA derived from one, can carry.

    A CCD reading carries the marker and its own codes, which are the codes the parser reads as acuity: BCVA_FETCH_CODES, 28631-0, or a code under an acuity-like display that no list names. A leaf naming any of these may read a CCD reading, so it cannot decide while the patient's CCD search failed.

Classes​

BodySiteEntry​

class BodySiteEntry(*args, **kwargs):

A serialised BodySite, as an observation's bodysite.

Variables​

  • static bodysite_coding_code : str | None
  • static bodysite_coding_display : str | None
  • static bodysite_coding_system : str | None
  • static text : str | None

CodingEntry​

class CodingEntry(*args, **kwargs):

One serialised Coding on an observation's own code.

asdict() emits every field of the dataclass, so all three keys are present on any entry that has a codings list at all.

Variables​

  • static code : str | None
  • static display : str | None
  • static system : str | None

ObservationEntry​

class ObservationEntry(*args, **kwargs):

A serialised Observation, as the ehr_data observation column holds.

total=False because a row is not guaranteed to carry every key: rows cached before codings existed have the flat code_system/code_code/ code_display keys instead (those are Observation properties now, so a freshly serialised entry has none of them), and _safe_observation_list copies whichever keys the entry it was given actually had.

Variables​

  • static code_code : str | None
  • static code_display : str | None
  • static code_system : str | None
  • static code_text : str | None

ObservationValueEntry​

class ObservationValueEntry(*args, **kwargs):

The keys this module reads from a serialised Observation.value.

value[x] is one of eleven variants (ObservationValue in bitfount.externals.ehr.types), each serialising to its own key set: value/unit for a Quantity, value alone for a ValueString, numerator/denominator for a Ratio, system/code/display/text for a CodeableConcept. Rather than a union of all eleven — most of which cannot be an acuity — this states the keys a BCVA reading can arrive under, and is total=False because which of them is present is exactly what varies.

Variables​

  • static code : str | None
  • static display : str | None
  • static system : str | None
  • static text : str | None
  • static unit : str | None
  • static value : float | int | str | bool | None

QuantityEntry​

class QuantityEntry(*args, **kwargs):

A serialised Quantity, as a Ratio's numerator or denominator.

asdict() emits every field of the dataclass, so all three keys are present on any entry carrying a Quantity at all. Only value is read here — a logMAR conversion needs the Snellen fraction's two numbers and nothing else.

Variables​

  • static comparator : str | None
  • static unit : str | None
  • static value : float | None