### Installing Documentation Dependencies Source: https://github.com/luisfabib/fhircraft/blob/main/docs/community/contributing.md Installs the core package along with necessary tools for building and previewing documentation, such as MkDocs Material and mkdocstrings. ```bash # Install core package + documentation tools pip install -e ".[dev, docs]" ``` -------------------------------- ### Verify Installation and Run Tests Source: https://github.com/luisfabib/fhircraft/blob/main/docs/community/contributing.md Confirm that pytest is installed and run a basic test to ensure the development environment is set up correctly. ```bash # Check that pytest is available pytest --version # Run a quick test to ensure everything works pytest test/test_config.py -v ``` -------------------------------- ### Constructing Models from Multiple Implementation Guides Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/resources-construction.md Shows how to construct models for profiles from different implementation guides by loading multiple packages into the factory. Each model enforces its specific profile constraints. ```python from fhircraft.fhir.resources import FHIRModelFactory factory = FHIRModelFactory(fhir_release="R4") # Load both US Core and International Patient Summary factory.register_package("hl7.fhir.us.core", "5.0.1") factory.register_package("hl7.fhir.us.mcode", "1.1.0") # Construct models for different profiles USCorePatient = factory.build( "http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient" ) CancerPatient = factory.build( "http://hl7.org/fhir/us/mcode/StructureDefinition/mcode-cancer-patient" ) # Each model validates using its profile rules us_patient = USCorePatient( name=[{"family": "Doe", "given": ["John"]}], gender="male" ) cancer_patient = CancerPatient( name=[{"family": "Smith", "given": ["Alice"]}], gender="female" ) print(f"Created US Core patient with name: {us_patient.name[0].given[0]} {us_patient.name[0].family}") #> Created US Core patient with name: John Doe print(f"Created mCODE cancer patient with name: {cancer_patient.name[0].given[0]} {cancer_patient.name[0].family}") #> Created mCODE cancer patient with name: Alice Smith ``` -------------------------------- ### Install Latest Fhircraft with Poetry Source: https://github.com/luisfabib/fhircraft/blob/main/docs/quickstart/installation.md Use this command to install the latest stable version of Fhircraft using Poetry. Ensure you are in a virtual environment. ```bash poetry add fhircraft ``` -------------------------------- ### Previewing Documentation Locally Source: https://github.com/luisfabib/fhircraft/blob/main/docs/community/contributing.md Starts a local development server for previewing documentation changes with live reloading. The server is accessible at http://127.0.0.1:8000. ```bash # From project root mkdocs serve ``` -------------------------------- ### Install Latest Fhircraft with uv Source: https://github.com/luisfabib/fhircraft/blob/main/docs/quickstart/installation.md Use this command to install the latest stable version of Fhircraft using uv. Ensure you are in a virtual environment. ```bash uv add fhircraft ``` -------------------------------- ### Install Latest Fhircraft with Pipenv Source: https://github.com/luisfabib/fhircraft/blob/main/docs/quickstart/installation.md Use this command to install the latest stable version of Fhircraft using pipenv. Ensure you are in a virtual environment. ```bash pipenv install fhircraft ``` -------------------------------- ### Verify Fhircraft Installation Source: https://github.com/luisfabib/fhircraft/blob/main/README.md Verify the Fhircraft installation by importing a FHIR type and printing a success message. ```python from fhircraft.fhir.resources import get_fhir_type # This should work without errors Patient = get_fhir_type("Patient","R4B") print("✓ Fhircraft installed successfully!") ``` -------------------------------- ### Install Development Fhircraft with Poetry Source: https://github.com/luisfabib/fhircraft/blob/main/docs/quickstart/installation.md Install the latest development version of Fhircraft directly from its GitHub repository using Poetry. This is useful for testing the newest features or contributing to the project. ```bash poetry add git+https://github.com/luisfabib/fhircraft.git ``` -------------------------------- ### Initialize FHIRModelFactory for Profiles Source: https://github.com/luisfabib/fhircraft/blob/main/docs/quickstart/quickstart.md Demonstrates how to initialize a FHIRModelFactory to work with FHIR implementation guides and create specialized resource models based on profiles. ```python from fhircraft.fhir.resources import FHIRModelFactory factory = FHIRModelFactory(fhir_release="R4") ``` -------------------------------- ### Install Development Fhircraft with uv Source: https://github.com/luisfabib/fhircraft/blob/main/docs/quickstart/installation.md Install the latest development version of Fhircraft directly from its GitHub repository using uv. This is useful for testing the newest features or contributing to the project. ```bash uv add git+https://github.com/luisfabib/fhircraft.git ``` -------------------------------- ### Install Latest Fhircraft with Pip Source: https://github.com/luisfabib/fhircraft/blob/main/docs/quickstart/installation.md Use this command to install the latest stable version of Fhircraft using pip. Ensure you are in a virtual environment. ```bash pip install fhircraft ``` -------------------------------- ### Constructing US Core Patient Model from Package Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/resources-construction.md Demonstrates building a US Core Patient model by registering an implementation guide package and then using its canonical URL. This is useful for adhering to US Core standards. ```python from fhircraft.fhir.resources import FHIRModelFactory factory = FHIRModelFactory(fhir_release="R4") # Load the US Core implementation guide # See managing-fhir-artifacts.md for package loading details factory.register_package("hl7.fhir.us.core", "5.0.1") # Construct a model for the US Core Patient profile # The canonical URL comes from the implementation guide USCorePatient = factory.build( "http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient" ) # Create a patient using the profile model # US Core Patient requires an identifier patient = USCorePatient( name=[{"given": ["John"], "family": "Doe"}], gender="male", identifier=[{ # Required by US Core "system": "http://example.org/mrn", "value": "12345" }] ) print(f"Created US Core patient: {patient.name[0].given[0]} {patient.name[0].family}") ``` -------------------------------- ### Install Fhircraft in Editable Mode with Development Dependencies Source: https://github.com/luisfabib/fhircraft/blob/main/docs/quickstart/installation.md Install Fhircraft in editable mode, allowing changes in the source code to be reflected immediately without reinstallation. This command also installs development dependencies. ```bash pip install -e .[dev] ``` -------------------------------- ### Integrate FHIR Package with US Core Profile Source: https://github.com/luisfabib/fhircraft/blob/main/README.md Shows how to extend base FHIR models with implementation guide profiles loaded from the FHIR package registry, using the US Core Patient profile as an example. ```python from fhircraft.fhir.resources import FHIRModelFactory # Create a FHIR (R5 release) factory factory = FHIRModelFactory(fhir_release="R4") # Load US Core Implementation Guide factory.register_package("hl7.fhir.us.core", "5.0.1") # Create US Core Patient model with enhanced validation USCorePatient = factory.build( canonical_url="http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient" ) # Use with US Core constraints patient = USCorePatient( identifier=[{"system": "http://example.org/mrn", "value": "12345"}], name=[{"family": "Doe", "given": ["John"]}], gender="male" ) ``` -------------------------------- ### Install Development Fhircraft with Pip Source: https://github.com/luisfabib/fhircraft/blob/main/docs/quickstart/installation.md Install the latest development version of Fhircraft directly from its GitHub repository using pip. This is useful for testing the newest features or contributing to the project. ```bash pip install git+https://github.com/luisfabib/fhircraft.git ``` -------------------------------- ### Example of Well-Documented Python Function Source: https://github.com/luisfabib/fhircraft/blob/main/docs/community/contributing.md Illustrates proper docstring formatting for a Python function, including arguments, return values, and potential exceptions. Use this as a template for public APIs. ```python def validate_fhir_resource(resource: dict, resource_type: str) -> bool: """Validate a FHIR resource against its structure definition. Args: resource: The FHIR resource as a dictionary resource_type: The FHIR resource type (e.g., "Patient", "Observation") Returns: True if validation succeeds, False otherwise Raises: ValueError: If resource_type is not a valid FHIR resource """ # Implementation here ``` -------------------------------- ### Verify Python Version Source: https://github.com/luisfabib/fhircraft/blob/main/docs/community/contributing.md Check if the installed Python version meets the project's requirement (3.10+). ```bash python --version # Should be 3.10+ ``` -------------------------------- ### Committing Changes with Git Source: https://github.com/luisfabib/fhircraft/blob/main/docs/community/contributing.md Shows the process of staging changes and committing them with a descriptive message following conventional commit guidelines. Includes an example of a detailed commit message. ```bash # Stage your changes git add . # Commit with a descriptive message git commit -m "fix: resolve patient validation for edge cases - Add validation for missing name fields - Handle null gender values gracefully - Add tests for edge cases in test_fhir_resources_factory.py Fixes #123" ``` -------------------------------- ### Clone Fhircraft Repository Source: https://github.com/luisfabib/fhircraft/blob/main/docs/quickstart/installation.md Clone the Fhircraft repository from GitHub to your local machine. This is the first step for development installations. ```bash git clone https://github.com/luisfabib/fhircraft.git cd fhircraft ``` -------------------------------- ### Writing a Pytest Test Case Source: https://github.com/luisfabib/fhircraft/blob/main/docs/community/contributing.md Demonstrates how to write a pytest test for FHIR resource creation, including testing valid and invalid inputs. This example uses pytest.raises for error checking. ```python # test/test_my_feature.py import pytest from fhircraft.fhir.resources import get_fhir_type def test_patient_creation_validates_gender(): """Test that invalid gender codes raise validation errors.""" Patient = get_fhir_type("Patient", "R5") # Valid gender should work patient = Patient(gender="female") assert patient.gender == "female" # Invalid gender should raise error with pytest.raises(ValueError): Patient(gender="invalid-gender") ``` -------------------------------- ### Load US Core Package and Build Patient Model Source: https://github.com/luisfabib/fhircraft/blob/main/docs/quickstart/quickstart.md Loads the US Core implementation guide and builds a specialized Patient model from its profile. This model can then be used to create FHIR Patient objects that conform to US Core constraints. ```python factory.register_package('hl7.fhir.us.core') USCorePatient = factory.build( canonical_url='http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient' ) us_patient = USCorePatient( name=[{"given": ["Bob"], "family": "Smith"}], gender="male", birthDate="1990-01-01" ) ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/luisfabib/fhircraft/blob/main/docs/community/contributing.md Run this command to serve the documentation locally and preview changes. ```bash mkdocs serve ``` -------------------------------- ### Clone and Navigate Repository Source: https://github.com/luisfabib/fhircraft/blob/main/docs/community/contributing.md Clone the Fhircraft repository and navigate into the project directory. ```bash git clone https://github.com/YOUR-USERNAME/fhircraft.git cd fhircraft ``` -------------------------------- ### Create and Checkout Documentation Branch Source: https://github.com/luisfabib/fhircraft/blob/main/docs/community/contributing.md Create a new Git branch for documentation improvements. ```bash # Create a branch git checkout -b docs/improve-fhirpath-guide ``` -------------------------------- ### Stage and Commit Documentation Changes Source: https://github.com/luisfabib/fhircraft/blob/main/docs/community/contributing.md Stage all documentation files and commit them with a descriptive message. ```bash # Make your changes, then commit git add docs/ git commit -m "docs: improve FHIRPath querying examples - Add more complex query examples - Clarify when to use different query methods - Fix typos in code examples" ``` -------------------------------- ### Building Documentation in Strict Mode Source: https://github.com/luisfabib/fhircraft/blob/main/docs/community/contributing.md Builds the documentation project in strict mode to catch warnings and errors, ensuring a clean build before deployment or submission. ```bash # Build in strict mode to catch warnings mkdocs build --strict ``` -------------------------------- ### Working with Context-Aware Structures Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/pydantic-representation.md Demonstrates how Fhircraft's FHIRList automatically maintains parent and resource context for nested elements. Use this to understand how elements retain references to their parent and the root resource. ```python from fhircraft.fhir.resources.datatypes.R5.core import Patient from fhircraft.fhir.resources.datatypes.R5.complex import HumanName patient = Patient(name=[]) # List fields use FHIRList instead of standard Python lists print(type(patient.name)) # (1)! #> # Add items and context is automatically maintained patient.name.append(HumanName(family="Smith", given=["John"])) # (2)! patient.name.append(HumanName(family="Smith", given=["Johnny"], use="nickname")) # Access nested elements with maintained context name = patient.name[0] # (3)! print(hasattr(name, '_parent')) # (4)! #> # True print(name._parent == patient) # (5)! #> # True print(name._resource == patient) # (7)! #> # True ``` -------------------------------- ### Create and Validate a FHIR Patient Resource Source: https://github.com/luisfabib/fhircraft/blob/main/README.md Demonstrates how to get a built-in FHIR R5 Patient model and create a validated patient instance. ```python from fhircraft.fhir.resources import get_fhir_type # Get built-in Patient model for FHIR R5 Patient = get_fhir_type("Patient", "R5") # Create and validate a patient patient = Patient( name=[{"given": ["Alice"], "family": "Johnson"}], gender="female", birthDate="1985-03-15" ) print(f"Created patient: {patient.name[0].given[0]} {patient.name[0].family}") ``` -------------------------------- ### Get and Inspect Fhircraft Configuration Object Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/configuration.md Retrieve the current Fhircraft configuration object to inspect its settings programmatically. Configuration objects are immutable after creation. ```python from fhircraft import get_config # Get the current active configuration config = get_config() # Inspect current validation settings print(f"Warnings disabled: {config.disable_validation_warnings}") print(f"Validation mode: {config.mode}") print(f"Disabled constraints: {config.disabled_fhir_constraints}") ``` -------------------------------- ### Push Documentation Branch Source: https://github.com/luisfabib/fhircraft/blob/main/docs/community/contributing.md Push the new documentation branch to your remote repository. ```bash # Push and create PR git push origin docs/improve-fhirpath-guide ``` -------------------------------- ### Reset Entire FHIR Model Cache Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/resources-construction.md Discards all cached FHIR models at once. This is useful when a batch of definitions has been reloaded and all subsequent builds should start from scratch. ```python from fhircraft.fhir.resources import FHIRModelFactory factory = FHIRModelFactory(fhir_release="R4") factory.reset_cache() print(factory.list_built()) # [] ``` -------------------------------- ### Generate Multiple Related FHIR Models Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/resources-construction.md Constructs multiple related FHIR models from an implementation guide and saves them into a single Python module. This ensures that related models can correctly reference each other. ```python from fhircraft.fhir.resources import FHIRModelFactory from fhircraft.fhir.resources.generator import generate_resource_model_code factory = FHIRModelFactory(fhir_release="R4") # Load the implementation guide factory.register_package("hl7.fhir.us.core", "5.0.1") # Construct multiple related models models_to_generate = [] us_core_profiles = [ "us-core-patient", "us-core-condition", "us-core-procedure", ] # Construct each model and add to the list for profile_name in us_core_profiles: model = factory.build( f"http://hl7.org/fhir/us/core/StructureDefinition/{profile_name}" ) models_to_generate.append(model) # Generate source code for all models together # This ensures proper cross-references between models source_code = generate_resource_model_code(models_to_generate) # Save to a single module file with open("us_core_models.py", "w") as f: f.write(source_code) print(f"Generated {len(models_to_generate)} models in us_core_models.py") ``` -------------------------------- ### Working with FHIR Collections Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/fhirpath.md Demonstrates retrieving all matching values, single values with fallbacks, and the first/last values from FHIR resource collections using FHIRPath methods. ```python from fhircraft.fhir.resources import get_fhir_type Patient = get_fhir_type("Patient", "R5") patient = Patient( name=[ {"given": ["John"], "family": "Smith"}, {"given": ["Johnny"], "family": "Smith", "use": "nickname"} ], telecom=[ {"system": "phone", "value": "555-0123", "use": "home"}, {"system": "phone", "value": "555-0456", "use": "work"}, {"system": "email", "value": "john@example.com"} ] ) # (1)! # Get all values - safe for any number of matches all_phones = patient.fhirpath_values("Patient.telecom.where(system='phone').value") # (2)! assert all_phones == ["555-0123", "555-0456"] # Get single value - strict about expecting exactly one gender = patient.fhirpath_single("Patient.gender", default="unknown") # (3)! assert gender == "unknown" # Get first/last safely - handles multiple values gracefully first_name = patient.fhirpath_first("Patient.name.given") # (4)! last_phone = patient.fhirpath_last("Patient.telecom.where(system='phone').value") # (5)! assert first_name == "John" assert last_phone == "555-0456" ``` -------------------------------- ### Testing Data Presence with FHIRPath Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/fhirpath.md Shows how to check for the existence of data using `fhirpath_exists`, count items with `fhirpath_count`, and verify missing data with `fhirpath_is_empty`. ```python # Check existence before processing if patient.fhirpath_exists("Patient.birthDate"): # (1)! birth_year = patient.fhirpath_single("Patient.birthDate.substring(0,4)") print(f"Born in {birth_year}") # Count items for validation phone_count = patient.fhirpath_count("Patient.telecom.where(system='phone')") # (2)! if phone_count > 1: print(f"Patient has {phone_count} phone numbers") # Verify required data is missing if patient.fhirpath_is_empty("Patient.address"): # (3)! print("No address on file") ``` -------------------------------- ### Get FHIR Resource Models using Direct Import Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/resources-models.md Import FHIR resource models directly from their respective modules for explicit access. This is suitable when the resource types and versions are known beforehand. ```python from fhircraft.fhir.resources.datatypes.R4B.core import Patient, Condition print(Patient) #> print(Condition) #> ``` -------------------------------- ### Capturing FhirValidationWarning Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/error-handling.md This example shows how to capture non-critical validation issues, which are emitted as FhirValidationWarning. Use this when you need to be aware of potential problems that do not strictly violate FHIR invariants but might indicate issues. ```python import warnings from fhircraft.exceptions import FhirValidationWarning with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always",FhirValidationWarning) patient = Patient(name=[{"given": ["Alice"]}]) # may emit dom-6 warning for w in caught: print(f"Validation warning: {w.message}") ``` -------------------------------- ### FHIRModelFactory Mode Selection Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/resources-construction.md Demonstrates building FHIR models using AUTO, SNAPSHOT, and DIFFERENTIAL modes with FHIRModelFactory. ```python from fhircraft.fhir.resources import FHIRModelFactory # AUTO mode (default) - factory decides based on available elements model_auto = FHIRModelFactory(fhir_release="R4").build( canonical_url="http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient" ) # Explicit SNAPSHOT mode - use the complete flattened view model_snapshot = FHIRModelFactory(fhir_release="R4").build( canonical_url="http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient", mode="snapshot" ) # Explicit DIFFERENTIAL mode - use constraints from profile only model_differential = FHIRModelFactory(fhir_release="R4").build( canonical_url="http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient", mode="differential" ) ``` -------------------------------- ### Capture FHIRPath Warnings Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/error-handling.md Shows how to use Python's `warnings` module to capture specific FHIRPath warnings or all Fhircraft warnings. ```python import warnings from fhircraft.exceptions import FhirPathWarning, FhircraftWarning # Capture only FHIRPath warnings with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always", FhirPathWarning) result = patient.fhirpath_values("Patient.name") for w in caught: print(f"FHIRPath warning: {w.message}") # Or suppress all Fhircraft warnings at once warnings.filterwarnings("ignore", category=FhircraftWarning) ``` -------------------------------- ### Get FHIR Resource Models using Resolver Function Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/resources-models.md Use the `get_fhir_type` function to retrieve Pydantic models for FHIR resources for a specific version. This is useful when you need to dynamically access resource types. ```python from fhircraft.fhir.resources import get_fhir_type Patient = get_fhir_type("Patient", "R4B") Condition = get_fhir_type("Condition", "R4B") print(Patient) #> print(Condition) #> ``` -------------------------------- ### Load Multiple FHIR Packages Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/managing-fhir-artifacts.md Configure the factory to load multiple FHIR packages simultaneously. This simplifies setup and ensures all required packages are available before model construction, suitable for complex applications needing various standards. ```python from fhircraft.fhir.resources import FHIRModelFactory factory = FHIRModelFactory(fhir_release="R4") # Configure the factory to load multiple packages factory.register_package("hl7.fhir.us.core", "5.0.1") # US healthcare standards factory.register_package("hl7.fhir.us.mcode", "1.1.0") # Minimal Common Oncology Data Elements # Create models from different packages USCorePatient = factory.build( "http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient" ) CancerPatient = factory.build( "http://hl7.org/fhir/us/mcode/StructureDefinition/mcode-cancer-patient" ) # Use both models us_patient = USCorePatient(name=[{"family": "Smith"}], gender="male") mcode_patient = CancerPatient(name=[{"family": "Jones"}], gender="female") print(f"Loaded {len([USCorePatient, mcode_patient])} different patient types") ``` -------------------------------- ### Importing Fhircraft Exceptions and Warnings Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/error-handling.md Import specific exceptions and warnings from `fhircraft.exceptions` to manage error handling granularity. It's recommended to import only what you need. ```python from fhircraft.exceptions import FhircraftException, FhirPathException from fhircraft.exceptions import FhircraftWarning, FhirValidationWarning ``` -------------------------------- ### FHIR Cardinality to Pydantic Type Mapping Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/pydantic-representation.md Illustrates how FHIR cardinality rules (min..max) are translated into Python type annotations and Pydantic Field constraints within Fhircraft models. Shows examples for cardinality 0..1, 1..2, and 1..*, including the use of Optional, List, and Field with max_length. ```python class MyPatient(FHIRBaseModel): # Cardinality 0..1 active: Optional[boolean] = Field(default=None) # Cardinality 1..2 name: Optional[List[HumanName]] = Field(default=None, max_length=3) # Cardinality 1..* identifier: Optional[List[Identifier]] = Field(default=None) ``` -------------------------------- ### Organizing Mappings with Multiple Groups Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/mapper.md Demonstrates how to define and use multiple groups within a mapping script to handle different aspects of a transformation. This promotes modularity and reusability. You can execute all groups or a specific group for testing. ```python script = """ map 'http://example.org/multi-group' = 'MultiGroup' uses "http://hl7.org/fhir/StructureDefinition/Patient" as target // Main group orchestrates the transformation group main(source src, target patient: Patient) { src -> patient then demographics(src, patient); // Handle demographics data src -> patient then contacts(src, patient); // Handle contact information src -> patient then identifiers(src, patient); // Handle identifiers } // Group focused on demographic fields group demographics(source src, target patient: Patient) { src.name -> patient.name as name then { src.name -> name.text; }; src.birthDate -> patient.birthDate; src.gender -> patient.gender; } // Group focused on contact information group contacts(source src, target patient: Patient) { src.phone as phone -> patient.telecom as tel then { phone -> tel.value, tel.system='phone'; }; src.email as email -> patient.telecom as email then { email -> email.value, email.system='email'; }; } // Group focused on identifier mappings group identifiers(source src, target patient: Patient) { src.ssn -> patient.identifier as id then { ssn -> id.value, id.system='http://hl7.org/fhir/sid/us-ssn'; }; } """ # Execute the entire mapping (all groups) targets = mapper.map(script, source_data) # Or execute only a specific group for testing targets = mapper.map(script, source_data, group="demographics") ``` -------------------------------- ### Accessing Built-in FHIRPath Environment Variables Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/fhirpath.md Demonstrates how to access standard FHIRPath environment variables such as %context, %resource, %rootResource, %ucum, and %fhirRelease using the fhirpath_single method. This is useful for inspecting the current evaluation context and resource properties. ```python from fhircraft.fhir.resources import get_fhir_type Patient = get_fhir_type("Patient", "R5") patient = Patient( id="patient-123", name=[{"given": ["Alice"], "family": "Johnson"}] ) name = patient.name[0] print(type(name.fhirpath_single("%context"))) # (1)! #> print(type(patient.fhirpath_single("%resource"))) # (2)! #> print(type(patient.fhirpath_single("%rootResource"))) # (3)! #> print(patient.fhirpath_single("%ucum")) # (4)! #> http://unitsofmeasure.org print(patient.fhirpath_single("%fhirRelease")) # (5)! #> R5 ``` -------------------------------- ### Working with Backbone Elements Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/pydantic-representation.md Illustrates how to construct FHIR resources with backbone elements using Fhircraft. It shows that backbone elements can be provided as dictionaries and are converted into typed Pydantic objects, allowing for natural navigation of nested structures. ```python # Observation.component is a backbone element component_data = { "code": { "coding": [ { "system": "http://loinc.org", "code": "8480-6", "display": "Systolic blood pressure" } ] }, "valueQuantity": { "value": 120, "unit": "mmHg", "system": "http://unitsofmeasure.org", "code": "mm[Hg]" } } observation = Observation( status="final", code={"text": "Blood pressure"}, component=[component_data] # (1)! ) # Access backbone element data component = observation.component[0] # (2)! print(type(component)) # (3)! #> print(component.valueQuantity.value) # (4)! #> 120.0 ``` -------------------------------- ### Querying FHIR Models with Built-in Methods Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/fhirpath.md Demonstrates how to use Fhircraft's built-in FHIRPath methods on resource instances to extract specific data points like family names, gender, and check for the existence of contact information. ```python from fhircraft.fhir.resources import get_fhir_type Patient = get_fhir_type("Patient", "R5") patient = Patient( name=[{"given": ["Alice"], "family": "Johnson"}], gender="female", telecom=[{"system": "phone", "value": "555-0123"}] ) # Query directly on the resource using built-in methods family_names = patient.fhirpath_values("Patient.name.family") gender = patient.fhirpath_single("Patient.gender") has_phone = patient.fhirpath_exists("Patient.telecom.where(system='phone')") assert family_names == ["Johnson"] assert gender == "female" assert has_phone == True ``` -------------------------------- ### Accessing Extension Metadata Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/pydantic-representation.md Illustrates how to access the metadata of an extension attached to a primitive value. The extension is directly accessible on the primitive model instance. ```python print(patient.birthDate.extension[0].url) # (2)! ``` -------------------------------- ### Calculate Average with $total Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/fhirpath.md Demonstrates calculating the average of a list of numbers by first using $total to accumulate the sum, and then dividing by the total count of items. ```python # Calculate average using $total accumulation avg_calc = fhirpath.parse("aggregate($total + $this, 0)").single(numbers) # (3)! average = avg_calc / len(numbers) assert average == 3.0 ``` -------------------------------- ### Load Fhircraft Configuration from Environment Variables Source: https://github.com/luisfabib/fhircraft/blob/main/docs/user-guide/configuration.md Load configuration settings directly from environment variables into your Python application. This method is standard for containerized environments like Docker and Kubernetes. ```python from fhircraft import load_config_from_env # Load configuration from environment variables load_config_from_env() # (1)! # 1. Configuration now reflects environment variable settings. No need to call configure() explicitly ```