Skip to main content

protocols

Structural protocols for objects passed into step tasks.

These Protocols describe the minimal interface that the DAG runner must satisfy when constructing and passing resource-like objects to Prefect tasks. Concrete implementations do not need to inherit from these — structural (duck-type) compatibility is sufficient.

Sub-modules​

model ModelResourceProtocol — any object that can load a Bitfount model. ehr EHRDataResource — concrete resource that queries an EHR provider (NextGen or FHIR R4) and returns EHRPatientResource records. EHRFetchOptions — which extra per-patient data to fetch alongside it. NO_EHR_RESOURCE_IDENTITY — the ehr hashing identity for a pod with no EHR configured.

Module​

Submodules​

Classes​

EHRDataResource​

class EHRDataResource(    hub: BitfountHub,    ehr_config: EHRConfig | None = None,    ehr_secrets: RefreshableJWT | None = None,    *,    knowledge_store: KnowledgeStore | None = None,):

Resource to allow connection to the EHR.

Built from the EHR configuration in the pod config. It holds one EHR connection (EHRDataService), through which tasks find patients by name and date of birth, by ID or by MRN, fetch their records, list the EHR's patients, and probe the EHR before a run.

Construct the resource for a single EHR provider.

The connection is built by build_ehr_data_service: a NextGenEHRConfig gets the NextGen service, which authenticates with the Hub's session; any other config whose provider ends in "r4" gets the FHIR R4 service. Anything else raises ValueError.

Arguments

  • hub: Bitfount Hub instance, whose session a NextGen connection authenticates with.
  • ehr_config: Provider configuration loaded from the pod config.
  • ehr_secrets: Externally-supplied JWT secrets for a FHIR R4 EHR. Not needed for SMARTBackendEHRConfig, which carries its own auth on the config object. May be None only when the config is SMART Backend, or when allow_no_ehr_secrets is set for a genuinely unauthenticated server.
  • knowledge_store: Where findings about the EHR server are kept; in memory for this connection when not given. Used by a FHIR R4 connection only.

Raises

  • ValueError: If ehr_config is None, if a NextGen config comes with no Hub, if base_url is missing on a FHIR R4 config, if the provider value is unrecognised, or if a FHIR R4 config has no usable credentials and allow_no_ehr_secrets is not set.

Methods​


check_availability​

def check_availability(self) ‑> EHRPreflightResult:

Establish whether this EHR can be reached, before any patient is queried.

The connection obtains a token and asks the FHIR server for its CapabilityStatement, as often as the preflight policy allows (EHRDataService.availability); both backends speak FHIR and differ only in where the token comes from.

The probe is a statement about the run, not about any patient: a patient the EHR has no record of is an answer, and answering is what this checks for.

Returns The verdict. available is False only when every attempt failed, so a single blip does not cost a run its EHR data.

fetch_patient​

def fetch_patient(    self,    patient_querier: PatientRecord,    *,    fetch_options: EHRFetchOptions = EHRFetchOptions(fetch_appointments=False, fetch_practitioner=False, observation_codes=None, observation_categories=None, supplementary_observation_codes=None),) ‑> EHRPatientResource:

Fetch the record of a patient a find_patient_by_* call accepted.

Arguments

  • patient_querier: The record the find call returned.
  • fetch_options: Forwarded to _get_patient_resource.

Returns The materialised EHRPatientResource.

find_patient_by_first_given_name​

def find_patient_by_first_given_name(    self,    given_words: Sequence[str],    *,    family: str | None,    dob: object,    sex: object = None,) ‑> PatientRecord:

Search by the first given name, accepting only the scan's patient.

The FHIR R4 name search prefix-matches any part of a name. NextGen's search, the patients born on the scan's date of birth filtered locally, substring-matches the family name and any one given name. Either way a search on the first given word alone can find someone else ("Mary" finds "Mary Beth" and "Maryanne", and on NextGen "Rosemary"). The hit is accepted only if one of its names has the scan's family name and exactly the scan's given names, and its date of birth is the scan's, as is its sex where both record one. Names are normalised as the BitfountPatientID name key is (see _name_words), and given names compared word by word. The record returned carries the accepted name entry's names, not the searched ones. No clinical data is fetched; pass the record to fetch_patient for that.

The search narrows the name search just made (narrows_last_search): on NextGen the candidates are those of the connection's last date of birth search when it was for the scan's date of birth, as it is right after the name search found nobody, so the retry makes no request (NextGenFHIRAPI.get_patient_entries_by_dob); otherwise it searches.

Arguments

  • given_words: The words of the scan's given name as written (see _name_parts); the search uses the first, and the identity check compares them normalised.
  • family: The scan's family name.
  • dob: The scan's date of birth.
  • sex: The scan's recorded sex, if any.

Returns The record for the accepted patient.

Raises

  • ValueError: If no given words are supplied.
  • NoMatchingPatientError: If no patient matches the search.
  • NonSpecificPatientError: If several patients match the search.
  • NoMatchingPatientError: Also, without searching, if the scan's date of birth is not a complete date.
  • IdentityMismatchError: If the patient found differs from the scan in date of birth, family name, given names or recorded sex, or lacks one of the first three.

find_patient_by_mrn​

def find_patient_by_mrn(    self,    mrn: str,    *,    expected_dob: object,    expected_family: str | None,    expected_sex: object = None,) ‑> PatientRecord:

Find a patient by MRN, accepting them only if they match the scan.

The identifier search is not scoped to an identifier system, and a site's imaging patient ID need not be the EHR's MRN, so the hit is checked against the scan's date of birth, family name and, where both record one, sex (_matching_name_entry, over every one of the hit's names). The record returned carries the accepted name entry's names. No clinical data is fetched; pass the record to fetch_patient for that.

On FHIR R4 the identifier is escaped for the search, so A12,B34 is one value and HOSP|123 the value HOSP|123, not value 123 in system HOSP. On NextGen it is passed as given, and only a patient holding it exactly as an MRN is a hit (NextGenFHIRAPI.get_patient_entry_by_mrn).

Arguments

  • mrn: The identifier to search on.
  • expected_dob: The scan's date of birth.
  • expected_family: The scan's family name.
  • expected_sex: The scan's recorded sex, if any.

Returns The record for the accepted patient.

Raises

  • ValueError: If the EHR cannot look patients up by MRN.
  • NoMatchingPatientError: If no patient holds the identifier.
  • NonSpecificPatientError: If several patients hold the identifier.
  • NoPatientIDError: If the patient found has no resource ID.
  • IdentityMismatchError: If the patient found differs from the scan in date of birth, family name or recorded sex, or lacks a date of birth or family name.

find_patient_by_name_dob​

def find_patient_by_name_dob(    self, given_name: str | None, family_name: str | None, patient_dob: str | date,) ‑> PatientRecord:

Find a single patient by demographic search, without fetching.

The search get_patient_info_by_name_dob makes, on the connection (EHRDataService.find_patient). The hit is not checked against the scan; its record carries the raw Patient resource (raw_patient). Pass the record to fetch_patient for the patient's clinical data.

Arguments

  • given_name: Patient's first/given name.
  • family_name: Patient's last/family name.
  • patient_dob: Date of birth, either as a date or an ISO-format string the backend can parse.

Returns The record for the patient found.

Raises

  • NoMatchingPatientError: Propagated from the backend when no patient matches the supplied demographics.

forbidden_resource_counts​

def forbidden_resource_counts(self) ‑> Mapping[str, int]:

HTTP 403 responses per FHIR resource type on this resource's connection.

Cumulative since the connection was built, so across every step of the run that shares this resource; take the difference across a step for its share.

Returns Resource type to count; empty for NextGen, which keeps none.

get_patient_info_by_id​

def get_patient_info_by_id(    self,    patient_id: str,    *,    fetch_options: EHRFetchOptions = EHRFetchOptions(fetch_appointments=False, fetch_practitioner=False, observation_codes=None, observation_categories=None, supplementary_observation_codes=None),) ‑> EHRPatientResource:

Read the patient with this EHR ID and normalise their record.

Arguments

  • patient_id: The EHR system's patient ID.
  • fetch_options: Forwarded to _get_patient_resource; see EHRFetchOptions.

get_patient_info_by_name_dob​

def get_patient_info_by_name_dob(    self,    given_name: str | None,    family_name: str | None,    patient_dob: str | date,    *,    fetch_options: EHRFetchOptions = EHRFetchOptions(fetch_appointments=False, fetch_practitioner=False, observation_codes=None, observation_categories=None, supplementary_observation_codes=None),) ‑> EHRPatientResource:

Look up a single patient by demographic search.

Finds the patient on the connection and normalises their record into an EHRPatientResource.

Arguments

  • given_name: Patient's first/given name.
  • family_name: Patient's last/family name.
  • patient_dob: Date of birth, either as a date or an ISO-format string the backend can parse.
  • fetch_options: Forwarded to _get_patient_resource; see EHRFetchOptions.

Returns The materialised EHRPatientResource. Code lists may be empty (or None on a GetPatientInfoError from the backend).

Raises

  • NoMatchingPatientError: Propagated from the backend when no patient matches the supplied demographics.

get_patient_lister​

def get_patient_lister(self) ‑> BaseEHRPatientLister:

A paginated patient-ID lister for this EHR, from the connection.

Raises

  • EHRConnectionError: If authentication has failed too often in a row for the run to go on.

reset_auth_budget​

def reset_auth_budget(self) ‑> None:

Give the connection its whole auth failure budget back.

Called at the start of each pass of patient lookups, or of a patient listing, so a pass that lost the EHR does not stop every later pass on this resource before it sends a request.

EHRFetchOptions​

class EHRFetchOptions(    fetch_appointments: bool = False,    fetch_practitioner: bool = False,    observation_codes: Sequence[tuple[str | None, str]] | None = None,    observation_categories: Sequence[str] | None = None,    supplementary_observation_codes: Sequence[tuple[str | None, str]] | None = None,):

Which extra per-patient EHR data to fetch, beyond the unfiltered code lists.

Condition/Procedure codes are always fetched unfiltered and matched against criteria locally afterwards — cheap, and every backend supports an unfiltered fetch. These don't work that way, each for its own reason, which is why they must be requested up front rather than filtered afterwards:

  • fetch_appointments gates an extra round-trip (previous appointments/encounters, next appointment) most flows don't need.
  • fetch_practitioner gates one extra round-trip for the patient's associated medical practitioner, which only display-oriented flows need.
  • observation_codes/observation_categories: Observations must be searched by an explicit code or category — at least one major FHIR backend (Epic) rejects an Observation search with neither.
  • supplementary_observation_codes: a best-effort code search alongside the two above, for observations a site may file under no core category. Run only when one of the two is, merged into their result, and its failure loses only what it alone would have found. On FHIR R4 the same codes also select the acuity readings read from the patient's documents (PatientRecord.get_document_acuity), merged the same way, for a provider whose profile reads them. When the observations hold a best-corrected reading for both eyes, the documents' CCDs are downloaded only if one may be newer, and the code search is skipped while the server is marked as serving acuity only in documents (_supplementary_acuity).

Variables​

  • fetch_appointments : bool
  • fetch_practitioner : bool

ModelResourceProtocol​

class ModelResourceProtocol(*args, **kwargs):

An object that can load a Bitfount model ready for inference.

Methods​


load_model​

def load_model(    self,    model_ref: Any,    *,    datastructure: DataStructure,    schema: BitfountSchema,    batch_size: int | None,) ‑> Any:

Load and return a model instance ready for inference.