Skip to main content

tree

The criteria_tree: its combinators, its node and leaf unions, and its evaluation.

  • The combinators (AndGroup, OrGroup, AtLeastGroup, NotGroup) and CriterionTreeNode, the union of every leaf type and combinator. CriterionLeaf is the union of the leaf types.
  • Walking a tree (iter_tree_nodes, iter_tree_leaves, the criterion numbers and groups, tree_depth).
  • evaluate_criterion_tree: one outcome per node, from the leaf outcomes, by the combine and score rules (_threshold_combine … _resolve_score).

Module​

Functions​

authored_criteria_tree​

def authored_criteria_tree(criteria_tree: CriterionTreeNode) ‑> dict[str, typing.Any]:

Get the tree as JSON, with only the keys that the config sets.

Arguments

  • criteria_tree: The configured tree.

Returns The tree as a JSON-safe dict. Defaults that the config does not set, and keys that it sets to null, are not included.

contains_manual​

def contains_manual(node: CriterionTreeNode) ‑> bool:

Whether any node in node is a manual node.

Arguments

  • node: The (sub)tree to check.

Returns True if node is, or has below it, a ManualCriterion.

evaluate_criterion_tree​

def evaluate_criterion_tree(    node: CriterionTreeNode,    leaf_outcomes: Mapping[str, CriterionOutcome],    node_outcomes: list[CriterionOutcome],    node_groups: Mapping[str, str | None] | None = None,    review_flags: list[str] | None = None,    rank_context: tuple[int, int] | None = None,    peers: PeerView | None = None,    negated: bool = False,) ‑> CriterionOutcome:

Recursively reduce one criteria_tree node into its outcome and score.

Dispatches by isinstance rather than by comparing node.node; each group class declares only its own valid fields. A leaf's outcome is looked up directly from leaf_outcomes (built by the filter pipeline, real grain/provenance already stamped). A combinator's outcome is synthesised by _combinator_outcome. Every node's outcome — leaf and combinator alike — is appended to node_outcomes before this call returns, so a caller can inspect every node's and every group's own state and source, not only the root's.

A multi_scan node evaluates its child on each of the anchor's peers instead (see _evaluate_multi_scan); the anchor's own outcomes for the leaves below it play no part.

A not-analysed child (see is_not_analysed) has no outcome. Directly under an and that no not above inverts, it is left out: it is assumed met, and a site checks it. Anywhere else it counts as unknown, because it could change the result: one option of an or or at_least could still satisfy the criterion, and under a not the assumption would turn into an exclusion.

Arguments

  • node: The (sub)tree to evaluate.
  • leaf_outcomes: Each leaf id's already-built CriterionOutcome (from the filter pipeline). Every criteria_tree leaf always produces a filter, and so an outcome, even when it degrades to an unknown one — a leaf id absent here is a caller error, and raises KeyError rather than degrading silently.
  • node_outcomes: Every node's own outcome, appended here in post-order (children before parents, root last) as this call recurses.
  • node_groups: Each node id's resolved (inherited) group, from iter_tree_nodes_with_resolved_group. None (the default) leaves every node's tree_group unset — the shape most tests of the combining rule itself need, without a caller building a group map that plays no part in the state/grain/provenance being checked.
  • review_flags: When passed, any node (leaf or group) whose review_reason sets a reason for its own resolved state (a plain
  • string: PASS only) has that reason appended, collected in the same walk as the boolean reduction. None (the default) skips collection entirely.
  • rank_context: (rank, group_size) if this node was assigned a rank by its parent, else None. Callers should not pass this; it is set on the recursive calls this function makes into its own children.
  • peers: The anchor row's peers, read by a multi_scan node. Required when the tree has one.
  • negated: Whether an odd number of not nodes sit above node. Callers should not pass this; it is set on the recursive calls.

Returns The node's own outcome (its combined state and resolved score, plus derived grain/provenance for a combinator).

evaluated_children​

The children of node that are evaluated, in order.

A not-analysed child (see is_not_analysed) is left out of its parent's verdict and score, so evaluation, scoring and telemetry use this list in place of a node's children. A leaf has none.

Arguments

  • node: An evaluated node.

Returns Its children without the not-analysed ones.

is_not_analysed​

def is_not_analysed(node: CriterionTreeNode) ‑> bool:

Whether node is a not-analysed subtree.

That is a manual node, or an and, or, at_least or not whose every child is itself not analysed. A not over a not-analysed child has no result to invert, so it is not analysed either. A multi_scan never is: the validator refuses a manual node under one.

Arguments

  • node: The (sub)tree to check.

Returns True if nothing in node is analysed.

iter_tree_leaves​

def iter_tree_leaves(    node: CriterionTreeNode,) ‑> Iterator[ColumnCriterion | CodeCriterion | ObservationCriterion | MedicationCriterion | AllergyCriterion | DeviceCriterion | AppointmentWindowCriterion | AliveCriterion]:

Depth-first leaves of a criteria_tree node.

Arguments

  • node: The (sub)tree to walk.

Returns An iterator over every leaf (CriterionLeaf) reachable from node.

iter_tree_nodes​

Depth-first every node (leaf or combinator) of a criteria_tree.

NotGroup and MultiScanGroup walk their single child; AndGroup/OrGroup/AtLeastGroup walk their children list.

Arguments

  • node: The (sub)tree to walk.

Returns An iterator over node itself and every node reachable from it.

iter_tree_nodes_with_criterion_number​

def iter_tree_nodes_with_criterion_number(    node: CriterionTreeNode,    inherited_type: CriterionType | None = None,    inherited_path: str = '',) ‑> Iterator[tuple[ColumnCriterion | CodeCriterion | ObservationCriterion | MedicationCriterion | AllergyCriterion | DeviceCriterion | AppointmentWindowCriterion | AliveCriterion | ManualCriterion | MultiScanGroup | AndGroup | OrGroup | AtLeastGroup | NotGroup, str | None]]:

Depth-first (node, criterion number) pairs.

The criterion number joins the item_number values on the path from the root, after I or E from the resolved criterion_type, for example E4a. It is the number AnnotatedTreeNode describes.

A node has a number only when it sets its own item_number and its criterion_type resolves. A node with no item_number of its own would repeat its ancestor's number, which does not identify it. Without a criterion_type, the digits alone do not make a protocol number.

item_number is not validated, so two nodes can have the same number.

Arguments

  • node: The (sub)tree to walk.
  • inherited_type: The criterion_type resolved from the ancestors. Callers should not pass this.
  • inherited_path: The item_number values of the ancestors, joined. Callers should not pass this.

Returns An iterator over (node, criterion number or None) for node and every node reachable from it.

iter_tree_nodes_with_resolved_group​

def iter_tree_nodes_with_resolved_group(    node: CriterionTreeNode,    inherited_group: str | None = None,) ‑> Iterator[tuple[ColumnCriterion | CodeCriterion | ObservationCriterion | MedicationCriterion | AllergyCriterion | DeviceCriterion | AppointmentWindowCriterion | AliveCriterion | ManualCriterion | MultiScanGroup | AndGroup | OrGroup | AtLeastGroup | NotGroup, str | None]]:

Depth-first (node, resolved group) pairs, resolving group by inheritance.

Every node — leaf or combinator — is yielded, unlike iter_tree_nodes' plain walk: a combinator's own outcome needs its resolved group exactly as a leaf's does, so both are resolved by the same walk here rather than a leaf-only one plus a second pass for combinators.

A node's resolved group is its own group when set, else the nearest ancestor's resolved group, else None when no ancestor sets one either. This is a pure function of the tree's own group fields: no node stores a parent reference, and nothing here mutates the tree. CriteriaMatchConfig's validator (_check_group_inheritance) separately guarantees no node overrides an ancestor's group with a different one, so in practice every descendant under one ancestor's group always resolves to that same value.

Arguments

  • node: The (sub)tree to walk.
  • inherited_group: The resolved group inherited from ancestors already visited. Callers should not pass this; it is set on the recursive calls this function makes into its own children.

Returns An iterator over (node, resolved_group) for node and every node reachable from it.

scored_children​

The evaluated children of node whose score counts in its own, in order.

A child with weight 0 is unweighted: it still decides node's state, through evaluated_children, but its score is left out of node's.

Arguments

  • node: An evaluated node.

Returns Its evaluated children without the unweighted ones.

tree_children​

The direct children of node, in order.

A not or multi_scan has its one child, an and, or or at_least its children, and any other node none. Every tree walk goes through this, so a new node type without children needs no change to the walks.

Arguments

  • node: A node of a criteria_tree.

Returns Its children.

tree_depth​

def tree_depth(node: CriterionTreeNode) ‑> int:

Longest path from node to any leaf, counting the leaf itself as 1.

Arguments

  • node: The (sub)tree to measure.

Returns The tree's depth, at least 1.

Global variables​

  • OnMatch - The state of a not whose child passes.

Classes​

AndGroup​

class AndGroup(**data: Any):

A criteria_tree node requiring every child to pass.

Arguments

  • children: The child nodes; at least one required.
  • review_reason: See ColumnCriterion.review_reason. Every child is necessary for an AndGroup to pass, so a flagged child that passes is always part of what produced the result.
  • combine: How this node's own score combines its children's scores when every child has passed (see evaluate_criterion_tree). "min" (default) takes the weakest child. "mean" blends children instead, weighted by each child's own weight.

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 combine : Literal['min', 'mean']
  • static model_config
  • static node : Literal['and']

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.

AtLeastGroup​

class AtLeastGroup(**data: Any):

A criteria_tree node requiring at least min_count children to pass.

Arguments

  • min_count: How many children must pass; must not exceed the number of children.
  • children: The child nodes; at least one required.
  • review_reason: See ColumnCriterion.review_reason.

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 model_config
  • static node : Literal['at_least']

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.

ManualCriterion​

class ManualCriterion(**data: Any):

A criteria_tree criterion that Bitfount does not analyse.

A protocol criterion that cannot be checked from the scan or EHR data, for example informed consent. It has only the fields that display it, so a config makes plain that nothing is analysed there. It has no filter and no outcome and no weight: it is served with the not_assessed state, and changes no verdict or score.

A manual node, or an and, or, at_least or not whose leaves are all manual, is a not-analysed subtree (see is_not_analysed). Such a subtree may sit under any node except a multi_scan. Its parent leaves it out: an or or at_least counts passes among its other children only, and no parent's score reads it (see evaluated_children).

Arguments

  • label: The criterion's short name. Required: without it the criterion shows nothing.
  • criterion_type: Whether it is an inclusion or an exclusion criterion.
  • item_number: This node's part of the protocol's criterion number.
  • trial_text: The protocol's wording.

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 label : str
  • static model_config
  • static node : Literal['manual']

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.

MultiScanGroup​

class MultiScanGroup(**data: Any):

A criteria_tree node evaluating its child on the patient's other scans.

The scan being judged is the anchor. select picks peers relative to it, the child is evaluated on each peer's own data, and quantifier combines the peers' results. The node's grain is multi_scan, whatever its children's. The child may hold only column leaves on scan measurements, with and/or/at_least/not around them.

Arguments

  • select: Which scans to read. fellow_eye: the opposite eye's scans.
  • quantifier: any passes if one selected scan passes; all if every selected scan passes. An unsettled scan makes either unknown unless the others already decide it.
  • on_empty: The state when no scan is selected, for example when the fellow eye has no scan in scope. Defaults to unknown.
  • child: The condition to evaluate on each selected scan.
  • review_reason: See ColumnCriterion.review_reason.

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 node : Literal['multi_scan']
  • static on_empty : Literal['unknown', 'pass', 'fail']
  • static quantifier : Literal['any', 'all']
  • static select : Literal['fellow_eye']

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.

NotGroup​

class NotGroup(**data: Any):

A criteria_tree node inverting its single child's state.

Arguments

  • child: The node to invert. pass and fail swap; unknown/na unchanged.
  • on_match: The state when child passes. "fail" (the default) excludes the patient. "unknown" makes a flagged exclusion: a person must verify the match before the patient is eligible. The node then gives the reason flagged_match, and the flag is child's own pass review reason, which the config validator requires. A not fails only when its child passes, so this unknown always means that the child matched.
  • review_reason: See ColumnCriterion.review_reason. Refused when on_match is "unknown": the flag belongs to child.

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 node : Literal['not']
  • static on_match : Literal['fail', 'unknown']
  • flags_match : bool - Whether a match of child makes this node unknown, not fail.

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.

OrGroup​

class OrGroup(**data: Any):

A criteria_tree node requiring at least one child to pass.

Arguments

  • children: The child nodes; at least one required.
  • review_reason: See ColumnCriterion.review_reason. Collected whenever this node passes, even if an unflagged sibling child also passes: flagging more than the minimum set of passing nodes is intentional, since missing a genuinely lower-priority match costs more than an unnecessary review.

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 node : Literal['or']

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.