FHIR Helpers
FHIR utilities for HealthChain.
BundleConverterConfig
Bases: BaseModel
Configuration for FHIR Bundle to DataFrame conversion.
This configuration object controls which FHIR resources are processed and how they are converted to DataFrame columns for ML model deployment.
| ATTRIBUTE | DESCRIPTION |
|---|---|
resources |
List of FHIR resource types to include in the conversion
TYPE:
|
observation_aggregation |
How to aggregate multiple observation values
TYPE:
|
age_calculation |
Method for calculating patient age
TYPE:
|
event_date_source |
Which resource to extract event date from
TYPE:
|
event_date_strategy |
Which date to use when multiple dates exist
TYPE:
|
resource_options |
Resource-specific configuration options (extensible)
TYPE:
|
Example
config = BundleConverterConfig( ... resources=["Patient", "Observation", "Condition"], ... observation_aggregation="median" ... ) df = bundle_to_dataframe(bundle, config=config)
Source code in healthchain/fhir/dataframe.py
validate_resources(v)
classmethod
Validate that requested resources are supported and warn about unsupported ones.
Source code in healthchain/fhir/dataframe.py
add_coding_to_codeable_concept(codeable_concept, code, system, display=None)
Add a coding to an existing CodeableConcept.
Useful for adding standardized codes (e.g., SNOMED CT) to resources that already have codes from other systems (e.g., ICD-10).
| PARAMETER | DESCRIPTION |
|---|---|
codeable_concept
|
The CodeableConcept to add coding to
TYPE:
|
code
|
The code value from the code system
TYPE:
|
system
|
The code system URI
TYPE:
|
display
|
Optional display text for the code
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
CodeableConcept
|
The updated CodeableConcept with the new coding added
TYPE:
|
Example
Add SNOMED CT code to a condition that has ICD-10
condition_code = condition.code condition_code = add_coding_to_codeable_concept( ... condition_code, ... code="44054006", ... system="http://snomed.info/sct", ... display="Type 2 diabetes mellitus" ... )
Source code in healthchain/fhir/resourcehelpers.py
add_provenance_metadata(resource, source, tag_code=None, tag_display=None)
Add provenance metadata to a FHIR resource.
Adds source system identifier, timestamp, and optional processing tags to track data lineage and transformations for audit trails.
| PARAMETER | DESCRIPTION |
|---|---|
resource
|
The FHIR resource to annotate
TYPE:
|
source
|
Name of the source system (e.g., "epic", "cerner")
TYPE:
|
tag_code
|
Optional tag code for processing operations (e.g., "aggregated", "deduplicated")
TYPE:
|
tag_display
|
Optional display text for the tag
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Resource
|
The resource with added provenance metadata
TYPE:
|
Example
condition = create_condition(subject="Patient/123", code="E11.9") condition = add_provenance_metadata(condition, "epic", "aggregated", "Aggregated from source")
Source code in healthchain/fhir/resourcehelpers.py
add_resource(bundle, resource, full_url=None)
Add a resource to a bundle.
| PARAMETER | DESCRIPTION |
|---|---|
bundle
|
The bundle to add to
TYPE:
|
resource
|
The resource to add, e.g. Condition, MedicationStatement, AllergyIntolerance
TYPE:
|
full_url
|
Optional full URL for the resource
TYPE:
|
Source code in healthchain/fhir/bundlehelpers.py
bundle_to_dataframe(bundle, config=None)
Convert a FHIR Bundle to a pandas DataFrame.
Converts FHIR resources to a tabular format with one row per patient. Uses a configuration object to control which resources are processed and how.
| PARAMETER | DESCRIPTION |
|---|---|
bundle
|
FHIR Bundle resource (object or dict)
TYPE:
|
config
|
BundleConverterConfig object specifying conversion behavior. If None, uses default config (Patient + Observation with mean aggregation)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
DataFrame with one row per patient and columns for each feature |
Example
from healthchain.fhir.converters import BundleConverterConfig
Default behavior
df = bundle_to_dataframe(bundle)
Custom config
config = BundleConverterConfig( ... resources=["Patient", "Observation", "Condition"], ... observation_aggregation="median", ... age_calculation="event_date" ... ) df = bundle_to_dataframe(bundle, config=config)
Source code in healthchain/fhir/dataframe.py
calculate_age_from_birthdate(birth_date)
Calculate age in years from a birth date string.
| PARAMETER | DESCRIPTION |
|---|---|
birth_date
|
Birth date in ISO format (YYYY-MM-DD or full ISO datetime)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Optional[int]
|
Age in years, or None if birth date is invalid |
Source code in healthchain/fhir/utilities.py
calculate_age_from_event_date(birth_date, event_date)
Calculate age in years from birth date and event date (MIMIC-IV style).
Uses the formula: age = year(eventDate) - year(birthDate) This matches MIMIC-IV on FHIR de-identified age calculation.
| PARAMETER | DESCRIPTION |
|---|---|
birth_date
|
Birth date in ISO format (YYYY-MM-DD or full ISO datetime)
TYPE:
|
event_date
|
Event date in ISO format (YYYY-MM-DD or full ISO datetime)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Optional[int]
|
Age in years based on year difference, or None if dates are invalid |
Example
calculate_age_from_event_date("1990-06-15", "2020-03-10") 30
Source code in healthchain/fhir/utilities.py
convert_prefetch_to_fhir_objects(prefetch_dict)
Convert a dictionary of FHIR resource dicts to FHIR Resource objects.
Takes a prefetch dictionary where values may be either dict representations of FHIR resources or already instantiated FHIR Resource objects, and ensures all values are FHIR Resource objects.
| PARAMETER | DESCRIPTION |
|---|---|
prefetch_dict
|
Dictionary mapping keys to FHIR resource dicts or objects
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Dict[str, Resource]
|
Dict[str, Resource]: Dictionary with same keys but all values as FHIR Resource objects |
Example
prefetch = { ... "patient": {"resourceType": "Patient", "id": "123"}, ... "condition": Condition(id="456", ...) ... } fhir_objects = convert_prefetch_to_fhir_objects(prefetch) isinstance(fhir_objects["patient"], Patient) # True isinstance(fhir_objects["condition"], Condition) # True
Source code in healthchain/fhir/readers.py
count_resources(bundle)
Count resources by type in a bundle.
| PARAMETER | DESCRIPTION |
|---|---|
bundle
|
The FHIR Bundle to analyze
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, int]
|
Dictionary mapping resource type names to their counts. |
Example
|
{"Condition": 2, "MedicationStatement": 1, "Patient": 1}
TYPE:
|
Example
bundle = create_bundle() add_resource(bundle, create_condition(...)) add_resource(bundle, create_condition(...)) add_resource(bundle, create_medication_statement(...)) counts = count_resources(bundle) print(counts)
Source code in healthchain/fhir/bundlehelpers.py
create_allergy_intolerance(patient, code=None, display=None, system='http://snomed.info/sct')
Create a minimal active FHIR AllergyIntolerance. If you need to create a more complex allergy intolerance, use the FHIR AllergyIntolerance resource directly. https://build.fhir.org/allergyintolerance.html
| PARAMETER | DESCRIPTION |
|---|---|
patient
|
REQUIRED. Reference to the patient (e.g. "Patient/123")
TYPE:
|
code
|
The allergen code
TYPE:
|
display
|
The display name for the allergen
TYPE:
|
system
|
The code system (default: SNOMED CT)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
AllergyIntolerance
|
A FHIR AllergyIntolerance resource with an auto-generated ID prefixed with 'hc-'
TYPE:
|
Source code in healthchain/fhir/resourcehelpers.py
create_bundle(bundle_type='collection')
Create an empty FHIR Bundle. https://www.hl7.org/fhir/bundle.html
| PARAMETER | DESCRIPTION |
|---|---|
bundle_type
|
The type of bundle (default: collection) Valid types: document, message, transaction, transaction-response, batch, batch-response, history, searchset, collection
TYPE:
|
Source code in healthchain/fhir/bundlehelpers.py
create_condition(subject, clinical_status='active', code=None, display=None, system='http://snomed.info/sct')
Create a minimal active FHIR Condition. If you need to create a more complex condition, use the FHIR Condition resource directly. https://build.fhir.org/condition.html
| PARAMETER | DESCRIPTION |
|---|---|
subject
|
REQUIRED. Reference to the patient (e.g. "Patient/123")
TYPE:
|
clinical_status
|
REQUIRED. Clinical status (default: active)
TYPE:
|
code
|
The condition code
TYPE:
|
display
|
The display name for the condition
TYPE:
|
system
|
The code system (default: SNOMED CT)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Condition
|
A FHIR Condition resource with an auto-generated ID prefixed with 'hc-'
TYPE:
|
Source code in healthchain/fhir/resourcehelpers.py
create_document_reference(data=None, url=None, content_type=None, status='current', description='DocumentReference created by HealthChain', attachment_title='Attachment created by HealthChain')
Create a minimal FHIR DocumentReference. If you need to create a more complex document reference, use the FHIR DocumentReference resource directly. https://build.fhir.org/documentreference.html
| PARAMETER | DESCRIPTION |
|---|---|
data
|
The data content of the document attachment
TYPE:
|
url
|
URL where the document can be accessed
TYPE:
|
content_type
|
MIME type of the document (e.g. "application/pdf", "text/xml", "image/png")
TYPE:
|
status
|
REQUIRED. Status of the document reference (default: current)
TYPE:
|
description
|
Description of the document reference
TYPE:
|
attachment_title
|
Title for the document attachment
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DocumentReference
|
A FHIR DocumentReference resource with an auto-generated ID prefixed with 'hc-'
TYPE:
|
Source code in healthchain/fhir/resourcehelpers.py
create_document_reference_content(attachment_data=None, url=None, content_type='text/plain', language='en-US', title=None, **kwargs)
Create a FHIR DocumentReferenceContent object.
Creates a DocumentReferenceContent structure that can be added to a DocumentReference. Either attachment_data or url must be provided. If attachment_data is provided, it will be base64 encoded automatically.
| PARAMETER | DESCRIPTION |
|---|---|
attachment_data
|
The content data (text that will be base64 encoded)
TYPE:
|
url
|
URL where the content can be accessed
TYPE:
|
content_type
|
MIME type (e.g., 'text/plain', 'text/html', 'application/pdf') (default: text/plain)
TYPE:
|
language
|
Language code (default: en-US)
TYPE:
|
title
|
Optional title for the content (default: "Attachment created by HealthChain")
TYPE:
|
**kwargs
|
Additional DocumentReferenceContent fields (e.g., format, profile)
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Dict[str, Any]
|
Dict[str, Any]: A FHIR DocumentReferenceContent dictionary with attachment and optional language |
Example
Create content with inline data
content = create_document_reference_content( ... attachment_data="Patient presents with fever...", ... content_type="text/plain", ... title="Clinical Note" ... )
Create content with URL reference
content = create_document_reference_content( ... url="https://example.com/document.pdf", ... content_type="application/pdf", ... title="Lab Report" ... )
Add content to a DocumentReference
doc_ref = DocumentReference( ... id="doc-1", ... status="current", ... content=[content] ... )
Source code in healthchain/fhir/resourcehelpers.py
create_medication_statement(subject, status='recorded', code=None, display=None, system='http://snomed.info/sct')
Create a minimal recorded FHIR MedicationStatement. If you need to create a more complex medication statement, use the FHIR MedicationStatement resource directly. https://build.fhir.org/medicationstatement.html
| PARAMETER | DESCRIPTION |
|---|---|
subject
|
REQUIRED. Reference to the patient (e.g. "Patient/123")
TYPE:
|
status
|
REQUIRED. Status of the medication (default: recorded)
TYPE:
|
code
|
The medication code
TYPE:
|
display
|
The display name for the medication
TYPE:
|
system
|
The code system (default: SNOMED CT)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MedicationStatement
|
A FHIR MedicationStatement resource with an auto-generated ID prefixed with 'hc-'
TYPE:
|
Source code in healthchain/fhir/resourcehelpers.py
create_patient(gender=None, birth_date=None, identifier=None, identifier_system='http://hospital.example.org')
Create a minimal FHIR Patient resource with basic gender and birthdate If you need to create a more complex patient, use the FHIR Patient resource directly https://hl7.org/fhir/patient.html (No required fields).
| PARAMETER | DESCRIPTION |
|---|---|
gender
|
Administrative gender (male, female, other, unknown)
TYPE:
|
birth_date
|
Birth date in YYYY-MM-DD format
TYPE:
|
identifier
|
Optional identifier value for the patient (e.g., MRN)
TYPE:
|
identifier_system
|
The system for the identifier (default: "http://hospital.example.org")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Patient
|
A FHIR Patient resource with an auto-generated ID prefixed with 'hc-'
TYPE:
|
Source code in healthchain/fhir/resourcehelpers.py
create_resource_from_dict(resource_dict, resource_type)
Create a FHIR resource instance from a dictionary
| PARAMETER | DESCRIPTION |
|---|---|
resource_dict
|
Dictionary representation of the resource
TYPE:
|
resource_type
|
Type of FHIR resource to create
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Optional[Resource]
|
Optional[Resource]: FHIR resource instance or None if creation failed |
Source code in healthchain/fhir/readers.py
create_risk_assessment_from_prediction(subject, prediction, status='final', method=None, basis=None, comment=None, occurrence_datetime=None)
Create a FHIR RiskAssessment from ML model prediction output. If you need to create a more complex risk assessment, use the FHIR RiskAssessment resource directly. https://hl7.org/fhir/riskassessment.html
| PARAMETER | DESCRIPTION |
|---|---|
subject
|
REQUIRED. Reference to the patient (e.g. "Patient/123")
TYPE:
|
prediction
|
Dictionary containing prediction details with keys: - outcome: CodeableConcept or dict with code, display, system for the predicted outcome - probability: float between 0 and 1 representing the risk probability - qualitative_risk: Optional str indicating risk level (e.g., "high", "moderate", "low")
TYPE:
|
status
|
REQUIRED. The status of the assessment (default: "final")
TYPE:
|
method
|
Optional CodeableConcept describing the assessment method/model used
TYPE:
|
basis
|
Optional list of References to observations or other resources used as input
TYPE:
|
comment
|
Optional text comment about the assessment
TYPE:
|
occurrence_datetime
|
When the assessment was made (ISO format). Uses current time if not provided.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RiskAssessment
|
A FHIR RiskAssessment resource with an auto-generated ID prefixed with 'hc-'
TYPE:
|
Example
prediction = { ... "outcome": {"code": "A41.9", "display": "Sepsis", "system": "http://hl7.org/fhir/sid/icd-10"}, ... "probability": 0.85, ... "qualitative_risk": "high" ... } risk = create_risk_assessment("Patient/123", prediction)
Source code in healthchain/fhir/resourcehelpers.py
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 | |
create_single_attachment(content_type=None, data=None, url=None, title='Attachment created by HealthChain')
Create a minimal FHIR Attachment.
Creates a FHIR Attachment resource with basic fields. Either data or url should be provided. If data is provided, it will be base64 encoded.
| PARAMETER | DESCRIPTION |
|---|---|
content_type
|
The MIME type of the content
TYPE:
|
data
|
The actual data content to be base64 encoded
TYPE:
|
url
|
The URL where the data can be found
TYPE:
|
title
|
A title for the attachment (default: "Attachment created by HealthChain")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Attachment
|
A FHIR Attachment resource with basic metadata and content
TYPE:
|
Source code in healthchain/fhir/elementhelpers.py
create_single_codeable_concept(code, display=None, system='http://snomed.info/sct')
Create a minimal FHIR CodeableConcept with a single coding.
| PARAMETER | DESCRIPTION |
|---|---|
code
|
REQUIRED. The code value from the code system
TYPE:
|
display
|
The display name for the code
TYPE:
|
system
|
The code system (default: SNOMED CT)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
CodeableConcept
|
A FHIR CodeableConcept resource with a single coding
TYPE:
|
Source code in healthchain/fhir/elementhelpers.py
create_single_reaction(code, display=None, system='http://snomed.info/sct', severity=None)
Create a minimal FHIR Reaction with a single coding.
Creates a FHIR Reaction object with a single manifestation coding. The manifestation describes the clinical reaction that was observed. The severity indicates how severe the reaction was.
| PARAMETER | DESCRIPTION |
|---|---|
code
|
REQUIRED. The code value from the code system representing the reaction manifestation
TYPE:
|
display
|
The display name for the manifestation code
TYPE:
|
system
|
The code system for the manifestation code (default: SNOMED CT)
TYPE:
|
severity
|
The severity of the reaction (mild, moderate, severe)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[Dict[str, Any]]
|
A list containing a single FHIR Reaction dictionary with manifestation and severity fields |
Source code in healthchain/fhir/elementhelpers.py
create_value_quantity_observation(code, value, unit, status='final', subject=None, system='http://loinc.org', display=None, effective_datetime=None)
Create a minimal FHIR Observation for vital signs or laboratory values. If you need to create a more complex observation, use the FHIR Observation resource directly. https://hl7.org/fhir/observation.html
| PARAMETER | DESCRIPTION |
|---|---|
status
|
REQUIRED. The status of the observation (default: "final")
TYPE:
|
code
|
REQUIRED. The observation code (e.g., LOINC code for the measurement)
TYPE:
|
value
|
The numeric value of the observation
TYPE:
|
unit
|
The unit of measure (e.g., "beats/min", "mg/dL")
TYPE:
|
system
|
The code system for the observation code (default: LOINC)
TYPE:
|
display
|
The display name for the observation code
TYPE:
|
effective_datetime
|
When the observation was made (ISO format). Uses current time if not provided.
TYPE:
|
subject
|
Reference to the patient (e.g. "Patient/123")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Observation
|
A FHIR Observation resource with an auto-generated ID prefixed with 'hc-'
TYPE:
|
Source code in healthchain/fhir/resourcehelpers.py
encode_gender(gender)
Encode gender as integer for ML models.
Standard encoding: Male=1, Female=0, Other/Unknown=None
| PARAMETER | DESCRIPTION |
|---|---|
gender
|
Gender string (case-insensitive)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Optional[int]
|
Encoded gender (1 for male, 0 for female, None for other/unknown) |
Source code in healthchain/fhir/utilities.py
extract_resources(bundle, resource_type)
Remove resources of a given type from a bundle and return them.
Useful for extracting and separating specific resource types (e.g., OperationOutcome) from a FHIR Bundle, modifying the bundle in place.
| PARAMETER | DESCRIPTION |
|---|---|
bundle
|
The FHIR Bundle to process (modified in place)
TYPE:
|
resource_type
|
The FHIR resource class or string name to extract (e.g., OperationOutcome or "OperationOutcome")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[Resource]
|
List[Resource]: All resources of the specified type that were in the bundle |
Source code in healthchain/fhir/bundlehelpers.py
get_resource_info(resource_type)
Get detailed information about a supported resource type.
| PARAMETER | DESCRIPTION |
|---|---|
resource_type
|
FHIR resource type name
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Dict[str, Any]
|
Dictionary with resource handler information, or empty dict if unsupported |
Example
info = get_resource_info("Observation") print(info["description"]) 'Clinical observations (vitals, labs)'
Source code in healthchain/fhir/dataframe.py
get_resources(bundle, resource_type)
Get all resources of a specific type from a bundle.
| PARAMETER | DESCRIPTION |
|---|---|
bundle
|
The bundle to search
TYPE:
|
resource_type
|
String name of the resource type (e.g. "Condition") or the type itself
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[Resource]
|
List of resources of the specified type |
Example
bundle = create_bundle()
Using string identifier
conditions = get_resources(bundle, "Condition") medications = get_resources(bundle, "MedicationStatement") allergies = get_resources(bundle, "AllergyIntolerance")
Or using type directly
from fhir.resources.condition import Condition conditions = get_resources(bundle, Condition)
Source code in healthchain/fhir/bundlehelpers.py
get_supported_resources()
Get list of supported FHIR resource types.
| RETURNS | DESCRIPTION |
|---|---|
List[str]
|
List of resource type names that can be converted to DataFrame columns |
Example
resources = get_supported_resources() print(resources) ['Patient', 'Observation', 'Condition', 'MedicationStatement']
Source code in healthchain/fhir/dataframe.py
merge_bundles(bundles, bundle_type='collection', deduplicate=False, dedupe_key='id')
Merge multiple FHIR bundles into a single bundle.
Combines entries from multiple bundles while preserving resource metadata. Useful for aggregating search results from multiple FHIR sources.
| PARAMETER | DESCRIPTION |
|---|---|
bundles
|
List of bundles to merge
TYPE:
|
bundle_type
|
Type for the merged bundle (default: "collection")
TYPE:
|
deduplicate
|
If True, remove duplicate resources based on dedupe_key
TYPE:
|
dedupe_key
|
Resource attribute to use for deduplication (default: "id")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Bundle
|
A new bundle containing all entries from input bundles |
Example
Merge search results from multiple sources
epic_bundle = gateway.search(Condition, {"patient": "123"}, "epic") cerner_bundle = gateway.search(Condition, {"patient": "123"}, "cerner") merged = merge_bundles([epic_bundle, cerner_bundle], deduplicate=True)
Use in Document workflow
doc = Document(data=merged) doc.fhir.bundle # Contains all conditions from both sources
Source code in healthchain/fhir/bundlehelpers.py
prefetch_to_bundle(prefetch)
Flatten CDS Hooks prefetch into a collection Bundle dict.
Converts the keyed prefetch format (used in CDS Hooks) into a flat bundle suitable for Dataset.from_fhir_bundle().
| PARAMETER | DESCRIPTION |
|---|---|
prefetch
|
CDS Hooks prefetch dict with format: {"patient": {...}, "observations": {"entry": [...]}, ...}
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Dict[str, Any]
|
Bundle dict with type "collection" and flattened entries |
Example
prefetch = request.prefetch bundle = prefetch_to_bundle(prefetch) dataset = Dataset.from_fhir_bundle(bundle, schema=schema)
Source code in healthchain/fhir/readers.py
print_supported_resources()
Print user-friendly list of supported FHIR resources for conversion.
Example
from healthchain.fhir.converters import print_supported_resources print_supported_resources() Supported FHIR Resources for ML Dataset Conversion:
✓ Patient Patient demographics (age, gender) Columns: age, gender ...
Source code in healthchain/fhir/dataframe.py
read_content_attachment(document_reference, include_data=True)
Read the attachments in a human readable format from a FHIR DocumentReference content field.
| PARAMETER | DESCRIPTION |
|---|---|
document_reference
|
The FHIR DocumentReference resource
TYPE:
|
include_data
|
Whether to include the data of the attachments. If true, the data will be also be decoded (default: True)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Optional[List[Dict[str, Any]]]
|
Optional[List[Dict[str, Any]]]: List of dictionaries containing attachment data and metadata, or None if no attachments are found: [ { "data": str, "metadata": Dict[str, Any] } ] |
Source code in healthchain/fhir/readers.py
set_condition_category(condition, category)
Set the category of a FHIR Condition to either 'problem-list-item' or 'encounter-diagnosis'.
| PARAMETER | DESCRIPTION |
|---|---|
condition
|
The FHIR Condition resource to modify
TYPE:
|
category
|
The category to set. Must be 'problem-list-item' or 'encounter-diagnosis'.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Condition
|
The modified FHIR Condition resource with the specified category set
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the category is not one of the allowed values. |
Source code in healthchain/fhir/resourcehelpers.py
set_resources(bundle, resources, resource_type, replace=True)
Set resources of a specific type in the bundle.
| PARAMETER | DESCRIPTION |
|---|---|
bundle
|
The bundle to modify
TYPE:
|
resources
|
The new resources to add
TYPE:
|
resource_type
|
String name of the resource type (e.g. "Condition") or the type itself
TYPE:
|
replace
|
If True, remove existing resources of this type before adding new ones. If False, append new resources to existing ones. Defaults to True.
TYPE:
|
Example
bundle = create_bundle()
Append to existing resources (default behavior)
set_resources(bundle, [condition1, condition2], "Condition") set_resources(bundle, [medication1], "MedicationStatement")
Replace existing resources
set_resources(bundle, [condition3], "Condition", replace=True)
Or using type directly
from fhir.resources.condition import Condition set_resources(bundle, [condition1, condition2], Condition)
Source code in healthchain/fhir/bundlehelpers.py
bundlehelpers
Helper functions for working with FHIR Bundles. Patterns: - create_(): create a new FHIR bundle - add_(): add a resource to a bundle - get_(): get resources from a bundle - set_(): set resources in a bundle - merge_(): merge multiple bundles into a single bundle - extract_(): extract resources from a bundle
add_resource(bundle, resource, full_url=None)
Add a resource to a bundle.
| PARAMETER | DESCRIPTION |
|---|---|
bundle
|
The bundle to add to
TYPE:
|
resource
|
The resource to add, e.g. Condition, MedicationStatement, AllergyIntolerance
TYPE:
|
full_url
|
Optional full URL for the resource
TYPE:
|
Source code in healthchain/fhir/bundlehelpers.py
count_resources(bundle)
Count resources by type in a bundle.
| PARAMETER | DESCRIPTION |
|---|---|
bundle
|
The FHIR Bundle to analyze
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, int]
|
Dictionary mapping resource type names to their counts. |
Example
|
{"Condition": 2, "MedicationStatement": 1, "Patient": 1}
TYPE:
|
Example
bundle = create_bundle() add_resource(bundle, create_condition(...)) add_resource(bundle, create_condition(...)) add_resource(bundle, create_medication_statement(...)) counts = count_resources(bundle) print(counts)
Source code in healthchain/fhir/bundlehelpers.py
create_bundle(bundle_type='collection')
Create an empty FHIR Bundle. https://www.hl7.org/fhir/bundle.html
| PARAMETER | DESCRIPTION |
|---|---|
bundle_type
|
The type of bundle (default: collection) Valid types: document, message, transaction, transaction-response, batch, batch-response, history, searchset, collection
TYPE:
|
Source code in healthchain/fhir/bundlehelpers.py
extract_resources(bundle, resource_type)
Remove resources of a given type from a bundle and return them.
Useful for extracting and separating specific resource types (e.g., OperationOutcome) from a FHIR Bundle, modifying the bundle in place.
| PARAMETER | DESCRIPTION |
|---|---|
bundle
|
The FHIR Bundle to process (modified in place)
TYPE:
|
resource_type
|
The FHIR resource class or string name to extract (e.g., OperationOutcome or "OperationOutcome")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[Resource]
|
List[Resource]: All resources of the specified type that were in the bundle |
Source code in healthchain/fhir/bundlehelpers.py
get_resource_type(resource_type)
Get the resource type class from string or type.
| PARAMETER | DESCRIPTION |
|---|---|
resource_type
|
String name of the resource type (e.g. "Condition") or the type itself
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Type[Resource]
|
The resource type class |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the resource type is not supported or cannot be imported |
Source code in healthchain/fhir/bundlehelpers.py
get_resources(bundle, resource_type)
Get all resources of a specific type from a bundle.
| PARAMETER | DESCRIPTION |
|---|---|
bundle
|
The bundle to search
TYPE:
|
resource_type
|
String name of the resource type (e.g. "Condition") or the type itself
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[Resource]
|
List of resources of the specified type |
Example
bundle = create_bundle()
Using string identifier
conditions = get_resources(bundle, "Condition") medications = get_resources(bundle, "MedicationStatement") allergies = get_resources(bundle, "AllergyIntolerance")
Or using type directly
from fhir.resources.condition import Condition conditions = get_resources(bundle, Condition)
Source code in healthchain/fhir/bundlehelpers.py
merge_bundles(bundles, bundle_type='collection', deduplicate=False, dedupe_key='id')
Merge multiple FHIR bundles into a single bundle.
Combines entries from multiple bundles while preserving resource metadata. Useful for aggregating search results from multiple FHIR sources.
| PARAMETER | DESCRIPTION |
|---|---|
bundles
|
List of bundles to merge
TYPE:
|
bundle_type
|
Type for the merged bundle (default: "collection")
TYPE:
|
deduplicate
|
If True, remove duplicate resources based on dedupe_key
TYPE:
|
dedupe_key
|
Resource attribute to use for deduplication (default: "id")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Bundle
|
A new bundle containing all entries from input bundles |
Example
Merge search results from multiple sources
epic_bundle = gateway.search(Condition, {"patient": "123"}, "epic") cerner_bundle = gateway.search(Condition, {"patient": "123"}, "cerner") merged = merge_bundles([epic_bundle, cerner_bundle], deduplicate=True)
Use in Document workflow
doc = Document(data=merged) doc.fhir.bundle # Contains all conditions from both sources
Source code in healthchain/fhir/bundlehelpers.py
set_resources(bundle, resources, resource_type, replace=True)
Set resources of a specific type in the bundle.
| PARAMETER | DESCRIPTION |
|---|---|
bundle
|
The bundle to modify
TYPE:
|
resources
|
The new resources to add
TYPE:
|
resource_type
|
String name of the resource type (e.g. "Condition") or the type itself
TYPE:
|
replace
|
If True, remove existing resources of this type before adding new ones. If False, append new resources to existing ones. Defaults to True.
TYPE:
|
Example
bundle = create_bundle()
Append to existing resources (default behavior)
set_resources(bundle, [condition1, condition2], "Condition") set_resources(bundle, [medication1], "MedicationStatement")
Replace existing resources
set_resources(bundle, [condition3], "Condition", replace=True)
Or using type directly
from fhir.resources.condition import Condition set_resources(bundle, [condition1, condition2], Condition)
Source code in healthchain/fhir/bundlehelpers.py
dataframe
FHIR to DataFrame converters.
This module provides generic functions to convert FHIR Bundles to pandas DataFrames for analysis and ML model deployment.
In instances where there are multiple codes present for a single resource, the first code is used as the primary code.
BundleConverterConfig
Bases: BaseModel
Configuration for FHIR Bundle to DataFrame conversion.
This configuration object controls which FHIR resources are processed and how they are converted to DataFrame columns for ML model deployment.
| ATTRIBUTE | DESCRIPTION |
|---|---|
resources |
List of FHIR resource types to include in the conversion
TYPE:
|
observation_aggregation |
How to aggregate multiple observation values
TYPE:
|
age_calculation |
Method for calculating patient age
TYPE:
|
event_date_source |
Which resource to extract event date from
TYPE:
|
event_date_strategy |
Which date to use when multiple dates exist
TYPE:
|
resource_options |
Resource-specific configuration options (extensible)
TYPE:
|
Example
config = BundleConverterConfig( ... resources=["Patient", "Observation", "Condition"], ... observation_aggregation="median" ... ) df = bundle_to_dataframe(bundle, config=config)
Source code in healthchain/fhir/dataframe.py
validate_resources(v)
classmethod
Validate that requested resources are supported and warn about unsupported ones.
Source code in healthchain/fhir/dataframe.py
bundle_to_dataframe(bundle, config=None)
Convert a FHIR Bundle to a pandas DataFrame.
Converts FHIR resources to a tabular format with one row per patient. Uses a configuration object to control which resources are processed and how.
| PARAMETER | DESCRIPTION |
|---|---|
bundle
|
FHIR Bundle resource (object or dict)
TYPE:
|
config
|
BundleConverterConfig object specifying conversion behavior. If None, uses default config (Patient + Observation with mean aggregation)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
DataFrame with one row per patient and columns for each feature |
Example
from healthchain.fhir.converters import BundleConverterConfig
Default behavior
df = bundle_to_dataframe(bundle)
Custom config
config = BundleConverterConfig( ... resources=["Patient", "Observation", "Condition"], ... observation_aggregation="median", ... age_calculation="event_date" ... ) df = bundle_to_dataframe(bundle, config=config)
Source code in healthchain/fhir/dataframe.py
extract_event_date(resources, source='Observation', strategy='earliest')
Extract event date from patient resources for age calculation.
Used primarily for MIMIC-IV on FHIR datasets where age is calculated based on event dates rather than current date.
| PARAMETER | DESCRIPTION |
|---|---|
resources
|
Dictionary of patient resources (from group_bundle_by_patient)
TYPE:
|
source
|
Which resource type to extract date from ("Observation" or "Encounter")
TYPE:
|
strategy
|
Which date to use ("earliest", "latest", "first")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Optional[str]
|
Event date in ISO format, or None if no suitable date found |
Example
resources = {"observations": [obs1, obs2], "encounters": [enc1]} event_date = extract_event_date(resources, source="Observation", strategy="earliest")
Source code in healthchain/fhir/dataframe.py
extract_observation_value(observation)
Extract numeric value from an Observation dict.
Handles different value types (valueQuantity, valueInteger, valueString) and attempts to convert to float.
Source code in healthchain/fhir/dataframe.py
get_resource_info(resource_type)
Get detailed information about a supported resource type.
| PARAMETER | DESCRIPTION |
|---|---|
resource_type
|
FHIR resource type name
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Dict[str, Any]
|
Dictionary with resource handler information, or empty dict if unsupported |
Example
info = get_resource_info("Observation") print(info["description"]) 'Clinical observations (vitals, labs)'
Source code in healthchain/fhir/dataframe.py
get_supported_resources()
Get list of supported FHIR resource types.
| RETURNS | DESCRIPTION |
|---|---|
List[str]
|
List of resource type names that can be converted to DataFrame columns |
Example
resources = get_supported_resources() print(resources) ['Patient', 'Observation', 'Condition', 'MedicationStatement']
Source code in healthchain/fhir/dataframe.py
group_bundle_by_patient(bundle)
Group Bundle resources by patient reference.
Organizes FHIR resources in a Bundle by their associated patient, making it easier to process patient-centric data. Accepts both Pydantic Bundle objects and dicts, converts to dict internally for performance.
| PARAMETER | DESCRIPTION |
|---|---|
bundle
|
FHIR Bundle resource (Pydantic object or dict)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Dict[str, Dict[str, List[Any]]]
|
Dictionary mapping patient references to their resources: |
Dict[str, Dict[str, List[Any]]]
|
{ "Patient/123": { "patient": Patient resource dict, "observations": [Observation dict, ...], "conditions": [Condition dict, ...], ... } |
Dict[str, Dict[str, List[Any]]]
|
} |
Source code in healthchain/fhir/dataframe.py
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 | |
print_supported_resources()
Print user-friendly list of supported FHIR resources for conversion.
Example
from healthchain.fhir.converters import print_supported_resources print_supported_resources() Supported FHIR Resources for ML Dataset Conversion:
✓ Patient Patient demographics (age, gender) Columns: age, gender ...
Source code in healthchain/fhir/dataframe.py
elementhelpers
FHIR element creation functions.
This module provides convenience functions for creating FHIR elements that are used as building blocks within FHIR resources (e.g., CodeableConcept, Attachment, Coding).
create_single_attachment(content_type=None, data=None, url=None, title='Attachment created by HealthChain')
Create a minimal FHIR Attachment.
Creates a FHIR Attachment resource with basic fields. Either data or url should be provided. If data is provided, it will be base64 encoded.
| PARAMETER | DESCRIPTION |
|---|---|
content_type
|
The MIME type of the content
TYPE:
|
data
|
The actual data content to be base64 encoded
TYPE:
|
url
|
The URL where the data can be found
TYPE:
|
title
|
A title for the attachment (default: "Attachment created by HealthChain")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Attachment
|
A FHIR Attachment resource with basic metadata and content
TYPE:
|
Source code in healthchain/fhir/elementhelpers.py
create_single_codeable_concept(code, display=None, system='http://snomed.info/sct')
Create a minimal FHIR CodeableConcept with a single coding.
| PARAMETER | DESCRIPTION |
|---|---|
code
|
REQUIRED. The code value from the code system
TYPE:
|
display
|
The display name for the code
TYPE:
|
system
|
The code system (default: SNOMED CT)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
CodeableConcept
|
A FHIR CodeableConcept resource with a single coding
TYPE:
|
Source code in healthchain/fhir/elementhelpers.py
create_single_reaction(code, display=None, system='http://snomed.info/sct', severity=None)
Create a minimal FHIR Reaction with a single coding.
Creates a FHIR Reaction object with a single manifestation coding. The manifestation describes the clinical reaction that was observed. The severity indicates how severe the reaction was.
| PARAMETER | DESCRIPTION |
|---|---|
code
|
REQUIRED. The code value from the code system representing the reaction manifestation
TYPE:
|
display
|
The display name for the manifestation code
TYPE:
|
system
|
The code system for the manifestation code (default: SNOMED CT)
TYPE:
|
severity
|
The severity of the reaction (mild, moderate, severe)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[Dict[str, Any]]
|
A list containing a single FHIR Reaction dictionary with manifestation and severity fields |
Source code in healthchain/fhir/elementhelpers.py
readers
FHIR conversion and reading functions.
This module provides functions for converting between different FHIR representations and reading data from FHIR resources.
convert_prefetch_to_fhir_objects(prefetch_dict)
Convert a dictionary of FHIR resource dicts to FHIR Resource objects.
Takes a prefetch dictionary where values may be either dict representations of FHIR resources or already instantiated FHIR Resource objects, and ensures all values are FHIR Resource objects.
| PARAMETER | DESCRIPTION |
|---|---|
prefetch_dict
|
Dictionary mapping keys to FHIR resource dicts or objects
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Dict[str, Resource]
|
Dict[str, Resource]: Dictionary with same keys but all values as FHIR Resource objects |
Example
prefetch = { ... "patient": {"resourceType": "Patient", "id": "123"}, ... "condition": Condition(id="456", ...) ... } fhir_objects = convert_prefetch_to_fhir_objects(prefetch) isinstance(fhir_objects["patient"], Patient) # True isinstance(fhir_objects["condition"], Condition) # True
Source code in healthchain/fhir/readers.py
create_resource_from_dict(resource_dict, resource_type)
Create a FHIR resource instance from a dictionary
| PARAMETER | DESCRIPTION |
|---|---|
resource_dict
|
Dictionary representation of the resource
TYPE:
|
resource_type
|
Type of FHIR resource to create
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Optional[Resource]
|
Optional[Resource]: FHIR resource instance or None if creation failed |
Source code in healthchain/fhir/readers.py
prefetch_to_bundle(prefetch)
Flatten CDS Hooks prefetch into a collection Bundle dict.
Converts the keyed prefetch format (used in CDS Hooks) into a flat bundle suitable for Dataset.from_fhir_bundle().
| PARAMETER | DESCRIPTION |
|---|---|
prefetch
|
CDS Hooks prefetch dict with format: {"patient": {...}, "observations": {"entry": [...]}, ...}
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Dict[str, Any]
|
Bundle dict with type "collection" and flattened entries |
Example
prefetch = request.prefetch bundle = prefetch_to_bundle(prefetch) dataset = Dataset.from_fhir_bundle(bundle, schema=schema)
Source code in healthchain/fhir/readers.py
read_content_attachment(document_reference, include_data=True)
Read the attachments in a human readable format from a FHIR DocumentReference content field.
| PARAMETER | DESCRIPTION |
|---|---|
document_reference
|
The FHIR DocumentReference resource
TYPE:
|
include_data
|
Whether to include the data of the attachments. If true, the data will be also be decoded (default: True)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Optional[List[Dict[str, Any]]]
|
Optional[List[Dict[str, Any]]]: List of dictionaries containing attachment data and metadata, or None if no attachments are found: [ { "data": str, "metadata": Dict[str, Any] } ] |
Source code in healthchain/fhir/readers.py
resourcehelpers
FHIR resource creation and modification functions.
This module provides convenience functions for creating and modifying FHIR resources.
Patterns: - create_(): create a new FHIR resource with sensible defaults - set_(): set specific fields of resources with soft validation - add_*(): add data to resources safely
Parameters marked REQUIRED are required by FHIR specification.
add_coding_to_codeable_concept(codeable_concept, code, system, display=None)
Add a coding to an existing CodeableConcept.
Useful for adding standardized codes (e.g., SNOMED CT) to resources that already have codes from other systems (e.g., ICD-10).
| PARAMETER | DESCRIPTION |
|---|---|
codeable_concept
|
The CodeableConcept to add coding to
TYPE:
|
code
|
The code value from the code system
TYPE:
|
system
|
The code system URI
TYPE:
|
display
|
Optional display text for the code
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
CodeableConcept
|
The updated CodeableConcept with the new coding added
TYPE:
|
Example
Add SNOMED CT code to a condition that has ICD-10
condition_code = condition.code condition_code = add_coding_to_codeable_concept( ... condition_code, ... code="44054006", ... system="http://snomed.info/sct", ... display="Type 2 diabetes mellitus" ... )
Source code in healthchain/fhir/resourcehelpers.py
add_provenance_metadata(resource, source, tag_code=None, tag_display=None)
Add provenance metadata to a FHIR resource.
Adds source system identifier, timestamp, and optional processing tags to track data lineage and transformations for audit trails.
| PARAMETER | DESCRIPTION |
|---|---|
resource
|
The FHIR resource to annotate
TYPE:
|
source
|
Name of the source system (e.g., "epic", "cerner")
TYPE:
|
tag_code
|
Optional tag code for processing operations (e.g., "aggregated", "deduplicated")
TYPE:
|
tag_display
|
Optional display text for the tag
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Resource
|
The resource with added provenance metadata
TYPE:
|
Example
condition = create_condition(subject="Patient/123", code="E11.9") condition = add_provenance_metadata(condition, "epic", "aggregated", "Aggregated from source")
Source code in healthchain/fhir/resourcehelpers.py
create_allergy_intolerance(patient, code=None, display=None, system='http://snomed.info/sct')
Create a minimal active FHIR AllergyIntolerance. If you need to create a more complex allergy intolerance, use the FHIR AllergyIntolerance resource directly. https://build.fhir.org/allergyintolerance.html
| PARAMETER | DESCRIPTION |
|---|---|
patient
|
REQUIRED. Reference to the patient (e.g. "Patient/123")
TYPE:
|
code
|
The allergen code
TYPE:
|
display
|
The display name for the allergen
TYPE:
|
system
|
The code system (default: SNOMED CT)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
AllergyIntolerance
|
A FHIR AllergyIntolerance resource with an auto-generated ID prefixed with 'hc-'
TYPE:
|
Source code in healthchain/fhir/resourcehelpers.py
create_condition(subject, clinical_status='active', code=None, display=None, system='http://snomed.info/sct')
Create a minimal active FHIR Condition. If you need to create a more complex condition, use the FHIR Condition resource directly. https://build.fhir.org/condition.html
| PARAMETER | DESCRIPTION |
|---|---|
subject
|
REQUIRED. Reference to the patient (e.g. "Patient/123")
TYPE:
|
clinical_status
|
REQUIRED. Clinical status (default: active)
TYPE:
|
code
|
The condition code
TYPE:
|
display
|
The display name for the condition
TYPE:
|
system
|
The code system (default: SNOMED CT)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Condition
|
A FHIR Condition resource with an auto-generated ID prefixed with 'hc-'
TYPE:
|
Source code in healthchain/fhir/resourcehelpers.py
create_document_reference(data=None, url=None, content_type=None, status='current', description='DocumentReference created by HealthChain', attachment_title='Attachment created by HealthChain')
Create a minimal FHIR DocumentReference. If you need to create a more complex document reference, use the FHIR DocumentReference resource directly. https://build.fhir.org/documentreference.html
| PARAMETER | DESCRIPTION |
|---|---|
data
|
The data content of the document attachment
TYPE:
|
url
|
URL where the document can be accessed
TYPE:
|
content_type
|
MIME type of the document (e.g. "application/pdf", "text/xml", "image/png")
TYPE:
|
status
|
REQUIRED. Status of the document reference (default: current)
TYPE:
|
description
|
Description of the document reference
TYPE:
|
attachment_title
|
Title for the document attachment
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DocumentReference
|
A FHIR DocumentReference resource with an auto-generated ID prefixed with 'hc-'
TYPE:
|
Source code in healthchain/fhir/resourcehelpers.py
create_document_reference_content(attachment_data=None, url=None, content_type='text/plain', language='en-US', title=None, **kwargs)
Create a FHIR DocumentReferenceContent object.
Creates a DocumentReferenceContent structure that can be added to a DocumentReference. Either attachment_data or url must be provided. If attachment_data is provided, it will be base64 encoded automatically.
| PARAMETER | DESCRIPTION |
|---|---|
attachment_data
|
The content data (text that will be base64 encoded)
TYPE:
|
url
|
URL where the content can be accessed
TYPE:
|
content_type
|
MIME type (e.g., 'text/plain', 'text/html', 'application/pdf') (default: text/plain)
TYPE:
|
language
|
Language code (default: en-US)
TYPE:
|
title
|
Optional title for the content (default: "Attachment created by HealthChain")
TYPE:
|
**kwargs
|
Additional DocumentReferenceContent fields (e.g., format, profile)
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Dict[str, Any]
|
Dict[str, Any]: A FHIR DocumentReferenceContent dictionary with attachment and optional language |
Example
Create content with inline data
content = create_document_reference_content( ... attachment_data="Patient presents with fever...", ... content_type="text/plain", ... title="Clinical Note" ... )
Create content with URL reference
content = create_document_reference_content( ... url="https://example.com/document.pdf", ... content_type="application/pdf", ... title="Lab Report" ... )
Add content to a DocumentReference
doc_ref = DocumentReference( ... id="doc-1", ... status="current", ... content=[content] ... )
Source code in healthchain/fhir/resourcehelpers.py
create_medication_statement(subject, status='recorded', code=None, display=None, system='http://snomed.info/sct')
Create a minimal recorded FHIR MedicationStatement. If you need to create a more complex medication statement, use the FHIR MedicationStatement resource directly. https://build.fhir.org/medicationstatement.html
| PARAMETER | DESCRIPTION |
|---|---|
subject
|
REQUIRED. Reference to the patient (e.g. "Patient/123")
TYPE:
|
status
|
REQUIRED. Status of the medication (default: recorded)
TYPE:
|
code
|
The medication code
TYPE:
|
display
|
The display name for the medication
TYPE:
|
system
|
The code system (default: SNOMED CT)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MedicationStatement
|
A FHIR MedicationStatement resource with an auto-generated ID prefixed with 'hc-'
TYPE:
|
Source code in healthchain/fhir/resourcehelpers.py
create_patient(gender=None, birth_date=None, identifier=None, identifier_system='http://hospital.example.org')
Create a minimal FHIR Patient resource with basic gender and birthdate If you need to create a more complex patient, use the FHIR Patient resource directly https://hl7.org/fhir/patient.html (No required fields).
| PARAMETER | DESCRIPTION |
|---|---|
gender
|
Administrative gender (male, female, other, unknown)
TYPE:
|
birth_date
|
Birth date in YYYY-MM-DD format
TYPE:
|
identifier
|
Optional identifier value for the patient (e.g., MRN)
TYPE:
|
identifier_system
|
The system for the identifier (default: "http://hospital.example.org")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Patient
|
A FHIR Patient resource with an auto-generated ID prefixed with 'hc-'
TYPE:
|
Source code in healthchain/fhir/resourcehelpers.py
create_risk_assessment_from_prediction(subject, prediction, status='final', method=None, basis=None, comment=None, occurrence_datetime=None)
Create a FHIR RiskAssessment from ML model prediction output. If you need to create a more complex risk assessment, use the FHIR RiskAssessment resource directly. https://hl7.org/fhir/riskassessment.html
| PARAMETER | DESCRIPTION |
|---|---|
subject
|
REQUIRED. Reference to the patient (e.g. "Patient/123")
TYPE:
|
prediction
|
Dictionary containing prediction details with keys: - outcome: CodeableConcept or dict with code, display, system for the predicted outcome - probability: float between 0 and 1 representing the risk probability - qualitative_risk: Optional str indicating risk level (e.g., "high", "moderate", "low")
TYPE:
|
status
|
REQUIRED. The status of the assessment (default: "final")
TYPE:
|
method
|
Optional CodeableConcept describing the assessment method/model used
TYPE:
|
basis
|
Optional list of References to observations or other resources used as input
TYPE:
|
comment
|
Optional text comment about the assessment
TYPE:
|
occurrence_datetime
|
When the assessment was made (ISO format). Uses current time if not provided.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RiskAssessment
|
A FHIR RiskAssessment resource with an auto-generated ID prefixed with 'hc-'
TYPE:
|
Example
prediction = { ... "outcome": {"code": "A41.9", "display": "Sepsis", "system": "http://hl7.org/fhir/sid/icd-10"}, ... "probability": 0.85, ... "qualitative_risk": "high" ... } risk = create_risk_assessment("Patient/123", prediction)
Source code in healthchain/fhir/resourcehelpers.py
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 | |
create_value_quantity_observation(code, value, unit, status='final', subject=None, system='http://loinc.org', display=None, effective_datetime=None)
Create a minimal FHIR Observation for vital signs or laboratory values. If you need to create a more complex observation, use the FHIR Observation resource directly. https://hl7.org/fhir/observation.html
| PARAMETER | DESCRIPTION |
|---|---|
status
|
REQUIRED. The status of the observation (default: "final")
TYPE:
|
code
|
REQUIRED. The observation code (e.g., LOINC code for the measurement)
TYPE:
|
value
|
The numeric value of the observation
TYPE:
|
unit
|
The unit of measure (e.g., "beats/min", "mg/dL")
TYPE:
|
system
|
The code system for the observation code (default: LOINC)
TYPE:
|
display
|
The display name for the observation code
TYPE:
|
effective_datetime
|
When the observation was made (ISO format). Uses current time if not provided.
TYPE:
|
subject
|
Reference to the patient (e.g. "Patient/123")
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Observation
|
A FHIR Observation resource with an auto-generated ID prefixed with 'hc-'
TYPE:
|
Source code in healthchain/fhir/resourcehelpers.py
set_condition_category(condition, category)
Set the category of a FHIR Condition to either 'problem-list-item' or 'encounter-diagnosis'.
| PARAMETER | DESCRIPTION |
|---|---|
condition
|
The FHIR Condition resource to modify
TYPE:
|
category
|
The category to set. Must be 'problem-list-item' or 'encounter-diagnosis'.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Condition
|
The modified FHIR Condition resource with the specified category set
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the category is not one of the allowed values. |
Source code in healthchain/fhir/resourcehelpers.py
utilities
FHIR utility functions.
This module provides utility functions for common operations like ID generation, age calculation, and gender encoding.
calculate_age_from_birthdate(birth_date)
Calculate age in years from a birth date string.
| PARAMETER | DESCRIPTION |
|---|---|
birth_date
|
Birth date in ISO format (YYYY-MM-DD or full ISO datetime)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Optional[int]
|
Age in years, or None if birth date is invalid |
Source code in healthchain/fhir/utilities.py
calculate_age_from_event_date(birth_date, event_date)
Calculate age in years from birth date and event date (MIMIC-IV style).
Uses the formula: age = year(eventDate) - year(birthDate) This matches MIMIC-IV on FHIR de-identified age calculation.
| PARAMETER | DESCRIPTION |
|---|---|
birth_date
|
Birth date in ISO format (YYYY-MM-DD or full ISO datetime)
TYPE:
|
event_date
|
Event date in ISO format (YYYY-MM-DD or full ISO datetime)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Optional[int]
|
Age in years based on year difference, or None if dates are invalid |
Example
calculate_age_from_event_date("1990-06-15", "2020-03-10") 30
Source code in healthchain/fhir/utilities.py
encode_gender(gender)
Encode gender as integer for ML models.
Standard encoding: Male=1, Female=0, Other/Unknown=None
| PARAMETER | DESCRIPTION |
|---|---|
gender
|
Gender string (case-insensitive)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Optional[int]
|
Encoded gender (1 for male, 0 for female, None for other/unknown) |