Skip to main content

columns

Criteria on a named column of the scan or patient data, and the field catalog.

  • The column leaf (ColumnCriterion): a column's value meets an operator and value, compared the way its field's MatchStrategy says (a scalar, a collection, or a glob), at the grain the leaf names or the catalog gives. DerivedFromColumn compares against another column of the same row.
  • The flat config field column_criteria, which the same generic filters serve.
  • The field catalog (FieldSpec, aggregate_field_specs, ehr_field_specs, resolve_grain): each known column's grain and match strategy.
  • add_age_column, which derives the age column the age criteria read.

Module​

Functions​

add_age_column​

def add_age_column(    df: pd.DataFrame, dob_col: str = "Patient's Birth Date", age_col: str = 'Age (yrs)',) ‑> pandas.core.frame.DataFrame:

Add an age column to df based on a date-of-birth column.

If age_col already exists the dataframe is returned unchanged.

note

dob_col is converted in-place to UTC-aware datetime64 as a side-effect of parsing. Unparseable DOB values (e.g. de-identification placeholders like "XXXX") are coerced to NaT; the original string values are therefore lost after this call. Age is computed only for rows with a valid DOB and left as NA for the rest.

If DOB parsing raises OverflowError (e.g. DOB set to Timestamp.min as a placeholder), a timedelta-based fallback is used.

Returns The same dataframe with the extra age column.

age_filters​

def age_filters(    config: CriteriaMatchConfig, ctx: FilterBuildContext,) ‑> list[ColumnFilter | MethodFilter]:

Build the patient-age filters.

Arguments

  • config: The criteria-matching config.
  • ctx: What the filter builders share; unused here.

Returns One filter for each of these fields that the config sets.

aggregate_field_specs​

def aggregate_field_specs(    field_specs_lists: list[list[FieldSpec]],) ‑> dict[str, FieldSpec]:

Merge per-source FieldSpec lists into one {name: FieldSpec} catalog.

Later sources win on a name clash (last-wins), matching the left-merge order used when assembling the match frame.

Arguments

  • field_specs_lists: One FieldSpec list per source, in merge order.

Returns The merged {name: FieldSpec} catalog.

column_criteria_filters​

def column_criteria_filters(    config: CriteriaMatchConfig,    ctx: FilterBuildContext,    earlier_filters: list[ColumnFilter | MethodFilter],) ‑> list[ColumnFilter | MethodFilter]:

Build the filters of the generic column_criteria.

Each entry is resolved against the field catalog, and its grain comes from the catalog when the entry does not set one. An entry is skipped when an earlier, typed filter already reads its column, when it targets an EHR code column, or when it repeats an earlier entry.

Arguments

  • config: The criteria-matching config.
  • ctx: What the filter builders share.
  • earlier_filters: The filters built from the typed fields, which take precedence over an entry on the same column.

Returns One filter for each entry that is not skipped.

column_leaf_filter​

def column_leaf_filter(    leaf: ColumnCriterion, ctx: FilterBuildContext,) ‑> ColumnFilter | MethodFilter:

Build the filter of a criteria_tree column leaf.

Built with the same logic as column_criteria (catalog lookup, column canonicalisation, grain resolution, an illegal operator degrading to unknown). A leaf is never skipped, because that would change how many children its group has: a leaf on an EHR code column gets a filter that decides unknown instead.

Arguments

  • leaf: The leaf.
  • ctx: What the filter builders share.

Returns The leaf's filter.

ehr_field_specs​

def ehr_field_specs() ‑> list[FieldSpec]:

The matchable PATIENT-grain FieldSpecs the EHR patient-data channel contributes.

patient_data sources otherwise contribute nothing to the field catalog (_build_catalog only aggregates scan_metrics sources' field_specs()), so a generic column_criteria entry targeting an EHR column with no explicit grain fell through resolve_grain's catalog lookup and defaulted to SCAN even though the column's provenance is EHR — the grain=SCAN/provenance=EHR gating hole. Advertising AGE_COL, CONDITIONS_COLUMN, and PROCEDURES_COLUMN here as PATIENT grain closes it for those columns.

The two appointment-record columns hold lists of dicts, so a generic column_criteria membership test against them is not meaningful. They are advertised anyway so their grain resolves correctly for anyone who writes one; the typed appointment_history and current_patient_months config fields are the intended surface. NEXT_APPOINTMENT_COL is "str" because the catalog has no date dtype, which also withholds ordering operators from what is a formatted string.

Returns One FieldSpec each for AGE_COL ("int"); CONDITIONS_COLUMN, PROCEDURES_COLUMN, PREV_APPOINTMENTS_COL, and PREV_ENCOUNTERS_COL (all "collection"); and NEXT_APPOINTMENT_COL ("str"). All are CriterionGrain.PATIENT.

make_collection_membership_filter​

def make_collection_membership_filter(    *, column: str, values: list[str], inclusion: bool,) ‑> Callable[[pd.Series[Any]], tuple[bool | None, str | None]]:

Build a MethodFilter callable testing membership in a cell's collection.

Use when the matched cell holds a collection and the criterion asks whether that collection contains any wanted value — the value in cell test (the collection lives in the cell). Dispatched for a collection-dtype column (ops in / not in). Each member is compared directly as a string; no member attribute is inspected. values are matched literally or as * glob wildcards.

Arguments

  • column: Name of the column holding the per-row collection.
  • values: Patterns to match against; a single member match is sufficient.
  • inclusion: If True build an inclusion filter (a match makes the subject eligible); if False build an exclusion filter (a match makes the subject ineligible).

Returns A callable taking a row and returning (eligible, context), where eligible is None when the collection data is absent (unknown).

make_derived_from_column_filter​

def make_derived_from_column_filter(    column: str, op: str, derived: DerivedFromColumn,) ‑> Callable[[pd.Series[Any]], tuple[bool | None, str | None]]:

Build a filter comparing column against a DerivedFromColumn-resolved value.

Generalises make_n_scan_biomarker_filter's missing-data handling to any column/operator pair. column's own absence resolves UNKNOWN first — the row cannot be evaluated at all. This matches every other generic criterion's missing-column convention. divisor_column being missing, NaN, or 0 resolves to derived.on_unusable_divisor instead, since no resolved value can be computed at all. Whether that counts as PASS, FAIL, or UNKNOWN is the criterion's own call, not this function's — see DerivedFromColumn.

Arguments

  • column: The column being compared (the filter's own left-hand side).
  • op: The comparison operator, applied as column op resolved_value.
  • derived: The right-hand side's resolution spec.

Returns A row predicate returning (state, context).

make_scalar_match_filter​

def make_scalar_match_filter(    *, column: str, values: list[Any], negate: bool,) ‑> Callable[[pd.Series[Any]], tuple[bool | None, str | None]]:

Build a MethodFilter callable glob-matching a scalar string cell.

Use when the matched cell holds a single scalar and the criterion asks whether that scalar is one of the wanted values — the cell in values test (the collection lives in the config, not the cell). Dispatched for a str-dtype column carrying a * glob (ops == / != / in / not in); a plain *-less str comparison stays a vectorized ColumnFilter instead. The cell is coerced to str and matched against values as * globs (via split_literal_and_regex_patterns); a match makes the row eligible, and negate=True (!= / not in) inverts.

Arguments

  • column: The scalar column to read.
  • values: Glob patterns / literals to match against.
  • negate: Invert the match (!= / not in).

Returns A callable (row) -> (eligible, context).

match_strategy_for​

def match_strategy_for(    dtype: str, op: str, has_glob: bool = False,) ‑> MatchStrategy:

Which MatchStrategy handles a legal (dtype, op) pair.

Returns COLUMN (a vectorized ColumnFilter: numeric/bool comparisons, numeric membership via .isin, and *-less str equality/membership), SCALAR_MATCH (a per-row str glob MethodFilter), or COLLECTION (collection-cell membership via make_collection_membership_filter). A str column routes to COLUMN unless the value carries a * glob (has_glob), in which case the per-row matcher is required. Assumes the pair is already known legal (see ALLOWED_OPS_BY_DTYPE in bitfount.steps.types.operators).

Arguments

  • dtype: The column's catalogued dtype tag.
  • op: The criterion operator.
  • has_glob: Whether any criterion value contains a * wildcard (only consulted for str columns).

Returns The matching strategy for the pair.

resolve_grain​

def resolve_grain(    column: str,    catalog: dict[str, FieldSpec],    explicit: CriterionGrain | None,    provenance: CriterionProvenance | None = None,) ‑> CriterionGrain:

Resolve a column's grain: explicit > catalog > provenance > SCAN default.

When the catalog does not carry the column (only three EHR columns are catalogued, so any other EHR-produced column misses), the column's provenance is used as a last resort: an EHR-sourced column defaults to PATIENT grain rather than SCAN. Without this a grain=SCAN / provenance=EHR outcome is skipped by the scan-evidence reducer (EHR provenance) and by the patient reducer (SCAN grain) — it gates nothing.

Arguments

  • column: The target column name.
  • catalog: The aggregated field catalog.
  • explicit: A grain set on the criterion, or None.
  • provenance: The column's resolved provenance, or None if unknown.

Returns The resolved CriterionGrain.

Classes​

ColumnCriterion​

class ColumnCriterion(**data: Any):

A generic, column-addressed eligibility criterion.

The expandable escape hatch: match any produced column by name without a dedicated typed field. Prefer a typed CriteriaMatchConfig field when one exists for the column.

Arguments

  • column: The DataFrame column to match against.
  • op: Comparison operator applied as column op value. Symbols only — a deliberately narrower surface than the alias set a ColumnFilter accepts.
  • value: The threshold/target value, or a DerivedFromColumn spec resolving it from another column instead of a literal.
  • grain: scan or patient; when None, resolved from the field catalog. Not organ or multi_scan: a column is read from one row and has no laterality, so its verdict cannot depend on which eye is the study eye or on other scans. _reject_non_column_grain enforces this.
  • node: Discriminator identifying this as a column-type criteria_tree node; irrelevant outside a tree (every column_criteria entry also carries it, unused).

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

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.

DerivedFromColumn​

class DerivedFromColumn(**data: Any):

A ColumnCriterion.value resolved from another column, not a literal.

resolved = ceil(numerator / row[divisor_column]), clamped to minimum when minimum is set. Exists for a criterion whose bound is not a fixed value: the config author does not supply it directly — criteria_matching computes it per row, from a second column. n_scan_*_typical_width_micrometers is the existing example: it needs ceil(width / slice_thickness), and a plain literal value cannot express that. slice_thickness varies by device and protocol, so it cannot be a fixed config value either.

Arguments

  • numerator: The constant divided by the value in divisor_column to resolve the comparison bound.
  • divisor_column: The column read (from the same row) as the divisor.
  • round: How the division result is rounded before comparison. Only "ceil" is supported: the one existing use rounds up, since a partial unit never satisfies a "spans at least N of them" bound.
  • minimum: A floor applied to the resolved value after rounding, or None for no floor. A numerator of 0 would otherwise resolve to 0 (ceil(0 / x) == 0), making the comparison vacuous.
  • on_unusable_divisor: The state to resolve to when divisor_column is missing, NaN, or 0 — True (pass), False (fail), or None (unknown). No resolved value can be computed in that case. There is no correct default for every criterion: whether "unevaluable" means "don't know" or "don't exclude" depends on the specific criterion, not on this mechanism.

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 divisor_column : str
  • static minimum : float | None
  • static model_config
  • static numerator : float
  • static on_unusable_divisor : bool | None
  • static round : Literal['ceil']

FieldSpec​

class FieldSpec(**data: Any):

A single matchable field a source can contribute to criteria matching.

Arguments

  • name: The flat DataFrame column name a criterion targets.
  • dtype: A coarse type tag ("float", "int", "bool", "str").
  • unit: Human-readable display unit (e.g. "mm²"), or None when unitless. Carries the character a consumer should render; an ASCII fallback belongs to whichever sink cannot take it, not here.
  • grain: Whether the field is per-scan or per-patient. A field is never organ: a column has no laterality.

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 dtype : str
  • static model_config
  • static name : str
  • static unit : str | None

MatchStrategy​

class MatchStrategy(*args, **kwds):

How a generic column_criteria is matched against its column.

The dispatch discriminator _build_generic_filter branches on when turning a criterion into a concrete filter — it names which matching mechanism applies, not merely which factory is called. Orthogonal to CriterionKind (the filter-type an outcome carries, column vs method): both SCALAR_MATCH and COLLECTION build a MethodFilter, so this three-way choice does not collapse onto that two-way one. Subclasses str so it compares equal to the historical literal keys.

Variables​

  • static COLLECTION
  • static COLUMN
  • static SCALAR_MATCH