Skip to content

FHIRPath Engine

FHIRPath evaluation engine components

CheckModifiers

Path: fhircraft.fhir.path.engine.additional.CheckModifiers

CheckModifiers(modifier: str | Literal)

Bases: FHIRPathFunction

A representation of the FHIRPath checkModifiers() function.

Attributes:

Name Type Description
modifier str

The modifier to check for.

Methods:

Name Description
evaluate

For each element in the input collection, verifies that there are no modifying extensions defined other than the ones given by the modifier argument (comma-separated string). If the check passes, the input collection is returned. Otherwise, an error is thrown, including if modifier is empty.

Source code in fhircraft/fhir/path/engine/additional.py
def __init__(self, modifier: str | Literal):
    if isinstance(modifier, Literal):
        modifier = modifier.value
    if not isinstance(modifier, str):
        raise FHIRPathError("checkModifiers() argument must be a string.")
    self.modifier = modifier

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

For each element in the input collection, verifies that there are no modifying extensions defined other than the ones given by the modifier argument (comma-separated string). If the check passes, the input collection is returned. Otherwise, an error is thrown, including if modifier is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/additional.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    For each element in the input collection, verifies that there are no modifying extensions defined other than the ones given by the modifier argument (comma-separated string). If the check passes, the input collection is returned. Otherwise, an error is thrown, including if modifier is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): The output collection.
    """
    raise NotImplementedError(
        "Evaluation of the FHIRPath checkModifiers() function is not supported."
    )

Comparable

Path: fhircraft.fhir.path.engine.additional.Comparable

Comparable(quantity: Quantity | FHIRPath)

Bases: FHIRPathFunction

A representation of the FHIRPath comparable() function.

Attributes:

Name Type Description
quantity Quantity | FHIRPath

The quantity to check for comparability or a FHIRPath that resolves to a Quantity.

Methods:

Name Description
evaluate

This function returns true if the engine executing the FHIRPath statement can compare the singleton Quantity with the singleton other Quantity and determine their relationship to each other. Comparable means that both have values and that the code and system for the units are the same (irrespective of system) or both have code + system, system is recognized by the FHIRPath implementation and the codes are comparable within that code system. E.g. days and hours or inches and cm.

Source code in fhircraft/fhir/path/engine/additional.py
def __init__(self, quantity: Quantity | FHIRPath):
    if isinstance(quantity, Quantity):
        quantity = Literal(quantity)
    if not isinstance(quantity, FHIRPath):
        raise FHIRPathError(
            "comparable() argument must be a Quantity or valid FHIRPath."
        )
    self.quantity = quantity

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

This function returns true if the engine executing the FHIRPath statement can compare the singleton Quantity with the singleton other Quantity and determine their relationship to each other. Comparable means that both have values and that the code and system for the units are the same (irrespective of system) or both have code + system, system is recognized by the FHIRPath implementation and the codes are comparable within that code system. E.g. days and hours or inches and cm.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/additional.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    This function returns `true` if the engine executing the FHIRPath statement can compare the singleton Quantity with the singleton other Quantity and determine their relationship to each other. Comparable means that both have values and that the code and system for the units are the same (irrespective of system) or both have code + system, system is recognized by the FHIRPath implementation and the codes are comparable within that code system. E.g. days and hours or inches and cm.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): The output collection.
    """
    if len(collection) == 0:
        return []
    elif len(collection) != 1:
        raise FHIRPathError("comparable() requires a singleton collection.")
    item = collection[0]
    if not isinstance(item.value, Quantity):
        raise FHIRPathError("comparable() requires a Quantity input.")
    input_quantity: Quantity = item.value
    if not isinstance(
        quantity := self.quantity.single(collection, environment=environment),
        Quantity,
    ):
        raise FHIRPathError("Comparable() input did not evaluate to a Quantity.")
    # TODO: Implement proper unit comparison logic once unit systems are supported
    return [FHIRPathCollectionItem.wrap(input_quantity.unit == quantity.unit)]

ConformsTo

Path: fhircraft.fhir.path.engine.additional.ConformsTo

ConformsTo(structure: str | Literal)

Bases: FHIRPathFunction

A representation of the FHIRPath conformsTo() function.

Attributes:

Name Type Description
structure str

The structure canonical URL.

Methods:

Name Description
evaluate

Returns true if the single input element conforms to the profile specified by the structure argument, and false otherwise. If the input is not a single item, the structure is empty, or the structure cannot be resolved to a valid profile, the result is empty.

Source code in fhircraft/fhir/path/engine/additional.py
def __init__(self, structure: str | Literal):
    if isinstance(structure, Literal):
        structure = structure.value
    if not isinstance(structure, str):
        raise FHIRPathError("conformsTo() argument must be a string.")
    self.structure = structure

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns true if the single input element conforms to the profile specified by the structure argument, and false otherwise. If the input is not a single item, the structure is empty, or the structure cannot be resolved to a valid profile, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/additional.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns `true` if the single input element conforms to the profile specified by the `structure` argument, and false otherwise. If the input is not a single item, the structure is empty, or the structure cannot be resolved to a valid profile, the result is empty.


    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): The output collection.
    """
    raise NotImplementedError(
        "Evaluation of the FHIRPath conformsTo() function is not supported."
    )

ElementDefinition

Path: fhircraft.fhir.path.engine.additional.ElementDefinition

Bases: FHIRPathFunction

A representation of the FHIRPath elementDefinition() function.

Methods:

Name Description
evaluate

Returns the FHIR element definition information for each element in the input collection. If the input collection is empty, the return value will be empty.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the FHIR element definition information for each element in the input collection. If the input collection is empty, the return value will be empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/additional.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the FHIR element definition information for each element in the input collection. If the input collection is empty, the return value will be empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): The output collection.
    """
    raise NotImplementedError(
        "Evaluation of the FHIRPath elementDefinition() function is not supported."
    )

Extension

Path: fhircraft.fhir.path.engine.additional.Extension

Extension(url: str | Literal)

Bases: FHIRPathFunction

A representation of the FHIRPath extension() function.

Attributes:

Name Type Description
url str

URL to query the extensions.

Note

This class is a syntactical shortcut equivalent to:

Invocation(Element('extension'), Where(Equals(Element('url'), url)))

Methods:

Name Description
evaluate

Filters the input collection for items named extension with the given url.

Source code in fhircraft/fhir/path/engine/additional.py
def __init__(self, url: str | Literal):
    if isinstance(url, Literal):
        url = url.value
    if not isinstance(url, str):
        raise FHIRPathError("Extension() argument must be a string.")
    self.url = url

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Filters the input collection for items named extension with the given url. Will return an empty collection if the input collection is empty or the url is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/additional.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Filters the input collection for items named `extension` with the given `url`.
    Will return an empty collection if the input collection is empty or the url is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): The output collection.
    """
    return Invocation(
        Element("extension"),
        Where(Equals(Element("url"), [FHIRPathCollectionItem.wrap(self.url)])),
    ).evaluate(collection, environment, create)

GetValue

Path: fhircraft.fhir.path.engine.additional.GetValue

Bases: FHIRPathFunction

A representation of the FHIRPath getValue() function.

Methods:

Name Description
evaluate

Return the underlying system value for the FHIR primitive if the input collection contains a single

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Return the underlying system value for the FHIR primitive if the input collection contains a single value which is a FHIR primitive, and it has a primitive value (see discussion for hasValue()). Otherwise the return value is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/additional.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Return the underlying system value for the FHIR primitive if the input collection contains a single
    value which is a FHIR primitive, and it has a primitive value (see discussion for hasValue()). Otherwise the return value is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): The output collection.
    """
    if len(collection) != 1:
        return []
    else:
        value = collection[0].value
        if isinstance(value, Date):
            value = value.to_date()
        elif isinstance(value, Time):
            value = value.to_time()
        elif isinstance(value, DateTime):
            value = value.to_datetime()

        has_primitive_value = value is not None and is_fhir_primitive(value)
        return [FHIRPathCollectionItem.wrap(value)] if has_primitive_value else []

HasValue

Path: fhircraft.fhir.path.engine.additional.HasValue

Bases: FHIRPathFunction

A representation of the FHIRPath hasValue() function.

Methods:

Name Description
evaluate

Returns true if the input collection contains a single value which is a FHIR primitive, and it has a primitive

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns true if the input collection contains a single value which is a FHIR primitive, and it has a primitive value (e.g. as opposed to not having a value and just having extensions). Otherwise, the return value is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/additional.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns true if the input collection contains a single value which is a FHIR primitive, and it has a primitive
    value (e.g. as opposed to not having a value and just having extensions). Otherwise, the return value is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): The output collection.
    """
    if len(collection) != 1:
        has_primitive_value = False
    else:
        value = collection[0].value
        if isinstance(value, Date):
            value = value.to_date()
        elif isinstance(value, Time):
            value = value.to_time()
        elif isinstance(value, DateTime):
            value = value.to_datetime()
        has_primitive_value = value is not None and is_fhir_primitive(value)
    return [FHIRPathCollectionItem.wrap(has_primitive_value)]

HighBoundary

Path: fhircraft.fhir.path.engine.additional.HighBoundary

Bases: FHIRPathFunction

A representation of the FHIRPath highBoundary() function.

Methods:

Name Description
evaluate

Returns the high boundary of a quantity or range based on precision.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the high boundary of a quantity or range based on precision. For date/time values, returns the latest possible moment. For decimal values, returns the highest value within precision range.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/additional.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the high boundary of a quantity or range based on precision.
    For date/time values, returns the latest possible moment.
    For decimal values, returns the highest value within precision range.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): The output collection.
    """
    if not collection:
        return []

    result = []
    for item in collection:
        value = item.value

        if isinstance(value, str):
            # Handle date/time strings
            if self._is_datetime_string(value):
                high_boundary = self._get_datetime_high_boundary(value)
                result.append(FHIRPathCollectionItem.wrap(high_boundary))
            else:
                result.append(item)  # Return as-is for non-datetime strings
        elif isinstance(value, (int, float)):
            # Handle numeric values - determine precision and calculate boundary
            high_boundary = self._get_numeric_high_boundary(value)
            result.append(FHIRPathCollectionItem.wrap(high_boundary))
        elif isinstance(value, Quantity):
            # Handle Quantity type
            new_quantity = Quantity(
                value=self._get_numeric_high_boundary(value.value),
                unit=value.unit if hasattr(value, "unit") else None,
            )
            result.append(FHIRPathCollectionItem.wrap(new_quantity))
        else:
            result.append(item)  # Return as-is for other types

    return result

HtmlChecks

Path: fhircraft.fhir.path.engine.additional.HtmlChecks

Bases: FHIRPathFunction

A representation of the FHIRPath htmlChecks() function.

Methods:

Name Description
evaluate

When invoked on a single xhtml element returns true if the rules around HTML usage are met, and false if they are not.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

When invoked on a single xhtml element returns true if the rules around HTML usage are met, and false if they are not. The return value is empty on any other kind of element, or a collection of xhtml elements.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Type Description
FHIRPathCollection

bool

Raises:

Type Description
FHIRPathError

If the collection is not a single item.

Source code in fhircraft/fhir/path/engine/additional.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    When invoked on a single xhtml element returns true if the rules around HTML usage are met, and false if they are not.
    The return value is empty on any other kind of element, or a collection of xhtml elements.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        bool

    Raises:
        FHIRPathError: If the collection is not a single item.
    """

    collection = ensure_list(collection)

    if len(collection) != 1:
        return []  # Return empty for non-single collections

    item = collection[0]

    # Check if the item is an XHTML string
    if not isinstance(item.value, str):
        return []  # Return empty for non-string values

    xhtml_content = item.value.strip()

    if not xhtml_content:
        return [FHIRPathCollectionItem.wrap(False)]

    try:
        # Basic XML well-formedness check
        try:
            ET.fromstring(xhtml_content)
        except ET.ParseError:
            return [FHIRPathCollectionItem.wrap(False)]

        # Check if it starts with a div element
        if not re.match(r"^\s*<div\s", xhtml_content, re.IGNORECASE):
            return [FHIRPathCollectionItem.wrap(False)]

        # Validate HTML structure and content
        validator = self.XHTMLValidator()
        validator.feed(xhtml_content)

        # Check validation results
        if validator.errors:
            return [FHIRPathCollectionItem.wrap(False)]

        # Check if div has non-whitespace content
        if not validator.has_content:
            return [FHIRPathCollectionItem.wrap(False)]

        # Check for HTML entities (not allowed, should use Unicode)
        if re.search(
            r"&(?!#\d+;|#x[0-9a-fA-F]+;|amp;|lt;|gt;|quot;|apos;)", xhtml_content
        ):
            return [FHIRPathCollectionItem.wrap(False)]

        return [FHIRPathCollectionItem.wrap(True)]

    except Exception:
        return [FHIRPathCollectionItem.wrap(False)]

LowBoundary

Path: fhircraft.fhir.path.engine.additional.LowBoundary

Bases: FHIRPathFunction

A representation of the FHIRPath lowBoundary() function.

Methods:

Name Description
evaluate

Returns the low boundary of a quantity or range based on precision.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the low boundary of a quantity or range based on precision. For date/time values, returns the earliest possible moment. For decimal values, returns the lowest value within precision range.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/additional.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the low boundary of a quantity or range based on precision.
    For date/time values, returns the earliest possible moment.
    For decimal values, returns the lowest value within precision range.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): The output collection.
    """
    if not collection:
        return []

    result = []
    for item in collection:
        value = item.value

        if isinstance(value, str):
            # Handle date/time strings
            if self._is_datetime_string(value):
                low_boundary = self._get_datetime_low_boundary(value)
                result.append(FHIRPathCollectionItem.wrap(low_boundary))
            else:
                result.append(item)  # Return as-is for non-datetime strings
        elif isinstance(value, (int, float)):
            # Handle numeric values - determine precision and calculate boundary
            low_boundary = self._get_numeric_low_boundary(value)
            result.append(FHIRPathCollectionItem.wrap(low_boundary))
        elif isinstance(value, Quantity):
            # Handle Quantity type
            new_quantity = Quantity(
                value=self._get_numeric_low_boundary(value.value),
                unit=value.unit if hasattr(value, "unit") else None,
            )
            result.append(FHIRPathCollectionItem.wrap(new_quantity))
        else:
            result.append(item)  # Return as-is for other types

    return result

MemberOf

Path: fhircraft.fhir.path.engine.additional.MemberOf

MemberOf(valueset: str | Literal)

Bases: FHIRPathFunction

A representation of the FHIRPath memberOf() function.

Attributes:

Name Type Description
valueset str

The valueset canonical URL.

Methods:

Name Description
evaluate

When invoked on a single code-valued element, returns true if the code is a member of the given valueset.

Source code in fhircraft/fhir/path/engine/additional.py
def __init__(self, valueset: str | Literal):
    if isinstance(valueset, Literal):
        valueset = valueset.value
    if not isinstance(valueset, str):
        raise FHIRPathError("memberOf() argument must be a string.")
    self.valueset = valueset

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

When invoked on a single code-valued element, returns true if the code is a member of the given valueset. When invoked on a single concept-valued element, returns true if any code in the concept is a member of the given valueset. When invoked on a single string, returns true if the string is equal to a code in the valueset, so long as the valueset only contains one codesystem. If the valueset in this case contains more than one codesystem, the return value is empty.

If the valueset cannot be resolved as a uri to a value set, or the input is empty or has more than one value, the return value is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/additional.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    When invoked on a single code-valued element, returns true if the code is a member of the given valueset.
    When invoked on a single concept-valued element, returns true if any code in the concept is a member of
    the given valueset. When invoked on a single string, returns true if the string is equal to a code
    in the valueset, so long as the valueset only contains one codesystem. If the valueset in this case contains more than one codesystem, the return value is empty.

    If the valueset cannot be resolved as a uri to a value set, or the input is empty or has more than one value,
    the return value is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): The output collection.
    """
    raise NotImplementedError(
        "Evaluation of the FHIRPath memberOf() function is not supported."
    )

Resolve

Path: fhircraft.fhir.path.engine.additional.Resolve

Bases: FHIRPathFunction

A representation of the FHIRPath resolve() function.

Methods:

Name Description
evaluate

For each item in the collection, if it is a string that is a uri (or canonical or url), locate the target of the

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

For each item in the collection, if it is a string that is a uri (or canonical or url), locate the target of the reference, and add it to the resulting collection. If the item does not resolve to a resource, the item is ignored and nothing is added to the output collection.

The items in the collection may also represent a Reference, in which case the Reference.reference is resolved. If the input is empty, the output will be empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/additional.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    For each item in the collection, if it is a string that is a `uri` (or `canonical` or `url`), locate the target of the
    reference, and add it to the resulting collection. If the item does not resolve to a resource, the item is ignored
    and nothing is added to the output collection.

    The items in the collection may also represent a `Reference`, in which case the `Reference.reference` is resolved.
    If the input is empty, the output will be empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): The output collection.
    """
    from fhircraft.fhir.resources.factory import construct_resource_model

    output_collection = []
    for item in collection:
        if "Reference" in type(item.value).__name__:
            resource_url = item.value.reference
        elif isinstance(item.value, str):
            resource_url = item.value
        else:
            raise FHIRPathError(
                "The resolve() function requires either a collection of URIs, Canonicals, URLs or References."
            )
        if not resource_url.startswith("http://") and not resource_url.startswith(
            "https://"
        ):
            return []
        resource = load_url(resource_url)
        profile_url = resource.get("meta", {}).get("profile", [None])[0]
        if profile_url:
            profile = construct_resource_model(profile_url)
            resource = profile.model_validate(resource)
        output_collection.append(resource)
    return output_collection

Slice

Path: fhircraft.fhir.path.engine.additional.Slice

Slice(structure: str | Literal, name: str | Literal)

Bases: FHIRPathFunction

A representation of the FHIRPath slice() function.

Attributes:

Name Type Description
structure str

The structure definition URL or name.

name str

The name of the slice.

Methods:

Name Description
evaluate

Returns the given slice as defined in the given structure definition. The structure

Source code in fhircraft/fhir/path/engine/additional.py
def __init__(self, structure: str | Literal, name: str | Literal):
    if isinstance(structure, Literal):
        structure = structure.value
    if not isinstance(structure, str):
        raise FHIRPathError("Slice() argument must be a string.")
    self.structure = structure
    if isinstance(name, Literal):
        name = name.value
    if not isinstance(name, str):
        raise FHIRPathError("Slice() argument must be a string.")
    self.name = name

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the given slice as defined in the given structure definition. The structure argument is a uri that resolves to the structure definition, and the name must be the name of a slice within that structure definition. If the structure cannot be resolved, or the name of the slice within the resolved structure is not present, or those parameters are empty, and empty value is returned.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/additional.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the given slice as defined in the given structure definition. The structure
    argument is a uri that resolves to the structure definition, and the name must be the
    name of a slice within that structure definition. If the structure cannot be resolved,
    or the name of the slice within the resolved structure is not present, or those parameters
    are empty, and empty value is returned.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): The output collection.
    """
    raise NotImplementedError(
        "Evaluation of the FHIRPath slice() function is not supported."
    )

SubsumedBy

Path: fhircraft.fhir.path.engine.additional.SubsumedBy

SubsumedBy(code: str | Literal)

Bases: FHIRPathFunction

A representation of the FHIRPath subsumedBy() function.

Attributes:

Name Type Description
code str

The code to check for subsumption.

Methods:

Name Description
evaluate

When invoked on a Coding-valued element and the given code is Coding-valued, returns true if the source code is equivalent to the given code, or if the source code is subsumed by the given code (i.e. the given code is an ancestor of the source code in a subsumption hierarchy), and false otherwise.

Source code in fhircraft/fhir/path/engine/additional.py
def __init__(self, code: str | Literal):
    if isinstance(code, Literal):
        code = code.value
    if not isinstance(code, str):
        raise FHIRPathError("subsumedBy() argument must be a string.")
    self.code = code

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

When invoked on a Coding-valued element and the given code is Coding-valued, returns true if the source code is equivalent to the given code, or if the source code is subsumed by the given code (i.e. the given code is an ancestor of the source code in a subsumption hierarchy), and false otherwise.

If the Codings are from different code systems, the relationships between the code systems must be well-defined or a run-time error is thrown.

When the source or given elements are CodeableConcepts, returns true if any Coding in the source or given elements is equivalent to or subsumed by the given code.

If either the input or the code parameter are not single value collections, the return value is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/additional.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    When invoked on a Coding-valued element and the given code is Coding-valued, returns true if the source code is equivalent to the given code, or if the source code is subsumed by the given code (i.e. the given code is an ancestor of the source code in a subsumption hierarchy), and false otherwise.

    If the Codings are from different code systems, the relationships between the code systems must be well-defined or a run-time error is thrown.

    When the source or given elements are CodeableConcepts, returns true if any Coding in the source or given elements is equivalent to or subsumed by the given code.

    If either the input or the code parameter are not single value collections, the return value is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): The output collection.
    """
    raise NotImplementedError(
        "Evaluation of the FHIRPath subsumes() function is not supported."
    )

Subsumes

Path: fhircraft.fhir.path.engine.additional.Subsumes

Subsumes(code: str | Literal)

Bases: FHIRPathFunction

A representation of the FHIRPath subsumes() function.

Attributes:

Name Type Description
code str

The code to check for subsumption.

Methods:

Name Description
evaluate

When invoked on a Coding-valued element and the given code is Coding-valued, returns true if the source code is equivalent to the given code, or if the source code subsumes the given code (i.e. the source code is an ancestor of the given code in a subsumption hierarchy), and false otherwise.

Source code in fhircraft/fhir/path/engine/additional.py
def __init__(self, code: str | Literal):
    if isinstance(code, Literal):
        code = code.value
    if not isinstance(code, str):
        raise FHIRPathError("subsumes() argument must be a string.")
    self.code = code

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

When invoked on a Coding-valued element and the given code is Coding-valued, returns true if the source code is equivalent to the given code, or if the source code subsumes the given code (i.e. the source code is an ancestor of the given code in a subsumption hierarchy), and false otherwise.

If the Codings are from different code systems, the relationships between the code systems must be well-defined or the return value is an empty value.

When the source or given elements are CodeableConcepts, returns true if any Coding in the source or given elements is equivalent to or subsumes the given code.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/additional.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    When invoked on a Coding-valued element and the given code is Coding-valued, returns true if the source code is equivalent to the given code, or if the source code subsumes the given code (i.e. the source code is an ancestor of the given code in a subsumption hierarchy), and false otherwise.

    If the Codings are from different code systems, the relationships between the code systems must be well-defined or the return value is an empty value.

    When the source or given elements are CodeableConcepts, returns true if any Coding in the source or given elements is equivalent to or subsumes the given code.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): The output collection.
    """
    raise NotImplementedError(
        "Evaluation of the FHIRPath subsumes() function is not supported."
    )

TypeChoice

Path: fhircraft.fhir.path.engine.additional.TypeChoice

TypeChoice(type_choice_name: str | Literal)

Bases: FHIRPath

Source code in fhircraft/fhir/path/engine/additional.py
def __init__(self, type_choice_name: str | Literal):
    if isinstance(type_choice_name, Literal):
        type_choice_name = type_choice_name.value
    if not isinstance(type_choice_name, str):
        raise FHIRPathError("TypeChoice() argument must be a string.")
    self.type_choice_name = type_choice_name

Aggregate

Path: fhircraft.fhir.path.engine.aggregates.Aggregate

Aggregate(expression: FHIRPath, init: Any | None = None)

Bases: FHIRPathFunction

A representation of the FHIRPath aggregate() function.

Parameters:

Name Type Description Default
expression FHIRPath

The aggregator expression to be evaluated for each element of the input collection.

required
init Optional[Any]

Initial value for the $total variable, defaults to an empty collection if not provided.

None

Methods:

Name Description
evaluate

Performs general-purpose aggregation by evaluating the aggregator expression for each element of the input collection.

Source code in fhircraft/fhir/path/engine/aggregates.py
def __init__(
    self,
    expression: FHIRPath,
    init: Any | None = None,
):
    self.expression = expression
    if init is None:
        self.init = None
    else:
        init = ensure_list(init)
        if len(init) != 1:
            raise ValueError("Aggregation init must be a single value, not a list")
        self.init = FHIRPathCollectionItem.wrap(init[0]).value

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Performs general-purpose aggregation by evaluating the aggregator expression for each element of the input collection. Within this expression, the standard iteration variables of $this and $index can be accessed, but also a $total aggregation variable.

The value of the $total variable is set to init, or empty ({ }) if no init value is supplied, and is set to the result of the aggregator expression after every iteration.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/aggregates.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Performs general-purpose aggregation by evaluating the aggregator expression for each element of the input collection.
    Within this expression, the standard iteration variables of $this and $index can be accessed, but also a $total aggregation variable.

    The value of the $total variable is set to init, or empty ({ }) if no init value is supplied, and is set to the result of
    the aggregator expression after every iteration.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.
    """
    context = environment.copy()
    for index, item in enumerate(collection):
        # Set up the environment for evaluating the expression
        context = get_expression_context(context, item, index)
        context["$total"] = context.get("$total", self.init if self.init else [])
        # Evaluate the expression
        result = self.expression.evaluate([item], context, create=create)
        # Update the total variable for the next iteration
        context["$total"] = result[0].value
    result = context.get("$total")
    if result is None:
        return []
    return [FHIRPathCollectionItem.wrap(result)]

And

Path: fhircraft.fhir.path.engine.boolean.And

And(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRPath

A representation of the FHIRPath and boolean logic operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

Returns True if both operands evaluate to True, False if either operand evaluates to False, and the empty collection ([]) otherwise.

Source code in fhircraft/fhir/path/engine/boolean.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns True if both operands evaluate to True, False if either operand evaluates to False, and the empty collection ([]) otherwise.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Source code in fhircraft/fhir/path/engine/boolean.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns `True` if both operands evaluate to `True`, `False` if either operand evaluates to `False`, and the empty collection (`[]`) otherwise.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection
    """
    left_boolean, right_boolean = _evaluate_boolean_expressions(
        self.left, self.right, collection, environment, create=create
    )
    if left_boolean is None:
        if right_boolean is True:
            return []
        elif right_boolean is False:
            return [FHIRPathCollectionItem.wrap(False)]
        elif right_boolean is None:
            return []
    elif right_boolean is None:
        if left_boolean is True:
            return []
        elif left_boolean is False:
            return [FHIRPathCollectionItem.wrap(False)]
        elif left_boolean is None:
            return []
    return [FHIRPathCollectionItem.wrap(left_boolean and right_boolean)]

Implies

Path: fhircraft.fhir.path.engine.boolean.Implies

Implies(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRPath

A representation of the FHIRPath implies boolean logic operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

If the left operand evaluates to True, this operator returns the boolean evaluation of the right operand. If the

Source code in fhircraft/fhir/path/engine/boolean.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the left operand evaluates to True, this operator returns the boolean evaluation of the right operand. If the left operand evaluates to False, this operator returns True. Otherwise, this operator returns True if the right operand evaluates to True, and the empty collection ([]) otherwise.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Source code in fhircraft/fhir/path/engine/boolean.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the left operand evaluates to `True`, this operator returns the boolean evaluation of the right operand. If the
    left operand evaluates to `False`, this operator returns `True`. Otherwise, this operator returns `True` if the right
    operand evaluates to `True`, and the empty collection (`[]`) otherwise.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection
    """
    left_boolean, right_boolean = _evaluate_boolean_expressions(
        self.left, self.right, collection, environment, create
    )
    if left_boolean is None:
        if right_boolean is True:
            return [FHIRPathCollectionItem.wrap(True)]
        elif right_boolean is False:
            return []
        elif right_boolean is None:
            return []
    elif right_boolean is None:
        if left_boolean is True:
            return []
        elif left_boolean is False:
            return [FHIRPathCollectionItem.wrap(True)]
        elif left_boolean is None:
            return []
    elif left_boolean is True:
        if right_boolean is True:
            return [FHIRPathCollectionItem.wrap(True)]
        elif right_boolean is False:
            return [FHIRPathCollectionItem.wrap(False)]
    elif right_boolean is True:
        if left_boolean is True:
            return [FHIRPathCollectionItem.wrap(True)]
        elif left_boolean is False:
            return [FHIRPathCollectionItem.wrap(True)]
    elif right_boolean is False and left_boolean is False:
        return [FHIRPathCollectionItem.wrap(True)]
    return []

Not

Path: fhircraft.fhir.path.engine.boolean.Not

Bases: FHIRPathFunction

A representation of the FHIRPath not boolean logic function.

Methods:

Name Description
evaluate

Returns True if the input collection evaluates to False, and False if it evaluates to True. Otherwise, the result is empty ([]):

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns True if the input collection evaluates to False, and False if it evaluates to True. Otherwise, the result is empty ([]):

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Source code in fhircraft/fhir/path/engine/boolean.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns `True` if the input collection evaluates to `False`, and `False` if it evaluates to `True`. Otherwise, the result is empty (`[]`):


    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection
    """
    if len(collection) > 1:
        raise FHIRPathRuntimeError(
            "Cannot assert Not() for a collection that has more than one item."
        )
    elif len(collection) == 0:
        return []
    else:
        boolean = bool(collection[0].value)
        return [FHIRPathCollectionItem.wrap(not boolean)]

Or

Path: fhircraft.fhir.path.engine.boolean.Or

Or(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRPath

A representation of the FHIRPath or boolean logic operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

Returns False if both operands evaluate to False, True if either operand evaluates to True, and empty ([]) otherwise.

Source code in fhircraft/fhir/path/engine/boolean.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns False if both operands evaluate to False, True if either operand evaluates to True, and empty ([]) otherwise.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Source code in fhircraft/fhir/path/engine/boolean.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns `False` if both operands evaluate to `False`, `True` if either operand evaluates to `True`, and empty (`[]`) otherwise.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection
    """
    left_boolean, right_boolean = _evaluate_boolean_expressions(
        self.left, self.right, collection, environment, create=create
    )
    if left_boolean is None:
        if right_boolean is True:
            return [FHIRPathCollectionItem.wrap(True)]
        elif right_boolean is False:
            return []
        elif right_boolean is None:
            return []
    elif right_boolean is None:
        if left_boolean is True:
            return [FHIRPathCollectionItem.wrap(True)]
        elif left_boolean is False:
            return []
        elif left_boolean is None:
            return []
    return [FHIRPathCollectionItem.wrap(left_boolean or right_boolean)]

Xor

Path: fhircraft.fhir.path.engine.boolean.Xor

Xor(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRPath

A representation of the FHIRPath xor boolean logic operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

Returns True if exactly one of the operands evaluates to True, False if either both operands evaluate to True or both operands evaluate to False, and the empty collection ([]) otherwise.

Source code in fhircraft/fhir/path/engine/boolean.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns True if exactly one of the operands evaluates to True, False if either both operands evaluate to True or both operands evaluate to False, and the empty collection ([]) otherwise.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Source code in fhircraft/fhir/path/engine/boolean.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns `True` if exactly one of the operands evaluates to `True`, `False` if either both operands evaluate to `True` or both operands evaluate to `False`, and the empty collection (`[]`) otherwise.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection
    """
    left_boolean, right_boolean = _evaluate_boolean_expressions(
        self.left, self.right, collection, environment, create
    )
    if left_boolean is None or right_boolean is None:
        return []
    return [FHIRPathCollectionItem.wrap(left_boolean ^ right_boolean)]

Contains

Path: fhircraft.fhir.path.engine.collection.Contains

Contains(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRCollectionOperator

A representation of the FHIRPath contains operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

If the right operand is a collection with a single item, this operator returns true if the item is in the

Source code in fhircraft/fhir/path/engine/collection.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the right operand is a collection with a single item, this operator returns true if the item is in the left operand using equality semantics. If the right-hand side of the operator is empty, the result is empty, if the left-hand side is empty, the result is false. This is the converse operation of in.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathError

If the left expression evaluates to a non-singleton collection.

Source code in fhircraft/fhir/path/engine/collection.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the right operand is a collection with a single item, this operator returns true if the item is in the
    left operand using equality semantics. If the right-hand side of the operator is empty, the result is empty,
    if the left-hand side is empty, the result is false. This is the converse operation of `in`.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathError: If the left expression evaluates to a non-singleton collection.
    """
    left_collection, right_collection = evaluate_left_right_expressions(
        self.left, self.right, collection, environment, create
    )
    if len(right_collection) == 0:
        return []
    if len(left_collection) == 0:
        return [FHIRPathCollectionItem.wrap(False)]
    if len(right_collection) != 1:
        raise FHIRPathRuntimeError(
            "Right expression evaluates to a non-singleton collection."
        )
    value = right_collection[0].value
    check_collection = [
        item.value if isinstance(item, FHIRPathCollectionItem) else item
        for item in left_collection
    ]
    return [FHIRPathCollectionItem.wrap(value in check_collection)]

FHIRCollectionOperator

Path: fhircraft.fhir.path.engine.collection.FHIRCollectionOperator

FHIRCollectionOperator(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRPath

Abstract class definition for the category of collection FHIRPath operators.

Source code in fhircraft/fhir/path/engine/collection.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

In

Path: fhircraft.fhir.path.engine.collection.In

In(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRCollectionOperator

A representation of the FHIRPath in operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

If the left operand is a collection with a single item, this operator returns true if the item is in the

Source code in fhircraft/fhir/path/engine/collection.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the left operand is a collection with a single item, this operator returns true if the item is in the right operand using equality semantics. If the left-hand side of the operator is empty, the result is empty, if the right-hand side is empty, the result is false. If the left operand has multiple items, an exception is thrown.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathRuntimeError

If the left expression evaluates to a non-singleton collection.

Source code in fhircraft/fhir/path/engine/collection.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the left operand is a collection with a single item, this operator returns true if the item is in the
    right operand using equality semantics. If the left-hand side of the operator is empty, the result is empty,
    if the right-hand side is empty, the result is false. If the left operand has multiple items, an exception is thrown.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: If the left expression evaluates to a non-singleton collection.
    """
    left_collection, right_collection = evaluate_left_right_expressions(
        self.left, self.right, collection, environment, create
    )
    if len(left_collection) == 0:
        return []
    if len(right_collection) == 0:
        return [FHIRPathCollectionItem.wrap(False)]
    if len(left_collection) != 1:
        raise FHIRPathRuntimeError(
            "Left expression evaluates to a non-singleton collection."
        )
    value = left_collection[0].value
    check_collection = [
        item.value if isinstance(item, FHIRPathCollectionItem) else item
        for item in right_collection
    ]
    return [FHIRPathCollectionItem.wrap(value in check_collection)]

Union

Path: fhircraft.fhir.path.engine.collection.Union

Union(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRCollectionOperator

A representation of the FHIRPath | operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

Merge the two collections into a single collection, eliminating any duplicate values to

Source code in fhircraft/fhir/path/engine/collection.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Merge the two collections into a single collection, eliminating any duplicate values to determine equality). There is no expectation of order in the resulting collection.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/collection.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Merge the two collections into a single collection, eliminating any duplicate values to
    determine equality). There is no expectation of order in the resulting collection.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.
    """
    left_collection, right_collection = evaluate_left_right_expressions(
        self.left, self.right, collection, environment, create=create
    )
    return UnionFunction(left_collection).evaluate(
        right_collection, environment, create
    )

Combine

Path: fhircraft.fhir.path.engine.combining.Combine

Combine(other_collection: FHIRPath | FHIRPathCollection)

Bases: FHIRPathFunction

A representation of the FHIRPath combine() function.

Attributes:

Name Type Description
other_collection FHIRPathCollection

The other collection to combine with.

Methods:

Name Description
evaluate

Merge the input and other collections into a single collection without eliminating duplicate

Source code in fhircraft/fhir/path/engine/combining.py
def __init__(self, other_collection: FHIRPath | FHIRPathCollection):
    self.other_collection = other_collection

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Merge the input and other collections into a single collection without eliminating duplicate values. Combining an empty collection with a non-empty collection will return the non-empty collection.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/combining.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Merge the input and other collections into a single collection without eliminating duplicate
    values. Combining an empty collection with a non-empty collection will return the non-empty
    collection.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.
    """
    if isinstance(self.other_collection, FHIRPath):
        self.other_collection = self.other_collection.evaluate(
            collection, environment, create
        )
    return collection + self.other_collection

Union

Path: fhircraft.fhir.path.engine.combining.Union

Union(other_collection: FHIRPath | FHIRPathCollection)

Bases: FHIRPathFunction

A representation of the FHIRPath union() function.

Attributes:

Name Type Description
other_collection FHIRPathCollection

The other collection to combine with.

Methods:

Name Description
evaluate

Merge the two collections into a single collection, eliminating any duplicate values.

Source code in fhircraft/fhir/path/engine/combining.py
def __init__(self, other_collection: FHIRPath | FHIRPathCollection):
    self.other_collection = other_collection

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Merge the two collections into a single collection, eliminating any duplicate values.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/combining.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Merge the two collections into a single collection, eliminating any duplicate values.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.
    """
    if isinstance(self.other_collection, FHIRPath):
        self.other_collection = self.other_collection.evaluate(
            collection, environment, create
        )
    return [
        FHIRPathCollectionItem.wrap(item)
        for item in sorted(
            list(set(collection) | set(self.other_collection)),
            key=lambda item: item.value,
        )
    ]

FHIRComparisonOperator

Path: fhircraft.fhir.path.engine.comparison.FHIRComparisonOperator

FHIRComparisonOperator(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRPath, ABC

Abstract class definition for the category of comparison FHIRPath operators.

Source code in fhircraft/fhir/path/engine/comparison.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

GreaterEqualThan

Path: fhircraft.fhir.path.engine.comparison.GreaterEqualThan

GreaterEqualThan(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRComparisonOperator

A representation of the FHIRPath >= operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

The greater or equal operator (>=) returns true if the first operand is greater than or equal to the second.

Source code in fhircraft/fhir/path/engine/comparison.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

The greater or equal operator (>=) returns true if the first operand is greater than or equal to the second. The operands must be of the same type, or convertible to the same type using implicit conversion.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathRuntimeError

If either expression evaluates to a non-singleton collection.

Source code in fhircraft/fhir/path/engine/comparison.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    The greater or equal operator (>=) returns true if the first operand is greater than or equal to the second.
    The operands must be of the same type, or convertible to the same type using implicit conversion.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: If either expression evaluates to a non-singleton collection.
    """
    left_value, right_value = evaluate_and_prepare_collection_values(
        self, self.left, self.right, collection, environment, create
    )
    if (not left_value and left_value!=0) or (not right_value and right_value!=0):
        return []
    return [FHIRPathCollectionItem.wrap(left_value >= right_value)]

GreaterThan

Path: fhircraft.fhir.path.engine.comparison.GreaterThan

GreaterThan(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRComparisonOperator

A representation of the FHIRPath > operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

The greater than operator (>) returns true if the first operand is strictly greater than the second.

Source code in fhircraft/fhir/path/engine/comparison.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

The greater than operator (>) returns true if the first operand is strictly greater than the second. The operands must be of the same type, or convertible to the same type using an implicit conversion.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathRuntimeError

If either expression evaluates to a non-singleton collection.

Source code in fhircraft/fhir/path/engine/comparison.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    The greater than operator (>) returns true if the first operand is strictly greater than the second.
    The operands must be of the same type, or convertible to the same type using an implicit conversion.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: If either expression evaluates to a non-singleton collection.
    """
    left_value, right_value = evaluate_and_prepare_collection_values(
        self, self.left, self.right, collection, environment, create
    )
    if (not left_value and left_value!=0) or (not right_value and right_value!=0):
        return []
    return [FHIRPathCollectionItem.wrap(left_value > right_value)]

LessEqualThan

Path: fhircraft.fhir.path.engine.comparison.LessEqualThan

LessEqualThan(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRComparisonOperator

A representation of the FHIRPath <= operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

The less or equal operator (<=) returns true if the first operand is less than or equal to the second.

Source code in fhircraft/fhir/path/engine/comparison.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

The less or equal operator (<=) returns true if the first operand is less than or equal to the second. The operands must be of the same type, or convertible to the same type using implicit conversion.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathRuntimeError

If either expression evaluates to a non-singleton collection.

Source code in fhircraft/fhir/path/engine/comparison.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    The less or equal operator (<=) returns true if the first operand is less than or equal to the second.
    The operands must be of the same type, or convertible to the same type using implicit conversion.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: If either expression evaluates to a non-singleton collection.
    """
    left_value, right_value = evaluate_and_prepare_collection_values(
        self, self.left, self.right, collection, environment, create
    )
    if (not left_value and left_value!=0) or (not right_value and right_value!=0):
        return []
    return [FHIRPathCollectionItem.wrap(left_value <= right_value)]

LessThan

Path: fhircraft.fhir.path.engine.comparison.LessThan

LessThan(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRComparisonOperator

A representation of the FHIRPath < operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

The less than operator (<) returns true if the first operand is strictly less than the second.

Source code in fhircraft/fhir/path/engine/comparison.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

The less than operator (<) returns true if the first operand is strictly less than the second. The operands must be of the same type, or convertible to the same type using implicit conversion.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathRuntimeError

If either expression evaluates to a non-singleton collection.

Source code in fhircraft/fhir/path/engine/comparison.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    The less than operator (<) returns true if the first operand is strictly less than the second.
    The operands must be of the same type, or convertible to the same type using implicit conversion.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: If either expression evaluates to a non-singleton collection.
    """
    left_value, right_value = evaluate_and_prepare_collection_values(
        self, self.left, self.right, collection, environment, create
    )
    if (not left_value and left_value!=0) or (not right_value and right_value!=0):
        return []
    return [FHIRPathCollectionItem.wrap(left_value < right_value)]

ConvertsToBoolean

Path: fhircraft.fhir.path.engine.conversion.ConvertsToBoolean

Bases: FHIRTypeConversionFunction

A representation of the FHIRPath convertsToBoolean() function.

Methods:

Name Description
evaluate

If the input collection contains a single item, this function will return True if the item can be converted to a Boolean, False otherwise.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the input collection contains a single item, this function will return True if the item can be converted to a Boolean, False otherwise. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the input collection contains a single item, this function will return `True` if the item can be converted to a Boolean, `False` otherwise.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.
    """
    self.validate_collection(collection)
    if not collection:
        return []
    return [
        FHIRPathCollectionItem.wrap(
            ToBoolean().evaluate(collection, environment, create) != []
        )
    ]

ConvertsToDate

Path: fhircraft.fhir.path.engine.conversion.ConvertsToDate

Bases: FHIRTypeConversionFunction

A representation of the FHIRPath convertsToDate() function.

Methods:

Name Description
evaluate

If the input collection contains a single item, this function will return True if:

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the input collection contains a single item, this function will return True if: - the item is a Date - the item is a DateTime - the item is a String and is convertible to a Date If the item is not one of the above types, or is not convertible to a Date (using the format YYYY-MM-DD), the result is False. If the item contains a partial date (e.g. '2012-01'), the result is a partial date. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the input collection contains a single item, this function will return `True` if:
        - the item is a `Date`
        - the item is a `DateTime`
        - the item is a `String` and is convertible to a `Date`
    If the item is not one of the above types, or is not convertible to a `Date` (using the format `YYYY-MM-DD`), the result is `False`.
    If the item contains a partial date (e.g. `'2012-01'`), the result is a partial date.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.
    """
    self.validate_collection(collection)
    if not collection:
        return []
    return [
        FHIRPathCollectionItem.wrap(
            ToDate().evaluate(collection, environment, create) != []
        )
    ]

ConvertsToDateTime

Path: fhircraft.fhir.path.engine.conversion.ConvertsToDateTime

Bases: FHIRTypeConversionFunction

A representation of the FHIRPath convertsToDateTime() function.

Methods:

Name Description
evaluate

If the input collection contains a single item, this function will return True if:

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the input collection contains a single item, this function will return True if: - the item is a DateTime - the item is a Date, in which case the result is a DateTime with the year, month, and day of the Date, and the time components empty (not set to zero) - the item is a String and is convertible to a DateTime If the item is a String, but the string is not convertible to a DateTime (using the format YYYY-MM-DDThh:mm:ss.fff(+|-)hh:mm), the result is False. If the item contains a partial datetime (e.g. '2012-01-01T10:00'), the result is 'True'. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the input collection contains a single item, this function will return `True` if:
        - the item is a `DateTime`
        - the item is a `Date`, in which case the result is a `DateTime` with the year, month, and day of the `Date`, and the time components empty (not set to zero)
        - the item is a `String` and is convertible to a `DateTime`
    If the item is a `String`, but the string is not convertible to a `DateTime` (using the format `YYYY-MM-DDThh:mm:ss.fff(+|-)hh:mm`), the result is `False`.
    If the item contains a partial datetime (e.g. `'2012-01-01T10:00'`), the result is 'True'.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.
    """
    self.validate_collection(collection)
    if not collection:
        return []
    return [
        FHIRPathCollectionItem.wrap(
            ToDateTime().evaluate(collection, environment, create) != []
        )
    ]

ConvertsToDecimal

Path: fhircraft.fhir.path.engine.conversion.ConvertsToDecimal

Bases: FHIRTypeConversionFunction

A representation of the FHIRPath convertsToDecimal() function.

Methods:

Name Description
evaluate

If the input collection contains a single item, this function will return True if:

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the input collection contains a single item, this function will return True if: - the item is an Integer or Decimal - the item is a String and is convertible to a Decimal - the item is a Boolean, where True results in a 1.0 and False results in a 0.0. If the item is not one of the above types, or is not convertible to a Decimal, the result is False. If the input collection is empty, the result is empty ('[]').

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the input collection contains a single item, this function will return `True` if:
        - the item is an `Integer` or `Decimal`
        - the item is a `String` and is convertible to a `Decimal`
        - the item is a `Boolean`, where `True` results in a `1.0` and `False` results in a `0.0`.
    If the item is not one of the above types, or is not convertible to a `Decimal`, the result is `False`.
    If the input collection is empty, the result is empty ('[]').

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.
    """
    self.validate_collection(collection)
    if not collection:
        return []
    return [
        FHIRPathCollectionItem.wrap(
            ToDecimal().evaluate(collection, environment, create) != []
        )
    ]

ConvertsToInteger

Path: fhircraft.fhir.path.engine.conversion.ConvertsToInteger

Bases: FHIRTypeConversionFunction

A representation of the FHIRPath convertsToInteger() function.

Methods:

Name Description
evaluate

If the input collection contains a single item, this function will return True if the item can be converted to an Integer, False otherwise.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the input collection contains a single item, this function will return True if the item can be converted to an Integer, False otherwise. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the input collection contains a single item, this function will return `True` if the item can be converted to an Integer, `False` otherwise.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.

    """
    self.validate_collection(collection)
    if not collection:
        return []
    return [
        FHIRPathCollectionItem.wrap(
            ToInteger().evaluate(collection, environment, create) != []
        )
    ]

ConvertsToQuantity

Path: fhircraft.fhir.path.engine.conversion.ConvertsToQuantity

Bases: FHIRTypeConversionFunction

A representation of the FHIRPath convertsToQuantity() function.

Methods:

Name Description
evaluate

If the input collection contains a single item, this function will return True if:

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the input collection contains a single item, this function will return True if: - the item is an Integer, or Decimal, where the resulting quantity will have the default unit ('1') - the item is a Quantity - the item is a String and is convertible to a Quantity - the item is a Boolean, where true results in the quantity 1.0 '1', and false results in the quantity 0.0 '1' If the item is not one of the above types, the result is False. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the input collection contains a single item, this function will return `True` if:
        - the item is an `Integer`, or `Decimal`, where the resulting quantity will have the default unit (`'1'`)
        - the item is a `Quantity`
        - the item is a `String` and is convertible to a `Quantity`
        - the item is a `Boolean`, where true results in the quantity `1.0 '1'`, and false results in the quantity `0.0 '1'`
    If the item is not one of the above types, the result is `False`.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.
    """
    self.validate_collection(collection)
    if not collection:
        return []
    return [
        FHIRPathCollectionItem.wrap(
            ToQuantity().evaluate(collection, environment, create) != []
        )
    ]

ConvertsToString

Path: fhircraft.fhir.path.engine.conversion.ConvertsToString

Bases: FHIRTypeConversionFunction

A representation of the FHIRPath convertsToString() function.

Methods:

Name Description
evaluate

If the input collection contains a single item, this function will return True if:

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the input collection contains a single item, this function will return True if: - the item in the input collection is a String - the item in the input collection is an Integer, Decimal, Date, Time, DateTime, or Quantity the output will contain its String representation - the item is a Boolean, where true results in 'true' and false in 'false'. If the item is not one of the above types, the result is False. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the input collection contains a single item, this function will return `True` if:
        - the item in the input collection is a `String`
        - the item in the input collection is an `Integer`, `Decimal`, `Date`, `Time`, `DateTime`, or `Quantity` the output will contain its `String` representation
        - the item is a `Boolean`, where true results in `'true'` and false in `'false'`.
    If the item is not one of the above types, the result is `False`.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.
    """
    self.validate_collection(collection)
    if not collection:
        return []
    return [
        FHIRPathCollectionItem.wrap(
            ToString().evaluate(collection, environment, create) != []
        )
    ]

ConvertsToTime

Path: fhircraft.fhir.path.engine.conversion.ConvertsToTime

Bases: FHIRTypeConversionFunction

A representation of the FHIRPath convertsToTime() function.

Methods:

Name Description
evaluate

If the input collection contains a single item, this function will return True if:

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the input collection contains a single item, this function will return True if: - the item is a Time - the item is a String and is convertible to a Time If the item is a String, but the string is not convertible to a DateTime (using the format hh:mm:ss.fff(+|-)hh:mm), the result is False. If the item contains a partial datetime (e.g. '10:00'), the result is 'True'. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the input collection contains a single item, this function will return `True` if:
        - the item is a `Time`
        - the item is a `String` and is convertible to a `Time`
    If the item is a `String`, but the string is not convertible to a `DateTime` (using the format `hh:mm:ss.fff(+|-)hh:mm`), the result is `False`.
    If the item contains a partial datetime (e.g. `'10:00'`), the result is 'True'.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.
    """
    self.validate_collection(collection)
    if not collection:
        return []
    return [
        FHIRPathCollectionItem.wrap(
            ToTime().evaluate(collection, environment, create) != []
        )
    ]

FHIRTypeConversionFunction

Path: fhircraft.fhir.path.engine.conversion.FHIRTypeConversionFunction

Bases: FHIRPathFunction

Abstract class definition for the category of type conversion FHIRPath functions.

Methods:

Name Description
validate_collection

Validates the input collection of a FHIRPath type conversion function.

validate_collection

validate_collection(collection: FHIRPathCollection)

Validates the input collection of a FHIRPath type conversion function.

Parameters:

Name Type Description Default
collection FHIRPathCollection

Collection to be validated.

required

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def validate_collection(self, collection: FHIRPathCollection):
    """
    Validates the input collection of a FHIRPath type conversion function.

    Args:
        collection (FHIRPathCollection): Collection to be validated.

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.
    """
    if len(collection) > 1:
        raise FHIRPathRuntimeError(
            f"FHIRPath function {self.__str__()} expected a single-item collection, instead got a {len(collection)}-items collection."
        )

Iif

Path: fhircraft.fhir.path.engine.conversion.Iif

Iif(criterion: FHIRPath, true_result: FHIRPath | FHIRPathCollection, otherwise_result: FHIRPath | FHIRPathCollection = list())

Bases: FHIRPathFunction

A representation of the FHIRPath iif() function.

Parameters:

Name Type Description Default
criterion FHIRPath

The criterion expression, is expected to evaluate to a Boolean.

required
true_result Union[FHIRPath, Any]

Value to be returned if criterion evaluates to True

required
otherwise_result Optional[Union[FHIRPath, Any]]

Value to be returned if criterion evaluates to False. Defaults to an empty collection.

list()

Methods:

Name Description
evaluate

This function acts as an immediate if, also known as a conditional operator.

Source code in fhircraft/fhir/path/engine/conversion.py
def __init__(
    self,
    criterion: FHIRPath,
    true_result: FHIRPath | FHIRPathCollection,
    otherwise_result: FHIRPath | FHIRPathCollection = list(),
):
    self.criterion = criterion
    self.true_result = true_result
    self.otherwise_result = otherwise_result

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

This function acts as an immediate if, also known as a conditional operator.

If criterion evaluates to True, the function returns the value of the true_result argument. If true_result is a FHIRPath expression it is evaluated.

If criterion is False or an empty collection, the function returns the otherwise_result argument, unless the optional otherwise_result is not given, in which case the function returns an empty collection. If otherwise_result is a FHIRPath expression it is evaluated.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    This function acts as an immediate if, also known as a conditional operator.

    If `criterion` evaluates to `True`, the function returns the value of the `true_result` argument.
    If `true_result` is a FHIRPath expression it is evaluated.

    If `criterion` is `False` or an empty collection, the function returns the `otherwise_result` argument,
    unless the optional `otherwise_result` is not given, in which case the function returns an empty collection.
    If `otherwise_result` is a FHIRPath expression it is evaluated.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.

    """
    criterion_collection = []
    for index, item in enumerate(collection):
        criterion_collection.extend(
            self.criterion.evaluate(
                [item], get_expression_context(environment, item, index), create
            )
        )

    if not criterion_collection:
        criterion = False
    else:
        criterion = criterion_collection[0].value

    if criterion:
        if isinstance(self.true_result, FHIRPath):
            return self.true_result.evaluate(collection, environment, create)
        else:
            return self.true_result
    else:
        if self.otherwise_result:
            if isinstance(self.otherwise_result, FHIRPath):
                return self.otherwise_result.evaluate(
                    collection, environment, create
                )
            else:
                return self.otherwise_result
        else:
            return []

ToBoolean

Path: fhircraft.fhir.path.engine.conversion.ToBoolean

Bases: FHIRTypeConversionFunction

A representation of the FHIRPath toBoolean() function.

Methods:

Name Description
evaluate

If the input collection contains a single item, this function will return a single Boolean if:

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the input collection contains a single item, this function will return a single Boolean if: - the item is a Boolean - the item is an Integer that is equal to one of the possible integer representations of Boolean values - the item is a Decimal that is equal to one of the possible decimal representations of Boolean values - the item is a String that is equal to one of the possible string representations of Boolean values

If the item is not one of the above types, or the item is a String, Integer, or Decimal, but is not equal to one of the possible values convertible to a Boolean, the result is false. If the input collection is empty, the result is empty ('[]').

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the input collection contains a single item, this function will return a single `Boolean` if:
        - the item is a `Boolean`
        - the item is an `Integer` that is equal to one of the possible integer representations of `Boolean` values
        - the item is a `Decimal` that is equal to one of the possible decimal representations of `Boolean` values
        - the item is a `String` that is equal to one of the possible string representations of `Boolean` values

    If the item is not one of the above types, or the item is a `String`, `Integer`, or `Decimal`, but is not equal to one of the possible values convertible to a `Boolean`, the result is false.
    If the input collection is empty, the result is empty ('[]').

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.

    """
    self.validate_collection(collection)
    if not collection:
        return []

    # Use type_utils for conversion
    from fhircraft.fhir.resources.datatypes.utils import to_boolean

    value = collection[0].value
    result = to_boolean(value)

    if result is not None:
        return [FHIRPathCollectionItem.wrap(result)]
    else:
        return []

ToDate

Path: fhircraft.fhir.path.engine.conversion.ToDate

Bases: FHIRTypeConversionFunction

A representation of the FHIRPath toDate() function.

Methods:

Name Description
evaluate

If the input collection contains a single item, this function will return a single date if:

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the input collection contains a single item, this function will return a single date if: - the item is a Date - the item is a DateTime - the item is a String and is convertible to a Date If the item is not one of the above types, or is not convertible to a Date (using the format YYYY-MM-DD), the result is empty. If the item contains a partial date (e.g. '2012-01'), the result is a partial date. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the input collection contains a single item, this function will return a single date if:
        - the item is a `Date`
        - the item is a `DateTime`
        - the item is a `String` and is convertible to a `Date`
    If the item is not one of the above types, or is not convertible to a `Date` (using the format `YYYY-MM-DD`), the result is empty.
    If the item contains a partial date (e.g. `'2012-01'`), the result is a partial date.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.
    """
    self.validate_collection(collection)
    if not collection:
        return []
    value = collection[0].value
    if isinstance(value, str):
        date_match = re.match(
            rf"^{primitives.YEAR_REGEX}(-{primitives.MONTH_REGEX}(-{primitives.DAY_REGEX})?)?$",
            value,
        )
        datetime_match = re.match(
            rf"^({primitives.YEAR_REGEX}(-{primitives.MONTH_REGEX}(-{primitives.DAY_REGEX})?)?)(T{primitives.HOUR_REGEX}(:{primitives.MINUTES_REGEX}(:{primitives.SECONDS_REGEX}({primitives.TIMEZONE_REGEX})?)?)?)?",
            value,
        )
        if date_match:
            return [FHIRPathCollectionItem.wrap(value)]
        elif datetime_match:
            return [FHIRPathCollectionItem.wrap(datetime_match.group(1))]
        else:
            return []
    else:
        return []

ToDateTime

Path: fhircraft.fhir.path.engine.conversion.ToDateTime

Bases: FHIRTypeConversionFunction

A representation of the FHIRPath toDateTime() function.

Methods:

Name Description
evaluate

If the input collection contains a single item, this function will return a single datetime if:

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the input collection contains a single item, this function will return a single datetime if: - the item is a DateTime - the item is a Date, in which case the result is a DateTime with the year, month, and day of the Date, and the time components empty (not set to zero) - the item is a String and is convertible to a DateTime If the item is a String, but the string is not convertible to a DateTime (using the format YYYY-MM-DDThh:mm:ss.fff(+|-)hh:mm), the result is empty. If the item contains a partial datetime (e.g. '2012-01-01T10:00'), the result is a partial datetime. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the input collection contains a single item, this function will return a single datetime if:
        - the item is a `DateTime`
        - the item is a `Date`, in which case the result is a `DateTime` with the year, month, and day of the `Date`, and the time components empty (not set to zero)
        - the item is a `String` and is convertible to a `DateTime`
    If the item is a `String`, but the string is not convertible to a `DateTime` (using the format `YYYY-MM-DDThh:mm:ss.fff(+|-)hh:mm`), the result is empty.
    If the item contains a partial datetime (e.g. `'2012-01-01T10:00'`), the result is a partial datetime.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.
    """
    self.validate_collection(collection)
    if not collection:
        return []
    value = collection[0].value
    if isinstance(value, str):
        date_match = re.match(
            rf"^{primitives.YEAR_REGEX}(-{primitives.MONTH_REGEX}(-{primitives.DAY_REGEX})?)?$",
            value,
        )
        datetime_match = re.match(
            rf"^({primitives.YEAR_REGEX}(-{primitives.MONTH_REGEX}(-{primitives.DAY_REGEX})?)?)(T{primitives.HOUR_REGEX}(:{primitives.MINUTES_REGEX}(:{primitives.SECONDS_REGEX}({primitives.TIMEZONE_REGEX})?)?)?)?",
            value,
        )
        if date_match or datetime_match:
            return [FHIRPathCollectionItem.wrap(value)]
        else:
            return []
    else:
        return []

ToDecimal

Path: fhircraft.fhir.path.engine.conversion.ToDecimal

Bases: FHIRTypeConversionFunction

A representation of the FHIRPath toDecimal() function.

Methods:

Name Description
evaluate

If the input collection contains a single item, this function will return a single decimal if:

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the input collection contains a single item, this function will return a single decimal if: - the item is an Integer or Decimal - the item is a String and is convertible to a Decimal - the item is a Boolean, where True results in a 1.0 and False results in a 0.0. If the item is not one of the above types, the result is empty ([]). If the item is a String, but the string is not convertible to a Decimal, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the input collection contains a single item, this function will return a single decimal if:
        - the item is an `Integer` or `Decimal`
        - the item is a `String` and is convertible to a `Decimal`
        - the item is a `Boolean`, where `True` results in a `1.0` and `False` results in a `0.0`.
    If the item is not one of the above types, the result is empty (`[]`).
    If the item is a `String`, but the string is not convertible to a `Decimal`, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.
    """
    self.validate_collection(collection)
    if not collection:
        return []
    value = collection[0].value
    if isinstance(value, (int, float, bool)):
        return [FHIRPathCollectionItem.wrap(float(value))]
    elif isinstance(value, str):
        if re.match(r"(\\+|-)?\d+(\.\d+)?", value):
            return [FHIRPathCollectionItem.wrap(float(value))]
        else:
            return []
    else:
        return []

ToInteger

Path: fhircraft.fhir.path.engine.conversion.ToInteger

Bases: FHIRTypeConversionFunction

A representation of the FHIRPath toInteger() function.

Methods:

Name Description
evaluate

If the input collection contains a single item, this function will return a single Integer if:

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the input collection contains a single item, this function will return a single Integer if: - the item is an Integer - the item is a String and is convertible to an integer - the item is a Boolean, where True results in a 1 and False results in a 0. If the item is not one the above types, the result is empty ([]).

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the input collection contains a single item, this function will return a single `Integer` if:
        - the item is an `Integer`
        - the item is a `String` and is convertible to an integer
        - the item is a `Boolean`, where `True` results in a 1 and `False` results in a 0.
    If the item is not one the above types, the result is empty (`[]`).

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.
    """
    self.validate_collection(collection)
    if not collection:
        return []

    # Use type_utils for conversion
    from fhircraft.fhir.resources.datatypes.utils import to_integer

    value = collection[0].value
    result = to_integer(value)

    if result is not None:
        return [FHIRPathCollectionItem.wrap(result)]
    else:
        return []

ToQuantity

Path: fhircraft.fhir.path.engine.conversion.ToQuantity

Bases: FHIRTypeConversionFunction

A representation of the FHIRPath toQuantity() function.

Methods:

Name Description
evaluate

If the input collection contains a single item, this function will return a single quantity if:

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the input collection contains a single item, this function will return a single quantity if: - the item is an Integer, or Decimal, where the resulting quantity will have the default unit ('1') - the item is a Quantity - the item is a String and is convertible to a Quantity - the item is a Boolean, where true results in the quantity 1.0 '1', and false results in the quantity 0.0 '1' If the item is not one of the above types, the result is empty. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the input collection contains a single item, this function will return a single quantity if:
        - the item is an `Integer`, or `Decimal`, where the resulting quantity will have the default unit (`'1'`)
        - the item is a `Quantity`
        - the item is a `String` and is convertible to a `Quantity`
        - the item is a `Boolean`, where true results in the quantity `1.0 '1'`, and false results in the quantity `0.0 '1'`
    If the item is not one of the above types, the result is empty.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.
    """
    from fhircraft.fhir.resources.datatypes.utils import get_complex_FHIR_type

    self.validate_collection(collection)
    Quantity = get_complex_FHIR_type("Quantity")
    if not collection:
        return []
    value = collection[0].value
    if isinstance(value, (bool, int, float)):
        return [FHIRPathCollectionItem.wrap(Quantity(value=float(value), unit="1"))]
    elif isinstance(value, str):
        quantity_match = re.match(
            r"((\+|-)?\d+(\.\d+)?)\s*(('([^']+)'|([a-zA-Z]+))?)", value
        )
        if quantity_match:
            return [
                FHIRPathCollectionItem.wrap(
                    Quantity(
                        value=quantity_match.group(1), unit=quantity_match.group(4)
                    )
                )
            ]
        else:
            return []
    elif isinstance(value, Quantity):
        return [FHIRPathCollectionItem.wrap(value)]
    else:
        return []

ToString

Path: fhircraft.fhir.path.engine.conversion.ToString

Bases: FHIRTypeConversionFunction

A representation of the FHIRPath toString() function.

Methods:

Name Description
evaluate

If the input collection contains a single item, this function will return a single string if:

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the input collection contains a single item, this function will return a single string if: - the item in the input collection is a String - the item in the input collection is an Integer, Decimal, Date, Time, DateTime, or Quantity the output will contain its String representation - the item is a Boolean, where true results in 'true' and false in 'false'. If the item is not one of the above types, the result is empty. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the input collection contains a single item, this function will return a single string if:
        - the item in the input collection is a `String`
        - the item in the input collection is an `Integer`, `Decimal`, `Date`, `Time`, `DateTime`, or `Quantity` the output will contain its `String` representation
        - the item is a `Boolean`, where true results in `'true'` and false in `'false'`.
    If the item is not one of the above types, the result is empty.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.
    """
    from fhircraft.fhir.resources.datatypes.utils import get_complex_FHIR_type

    self.validate_collection(collection)
    if not collection:
        return []
    value = collection[0].value
    if isinstance(value, bool):
        return [FHIRPathCollectionItem.wrap("true" if value else "false")]
    elif isinstance(value, (str, int, float)):
        return [FHIRPathCollectionItem.wrap(str(value))]
    elif isinstance(value, get_complex_FHIR_type("Quantity")):
        return [FHIRPathCollectionItem.wrap(f"{value.value} {value.unit}")]
    else:
        return []

ToTime

Path: fhircraft.fhir.path.engine.conversion.ToTime

Bases: FHIRTypeConversionFunction

A representation of the FHIRPath toTime() function.

Methods:

Name Description
evaluate

If the input collection contains a single item, this function will return a single time if:

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the input collection contains a single item, this function will return a single time if: - the item is a Time - the item is a String and is convertible to a Time If the item is a String, but the string is not convertible to a Time (using the format hh:mm:ss.fff(+|-)hh:mm), the result is empty. If the item contains a partial datetime (e.g. '10:00'), the result is a partial datetime. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Raises:

Type Description
FHIRPathRuntimeError

If input collection has more than one item.

Source code in fhircraft/fhir/path/engine/conversion.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the input collection contains a single item, this function will return a single time if:
        - the item is a `Time`
        - the item is a `String` and is convertible to a `Time`
    If the item is a `String`, but the string is not convertible to a `Time` (using the format `hh:mm:ss.fff(+|-)hh:mm`), the result is empty.
    If the item contains a partial datetime (e.g. `'10:00'`), the result is a partial datetime.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Raises:
        FHIRPathRuntimeError: If input collection has more than one item.
    """
    self.validate_collection(collection)
    if not collection:
        return []
    value = collection[0].value
    if isinstance(value, str):
        time_match = re.match(
            rf"^{primitives.HOUR_REGEX}(:{primitives.MINUTES_REGEX}(:{primitives.SECONDS_REGEX}({primitives.TIMEZONE_REGEX})?)?)?",
            value,
        )
        if time_match:
            return [FHIRPathCollectionItem.wrap(value)]
        else:
            return []
    else:
        return []

Element

Path: fhircraft.fhir.path.engine.core.Element

Element(label: str | Literal)

Bases: FHIRPath

A class representing an element in a FHIRPath, used for navigating and manipulating FHIR resources.

Attributes:

Name Type Description
label str

The name of the element.

Methods:

Name Description
create_element

Ensure that the input parent object has the necessary field information to create a new element based on the label provided.

setter

Sets the value of the specified element in the parent object.

Source code in fhircraft/fhir/path/engine/core.py
def __init__(self, label: str | Literal):
    if isinstance(label, Literal):
        label = label.value
    if not isinstance(label, str):
        raise FHIRPathError("Element() argument must be a string.")
    self.label = label

create_element

create_element(parent: Any) -> Any

Ensure that the input parent object has the necessary field information to create a new element based on the label provided.

Parameters:

Name Type Description Default
parent Any

The parent object from which the element will be created.

required

Returns:

Name Type Description
element Any

The newly created element based on the field information of the parent object, or None if the parent is invalid or lacks the required field information.

Raises:

Type Description
KeyError

If there is an issue with retrieving the field information from the parent object.

AttributeError

If there is an attribute error while trying to create the new element.

Source code in fhircraft/fhir/path/engine/core.py
def create_element(self, parent: typing.Any) -> typing.Any:
    """
    Ensure that the input parent object has the necessary field information to create a new element based on the label provided.

    Args:
        parent (Any): The parent object from which the element will be created.

    Returns:
        element (Any): The newly created element based on the field information of the parent object, or None if the parent is invalid or lacks the required field information.

    Raises:
        KeyError: If there is an issue with retrieving the field information from the parent object.
        AttributeError: If there is an attribute error while trying to create the new element.
    """
    if not parent:
        return None
    if not hasattr(parent.__class__, "model_fields"):
        return None
    field_info = parent.__class__.model_fields.get(self.label)

    # Check if parent model allows extra fields
    if field_info is None:
        model_config = getattr(parent.__class__, "model_config", {})
        extra_setting = (
            model_config.get("extra")
            if isinstance(model_config, dict)
            else getattr(model_config, "extra", None)
        )
        if extra_setting == "allow":
            # For models with extra='allow', create new instance of same type
            # This supports dynamic models
            new_element = parent.__class__()
            return new_element
        return None

    model = get_fhir_model_from_field(field_info)
    if not model:
        new_element = None
    else:
        new_element = model.model_construct()
    if field_info and contains_list_type(field_info.annotation):
        new_element = ensure_list(new_element)
    return new_element

setter staticmethod

setter(value: Any, item: FHIRPathCollectionItem, index: int, label: str, is_list_type: bool) -> None

Sets the value of the specified element in the parent object.

Parameters:

Name Type Description Default
value Any

The value to set for the element.

required
item FHIRPathCollectionItem

The parent collection item.

required
index int

The index of the element in the parent object.

required
label str

The label of the element to set.

required
Source code in fhircraft/fhir/path/engine/core.py
@staticmethod
def setter(
    value: typing.Any,
    item: FHIRPathCollectionItem,
    index: int,
    label: str,
    is_list_type: bool,
) -> None:
    """
    Sets the value of the specified element in the parent object.

    Args:
        value (Any): The value to set for the element.
        item (FHIRPathCollectionItem): The parent collection item.
        index (int): The index of the element in the parent object.
        label (str): The label of the element to set.
    """
    parent = item.value
    current_values = getattr(parent, label)
    if not isinstance(current_values, list):
        if not is_list_type and isinstance(value, list):
            if value and len(value) > 1:
                raise ValueError(
                    f"Cannot set multiple values to non-list field '{label}'"
                )
            value = value[0] if value else None
        setattr(parent, label, value)
    else:
        if is_list_type and isinstance(value, list):
            setattr(parent, label, value)
        elif len(current_values) <= index:
            current_values.insert(index, value)
        else:
            current_values[index] = value

FHIRPath

Path: fhircraft.fhir.path.engine.core.FHIRPath

Bases: ABC

Abstract base class for FHIRPath expressions.

Methods:

Name Description
values

Evaluates the FHIRPath expression and returns all resulting values as a list.

single

Evaluates the FHIRPath expression and returns a single value.

first

Evaluates the FHIRPath expression and returns the first value.

last

Evaluates the FHIRPath expression and returns the last value.

exists

Checks if the FHIRPath expression matches any values in the data.

count

Returns the number of values that match the FHIRPath expression.

is_empty

Checks if the FHIRPath expression matches no values in the data.

update_values

Evaluates the FHIRPath expression and sets all matching locations to the given value.

update_single

Evaluates the FHIRPath expression and sets a single matching location to the given value.

trace

Returns a trace of evaluation steps for debugging purposes.

debug_info

Returns debugging information about the evaluation.

evaluate

Evaluates the current object against the provided FHIRPathCollection.

values

values(data: Any, environment: dict | None = None) -> List[Any]

Evaluates the FHIRPath expression and returns all resulting values as a list.

Parameters:

Name Type Description Default
data Any

The data to evaluate the FHIRPath expression against.

required
environment dict | None

Optional map of additional variables to include in the evaluation context.

None

Returns:

Type Description
List[Any]

List[Any]: A list of all values that match the FHIRPath expression. Returns an empty list if no matches are found.

Source code in fhircraft/fhir/path/engine/core.py
def values(self, data: Any, environment: dict | None = None) -> List[Any]:
    """
    Evaluates the FHIRPath expression and returns all resulting values as a list.

    Args:
        data: The data to evaluate the FHIRPath expression against.
        environment: Optional map of additional variables to include in the evaluation context.

    Returns:
        List[Any]: A list of all values that match the FHIRPath expression. Returns an empty list if no matches are found.
    """
    collection = self.__evaluate_wrapped(data, environment=environment)
    return [item.value for item in collection]

single

single(data: Any, default: Any = None, environment: dict | None = None) -> Any

Evaluates the FHIRPath expression and returns a single value.

Parameters:

Name Type Description Default
data Any

The data to evaluate the FHIRPath expression against.

required
default Any

The default value to return if no matches are found.

None
environment dict | None

Optional map of additional variables to include in the evaluation context.

None

Returns:

Name Type Description
Any Any

The single matching value.

Raises:

Type Description
FHIRPathError

If more than one value is found.

Source code in fhircraft/fhir/path/engine/core.py
def single(
    self, data: Any, default: Any = None, environment: dict | None = None
) -> Any:
    """
    Evaluates the FHIRPath expression and returns a single value.

    Args:
        data: The data to evaluate the FHIRPath expression against.
        default: The default value to return if no matches are found.
        environment: Optional map of additional variables to include in the evaluation context.

    Returns:
        Any: The single matching value.

    Raises:
        FHIRPathError: If more than one value is found.
    """
    values = self.values(data, environment=environment)
    if len(values) == 0:
        return default
    elif len(values) == 1:
        return values[0]
    else:
        raise FHIRPathRuntimeError(
            f"Expected single value but found {len(values)} values. "
            f"Use values() to retrieve multiple values or first() to get the first one."
        )

first

first(data: Any, default: Any = None, environment: dict | None = None) -> Any

Evaluates the FHIRPath expression and returns the first value.

Parameters:

Name Type Description Default
data Any

The data to evaluate the FHIRPath expression against.

required
default Any

The default value to return if no matches are found.

None
environment dict | None

Optional map of additional variables to include in the evaluation context.

None

Returns:

Name Type Description
Any Any

The first matching value, or the default if no matches.

Source code in fhircraft/fhir/path/engine/core.py
def first(
    self, data: Any, default: Any = None, environment: dict | None = None
) -> Any:
    """
    Evaluates the FHIRPath expression and returns the first value.

    Args:
        data: The data to evaluate the FHIRPath expression against.
        default: The default value to return if no matches are found.
        environment: Optional map of additional variables to include in the evaluation context.

    Returns:
        Any: The first matching value, or the default if no matches.
    """
    values = self.values(data, environment=environment)
    return values[0] if values else default

last

last(data: Any, default: Any = None, environment: dict | None = None) -> Any

Evaluates the FHIRPath expression and returns the last value.

Parameters:

Name Type Description Default
data Any

The data to evaluate the FHIRPath expression against.

required
default Any

The default value to return if no matches are found.

None
environment dict | None

Optional map of additional variables to include in the evaluation context.

None

Returns:

Name Type Description
Any Any

The last matching value, or the default if no matches.

Source code in fhircraft/fhir/path/engine/core.py
def last(
    self, data: Any, default: Any = None, environment: dict | None = None
) -> Any:
    """
    Evaluates the FHIRPath expression and returns the last value.

    Args:
        data: The data to evaluate the FHIRPath expression against.
        default: The default value to return if no matches are found.
        environment: Optional map of additional variables to include in the evaluation context.

    Returns:
        Any: The last matching value, or the default if no matches.
    """
    values = self.values(data, environment=environment)
    return values[-1] if values else default

exists

exists(data: Any, environment: dict | None = None) -> bool

Checks if the FHIRPath expression matches any values in the data.

Parameters:

Name Type Description Default
data Any

The data to evaluate the FHIRPath expression against.

required
environment dict | None

Optional map of additional variables to include in the evaluation context.

None

Returns:

Name Type Description
bool bool

True if at least one value matches, False otherwise.

Source code in fhircraft/fhir/path/engine/core.py
def exists(self, data: Any, environment: dict | None = None) -> bool:
    """
    Checks if the FHIRPath expression matches any values in the data.

    Args:
        data: The data to evaluate the FHIRPath expression against.
        environment: Optional map of additional variables to include in the evaluation context.

    Returns:
        bool: True if at least one value matches, False otherwise.
    """
    return len(self.values(data, environment=environment)) > 0

count

count(data: Any, environment: dict | None = None) -> int

Returns the number of values that match the FHIRPath expression.

Parameters:

Name Type Description Default
data Any

The data to evaluate the FHIRPath expression against.

required
environment dict | None

Optional map of additional variables to include in the evaluation context.

None

Returns:

Name Type Description
int int

The number of matching values.

Source code in fhircraft/fhir/path/engine/core.py
def count(self, data: Any, environment: dict | None = None) -> int:
    """
    Returns the number of values that match the FHIRPath expression.

    Args:
        data: The data to evaluate the FHIRPath expression against.
        environment: Optional map of additional variables to include in the evaluation context.

    Returns:
        int: The number of matching values.
    """
    return len(self.values(data, environment=environment))

is_empty

is_empty(data: Any, environment: dict | None = None) -> bool

Checks if the FHIRPath expression matches no values in the data.

Parameters:

Name Type Description Default
data Any

The data to evaluate the FHIRPath expression against.

required
environment dict | None

Optional map of additional variables to include in the evaluation context.

None

Returns:

Name Type Description
bool bool

True if no values match, False otherwise.

Source code in fhircraft/fhir/path/engine/core.py
def is_empty(self, data: Any, environment: dict | None = None) -> bool:
    """
    Checks if the FHIRPath expression matches no values in the data.

    Args:
        data: The data to evaluate the FHIRPath expression against.
        environment: Optional map of additional variables to include in the evaluation context.

    Returns:
        bool: True if no values match, False otherwise.
    """
    return not self.exists(data, environment=environment)

update_values

update_values(data: Any, value: Any, environment: dict | None = None) -> None

Evaluates the FHIRPath expression and sets all matching locations to the given value.

Parameters:

Name Type Description Default
data Any

The data to evaluate the FHIRPath expression against.

required
value Any

The value to set at all matching locations.

required
environment dict | None

Optional map of additional variables to include in the evaluation context.

None

Raises:

Type Description
RuntimeError

If no matching locations are found or if locations cannot be set.

Source code in fhircraft/fhir/path/engine/core.py
def update_values(
    self, data: Any, value: Any, environment: dict | None = None
) -> None:
    """
    Evaluates the FHIRPath expression and sets all matching locations to the given value.

    Args:
        data: The data to evaluate the FHIRPath expression against.
        value: The value to set at all matching locations.
        environment: Optional map of additional variables to include in the evaluation context.

    Raises:
        RuntimeError: If no matching locations are found or if locations cannot be set.
    """
    collection = self.__evaluate_wrapped(data, environment=environment, create=True)
    if not collection:
        raise RuntimeError(
            "No matching locations found. Cannot set value on empty result."
        )
    for item in collection:
        item.set_value(value)

update_single

update_single(data: Any, value: Any, environment: dict | None = None) -> None

Evaluates the FHIRPath expression and sets a single matching location to the given value.

Parameters:

Name Type Description Default
data Any

The data to evaluate the FHIRPath expression against.

required
value Any

The value to set at the matching location.

required

Raises:

Type Description
FHIRPathError

If zero or more than one matching locations are found.

RuntimeError

If the location cannot be set.

Source code in fhircraft/fhir/path/engine/core.py
def update_single(
    self, data: Any, value: Any, environment: dict | None = None
) -> None:
    """
    Evaluates the FHIRPath expression and sets a single matching location to the given value.

    Args:
        data: The data to evaluate the FHIRPath expression against.
        value: The value to set at the matching location.

    Raises:
        FHIRPathError: If zero or more than one matching locations are found.
        RuntimeError: If the location cannot be set.
    """
    collection = self.__evaluate_wrapped(data, environment=environment, create=True)
    if len(collection) == 0:
        raise FHIRPathError(
            "FHIRPath yielded empty collection. Cannot set value on empty result."
        )
    elif len(collection) > 1:
        raise FHIRPathError(
            f"Expected single location but found {len(collection)} locations. "
            f"Use update_values() to set all locations."
        )
    collection[0].set_value(value)

trace

trace(data: Any, verbose: bool = False, environment: dict | None = None) -> List[str]

Returns a trace of evaluation steps for debugging purposes.

Parameters:

Name Type Description Default
data Any

The data to evaluate the FHIRPath expression against.

required
verbose bool

If True, includes detailed information about each step.

False

Returns:

Type Description
List[str]

List[str]: A list of trace messages showing the evaluation steps.

Source code in fhircraft/fhir/path/engine/core.py
def trace(
    self, data: Any, verbose: bool = False, environment: dict | None = None
) -> List[str]:
    """
    Returns a trace of evaluation steps for debugging purposes.

    Args:
        data: The data to evaluate the FHIRPath expression against.
        verbose: If True, includes detailed information about each step.

    Returns:
        List[str]: A list of trace messages showing the evaluation steps.
    """
    trace_messages = []

    def trace_step(message: str, level: int = 0):
        indent = "  " * level
        trace_messages.append(f"{indent}{message}")

    try:
        # Start tracing
        trace_step(f"Starting evaluation of: {self}")
        trace_step(f"Input data type: {type(data).__name__}")

        if verbose:
            trace_step(f"Input data: {repr(data)[:100]}...")

        # Wrap data and trace collection creation
        wrapped_data = [
            FHIRPathCollectionItem.wrap(item) for item in ensure_list(data)
        ]
        trace_step(f"Created collection with {len(wrapped_data)} items")

        if verbose:
            for i, item in enumerate(wrapped_data):
                trace_step(
                    f"  Item {i}: {type(item.value).__name__} = {repr(item.value)[:50]}...",
                    1,
                )

        # Evaluate and trace results
        result_collection = self.evaluate(
            wrapped_data, environment=environment or dict(), create=False
        )
        trace_step(f"Evaluation completed: {len(result_collection)} results")

        if verbose:
            for i, item in enumerate(result_collection):
                trace_step(
                    f"  Result {i}: {type(item.value).__name__} = {repr(item.value)[:50]}...",
                    1,
                )
                if item.path:
                    trace_step(f"    Path: {item.path}", 2)
                if item.parent:
                    trace_step(f"    Parent: {type(item.parent.value).__name__}", 2)

        # Extract values for final result
        values = [item.value for item in result_collection]
        trace_step(f"Final result: {len(values)} values")

    except Exception as e:
        trace_step(f"ERROR during evaluation: {type(e).__name__}: {str(e)}")
        trace_step(f"Expression: {self}")

    return trace_messages

debug_info

debug_info(data: Any) -> dict

Returns debugging information about the evaluation.

Parameters:

Name Type Description Default
data Any

The data to evaluate the FHIRPath expression against.

required

Returns:

Type Description
dict

A dictionary containing debugging information including: - expression: String representation of the FHIRPath expression - expression_type: Type of the FHIRPath expression - input_data_type: Type of the input data - input_data_size: Size/length of input data if applicable - result_count: Number of results from evaluation - result_types: Types of result values - evaluation_success: Whether evaluation completed successfully - error: Error information if evaluation failed - collection_items: Information about FHIRPathCollectionItem objects

Source code in fhircraft/fhir/path/engine/core.py
def debug_info(self, data: Any) -> dict:
    """
    Returns debugging information about the evaluation.

    Args:
        data: The data to evaluate the FHIRPath expression against.

    Returns:
        (dict): A dictionary containing debugging information including:
            - expression: String representation of the FHIRPath expression
            - expression_type: Type of the FHIRPath expression
            - input_data_type: Type of the input data
            - input_data_size: Size/length of input data if applicable
            - result_count: Number of results from evaluation
            - result_types: Types of result values
            - evaluation_success: Whether evaluation completed successfully
            - error: Error information if evaluation failed
            - collection_items: Information about FHIRPathCollectionItem objects
    """
    debug_data = {
        "expression": str(self),
        "expression_type": type(self).__name__,
        "expression_repr": repr(self),
        "input_data_type": type(data).__name__,
        "input_data_size": None,
        "result_count": 0,
        "result_types": [],
        "result_values": [],
        "evaluation_success": False,
        "error": None,
        "collection_items": [],
        "trace": [],
    }

    try:
        # Analyze input data
        if hasattr(data, "__len__") and not isinstance(data, str):
            debug_data["input_data_size"] = len(data)

        # Get trace information
        debug_data["trace"] = self.trace(data, verbose=True)

        # Perform evaluation
        result_collection = self.__evaluate_wrapped(data, create=False)

        # Analyze results
        debug_data["result_count"] = len(result_collection)
        debug_data["evaluation_success"] = True

        for item in result_collection:
            debug_data["result_types"].append(type(item.value).__name__)
            debug_data["result_values"].append(repr(item.value)[:100])

            # Collection item details
            item_info = {
                "value_type": type(item.value).__name__,
                "value_repr": repr(item.value)[:100],
                "path": str(item.path) if item.path else None,
                "path_type": type(item.path).__name__ if item.path else None,
                "has_parent": item.parent is not None,
                "has_setter": item.setter is not None,
                "element": item.element,
                "index": item.index,
            }
            debug_data["collection_items"].append(item_info)

        # Remove duplicates from result_types
        debug_data["result_types"] = list(set(debug_data["result_types"]))

    except Exception as e:
        debug_data["evaluation_success"] = False
        debug_data["error"] = {
            "type": type(e).__name__,
            "message": str(e),
            "expression": str(self),
        }

        # Still try to get trace even if evaluation failed
        try:
            debug_data["trace"] = self.trace(data, verbose=True)
        except:
            debug_data["trace"] = [
                f"Failed to generate trace for expression: {self}"
            ]

    return debug_data

evaluate abstractmethod

evaluate(collection: FHIRPathCollection, environment: dict, create: bool) -> FHIRPathCollection

Evaluates the current object against the provided FHIRPathCollection.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The collection of FHIRPath elements to evaluate.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

required

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The result of the evaluation as a FHIRPathCollection.

Raises:

Type Description
NotImplementedError

This method must be implemented by subclasses.

Source code in fhircraft/fhir/path/engine/core.py
@abstractmethod
def evaluate(
    self,
    collection: FHIRPathCollection,
    environment: dict,
    create: bool,
) -> FHIRPathCollection:
    """
    Evaluates the current object against the provided FHIRPathCollection.

    Args:
        collection (FHIRPathCollection): The collection of FHIRPath elements to evaluate.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The result of the evaluation as a FHIRPathCollection.

    Raises:
        NotImplementedError: This method must be implemented by subclasses.
    """
    raise NotImplementedError()

FHIRPathCollectionItem

Path: fhircraft.fhir.path.engine.core.FHIRPathCollectionItem

dataclass

FHIRPathCollectionItem(value: Any, path: Any = None, element: Optional[str] = None, index: Optional[int] = None, parent: Optional[FHIRPathCollectionItem] = None, setter: Optional[Callable] = None)

Bases: object

A context-aware representation of an item in a FHIRPath collection.

Attributes

value (Any): The value of the collection item. path (Optional[FHIRPath]): The path associated with the collection item, by default This(). element (Optional[str]): The element name of the collection item, by default None. index (Optional[int]): The index of the collection item, by default None. parent (Optional[FHIRPathCollectionItem]): The item of the parent collection from which this item was derived, by default None. setter (Optional[callable]): The setter function for the collection item, by default None.

Parameters:

Name Type Description Default
value Any
required
path Any
None
element str | None
None
index int | None
None
parent ForwardRef | None
None
setter Callable | None
None

Methods:

Name Description
wrap

Wraps data in a FHIRPathCollectionItem instance.

set_value

Sets the value of the item using the setter function.

construct_resource

Constructs a FHIR resource based on the field information.

Attributes:

Name Type Description
field_info

Retrieves the field information from the parent's value.

is_list_type

Checks if the field information indicates a list type.

full_path

Retrieves the full path of the item.

field_info property

field_info

Retrieves the field information from the parent's value.

Returns:

Type Description
Any

The field information, or None if not available.

is_list_type property

is_list_type

Checks if the field information indicates a list type.

Returns:

Type Description
bool

True if the field information indicates a list type, False otherwise.

full_path property

full_path

Retrieves the full path of the item.

Returns:

Type Description
str

The full path of the item.

wrap classmethod

wrap(data: Any) -> FHIRPathCollectionItem

Wraps data in a FHIRPathCollectionItem instance.

Parameters:

Name Type Description Default
data Any

The data to be wrapped.

required

Returns:

Name Type Description
item FHIRPathCollectionItem

The wrapped FHIRPathCollectionItem instance.

Source code in fhircraft/fhir/path/engine/core.py
@classmethod
def wrap(cls, data: Any) -> "FHIRPathCollectionItem":
    """
    Wraps data in a FHIRPathCollectionItem instance.

    Args:
        data (Any): The data to be wrapped.

    Returns:
        item (FHIRPathCollectionItem): The wrapped FHIRPathCollectionItem instance.
    """
    if isinstance(data, cls):
        return data
    else:
        return cls(data)

set_value

set_value(value)

Sets the value of the item using the setter function.

Parameters:

Name Type Description Default
value Any

The value to set.

required

Raises:

Type Description
ValueError

If the value is a list.

RuntimeError

If there is no setter function associated with this item.

Source code in fhircraft/fhir/path/engine/core.py
def set_value(self, value):
    """
    Sets the value of the item using the setter function.

    Args:
        value (Any): The value to set.

    Raises:
        ValueError: If the value is a list.
        RuntimeError: If there is no setter function associated with this item.
    """
    if self.setter:
        self.setter(value)
    else:
        raise RuntimeError("There is not setter function associated with this item")

construct_resource

construct_resource()

Constructs a FHIR resource based on the field information.

Returns:

Type Description
Any

The constructed FHIR resource, or None if construction fails.

Source code in fhircraft/fhir/path/engine/core.py
def construct_resource(self):
    """
    Constructs a FHIR resource based on the field information.

    Returns:
        (Any): The constructed FHIR resource, or None if construction fails.
    """
    if self.field_info:
        model = get_fhir_model_from_field(self.field_info)
        if not model:
            raise ValueError(
                f"Could not construct resource from field information: {self.field_info}"
            )
        return model.model_construct()

FHIRPathFunction

Path: fhircraft.fhir.path.engine.core.FHIRPathFunction

Bases: FHIRPath, ABC

Abstract base class representing a FHIRPath function, used for functional evaluation of collections.

Invocation

Path: fhircraft.fhir.path.engine.core.Invocation

Invocation(left: FHIRPath, right: FHIRPath)

Bases: FHIRPath

A class representing an invocation in the context of FHIRPath evaluation indicated by two dot-separated identifiers <left>.<right>.

Attributes:

Name Type Description
left FHIRPath

The left-hand side FHIRPath segment of the invocation.

right FHIRPath

The right-hand side FHIRPath segment of the invocation.

Methods:

Name Description
evaluate

Performs the evaluation of the Invocation by applying the left-hand side FHIRPath segment on the given collection to obtain a parent collection.

Source code in fhircraft/fhir/path/engine/core.py
def __init__(self, left: FHIRPath, right: FHIRPath):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Performs the evaluation of the Invocation by applying the left-hand side FHIRPath segment on the given collection to obtain a parent collection. Then, the right-hand side FHIRPath segment is applied on the parent collection to derive the child collection.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The collection on which the evaluation is performed.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The resulting child collection after the evaluation process.

Source code in fhircraft/fhir/path/engine/core.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Performs the evaluation of the Invocation by applying the left-hand side FHIRPath segment on the given collection to obtain a parent collection.
    Then, the right-hand side FHIRPath segment is applied on the parent collection to derive the child collection.

    Args:
        collection (FHIRPathCollection): The collection on which the evaluation is performed.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The resulting child collection after the evaluation process.
    """
    parent_collection = self.left.evaluate(collection, environment, create)
    return self.right.evaluate(parent_collection, environment, create)

Literal

Path: fhircraft.fhir.path.engine.core.Literal

Literal(value: Any)

Bases: FHIRPath

A class representation of a constant literal value in the FHIRPath.

Attributes:

Name Type Description
value Any

The literal value to be represented.

Methods:

Name Description
evaluate

Simply returns the input collection.

Source code in fhircraft/fhir/path/engine/core.py
def __init__(self, value: Any):
    self.value = value

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Simply returns the input collection.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The collection of items to be evaluated.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

A list of FHIRPathCollectionItem instances after evaluation.

Source code in fhircraft/fhir/path/engine/core.py
def evaluate(
    self,
    collection: FHIRPathCollection,
    environment: dict,
    create: bool = False,
) -> FHIRPathCollection:
    """
    Simply returns the input collection.

    Args:
        collection (FHIRPathCollection): The collection of items to be evaluated.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): A list of FHIRPathCollectionItem instances after evaluation.
    """
    return [FHIRPathCollectionItem(self.value, parent=None, path=None)]

RootElement

Path: fhircraft.fhir.path.engine.core.RootElement

RootElement(type: str = 'Resource')

Bases: FHIRPath

A class representing the root of a FHIRPath, i.e. the top-most segment of the FHIRPath whose collection has no parent associated.

Attributes:

Name Type Description
type str

The expected FHIR resource type of the root element, by default.

Methods:

Name Description
evaluate

Evaluate the input collection to assert that the entries are valid FHIR resources of the given type.

Source code in fhircraft/fhir/path/engine/core.py
def __init__(self, type: str = "Resource"):
    self.type = type

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Evaluate the input collection to assert that the entries are valid FHIR resources of the given type.

Parameters:

Name Type Description Default
collection Collection

The collection of items to be evaluated.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection Collection

The same collection after validation.

Source code in fhircraft/fhir/path/engine/core.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Evaluate the input collection to assert that the entries are valid FHIR resources of the given type.

    Args:
        collection (Collection): The collection of items to be evaluated.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (Collection): The same collection after validation.
    """
    for item in collection:
        resource = item.value
        # Check if resource is of valid type
        if (
            isinstance(resource, dict)
            and (
                "resourceType" not in resource
                or not resource["resourceType"] == self.type
            )
        ) or (
            not isinstance(resource, dict)
            and (
                not hasattr(resource, "resourceType")
                or not resource.resourceType == self.type
            )
        ):
            raise FHIRPathError(
                f"Root element must be a valid FHIR resource of type {self.type}."
            )
    return collection

This

Path: fhircraft.fhir.path.engine.core.This

Bases: FHIRPath

A representation of a current element. Used for internal purposes and has no FHIRPath shorthand notation.

Methods:

Name Description
evaluate

Simply returns the input collection.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Simply returns the input collection.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The collection of items to be evaluated.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/core.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Simply returns the input collection.

    Args:
        collection (FHIRPathCollection): The collection of items to be evaluated.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): The output collection.
    """
    return environment.get("this", collection)

TypeSpecifier

Path: fhircraft.fhir.path.engine.core.TypeSpecifier

TypeSpecifier(specifier: str)

Bases: FHIRPath

A type specifier is an identifier that must resolve to the name of a type in a model. Type specifiers can have qualifiers, e.g. FHIR.Patient, where the qualifier is the name of the model.

Attributes:

Name Type Description
specifier str

The type specifier string.

namespace Optional[str]

The namespace of the type specifier, by default "FHIR".

Methods:

Name Description
evaluate

Evaluate the input collection to assert that the entries are valid FHIR resources of the given type.

Source code in fhircraft/fhir/path/engine/core.py
def __init__(self, specifier: str):
    if "." in specifier:
        namespace, specifier = specifier.split(".", 1)
    else:
        namespace = None
    self.specifier: str = specifier
    self.namespace: str | None = namespace

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Evaluate the input collection to assert that the entries are valid FHIR resources of the given type. The type is resolved based on the namespace and specifier using the FHIR release specified in the environment variable %fhirRelease. If the variable is not present, it defaults to "R4" and will warn on usage.

Parameters:

Name Type Description Default
collection Collection

The collection of items to be evaluated.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection Collection

The same collection after validation.

Source code in fhircraft/fhir/path/engine/core.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Evaluate the input collection to assert that the entries are valid FHIR resources of the given type.
    The type is resolved based on the namespace and specifier using the FHIR release specified in the environment
    variable `%fhirRelease`. If the variable is not present, it defaults to "R4" and will warn on usage.

    Args:
        collection (Collection): The collection of items to be evaluated.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (Collection): The same collection after validation.
    """
    from fhircraft.fhir.resources.datatypes.utils import get_fhir_type

    namespace = self.namespace or "FHIR"
    if namespace == "FHIR":
        self.specifier = self.specifier[0].upper() + self.specifier[1:]
        release = environment.get("%fhirRelease")
        if release:
            release = (
                release.value
                if isinstance(release, FHIRPathCollectionItem)
                else release
            )
        if not release:
            warnings.warn(
                "No %fhirRelease found in environment. Defaulting to R4 for type resolution.",
                UserWarning,
            )
            release = "R4"
        type = get_fhir_type(self.specifier, release=release)
    else:
        raise NameError(
            f"Unknown namespace '{self.namespace}' for type specifier '{self.specifier}'"
        )
    return [FHIRPathCollectionItem(value=type)]

ContextualIndex

Path: fhircraft.fhir.path.engine.environment.ContextualIndex

Bases: ContextualVariable

A class representation of the FHIRPath $index operator used to represent the index of an item in the input collection currently under evaluation.

ContextualThis

Path: fhircraft.fhir.path.engine.environment.ContextualThis

Bases: ContextualVariable

A class representation of the FHIRPath $this operator used to represent the item from the input collection currently under evaluation.

Methods:

Name Description
evaluate

Evaluates the contextual variable within the given environment. For $this, if the variable is not defined in the current context

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Evaluates the contextual variable within the given environment. For $this, if the variable is not defined in the current context it returns the current collection being evaluated (for compatibility with the FHIR restricted subset where $this can refer to any element that has focus).

Parameters:

Name Type Description Default
collection FHIRPathCollection

The collection of items to be evaluated.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

A list of FHIRPathCollectionItem instances after evaluation.

Source code in fhircraft/fhir/path/engine/environment.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Evaluates the contextual variable within the given environment. For `$this`, if the variable is not defined in the current context
    it returns the current collection being evaluated (for compatibility with the FHIR restricted subset where `$this` can refer to
    any element that has focus).

    Args:
        collection (FHIRPathCollection): The collection of items to be evaluated.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): A list of FHIRPathCollectionItem instances after evaluation.
    """
    if self.variable not in environment:
        return collection
    return [FHIRPathCollectionItem.wrap(environment[self.variable])]

ContextualTotal

Path: fhircraft.fhir.path.engine.environment.ContextualTotal

Bases: ContextualVariable

A class representation of the FHIRPath $total operator used to represent an aggregated value over a collection within a context.

ContextualVariable

Path: fhircraft.fhir.path.engine.environment.ContextualVariable

Bases: FHIRPath

A base class for FHIRPath contextual variables such as $this, $index, and $total.

Methods:

Name Description
evaluate

Evaluates the contextual variable within the given environment.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Evaluates the contextual variable within the given environment.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The collection of items to be evaluated.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

A list of FHIRPathCollectionItem instances after evaluation.

Source code in fhircraft/fhir/path/engine/environment.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Evaluates the contextual variable within the given environment.

    Args:
        collection (FHIRPathCollection): The collection of items to be evaluated.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): A list of FHIRPathCollectionItem instances after evaluation.
    """
    if self.variable not in environment:
        raise FHIRPathError(
            f"The {self.variable} variable is not defined within the current context."
        )
    value = environment[self.variable]
    if value is None or value == []:
        return []
    return [FHIRPathCollectionItem.wrap(value)]

EnvironmentVariable

Path: fhircraft.fhir.path.engine.environment.EnvironmentVariable

EnvironmentVariable(variable: str)

Bases: FHIRPathVariable

A class representation of a FHIRPath environmental variables such as %context and %resource.

Methods:

Name Description
evaluate

Evaluates the contextual variable within the given environment.

Source code in fhircraft/fhir/path/engine/environment.py
def __init__(self, variable: str):
    if not variable.startswith("%"):
        raise ValueError("FHIRPath environment variable names must start with '%'")
    self.variable = variable

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Evaluates the contextual variable within the given environment.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The collection of items to be evaluated.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

A list of FHIRPathCollectionItem instances after evaluation.

Source code in fhircraft/fhir/path/engine/environment.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Evaluates the contextual variable within the given environment.

    Args:
        collection (FHIRPathCollection): The collection of items to be evaluated.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): A list of FHIRPathCollectionItem instances after evaluation.
    """
    if self.variable not in environment:
        raise FHIRPathError(
            f"The {self.variable} variable is not defined within the current context."
        )
    value = environment[self.variable]
    if value is None or value == []:
        return []
    return [FHIRPathCollectionItem.wrap(value)]

FHIRPathVariable

Path: fhircraft.fhir.path.engine.environment.FHIRPathVariable

Bases: FHIRPath

Abstract class for FHIRPath contextual and environmental variables

Attributes:

Name Type Description
variable str

The name of the variable.

Equals

Path: fhircraft.fhir.path.engine.equality.Equals

Equals(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRPath

A representation of the FHIRPath = operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

Returns true if the left collection is equal to the right collection:

Source code in fhircraft/fhir/path/engine/equality.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment, create: bool = False) -> FHIRPathCollection

Returns true if the left collection is equal to the right collection: As noted above, if either operand is an empty collection, the result is an empty collection. Otherwise: If both operands are collections with a single item, they must be of the same type (or be implicitly convertible to the same type), and: - For primitives: - String: comparison is based on Unicode values - Integer: values must be exactly equal - Decimal: values must be equal, trailing zeroes after the decimal are ignored - Boolean: values must be the same - Date: must be exactly the same - DateTime: must be exactly the same, respecting the timezone offset (though +00:00 = -00:00 = Z) - Time: must be exactly the same - For complex types, equality requires all child properties to be equal, recursively.= If both operands are collections with multiple items: - Each item must be equal - Comparison is order dependent Otherwise, equals returns false. Note that this implies that if the collections have a different number of items to compare, the result will be false.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/equality.py
def evaluate(
    self, collection: FHIRPathCollection, environment, create: bool = False
) -> FHIRPathCollection:
    """
    Returns true if the left collection is equal to the right collection:
    As noted above, if either operand is an empty collection, the result is an empty collection. Otherwise:
    If both operands are collections with a single item, they must be of the same type (or be implicitly convertible to the same type), and:
        - For primitives:
            - String: comparison is based on Unicode values
            - Integer: values must be exactly equal
            - Decimal: values must be equal, trailing zeroes after the decimal are ignored
            - Boolean: values must be the same
            - Date: must be exactly the same
            - DateTime: must be exactly the same, respecting the timezone offset (though +00:00 = -00:00 = Z)
            - Time: must be exactly the same
        - For complex types, equality requires all child properties to be equal, recursively.=
    If both operands are collections with multiple items:
        - Each item must be equal
        - Comparison is order dependent
    Otherwise, equals returns false.
    Note that this implies that if the collections have a different number of items to compare, the result will be false.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.
    """
    left_collection, right_collection = evaluate_left_right_expressions(
        self.left, self.right, collection, environment, create
    )
    if len(left_collection) == 0 or len(right_collection) == 0:
        equals = []
    elif len(left_collection) == 1 and len(right_collection) == 1:
        equals = left_collection[0] == right_collection[0]
    elif len(left_collection) != len(right_collection):
        equals = False
    else:
        equals = all(l == r for l, r in zip(left_collection, right_collection))
    return [FHIRPathCollectionItem.wrap(equals)]

Equivalent

Path: fhircraft.fhir.path.engine.equality.Equivalent

Equivalent(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRPath

A representation of the FHIRPath ~ operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

Returns true if the collections are the same. In particular, comparing empty collections for equivalence { } ~ { } will result in true.

Source code in fhircraft/fhir/path/engine/equality.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns true if the collections are the same. In particular, comparing empty collections for equivalence { } ~ { } will result in true. If both operands are collections with a single item, they must be of the same type (or implicitly convertible to the same type), and: - For primitives - String: the strings must be the same, ignoring case and locale, and normalizing whitespace. - Integer: exactly equal - Decimal: values must be equal, comparison is done on values rounded to the precision of the least precise operand. Trailing zeroes after the decimal are ignored in determining precision. - Date, DateTime and Time: values must be equal, except that if the input values have different levels of precision, the comparison returns false, not empty ({ }). - Boolean: the values must be the same - For complex types, equivalence requires all child properties to be equivalent, recursively, except for "id" elements. If both operands are collections with multiple items: - Each item must be equivalent - Comparison is not order dependent Note that this implies that if the collections have a different number of items to compare, or if one input is a value and the other is empty ({ }), the result will be false.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/equality.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns true if the collections are the same. In particular, comparing empty collections for equivalence { } ~ { } will result in true.
    If both operands are collections with a single item, they must be of the same type (or implicitly convertible to the same type), and:
        - For primitives
            - String: the strings must be the same, ignoring case and locale, and normalizing whitespace.
            - Integer: exactly equal
            - Decimal: values must be equal, comparison is done on values rounded to the precision of the least precise operand. Trailing zeroes after the decimal are ignored in determining precision.
            - Date, DateTime and Time: values must be equal, except that if the input values have different levels of precision, the comparison returns false, not empty ({ }).
            - Boolean: the values must be the same
        - For complex types, equivalence requires all child properties to be equivalent, recursively, except for "id" elements.
    If both operands are collections with multiple items:
        - Each item must be equivalent
        - Comparison is not order dependent
    Note that this implies that if the collections have a different number of items to compare, or if one input is a value and the other is empty ({ }), the result will be false.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.
    """

    left_collection, right_collection = evaluate_left_right_expressions(
        self.left, self.right, collection, environment, create
    )
    if len(left_collection) == 0 and len(right_collection) == 0:
        equivalent = True
    elif len(left_collection) == 0 or len(right_collection) == 0:
        equivalent = False
    elif len(left_collection) != len(right_collection):
        equivalent = False
    else:
        # Order-independent comparison: each item in left must have an equivalent in right
        # and vice versa (since lengths are equal, we only need to check one direction)
        remaining_right = list(right_collection)
        equivalent = True

        for left_item in left_collection:
            found_equivalent = False
            for i, right_item in enumerate(remaining_right):
                # Use equivalence logic based on FHIRPath specification
                if self._is_equivalent(left_item, right_item):
                    remaining_right.pop(i)
                    found_equivalent = True
                    break

            if not found_equivalent:
                equivalent = False
                break

    return [FHIRPathCollectionItem.wrap(equivalent)]

NotEquals

Path: fhircraft.fhir.path.engine.equality.NotEquals

NotEquals(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRPath

A representation of the FHIRPath != operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

The converse of the equals operator, returning true if equal returns false; false if equal

Source code in fhircraft/fhir/path/engine/equality.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

The converse of the equals operator, returning true if equal returns false; false if equal returns true; and empty ({ }) if equal returns empty. In other words, A != B is short-hand for (A = B).not().

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Source code in fhircraft/fhir/path/engine/equality.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    The converse of the equals operator, returning true if equal returns false; false if equal
    returns true; and empty ({ }) if equal returns empty. In other words, A != B is short-hand for (A = B).not().


    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection
    """
    return [
        FHIRPathCollectionItem.wrap(
            not Equals(self.left, self.right)
            .evaluate(collection, environment, create)[0]
            .value
        )
    ]

NotEquivalent

Path: fhircraft.fhir.path.engine.equality.NotEquivalent

NotEquivalent(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRPath

A representation of the FHIRPath !~ operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

The converse of the equivalent operator, returning true if equivalent returns

Source code in fhircraft/fhir/path/engine/equality.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

The converse of the equivalent operator, returning true if equivalent returns false and false is equivalent returns true. In other words, A !~ B is short-hand for (A ~ B).not().

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required

Returns:

Type Description
FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/equality.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    The converse of the equivalent operator, returning true if equivalent returns
    false and false is equivalent returns true. In other words, A !~ B is short-hand for (A ~ B).not().


    Args:
        collection (FHIRPathCollection): The input collection.

    Returns:
        (FHIRPathCollection): The output collection.
    """
    return [
        FHIRPathCollectionItem.wrap(
            not Equivalent(self.left, self.right)
            .evaluate(collection, environment, create)[0]
            .value
        )
    ]

All

Path: fhircraft.fhir.path.engine.existence.All

All(criteria: FHIRPath | FHIRPathCollection)

Bases: FHIRPathFunction

Representation of the FHIRPath all() function.

Attributes:

Name Type Description
criteria FHIRPath

Criteria to be applied to the collection prior to the evalution.

Methods:

Name Description
evaluate

Returns True if for every element in the input collection, criteria evaluates to True.

Source code in fhircraft/fhir/path/engine/existence.py
def __init__(self, criteria: FHIRPath | FHIRPathCollection):
    self.criteria = criteria

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns True if for every element in the input collection, criteria evaluates to True. Otherwise, the result is False. If the input collection is empty ({}), the result is True.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Source code in fhircraft/fhir/path/engine/existence.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns `True` if for every element in the input collection, criteria evaluates to `True`.
    Otherwise, the result is `False`. If the input collection is empty (`{}`), the result is `True`.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection
    """
    if len(collection) == 0:
        return [FHIRPathCollectionItem.wrap(True)]
    return [
        FHIRPathCollectionItem.wrap(
            all(
                [
                    (
                        self.criteria.evaluate(
                            [item],
                            get_expression_context(environment, item, index),
                            create,
                        )[0].value
                        if isinstance(self.criteria, FHIRPath)
                        else item.value == self.criteria
                    )
                    for index, item in enumerate(collection)
                ]
            )
        )
    ]

AllFalse

Path: fhircraft.fhir.path.engine.existence.AllFalse

Bases: FHIRPathFunction

Representation of the FHIRPath allFalse() function.

Methods:

Name Description
evaluate

Takes a collection of Boolean values and returns True if all the items are False.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Takes a collection of Boolean values and returns True if all the items are False. If any items are True, the result is False. If the input is empty ({}), the result is True.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Source code in fhircraft/fhir/path/engine/existence.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Takes a collection of Boolean values and returns `True` if all the items are `False`.
    If any items are `True`, the result is `False`. If the input is empty (`{}`), the result is `True`.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection
    """
    return _all_or_any_boolean(collection, all, False)

AllTrue

Path: fhircraft.fhir.path.engine.existence.AllTrue

Bases: FHIRPathFunction

Representation of the FHIRPath allTrue() function.

Methods:

Name Description
evaluate

Takes a collection of Boolean values and returns True if all the items are True. If any

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Takes a collection of Boolean values and returns True if all the items are True. If any items are False, the result is False. If the input is empty ({}), the result is True.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Source code in fhircraft/fhir/path/engine/existence.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Takes a collection of Boolean values and returns `True` if all the items are `True`. If any
    items are `False`, the result is `False`. If the input is empty (`{}`), the result is `True`.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection
    """
    return _all_or_any_boolean(collection, all, True)

AnyFalse

Path: fhircraft.fhir.path.engine.existence.AnyFalse

Bases: FHIRPathFunction

Representation of the FHIRPath anyFalse() function.

Methods:

Name Description
evaluate

Takes a collection of Boolean values and returns True if any of the items are False. If all

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Takes a collection of Boolean values and returns True if any of the items are False. If all the items are True, or if the input is empty ({}), the result is False.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Source code in fhircraft/fhir/path/engine/existence.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Takes a collection of Boolean values and returns `True` if any of the items are `False`. If all
    the items are `True`, or if the input is empty (`{}`), the result is `False`.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection
    """
    return _all_or_any_boolean(collection, any, False)

AnyTrue

Path: fhircraft.fhir.path.engine.existence.AnyTrue

Bases: FHIRPathFunction

Representation of the FHIRPath anyTrue() function.

Methods:

Name Description
evaluate

Takes a collection of Boolean values and returns True if any of the items are True.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Takes a collection of Boolean values and returns True if any of the items are True. If all the items are False, or if the input is empty ({}), the result is False.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Source code in fhircraft/fhir/path/engine/existence.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Takes a collection of Boolean values and returns `True` if any of the items are `True`.
    If all the items are `False`, or if the input is empty (`{}`), the result is `False`.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection
    """
    return _all_or_any_boolean(collection, any, True)

Count

Path: fhircraft.fhir.path.engine.existence.Count

Bases: FHIRPathFunction

Representation of the FHIRPath count() function.

Methods:

Name Description
evaluate

Returns the integer count of the number of items in the input collection. Returns 0 when the input collection is empty.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the integer count of the number of items in the input collection. Returns 0 when the input collection is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Source code in fhircraft/fhir/path/engine/existence.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the integer count of the number of items in the input collection. Returns 0 when the input collection is empty.


    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection
    """
    return [FHIRPathCollectionItem.wrap(len(collection))]

Distinct

Path: fhircraft.fhir.path.engine.existence.Distinct

Bases: FHIRPathFunction

Representation of the FHIRPath distinct() function.

Methods:

Name Description
evaluate

Returns a collection containing only the unique items in the input collection. If the input collection is empty ([]), the result is empty.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns a collection containing only the unique items in the input collection. If the input collection is empty ([]), the result is empty. Note that the order of elements in the input collection is not guaranteed to be preserved in the result.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Source code in fhircraft/fhir/path/engine/existence.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns a collection containing only the unique items in the input collection. If the input collection is empty (`[]`), the result is empty.
    Note that the order of elements in the input collection is not guaranteed to be preserved in the result.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection
    """
    return list(set(collection))

Empty

Path: fhircraft.fhir.path.engine.existence.Empty

Bases: FHIRPathFunction

Representation of the FHIRPath empty() function.

Methods:

Name Description
evaluate

Returns True if the input collection is empty ({}) and False otherwise.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns True if the input collection is empty ({}) and False otherwise.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Source code in fhircraft/fhir/path/engine/existence.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns `True` if the input collection is empty (`{}`) and `False` otherwise.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection
    """
    return [FHIRPathCollectionItem.wrap(len(collection) == 0)]

Exists

Path: fhircraft.fhir.path.engine.existence.Exists

Exists(criteria: FHIRPath | None = None)

Bases: FHIRPathFunction

Representation of the FHIRPath exists() function.

Attributes:

Name Type Description
criteria FHIRPath

Optional criteria to be applied to the collection prior to the determination of the exists

Methods:

Name Description
evaluate

Returns True if the collection has any elements, and False otherwise.

Source code in fhircraft/fhir/path/engine/existence.py
def __init__(self, criteria: FHIRPath | None = None):
    self.criteria = criteria

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns True if the collection has any elements, and False otherwise. This is the opposite of empty(), and as such is a shorthand for empty().not(). If the input collection is empty ({}), the result is False. The function can also take an optional criteria to be applied to the collection prior to the determination of the exists. In this case, the function is shorthand for where(criteria).exists().

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Source code in fhircraft/fhir/path/engine/existence.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns `True` if the collection has any elements, and `False` otherwise.
    This is the opposite of empty(), and as such is a shorthand for empty().not().
    If the input collection is empty (`{}`), the result is `False`.
    The function can also take an optional criteria to be applied to the collection
    prior to the determination of the exists. In this case, the function is
    shorthand for where(criteria).exists().

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection
    """
    if self.criteria:
        collection = Where(self.criteria).evaluate(collection, environment, create)
    return [FHIRPathCollectionItem.wrap(len(collection) > 0)]

IsDistinct

Path: fhircraft.fhir.path.engine.existence.IsDistinct

Bases: FHIRPathFunction

Representation of the FHIRPath isDistinct() function.

Methods:

Name Description
evaluate

Returns True if all the items in the input collection are distinct.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns True if all the items in the input collection are distinct. If the input collection is empty ([]), the result is True.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Source code in fhircraft/fhir/path/engine/existence.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns `True` if all the items in the input collection are distinct.
    If the input collection is empty (`[]`), the result is `True`.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection
    """
    return [
        FHIRPathCollectionItem.wrap(len(list(set(collection))) == len(collection))
    ]

SubsetOf

Path: fhircraft.fhir.path.engine.existence.SubsetOf

SubsetOf(other: FHIRPathCollection | FHIRPath)

Bases: FHIRPathFunction

Representation of the FHIRPath subsetOf() function.

Attributes:

Name Type Description
other Union[FHIRPathCollection, FHIRPath]

other collection to which to determine whether input is a subset of.

Methods:

Name Description
evaluate

Returns True if all items in the input collection are members of the collection passed as the

Source code in fhircraft/fhir/path/engine/existence.py
def __init__(self, other: FHIRPathCollection | FHIRPath):
    self.other = other

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns True if all items in the input collection are members of the collection passed as the other argument.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Note

Conceptually, this function is evaluated by testing each element in the input collection for membership in the other collection, with a default of True. This means that if the input collection is empty ([]), the result is True, otherwise if the other collection is empty, the result is False.

Source code in fhircraft/fhir/path/engine/existence.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns `True` if all items in the input collection are members of the collection passed as the
    other argument.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Note:
        Conceptually, this function is evaluated by testing each element in the input collection for
        membership in the other collection, with a default of `True`. This means that if the input collection
        is empty (`[]`), the result is `True`, otherwise if the other collection is empty, the result is `False`.
    """
    if len(collection) == 0:
        return [FHIRPathCollectionItem.wrap(True)]
    other_collection = (
        self.other.evaluate(collection, environment, create)
        if isinstance(self.other, FHIRPath)
        else self.other
    )
    if len(other_collection) == 0:
        return [FHIRPathCollectionItem.wrap(False)]
    for item in collection:
        if item not in other_collection:
            return [FHIRPathCollectionItem.wrap(False)]
    else:
        return [FHIRPathCollectionItem.wrap(True)]

SupersetOf

Path: fhircraft.fhir.path.engine.existence.SupersetOf

SupersetOf(other: FHIRPathCollection | FHIRPath)

Bases: FHIRPathFunction

Representation of the FHIRPath supersetOf() function.

Attributes:

Name Type Description
other Union[FHIRPathCollection, FHIRPath]

Other collection to which to determine whether input is a superset of.

Methods:

Name Description
evaluate

Returns true if all items in the collection passed as the other argument are

Source code in fhircraft/fhir/path/engine/existence.py
def __init__(self, other: FHIRPathCollection | FHIRPath):
    self.other = other

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns true if all items in the collection passed as the other argument are members of the input collection. Membership is determined using the = (Equals) (=) operation.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection

Note

Conceptually, this function is evaluated by testing each element in the other collection for membership in the input collection, with a default of True. This means that if the other collection is empty ([]), the result is True, otherwise if the other collection is empty, the result is False.

Source code in fhircraft/fhir/path/engine/existence.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns true if all items in the collection passed as the other argument are
    members of the input collection. Membership is determined using the = (Equals) (=) operation.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection

    Note:
        Conceptually, this function is evaluated by testing each element in the other collection for
        membership in the input collection, with a default of `True`. This means that if the other collection
        is empty (`[]`), the result is `True`, otherwise if the other collection is empty, the result is `False`.
    """
    if len(collection) == 0:
        return [FHIRPathCollectionItem.wrap(True)]
    other_collection = (
        self.other.evaluate(collection, environment, create)
        if isinstance(self.other, FHIRPath)
        else self.other
    )
    if len(other_collection) == 0:
        return [FHIRPathCollectionItem.wrap(True)]
    for item in other_collection:
        if item not in collection:
            return [FHIRPathCollectionItem.wrap(False)]
    else:
        return [FHIRPathCollectionItem.wrap(True)]

OfType

Path: fhircraft.fhir.path.engine.filtering.OfType

OfType(_type: TypeSpecifier)

Bases: FHIRPathFunction

Representation of the FHIRPath ofType() function.

Attributes:

Name Type Description
type class

Type class

Methods:

Name Description
evaluate

Returns a collection that contains all items in the input collection that are of the given type

Source code in fhircraft/fhir/path/engine/filtering.py
def __init__(self, _type: TypeSpecifier):
    self.type = _type

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns a collection that contains all items in the input collection that are of the given type or a subclass thereof. If the input collection is empty ([]), the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Type Description
FHIRPathCollection

FHIRPathCollection): The output collection.

Source code in fhircraft/fhir/path/engine/filtering.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns a collection that contains all items in the input collection that are of the given type
    or a subclass thereof. If the input collection is empty (`[]`), the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection): The output collection.
    """
    collection = ensure_list(collection)
    filtered_collection = []
    for item in collection:
        filtered_collection.extend(
            As(This(), self.type).evaluate([item], environment, create)
        )
    return filtered_collection

Repeat

Path: fhircraft.fhir.path.engine.filtering.Repeat

Repeat(projection: FHIRPath)

Bases: FHIRPathFunction

Representation of the FHIRPath repeat() function.

Attributes:

Name Type Description
projection FHIRPath

Expression to evaluate for each collection item.

Methods:

Name Description
evaluate

A version of select that will repeat the projection and add it to the output collection, as

Source code in fhircraft/fhir/path/engine/filtering.py
def __init__(self, projection: FHIRPath):
    self.projection = projection

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

A version of select that will repeat the projection and add it to the output collection, as long as the projection yields new items (as determined by the = (Equals) (=) operator).

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Type Description
FHIRPathCollection

FHIRPathCollection): The output collection.

Source code in fhircraft/fhir/path/engine/filtering.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    A version of select that will repeat the projection and add it to the output collection, as
    long as the projection yields new items (as determined by the = (Equals) (=) operator).

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection): The output collection.
    """

    def project_recursively(input_collection):
        output_collection = []
        for index, item in enumerate(input_collection):
            new_collection = self.projection.evaluate(
                [item], get_expression_context(environment, item, index), create
            )
            output_collection.extend(new_collection)
            if len(new_collection) > 0:
                output_collection.extend(project_recursively(new_collection))
        return output_collection

    return project_recursively(collection)

Select

Path: fhircraft.fhir.path.engine.filtering.Select

Select(projection: FHIRPath)

Bases: FHIRPathFunction

Representation of the FHIRPath select() function.

Attributes:

Name Type Description
projection FHIRPath

Expression to evaluate for each collection item.

Methods:

Name Description
evaluate

Evaluates the projection expression for each item in the input collection. The result of each

Source code in fhircraft/fhir/path/engine/filtering.py
def __init__(self, projection: FHIRPath):
    self.projection = projection

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Evaluates the projection expression for each item in the input collection. The result of each evaluation is added to the output collection. If the evaluation results in a collection with multiple items, all items are added to the output collection (collections resulting from evaluation of projection are flattened). This means that if the evaluation for an element results in the empty collection ([]), no element is added to the result, and that if the input collection is empty ([]), the result is empty as well.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Type Description
FHIRPathCollection

FHIRPathCollection): The output collection.

Source code in fhircraft/fhir/path/engine/filtering.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Evaluates the projection expression for each item in the input collection. The result of each
    evaluation is added to the output collection. If the evaluation results in a collection with
    multiple items, all items are added to the output collection (collections resulting from
    evaluation of projection are flattened). This means that if the evaluation for an element
    results in the empty collection (`[]`), no element is added to the result, and that if the
    input collection is empty (`[]`), the result is empty as well.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection): The output collection.
    """
    collection = ensure_list(collection)
    return [
        projected_item
        for index, item in enumerate(collection)
        for projected_item in ensure_list(
            self.projection.evaluate(
                [item], get_expression_context(environment, item, index), create
            )
        )
    ]

Where

Path: fhircraft.fhir.path.engine.filtering.Where

Where(expression: FHIRPath)

Bases: FHIRPathFunction

Representation of the FHIRPath where() function.

Attributes:

Name Type Description
expression FHIRPath

Expression to evaluate for each collection item.

Methods:

Name Description
evaluate

Returns a collection containing only those elements in the input collection for which

Source code in fhircraft/fhir/path/engine/filtering.py
def __init__(self, expression: FHIRPath):
    self.expression = expression

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns a collection containing only those elements in the input collection for which the stated criteria expression evaluates to True. Elements for which the expression evaluates to false or empty ([]) are not included in the result. If the input collection is empty ([]), the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Type Description
FHIRPathCollection

FHIRPathCollection): The output collection.

Source code in fhircraft/fhir/path/engine/filtering.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns a collection containing only those elements in the input collection for which
    the stated criteria expression evaluates to `True`. Elements for which the expression
    evaluates to false or empty (`[]`) are not included in the result.
    If the input collection is empty (`[]`), the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection): The output collection.
    """
    collection = ensure_list(collection)
    expression_collection = [
        self.expression.evaluate(
            [item], get_expression_context(environment, item, index), create
        )
        for index, item in enumerate(collection)
    ]
    checks = [
        bool(collection[0].value) if len(collection) > 0 else False
        for collection in expression_collection
    ]
    return [item for item, check in zip(collection, checks) if check]

Date

Path: fhircraft.fhir.path.engine.literals.Date

dataclass

Date(valuestring=None, value_date=None)

Bases: FHIRPathLiteralType

Date(valuestring=None, value_date=None)

Parameters:

Name Type Description Default
year int
required
month int | None
required
day int | None
required
Source code in fhircraft/fhir/path/engine/literals.py
def __init__(self, valuestring=None, value_date=None):
    if valuestring:
        match = re.match(r"\@(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?", valuestring)
        if match:
            groups = match.groups()
            self.year, self.month, self.day = [  # type: ignore
                int(group) if group else None
                for group in list(groups) + [None for _ in range(3 - len(groups))]
            ]
        else:
            raise ValueError(f'Invalid string format "{valuestring}" for Date type')
    elif value_date:
        self.year = value_date.year
        self.month = value_date.month
        self.day = value_date.day

DateTime

Path: fhircraft.fhir.path.engine.literals.DateTime

dataclass

DateTime(valuestring: str | None = None, value_datetime: datetime | None = None)

Bases: FHIRPathLiteralType

DateTime(valuestring: str | None = None, value_datetime: datetime.datetime | None = None)

Parameters:

Name Type Description Default
year int
required
month int | None
required
day int | None
required
hour int | None
required
minute int | None
required
second int | None
required
millisecond int | None
required
hour_shift int | None
required
minute_shift int | None
required
Source code in fhircraft/fhir/path/engine/literals.py
def __init__(
    self, valuestring: str | None = None, value_datetime: datetime | None = None
):
    if valuestring:
        match = re.match(
            r"\@([0-9]{4})(?:-([0-9]{2})(?:-?([0-9]{2})T(?:(\d{2})(?:\:(\d{2})(?:\:(\d{2})(?:\.(\d{3})(?:([+|-]\d{2})(?:\:(\d{2}))?)?)?)?)?)?)?)?",
            valuestring,
        )
        if match:
            groups = match.groups()
            (
                self.year,  # type: ignore
                self.month,
                self.day,
                self.hour,
                self.minute,
                self.second,
                self.millisecond,
                self.hour_shift,
                self.minute_shift,
            ) = [
                int(group) if group else None
                for group in list(groups) + [None for _ in range(9 - len(groups))]
            ]
        else:
            raise ValueError(
                f'Invalid string format "{valuestring}" for DateTime type'
            )
    elif value_datetime:
        self.year = value_datetime.year
        self.month = value_datetime.month
        self.day = value_datetime.day
        self.hour = value_datetime.hour
        self.minute = value_datetime.minute
        self.second = value_datetime.second
        self.millisecond = value_datetime.microsecond // 1000
        self.hour_shift = None
        self.minute_shift = None

FHIRPathLiteralType

Path: fhircraft.fhir.path.engine.literals.FHIRPathLiteralType

Bases: ABC

Quantity

Path: fhircraft.fhir.path.engine.literals.Quantity

dataclass

Quantity(value: Union[int, float], unit: Optional[str])

Bases: FHIRPathLiteralType

Quantity(value: int | float, unit: str | None)

Parameters:

Name Type Description Default
value int | float
required
unit str | None
required

Time

Path: fhircraft.fhir.path.engine.literals.Time

dataclass

Time(valuestring: str | None = None, value_time: datetime | None = None)

Bases: FHIRPathLiteralType

Time(valuestring: str | None = None, value_time: datetime.datetime | None = None)

Parameters:

Name Type Description Default
hour int
required
minute int | None
required
second int | None
required
millisecond int | None
required
hour_shift int | None
required
minute_shift int | None
required
Source code in fhircraft/fhir/path/engine/literals.py
def __init__(
    self, valuestring: str | None = None, value_time: datetime | None = None
):
    if valuestring:
        match = re.match(
            r"\@T(\d{2})(?:\:(\d{2})(?:\:(\d{2})(?:\.(\d{3})(?:([+|-]\d{2})(?:\:(\d{2}))?)?)?)?)?",
            valuestring,
        )
        if match:
            groups = match.groups()
            (
                self.hour,  # type: ignore
                self.minute,
                self.second,
                self.millisecond,
                self.hour_shift,
                self.minute_shift,
            ) = [
                int(group) if group else None
                for group in list(groups) + [None for _ in range(6 - len(groups))]
            ]
        else:
            raise ValueError(f'Invalid string format "{valuestring}" for Time type')
    elif value_time:
        self.hour = value_time.hour
        self.minute = value_time.minute
        self.second = value_time.second
        self.millisecond = value_time.microsecond // 1000
        self.hour_shift = None
        self.minute_shift = None

Abs

Path: fhircraft.fhir.path.engine.math.Abs

Bases: FHIRPathMathFunction

A representation of the FHIRPath abs function.

Addition

Path: fhircraft.fhir.path.engine.math.Addition

Addition(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRMathOperator

A representation of the FHIRPath + operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

For Integer, Decimal, and quantity, adds the operands. For strings, concatenates the right

Source code in fhircraft/fhir/path/engine/math.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

For Integer, Decimal, and quantity, adds the operands. For strings, concatenates the right operand to the left operand. When adding quantities, the units of each quantity must be the same.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathRuntimeError

If either expression evaluates to a non-singleton collection.

Source code in fhircraft/fhir/path/engine/math.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    For Integer, Decimal, and quantity, adds the operands. For strings, concatenates the right
    operand to the left operand.
    When adding quantities, the units of each quantity must be the same.


    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: If either expression evaluates to a non-singleton collection.
    """
    left_value, right_value = evaluate_and_prepare_collection_values(
        self, self.left, self.right, collection, environment, create
    )
    if left_value is None or right_value is None:
        return []
    elif isinstance(left_value, str) and isinstance(right_value, str):
        return [FHIRPathCollectionItem.wrap(left_value + right_value)]
    elif isinstance(left_value, (int, float)) and isinstance(
        right_value, (int, float)
    ):
        return [FHIRPathCollectionItem.wrap(left_value + right_value)]
    elif isinstance(left_value, (Quantity)) and isinstance(right_value, (Quantity)):
        if left_value.unit != right_value.unit:
            raise FHIRPathRuntimeError(
                f"FHIRPath operator {self.__str__()} cannot add quantities with different units: {left_value.unit} and {right_value.unit}."
            )
        return [FHIRPathCollectionItem.wrap(left_value + right_value)]
    else:
        raise FHIRPathRuntimeError(
            f"FHIRPath operator {self.__str__()} cannot add {type(left_value).__name__} and {type(right_value).__name__}."
        )

Ceiling

Path: fhircraft.fhir.path.engine.math.Ceiling

Bases: FHIRPathMathFunction

A representation of the FHIRPath ceiling function.

Div

Path: fhircraft.fhir.path.engine.math.Div

Div(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRMathOperator

A representation of the FHIRPath div operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

Performs truncated division of the left operand by the right operand (supported for Integer and Decimal).

Source code in fhircraft/fhir/path/engine/math.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Performs truncated division of the left operand by the right operand (supported for Integer and Decimal).

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathRuntimeError

If either expression evaluates to a non-singleton collection.

Source code in fhircraft/fhir/path/engine/math.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Performs truncated division of the left operand by the right operand (supported for Integer and Decimal).

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: If either expression evaluates to a non-singleton collection.
    """
    left_value, right_value = evaluate_and_prepare_collection_values(
        self, self.left, self.right, collection, environment, create
    )
    if left_value is None or right_value is None:
        return []
    elif isinstance(left_value, (int, float)) and isinstance(
        right_value, (int, float)
    ):
        if right_value == 0:
            return []
        return [FHIRPathCollectionItem.wrap(left_value // right_value)]  # type: ignore
    else:
        raise FHIRPathRuntimeError(
            f"FHIRPath operator {self.__str__()} cannot perform truncated division between {type(left_value).__name__} and {type(right_value).__name__}."
        )

Division

Path: fhircraft.fhir.path.engine.math.Division

Division(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRMathOperator

A representation of the FHIRPath / operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

Divides the left operand by the right operand (supported for Integer, Decimal, and Quantity).

Source code in fhircraft/fhir/path/engine/math.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Divides the left operand by the right operand (supported for Integer, Decimal, and Quantity). The result of a division is always Decimal, even if the inputs are both Integer. For integer division, use the div operator. If an attempt is made to divide by zero, the result is empty. For division involving quantities, the resulting quantity will have the appropriate unit.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathRuntimeError

If either expression evaluates to a non-singleton collection.

Source code in fhircraft/fhir/path/engine/math.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Divides the left operand by the right operand (supported for Integer, Decimal, and Quantity).
    The result of a division is always Decimal, even if the inputs are both Integer. For integer division,
    use the `div` operator.
    If an attempt is made to divide by zero, the result is empty.
    For division involving quantities, the resulting quantity will have the appropriate unit.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: If either expression evaluates to a non-singleton collection.
    """
    left_value, right_value = evaluate_and_prepare_collection_values(
        self, self.left, self.right, collection, environment, create
    )
    if left_value is None or right_value is None:
        return []
    if (isinstance(right_value, Quantity) and right_value.value == 0) or (
        isinstance(right_value, (int, float)) and right_value == 0
    ):
        return []
    elif isinstance(left_value, (int, float, Quantity)) and isinstance(
        right_value, (int, float, Quantity)
    ):
        return [FHIRPathCollectionItem.wrap(left_value / right_value)]  # type: ignore
    else:
        raise FHIRPathRuntimeError(
            f"FHIRPath operator {self.__str__()} cannot divide {type(left_value).__name__} and {type(right_value).__name__}."
        )

Exp

Path: fhircraft.fhir.path.engine.math.Exp

Bases: FHIRPathMathFunction

A representation of the FHIRPath exp function.

FHIRMathOperator

Path: fhircraft.fhir.path.engine.math.FHIRMathOperator

FHIRMathOperator(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRPath

Abstract class definition for the category of math FHIRPath operators.

Source code in fhircraft/fhir/path/engine/math.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

FHIRPathMathFunction

Path: fhircraft.fhir.path.engine.math.FHIRPathMathFunction

Bases: FHIRPathFunction

Abstract class definition for the category of math FHIRPath functions.

Methods:

Name Description
evaluate

Computes the computed value based on its argument (supported for Integer, Decimal and Quantity values).

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Computes the computed value based on its argument (supported for Integer, Decimal and Quantity values).

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathRuntimeError

For non-singleton collections.

Source code in fhircraft/fhir/path/engine/math.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Computes the computed value based on its argument (supported for Integer, Decimal and Quantity values).

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: For non-singleton collections.
    """
    if len(collection) == 0:
        return []
    elif len(collection) > 1:
        raise FHIRPathRuntimeError("Input collection must be a singleton.")
    value = collection[0].value
    if isinstance(value, (int, float)):
        value = self.math_operation(value)
    elif isinstance(value, (Quantity)):
        value = Quantity(self.math_operation(value.value), value.unit)
    else:
        raise FHIRPathRuntimeError(
            f"FHIRPath function {self.__class__.__name__}() cannot compute abs for {type(value).__name__}."
        )
    return [FHIRPathCollectionItem.wrap(value)]

Floor

Path: fhircraft.fhir.path.engine.math.Floor

Bases: FHIRPathMathFunction

A representation of the FHIRPath floor function.

Ln

Path: fhircraft.fhir.path.engine.math.Ln

Bases: FHIRPathMathFunction

A representation of the FHIRPath ln function.

Log

Path: fhircraft.fhir.path.engine.math.Log

Log(base: int | FHIRPath)

Bases: FHIRPathMathFunction

A representation of the FHIRPath log function.

Attributes:

Name Type Description
base int | Literal

The base of the logarithm. Must be an integer greater than 1.

Methods:

Name Description
evaluate

Computes the logarithm of the input value to the specified base.

Source code in fhircraft/fhir/path/engine/math.py
def __init__(self, base: int | FHIRPath):
    self.base = Literal(base) if not isinstance(base, FHIRPath) else base

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Computes the logarithm of the input value to the specified base.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathRuntimeError

For non-singleton collections or invalid base.

Source code in fhircraft/fhir/path/engine/math.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Computes the logarithm of the input value to the specified base.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: For non-singleton collections or invalid base.
    """
    if (
        not isinstance(
            base := self.base.single(collection, environment=environment), int
        )
        or base <= 1
    ):
        raise FHIRPathRuntimeError(
            "The base argument of the log function must be an integer greater than 1."
        )
    self.math_operation = lambda x: log(x, base)
    return super().evaluate(collection, environment, create)

Mod

Path: fhircraft.fhir.path.engine.math.Mod

Mod(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRMathOperator

A representation of the FHIRPath mod operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

Computes the remainder of the truncated division of its arguments (supported for Integer and Decimal).

Source code in fhircraft/fhir/path/engine/math.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Computes the remainder of the truncated division of its arguments (supported for Integer and Decimal).

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathRuntimeError

If either expression evaluates to a non-singleton collection.

Source code in fhircraft/fhir/path/engine/math.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Computes the remainder of the truncated division of its arguments (supported for Integer and Decimal).

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: If either expression evaluates to a non-singleton collection.
    """
    left_value, right_value = evaluate_and_prepare_collection_values(
        self, self.left, self.right, collection, environment, create
    )
    if left_value is None or right_value is None:
        return []
    elif isinstance(left_value, (int, float)) and isinstance(
        right_value, (int, float)
    ):
        return [FHIRPathCollectionItem.wrap(left_value % right_value)]
    else:
        raise FHIRPathRuntimeError(
            f"FHIRPath operator {self.__str__()} cannot divide {type(left_value).__name__} and {type(right_value).__name__}."
        )

Multiplication

Path: fhircraft.fhir.path.engine.math.Multiplication

Multiplication(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRMathOperator

A representation of the FHIRPath * operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

Multiplies both arguments (supported for Integer, Decimal, and Quantity). For multiplication

Source code in fhircraft/fhir/path/engine/math.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Multiplies both arguments (supported for Integer, Decimal, and Quantity). For multiplication involving quantities, the resulting quantity will have the appropriate unit.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathRuntimeError

If either expression evaluates to a non-singleton collection.

Source code in fhircraft/fhir/path/engine/math.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Multiplies both arguments (supported for Integer, Decimal, and Quantity). For multiplication
    involving quantities, the resulting quantity will have the appropriate unit.


    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: If either expression evaluates to a non-singleton collection.
    """

    left_value, right_value = evaluate_and_prepare_collection_values(
        self, self.left, self.right, collection, environment, create
    )
    if left_value is None or right_value is None:
        return []
    elif isinstance(left_value, (int, float)) and isinstance(
        right_value, (int, float)
    ):
        return [FHIRPathCollectionItem.wrap(left_value * right_value)]
    elif isinstance(left_value, (Quantity)) and isinstance(right_value, (Quantity)):
        return [FHIRPathCollectionItem.wrap(left_value * right_value)]
    else:
        raise FHIRPathRuntimeError(
            f"FHIRPath operator {self.__str__()} cannot multiply {type(left_value).__name__} and {type(right_value).__name__}."
        )

Power

Path: fhircraft.fhir.path.engine.math.Power

Power(exponent: int | float | FHIRPath)

Bases: FHIRPathMathFunction

A representation of the FHIRPath power function.

Attributes:

Name Type Description
exponent int | float | Literal

The exponent to which the input value is raised.

Methods:

Name Description
evaluate

Computes the input value raised to the specified exponent.

Source code in fhircraft/fhir/path/engine/math.py
def __init__(self, exponent: int | float | FHIRPath):
    self.exponent = (
        Literal(exponent) if not isinstance(exponent, FHIRPath) else exponent
    )

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Computes the input value raised to the specified exponent. Args: collection (FHIRPathCollection): The input collection. environment (dict): The environment context for the evaluation. create (bool): Whether to create new elements during evaluation if necessary. Returns: FHIRPathCollection: The output collection.

Raises:

Type Description
FHIRPathRuntimeError

For non-singleton collections or invalid exponent.

Source code in fhircraft/fhir/path/engine/math.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Computes the input value raised to the specified exponent.
    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.
    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: For non-singleton collections or invalid exponent.
    """

    if not isinstance(
        exponent := self.exponent.single(collection, environment=environment),
        (int, float),
    ):
        raise FHIRPathRuntimeError(
            "The exponent argument of the power function must be a number."
        )
    self.math_operation = lambda x: pow(x, exponent)
    return super().evaluate(collection, environment, create)

Round

Path: fhircraft.fhir.path.engine.math.Round

Round(precision: int | FHIRPath)

Bases: FHIRPathMathFunction

A representation of the FHIRPath round function.

Attributes:

Name Type Description
precision int

The number of decimal places to round to.

Methods:

Name Description
evaluate

Rounds the input value to the specified precision.

Source code in fhircraft/fhir/path/engine/math.py
def __init__(self, precision: int | FHIRPath):
    self.precision = (
        Literal(precision) if not isinstance(precision, FHIRPath) else precision
    )

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Rounds the input value to the specified precision.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathRuntimeError

For non-singleton collections or invalid precision.

Source code in fhircraft/fhir/path/engine/math.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Rounds the input value to the specified precision.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: For non-singleton collections or invalid precision.
    """
    if (
        not isinstance(
            precision := self.precision.single(collection, environment=environment),
            int,
        )
        or precision < 0
    ):
        raise FHIRPathRuntimeError(
            "The precision argument of the round function must be a non-negative integer."
        )
    self.math_operation = lambda x: round(x, precision)
    return super().evaluate(collection, environment, create)

Sqrt

Path: fhircraft.fhir.path.engine.math.Sqrt

Bases: FHIRPathMathFunction

A representation of the FHIRPath sqrt function.

Subtraction

Path: fhircraft.fhir.path.engine.math.Subtraction

Subtraction(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRMathOperator

A representation of the FHIRPath - operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

Subtracts the right operand from the left operand (supported for Integer, Decimal, and Quantity).

Source code in fhircraft/fhir/path/engine/math.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Subtracts the right operand from the left operand (supported for Integer, Decimal, and Quantity). When subtracting quantities, the units of each quantity must be the same.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathRuntimeError

If either expression evaluates to a non-singleton collection.

Source code in fhircraft/fhir/path/engine/math.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Subtracts the right operand from the left operand (supported for Integer, Decimal, and Quantity).
    When subtracting quantities, the units of each quantity must be the same.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: If either expression evaluates to a non-singleton collection.
    """
    left_value, right_value = evaluate_and_prepare_collection_values(
        self, self.left, self.right, collection, environment, create
    )
    if left_value is None or right_value is None:
        return []
    elif isinstance(left_value, (int, float)) and isinstance(
        right_value, (int, float)
    ):
        return [FHIRPathCollectionItem.wrap(left_value - right_value)]
    elif isinstance(left_value, (Quantity)) and isinstance(right_value, (Quantity)):
        if left_value.unit != right_value.unit:
            raise FHIRPathRuntimeError(
                f"FHIRPath operator {self.__str__()} cannot subtract quantities with different units: {left_value.unit} and {right_value.unit}."
            )
        return [FHIRPathCollectionItem.wrap(left_value - right_value)]
    else:
        raise FHIRPathRuntimeError(
            f"FHIRPath operator {self.__str__()} cannot subtract {type(left_value).__name__} and {type(right_value).__name__}."
        )

Truncate

Path: fhircraft.fhir.path.engine.math.Truncate

Bases: FHIRPathMathFunction

A representation of the FHIRPath truncate function.

Children

Path: fhircraft.fhir.path.engine.navigation.Children

Bases: FHIRPathFunction

Representation of the FHIRPath children() function.

Methods:

Name Description
evaluate

Returns a collection with all immediate child nodes of all items in the input collection.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns a collection with all immediate child nodes of all items in the input collection.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Source code in fhircraft/fhir/path/engine/navigation.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns a collection with all immediate child nodes of all items in the input collection.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.
    """
    children_collection = []
    for item in collection:
        if isinstance(item.value, BaseModel):
            fields = item.value.__class__.model_fields
        elif isinstance(item.value, dict):
            fields = list(item.value.keys())
        else:
            fields = []
        for field in fields:
            children_collection.extend(
                Element(field).evaluate([item], environment, create)
            )
    return children_collection

Descendants

Path: fhircraft.fhir.path.engine.navigation.Descendants

Bases: FHIRPathFunction

Representation of the FHIRPath descendants() function.

Methods:

Name Description
evaluate

Returns a collection with all descendant nodes of all items in the input collection. The result does not include

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns a collection with all descendant nodes of all items in the input collection. The result does not include the nodes in the input collection themselves.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Note

This function is a shorthand for repeat(children()).

Source code in fhircraft/fhir/path/engine/navigation.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns a collection with all descendant nodes of all items in the input collection. The result does not include
    the nodes in the input collection themselves.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Note:
        This function is a shorthand for `repeat(children())`.
    """
    return Repeat(Children()).evaluate(collection, environment, create)

Concatenation

Path: fhircraft.fhir.path.engine.strings.Concatenation

Concatenation(left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection)

Bases: FHIRPath

A representation of the FHIRPath & operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

right FHIRPath | FHIRPathCollection

Right operand.

Methods:

Name Description
evaluate

For strings, will concatenate the strings, where an empty operand is taken to be the empty string.

Source code in fhircraft/fhir/path/engine/strings.py
def __init__(
    self, left: FHIRPath | FHIRPathCollection, right: FHIRPath | FHIRPathCollection
):
    self.left = left
    self.right = right

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

For strings, will concatenate the strings, where an empty operand is taken to be the empty string. This differs from + on two strings, which will result in an empty collection when one of the operands is empty. This operator is specifically included to simplify treating an empty collection as an empty string, a common use case in string manipulation.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathError

If either expression evaluates to a non-singleton collection.

Source code in fhircraft/fhir/path/engine/strings.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    For strings, will concatenate the strings, where an empty operand is taken to be the empty string.
    This differs from + on two strings, which will result in an empty collection when one of the operands
    is empty. This operator is specifically included to simplify treating an empty collection as an empty
    string, a common use case in string manipulation.


    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathError: If either expression evaluates to a non-singleton collection.
    """
    left_value, right_value = evaluate_and_prepare_collection_values(
        self,
        self.left,
        self.right,
        collection,
        environment,
        create,
        prevent_all_empty=False,
    )
    left_value = left_value or ""
    right_value = right_value or ""
    return [FHIRPathCollectionItem.wrap(f"{left_value}{right_value}")]

Contains

Path: fhircraft.fhir.path.engine.strings.Contains

Contains(substring: str | FHIRPath)

Bases: StringManipulationFunction

A representation of the FHIRPath contains() function.

Attributes:

Name Type Description
substring str | FHIRPath

Substring to query or FHIRPath that resolves to a string.

Methods:

Name Description
evaluate

Returns true when the given substring is a substring of the input string.

Source code in fhircraft/fhir/path/engine/strings.py
def __init__(self, substring: str | FHIRPath):
    if isinstance(substring, str):
        substring = Literal(substring)
    if not isinstance(substring, FHIRPath):
        raise FHIRPathError(
            "Contains() argument must be a string literal or a valid FHIRPath."
        )
    self.substring = substring

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns true when the given substring is a substring of the input string. If substring is the empty string (''), the result is True. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathError

If input collection has more than one item.

FHIRPathError

If the item in the input collection is not a string.

Note

Note: The FHIRPath .contains() function described here is a string function that looks for a substring in a string. This is different than the contains FHIRPath operator, which is a list operator that looks for an element in a list.

Source code in fhircraft/fhir/path/engine/strings.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns true when the given substring is a substring of the input string.
    If substring is the empty string (`''`), the result is `True`.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathError: If input collection has more than one item.
        FHIRPathError: If the item in the input collection is not a string.

    Note:
        Note: The FHIRPath `.contains()` function described here is a string function that looks
        for a substring in a string. This is different than the `contains` FHIRPath operator, which
        is a list operator that looks for an element in a list.

    """
    self.validate_collection(collection)
    if not collection:
        return []
    if not isinstance(
        substring := self.substring.single(collection, environment=environment), str
    ):
        raise FHIRPathError("Contains() argument must resolve to a string.")
    if not substring:
        return [FHIRPathCollectionItem.wrap(True)]
    return [FHIRPathCollectionItem.wrap(substring in collection[0].value)]

EndsWith

Path: fhircraft.fhir.path.engine.strings.EndsWith

EndsWith(suffix: str | FHIRPath)

Bases: StringManipulationFunction

A representation of the FHIRPath endsWith() function.

Attributes:

Name Type Description
suffix str | FHIRPath

String suffix to query or FHIRPath that resolves to a string.

Methods:

Name Description
evaluate

Returns true when the input string ends with the given suffix.

Source code in fhircraft/fhir/path/engine/strings.py
def __init__(self, suffix: str | FHIRPath):
    if isinstance(suffix, str):
        suffix = Literal(suffix)
    if not isinstance(suffix, FHIRPath):
        raise FHIRPathError(
            "EndsWith() argument must be a string literal or a valid FHIRPath."
        )
    self.suffix = suffix

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns true when the input string ends with the given suffix. If suffix is the empty string (''), the result is True. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathError

If input collection has more than one item.

FHIRPathError

If the item in the input collection is not a string.

Source code in fhircraft/fhir/path/engine/strings.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns true when the input string ends with the given suffix.
    If suffix is the empty string (`''`), the result is `True`.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathError: If input collection has more than one item.
        FHIRPathError: If the item in the input collection is not a string.

    """
    self.validate_collection(collection)
    if not collection:
        return []
    if not isinstance(
        suffix := self.suffix.single(collection, environment=environment), str
    ):
        raise FHIRPathError("StartsWith() argument must resolve to a string.")
    if not suffix:
        return [FHIRPathCollectionItem.wrap(True)]
    return [FHIRPathCollectionItem.wrap(collection[0].value.endswith(suffix))]

IndexOf

Path: fhircraft.fhir.path.engine.strings.IndexOf

IndexOf(substring: str | FHIRPath)

Bases: StringManipulationFunction

A representation of the FHIRPath indexOf() function.

Attributes:

Name Type Description
substring str | FHIRPath

Subtring query or FHIRPath that resolves to a string..

Methods:

Name Description
evaluate

Returns the 0-based index of the first position substring is found in the input string,

Source code in fhircraft/fhir/path/engine/strings.py
def __init__(self, substring: str | FHIRPath):
    if isinstance(substring, str):
        substring = Literal(substring)
    if not isinstance(substring, FHIRPath):
        raise FHIRPathError(
            "IndexOf() argument must be a literal string or a valid FHIRPath."
        )
    self.substring = substring

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the 0-based index of the first position substring is found in the input string, or -1 if it is not found. If substring is an empty string (''), the function returns 0. If the input or substring is empty ([]), the result is empty ([]).

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathError

If input collection has more than one item.

FHIRPathError

If the item in the input collection is not a string.

Source code in fhircraft/fhir/path/engine/strings.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the 0-based index of the first position substring is found in the input string,
    or `-1` if it is not found.
    If substring is an empty string (`''`), the function returns `0`.
    If the input or substring is empty (`[]`), the result is empty (`[]`).

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathError: If input collection has more than one item.
        FHIRPathError: If the item in the input collection is not a string.

    """
    self.validate_collection(collection)
    if not isinstance(
        substring := self.substring.single(collection, environment=environment), str
    ):
        raise FHIRPathError(
            "IndexOf() argument must resolve in a non-empty string."
        )
    if len(collection) == 0:
        return []
    return [FHIRPathCollectionItem.wrap(collection[0].value.find(substring))]

Length

Path: fhircraft.fhir.path.engine.strings.Length

Bases: StringManipulationFunction

A representation of the FHIRPath length() function.

Methods:

Name Description
evaluate

Returns the length of the input string. If the input collection is empty ([]), the result is empty.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the length of the input string. If the input collection is empty ([]), the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathError

If input collection has more than one item.

FHIRPathError

If the item in the input collection is not a string.

Source code in fhircraft/fhir/path/engine/strings.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the length of the input string. If the input collection is empty (`[]`), the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathError: If input collection has more than one item.
        FHIRPathError: If the item in the input collection is not a string.
    """
    self.validate_collection(collection)
    if not collection:
        return []
    return [FHIRPathCollectionItem.wrap(len(collection[0].value))]

Lower

Path: fhircraft.fhir.path.engine.strings.Lower

Bases: StringManipulationFunction

A representation of the FHIRPath lower() function.

Methods:

Name Description
evaluate

Returns the input string with all characters converted to lower case.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the input string with all characters converted to lower case. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathError

If input collection has more than one item.

FHIRPathError

If the item in the input collection is not a string.

Source code in fhircraft/fhir/path/engine/strings.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the input string with all characters converted to lower case.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathError: If input collection has more than one item.
        FHIRPathError: If the item in the input collection is not a string.
    """
    self.validate_collection(collection)
    if not collection:
        return []
    return [FHIRPathCollectionItem.wrap(collection[0].value.lower())]

Matches

Path: fhircraft.fhir.path.engine.strings.Matches

Matches(regex: str | FHIRPath)

Bases: StringManipulationFunction

A representation of the FHIRPath matches() function.

Attributes:

Name Type Description
regex str | FHIRPath

Regular expression to match or FHIRPath that resolves to a string.

Methods:

Name Description
evaluate

Returns True when the value matches the given regular expression. Regular expressions

Source code in fhircraft/fhir/path/engine/strings.py
def __init__(self, regex: str | FHIRPath):
    if isinstance(regex, str):
        regex = Literal(regex)
    if not isinstance(regex, FHIRPath):
        raise FHIRPathError(
            "Matches() argument must be a string literal or valid FHIRPath."
        )
    self.regex = regex

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns True when the value matches the given regular expression. Regular expressions should function consistently, regardless of any culture- and locale-specific settings in the environment, should be case-sensitive, use 'single line' mode and allow Unicode characters. If the input collection or regex are empty, the result is empty ([]).

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathError

If input collection has more than one item.

FHIRPathError

If the item in the input collection is not a string.

Source code in fhircraft/fhir/path/engine/strings.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns `True` when the value matches the given regular expression. Regular expressions
    should function consistently, regardless of any culture- and locale-specific settings
    in the environment, should be case-sensitive, use 'single line' mode and allow Unicode characters.
    If the input collection or regex are empty, the result is empty (`[]`).

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathError: If input collection has more than one item.
        FHIRPathError: If the item in the input collection is not a string.
    """
    self.validate_collection(collection)
    if not collection or self.regex.is_empty(collection, environment=environment):
        return []
    if not isinstance(
        regex := self.regex.single(collection, environment=environment), str
    ):
        raise FHIRPathError("Matches() argument must resolve to a string.")
    return [FHIRPathCollectionItem.wrap(bool(re.match(regex, collection[0].value)))]

Replace

Path: fhircraft.fhir.path.engine.strings.Replace

Replace(pattern: str | FHIRPath | FHIRPathCollection, substitution: str | FHIRPath | FHIRPathCollection)

Bases: StringManipulationFunction

A representation of the FHIRPath replace() function.

Attributes:

Name Type Description
pattern str | FHIRPath

Substring to substitute or FHIRPath that resolves to a string.

substitution str | FHIRPath

String to substitute pattern with or FHIRPath that resolves to a string.

Methods:

Name Description
evaluate

Returns the input string with all instances of pattern replaced with substitution.

Source code in fhircraft/fhir/path/engine/strings.py
def __init__(
    self,
    pattern: str | FHIRPath | FHIRPathCollection,
    substitution: str | FHIRPath | FHIRPathCollection,
):
    if isinstance(pattern, str):
        self.pattern = Literal(pattern)
    elif isinstance(pattern, list):
        if len(pattern) > 0 and isinstance(pattern[0], FHIRPathCollectionItem):
            self.pattern = (
                Literal(pattern[0])
                if not isinstance(pattern[0], Literal)
                else pattern[0]
            )
        else:
            self.pattern = Literal(None)
    elif isinstance(pattern, FHIRPath):
        self.pattern = pattern
    else:
        raise FHIRPathError(
            "Replace() pattern argument must be a string literal or valid FHIRPath."
        )

    if isinstance(substitution, str):
        self.substitution = Literal(substitution)
    elif isinstance(substitution, list):
        if len(substitution) > 0 and isinstance(
            substitution[0], FHIRPathCollectionItem
        ):
            self.substitution = (
                Literal(substitution[0])
                if not isinstance(substitution[0], Literal)
                else substitution[0]
            )
        else:
            self.substitution = Literal(None)
    elif isinstance(substitution, FHIRPath):
        self.substitution = substitution
    else:
        raise FHIRPathError(
            "Replace() substitution argument must be a string literal or valid FHIRPath."
        )

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the input string with all instances of pattern replaced with substitution. If the substitution is the empty string (''), instances of pattern are removed from the result. If pattern is the empty string (''), every character in the input string is surrounded by the substitution, e.g. 'abc'.replace('','x') becomes 'xaxbxcx'. If the input collection, pattern, or substitution are empty, the result is empty ({ }).

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathError

If input collection has more than one item.

FHIRPathError

If the item in the input collection is not a string.

Source code in fhircraft/fhir/path/engine/strings.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the input string with all instances of `pattern` replaced with `substitution`.
    If the substitution is the empty string (`''`), instances of pattern are removed from the result.
    If pattern is the empty string (`''`), every character in the input string is surrounded by
    the substitution, e.g. `'abc'.replace('','x')` becomes `'xaxbxcx'`.
    If the input collection, pattern, or substitution are empty, the result is empty ({ }).

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathError: If input collection has more than one item.
        FHIRPathError: If the item in the input collection is not a string.
    """
    self.validate_collection(collection)
    if (
        not collection
        or self.substitution.is_empty(collection, environment=environment)
        or self.pattern.is_empty(collection, environment=environment)
    ):
        return []
    if not isinstance(
        pattern := self.pattern.single(collection, environment=environment), str
    ):
        raise FHIRPathError("Replace() pattern argument must resolve to a string.")
    if not isinstance(
        substitution := self.substitution.single(
            collection, environment=environment
        ),
        str,
    ):
        raise FHIRPathError(
            "Replace() substitution argument must resolve to a string."
        )
    return [
        FHIRPathCollectionItem.wrap(
            collection[0].value.replace(pattern, substitution)
        )
    ]

ReplaceMatches

Path: fhircraft.fhir.path.engine.strings.ReplaceMatches

ReplaceMatches(regex: str | FHIRPath, substitution: str | FHIRPath)

Bases: StringManipulationFunction

A representation of the FHIRPath replaceMatches() function.

Attributes:

Name Type Description
regex str | FHIRPath

Regular expression to substitute or FHIRPath that resolves to a string.

substitution str | FHIRPath

String to substitute regex with or FHIRPath that resolves to a string.

Methods:

Name Description
evaluate

Matches the input using the regular expression in regex and replaces each match with the

Source code in fhircraft/fhir/path/engine/strings.py
def __init__(self, regex: str | FHIRPath, substitution: str | FHIRPath):
    if isinstance(regex, str):
        regex = Literal(regex)
    if not isinstance(regex, FHIRPath):
        raise FHIRPathError(
            "ReplaceMatches() regex argument must be a string literal or valid FHIRPath."
        )
    if isinstance(substitution, str):
        substitution = Literal(substitution)
    if not isinstance(substitution, FHIRPath):
        raise FHIRPathError(
            "ReplaceMatches() substitution argument must be a string literal or valid FHIRPath."
        )
    self.regex = regex
    self.substitution = substitution

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Matches the input using the regular expression in regex and replaces each match with the substitution string. The substitution may refer to identified match groups in the regular expression. If the input collection, regex, or substitution are empty, the result is empty ([]).

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathError

If input collection has more than one item.

FHIRPathError

If the item in the input collection is not a string.

Source code in fhircraft/fhir/path/engine/strings.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Matches the input using the regular expression in regex and replaces each match with the
    substitution string. The substitution may refer to identified match groups in the regular expression.
    If the input collection, regex, or substitution are empty, the result is empty (`[]`).

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathError: If input collection has more than one item.
        FHIRPathError: If the item in the input collection is not a string.
    """
    self.validate_collection(collection)
    if (
        not collection
        or self.regex.is_empty(collection, environment=environment)
        or self.substitution.is_empty(collection, environment=environment)
    ):
        return []
    if not isinstance(
        regex := self.regex.single(collection, environment=environment), str
    ):
        raise FHIRPathError(
            "ReplaceMatches() regex argument must resolve to a string."
        )
    if not isinstance(
        substitution := self.substitution.single(
            collection, environment=environment
        ),
        str,
    ):
        raise FHIRPathError(
            "ReplaceMatches() substitution argument must resolve to a string."
        )
    return [
        FHIRPathCollectionItem.wrap(
            re.sub(regex, substitution, collection[0].value)
        )
    ]

StartsWith

Path: fhircraft.fhir.path.engine.strings.StartsWith

StartsWith(prefix: str | FHIRPath)

Bases: StringManipulationFunction

A representation of the FHIRPath startsWith() function.

Attributes:

Name Type Description
prefix str | FHIRPath

String prefix to query or FHIRPath that resolves to a string..

Methods:

Name Description
evaluate

Returns true when the input string starts with the given prefix.

Source code in fhircraft/fhir/path/engine/strings.py
def __init__(self, prefix: str | FHIRPath):
    if isinstance(prefix, str):
        prefix = Literal(prefix)
    if not isinstance(prefix, FHIRPath):
        raise FHIRPathError(
            "StartsWith() argument must be a string literal or a valid FHIRPath."
        )
    self.prefix = prefix

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns true when the input string starts with the given prefix. If prefix is the empty string (''), the result is True. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathError

If input collection has more than one item.

FHIRPathError

If the item in the input collection is not a string.

Source code in fhircraft/fhir/path/engine/strings.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns true when the input string starts with the given prefix.
    If prefix is the empty string (`''`), the result is `True`.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathError: If input collection has more than one item.
        FHIRPathError: If the item in the input collection is not a string.

    """
    self.validate_collection(collection)
    if not collection:
        return []
    if not isinstance(
        prefix := self.prefix.single(collection, environment=environment), str
    ):
        raise FHIRPathError("StartsWith() argument must resolve to a string.")
    if not prefix:
        return [FHIRPathCollectionItem.wrap(True)]
    return [FHIRPathCollectionItem.wrap(collection[0].value.startswith(prefix))]

StringManipulationFunction

Path: fhircraft.fhir.path.engine.strings.StringManipulationFunction

Bases: FHIRPathFunction

Abstract class definition for category of string manipulation FHIRPath functions.

Methods:

Name Description
validate_collection

Validates the input collection of a FHIRPath string manipulation function.

validate_collection

validate_collection(collection: FHIRPathCollection)

Validates the input collection of a FHIRPath string manipulation function.

Parameters:

Name Type Description Default
collection FHIRPathCollection

Collection to be validated.

required

Returns:

Type Description
FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathError

If input collection has more than one item.

FHIRPathError

If the item in the input collection is not a string.

Source code in fhircraft/fhir/path/engine/strings.py
def validate_collection(self, collection: FHIRPathCollection):
    """
    Validates the input collection of a FHIRPath string manipulation function.

    Args:
        collection (FHIRPathCollection): Collection to be validated.

    Returns:
        (FHIRPathCollection): The output collection.

    Raises:
        FHIRPathError: If input collection has more than one item.
        FHIRPathError: If the item in the input collection is not a string.
    """
    if len(collection) > 1:
        raise FHIRPathError(
            f"FHIRPath function {self.__str__()} expected a single-item collection, instead got a {len(collection)}-items collection."
        )
    if len(collection) == 1 and not isinstance(collection[0].value, str):
        raise FHIRPathError(
            f"FHIRPath function {self.__str__()} expected a string, instead got a {type(collection[0])}"
        )

Substring

Path: fhircraft.fhir.path.engine.strings.Substring

Substring(start: int | FHIRPath, end: int | FHIRPath | None = None)

Bases: StringManipulationFunction

A representation of the FHIRPath substring() function.

Attributes:

Name Type Description
start int | FHIRPath

Start index of the substring or FHIRPath that resolves to an integer.

end Optional[int | FHIRPath]

Optinoasl, end index of the substring or FHIRPath that resolves to an integer.

Methods:

Name Description
evaluate

Returns the part of the string starting at position start (zero-based). If length is given, will

Source code in fhircraft/fhir/path/engine/strings.py
def __init__(self, start: int | FHIRPath, end: int | FHIRPath | None = None):
    self.start: FHIRPath = Literal(start) if isinstance(start, int) else start
    self.end: FHIRPath | None = Literal(end) if isinstance(end, int) else end

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the part of the string starting at position start (zero-based). If length is given, will return at most length number of characters from the input string. If start lies outside the length of the string, the function returns empty ([]). If there are less remaining characters in the string than indicated by length, the function returns just the remaining characters. If the input or start is empty, the result is empty. If an empty length is provided, the behavior is the same as if length had not been provided.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathError

If input collection has more than one item.

FHIRPathError

If the item in the input collection is not a string.

Source code in fhircraft/fhir/path/engine/strings.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the part of the string starting at position start (zero-based). If length is given, will
    return at most length number of characters from the input string.
    If start lies outside the length of the string, the function returns empty (`[]`). If there are
    less remaining characters in the string than indicated by length, the function returns just the
    remaining characters.
    If the input or start is empty, the result is empty.
    If an empty length is provided, the behavior is the same as if length had not been provided.


    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathError: If input collection has more than one item.
        FHIRPathError: If the item in the input collection is not a string.

    """
    if not isinstance(
        (start := self.start.single(collection, environment=environment)), int
    ):
        raise FHIRPathError(
            "Substring() start argument must resolve to an integer."
        )
    end = self.end.single(collection, environment=environment) if self.end else None

    if (
        end := (
            self.end.single(collection, environment=environment)
            if self.end
            else None
        )
    ) and not isinstance(end, int):
        raise FHIRPathError("Substring() end argument must resolve to an integer.")
    self.validate_collection(collection)
    if not collection or start > len(collection[0].value) - 1:
        return []
    if end is None:
        return [FHIRPathCollectionItem.wrap(collection[0].value[start:])]
    return [FHIRPathCollectionItem.wrap(collection[0].value[start:end])]

ToChars

Path: fhircraft.fhir.path.engine.strings.ToChars

Bases: StringManipulationFunction

A representation of the FHIRPath toChars() function.

Methods:

Name Description
evaluate

Returns the list of characters in the input string. If the input collection is empty ([]), the result is empty.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the list of characters in the input string. If the input collection is empty ([]), the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathError

If input collection has more than one item.

FHIRPathError

If the item in the input collection is not a string.

Source code in fhircraft/fhir/path/engine/strings.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the list of characters in the input string. If the input collection is empty (`[]`), the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathError: If input collection has more than one item.
        FHIRPathError: If the item in the input collection is not a string.
    """
    self.validate_collection(collection)
    if not collection:
        return []
    return [
        FHIRPathCollectionItem(character, parent=collection[0])
        for character in collection[0].value
    ]

Upper

Path: fhircraft.fhir.path.engine.strings.Upper

Bases: StringManipulationFunction

A representation of the FHIRPath upper() function.

Methods:

Name Description
evaluate

Returns the input string with all characters converted to upper case.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the input string with all characters converted to upper case. If the input collection is empty, the result is empty.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathError

If input collection has more than one item.

FHIRPathError

If the item in the input collection is not a string.

Source code in fhircraft/fhir/path/engine/strings.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the input string with all characters converted to upper case.
    If the input collection is empty, the result is empty.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathError: If input collection has more than one item.
        FHIRPathError: If the item in the input collection is not a string.
    """
    self.validate_collection(collection)
    if not collection:
        return []
    return [FHIRPathCollectionItem.wrap(collection[0].value.upper())]

Exclude

Path: fhircraft.fhir.path.engine.subsetting.Exclude

Exclude(other_collection: FHIRPath | FHIRPathCollection)

Bases: FHIRPathFunction

A representation of the FHIRPath exclude() function.

Attributes:

Name Type Description
other_collection FHIRPathCollection

The other collection to compute the exclusion with.

Methods:

Name Description
evaluate

Returns the set of elements that are not in the other collection. Duplicate items will not be

Source code in fhircraft/fhir/path/engine/subsetting.py
def __init__(self, other_collection: FHIRPath | FHIRPathCollection):
    self.other_collection = other_collection

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the set of elements that are not in the other collection. Duplicate items will not be eliminated by this function, and order will be preserved.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Type Description
FHIRPathCollection

FHIRPathCollection): The output collection.

Source code in fhircraft/fhir/path/engine/subsetting.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the set of elements that are not in the other collection. Duplicate items will not be
    eliminated by this function, and order will be preserved.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection): The output collection.
    """
    if isinstance(self.other_collection, FHIRPath):
        self.other_collection = self.other_collection.evaluate(
            collection, environment, create
        )
    return [item for item in collection if item not in self.other_collection]

First

Path: fhircraft.fhir.path.engine.subsetting.First

Bases: FHIRPathFunction

A representation of the FHIRPath first() function.

Methods:

Name Description
evaluate

Returns a collection containing only the first item in the input collection.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns a collection containing only the first item in the input collection.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Type Description
FHIRPathCollection

FHIRPathCollection): The output collection.

Info

Equivalent to Index(0).

Source code in fhircraft/fhir/path/engine/subsetting.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns a collection containing only the first item in the input collection.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection): The output collection.

    Info:
        Equivalent to `Index(0)`.
    """
    return Index(0).evaluate(collection, environment, create=False)

Index

Path: fhircraft.fhir.path.engine.subsetting.Index

Index(index: int | Literal)

Bases: FHIRPath

A representation of the FHIRPath index [idx] operator.

Attributes:

Name Type Description
index int

The index value for the FHIRPath index.

Methods:

Name Description
evaluate

The indexer operation returns a collection with only the index-th item (0-based index). If the input

Source code in fhircraft/fhir/path/engine/subsetting.py
def __init__(self, index: int | Literal):
    if isinstance(index, Literal):
        index = index.value
    if not isinstance(index, int):
        raise FHIRPathError("Index() argument must be an integer number.")
    self.index = index

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

The indexer operation returns a collection with only the index-th item (0-based index). If the input collection is empty ([]), or the index lies outside the boundaries of the input collection, an empty collection is returned.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
create bool

Pad the collection array if the index lies out of bounds of the collection.

False

Returns:

Type Description
FHIRPathCollection

FHIRPathCollection): The indexed collection item.

Raises:

Type Description
FhirPathError

If create=True and collection is composed of items with different parent elements.

Notes

The collection padding with create=True allows the function to create and later access new elements. The padded object is initialized based on the collection items' common parent (if exists). Therefore, this option is only available for a homogeneous collection of items.

Source code in fhircraft/fhir/path/engine/subsetting.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    The indexer operation returns a collection with only the index-th item (0-based index). If the input
    collection is empty (`[]`), or the index lies outside the boundaries of the input collection,
    an empty collection is returned.

    Args:
        collection (FHIRPathCollection): The input collection.
        create (bool): Pad the collection array if the index lies out of bounds of the collection.

    Returns:
        FHIRPathCollection): The indexed collection item.

    Raises:
        FhirPathError: If `create=True` and collection is composed of items with different parent elements.

    Notes:
        The collection padding with `create=True` allows the function to create and later access new elements.
        The padded object is initialized based on the collection items' common parent (if exists).
        Therefore, this option is only available for a homogeneous collection of items.
    """
    # Check whether array is too short and it can be extended
    if len(collection) <= self.index and create:
        # Calculate how many elements must be padded
        pad = self.index - len(collection) + 1
        all_same_parent = collection and all(
            [
                (
                    item.parent.value
                    in [
                        subitem.parent.value
                        for subitem in collection
                        if subitem.parent
                    ]
                    if item.parent
                    else True
                )
                for item in collection
            ]
        )
        if all_same_parent:
            parent_array = collection[0]
            if parent_array.parent:
                new_values = ensure_list(
                    parent_array.parent.value.get(parent_array.path.label)
                    if isinstance(parent_array.parent.value, dict)
                    else getattr(parent_array.parent.value, parent_array.path.label)
                )
                if hasattr(new_values[0].__class__, "model_construct"):
                    new_values.extend(
                        [parent_array.construct_resource() for __ in range(pad)]
                    )
                else:
                    new_values.extend([None for __ in range(pad)])
            else:
                new_values = collection
                new_values.extend(
                    [FHIRPathCollectionItem.wrap(None) for __ in range(pad)]
                )
            return [
                FHIRPathCollectionItem(
                    new_values[self.index],
                    path=Element(parent_array.element or ""),
                    setter=(
                        partial(parent_array.setter, index=self.index)
                        if parent_array.setter
                        else None
                    ),
                    parent=parent_array.parent,
                )
            ]
        else:
            raise FHIRPathError(
                f"Cannot create new array element due to inhomogeneity in parents"
            )
    # If index is within array bounds, get element
    if collection and len(collection) > self.index:
        return [collection[self.index]]
    # Else return empty list
    return []

Intersect

Path: fhircraft.fhir.path.engine.subsetting.Intersect

Intersect(other_collection: FHIRPath | FHIRPathCollection)

Bases: FHIRPathFunction

A representation of the FHIRPath intersect() function.

Attributes:

Name Type Description
other_collection FHIRPathCollection

The other collection to compute the intersection with.

Methods:

Name Description
evaluate

Returns the set of elements that are in both collections. Duplicate items will be eliminated

Source code in fhircraft/fhir/path/engine/subsetting.py
def __init__(self, other_collection: FHIRPath | FHIRPathCollection):
    self.other_collection = other_collection

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the set of elements that are in both collections. Duplicate items will be eliminated by this function. Order of items is preserved in the result of this function.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Type Description
FHIRPathCollection

FHIRPathCollection): The output collection.

Source code in fhircraft/fhir/path/engine/subsetting.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the set of elements that are in both collections. Duplicate items will be eliminated
    by this function. Order of items is preserved in the result of this function.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection): The output collection.
    """
    if isinstance(self.other_collection, FHIRPath):
        self.other_collection = self.other_collection.evaluate(
            collection, environment, create
        )
    return [item for item in collection if item in self.other_collection]

Last

Path: fhircraft.fhir.path.engine.subsetting.Last

Bases: FHIRPathFunction

A representation of the FHIRPath last() function.

Methods:

Name Description
evaluate

Returns a collection containing only the last item in the input collection.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns a collection containing only the last item in the input collection.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Type Description
FHIRPathCollection

FHIRPathCollection): The output collection.

Info

Equivalent to Index(-1).

Source code in fhircraft/fhir/path/engine/subsetting.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns a collection containing only the last item in the input collection.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection): The output collection.

    Info:
        Equivalent to `Index(-1)`.
    """
    return Index(-1).evaluate(collection, environment, create=False)

Single

Path: fhircraft.fhir.path.engine.subsetting.Single

Bases: FHIRPathFunction

A representation of the FHIRPath single() function.

Methods:

Name Description
evaluate

Will return the single item in the input if there is just one item. If the input collection is empty ([]), the result is empty.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Will return the single item in the input if there is just one item. If the input collection is empty ([]), the result is empty. If there are multiple items, an error is signaled to the evaluation environment. This function is useful for ensuring that an error is returned if an assumption about cardinality is violated at run-time.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Type Description
FHIRPathCollection

FHIRPathCollection): The output collection.

Info

Equivalent to Index(0) with additional error raising in case of non-singleton input collection.

Source code in fhircraft/fhir/path/engine/subsetting.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Will return the single item in the input if there is just one item. If the input collection is empty (`[]`), the result is empty.
    If there are multiple items, an error is signaled to the evaluation environment. This function is useful for ensuring that an
    error is returned if an assumption about cardinality is violated at run-time.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection): The output collection.

    Info:
        Equivalent to `Index(0)` with additional error raising in case of non-singleton input collection.
    """
    if len(collection) > 1:
        raise FHIRPathError(
            f"Expected single value for single(), instead got {len(collection)} items in the collection"
        )
    return Index(0).evaluate(collection, environment, create=False)

Skip

Path: fhircraft.fhir.path.engine.subsetting.Skip

Skip(num: int | FHIRPath)

Bases: FHIRPathFunction

A representation of the FHIRPath skip() function.

Attributes:

Name Type Description
num int | FHIRPath

The number of items to skip or FHIRPath evaluating to an integer.

Methods:

Name Description
evaluate

Returns a collection containing all but the first num items in the input collection. Will return

Source code in fhircraft/fhir/path/engine/subsetting.py
def __init__(self, num: int | FHIRPath):
    self.num = Literal(num) if not isinstance(num, FHIRPath) else num

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns a collection containing all but the first num items in the input collection. Will return an empty collection if there are no items remaining after the indicated number of items have been skipped, or if the input collection is empty. If num is less than or equal to zero, the input collection is simply returned.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Type Description
FHIRPathCollection

FHIRPathCollection): The output collection.

Source code in fhircraft/fhir/path/engine/subsetting.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns a collection containing all but the first `num` items in the input collection. Will return
    an empty collection if there are no items remaining after the indicated number of items have
    been skipped, or if the input collection is empty. If `num` is less than or equal to zero, the
    input collection is simply returned.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection): The output collection.
    """
    if not isinstance(
        num := self.num.single(collection, environment=environment), int
    ):
        raise FHIRPathError("Skip() argument must evaluate to an integer number.")
    if num <= 0:
        return []
    return ensure_list(collection[num:])

Tail

Path: fhircraft.fhir.path.engine.subsetting.Tail

Bases: FHIRPathFunction

A representation of the FHIRPath tail() function.

Methods:

Name Description
evaluate

Returns a collection containing all but the first item in the input collection. Will return

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns a collection containing all but the first item in the input collection. Will return an empty collection if the input collection has no items, or only one item.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Type Description
FHIRPathCollection

FHIRPathCollection): The output collection.

Source code in fhircraft/fhir/path/engine/subsetting.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns a collection containing all but the first item in the input collection. Will return
    an empty collection if the input collection has no items, or only one item.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection): The output collection.
    """
    return ensure_list(collection[1:])

Take

Path: fhircraft.fhir.path.engine.subsetting.Take

Take(num: int | FHIRPath)

Bases: FHIRPathFunction

A representation of the FHIRPath take() function.

Attributes:

Name Type Description
num int

The number of items to take.

Methods:

Name Description
evaluate

Returns a collection containing the first num items in the input collection, or less if there

Source code in fhircraft/fhir/path/engine/subsetting.py
def __init__(self, num: int | FHIRPath):
    self.num = Literal(num) if not isinstance(num, FHIRPath) else num

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns a collection containing the first num items in the input collection, or less if there are less than num items. If num is less than or equal to 0, or if the input collection is empty ([]), take returns an empty collection.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Type Description
FHIRPathCollection

FHIRPathCollection): The output collection.

Source code in fhircraft/fhir/path/engine/subsetting.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns a collection containing the first `num` items in the input collection, or less if there
    are less than `num` items. If num is less than or equal to 0, or if the input collection
    is empty (`[]`), take returns an empty collection.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection): The output collection.
    """
    if not isinstance(
        num := self.num.single(collection, environment=environment), int
    ):
        raise FHIRPathError("Skip() argument must evaluate to an integer number.")
    if num <= 0:
        return []
    return ensure_list(collection[:num])

As

Path: fhircraft.fhir.path.engine.types.As

As(left: FHIRPath | FHIRPathCollection, type_specifier: TypeSpecifier)

Bases: FHIRTypesOperator

A representation of the FHIRPath as operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

type_specifier str

Type specifier.

Methods:

Name Description
evaluate

If the left operand is a collection with a single item and the second operand is an identifier,

Source code in fhircraft/fhir/path/engine/types.py
def __init__(
    self,
    left: FHIRPath | FHIRPathCollection,
    type_specifier: TypeSpecifier,
):
    self.type_specifier = type_specifier
    self.left = left

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the left operand is a collection with a single item and the second operand is an identifier, this operator returns the value of the left operand if it is of the type specified in the second operand, or a subclass thereof. If the identifier cannot be resolved to a valid type identifier, the evaluator will throw an error. If there is more than one item in the input collection, the evaluator will throw an error. Otherwise, this operator returns the empty collection.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathRuntimeError

If either expression evaluates to a non-singleton collection.

Source code in fhircraft/fhir/path/engine/types.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the left operand is a collection with a single item and the second operand is an identifier,
    this operator returns the value of the left operand if it is of the type specified in the second
    operand, or a subclass thereof. If the identifier cannot be resolved to a valid type identifier,
    the evaluator will throw an error. If there is more than one item in the input collection, the
    evaluator will throw an error. Otherwise, this operator returns the empty collection.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: If either expression evaluates to a non-singleton collection.
    """
    value = self._get_singleton_collection_value(collection, environment, create)
    if value is None:
        return []
    return (
        [FHIRPathCollectionItem.wrap(value)]
        if self._validate_type_specifier(value, environment, create)
        else []
    )

FHIRTypesOperator

Path: fhircraft.fhir.path.engine.types.FHIRTypesOperator

FHIRTypesOperator(left: FHIRPath | FHIRPathCollection, type_specifier: TypeSpecifier)

Bases: FHIRPath

Abstract class definition for the category of types FHIRPath operators.

Source code in fhircraft/fhir/path/engine/types.py
def __init__(
    self,
    left: FHIRPath | FHIRPathCollection,
    type_specifier: TypeSpecifier,
):
    self.type_specifier = type_specifier
    self.left = left

Is

Path: fhircraft.fhir.path.engine.types.Is

Is(left: FHIRPath | FHIRPathCollection, type_specifier: TypeSpecifier)

Bases: FHIRTypesOperator

A representation of the FHIRPath is operator.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

type_specifier str

Type specifier.

Methods:

Name Description
evaluate

If the left operand is a collection with a single item and the second operand is a type identifier,

Source code in fhircraft/fhir/path/engine/types.py
def __init__(
    self,
    left: FHIRPath | FHIRPathCollection,
    type_specifier: TypeSpecifier,
):
    self.type_specifier = type_specifier
    self.left = left

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

If the left operand is a collection with a single item and the second operand is a type identifier, this operator returns true if the type of the left operand is the type specified in the second operand, or a subclass thereof. If the input value is not of the type, this operator returns false. If the identifier cannot be resolved to a valid type identifier, the evaluator will throw an error. If the input collections contains more than one item, the evaluator will throw an error. In all other cases this operator returns the empty collection.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
FHIRPathCollection FHIRPathCollection

The output collection.

Raises:

Type Description
FHIRPathRuntimeError

If either expression evaluates to a non-singleton collection.

Source code in fhircraft/fhir/path/engine/types.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    If the left operand is a collection with a single item and the second operand is a type identifier,
    this operator returns true if the type of the left operand is the type specified in the second operand,
    or a subclass thereof. If the input value is not of the type, this operator returns false. If the identifier
    cannot be resolved to a valid type identifier, the evaluator will throw an error. If the input collections
    contains more than one item, the evaluator will throw an error. In all other cases this operator returns the empty collection.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        FHIRPathCollection: The output collection.

    Raises:
        FHIRPathRuntimeError: If either expression evaluates to a non-singleton collection.
    """
    value = self._get_singleton_collection_value(collection, environment, create)
    if value is None:
        return []
    return [
        FHIRPathCollectionItem.wrap(
            self._validate_type_specifier(value, environment, create)
        )
    ]

LegacyAs

Path: fhircraft.fhir.path.engine.types.LegacyAs

LegacyAs(type_specifier: TypeSpecifier)

Bases: FHIRPathFunction

The as() function is supported for backwards compatibility with previous implementations of FHIRPath. Just as with the as keyword, the type argument is an identifier that must resolve to the name of a type in a model.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

type_specifier str

Type specifier.

Source code in fhircraft/fhir/path/engine/types.py
def __init__(self, type_specifier: TypeSpecifier):
    self.type_specifier: TypeSpecifier = type_specifier

LegacyIs

Path: fhircraft.fhir.path.engine.types.LegacyIs

LegacyIs(type_specifier: TypeSpecifier)

Bases: FHIRPathFunction

The is() function is supported for backwards compatibility with previous implementations of FHIRPath. Just as with the is keyword, the type argument is an identifier that must resolve to the name of a type in a model.

Attributes:

Name Type Description
left FHIRPath | FHIRPathCollection

Left operand.

type_specifier str

Type specifier.

Source code in fhircraft/fhir/path/engine/types.py
def __init__(self, type_specifier: TypeSpecifier):
    self.type_specifier = type_specifier

Now

Path: fhircraft.fhir.path.engine.utility.Now

Bases: FHIRPathFunction

A representation of the FHIRPath now() function.

Methods:

Name Description
evaluate

Returns the current date and time, including timezone offset.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the current date and time, including timezone offset.

Returns:

Name Type Description
DateTime FHIRPathCollection

The current date and time, including timezone offset.

Source code in fhircraft/fhir/path/engine/utility.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the current date and time, including timezone offset.

    Returns:
        DateTime: The current date and time, including timezone offset.
    """
    now = datetime.datetime.now()
    return [FHIRPathCollectionItem(DateTime(value_datetime=now))]

TimeOfDay

Path: fhircraft.fhir.path.engine.utility.TimeOfDay

Bases: FHIRPathFunction

A representation of the FHIRPath timeOfDay() function.

Methods:

Name Description
evaluate

Returns the current time.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the current time.

Returns:

Name Type Description
Time FHIRPathCollection

The current time.

Source code in fhircraft/fhir/path/engine/utility.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the current time.

    Returns:
        Time: The current time.
    """
    return [FHIRPathCollectionItem(Time(value_time=datetime.datetime.now()))]

Today

Path: fhircraft.fhir.path.engine.utility.Today

Bases: FHIRPathFunction

A representation of the FHIRPath Today() function.

Methods:

Name Description
evaluate

Returns the current date.

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Returns the current date.

Returns:

Name Type Description
Date FHIRPathCollection

The current date.

Source code in fhircraft/fhir/path/engine/utility.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Returns the current date.

    Returns:
        Date: The current date.
    """
    return [FHIRPathCollectionItem(Date(value_date=datetime.datetime.now().date()))]

Trace

Path: fhircraft.fhir.path.engine.utility.Trace

Trace(name: FHIRPath | str, projection: Optional[FHIRPath] = None)

Bases: FHIRPathFunction

A representation of the FHIRPath trace() function.

Attributes:

Name Type Description
name (str | FHIRPath

Subtring query or FHIRPath to evaluate for the trace name.

Methods:

Name Description
evaluate

Adds a String representation of the input collection to the diagnostic log, using the name argument

Source code in fhircraft/fhir/path/engine/utility.py
def __init__(self, name: FHIRPath | str, projection: Optional[FHIRPath] = None):
    self.name = Literal(name) if isinstance(name, str) else name
    self.projection = projection

evaluate

evaluate(collection: FHIRPathCollection, environment: dict, create: bool = False) -> FHIRPathCollection

Adds a String representation of the input collection to the diagnostic log, using the name argument as the name in the log. This log should be made available to the user in some appropriate fashion. Does not change the input, so returns the input collection as output.

If the projection argument is used, the trace would log the result of evaluating the project expression on the input, but still return the input to the trace function unchanged.

Parameters:

Name Type Description Default
collection FHIRPathCollection

The input collection.

required
environment dict

The environment context for the evaluation.

required
create bool

Whether to create new elements during evaluation if necessary.

False

Returns:

Name Type Description
collection FHIRPathCollection

The input collection.

Source code in fhircraft/fhir/path/engine/utility.py
def evaluate(
    self, collection: FHIRPathCollection, environment: dict, create: bool = False
) -> FHIRPathCollection:
    """
    Adds a `String` representation of the input collection to the diagnostic log, using the `name` argument
    as the name in the log. This log should be made available to the user in some appropriate fashion. Does not
    change the input, so returns the input collection as output.

    If the `projection` argument is used, the trace would log the result of evaluating the project expression on the input,
    but still return the input to the trace function unchanged.

    Args:
        collection (FHIRPathCollection): The input collection.
        environment (dict): The environment context for the evaluation.
        create (bool): Whether to create new elements during evaluation if necessary.

    Returns:
        collection (FHIRPathCollection): The input collection.
    """
    log_collection = collection
    if self.projection:
        log_collection = Select(self.projection).evaluate(
            collection, environment, create
        )
    if not isinstance(
        name := self.name.single(collection, environment=environment), str
    ):
        raise TypeError("Trace name must evaluate to a string.")
    logger.debug(
        f"FHIRPath trace: {name} - {[str(item.value) if isinstance(item, FHIRPathCollectionItem) else str(item) for item in ensure_list(log_collection)]}"
    )
    return collection