Skip to content

onconova.interoperability.fhir.utils

COMMON_CLINICAL_UNITS module-attribute

construct_fhir_codeable_concept(concept)

Construct a FHIR CodeableConcept from a CodedConcept or Coding object.

Parameters:

Name Type Description Default

concept

CodedConcept | Coding

The concept to convert. Can be either a CodedConcept or a Coding object.

required

Returns:

Name Type Description
CodeableConcept CodeableConcept

A FHIR CodeableConcept containing the provided concept as a coding element.

Examples:

>>> coded_concept = CodedConcept(...)
>>> codeable = construct_fhir_codeable_concept(coded_concept)
>>>
>>> coding = Coding(...)
>>> codeable = construct_fhir_codeable_concept(coding)
Source code in onconova/interoperability/fhir/utils.py
def construct_fhir_codeable_concept(concept: CodedConcept | Coding) -> CodeableConcept:
    """
    Construct a FHIR CodeableConcept from a CodedConcept or Coding object.

    Args:
        concept (CodedConcept | Coding): The concept to convert. Can be either a
            CodedConcept or a Coding object.

    Returns:
        CodeableConcept: A FHIR CodeableConcept containing the provided concept
            as a coding element.

    Examples:
        >>> coded_concept = CodedConcept(...)
        >>> codeable = construct_fhir_codeable_concept(coded_concept)
        >>>
        >>> coding = Coding(...)
        >>> codeable = construct_fhir_codeable_concept(coding)
    """
    if isinstance(concept, CodedConcept):
        return CodeableConcept(coding=[Coding(code=concept.code, system=concept.system, version=concept.version, display=concept.display)])
    elif isinstance(concept, Coding):
        return CodeableConcept(coding=[concept])

get_common_ucum_equivalent(internal_unit)

Get UCUM equivalent for common clinical units.

Parameters:

Name Type Description Default

internal_unit

str

Internal unit format

required

Returns:

Type Description
str

UCUM equivalent or original if not found

Source code in onconova/interoperability/fhir/utils.py
def get_common_ucum_equivalent(internal_unit: str) -> str:
    """Get UCUM equivalent for common clinical units.

    Args:
        internal_unit: Internal unit format

    Returns:
        UCUM equivalent or original if not found
    """
    return COMMON_CLINICAL_UNITS.get(internal_unit, internal_to_ucum(internal_unit))

get_unit_type_category(unit)

Categorize a unit by type for better organization.

Parameters:

Name Type Description Default

unit

str

Unit string (internal or UCUM format)

required

Returns:

Type Description
str

Unit category string

Source code in onconova/interoperability/fhir/utils.py
def get_unit_type_category(unit: str) -> str:
    """Categorize a unit by type for better organization.

    Args:
        unit: Unit string (internal or UCUM format)

    Returns:
        Unit category string
    """
    if not unit or not isinstance(unit, str):
        return "unknown"

    unit_lower = unit.lower()

    # Categorize based on common patterns and measure types
    if any(
        x in unit_lower
        for x in ["g/", "mg/", "ug/", "ng/", "pg/", "g__", "mg__", "ug__"]
    ):
        return "mass_concentration"
    elif any(
        x in unit_lower for x in ["mol/", "mmol/", "umol/", "nmol/", "mol__", "mmol__"]
    ):
        return "substance_concentration"
    elif any(x in unit_lower for x in ["iu/", "[iu]/", "u/", "iu__", "u__"]):
        return "activity_concentration"
    elif any(x in unit_lower for x in ["cells/", "{cells}/", "cells__"]):
        return "cell_count"
    elif any(x in unit_lower for x in ["%", "ppm", "ppb", "ppt"]):
        return "fraction"
    elif any(
        x in unit_lower for x in ["cel", "degf", "fahrenheit", "celsius", "kelvin"]
    ):
        return "temperature"
    elif any(
        x in unit_lower for x in ["mmhg", "mm[hg]", "pa", "atm", "bar", "psi", "torr"]
    ):
        return "pressure"
    elif any(x in unit_lower for x in ["m2", "m3", "cm2", "cm3", "square", "cubic"]):
        return "area_volume"
    elif any(
        x in unit_lower for x in ["s", "min", "hour", "day", "week", "month", "year"]
    ):
        return "time"
    elif any(x in unit_lower for x in ["gy", "gray"]):
        return "radiation_dose"
    elif any(x in unit_lower for x in ["ph]", "ph_units"]):
        return "ph_scale"
    elif any(x in unit_lower for x in ["osm", "mosm"]):
        return "osmolality"
    else:
        return "other"

internal_to_ucum(unit)

Convert internal unit representation to UCUM format.

Maps internal unit strings used in measures.py to their UCUM equivalents. Handles both simple units and bidimensional units (e.g., mg__dl -> mg/dL).

Parameters:

Name Type Description Default

unit

str

Internal unit string representation

required

Returns:

Type Description
str

UCUM-formatted unit string

Examples:

>>> internal_to_ucum("mg__dl")
'mg/dL'
>>> internal_to_ucum("IU")
'[iU]'
>>> internal_to_ucum("square_meter")
'm2'
Source code in onconova/interoperability/fhir/utils.py
def internal_to_ucum(unit: str) -> str:
    """Convert internal unit representation to UCUM format.

    Maps internal unit strings used in measures.py to their UCUM equivalents.
    Handles both simple units and bidimensional units (e.g., mg__dl -> mg/dL).

    Args:
        unit: Internal unit string representation

    Returns:
        UCUM-formatted unit string

    Examples:
        >>> internal_to_ucum("mg__dl")
        'mg/dL'
        >>> internal_to_ucum("IU")
        '[iU]'
        >>> internal_to_ucum("square_meter")
        'm2'
    """
    if not unit or not isinstance(unit, str):
        return unit

    # Handle bidimensional units first (primary__reference format)
    if "__" in unit:
        primary, reference = unit.split("__", 1)
        # Convert both parts and combine with UCUM division
        primary_ucum = _convert_single_unit_to_ucum(primary)
        reference_ucum = _convert_single_unit_to_ucum(reference)
        return f"{primary_ucum}/{reference_ucum}"

    # Handle simple units
    return _convert_single_unit_to_ucum(unit)

normalize_unit_string(unit)

Normalize a unit string by handling common variations and case issues.

Parameters:

Name Type Description Default

unit

str

Unit string to normalize

required

Returns:

Type Description
str

Normalized unit string

Source code in onconova/interoperability/fhir/utils.py
def normalize_unit_string(unit: str) -> str:
    """Normalize a unit string by handling common variations and case issues.

    Args:
        unit: Unit string to normalize

    Returns:
        Normalized unit string
    """
    if not unit or not isinstance(unit, str):
        return unit

    # Remove extra whitespace
    normalized = unit.strip()

    # Handle common case variations
    case_normalizations = {
        "ML": "mL",
        "DL": "dL",
        "UL": "uL",
        "Ml": "mL",
        "Dl": "dL",
        "Ul": "uL",
        "iu": "[iU]",  # UCUM format
        "IU": "IU",  # Internal format
    }

    for old, new in case_normalizations.items():
        if normalized == old:
            normalized = new
            break

    return normalized

ucum_to_internal(unit)

Convert UCUM unit format to internal representation.

Maps UCUM unit strings to internal format used in measures.py. Handles both simple units and compound units with division.

Parameters:

Name Type Description Default

unit

str

UCUM-formatted unit string

required

Returns:

Type Description
str

Internal unit string representation

Examples:

>>> ucum_to_internal("mg/dL")
'mg__dl'
>>> ucum_to_internal("[iU]")
'IU'
>>> ucum_to_internal("m2")
'square_meter'
Source code in onconova/interoperability/fhir/utils.py
def ucum_to_internal(unit: str) -> str:
    """Convert UCUM unit format to internal representation.

    Maps UCUM unit strings to internal format used in measures.py.
    Handles both simple units and compound units with division.

    Args:
        unit: UCUM-formatted unit string

    Returns:
        Internal unit string representation

    Examples:
        >>> ucum_to_internal("mg/dL")
        'mg__dl'
        >>> ucum_to_internal("[iU]")
        'IU'
        >>> ucum_to_internal("m2")
        'square_meter'
    """
    if not unit or not isinstance(unit, str):
        return unit

    # Handle compound units with division
    if "/" in unit:
        parts = unit.split("/", 1)  # Split on first occurrence only
        primary_ucum = parts[0]
        reference_ucum = parts[1]

        # Convert both parts and combine with internal format
        primary_internal = _convert_single_ucum_to_internal(primary_ucum)
        reference_internal = _convert_single_ucum_to_internal(reference_ucum)
        return f"{primary_internal}__{reference_internal}"

    # Handle simple units
    return _convert_single_ucum_to_internal(unit)

validate_bidirectional_conversion(internal_unit)

Validate that a unit conversion works bidirectionally.

Parameters:

Name Type Description Default

internal_unit

str

Internal format unit to test

required

Returns:

Type Description
bool

True if conversion is bidirectional, False otherwise

Source code in onconova/interoperability/fhir/utils.py
def validate_bidirectional_conversion(internal_unit: str) -> bool:
    """Validate that a unit conversion works bidirectionally.

    Args:\n        internal_unit: Internal format unit to test

    Returns:\n        True if conversion is bidirectional, False otherwise
    """
    try:
        # Test internal -> UCUM -> internal roundtrip
        ucum_unit = internal_to_ucum(internal_unit)
        back_to_internal = ucum_to_internal(ucum_unit)
        return back_to_internal == internal_unit
    except Exception:
        return False
runner