core
The types that every part of criteria matching shares.
The state, grain, family and provenance of a criterion; the outcome of a filter
(MethodOutcome) and of a criterion (CriterionOutcome) for one row; why a
criterion could not decide (UnknownReason); the evidence types that an
outcome carries; the base class of every criteria_tree node (_TreeNode);
and the served tree and its findings (AnnotatedTreeNode, TreeFinding).
The evidence types of the different record kinds are here, not in their
domain modules, because MethodOutcome and CriterionOutcome carry them.
This module imports no other criteria-matching module.
Module
Functions
finest_grain
def finest_grain( grains: Iterable[CriterionGrain],) ‑> CriterionGrain:The finest of grains, in the order patient, organ, multi-scan, scan.
A combinator's verdict can depend on anything that its children depend on, so it takes the finest grain among them.
Arguments
grains: The grains to compare. Must not be empty.
Returns The finest grain.
unknown_reason
def unknown_reason( code: UnknownReasonCode, *, records: str = 'records', label: str = 'This value',) ‑> UnknownReason:Make the reason that a leaf could not decide.
Arguments
code: The reason.records: The kind of EHR record that the leaf reads, such as "medications". Used by the EHR reasons.label: The name of the value that the leaf reads, such as "Total GA Area". Used byVALUE_MISSING.
Returns The reason, with its text.
Classes
AnnotatedMultiScan
class AnnotatedMultiScan(*args, **kwargs):One scan that a served multi_scan node read.
Attributes
scan_id: The scan.date: The scan's study date, asYYYY-MM-DD. Not included if it cannot be read.laterality: The scan's eye,"L"or"R". Not included otherwise.state: The node's child evaluated on this scan.
Variables
- static
date : str
- static
laterality : str
- static
scan_id : str
- static
state : TreeNodeState
AnnotatedTreeNode
class AnnotatedTreeNode(*args, **kwargs):One node of the annotated criteria_tree, with the result of the node.
The node also has its other configured keys, for example column or
code on a leaf. They are not typed here.
To make the criterion number, join the item_number values on the path from
the root and add I or E from criterion_type, for example E4a. The
highest node with an item_number is a protocol criterion. A lower node with
an item_number is a sub-item. A node with no item_number on its path is
not a protocol criterion.
Attributes
node: The node type, for exampleand,or,not,multi_scan,columnormanual. Amanualnode is a criterion that Bitfount does not analyse.state: The result of the condition of the node itself. Anotnode reverses the result of its child, so below anot,passmeans that the condition matched, and thenotnode fails. Anotcan be in an inclusion or an exclusion.not_assessedis a not-analysed criterion: amanualnode, or anand,or,at_leastornotof them, and every node below it. It can be at any depth, beside analysed nodes. It has nosource,findings,checked_windoworunknown_reason. Directly under anandit changes no verdict or score. In anororat_least, or under anot, it counts asunknown, because it could change the result.source: The record types that the node, or the leaves below it, read, in the orderscan,ehr,supplied.criterion_type:inclusionorexclusion. A node without a value gets the value of its nearest ancestor.item_number: The part of the criterion number that the node adds, for example"4", or"a"on a sub-item.label: The display title.trial_text: The protocol text.review_reason: Something a person must check, as the config wrote it: text for when the node passed, or an object with the text for each state it names (pass,fail,unknown).findings: Only on a leaf. The records that the leaf read and decided on, whatever its state. An empty list means that the leaf read no record. Not included if the leaf has no records to show. An appointment leaf shows only the records its bound needs, for example the latest 3 for "at least 3".checked_window: Only on a leaf. The dates within which the leaf searched for records. Not included if the leaf searched all records, or could not search.on_match: Only on anotnode that is a flagged exclusion, with the valueunknown. A match of its child makes the nodeunknownwith the reasonflagged_match, notfail: a person must verify the match. The child'sreview_reasonsays what to verify.unknown_reason: Only on a node whose state isunknownand that has a reason of its own: a leaf, amulti_scannode that selected no scan, or anotwithon_matchwhose child matched. Why it could not decide.scans: Only on amulti_scannode: every scan it read, and its child's state there. An empty list means no scan was selected. The node's child is shown as evaluated on the latest scan whose state matches the node's, with that scan's date and eye on its findings.children: The child nodes of anand,ororat_leastnode.child: The child node of anotormulti_scannode.
Variables
- static
checked_window : IsoDateWindow
- static
child : AnnotatedTreeNode
- static
children : list[AnnotatedTreeNode]
- static
criterion_type : CriterionType
- static
findings : list[TreeFinding]
- static
item_number : str
- static
label : str
- static
node : str
- static
on_match : Literal['unknown']
- static
review_reason : str | ServedReviewReasons
- static
scans : list[AnnotatedMultiScan]
- static
source : list[CriterionProvenance]
- static
state : TreeNodeState
- static
trial_text : str
- static
unknown_reason : UnknownReason
AppointmentEvidence
class AppointmentEvidence(*args, **kwargs):The appointments and encounters that an appointment leaf decided on.
A TypedDict, like CodeMatchEvidence, so that it stays a plain dict in
JSON.
Attributes
records: The records that meet the leaf's bound, ascending by date: the latestcountrecords in each period that the bound checks, or in the whole window if it has no period. On a fail, a period that fell short has fewer.unreadable: The records whose date could not be read, on a leaf that could not decide because of them. The leaf cannot tell whether they are in its window, so a person must check them. Not included on a pass: the bound is "at least N", so they cannot undo it.
AppointmentRecord
class AppointmentRecord(*args, **kwargs):One appointment or encounter that an appointment leaf read.
Attributes
date: The date of the record, asYYYY-MM-DD. Not included if the date could not be read.event: What the record was, as the EHR recorded it: the appointment description, or the encounter or visit type."Appointment"or"Encounter"if the EHR recorded none.
CodeMatch
class CodeMatch(*args, **kwargs):One code that qualified, and how it qualified.
Attributes
code: The code as the EHR recorded it, not the configured pattern it matched — a configuredH35.3*reports theH35.31actually present.text: The entry's name for display: itscode_text, else the matched coding'sdisplay, else any coding'sdisplay;Nonewhen the entry carries none. Absent from rows written before it existed.scope:any_eyefor a code qualifying regardless of laterality,study_eyefor one whose inferred laterality had to include the scan eye (and did),fellow_eyefor one whose inferred laterality had to include the other eye (and did).code_system: The code system of the code that matched, as the EHR recorded it. Not included if the EHR gives none.date: The date of the record, asYYYY-MM-DD. The same code on two dates is two matches. Not included if the record has no date, or if the criterion does not report dates.date_window: The dates of a record that covers a period, such as a medication course. Set instead ofdate. The same code with two windows is two matches.doses: The doses of a medication record, one for each dose reading with an amount, of each dosage instruction that applies to the leaf's eye. Two records with the same code and dates but different doses are two matches. Not included if the record gives none, or the leaf is not a medication leaf.abatement_date: The date a condition abated, asYYYY-MM-DD. Not included if the record has none, or the leaf is not a condition leaf. Two conditions with the same code and date that differ in this are two matches.clinical_status: The FHIR clinical status of a condition, for exampleresolved. Not included if the record has no status, if its status is not a FHIR clinical status code (in any case), or if the leaf is not a condition leaf. Two conditions with the same code and date that differ in this are two matches.
Variables
- static
abatement_date : str
- static
clinical_status : str
- static
code : str
- static
code_system : str
- static
date : str
- static
date_window : IsoDateWindow
- static
doses : list[MedicationDose]
- static
scope : Literal['any_eye', 'study_eye', 'fellow_eye']
- static
text : str | None
CodeMatchEvidence
class CodeMatchEvidence(*args, **kwargs):Which EHR codes drove a code-list criterion's verdict, structurally.
The typed counterpart to a code filter's prose context string. The filters already know the codes; this carries them in a form a consumer can render or filter on without parsing English, and it is persisted inside the criterion's evidence so the patient API can serve it.
A TypedDict rather than a model for the same reason as CriterionEvidence
(which nests it): the value is persisted as JSON, so it must stay a plain dict
through json_safe and json.dumps. total=False because a row written
before this existed carries no key at all — read every key with .get.
Only the codes that decided something appear. A configured code that simply did not match is absent; so is a code matched inside a recency window whose event date proved too old, and a study-eye code whose laterality was inferred and disagreed with the scan eye. All three contributed nothing to the verdict.
Attributes
matched_codes: Every code that qualified, ascending by code. The same code can appear more than once, with a different date, text or doses. For an inclusion criterion these are the codes that made the patient eligible; for an exclusion criterion, the codes that disqualified them. Empty when nothing matched decisively.
Plural, and complete: the filters used to stop at their first decisive match, so the evidence could name only one of several qualifying codes. They now scan every entry. The verdict is unchanged either way — the first match already settled it — so this widens what is reported without moving any patient between states.
pending_laterality_review: Codes that matched a study-eye list but whose own laterality could not be inferred, so they could not decide the verdict. Their presence is why the criterion's state follows the configuredeligible_on_*_codes_lat_unknownrather than the codes themselves — a reviewer resolves them by hand. Reported only when nothing qualified: a populatedmatched_codessettles the criterion, which makes an indeterminate code moot.matched_values: The measurements that qualified, for a criterion whose verdict turned on an observation's own value. Empty or absent for every other code-list criterion, which has no measurement to report — a condition code either is or is not present.
Reported alongside matched_codes rather than instead of it: the code says which concept qualified, the value says what it read.
pending_date_review: Codes that matched an exclusion list carrying a recency window, but whose event date is unknown, so recency could not be confirmed. Exclusion-only: the inclusion filter has no windows. Reported under the same condition aspending_laterality_review.
Variables
- static
matched_codes : list[CodeMatch]
- static
matched_values : list[MeasuredValue]
- static
pending_date_review : list[str]
- static
pending_laterality_review : list[str]
CriteriaEvaluation
class CriteriaEvaluation(**data: Any):One evaluated subject: its identity paired with its per-criterion outcomes.
Arguments
identity: The evaluated subject's identity.outcomes: The per-criterion outcomes (one per filter/bound; a range field contributes two, sharing anoutput_field). Never contains acriteria_treeleaf outcome onceattach_criteria_tree_verdicthas run — those live intree_node_outcomesinstead, alongside every combinator's own outcome, plus one entry here (the root's, duplicated) for the tree's own combined state.tree_node_outcomes: Everycriteria_treenode's own outcome — leaf and combinator alike, including the root — in post-order (children before parents). Leaves are moved here out ofoutcomesbyattach_criteria_tree_verdictsomatches_allnever re-ANDs an individual branch's leaf (which would defeat OR/AT_LEAST/NOT); every combinator's outcome is synthesised fresh, withgrain/provenancederived from its children (see_combinator_outcome) rather than fixed. Empty when nocriteria_treeis configured.review_flags: Every triggeredreview_reasonfrom the tree (leaf or group) whose own state resolved topass, in tree order, without deduplication. Populated byattach_criteria_tree_verdict; a downstream triage signal only — never affectsmatches_all.tree_score: The root node's own resolved[0, 1]score (seeCriterionOutcome.score), orNonewhen nocriteria_treeis configured. Entirely additive tomatches_all— a ranking signal, never a substitute for the PASS/FAIL gate.criteria_tree: The configured tree with the results of this row.Noneif nocriteria_treeis configured.
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
criteria_tree : AnnotatedTreeNode | None
- static
identity : SubjectIdentity
- static
model_config
- static
outcomes : list[CriterionOutcome]
- static
review_flags : list[str]
- static
tree_node_outcomes : list[CriterionOutcome]
- static
tree_score : float | None
-
matches_all : bool- Whether every criterion passed (reproducesFILTER_MATCHING_COLUMN).Any non-
pass(fail or unknown) means the row does not match; an empty outcome list (no active filters) is vacuouslyTrue.Returns:
Trueiff every outcome's state ispass.
CriterionFamily
class CriterionFamily(*args, **kwds):The kind of criterion, which sets the shape of its result.
The family tells a consumer how to read value and which other fields
are set:
scan_metric: a scan measurement compared with a bound, such as GA area.valueis the measured number.patient_metric: a number about the patient compared with a bound, such as age.valueis that number.code_list: whether the record has matching codes, such as a condition, a medication or an observation. The matches are incode_match.compound_scan: a check that combines more than one scan measurement.appointment: the patient's visit history in a date window.generic_columnandgeneric_method: any other configured check.
The patient API's EligibilityCriterion variants match these members one
to one, so a consumer can choose the variant from family.
The family is set by the code that builds the criterion. It cannot be found from the other three labels, which are independent of it:
CriterionKind: which filter type ran (columnormethod).CriterionGrain: where the verdict is decided (per patient, per organ or per scan).CriterionProvenance: where the data came from.
A family limits the values that those three labels can take. For example,
a code_list is always a method filter, its grain is patient or organ,
and its provenance is ehr or supplied. But the three values do not
identify a family: an appointment criterion can have the same kind, grain
and provenance as a code_list, and its value has a different shape.
Subclasses str so members serialise straight into JSON evidence.
Ancestors
Variables
- static
APPOINTMENT
- static
CODE_LIST
- static
COMPOUND_SCAN
- static
GENERIC_COLUMN
- static
GENERIC_METHOD
- static
PATIENT_METRIC
- static
SCAN_METRIC
CriterionGrain
class CriterionGrain(*args, **kwds):How much scan data a criterion's verdict depends on.
PATIENT: none; decided once for the patient. ORGAN: which eye is the
study eye, but no scan data. MULTI_SCAN: data from a set of the
patient's scans, for example the fellow eye's. SCAN: the scan's own
data.
Ancestors
CriterionKind
class CriterionKind(*args, **kwds):Which filter type produced a CriterionOutcome.
The explicit filter-type discriminator consumers branch on: COLUMN for a
ColumnFilter outcome, METHOD for a MethodFilter outcome. Subclasses
str so members serialise straight into JSON evidence.
Ancestors
CriterionOutcome
class CriterionOutcome(**data: Any):One criterion's outcome for one row, carrying enough to regenerate any string.
Arguments
config_field: OriginatingCriteriaMatchConfigfield, orNoneif unmapped.output_field: Logical field name / evidence key (filter column or name).column_name: Exact flat-df column name the filter would write (for tabulation).operator: TheColumnFilteroperator (">", ...);Nonefor aMethodFilterthat does not know its own operator.operand: The configured value the operator compared against — the comparison's right-hand side. Namedoperandrather thanthresholdbecause it is not always a bound:in/not input the whole candidate list here.Nonefor a filter with no recorded comparison.value: The observed value on the row, orNoneif missing/not applicable. AColumnFilterreports its cell; a code-listMethodFilterreports itsCodeMatchEvidence— the codes that drove the verdict — so a structured verdict lands in the same field as a scalar one rather than in a field of its own. Readfamilyto know which to expect. Every otherMethodFilterhas no single observed value and reportsNone.state:pass/fail/unknown(producer never emitsna).context: Runtime context that cannot be regenerated, as prose (e.g. matched codes). Consumed by the report's context column; for a code-list criterionvaluecarries the same information structurally.failed_message: AMethodFilter's regenerated failure reason (its static message, or a "missing values"/"unable to determine" variant), orNonefor aColumnFilteroutcome.grain:patient,organ,multi_scanorscan— where the verdict is decided (seeCriterionGrain), not the data source (seeprovenance).provenance:scanorehr— the data source (distinct fromgrain). Defaults tounknown; stamped bybuild_criterion_outcomesfrom the source column, not by the filter (age can be either source).unit: The target column's display unit (e.g."mm²"), orNonewhen the field is unitless or unknown. Likeprovenance, not a filter attribute — stamped bybuild_criterion_outcomesfrom the target column'sFieldSpecin the field catalog, or, when that gives none, from the column's CSV header (COLUMN_HEADER_UNITS).display_name: What the column the row's verdict read measures (e.g."CNV probability"), orNonewhen the column has no display name. Stamped bybuild_criterion_outcomesfromCOLUMN_DISPLAY_NAMES. The served tree shows it as the text of a measurement finding.absent_column: For aColumnFilteroutcome whose target column was entirely absent from the row (as opposed to present with aNaNvalue), the raw configured column name to render into the regenerated "not found" reason instead of its display rename.Nonewhen the column was present (even ifNaN), and alwaysNonefor aMethodFilteroutcome.matched_column: The source column this row's verdict actually read, for a filter that can read more than one. Set only by the observation filter, which spansOBSERVATIONS_COLUMNandSUPPLIED_OBSERVATIONS_COLUMN, and only when the row produced qualifying candidates.build_criterion_outcomesprefers it over the filter-levelprovenance_columnwhen stampingprovenance, which is what makes provenance per-row rather than per-filter for a multi-column filter.Nonefor every single-column filter and for a row that matched nothing — the filter-level constant is used then.kind:columnfor aColumnFilteroutcome,methodfor aMethodFilteroutcome. The explicit filter-type discriminator consumers branch on.family: The semantic criterion family (seeCriterionFamily), carried through from the filter that produced this outcome.Noneonly for a filter built without one — a directly constructed filter in a test, or a user-authoredColumnFilterin a task config, neither of which comes frombuild_eligibility_filters.tree_node_id: Thecriteria_treeleaf id this outcome was built from, orNonefor an outcome not built from a tree leaf.attach_criteria_tree_verdictuses this to move the outcome out ofCriteriaEvaluation.outcomesintotree_node_outcomes, so a tree leaf's own PASS/FAIL is never re-ANDed bymatches_all. A combinator's own synthesised outcome (see_combinator_outcome) also sets this, to its own node id, so every entry intree_node_outcomesis addressable the same way.tree_group: The tree node's resolved (inherited)groupreporting label, stamped byevaluate_criterion_treefor every node — leaf or combinator.Nonewhen neither the node nor any ancestor set one, and alwaysNonefor a non-tree outcome.
Not an identity: group does not override, so every node beneath a region root shares that root's exact string (see _check_group_inheritance). Uniqueness is enforced among region roots, not among the leaves under one.
tree_evidence_id: The tree node's ownevidence_id, stamped byevaluate_criterion_tree.Nonefor a node that sets none and for every non-tree outcome. Unliketree_groupthis is not inherited and is unique tree-wide, so it identifies the one leaf that set it.score: This node's own resolved[0, 1]score (seeevaluate_criterion_tree), orNoneif this node has not resolved enough to score yet, or if it is not part of acriteria_treeat all.examined: The records a code-addressed leaf decided on, whatever the verdict (seeMethodOutcome.examined). The served tree shows them as the leaf's findings.Nonefor every other criterion.checked_window: The dates within which the leaf searched for records: itsdate_range, resolved against the reference date. An open end is the reference date. An open start is not included.Noneif the leaf has nodate_range, or the state isunknown, because then the leaf searched all records, or could not search.unknown_reason: Why the criterion could not decide. Set only if the state isunknown.appointments: The appointments and encounters an appointment leaf decided on (seeMethodOutcome.appointments). The served tree shows them as the leaf's findings.Nonefor every other criterion.multi_scan: What amulti_scannode read;Noneon every other outcome.
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
absent_column : str | None
- static
appointments : AppointmentEvidence | None
- static
checked_window : IsoDateWindow | None
- static
column_name : str
- static
config_field : str | None
- static
context : str | None
- static
display_name : str | None
- static
examined : CodeMatchEvidence | None
- static
failed_message : str | None
- static
family : CriterionFamily | None
- static
grain : CriterionGrain
- static
kind : CriterionKind
- static
matched_column : str | None
- static
model_config
- static
multi_scan : MultiScanEvidence | None
- static
operand : Any
- static
operator : str | None
- static
output_field : str
- static
provenance : CriterionProvenance
- static
score : float | None
- static
state : CriterionState
- static
tree_evidence_id : str | None
- static
tree_group : str | None
- static
tree_node_id : str | None
- static
unit : str | None
- static
unknown_reason : UnknownReason | None
- static
value : Any
CriterionProvenance
class CriterionProvenance(*args, **kwds):Where a criterion's evaluated data was pulled from — its data source.
The source axis, orthogonal to CriterionGrain (where the verdict is
decided: per patient, per organ or per scan). A patient-grain criterion can
still be scan-provenance: age computed from a DICOM birth-date is
grain=patient, provenance=scan. Subclasses str so members serialise
straight into JSON evidence. Not a filter attribute — resolved in
build_criterion_outcomes from the source column each value was built from.
Ancestors
CriterionState
class CriterionState(*args, **kwds):A single criterion's evaluated state.
na = not applicable to this row (a patient-level criterion on a scan row);
only consumers assign na, never the producer. Subclasses str so members
serialise straight into JSON evidence.
Ancestors
CriterionType
class CriterionType(*args, **kwds):The part of the trial protocol that a criteria_tree node is in.
Ancestors
DoseFrequency
class DoseFrequency(*args, **kwargs):How often a dose is given: count times in each period.
For example, "twice daily" is count 2, period 1 and period_unit
"d", and "every 4 to 6 hours" is count 1, period 4, period_max 6
and period_unit "h".
Attributes
count: How many times in each period.count_max: The highest count, if the count is a range.period: The length of the period.period_max: The longest period, if the period is a range.period_unit: The unit of the period, for example"d"or"h".
Variables
- static
count : int
- static
count_max : int
- static
period : float
- static
period_max : float
- static
period_unit : str
DoseMeasurement
class DoseMeasurement(*args, **kwargs):The amount of one dose: a single quantity, or a range.
Attributes
value: The quantity, for example200. Not included for a range.low: The lowest quantity of a range, for example1in "1 to 2 tablets". Not included for a single quantity.high: The highest quantity of a range.unit: The unit, for example"mg". Not included if not recorded.
IsoDateWindow
class IsoDateWindow(*args, **kwargs):A period from one date to another, for example a medication course.
Attributes
start: The first date, asYYYY-MM-DD. Not included if the period has no start, or the start is not known.end: The last date, asYYYY-MM-DD. Not included if the period has no end, for example a course that has not stopped.
MeasuredValue
class MeasuredValue(*args, **kwargs):One observation entry's own measurement, as evidence.
An observation criterion's verdict turns on a number, not merely on a
code being present, so reporting only the code leaves a reviewer unable
to see what was measured. A BCVA criterion reporting pass says
nothing about whether the study eye read 20/40 or 20/200; this carries
the reading itself.
A TypedDict, and total=False, for the same reasons as
CodeMatchEvidence, which nests it: the value is persisted as JSON, and
a row written before this existed carries no key — read every key with
.get.
Attributes
code: The code the entry was recorded under.value: The entry's own resolved value — a number for a quantity, a string for a free-text reading (a Snellen"20/40"). AvalueCodeableConceptcarries no value field of its own, so it reports itstext, elsedisplay, elsecode.unit: The entry's unit, when it stated one.comparator:"<","<=",">"or">="when the entry stated a limit rather than a measurement,Nonewhenvalueis the measurement itself. A below-detection result reports the detection limit as itsvalue, so without this a reader sees an undetectable troponin as a reading of exactly0.02.date: The entry's date as"%Y-%m-%d", when it stated one. Which reading qualified matters as much as the value: a window satisfied by a five-year-old measurement is a different fact about a patient than one satisfied last week.laterality:"L"or"R"when the entry resolves to exactly one eye,Nonewhen it is bilateral or indeterminate.scopesays whether the eye had to match the scan's; this says which eye was actually read, which a reviewer needs when both eyes were measured at one visit and only one of them qualified.scope:any_eyefor an entry qualifying regardless of laterality,study_eyeorfellow_eyefor one whose laterality had to include the scan eye or the other eye (and did) — the same distinctionCodeMatch.scopedraws.code_system: The code system ofcode, as the EHR recorded it. Not included if the EHR gives none.
Variables
- static
code : str
- static
code_system : str
- static
comparator : str | None
- static
date : str | None
- static
laterality : str | None
- static
scope : Literal['any_eye', 'study_eye', 'fellow_eye']
- static
unit : str | None
- static
value : float | str | None
MedicationDose
class MedicationDose(*args, **kwargs):One dose of a medication record, as its dosage instruction gives it.
Attributes
measurement: The amount of the dose. Not included if not recorded.frequency: How often the dose is given. Not included if not recorded.type:"ordered"for the prescriber's order, or"calculated"for the amount worked out for this patient. Not included if the EHR does not say.laterality: The eye that the dosage instruction is for,"L"or"R". Not included if the instruction does not say, or is for both eyes.
Variables
- static
frequency : DoseFrequency
- static
laterality : str
- static
measurement : DoseMeasurement
- static
type : str
MethodOutcome
class MethodOutcome( passed: ForwardRef('bool | None'), context: ForwardRef('str | None') = None, code_match: ForwardRef(''codeBlockAnchor[CodeMatchEvidence](/api/bitfount/steps/criteria_matching/core#codematchevidence)' | None') = None, matched_column: ForwardRef('str | None') = None, measured_value: ForwardRef('float | int | str | None') = None, definitive: ForwardRef('bool') = False, examined: ForwardRef(''codeBlockAnchor[CodeMatchEvidence](/api/bitfount/steps/criteria_matching/core#codematchevidence)' | None') = None, unknown_reason: ForwardRef(''codeBlockAnchor[UnknownReason](/api/bitfount/steps/criteria_matching/core#unknownreason)' | None') = None, appointments: ForwardRef(''codeBlockAnchor[AppointmentEvidence](/api/bitfount/steps/criteria_matching/core#appointmentevidence)' | None') = None, no_match: ForwardRef('bool') = False,):What a MethodFilter's per-row callable returns.
A NamedTuple with defaults, so the plain (eligible, context) tuple every
existing filter returns is still a valid return value and needs no change:
MethodFilter.evaluate_row normalises whatever it gets through
MethodOutcome(*result). A filter with more to report sets the later
fields.
Attributes
passed: The verdict —Nonefor unknown (e.g. the filter's data is absent for this row), which never becomespass.context: Human-readable runtime detail that cannot be regenerated from the filter's configuration (the report's context column renders this).code_match: The same detail structurally, for a code-list filter. Unlikecontext, this is persisted into the criterion's evidence and served by the patient API.matched_column: For a filter that reads more than one source column, the column this row's qualifying candidates came from. Only the observation filter sets it (it spansOBSERVATIONS_COLUMNandSUPPLIED_OBSERVATIONS_COLUMN); it is what letsbuild_criterion_outcomesstamp provenance per row instead of per filter.Nonewhen the filter reads one column, or when this row produced no candidates to attribute.measured_value: The scalar this row measured, for a filter whose verdict turns on a number the evidence should report (a distance, a width). ReachesCriterionOutcome.valuewhen there is nocode_match; a filter produces one or the other, never both.examined: The records the filter decided on, whatever the verdict. Unlikecode_match, it keeps a record that was read but did not qualify, such as a reading outside a value bound. Only the code-addressedcriteria_treeleaves set it.definitive: Set by a filter that reached this verdict deliberately while a required column is null — a measured absence settling the question rather than a failure to measure. It suppresses the "missing values" rewrite offailed_message, which otherwise reports such a row as unmeasured.unknown_reason: Why the filter could not decide, whenpassedisNoneand the filter knows the reason. Otherwise the filter'sexplain_unknowngives the reason.appointments: The appointments and encounters that an appointment leaf decided on, whatever the verdict. Only the appointment leaf sets it.no_match: Whether the filter read the row's records and none matched what it looks for.MethodFilter.no_match_reasonturns such a fail intounknown. Only thecriteria_treeEHR leaves set it.
Variables
appointments : AppointmentEvidence | None- Alias for field number 8
code_match : CodeMatchEvidence | None- Alias for field number 2
context : str | None- Alias for field number 1
definitive : bool- Alias for field number 5
examined : CodeMatchEvidence | None- Alias for field number 6
matched_column : str | None- Alias for field number 3
measured_value : float | int | str | None- Alias for field number 4
no_match : bool- Alias for field number 9
passed : bool | None- Alias for field number 0
unknown_reason : UnknownReason | None- Alias for field number 7
MultiScanEvidence
class MultiScanEvidence(**data: Any):What a multi_scan node read.
Arguments
peers: Every selected scan, in row order. Empty when none was selected and the node took itson_emptystate.determining_scan_id: The scan whose state matches the node's, latest by study date then scan id; its child outcomes are the ones served.Nonewhen no selected scan matches, or when the matching scan has no scan id.determining_index: The position inpeersof that same scan. Unlike the scan id it names the scan when it has no scan id.Nonewhen no selected scan matches.child_node_ids: The ids of the nodes of the node's child subtree. Their outcomes on the anchor's row are the determining scan's, not the anchor's own, so the anchor's measurements leave them out.
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
child_node_ids : list[str]
- static
determining_index : int | None
- static
determining_scan_id : str | None
- static
model_config
- static
peers : list[MultiScanPeerResult]
MultiScanPeerResult
class MultiScanPeerResult(**data: Any):One scan that a multi_scan node read, and its child's state there.
Arguments
identity: The scan's subject: patient, scan, date and eye.state: The node's child evaluated on this scan.
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.
ReviewReasons
class ReviewReasons(**data: Any):What a person must check, for each state that a node can resolve to.
A config writes the states by name, pass, fail and unknown. The node
is flagged for review with the reason for whichever state it resolves to.
Arguments
pass_: The reason when the node passes. Writtenpassin a config.fail: The reason when the node fails.unknown: The reason when the node cannot decide.
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 : str | None
- static
model_config
- static
pass_ : str | None
- static
unknown : str | None
Methods
for_state
def for_state(self, state: CriterionState) ‑> str | None:The reason for state, or None when this object sets none.
ServedReviewReasons
class ServedReviewReasons(*args, **kwargs):dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)
SubjectIdentity
class SubjectIdentity(**data: Any):Identity of the subject evaluated on one row.
Every field is already known to criteria_matching while it evaluates the
row. scan_id/study_date/laterality are None on the non-file-system
(EHR) grain, where a row is a patient rather than a scan.
Arguments
bitfount_patient_id: The Bitfount patient ID, orNonewhen the row has none. Absence isNonerather than the empty string it used to be: an ID is derived from a name and a date of birth, and a name that cannot be reduced to a given and a family name yields no ID (seebitfount.federated.algorithms.ophthalmology.dataframe_generation_extensions.name_id_key). An empty string is a value, and values match each other — pandas joins two rows sharing""as if they were one patient, and a consumer that forgets to check gets no complaint from the type checker.Nonemakes the absence a distinct state the checker enforces at every point of use.scan_id: The scan filename, orNoneon the EHR grain.study_date: The scan study date (YYYYMMDD), orNone.laterality: The scan laterality, orNone.name: Display name from the row (a fallback; EHR prefers its own lookup).mrns: Medical record number(s) found on the row.
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
bitfount_patient_id : str | None
- static
laterality : str | None
- static
model_config
- static
mrns : list[str]
- static
name : str | None
- static
scan_id : str | None
- static
study_date : str | None
TreeFinding
class TreeFinding(*args, **kwargs):One patient record that a leaf read. Each key is optional.
Attributes
measurement: The measured value. Not included if the code tells all (for example a smoking status).code: The code of the record. A measurement with no code, for example a scan measurement, has only thetextof what it measures. Not included if that is not known.date: The date of the record.date_window: The dates of a record that covers a period, such as a medication course. Set instead ofdate.doses: The doses of a medication record: the amount, and how often. One for each dose reading of each dosage instruction that applies to the leaf's eye.abatement_date: The date a condition abated, asYYYY-MM-DD. Not included if the record has none, or is not a condition.clinical_status: The FHIR clinical status of a condition. Not included if the record has none that is known, or is not a condition.laterality: The eye of the record,"L"or"R". Not included if the record is for both eyes, or if the eye is not known.review_reason: Why the leaf could not use this record, for example because its date is not recorded. A person must check it.
Variables
- static
abatement_date : str
- static
clinical_status : str
- static
code : TreeFindingCode
- static
date : str
- static
date_window : IsoDateWindow
- static
doses : list[MedicationDose]
- static
laterality : str
- static
measurement : TreeMeasurement
- static
review_reason : str
TreeFindingCode
class TreeFindingCode(*args, **kwargs):The code of a finding. Each key is optional.
Attributes
text: The display text of the finding. For a code, the code's display. For a measurement, what it measures, and for a scan measurement which eye: for example"CNV probability (study eye)".code: The code.code_system: The code system of the code.
TreeMeasurement
class TreeMeasurement(*args, **kwargs):A measured value of a finding.
Attributes
value: The measured value, for example7.2. A list or an object for a column that holds one.unit: The display unit of the value, for example"%". Not included if the value has no unit.comparator: The comparator that the record gives with the value, for example"<"for a result below a detection limit. Not included if the record gives none.
Variables
- static
comparator : str
- static
unit : str
- static
value : bool | int | float | str | list[typing.Any] | dict[str, typing.Any]
TreeNodeState
class TreeNodeState(*args, **kwds):The state of a node of the served criteria_tree.
The CriterionState values, and not_assessed for a not-analysed
criterion (a manual node, or a group or not of them), which Bitfount
does not check. not_assessed is never an evidence status: a not-analysed
criterion has no outcome. Subclasses str so members serialise straight
into JSON.
Ancestors
UnknownReason
class UnknownReason(*args, **kwargs):Why a criteria_tree node could not decide, for a person to read.
Attributes
code: The reason, from a fixed set, for a client to group or style by.text: The reason as a sentence, ready to show.
UnknownReasonCode
class UnknownReasonCode(*args, **kwds):Why a criteria_tree node could not decide, from a fixed set.
Ancestors
Variables
- static
ANALYSIS_NOT_RUN
- static
CHECK_FAILED
- static
EHR_MATCH_AMBIGUOUS
- static
EHR_NOT_CHECKED
- static
EHR_UNAVAILABLE
- static
EHR_UNSUPPORTED
- static
FLAGGED_MATCH
- static
FOVEA_NOT_LOCATED
- static
HISTORY_INCOMPLETE
- static
NOT_IN_EHR
- static
NOT_REQUESTED
- static
NOT_SUPPORTED
- static
NO_MATCHING_RECORD
- static
NO_OTHER_EYE_SCAN
- static
RECORDS_UNREADABLE
- static
RETINAL_LAYERS_NOT_FOUND
- static
SCAN_ANALYSIS_FAILED
- static
SCAN_EYE_UNKNOWN
- static
SCAN_NOT_ANALYSED
- static
SCAN_NO_RESULT
- static
SCAN_SCALE_MISSING
- static
SCAN_UNREADABLE
- static
VALUE_MISSING