Data Exchange For Quality Measures Implementation Guide
4.0.0 - STU4 United States of America

This page is part of the Da Vinci Data Exchange for Quality Measures (DEQM) FHIR IG (v4.0.0: STU4 (v4.0.0)) based on FHIR R4. This is the current published version. For a full list of available versions, see the Directory of published versions

Example Bundle: Additional Supplemental Data Example - Artifact Bundle

Bundle sde-example-artifact-bundle of type transaction


Entry 1 - fullUrl = urn:uuid:31244296-3e84-4e17-94b1-4159d64e41db

Request:

PUT Library/FHIRHelpers

Resource Library:

Related Artifacts

Depends OnFHIR model informationhttp://fhir.org/guides/cqf/common/Library/FHIR-ModelInfo|4.0.1

Contents

text/cql

/*
@author: Bryn Rhodes
@description: This library defines functions to convert between FHIR
 data types and CQL system-defined types, as well as functions to support
 FHIRPath implementation. For more information, see the FHIRHelpers wiki page:
 https://github.com/cqframework/clinical_quality_language/wiki/FHIRHelpers
@allowFluent: true
*/
library FHIRHelpers version '4.0.1'

using FHIR version '4.0.1'

define function ToInterval(period FHIR.Period):
    if period is null then
        null
    else
        if period."start" is null then
            Interval(period."start".value, period."end".value]
        else
            Interval[period."start".value, period."end".value]

define function ToCalendarUnit(unit System.String):
    case unit
        when 'ms' then 'millisecond'
        when 's' then 'second'
        when 'min' then 'minute'
        when 'h' then 'hour'
        when 'd' then 'day'
        when 'wk' then 'week'
        when 'mo' then 'month'
        when 'a' then 'year'
        else unit
    end

define function ToQuantity(quantity FHIR.Quantity):
    case
        when quantity is null then null
        when quantity.value is null then null
        when quantity.comparator is not null then
            Message(null, true, 'FHIRHelpers.ToQuantity.ComparatorQuantityNotSupported', 'Error', 'FHIR Quantity value has a comparator and cannot be converted to a System.Quantity value.')
        when quantity.system is null or quantity.system.value = 'http://unitsofmeasure.org'
              or quantity.system.value = 'http://hl7.org/fhirpath/CodeSystem/calendar-units' then
            System.Quantity { value: quantity.value.value, unit: ToCalendarUnit(Coalesce(quantity.code.value, quantity.unit.value, '1')) }
        else
            Message(null, true, 'FHIRHelpers.ToQuantity.InvalidFHIRQuantity', 'Error', 'Invalid FHIR Quantity code: ' & quantity.unit.value & ' (' & quantity.system.value & '|' & quantity.code.value & ')')
    end

define function ToQuantityIgnoringComparator(quantity FHIR.Quantity):
    case
        when quantity is null then null
        when quantity.value is null then null
        when quantity.system is null or quantity.system.value = 'http://unitsofmeasure.org'
              or quantity.system.value = 'http://hl7.org/fhirpath/CodeSystem/calendar-units' then
            System.Quantity { value: quantity.value.value, unit: ToCalendarUnit(Coalesce(quantity.code.value, quantity.unit.value, '1')) }
        else
            Message(null, true, 'FHIRHelpers.ToQuantity.InvalidFHIRQuantity', 'Error', 'Invalid FHIR Quantity code: ' & quantity.unit.value & ' (' & quantity.system.value & '|' & quantity.code.value & ')')
    end

define function ToInterval(quantity FHIR.Quantity):
    if quantity is null then null else
        case quantity.comparator.value
            when '<' then
                Interval[
                    null,
                    ToQuantityIgnoringComparator(quantity)
                )
            when '<=' then
                Interval[
                    null,
                    ToQuantityIgnoringComparator(quantity)
                ]
            when '>=' then
                Interval[
                    ToQuantityIgnoringComparator(quantity),
                    null
                ]
            when '>' then
                Interval(
                    ToQuantityIgnoringComparator(quantity),
                    null
                ]
            else
                Interval[ToQuantity(quantity), ToQuantity(quantity)]
        end

define function ToRatio(ratio FHIR.Ratio):
    if ratio is null then
        null
    else
        System.Ratio { numerator: ToQuantity(ratio.numerator), denominator: ToQuantity(ratio.denominator) }

define function ToInterval(range FHIR.Range):
    if range is null then
        null
    else
        Interval[ToQuantity(range.low), ToQuantity(range.high)]

define function ToCode(coding FHIR.Coding):
    if coding is null then
        null
    else
        System.Code {
          code: coding.code.value,
          system: coding.system.value,
          version: coding.version.value,
          display: coding.display.value
        }

define function ToConcept(concept FHIR.CodeableConcept):
    if concept is null then
        null
    else
        System.Concept {
            codes: concept.coding C return ToCode(C),
            display: concept.text.value
        }

define function reference(reference String):
    if reference is null then
        null
    else
        Reference { reference: string { value: reference } }

define function resolve(reference String) returns Resource: external
define function resolve(reference Reference) returns Resource: external
define function reference(resource Resource) returns Reference: external
define function extension(element Element, url String) returns List<Element>: external
define function extension(resource Resource, url String) returns List<Element>: external
define function hasValue(element Element) returns Boolean: external
define function getValue(element Element) returns Any: external
define function ofType(identifier String) returns List<Any>: external
define function is(identifier String) returns Boolean: external
define function as(identifier String) returns Any: external
define function elementDefinition(element Element) returns ElementDefinition: external
define function slice(element Element, url String, name String) returns List<Element>: external
define function checkModifiers(resource Resource) returns Resource: external
define function checkModifiers(resource Resource, modifier String) returns Resource: external
define function checkModifiers(element Element) returns Element: external
define function checkModifiers(element Element, modifier String) returns Element: external
define function conformsTo(resource Resource, structure String) returns Boolean: external
define function memberOf(code code, valueSet String) returns Boolean: external
define function memberOf(coding Coding, valueSet String) returns Boolean: external
define function memberOf(concept CodeableConcept, valueSet String) returns Boolean: external
define function subsumes(coding Coding, subsumedCoding Coding) returns Boolean: external
define function subsumes(concept CodeableConcept, subsumedConcept CodeableConcept) returns Boolean: external
define function subsumedBy(coding Coding, subsumingCoding Coding) returns Boolean: external
define function subsumedBy(concept CodeableConcept, subsumingConcept CodeableConcept) returns Boolean: external
define function htmlChecks(element Element) returns Boolean: external

define function ToString(value AccountStatus): value.value
define function ToString(value ActionCardinalityBehavior): value.value
define function ToString(value ActionConditionKind): value.value
define function ToString(value ActionGroupingBehavior): value.value
define function ToString(value ActionParticipantType): value.value
define function ToString(value ActionPrecheckBehavior): value.value
define function ToString(value ActionRelationshipType): value.value
define function ToString(value ActionRequiredBehavior): value.value
define function ToString(value ActionSelectionBehavior): value.value
define function ToString(value ActivityDefinitionKind): value.value
define function ToString(value ActivityParticipantType): value.value
define function ToString(value AddressType): value.value
define function ToString(value AddressUse): value.value
define function ToString(value AdministrativeGender): value.value
define function ToString(value AdverseEventActuality): value.value
define function ToString(value AggregationMode): value.value
define function ToString(value AllergyIntoleranceCategory): value.value
define function ToString(value AllergyIntoleranceCriticality): value.value
define function ToString(value AllergyIntoleranceSeverity): value.value
define function ToString(value AllergyIntoleranceType): value.value
define function ToString(value AppointmentStatus): value.value
define function ToString(value AssertionDirectionType): value.value
define function ToString(value AssertionOperatorType): value.value
define function ToString(value AssertionResponseTypes): value.value
define function ToString(value AuditEventAction): value.value
define function ToString(value AuditEventAgentNetworkType): value.value
define function ToString(value AuditEventOutcome): value.value
define function ToString(value BindingStrength): value.value
define function ToString(value BiologicallyDerivedProductCategory): value.value
define function ToString(value BiologicallyDerivedProductStatus): value.value
define function ToString(value BiologicallyDerivedProductStorageScale): value.value
define function ToString(value BundleType): value.value
define function ToString(value CapabilityStatementKind): value.value
define function ToString(value CarePlanActivityKind): value.value
define function ToString(value CarePlanActivityStatus): value.value
define function ToString(value CarePlanIntent): value.value
define function ToString(value CarePlanStatus): value.value
define function ToString(value CareTeamStatus): value.value
define function ToString(value CatalogEntryRelationType): value.value
define function ToString(value ChargeItemDefinitionPriceComponentType): value.value
define function ToString(value ChargeItemStatus): value.value
define function ToString(value ClaimResponseStatus): value.value
define function ToString(value ClaimStatus): value.value
define function ToString(value ClinicalImpressionStatus): value.value
define function ToString(value CodeSearchSupport): value.value
define function ToString(value CodeSystemContentMode): value.value
define function ToString(value CodeSystemHierarchyMeaning): value.value
define function ToString(value CommunicationPriority): value.value
define function ToString(value CommunicationRequestStatus): value.value
define function ToString(value CommunicationStatus): value.value
define function ToString(value CompartmentCode): value.value
define function ToString(value CompartmentType): value.value
define function ToString(value CompositionAttestationMode): value.value
define function ToString(value CompositionStatus): value.value
define function ToString(value ConceptMapEquivalence): value.value
define function ToString(value ConceptMapGroupUnmappedMode): value.value
define function ToString(value ConditionalDeleteStatus): value.value
define function ToString(value ConditionalReadStatus): value.value
define function ToString(value ConsentDataMeaning): value.value
define function ToString(value ConsentProvisionType): value.value
define function ToString(value ConsentState): value.value
define function ToString(value ConstraintSeverity): value.value
define function ToString(value ContactPointSystem): value.value
define function ToString(value ContactPointUse): value.value
define function ToString(value ContractPublicationStatus): value.value
define function ToString(value ContractStatus): value.value
define function ToString(value ContributorType): value.value
define function ToString(value CoverageStatus): value.value
define function ToString(value CurrencyCode): value.value
define function ToString(value DayOfWeek): value.value
define function ToString(value DaysOfWeek): value.value
define function ToString(value DetectedIssueSeverity): value.value
define function ToString(value DetectedIssueStatus): value.value
define function ToString(value DeviceMetricCalibrationState): value.value
define function ToString(value DeviceMetricCalibrationType): value.value
define function ToString(value DeviceMetricCategory): value.value
define function ToString(value DeviceMetricColor): value.value
define function ToString(value DeviceMetricOperationalStatus): value.value
define function ToString(value DeviceNameType): value.value
define function ToString(value DeviceRequestStatus): value.value
define function ToString(value DeviceUseStatementStatus): value.value
define function ToString(value DiagnosticReportStatus): value.value
define function ToString(value DiscriminatorType): value.value
define function ToString(value DocumentConfidentiality): value.value
define function ToString(value DocumentMode): value.value
define function ToString(value DocumentReferenceStatus): value.value
define function ToString(value DocumentRelationshipType): value.value
define function ToString(value EligibilityRequestPurpose): value.value
define function ToString(value EligibilityRequestStatus): value.value
define function ToString(value EligibilityResponsePurpose): value.value
define function ToString(value EligibilityResponseStatus): value.value
define function ToString(value EnableWhenBehavior): value.value
define function ToString(value EncounterLocationStatus): value.value
define function ToString(value EncounterStatus): value.value
define function ToString(value EndpointStatus): value.value
define function ToString(value EnrollmentRequestStatus): value.value
define function ToString(value EnrollmentResponseStatus): value.value
define function ToString(value EpisodeOfCareStatus): value.value
define function ToString(value EventCapabilityMode): value.value
define function ToString(value EventTiming): value.value
define function ToString(value EvidenceVariableType): value.value
define function ToString(value ExampleScenarioActorType): value.value
define function ToString(value ExplanationOfBenefitStatus): value.value
define function ToString(value ExposureState): value.value
define function ToString(value ExtensionContextType): value.value
define function ToString(value FHIRAllTypes): value.value
define function ToString(value FHIRDefinedType): value.value
define function ToString(value FHIRDeviceStatus): value.value
define function ToString(value FHIRResourceType): value.value
define function ToString(value FHIRSubstanceStatus): value.value
define function ToString(value FHIRVersion): value.value
define function ToString(value FamilyHistoryStatus): value.value
define function ToString(value FilterOperator): value.value
define function ToString(value FlagStatus): value.value
define function ToString(value GoalLifecycleStatus): value.value
define function ToString(value GraphCompartmentRule): value.value
define function ToString(value GraphCompartmentUse): value.value
define function ToString(value GroupMeasure): value.value
define function ToString(value GroupType): value.value
define function ToString(value GuidanceResponseStatus): value.value
define function ToString(value GuidePageGeneration): value.value
define function ToString(value GuideParameterCode): value.value
define function ToString(value HTTPVerb): value.value
define function ToString(value IdentifierUse): value.value
define function ToString(value IdentityAssuranceLevel): value.value
define function ToString(value ImagingStudyStatus): value.value
define function ToString(value ImmunizationEvaluationStatus): value.value
define function ToString(value ImmunizationStatus): value.value
define function ToString(value InvoicePriceComponentType): value.value
define function ToString(value InvoiceStatus): value.value
define function ToString(value IssueSeverity): value.value
define function ToString(value IssueType): value.value
define function ToString(value LinkType): value.value
define function ToString(value LinkageType): value.value
define function ToString(value ListMode): value.value
define function ToString(value ListStatus): value.value
define function ToString(value LocationMode): value.value
define function ToString(value LocationStatus): value.value
define function ToString(value MeasureReportStatus): value.value
define function ToString(value MeasureReportType): value.value
define function ToString(value MediaStatus): value.value
define function ToString(value MedicationAdministrationStatus): value.value
define function ToString(value MedicationDispenseStatus): value.value
define function ToString(value MedicationKnowledgeStatus): value.value
define function ToString(value MedicationRequestIntent): value.value
define function ToString(value MedicationRequestPriority): value.value
define function ToString(value MedicationRequestStatus): value.value
define function ToString(value MedicationStatementStatus): value.value
define function ToString(value MedicationStatus): value.value
define function ToString(value MessageSignificanceCategory): value.value
define function ToString(value Messageheader_Response_Request): value.value
define function ToString(value MimeType): value.value
define function ToString(value NameUse): value.value
define function ToString(value NamingSystemIdentifierType): value.value
define function ToString(value NamingSystemType): value.value
define function ToString(value NarrativeStatus): value.value
define function ToString(value NoteType): value.value
define function ToString(value NutritiionOrderIntent): value.value
define function ToString(value NutritionOrderStatus): value.value
define function ToString(value ObservationDataType): value.value
define function ToString(value ObservationRangeCategory): value.value
define function ToString(value ObservationStatus): value.value
define function ToString(value OperationKind): value.value
define function ToString(value OperationParameterUse): value.value
define function ToString(value OrientationType): value.value
define function ToString(value ParameterUse): value.value
define function ToString(value ParticipantRequired): value.value
define function ToString(value ParticipantStatus): value.value
define function ToString(value ParticipationStatus): value.value
define function ToString(value PaymentNoticeStatus): value.value
define function ToString(value PaymentReconciliationStatus): value.value
define function ToString(value ProcedureStatus): value.value
define function ToString(value PropertyRepresentation): value.value
define function ToString(value PropertyType): value.value
define function ToString(value ProvenanceEntityRole): value.value
define function ToString(value PublicationStatus): value.value
define function ToString(value QualityType): value.value
define function ToString(value QuantityComparator): value.value
define function ToString(value QuestionnaireItemOperator): value.value
define function ToString(value QuestionnaireItemType): value.value
define function ToString(value QuestionnaireResponseStatus): value.value
define function ToString(value ReferenceHandlingPolicy): value.value
define function ToString(value ReferenceVersionRules): value.value
define function ToString(value ReferredDocumentStatus): value.value
define function ToString(value RelatedArtifactType): value.value
define function ToString(value RemittanceOutcome): value.value
define function ToString(value RepositoryType): value.value
define function ToString(value RequestIntent): value.value
define function ToString(value RequestPriority): value.value
define function ToString(value RequestStatus): value.value
define function ToString(value ResearchElementType): value.value
define function ToString(value ResearchStudyStatus): value.value
define function ToString(value ResearchSubjectStatus): value.value
define function ToString(value ResourceType): value.value
define function ToString(value ResourceVersionPolicy): value.value
define function ToString(value ResponseType): value.value
define function ToString(value RestfulCapabilityMode): value.value
define function ToString(value RiskAssessmentStatus): value.value
define function ToString(value SPDXLicense): value.value
define function ToString(value SearchComparator): value.value
define function ToString(value SearchEntryMode): value.value
define function ToString(value SearchModifierCode): value.value
define function ToString(value SearchParamType): value.value
define function ToString(value SectionMode): value.value
define function ToString(value SequenceType): value.value
define function ToString(value ServiceRequestIntent): value.value
define function ToString(value ServiceRequestPriority): value.value
define function ToString(value ServiceRequestStatus): value.value
define function ToString(value SlicingRules): value.value
define function ToString(value SlotStatus): value.value
define function ToString(value SortDirection): value.value
define function ToString(value SpecimenContainedPreference): value.value
define function ToString(value SpecimenStatus): value.value
define function ToString(value Status): value.value
define function ToString(value StrandType): value.value
define function ToString(value StructureDefinitionKind): value.value
define function ToString(value StructureMapContextType): value.value
define function ToString(value StructureMapGroupTypeMode): value.value
define function ToString(value StructureMapInputMode): value.value
define function ToString(value StructureMapModelMode): value.value
define function ToString(value StructureMapSourceListMode): value.value
define function ToString(value StructureMapTargetListMode): value.value
define function ToString(value StructureMapTransform): value.value
define function ToString(value SubscriptionChannelType): value.value
define function ToString(value SubscriptionStatus): value.value
define function ToString(value SupplyDeliveryStatus): value.value
define function ToString(value SupplyRequestStatus): value.value
define function ToString(value SystemRestfulInteraction): value.value
define function ToString(value TaskIntent): value.value
define function ToString(value TaskPriority): value.value
define function ToString(value TaskStatus): value.value
define function ToString(value TestReportActionResult): value.value
define function ToString(value TestReportParticipantType): value.value
define function ToString(value TestReportResult): value.value
define function ToString(value TestReportStatus): value.value
define function ToString(value TestScriptRequestMethodCode): value.value
define function ToString(value TriggerType): value.value
define function ToString(value TypeDerivationRule): value.value
define function ToString(value TypeRestfulInteraction): value.value
define function ToString(value UDIEntryType): value.value
define function ToString(value UnitsOfTime): value.value
define function ToString(value Use): value.value
define function ToString(value VariableType): value.value
define function ToString(value VisionBase): value.value
define function ToString(value VisionEyes): value.value
define function ToString(value VisionStatus): value.value
define function ToString(value XPathUsageType): value.value
define function ToString(value base64Binary): value.value
define function ToBoolean(value boolean): value.value
define function ToDate(value date): value.value
define function ToDateTime(value dateTime): value.value
define function ToDecimal(value decimal): value.value
define function ToDateTime(value instant): value.value
define function ToInteger(value integer): value.value
define function ToString(value string): value.value
define function ToTime(value time): value.value
define function ToString(value uri): value.value
define function ToString(value xhtml): value.value

Content not shown - (application/elm+xml, size = 431Kb)

Content not shown - (application/elm+json, size = 785Kb)


Entry 2 - fullUrl = urn:uuid:aa99c584-12e5-46bb-8b30-ab10cfe26471

Request:

PUT Library/FHIRCommon

Resource Library:

Related Artifacts

Depends OnFHIR model informationhttp://fhir.org/guides/cqf/common/Library/FHIR-ModelInfo|4.0.1
Depends OnLibrary FHIRHelpershttp://fhir.org/guides/cqf/Library/FHIRHelpers|4.0.1
Depends OnCode system LOINCLogical Observation Identifiers, Names and Codes (LOINC)
Depends OnCode system SNOMEDCTSNOMED CT (all versions)
Depends OnCode system RoleCodeRoleCode
Depends OnCode system Diagnosis RoleDiagnosis Role
Depends OnCode system RequestIntenthttp://terminology.hl7.org/CodeSystem/request-intent
Depends OnCode system MedicationRequestCategoryMedicationRequest Category Codes
Depends OnCode system ConditionClinicalStatusCodesCondition Clinical Status Codes
Depends OnCode system ConditionVerificationStatusCodesConditionVerificationStatus
Depends OnCode system AllergyIntoleranceClinicalStatusCodesAllergyIntolerance Clinical Status Codes
Depends OnCode system AllergyIntoleranceVerificationStatusCodesAllergyIntolerance Verification Status
Depends OnValue set Active ConditionCQF Active Condition
Depends OnValue set Inactive ConditionCQF Inactive Condition

Parameters

PatientOut01Patient

Data Requirements

Type: Patient (Patient)

Contents

text/cql

/*
@author: Bryn Rhodes
@description: Common terminologies and functions used in FHIR-based CQL artifacts
*/
library FHIRCommon version '4.0.1'

using FHIR version '4.0.1'

include FHIRHelpers version '4.0.1'

codesystem "LOINC": 'http://loinc.org'
codesystem "SNOMEDCT": 'http://snomed.info/sct'
codesystem "RoleCode": 'http://terminology.hl7.org/CodeSystem/v3-RoleCode'
codesystem "Diagnosis Role": 'http://terminology.hl7.org/CodeSystem/diagnosis-role'
codesystem "RequestIntent": 'http://terminology.hl7.org/CodeSystem/request-intent'
codesystem "MedicationRequestCategory": 'http://terminology.hl7.org/CodeSystem/medicationrequest-category'
codesystem "ConditionClinicalStatusCodes": 'http://terminology.hl7.org/CodeSystem/condition-clinical'
codesystem "ConditionVerificationStatusCodes": 'http://terminology.hl7.org/CodeSystem/condition-ver-status'
codesystem "AllergyIntoleranceClinicalStatusCodes": 'http://terminology.hl7.org/CodeSystem/allergyintolerance-clinical'
codesystem "AllergyIntoleranceVerificationStatusCodes": 'http://terminology.hl7.org/CodeSystem/allergyintolerance-verification'

valueset "Active Condition": 'http://fhir.org/guides/cqf/common/ValueSet/active-condition'
valueset "Inactive Condition": 'http://fhir.org/guides/cqf/common/ValueSet/inactive-condition'

code "Birthdate": '21112-8' from "LOINC" display 'Birth date'
code "Dead": '419099009' from "SNOMEDCT" display 'Dead'
code "ER": 'ER' from "RoleCode" display 'Emergency room'
code "ICU": 'ICU' from "RoleCode" display 'Intensive care unit'
code "Billing": 'billing' from "Diagnosis Role" display 'Billing'

// Condition Clinical Status Codes - Consider value sets for these
code "active": 'active' from "ConditionClinicalStatusCodes"
code "recurrence": 'recurrence' from "ConditionClinicalStatusCodes"
code "relapse": 'relapse' from "ConditionClinicalStatusCodes"
code "inactive": 'inactive' from "ConditionClinicalStatusCodes"
code "remission": 'remission' from "ConditionClinicalStatusCodes"
code "resolved": 'resolved' from "ConditionClinicalStatusCodes"

// Condition Verification Status Codes - Consider value sets for these
code "unconfirmed": 'unconfirmed' from ConditionVerificationStatusCodes
code "provisional": 'provisional' from ConditionVerificationStatusCodes
code "differential": 'differential' from ConditionVerificationStatusCodes
code "confirmed": 'confirmed' from ConditionVerificationStatusCodes
code "refuted": 'refuted' from ConditionVerificationStatusCodes
code "entered-in-error": 'entered-in-error' from ConditionVerificationStatusCodes

code "allergy-active": 'active' from "AllergyIntoleranceClinicalStatusCodes"
code "allergy-inactive": 'inactive' from "AllergyIntoleranceClinicalStatusCodes"
code "allergy-resolved": 'resolved' from "AllergyIntoleranceClinicalStatusCodes"

// Allergy/Intolerance Verification Status Codes - Consider value sets for these
code "allergy-unconfirmed": 'unconfirmed' from AllergyIntoleranceVerificationStatusCodes
code "allergy-confirmed": 'confirmed' from AllergyIntoleranceVerificationStatusCodes
code "allergy-refuted": 'refuted' from AllergyIntoleranceVerificationStatusCodes

// MedicationRequest Category Codes
code "Community": 'community' from "MedicationRequestCategory" display 'Community'
code "Discharge": 'discharge' from "MedicationRequestCategory" display 'Discharge'

// Diagnosis Role Codes
code "AD": 'AD' from "Diagnosis Role" display 'Admission diagnosis'
code "DD": 'DD' from "Diagnosis Role" display 'Discharge diagnosis'
code "CC": 'CC' from "Diagnosis Role" display 'Chief complaint'
code "CM": 'CM' from "Diagnosis Role" display 'Comorbidity diagnosis'
code "pre-op": 'pre-op' from "Diagnosis Role" display 'pre-op diagnosis'
code "post-op": 'post-op' from "Diagnosis Role" display 'post-op diagnosis'
code "billing": 'billing' from "Diagnosis Role" display 'billing diagnosis'

context Patient

/*
@description: Normalizes a value that is a choice of timing-valued types to an equivalent interval
@comment: Normalizes a choice type of FHIR.dateTime, FHIR.Period, FHIR.Timing, FHIR.instance, FHIR.string, FHIR.Age, or FHIR.Range types
to an equivalent interval. This selection of choice types is a superset of the majority of choice types that are used as possible
representations for timing-valued elements in FHIR, allowing this function to be used across any resource. NOTE: Due to the
complexity of determining a single interval from a Timing or String type, this function will throw a run-time exception if it is used
with a Timing or String.
*/
define function ToInterval(choice Choice<FHIR.dateTime, FHIR.Period, FHIR.Timing, FHIR.instant, FHIR.string, FHIR.Age, FHIR.Range>):
  case
	  when choice is FHIR.dateTime then
    	Interval[FHIRHelpers.ToDateTime(choice as FHIR.dateTime), FHIRHelpers.ToDateTime(choice as FHIR.dateTime)]
		when choice is FHIR.Period then
  		FHIRHelpers.ToInterval(choice as FHIR.Period)
		when choice is FHIR.instant then
			Interval[FHIRHelpers.ToDateTime(choice as FHIR.instant), FHIRHelpers.ToDateTime(choice as FHIR.instant)]
		when choice is FHIR.Age then
		  Interval[FHIRHelpers.ToDate(Patient.birthDate) + FHIRHelpers.ToQuantity(choice as FHIR.Age),
			  FHIRHelpers.ToDate(Patient.birthDate) + FHIRHelpers.ToQuantity(choice as FHIR.Age) + 1 year)
		when choice is FHIR.Range then
		  Interval[FHIRHelpers.ToDate(Patient.birthDate) + FHIRHelpers.ToQuantity((choice as FHIR.Range).low),
			  FHIRHelpers.ToDate(Patient.birthDate) + FHIRHelpers.ToQuantity((choice as FHIR.Range).high) + 1 year)
		when choice is FHIR.Timing then
		  Message(null as Interval<DateTime>, true, '1', 'Error', 'Cannot compute a single interval from a Timing type')
    when choice is FHIR.string then
      Message(null as Interval<DateTime>, true, '1', 'Error', 'Cannot compute an interval from a String value')
		else
			null as Interval<DateTime>
	end

/*
@description: Returns an interval representing the normalized Abatement of a given Condition resource.
@comment: NOTE: Due to the complexity of determining an interval from a String, this function will throw
a run-time exception if used with a Condition instance that has a String as the abatement value.
*/
define function ToAbatementInterval(condition Condition):
	if condition.abatement is FHIR.dateTime then
	  Interval[FHIRHelpers.ToDateTime(condition.abatement as FHIR.dateTime), FHIRHelpers.ToDateTime(condition.abatement as FHIR.dateTime)]
	else if condition.abatement is FHIR.Period then
	  FHIRHelpers.ToInterval(condition.abatement as FHIR.Period)
	else if condition.abatement is FHIR.string then
    Message(null as Interval<DateTime>, true, '1', 'Error', 'Cannot compute an interval from a String value')
	else if condition.abatement is FHIR.Age then
		Interval[FHIRHelpers.ToDate(Patient.birthDate) + FHIRHelpers.ToQuantity(condition.abatement as FHIR.Age),
			FHIRHelpers.ToDate(Patient.birthDate) + FHIRHelpers.ToQuantity(condition.abatement as FHIR.Age) + 1 year)
	else if condition.abatement is FHIR.Range then
	  Interval[FHIRHelpers.ToDate(Patient.birthDate) + FHIRHelpers.ToQuantity((condition.abatement as FHIR.Range).low),
		  FHIRHelpers.ToDate(Patient.birthDate) + FHIRHelpers.ToQuantity((condition.abatement as FHIR.Range).high) + 1 year)
	else if condition.abatement is FHIR.boolean then
	  Interval[end of ToInterval(condition.onset), condition.recordedDate)
	else null

/*
@description: Returns an interval representing the normalized prevalence period of a given Condition resource.
@comment: Uses the ToInterval and ToAbatementInterval functions to determine the widest potential interval from
onset to abatement as specified in the given Condition.
*/
define function ToPrevalenceInterval(condition Condition):
if condition.clinicalStatus ~ "active"
  or condition.clinicalStatus ~ "recurrence"
  or condition.clinicalStatus ~ "relapse" then
  Interval[start of ToInterval(condition.onset), end of ToAbatementInterval(condition)]
else
  Interval[start of ToInterval(condition.onset), end of ToAbatementInterval(condition))

/*
@description: Returns any extensions defined on the given resource with the specified url.
@comment: NOTE: Extensions are not the preferred approach, but are used as a way to access
content that is defined by extensions but not yet surfaced in the
CQL model info.
*/
define function Extensions(domainResource DomainResource, url String):
  domainResource.extension E
	  where E.url = url
		return E

/*
@description: Returns the single extension (if present) on the given resource with the specified url.
@comment: This function uses singleton from to ensure that a run-time exception is thrown if there
is more than one extension on the given resource with the specified url.
*/
define function Extension(domainResource DomainResource, url String):
  singleton from "Extensions"(domainResource, url)

/*
@description: Returns any extensions defined on the given element with the specified url.
@comment: NOTE: Extensions are not the preferred approach, but are used as a way to access
content that is defined by extensions but not yet surfaced in the CQL model info.
*/
define function Extensions(element Element, url String):
  element.extension E
	  where E.url = url
		return E

/*
@description: Returns the single extension (if present) on the given element with the specified url.
@comment: This function uses singleton from to ensure that a run-time exception is thrown if there
is more than one extension on the given resource with the specified url.
*/
define function Extension(element Element, url String):
  singleton from Extensions(element, url)

/*
@description: Returns any modifier extensions defined on the given resource with the specified url.
@comment: NOTE: Extensions are not the preferred approach, but are used as a way to access
content that is defined by extensions but not yet surfaced in the
CQL model info.
*/
define function ModifierExtensions(domainResource DomainResource, url String):
  domainResource.modifierExtension E
	  where E.url = url
		return E

/*
@description: Returns the single modifier extension (if present) on the given resource with the specified url.
@comment: This function uses singleton from to ensure that a run-time exception is thrown if there
is more than one extension on the given resource with the specified url.
*/
define function ModifierExtension(domainResource DomainResource, url String):
  singleton from ModifierExtensions(domainResource, url)

/*
@description: Returns any modifier extensions defined on the given element with the specified url.
@comment: NOTE: Extensions are not the preferred approach, but are used as a way to access
content that is defined by extensions but not yet surfaced in the CQL model info.
*/
define function ModifierExtensions(element BackboneElement, url String):
  element.modifierExtension E
	  where E.url = url
		return E

/*
@description: Returns the single modifier extension (if present) on the given element with the specified url.
@comment: This function uses singleton from to ensure that a run-time exception is thrown if there
is more than one extension on the given resource with the specified url.
*/
define function ModifierExtension(element BackboneElement, url String):
  singleton from ModifierExtensions(element, url)

/*
@description: Returns any base-FHIR extensions defined on the given resource with the specified id.
@comment: NOTE: Extensions are not the preferred approach, but are used as a way to access
content that is defined by extensions but not yet surfaced in the CQL model info.
*/
define function BaseExtensions(domainResource DomainResource, id String):
  domainResource.extension E
	  where E.url = ('http://hl7.org/fhir/StructureDefinition/' + id)
		return E

/*
@description: Returns the single base-FHIR extension (if present) on the given resource with the specified id.
@comment: This function uses singleton from to ensure that a run-time exception is thrown if there
is more than one extension on the given resource with the specified url.
*/
define function BaseExtension(domainResource DomainResource, id String):
  singleton from BaseExtensions(domainResource, id)

/*
@description: Returns any base-FHIR extensions defined on the given element with the specified id.
@comment: NOTE: Extensions are not the preferred approach, but are used as a way to access
content that is defined by extensions but not yet surfaced in the CQL model info.
*/
define function BaseExtensions(element Element, id String):
  element.extension E
	  where E.url = ('http://hl7.org/fhir/StructureDefinition/' + id)
		return E

/*
@description: Returns the single base-FHIR extension (if present) on the given element with the specified id.
@comment: This function uses singleton from to ensure that a run-time exception is thrown if there
is more than one extension on the given resource with the specified url.
*/
define function BaseExtension(element Element, id String):
  singleton from BaseExtensions(element, id)

/*
@description: Returns any base-FHIR modifier extensions defined on the given resource with the specified id.
@comment: NOTE: Extensions are not the preferred approach, but are used as a way to access
content that is defined by extensions but not yet surfaced in the CQL model info.
*/
define function BaseModifierExtensions(domainResource DomainResource, id String):
  domainResource.modifierExtension E
	  where E.url = ('http://hl7.org/fhir/StructureDefinition/' + id)
		return E

/*
@description: Returns the single base-FHIR modifier extension (if present) on the given resource with the specified id.
@comment: This function uses singleton from to ensure that a run-time exception is thrown if there
is more than one extension on the given resource with the specified url.
*/
define function BaseModifierExtension(domainResource DomainResource, id String):
  singleton from BaseModifierExtensions(domainResource, id)

/*
@description: Returns any base-FHIR modifier extensions defined on the given element with the specified id.
@comment: NOTE: Extensions are not the preferred approach, but are used as a way to access
content that is defined by extensions but not yet surfaced in the CQL model info.
*/
define function BaseModifierExtensions(element BackboneElement, id String):
  element.modifierExtension E
	  where E.url = ('http://hl7.org/fhir/StructureDefinition/' + id)
		return E

/*
@description: Returns the single base-FHIR extension (if present) on the given element with the specified id.
@comment: This function uses singleton from to ensure that a run-time exception is thrown if there
is more than one extension on the given resource with the specified url.
*/
define function BaseModifierExtension(element BackboneElement, id String):
  singleton from BaseModifierExtensions(element, id)

Content not shown - (application/elm+xml, size = 213Kb)

Content not shown - (application/elm+json, size = 406Kb)


Entry 3 - fullUrl = urn:uuid:b3463968-f67d-42ef-8494-cd4ea42e87b9

Request:

PUT Library/MATGlobalCommonFunctionsFHIR4

Resource Library:

Related Artifacts

Depends OnFHIR model informationhttp://fhir.org/guides/cqf/common/Library/FHIR-ModelInfo|4.0.1
Depends OnLibrary FHIRHelpershttp://fhir.org/guides/cqf/Library/FHIRHelpers|4.0.1
Depends OnCode system ConditionClinicalStatusCodesCondition Clinical Status Codes
Depends OnCode system AllergyIntoleranceClinicalStatusCodesAllergyIntolerance Clinical Status Codes
Depends OnCode system AllergyIntoleranceVerificationStatusCodesAllergyIntolerance Verification Status
Depends OnCode system Diagnosis RoleDiagnosis Role
Depends OnCode system LOINCLogical Observation Identifiers, Names and Codes (LOINC)
Depends OnCode system MedicationRequestCategoryMedicationRequest Category Codes
Depends OnCode system ConditionVerificationStatusCodesConditionVerificationStatus
Depends OnCode system SNOMEDCTSNOMED CT (all versions)
Depends OnCode system RoleCodeRoleCode
Depends OnValue set Emergency Department VisitEmergency Department Visit
Depends OnValue set Encounter InpatientEncounter Inpatient
Depends OnValue set Observation ServicesObservation Services

Parameters

Measurement PeriodIn01Period
PatientOut01Patient
Inpatient EncounterOut0*Encounter

Data Requirements

Type: Patient (Patient)
Type: Encounter (Encounter)
FilterValue
typeIn ValueSet Encounter Inpatient
Type: Encounter (Encounter)
FilterValue
typeIn ValueSet Observation Services
Type: Encounter (Encounter)
FilterValue
typeIn ValueSet Emergency Department Visit
Type: Condition (Condition)
Type: Location (Location)
Type: Provenance (Provenance)
FilterValue
targetOne of these codes:

Contents

text/cql

library MATGlobalCommonFunctionsFHIR4 version '6.1.000'

/*@update: BTR 2020-03-31 ->
Incremented version to 5.0.000
Updated FHIR version to 4.0.1
Changed timezone keyword to timezoneoffset for use with CQL 1.4
Removed Normalize Onset in favor of more general Normalize Interval
Updated CodeSystems for ConditionVerificationStatusCodes and RoleCodes

@update: BTR 2021-05-13 ->
Added ActiveCondition Codes and Inactive Condition Codes value sets
Added function documentation throughout
Fixed EDVisit not using Last
Updated prevalence period to use an inclusive boundary if the condition is active
Added HasStart, HasEnd, Earliest, and Latest functions
Removed ToDate and Age calculation functions

@update: BTR 2021-06-25 ->
Added GetBaseExtension overloads for Element*/

using FHIR version '4.0.1'

include FHIRHelpers version '4.0.1' called FHIRHelpers

codesystem "ConditionClinicalStatusCodes": 'http://terminology.hl7.org/CodeSystem/condition-clinical' 
codesystem "AllergyIntoleranceClinicalStatusCodes": 'http://terminology.hl7.org/CodeSystem/allergyintolerance-clinical' 
codesystem "AllergyIntoleranceVerificationStatusCodes": 'http://terminology.hl7.org/CodeSystem/allergyintolerance-verification' 
codesystem "Diagnosis Role": 'http://terminology.hl7.org/CodeSystem/diagnosis-role' 
codesystem "LOINC": 'http://loinc.org' 
codesystem "MedicationRequestCategory": 'http://terminology.hl7.org/CodeSystem/medicationrequest-category' 
codesystem "ConditionVerificationStatusCodes": 'http://terminology.hl7.org/CodeSystem/condition-ver-status' 
codesystem "SNOMEDCT": 'http://snomed.info/sct' 
codesystem "RoleCode": 'http://terminology.hl7.org/CodeSystem/v3-RoleCode' 

valueset "Emergency Department Visit": 'http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.117.1.7.1.292' 
valueset "Encounter Inpatient": 'http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.666.5.307' 
valueset "Observation Services": 'http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1111.143' 

code "active": 'active' from "ConditionClinicalStatusCodes" display 'active'
code "allergy-active": 'active' from "AllergyIntoleranceClinicalStatusCodes" display 'allergy-active'
code "allergy-confirmed": 'confirmed' from "AllergyIntoleranceVerificationStatusCodes" display 'allergy-confirmed'
code "allergy-inactive": 'inactive' from "AllergyIntoleranceClinicalStatusCodes" display 'allergy-inactive'
code "allergy-refuted": 'refuted' from "AllergyIntoleranceVerificationStatusCodes" display 'allergy-refuted'
code "allergy-resolved": 'resolved' from "AllergyIntoleranceClinicalStatusCodes" display 'allergy-resolved'
code "allergy-unconfirmed": 'unconfirmed' from "AllergyIntoleranceVerificationStatusCodes" display 'allergy-unconfirmed'
code "Billing": 'billing' from "Diagnosis Role" display 'Billing'
code "Birthdate": '21112-8' from "LOINC" display 'Birth date'
code "Community": 'community' from "MedicationRequestCategory" display 'Community'
code "confirmed": 'confirmed' from "ConditionVerificationStatusCodes" display 'confirmed'
code "Dead": '419099009' from "SNOMEDCT" display 'Dead'
code "differential": 'differential' from "ConditionVerificationStatusCodes" display 'differential'
code "Discharge": 'discharge' from "MedicationRequestCategory" display 'Discharge'
code "entered-in-error": 'entered-in-error' from "ConditionVerificationStatusCodes" display 'entered-in-error'
code "ER": 'ER' from "RoleCode" display 'Emergency room'
code "ICU": 'ICU' from "RoleCode" display 'Intensive care unit'
code "inactive": 'inactive' from "ConditionClinicalStatusCodes" display 'inactive'
code "provisional": 'provisional' from "ConditionVerificationStatusCodes" display 'provisional'
code "recurrence": 'recurrence' from "ConditionClinicalStatusCodes" display 'recurrence'
code "refuted": 'refuted' from "ConditionVerificationStatusCodes" display 'refuted'
code "relapse": 'relapse' from "ConditionClinicalStatusCodes" display 'relapse'
code "remission": 'remission' from "ConditionClinicalStatusCodes" display 'remission'
code "resolved": 'resolved' from "ConditionClinicalStatusCodes" display 'resolved'
code "unconfirmed": 'unconfirmed' from "ConditionVerificationStatusCodes" display 'unconfirmed'

parameter "Measurement Period" Interval<DateTime>
  default Interval[@2019-01-01T00:00:00.0, @2020-01-01T00:00:00.0)

context Patient

define "Inpatient Encounter":
  [Encounter: "Encounter Inpatient"] EncounterInpatient
      		where EncounterInpatient.status = 'finished'
      		    and "LengthInDays"(EncounterInpatient.period) <= 120
      			and EncounterInpatient.period ends during "Measurement Period"

/*Calculates the difference in calendar days between the start and end of the given interval.*/
define function "LengthInDays"(Value Interval<DateTime> ):
  difference in days between start of Value and end of Value

/*Returns the most recent emergency department visit, if any, that occurs 1 hour or less prior to the given encounter.*/
define function "ED Visit"(TheEncounter FHIR.Encounter ):
  Last(
    [Encounter: "Emergency Department Visit"] EDVisit
      where EDVisit.status = 'finished'
        and EDVisit.period ends 1 hour or less on or before start of FHIRHelpers.ToInterval(TheEncounter.period)
      sort by end of period
    )

/*Hospitalization returns the total interval for admission to discharge for the given encounter, or for the admission of any immediately prior emergency department visit to the discharge of the given encounter.*/
define function "Hospitalization"(TheEncounter FHIR.Encounter ):
  ( "ED Visit"(TheEncounter) ) X
    return
        if X is null then TheEncounter.period
        else Interval[start of FHIRHelpers.ToInterval(X.period), end of FHIRHelpers.ToInterval(TheEncounter.period)]

/*Returns list of all locations within an encounter, including locations for immediately prior ED visit.*/
define function "Hospitalization Locations"(TheEncounter FHIR.Encounter ):
  ( "ED Visit"(TheEncounter) ) EDEncounter
    return
        if EDEncounter is null then TheEncounter.location
        else flatten { EDEncounter.location, TheEncounter.location }

/*Returns the length of stay in days (i.e. the number of days between admission and discharge) for the given encounter, or from the admission of any immediately prior emergency department visit to the discharge of the encounter*/
define function "Hospitalization Length of Stay"(TheEncounter FHIR.Encounter ):
  LengthInDays("Hospitalization"(TheEncounter))

/*Returns admission time for an encounter or for immediately prior emergency department visit.*/
define function "Hospital Admission Time"(TheEncounter FHIR.Encounter ):
  start of "Hospitalization"(TheEncounter)

/*Hospital Discharge Time returns the discharge time for an encounter*/
define function "Hospital Discharge Time"(TheEncounter FHIR.Encounter ):
  end of FHIRHelpers.ToInterval(TheEncounter.period)

/*Returns earliest arrival time for an encounter including any prior ED visit.*/
define function "Hospital Arrival Time"(TheEncounter FHIR.Encounter ):
  start of FHIRHelpers.ToInterval(First(
  	    ( "Hospitalization Locations"(TheEncounter) ) HospitalLocation
  			sort by start of FHIRHelpers.ToInterval(period)
  	).period)
  
  // TODO - fix these (must fetch Location resources and compare id to reference)
  /*Returns the latest departure time for encounter including any prior ED visit. */
  /*
  define function "Hospital Departure Time"(TheEncounter FHIR.Encounter):
  	end of FHIRHelpers.ToInterval(Last(
  	    ( "Hospitalization Locations"(TheEncounter) ) HospitalLocation
  			sort by start of FHIRHelpers.ToInterval(period)
  	).period)
  
  define function "Emergency Department Arrival Time"(TheEncounter FHIR.Encounter):
  	start of FHIRHelpers.ToInterval((
  	    singleton from (
  	        ( "Hospitalization Locations"(TheEncounter) ) HospitalLocation
  				where HospitalLocation.type ~ "ER"
  		)
  	).period)
  
  define function "First Inpatient Intensive Care Unit"(TheEncounter FHIR.Encounter):
  	First(
  	    ( TheEncounter.location ) HospitalLocation
  			where HospitalLocation.type ~ "ICU"
  				and HospitalLocation.period during TheEncounter.period
  			sort by start of FHIRHelpers.ToInterval(period)
  	)
  */
  
  /*Hospitalization with Observation and Outpatient Surgery Service returns the total interval from the start of any immediately prior emergency department visit, outpatient surgery visit or observation visit to the discharge of the given encounter.*/
  /* TODO:
  define function "HospitalizationWithObservationAndOutpatientSurgeryService"(Encounter "Encounter, Performed" ):
  Encounter Visit
  	let ObsVisit: Last(["Encounter, Performed": "Observation Services"] LastObs
  			where LastObs.relevantPeriod ends 1 hour or less on or before start of Visit.relevantPeriod
  			sort by
  			end of relevantPeriod
  	),
  	VisitStart: Coalesce(start of ObsVisit.relevantPeriod, start of Visit.relevantPeriod),
  	EDVisit: Last(["Encounter, Performed": "Emergency Department Visit"] LastED
  			where LastED.relevantPeriod ends 1 hour or less on or before VisitStart
  			sort by
  			end of relevantPeriod
  	),
  	VisitStartWithED: Coalesce(start of EDVisit.relevantPeriod, VisitStart),
  	OutpatientSurgeryVisit: Last(["Encounter, Performed": "Outpatient Surgery Service"] LastSurgeryOP
  			where LastSurgeryOP.relevantPeriod ends 1 hour or less on or before VisitStartWithED
  			sort by
  			end of relevantPeriod
  	)
  	return Interval[Coalesce(start of OutpatientSurgeryVisit.relevantPeriod, VisitStartWithED),
  	end of Visit.relevantPeriod]
  */

/*Hospitalization with Observation returns the total interval from the start of any immediately prior emergency department visit through the observation visit to the discharge of the given encounter*/
define function "HospitalizationWithObservation"(TheEncounter FHIR.Encounter ):
  TheEncounter Visit
  		let ObsVisit: Last([Encounter: "Observation Services"] LastObs
  				where LastObs.period ends 1 hour or less on or before start of Visit.period
  				sort by end of period
  			),
  			VisitStart: Coalesce(start of ObsVisit.period, start of Visit.period),
  			EDVisit: Last([Encounter: "Emergency Department Visit"] LastED
  				where LastED.period ends 1 hour or less on or before VisitStart
  				sort by end of period
  			)
  		return Interval[Coalesce(start of EDVisit.period, VisitStart), end of Visit.period]

/**
* Normalizes the input argument to an interval representation.
* The input can be provided as a dateTime, Period, Timing, instant, string, Age, or Range.
* The intent of this function is to provide a clear and concise mechanism to treat single
* elements that have multiple possible representations as intervals so that logic doesn't have to account
* for the variability. More complex calculations (such as medication request period or dispense period
* calculation) need specific guidance and consideration. That guidance may make use of this function, but
* the focus of this function is on single element calculations where the semantics are unambiguous.
* If the input is a dateTime, the result a DateTime Interval beginning and ending on that dateTime.
* If the input is a Period, the result is a DateTime Interval.
* If the input is a Timing, an error is raised indicating a single interval cannot be computed from a Timing.
* If the input is an instant, the result is a DateTime Interval beginning and ending on that instant.
* If the input is a string, an error is raised indicating a single interval cannot be computed from a string.
* If the input is an Age, the result is a DateTime Interval beginning when the patient was the given Age,
and ending immediately prior to when the patient was the given Age plus one year.
* If the input is a Range, the result is a DateTime Interval beginning when the patient was the Age given
by the low end of the Range, and ending immediately prior to when the patient was the Age given by the
high end of the Range plus one year.*/
define function "Normalize Interval"(choice Choice<FHIR.dateTime, FHIR.Period, FHIR.Timing, FHIR.instant, FHIR.string, FHIR.Age, FHIR.Range> ):
  case
  	  when choice is FHIR.dateTime then
  	Interval[FHIRHelpers.ToDateTime(choice as FHIR.dateTime), FHIRHelpers.ToDateTime(choice as FHIR.dateTime)]
  		when choice is FHIR.Period then
  		FHIRHelpers.ToInterval(choice as FHIR.Period)
  		when choice is FHIR.instant then
  			Interval[FHIRHelpers.ToDateTime(choice as FHIR.instant), FHIRHelpers.ToDateTime(choice as FHIR.instant)]
  		when choice is FHIR.Age then
  		  Interval[FHIRHelpers.ToDate(Patient.birthDate) + FHIRHelpers.ToQuantity(choice as FHIR.Age),
  			  FHIRHelpers.ToDate(Patient.birthDate) + FHIRHelpers.ToQuantity(choice as FHIR.Age) + 1 year)
  		when choice is FHIR.Range then
  		  Interval[FHIRHelpers.ToDate(Patient.birthDate) + FHIRHelpers.ToQuantity((choice as FHIR.Range).low),
  			  FHIRHelpers.ToDate(Patient.birthDate) + FHIRHelpers.ToQuantity((choice as FHIR.Range).high) + 1 year)
  		when choice is FHIR.Timing then
  		  Message(null as Interval<DateTime>, true, '1', 'Error', 'Cannot compute a single interval from a Timing type')
    when choice is FHIR.string then
      Message(null as Interval<DateTime>, true, '1', 'Error', 'Cannot compute an interval from a String value')
  		else
  			null as Interval<DateTime>
  	end

/**
* Returns an interval representing the abatement of the given condition, if an
abatement element is present, null otherwise.
This function uses the semantics of Normalize Interval to interpret the abatement
element.*/
define function "Normalize Abatement"(condition Condition ):
  if condition.abatement is FHIR.dateTime then
  	  Interval[FHIRHelpers.ToDateTime(condition.abatement as FHIR.dateTime), FHIRHelpers.ToDateTime(condition.abatement as FHIR.dateTime)]
  	else if condition.abatement is FHIR.Period then
  	  FHIRHelpers.ToInterval(condition.abatement as FHIR.Period)
  	else if condition.abatement is FHIR.string then
  Message(null as Interval<DateTime>, true, '1', 'Error', 'Cannot compute an interval from a String value')
  	else if condition.abatement is FHIR.Age then
  		Interval[FHIRHelpers.ToDate(Patient.birthDate) + FHIRHelpers.ToQuantity(condition.abatement as FHIR.Age),
  			FHIRHelpers.ToDate(Patient.birthDate) + FHIRHelpers.ToQuantity(condition.abatement as FHIR.Age) + 1 year)
  	else if condition.abatement is FHIR.Range then
  	  Interval[FHIRHelpers.ToDate(Patient.birthDate) + FHIRHelpers.ToQuantity((condition.abatement as FHIR.Range).low),
  		  FHIRHelpers.ToDate(Patient.birthDate) + FHIRHelpers.ToQuantity((condition.abatement as FHIR.Range).high) + 1 year)
  	else if condition.abatement is FHIR.boolean then
  	  Interval[end of "Normalize Interval"(condition.onset), condition.recordedDate)
  	else null

/*Returns an interval representing the period during which the condition was prevalent (i.e. onset to abatement)
If the condition is "active", then abatement being unknown
would indicate the condition is ongoing, and the ending boundary of the prevalence
period is inclusive, otherwise, the abatement is considered unknown and the ending boundary
of the prevalence period is exclusive.
Note that when using this function it should be noted that many clinical systems
do not actually capture abatement, so care should be taken when using this function
to meet clinical intent.*/
define function "Prevalence Period"(condition Condition ):
  if condition.clinicalStatus ~ "active"
    or condition.clinicalStatus ~ "recurrence"
    or condition.clinicalStatus ~ "relapse" then
    Interval[start of "Normalize Interval"(condition.onset), end of "Normalize Abatement"(condition)]
  else
    Interval[start of "Normalize Interval"(condition.onset), end of "Normalize Abatement"(condition))

/*Returns the tail of the given uri (i.e. everything after the last slash in the URI).*/
define function "GetId"(uri String ):
  Last(Split(uri, '/'))

/*Returns the Condition resources referenced by the diagnosis element of the Encounter*/
define function "EncounterDiagnosis"(Encounter Encounter ):
  Encounter.diagnosis D
    return singleton from ([Condition] C where C.id = "GetId"(D.condition.reference))
  
  // Returns the condition that is specified as the principal diagnosis for the encounter
  // TODO: BTR 2019-07-30: Shouldn't need the FHIRHelpers reference here, investigate

define function "PrincipalDiagnosis"(Encounter Encounter ):
  (singleton from (Encounter.diagnosis D where FHIRHelpers.ToInteger(D.rank) = 1)) PD
  		return singleton from ([Condition] C where C.id = "GetId"(PD.condition.reference))
  // Returns the location for the given location reference

/*Returns the Location resource specified by the given reference*/
define function "GetLocation"(reference Reference ):
  singleton from (
    [Location] L where L.id = GetId(reference.reference)
  )

/*NOTE: Extensions are not the preferred approach, but are used as a way to access
content that is defined by extensions but not yet surfaced in the
CQL model info.*/
define function "GetExtensions"(domainResource DomainResource, url String ):
  domainResource.extension E
  	  where E.url = ('http://hl7.org/fhir/us/qicore/StructureDefinition/' + url)
  		return E

define function "GetExtension"(domainResource DomainResource, url String ):
  singleton from "GetExtensions"(domainResource, url)

/*NOTE: Extensions are not the preferred approach, but are used as a way to access
content that is defined by extensions but not yet surfaced in the
CQL model info.*/
define function "GetExtensions"(element Element, url String ):
  element.extension E
  	  where E.url = (url)
  		return E

define function "GetExtension"(element Element, url String ):
  singleton from "GetExtensions"(element, url)

/*NOTE: Extensions are not the preferred approach, but are used as a way to access
content that is defined by extensions but not yet surfaced in the
CQL model info.*/
define function "GetBaseExtensions"(domainResource DomainResource, url String ):
  domainResource.extension E
  	  where E.url = ('http://hl7.org/fhir/StructureDefinition/' + url)
  		return E

define function "GetBaseExtension"(domainResource DomainResource, url String ):
  singleton from "GetBaseExtensions"(domainResource, url)

/*@description: Returns any base-FHIR extensions defined on the given element with the specified id.
@comment: NOTE: Extensions are not the preferred approach, but are used as a way to access
content that is defined by extensions but not yet surfaced in the CQL model info.*/
define function "BaseExtensions"(element Element, id String ):
  element.extension E
  	  where E.url = ('http://hl7.org/fhir/StructureDefinition/' + id)
  		return E

/*@description: Returns the single base-FHIR extension (if present) on the given element with the specified id.
@comment: This function uses singleton from to ensure that a run-time exception is thrown if there
is more than one extension on the given resource with the specified url.*/
define function "BaseExtension"(element Element, id String ):
  singleton from BaseExtensions(element, id)

/*NOTE: Provenance is not the preferred approach, this is provided only as an illustration
for what using Provenance could look like, and is not a tested pattern*/
define function "GetProvenance"(resource Resource ):
  singleton from ([Provenance: target in resource.id])

define function "GetMedicationCode"(request MedicationRequest ):
  if request.medication is CodeableConcept then
  	  request.medication as CodeableConcept
  	else
  	  (singleton from ([Medication] M where M.id = GetId((request.medication as Reference).reference))).code

/*Given an interval, return true if the interval has a starting boundary specified (i.e. the start of the interval is not null and not the minimum DateTime value)*/
define function "HasStart"(period Interval<DateTime> ):
  not ( start of period is null
      or start of period = minimum DateTime
  )

/*Given an interval, return true if the interval has an ending boundary specified (i.e. the end of the interval is not null and not the maximum DateTime value)*/
define function "HasEnd"(period Interval<DateTime> ):
  not (
    end of period is null
      or
      end of period = maximum DateTime
  )

/*Given an interval, return the ending point if the interval has an ending boundary specified, otherwise, return the starting point*/
define function "Latest"(choice Choice<FHIR.dateTime, FHIR.Period, FHIR.Timing, FHIR.instant, FHIR.string, FHIR.Age, FHIR.Range> ):
  ("Normalize Interval"(choice)) period
    return
      if ( HasEnd(period)) then end of period
      else start of period

/*Given an interval, return the starting point if the interval has a starting boundary specified, otherwise, return the ending point*/
define function "Earliest"(choice Choice<FHIR.dateTime, FHIR.Period, FHIR.Timing, FHIR.instant, FHIR.string, FHIR.Age, FHIR.Range> ):
  ("Normalize Interval"(choice)) period
    return
      if (HasStart(period)) then start of period
      else end of period

Content not shown - (application/elm+xml, size = 302Kb)

Content not shown - (application/elm+json, size = 572Kb)


Entry 4 - fullUrl = urn:uuid:c6098378-cb38-4ae2-a096-3a3cc5c620d5

Request:

PUT Library/SupplementalDataElementsFHIR4

Resource Library:

Related Artifacts

Depends OnFHIR model informationhttp://fhir.org/guides/cqf/common/Library/FHIR-ModelInfo|4.0.1
Depends OnLibrary FHIRHelpershttp://fhir.org/guides/cqf/Library/FHIRHelpers|4.0.1
Depends OnValue set EthnicityEthnicity
Depends OnValue set ONC Administrative SexONC Administrative Sex
Depends OnValue set PayerPayer
Depends OnValue set RaceRace

Parameters

PatientOut01Patient
SDE EthnicityOut0*Coding
SDE PayerOut0*Resource
SDE RaceOut0*Coding
SDE SexOut01Coding

Data Requirements

Type: Patient (Patient)
Type: Coverage (Coverage)
FilterValue
typeIn ValueSet Payer

Contents

text/cql

library SupplementalDataElementsFHIR4 version '2.0.000'

/*@update: @@BTR 2020-03-31 ->
Incremented version to 2.0.0
Updated FHIR version to 4.0.1
@@@*/

using FHIR version '4.0.1'

include FHIRHelpers version '4.0.1' called FHIRHelpers

valueset "Ethnicity": 'http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.114222.4.11.837' 
valueset "ONC Administrative Sex": 'http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1' 
valueset "Payer": 'http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.114222.4.11.3591' 
valueset "Race": 'http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.114222.4.11.836' 

context Patient

define "SDE Ethnicity":
  (flatten (
      Patient.extension Extension
        where Extension.url = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-ethnicity'
          return Extension.extension
    )) E
      where E.url = 'ombCategory'
        or E.url = 'detailed'
      return E.value as Coding

define "SDE Payer":
  [Coverage: type in "Payer"] Payer
        return {
          code: Payer.type,
          period: Payer.period
        }

define "SDE Race":
  (flatten (
      Patient.extension Extension
        where Extension.url = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-race'
          return Extension.extension
    )) E
      where E.url = 'ombCategory'
        or E.url = 'detailed'
      return E.value as Coding

define "SDE Sex":
  case
      when Patient.gender = 'male' then Code { code: 'M', system: 'http://hl7.org/fhir/v3/AdministrativeGender', display: 'Male' }
      when Patient.gender = 'female' then Code { code: 'F', system: 'http://hl7.org/fhir/v3/AdministrativeGender', display: 'Female' }
      else null
    end

Content not shown - (application/elm+xml, size = 31Kb)

Content not shown - (application/elm+json, size = 56Kb)


Entry 5 - fullUrl = urn:uuid:e3b78b9e-96ee-43fb-aeea-22a7681a1538

Request:

PUT Library/NHSNGlycemicControlHypoglycemicInitialPopulation

Resource Library:

Related Artifacts

Depends OnFHIR model informationhttp://fhir.org/guides/cqf/common/Library/FHIR-ModelInfo|4.0.1
Depends OnLibrary FHIRHelpershttp://fhir.org/guides/cqf/Library/FHIRHelpers|4.0.1
Depends OnLibrary SDESupplementalDataElementsFHIR4 (version 2.0.000)
Depends OnLibrary GlobalMAT Global Common Functions FHIRR4 (version 6.1.000)
Depends OnCode system ActCodeActCode
Depends OnCode system Diagnosis RoleDiagnosis Role
Depends OnCode system Specimen TypespecimenType
Depends OnCode system Observation CategoryObservation Category Codes
Depends OnCode system Condition CategoryCondition Category Codes
Depends OnValue set Blood Glucose Laboratory and Point of Care TestsBlood Glucose Laboratory and Point of Care Tests
Depends OnValue set Inpatient, Emergency, and Observation Locationshttp://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1046.265
Depends OnValue set Discharge DispositionDischarge disposition
Depends OnValue set Antidiabetic MedicationsAntidiabetic Medications
Depends OnValue set Emergency Department VisitEmergency Department Visit
Depends OnValue set Encounter InpatientEncounter Inpatient
Depends OnValue set Observation ServicesObservation Services
Depends OnValue set PayerPayer

Parameters

Measurement PeriodIn01Period
PatientOut01Patient
Inpatient EncounterOut0*Encounter
Patient Hospital LocationsOut0*Encounter
Antidiabetic Drugs Administered or OrderedOut0*Resource
Initial PopulationOut0*Encounter
SDE Chief ComplaintOut0*Encounter
SDE ConditionOut0*Condition
SDE Condition during EncounterOut0*Condition
SDE Encounter Discharge DispositionsOut0*Encounter
SDE Encounter LocationsOut0*Encounter
SDE Medication AdministrationOut0*MedicationAdministration
SDE Medication RequestOut0*MedicationRequest
SDE Blood Glucose ObservationOut0*Observation
SDE PayerOut0*Resource
SDE SpecimenOut0*Specimen
SDE Minimal PatientOut01Patient
SDE Minimal Medication RequestsOut0*MedicationRequest

Data Requirements

Type: Patient (Patient)
Type: Encounter (Encounter)
FilterValue
classOne of these codes: ActCode IMP: inpatient encounter, ActCode ACUTE: inpatient acute, ActCode NONAC: inpatient non-acute, ActCode SS: short stay
Type: Encounter (Encounter)
FilterValue
typeIn ValueSet Encounter Inpatient
Type: Encounter (Encounter)
Type: Encounter (Encounter)
FilterValue
typeIn ValueSet Observation Services
Type: Encounter (Encounter)
FilterValue
typeIn ValueSet Emergency Department Visit
Type: Location (Location)
Type: Medication (Medication)
Type: MedicationAdministration (MedicationAdministration)
Type: MedicationRequest (MedicationRequest)
Type: Specimen (Specimen)
Type: Condition (Condition)
Type: Observation (Observation)
FilterValue
codeIn ValueSet Blood Glucose Laboratory and Point of Care Tests
Type: Coverage (Coverage)
FilterValue
typeIn ValueSet Payer

Contents

text/cql

library NHSNGlycemicControlHypoglycemicInitialPopulation version '0.0.002'

using FHIR version '4.0.1'

include FHIRHelpers version '4.0.1' called FHIRHelpers
include SupplementalDataElementsFHIR4 version '2.0.000' called SDE
include MATGlobalCommonFunctionsFHIR4 version '6.1.000' called Global

codesystem "ActCode": 'http://terminology.hl7.org/CodeSystem/v3-ActCode' 
codesystem "Diagnosis Role": 'http://terminology.hl7.org/CodeSystem/diagnosis-role'
codesystem "Specimen Type": 'http://terminology.hl7.org/CodeSystem/v2-0487'
codesystem "Observation Category": 'http://terminology.hl7.org/CodeSystem/observation-category'
codesystem "Condition Category": 'http://terminology.hl7.org/CodeSystem/condition-category' 

valueset "Blood Glucose Laboratory and Point of Care Tests": 'http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1190.38'
valueset "Inpatient, Emergency, and Observation Locations": 'http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1046.265'
valueset "Discharge Disposition": 'http://terminology.hl7.org/ValueSet/encounter-discharge-disposition'
valueset "Antidiabetic Medications": 'http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1190.58'
valueset "Emergency Department Visit": 'http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.117.1.7.1.292'
valueset "Encounter Inpatient": 'http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.666.5.307'
valueset "Observation Services": 'http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1111.143'

code "Chief Complaint": 'CC' from "Diagnosis Role" display 'Chief complaint'
code "emergency": 'EMER' from "ActCode" display 'emergency'
code "inpatient acute": 'ACUTE' from "ActCode" display 'inpatient acute'
code "inpatient encounter": 'IMP' from "ActCode" display 'inpatient encounter'
code "inpatient non-acute": 'NONAC' from "ActCode" display 'inpatient non-acute'
code "observation encounter": 'OBSENC' from "ActCode" display 'observation encounter'
code "short stay": 'SS' from "ActCode" display 'short stay'
code "laboratory": 'laboratory' from "Observation Category" display 'Laboratory'
code "encounter-diagnosis": 'encounter-diagnosis' from "Condition Category" display'encounter-diagnosis'

parameter "Measurement Period" Interval<DateTime>
 default Interval[@2022-01-01T00:00:00.0, @2022-01-31T00:00:00.0)

context Patient

define "Initial Population":
  ("Inpatient Encounter"
  union "Patient Hospital Locations") InpatientEncounters
  with "Antidiabetic Drugs Administered or Ordered" ADD
  such that Coalesce(start of Global."Normalize Interval"(ADD.effective), ADD.authoredOn)
      during "HospitalizationWithObservationOrEmergency"(InpatientEncounters)
    and Coalesce(start of Global."Normalize Interval"(ADD.effective), ADD.authoredOn) during "Measurement Period"

define "Inpatient Encounter":
  [Encounter: class in {"inpatient encounter", "inpatient acute", "inpatient non-acute", "short stay"}]
    union [Encounter: "Encounter Inpatient"] Encounters
  where Encounters.status in {'in-progress', 'finished'}
    and Encounters.period overlaps "Measurement Period"

define "Patient Hospital Locations":
  [Encounter] Encounters
  where exists(
    Encounters.location EncounterLocation
    where Global.GetLocation(EncounterLocation.location).type in "Inpatient, Emergency, and Observation Locations"
      and EncounterLocation.period during Encounters.period
  )

define "Antidiabetic Drugs Administered or Ordered":
  ([MedicationAdministration] ADDMedAdmin
    where GetMedicationCode(ADDMedAdmin.medication) in "Antidiabetic Medications"
      and ADDMedAdmin.status ~ 'completed')
  union (
    [MedicationRequest] MedicationRequests
      where GetMedicationCode(MedicationRequests.medication) in "Antidiabetic Medications"
  )

define function "GetMedicationCode"(choice Choice<FHIR.CodeableConcept, FHIR.Reference>):
  case
    when choice is FHIR.CodeableConcept then
      choice as FHIR.CodeableConcept
    when choice is FHIR.Reference then
      GetMedication(choice as FHIR.Reference).code
    else
      null as FHIR.CodeableConcept
  end

define function "GetMedication"(reference Reference ):
  singleton from (
    [Medication] M where M.id = Global.GetId(reference.reference)
  )

define function "HospitalizationWithObservationOrEmergency"(TheEncounter FHIR.Encounter ):
  TheEncounter Visit
    let ObsVisit: Last([Encounter: "Observation Services"] LastObs
        where LastObs.class ~ "observation encounter"
          and LastObs.period ends 1 hour or less on or before start of Visit.period
  				sort by end of period
    ),
    VisitStart: Coalesce(start of ObsVisit.period, start of Visit.period),
    EDVisit: Last([Encounter: "Emergency Department Visit"] LastED
        where LastED.class ~ "emergency"
          and LastED.period ends 1 hour or less on or before start of Visit.period
  				sort by end of period
    )
    return Interval[Coalesce(start of EDVisit.period, VisitStart), end of Visit.period]

define function "GetSpecimen"(reference Reference):
  singleton from (
    [Specimen] S where S.id = Global.GetId(reference.reference)
  )

define function "GetPatientExtensions"(domainResource DomainResource):
  domainResource.extension E
    where E.url = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-race'
      or E.url = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-ethnicity'
      or E.url = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-birthsex'
      or E.url = 'https://hl7.org/fhir/us/core/StructureDefinition-us-core-genderIdentity'
    return E

define function "GetPatientAddress"(addresses List<FHIR.Address>):
  addresses address
  return FHIR.Address{
    postalCode: address.postalCode
  }

define function "MedicationRequestResource"(medicationRequest MedicationRequest):
  medicationRequest m
  return MedicationRequest{
    id: FHIR.id {value: 'new-' + m.id},
    medication: GetMedicationCode(m.medication),
    dosageInstruction: m.dosageInstruction
  }
  
//Supplement Data Elements
define "SDE Chief Complaint":
  "Initial Population" IP
  with IP.diagnosis InitialPopulationDiagnosis
  such that InitialPopulationDiagnosis.use ~ "Chief Complaint"

define "SDE Condition":
  [Condition] Conditions
  with "Initial Population" InitialPopulation
  such that Global."Normalize Interval"(Conditions.onset) overlaps InitialPopulation.period
  
define "SDE Condition during Encounter":
  [Condition] ConditionEncounterDiagnosis
  with ConditionEncounterDiagnosis.category Category
  such that Category ~ "encounter-diagnosis"
    and exists("Initial Population")
    
define "SDE Encounter Discharge Dispositions":
	"Initial Population" DischargeDispositions 
  where DischargeDispositions.hospitalization.dischargeDisposition in "Discharge Disposition"
  
define "SDE Encounter Locations":
  "Initial Population" InitialPopulation 
  where exists ( 
    InitialPopulation.location InitialPopulationLocation
    where (Global.GetLocation(InitialPopulationLocation.location).type in "Inpatient, Emergency, and Observation Locations"   
      and InitialPopulationLocation.period during InitialPopulation.period)
  )

define "SDE Medication Administration":
	[MedicationAdministration] MedicationAdministrations
  with "Initial Population" InitialPopulation
  such that start of Global."Normalize Interval"(MedicationAdministrations.effective) during "HospitalizationWithObservationOrEmergency"(InitialPopulation)
    and start of Global."Normalize Interval"(MedicationAdministrations.effective) during "Measurement Period"

define "SDE Medication Request":
	[MedicationRequest] MedicationRequests
  with "Initial Population" InitialPopulation
	such that MedicationRequests.authoredOn during "HospitalizationWithObservationOrEmergency"(InitialPopulation)
    and MedicationRequests.authoredOn during "Measurement Period"

define "SDE Blood Glucose Observation":
	[Observation: "Blood Glucose Laboratory and Point of Care Tests"] Observations 
  with "Initial Population" InitialPopulation
  such that start of Global."Normalize Interval"(Observations.effective) during InitialPopulation.period
    or Global."Normalize Interval"(GetSpecimen(Observations.specimen).collection.collected) during InitialPopulation.period
  with Observations.category category
  such that category ~ "laboratory"

define "SDE Payer": 
	SDE."SDE Payer" Payer
  with "Initial Population" InitialPopulation
  such that start of Payer.period before end of InitialPopulation.period
  
define "SDE Specimen":
  [Specimen] Specimen
  with "Initial Population" InitialPopulation
  such that Global."Normalize Interval"(Specimen.collection.collected) during InitialPopulation.period

//Change on CQF ruler happened on 8/12. Check to make sure CQF-Ruler version is dated at or after (version 2.0.0). 
//Wait 2-3 days before the changes are actually applied to the CQF-Ruler.
define "SDE Minimal Patient":
  Patient{
    id: Patient.id,
    extension: GetPatientExtensions(Patient),
    identifier: Patient.identifier,
    gender: Patient.gender,
    birthDate: Patient.birthDate,
    deceased: Patient.deceased,
    address: GetPatientAddress(Patient.address)
  }
  
define "SDE Minimal Medication Requests":
  [MedicationRequest] MedicationRequests
  return MedicationRequestResource(MedicationRequests)

/*define "SDE Resource Construction Test Inlib":
  FHIR.Observation 
  {
    id: FHIR.id { value: 'observation-sdetestinlib-' + ToString(Now()) },
    status: FHIR.ObservationStatus { value: 'final' },
    code: FHIR.CodeableConcept { coding: { FHIR.Coding { code: FHIR.code { value: 'days-since-appointment' } } } },
    subject: FHIR.Reference { reference: FHIR.string { value: Patient.id.value }}
    //value: FHIR.integer { value: Abs(difference in days between end of SDE."Last Appointment".period and ToDateTime(Today())) }
  }*/

  define "SDE Ethnicity Coding":
    SDE."SDE Ethnicity"

  define "SDE Race Coding":
    SDE."SDE Race"


Entry 6 - fullUrl = urn:uuid:61d3ae55-c7b7-484f-96df-4f3ef8c080c0

Request:

PUT Measure/NHSNGlycemicControlHypoglycemicInitialPopulation

Resource Measure:

Generated Narrative: Measure

Resource Measure "NHSNGlycemicControlHypoglycemicInitialPopulation"

CQFM Effective Data Requirements:

Related Artifacts

depends-onLibrary FHIRHelpershttp://fhir.org/guides/cqf/Library/FHIRHelpers|4.0.1
depends-onLibrary GlobalMAT Global Common Functions FHIRR4 (version 6.1.000)
depends-onLibrary SDESupplementalDataElementsFHIR4 (version 2.0.000)
depends-onCode system ActCodeActCode
depends-onCode system Condition CategoryCondition Category Codes
depends-onCode system Observation CategoryObservation Category Codes
depends-onCode system Diagnosis RoleDiagnosis Role
depends-onValue set Antidiabetic MedicationsAntidiabetic Medications
depends-onValue set Inpatient, Emergency, and Observation Locationshttp://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1046.265
depends-onValue set Blood Glucose Laboratory and Point of Care TestsBlood Glucose Laboratory and Point of Care Tests
depends-onValue set PayerPayer
depends-onValue set Discharge DispositionDischarge disposition

Parameters

Measurement Periodin01Period
SDE Medication Requestout0*MedicationRequest
SDE Encounter Locationsout0*Encounter
SDE Minimal Medication Requestsout0*MedicationRequest
SDE Condition during Encounterout0*Condition
SDE Medication Administrationout0*MedicationAdministration
SDE Blood Glucose Observationout0*Observation
SDE Conditionout0*Condition
SDE Payerout0*Resource
Initial Populationout0*Encounter
SDE Encounter Discharge Dispositionsout0*Encounter
SDE Minimal Patientout01Patient
SDE Specimenout0*Specimen
SDE Chief Complaintout0*Encounter

Data Requirements

Type: Encounter (Encounter)
FilterValue
classOne of these codes: ActCode IMP: inpatient encounter, ActCode ACUTE: inpatient acute, ActCode NONAC: inpatient non-acute, ActCode SS: short stay
Type: Encounter (Encounter)
Type: Encounter (Encounter)
FilterValue
classOne of these codes: ActCode IMP: inpatient encounter, ActCode ACUTE: inpatient acute, ActCode NONAC: inpatient non-acute, ActCode SS: short stay
Type: Medication (Medication)
Type: MedicationAdministration (MedicationAdministration)
Type: MedicationRequest (MedicationRequest)
Type: Location (Location)
Type: Condition (Condition)
Type: Specimen (Specimen)
Type: Observation (Observation)
FilterValue
codeIn ValueSet Blood Glucose Laboratory and Point of Care Tests
Type: Coverage (Coverage)
FilterValue
typeIn ValueSet Payer
Type: Patient (Patient)

Contents

url: http://nhsnlink.org/fhir/Measure/NHSNGlycemicControlHypoglycemicInitialPopulation

identifier: id: nhsnglycemiccontrolhypoglycemicinitialpopulation

version: 0.000.01

name: NHSNGlycemicControlHypoglycemicInitialPopulation

title: NHSN Glycemic Control, Hypoglycemia Initial Population

status: DRAFT

experimental: true

date: 2022-08-29 12:53:08-0800

publisher: NHSN

description: All inpatient encounters (including ED/Observation visits that end within 1 hour of the start of the inpatient encounter) for patients of all ages where at least one ADD was ordered or administered during the encounter that is during the measurement period.

purpose: The primary purpose of this site is to provide CDC’s NHSN with access to view measure specification content in the dQMs under development by Lantana Consulting Group. Please note, this site is draft and undergoes constant revision and is not intended to serve as an implementation guide.

copyright: This measure and specifications are subject to further revisions. This performance measure is not a clinical guideline, does not establish a standard of medical care and has not been tested for all potential applications. THE MEASURES AND SPECIFICATIONS ARE PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND.

library: NHSN Glycemic Control Hypoglycemic Initial Population

scoring: Cohort (MeasureScoring#cohort)

type: Outcome (MeasureType#outcome)

rationale: The NHSN Glycemic Control, Hypoglycemia module provides a mechanism for facilities to report inpatient medication-related hypoglycemia events, and to provide analytic reports based on these data to inform glycemic control quality improvement efforts and patient safety events. The primary objective of the NHSN Glycemic Control, Hypoglycemia module is to facilitate measurement and benchmarking of medication-related hypoglycemia events within a facility. As additional data are collected by NHSN, an additional objective will be to facilitate inter-facility benchmarking and evaluate national-level trends of medication-related hypoglycemia over time. The IP dQM provides the initial population and FHIR line-level data necessary for calculating the module metrics.

group

population

id

initial-population-01

code: Initial Population (MeasurePopulationType#initial-population)

description: All inpatient encounters, as well as ED and OBS encounters that end within 1 hour of the start of the inpatient encounter, for patients of all ages where at least one antidiabetic drug (ADD) was ordered or administered during the encounter that is during the measurement period.

Criteria

-LanguageExpression
*text/cql.identifierInitial Population

supplementalData

id

sde-chief-complaint

Criteria

-LanguageExpression
*text/cql.identifierSDE Chief Complaint

supplementalData

id

sde-condition

Criteria

-LanguageExpression
*text/cql.identifierSDE Condition

supplementalData

id

sde-condition-during-encounter

Criteria

-LanguageExpression
*text/cql.identifierSDE Condition during Encounter

supplementalData

id

sde-encounter-discharge-dispositions

Criteria

-LanguageExpression
*text/cql.identifierSDE Encounter Discharge Dispositions

supplementalData

id

sde-encounter-locations

Criteria

-LanguageExpression
*text/cql.identifierSDE Encounter Locations

supplementalData

id

sde-medication-administration

Criteria

-LanguageExpression
*text/cql.identifierSDE Medication Administration

supplementalData

id

sde-medication-request

Criteria

-LanguageExpression
*text/cql.identifierSDE Medication Request

supplementalData

id

sde-blood-glucose-observation

Criteria

-LanguageExpression
*text/cql.identifierSDE Blood Glucose Observation

supplementalData

id

sde-payer

Criteria

-LanguageExpression
*text/cql.identifierSDE Payer

supplementalData

id

sde-specimen

Criteria

-LanguageExpression
*text/cql.identifierSDE Specimen

supplementalData

id

sde-minimal-patient

Criteria

-LanguageExpression
*text/cql.identifierSDE Minimal Patient

supplementalData

id

sde-minimal-medication-requests

Criteria

-LanguageExpression
*text/cql.identifierSDE Minimal Medication Requests

supplementalData

id

sde-ethnicity-coding

Criteria

-LanguageExpression
*text/cql.identifierSDE Ethnicity Coding

supplementalData

id

sde-race-coding

Criteria

-LanguageExpression
*text/cql.identifierSDE Race Coding