Knowledge Artifact Metadata
Name (machine-readable) | CMS871HHHyperFHIR
Title (human-readable) | Hospital Harm - Severe HyperglycemiaFHIR
Status | draft
Experimental | false
Description | This measure assesses the number of inpatient hospital days for patients age 18 and older with a hyperglycemic event (harm) per the total qualifying inpatient hospital days for that encounter
Clinical Usage | The measure is using mg/dL as the unit of measurement for glucose results. Millimoles per liter (mmol/L) should be converted to milligrams per deciliter (mg/dL) for reporting this measure. When evaluating for days with a glucose level >300 mg/dL, the first 24-hour period after admission to the hospital is not evaluated to account for potentially poor glucose control outside of the hospital setting or that preceded the start of hospital care. The admission starts in the ED or observation when the transition between the ED encounter, observation encounter, and the inpatient encounter are within an hour or less of each other. This measure evaluates the first 10 days of an eligible inpatient hospitalization in determining eligible days for the denominator and numerator (i.e., the length of stay is truncated to <=10 days when the length exceeds 10 days). Patients admitted for longer length of stays are more likely to have more complex medical conditions. In determining eligible days for the denominator and numerator, this measure does not evaluate the last day if it was less than a 24-hour period. The “Days in Hospitalization” logic within Measure Observation 1 (associated with the denominator), in conjunction with other logic, returns the day number (e.g., day 1 to day 10) for each day within the hospitalization period to determine the eligible hospital days (e.g., from day 2 to day 10). The “Days in Hospitalization” logic within Measure Observation 2 (associated with the numerator), in conjunction with other logic, returns the day number (e.g., day 1 to day 10) for each day within the hospitalization period to determine the eligible hyperglycemic event days (e.g., from day 2 to day 10). Since the measure does not count any hyperglycemic events that occur in the first 24 hours, day 1 is not considered an eligible hospital day for the Measure Observations. Eligible days range from day 2 up to day 10. However, the measure does allow day 1 to be counted for the Numerator as one of the preceding days for a day where no glucose result is found. In this instance, the measure could evaluate day 1 as one of the two days preceding the day with no glucose result to see if there was a glucose value >=200 mg/dL on day 1. Multiple hyperglycemic events can occur during a ‘day,’ but this is still considered one hyperglycemic event day. The numerator returns the first eligible encounter that meets the qualifying criteria: an inpatient hospitalization with a hyperglycemic event. Only one numerator is counted per encounter. Note that the Numerator returns the encounters, not days, that meet the criteria. This measure includes two measure observations used to calculate the ratio of the number of inpatient hospital days with a hyperglycemic (high blood glucose) event over the total number of eligible inpatient hospital days (<= 10 days) for that encounter. In ratio measures, both the denominator and numerator populations flow separately from the same initial population. Therefore, the same exclusion criteria must be applied to both the denominator and numerator to prevent excluded cases from being considered. The specimen source for the glucose test is blood, serum, plasma, or interstitial fluid, and can be obtained by a laboratory test, a POC test, or a continuous glucose monitor (CGM). Glucose test results from urine specimens are not considered. This eCQM is an episode-based measure. An episode is defined as each inpatient hospitalization or encounter that ends during the measurement period. This FHIR-based measure has been derived from the QDM-based measure: CMS871v5. Please refer to the HL7 QI-Core Implementation Guide (https://hl7.org/fhir/us/qicore/STU4.1.1/) for more information on QI-Core and mapping recommendations from QDM to QI-Core 4.1.1 (https://hl7.org/fhir/us/qicore/STU4.1.1/qdm-to-qicore.html).
Effective Period | 2026-01-01..2026-12-31
Measure Steward | Centers for Medicare & Medicaid Services (CMS)
Copyright | Limited proprietary coding is contained in the Measure specifications for user convenience. Users of proprietary code sets should obtain all necessary licenses from the owners of the code sets. American Institutes for Research(R), formerly IMPAQ International, disclaims all liability for use or accuracy of any third party codes contained in the specifications. LOINC(R) copyright 2004-2024 Regenstrief Institute, Inc. This material contains SNOMED Clinical Terms(R) (SNOMED CT[R]) copyright 2004-2024 International Health Terminology Standards Development Organisation. ICD-10 copyright 2024 World Health Organization. All Rights Reserved.
Measure Metadata
Short Name Identifier | CMS871FHIR
Version Independent Identifier | urn:uuid:c44ca609-d795-4715-a8fc-1b0b30e46048
Version Specific Identifier | urn:uuid:b85cda48-6920-482f-aa2f-16efa09efe3f
Publisher (CMS) Identifier | 871FHIR
Identifier | org.hl7.fhir.r5.model.Identifier@2d7160e8
Version Number | Draft based on 0.2.001
Rationale | Hyperglycemia, i.e., elevated glucose level, is common among hospitalized patients, especially those with preexisting diabetes (Umpierrez et al., 2012) and accounts for over 30% of noncritically ill hospitalized patients (Korytkowski, 2022). Hyperglycemia can also affect individuals with no prior history of diabetes and may be induced by medications such as steroids or by parenteral (intravenous) or enteral (tube) feeding. Severe hyperglycemia, i.e., an extremely elevated glucose level, is significantly associated with a range of harms, including increased in-hospital mortality, infection rates, and hospital length of stay (Pasquel, et al., 2021; Umpierrez et al., 2012, 2015). Lower rates of inpatient severe hyperglycemia may not only improve care for patients but also may reduce costs for healthcare payers (Krinsley et al., 2016). The rate of hyperglycemia varies across hospitals, suggesting opportunities for improvement in inpatient glycemic management (Bersoux et al., 2013; Seisa et al., 2022). The rate of inpatient hyperglycemia can be considered a marker for quality of hospital care, since inpatient hyperglycemia is largely avoidable with proper glycemic management. The use of evidence-based standardized protocols and insulin management protocols have been shown to improve glycemic control and safety (Leroy et al., 2020; Maynard et al., 2015). It should be noted that this measure does not aim to measure overall glucose control in hospitalized patients; rather, its goal is to assess the occurrence and extent of severe hyperglycemia. This measure is also intended to be used in combination with its companion measure of hypoglycemia (Hospital Harm – Hypoglycemia) to reduce unintended consequences of measurement.
Clinical Recommendation Statement | Multiple guidelines address recommended levels of glycemic control, though these do not define severe hyperglycemia: From Section 16, Diabetes Care in the Hospital, in the Standards of Care in Diabetes by the American Diabetes Association (American Diabetes Association Professional Practice Committee, 2024): 16.4 Insulin and/or other therapies should be initiated or intensified for treatment of persistent hyperglycemia starting at a threshold of ≥180 mg/dL (10.0 mmol/L) (confirmed on two occasions within 24 hours) for noncritically ill (non-ICU) individuals. 16.5a Once therapy is initiated, a glycemic goal of 140–180 mg/dL (7.8–10.0 mmol/L) is recommended for most critically ill (ICU) individuals with hyperglycemia. 16.5 More stringent glycemic goals, such as 110–140 mg/dL (6.1–7.8 mmol/L), may be appropriate for selected critically ill individuals and are acceptable if they can be achieved without significant hypoglycemia. From Management of Hyperglycemia in Hospitalized Adult Patients in Non-Critical Care Settings: An Endocrine Society Clinical Practice Guideline (Korytkowski et al., 2022): Recommendation 1.1 In adults with insulin-treated diabetes hospitalized for noncritical illness who are at high risk of hypoglycemia, we suggest the use of real-time continuous glucose monitoring (CGM) with confirmatory bedside point-of-care blood glucose (POC-BG) monitoring for adjustments in insulin dosing rather than point-of-care blood glucose (POC-BG) testing alone in hospital settings where resources and training are available. Recommendation 10.1 In adults with no prior history of diabetes hospitalized for noncritical illness with hyperglycemia [defined as blood glucose (BG) > 140 mg/dL (7.8 mmol/L)] during hospitalization, we suggest initial therapy with correctional insulin over scheduled insulin therapy (defined as basal or basal/bolus insulin) to maintain glucose targets in the range of 100 to 180 mg/dL (5.6 to 10.0 mmol/L). For patients with persistent hyperglycemia [≥2 point-of-care blood glucose (POC-BG) measurements ≥ 180 mg/dL (≥10.0 mmol/L) in a 24-hour period on correctional insulin alone], we suggest the addition of scheduled insulin therapy. Recommendation 10.2 In adults with diabetes treated with diet or noninsulin diabetes medications prior to admission, we suggest initial therapy with correctional insulin or scheduled insulin therapy to maintain glucose targets in the range of 100 to 180 mg/dL (5.6 to 10.0 mmol/L). For hospitalized adults started on correctional insulin alone and with persistent hyperglycemia [≥2 point-of-care blood glucose (POC-BG) measurements ≥ 180 mg/dL in a 24-hour period (≥10.0 mmol/L)], we suggest addition of scheduled insulin therapy. We suggest initiation of scheduled insulin therapy for patients with confirmed admission blood glucose (BG) ≥ 180 mg/dL (≥10.0 mmol/L). Recommendation 10.3 In adults with insulin-treated diabetes prior to admission who are hospitalized for noncritical illness, we recommend continuation of the scheduled insulin regimen modified for nutritional status and severity of illness to maintain glucose targets in the range of 100 to 180 mg/dL (5.6 to 10.0 mmol/L). Remarks Reductions in the dose of basal insulin (by 10% to 20%) at time of hospitalization may be required for patients on basal heavy insulin regimens (defined as doses of basal insulin ≥ 0.6 to 1.0 units/kg/day), in which basal insulin is being used inappropriately to cover meal-related excursions in BG. There is no clinically accepted cutoff for severe hyperglycemia. Studies have used thresholds of >140, >180, >300, >350 and >400 mg/dL, among other values (American Diabetes Association Professional Practice Committee, 2024; Umpierrez et al, 2012, 2015; Jamesen et al., 2015; Donihi et al., 2011; Mendez et al, 2015; Seisa et al., 2022). Blood glucose level <180 mg/dL is associated with lower rates of mortality and stroke compared with a target glucose <200 mg/dL (Sathya et al., 2013). Glycemic goals may also differ among hospitalized patients. For inpatient management of hyperglycemia in noncritical care, the expert consensus recommends a target range of 100–180 mg/dL (5.6–10.0 mmol/L) for noncritically ill patients with “new” hyperglycemia as well as people with known diabetes prior to admission. Glycemic levels up to 250 mg/dL (13.9 mmol/L) may be acceptable in terminally ill patients with short life expectancy, patients with advanced kidney failure and/or on dialysis, patients at high risk for hypoglycemia, and/or patients with labile glycemic excursions. In these individuals, less aggressive treatment goals that would help avoid symptomatic hypoglycemia and/or hyperglycemia are often more appropriate (American Diabetes Association Professional Practice Committee, 2024). In an older patient with a prior history of severe hypoglycemia, some degree of hyperglycemia may be tolerated to maximize safety. Intensive insulin therapy to target glucose of 100 and 140mg/dL in the ICU did not significantly reduce perioperative complications compared with target glucose of 141 and 180mg/dL after coronary artery bypass surgery (Umpierrez et al., 2015). The current recommendation is to maintain a blood glucose level between 140-180 mg/dL (7.8-10.0 mmol/L) in both cardiac and non-cardiac ICU patients (Sreedharan et al., 2022). For patients who present with hyperglycemic crises, neurologic status must be monitored closely, with frequent re-examination. Care should be taken to prevent over-correction of hyperglycemia and hyperosmolarity following initial ﬂuid resuscitation of these patients to prevent cerebral edema, which carries a high mortality rate (Gosmanov et al., 2021).
Guidance | The measure is using mg/dL as the unit of measurement for glucose results. Millimoles per liter (mmol/L) should be converted to milligrams per deciliter (mg/dL) for reporting this measure. When evaluating for days with a glucose level >300 mg/dL, the first 24-hour period after admission to the hospital is not evaluated to account for potentially poor glucose control outside of the hospital setting or that preceded the start of hospital care. The admission starts in the ED or observation when the transition between the ED encounter, observation encounter, and the inpatient encounter are within an hour or less of each other. This measure evaluates the first 10 days of an eligible inpatient hospitalization in determining eligible days for the denominator and numerator (i.e., the length of stay is truncated to <=10 days when the length exceeds 10 days). Patients admitted for longer length of stays are more likely to have more complex medical conditions. In determining eligible days for the denominator and numerator, this measure does not evaluate the last day if it was less than a 24-hour period. The “Days in Hospitalization” logic within Measure Observation 1 (associated with the denominator), in conjunction with other logic, returns the day number (e.g., day 1 to day 10) for each day within the hospitalization period to determine the eligible hospital days (e.g., from day 2 to day 10). The “Days in Hospitalization” logic within Measure Observation 2 (associated with the numerator), in conjunction with other logic, returns the day number (e.g., day 1 to day 10) for each day within the hospitalization period to determine the eligible hyperglycemic event days (e.g., from day 2 to day 10). Since the measure does not count any hyperglycemic events that occur in the first 24 hours, day 1 is not considered an eligible hospital day for the Measure Observations. Eligible days range from day 2 up to day 10. However, the measure does allow day 1 to be counted for the Numerator as one of the preceding days for a day where no glucose result is found. In this instance, the measure could evaluate day 1 as one of the two days preceding the day with no glucose result to see if there was a glucose value >=200 mg/dL on day 1. Multiple hyperglycemic events can occur during a ‘day,’ but this is still considered one hyperglycemic event day. The numerator returns the first eligible encounter that meets the qualifying criteria: an inpatient hospitalization with a hyperglycemic event. Only one numerator is counted per encounter. Note that the Numerator returns the encounters, not days, that meet the criteria. This measure includes two measure observations used to calculate the ratio of the number of inpatient hospital days with a hyperglycemic (high blood glucose) event over the total number of eligible inpatient hospital days (<= 10 days) for that encounter. In ratio measures, both the denominator and numerator populations flow separately from the same initial population. Therefore, the same exclusion criteria must be applied to both the denominator and numerator to prevent excluded cases from being considered. The specimen source for the glucose test is blood, serum, plasma, or interstitial fluid, and can be obtained by a laboratory test, a POC test, or a continuous glucose monitor (CGM). Glucose test results from urine specimens are not considered. This eCQM is an episode-based measure. An episode is defined as each inpatient hospitalization or encounter that ends during the measurement period. This FHIR-based measure has been derived from the QDM-based measure: CMS871v5. Please refer to the HL7 QI-Core Implementation Guide (https://hl7.org/fhir/us/qicore/STU4.1.1/) for more information on QI-Core and mapping recommendations from QDM to QI-Core 4.1.1 (https://hl7.org/fhir/us/qicore/STU4.1.1/qdm-to-qicore.html).
Supplemental Data Guidance | For every patient evaluated by this measure also identify payer, race, ethnicity and sex; SDE Ethnicity SDE Payer SDE Race SDE Sex
Measure Population Criteria (ID: Group_1)
Initial Population | ID: InitialPopulation_1 Description: Inpatient hospitalizations for patients age 18 and older that end during the measurement period, as well as either: - A diagnosis of diabetes that starts before or during the encounter; or - Administration of at least one dose of insulin or any hypoglycemic medication during the encounter; or - Presence of at least one glucose value >=200 mg/dL at any time during the encounter Logic Definition: Initial Population
Denominator | ID: Denominator_1 Description: Equals Initial Population Logic Definition: Denominator
Denominator Exclusion | ID: DenominatorExclusion_1 Description: Inpatient hospitalizations for patients with a glucose result of >600 mg/dL anytime between 1 hour prior to the start of the encounter to 6 hours after the start of the encounter. -Inpatient hospitalizations for patients who have comfort care measures ordered or provided during the encounter. -Inpatient hospitalizations for patients who have a discharge disposition to hospice care at home or in a health care facility. Logic Definition: Denominator Exclusions
Numerator | ID: Numerator_1 Description: Inpatient hospitalizations with a hyperglycemic event within the first 10 days of the encounter minus the first 24 hours, and minus the last period before discharge from the hospital if less than 24 hours A hyperglycemic event is defined as: - A day with at least one glucose value >300 mg/dL; OR - A day where a glucose test and result was not found, and it was preceded by two consecutive days where at least one glucose value during each of the two days was >=200 mg/dL Logic Definition: Numerator
Numerator Exclusion | ID: NumeratorExclusion_1 Description: Inpatient hospitalizations for patients with a glucose result of >600 mg/dL anytime between 1 hour prior to the start of the encounter to 6 hours after the start of the encounter. -Inpatient hospitalizations for patients who have comfort care measures ordered or provided during the encounter. -Inpatient hospitalizations for patients who have a discharge disposition to hospice care at home or in a health care facility. Logic Definition: Numerator Exclusions
Measure Observation | ID: MeasureObservation_1_1 Description: Measure Observation 1, associated with the denominator of the ratio: The total number of eligible days of the inpatient hospitalization which match the initial population/denominator criteria and did not meet the denominator exclusion criteria. Logic Definition: Denominator Observations
Measure Observation | ID: MeasureObservation_1_2 Description: Measure Observation 2, associated with the numerator of the ratio: The total number of hyperglycemic days during the inpatient hospitalization that meet the numerator criteria and did not meet the numerator exclusion criteria. Days with a hyperglycemic event are defined as: - All days with a glucose level >300 mg/dL (except those occurring in the first 24-hour period after admission to the hospital (including the emergency department and observation)) OR - All days where a glucose was not measured, and it was immediately preceded by two contiguous, consecutive days where at least one glucose value during each of the two days was >=200 mg/dL. Logic Definition: Numerator Observations
Population Basis | Encounter
Scoring | [http://terminology.hl7.org/CodeSystem/measure-scoring#ratio: 'Ratio']
Type | [http://terminology.hl7.org/CodeSystem/measure-type#outcome: 'Outcome']
Rate Aggregation | None
Improvement Notation | [http://terminology.hl7.org/CodeSystem/measure-improvement-notation#decrease: 'decrease']
Supplemental Data Elements
Supplemental Data Element | ID: sde-ethnicity Usage Code: [http://terminology.hl7.org/CodeSystem/measure-data-usage#supplemental-data] Description: SDE Ethnicity Logic Definition: SDE Ethnicity
Supplemental Data Element | ID: sde-payer Usage Code: [http://terminology.hl7.org/CodeSystem/measure-data-usage#supplemental-data] Description: SDE Payer Logic Definition: SDE Payer
Supplemental Data Element | ID: sde-race Usage Code: [http://terminology.hl7.org/CodeSystem/measure-data-usage#supplemental-data] Description: SDE Race Logic Definition: SDE Race
Supplemental Data Element | ID: sde-sex Usage Code: [http://terminology.hl7.org/CodeSystem/measure-data-usage#supplemental-data] Description: SDE Sex Logic Definition: SDE Sex
Measure Logic
Primary Library | https://madie.cms.gov/Library/CMS871HHHyperFHIR
Dependency | Description: Library SDE Resource: https://madie.cms.gov/Library/SupplementalDataElements|5.1.000 Canonical URL: `https://madie.cms.gov/Library/SupplementalDataElements|5.1.000`
Dependency | Description: Library FHIRHelpers Resource: https://madie.cms.gov/Library/FHIRHelpers|4.4.000 Canonical URL: `https://madie.cms.gov/Library/FHIRHelpers|4.4.000`
Dependency | Description: Library CQMCommon Resource: https://madie.cms.gov/Library/CQMCommon|4.0.000 Canonical URL: `https://madie.cms.gov/Library/CQMCommon|4.0.000`
Dependency | Description: Library QICoreCommon Resource: https://madie.cms.gov/Library/QICoreCommon|4.0.000 Canonical URL: `https://madie.cms.gov/Library/QICoreCommon|4.0.000`
Dependency | Description: Code system SNOMEDCT Resource: http://snomed.info/sct Canonical URL: `http://snomed.info/sct`
Dependency | Description: Value set Encounter Inpatient Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.666.5.307 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.666.5.307`
Dependency | Description: Value set Observation Services Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1111.143 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1111.143`
Dependency | Description: Value set Emergency Department Visit Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.117.1.7.1.292 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.117.1.7.1.292`
Dependency | Description: Value set Diabetes Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.464.1003.103.12.1001 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.464.1003.103.12.1001`
Dependency | Description: Value set Hypoglycemics Treatment Medications Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1196.394 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1196.394`
Dependency | Description: Value set Glucose Lab Test Mass Per Volume Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1248.34 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1248.34`
Dependency | Description: Value set Comfort Measures Resource: http://cts.nlm.nih.gov/fhir/ValueSet/1.3.6.1.4.1.33895.1.3.0.45 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/1.3.6.1.4.1.33895.1.3.0.45`
Dependency | Description: Value set Discharged to Home for Hospice Care Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.117.1.7.1.209 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.117.1.7.1.209`
Dependency | Description: Value set Discharged to Health Care Facility for Hospice Care Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.117.1.7.1.207 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.117.1.7.1.207`
Dependency | Description: Value set Payer Type Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.114222.4.11.3591 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.114222.4.11.3591`
Direct Reference Code | Display: Male (finding) Code: 248153007 System: `http://snomed.info/sct`
Direct Reference Code | Display: Female (finding) Code: 248152002 System: `http://snomed.info/sct`
Parameter | Name: Measurement Period Use: in Min Cardinality: 0 Max Cardinality: 1 Type: Period
Parameter | Name: SDE Sex Use: out Min Cardinality: 0 Max Cardinality: 1 Type: Coding
Parameter | Name: Numerator Use: out Min Cardinality: 0 Max Cardinality: * Type: Resource
Parameter | Name: Denominator Use: out Min Cardinality: 0 Max Cardinality: * Type: Resource
Parameter | Name: Numerator Exclusions Use: out Min Cardinality: 0 Max Cardinality: * Type: Resource
Parameter | Name: SDE Payer Use: out Min Cardinality: 0 Max Cardinality: * Type: Resource
Parameter | Name: Initial Population Use: out Min Cardinality: 0 Max Cardinality: * Type: Resource
Parameter | Name: SDE Ethnicity Use: out Min Cardinality: 0 Max Cardinality: 1 Type: Resource
Parameter | Name: Denominator Exclusions Use: out Min Cardinality: 0 Max Cardinality: * Type: Resource
Parameter | Name: SDE Race Use: out Min Cardinality: 0 Max Cardinality: 1 Type: Resource
Measure Logic Data Requirements
Data Requirement | Type: Patient Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-patient Must Support Elements: extension, birthDate, birthDate.value, url
Data Requirement | Type: Encounter Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-encounter Must Support Elements: type, status, status.value, period, hospitalization, hospitalization.dischargeDisposition Code Filter(s): Path: type ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1111.143
Data Requirement | Type: Encounter Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-encounter Must Support Elements: type, status, status.value, period, hospitalization, hospitalization.dischargeDisposition Code Filter(s): Path: type ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.117.1.7.1.292
Data Requirement | Type: Encounter Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-encounter Must Support Elements: type, period, status, status.value, hospitalization, hospitalization.dischargeDisposition, hospitalizationPeriod, encounter Code Filter(s): Path: type ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.666.5.307
Data Requirement | Type: Condition Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-condition-encounter-diagnosis Must Support Elements: code Code Filter(s): Path: code ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.464.1003.103.12.1001
Data Requirement | Type: MedicationAdministration Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-medicationadministration Must Support Elements: medication, status, status.value, effective Code Filter(s): Path: medication ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1196.394
Data Requirement | Type: MedicationAdministration Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-medicationadministration Must Support Elements: medication.reference.value, status, status.value, effective
Data Requirement | Type: Medication Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-medication Must Support Elements: id.value, code
Data Requirement | Type: Observation Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-observation-lab Must Support Elements: code, effective, status, status.value, value, id, id.value Code Filter(s): Path: code ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1248.34
Data Requirement | Type: ServiceRequest Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-servicerequest Must Support Elements: code Code Filter(s): Path: code ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/1.3.6.1.4.1.33895.1.3.0.45
Data Requirement | Type: Procedure Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-procedure Must Support Elements: code Code Filter(s): Path: code ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/1.3.6.1.4.1.33895.1.3.0.45
Data Requirement | Type: Coverage Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-coverage Must Support Elements: type, period Code Filter(s): Path: type ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.114222.4.11.3591
Measure Logic Definitions
Logic Definition | Library Name: SupplementalDataElements
    define "SDE Sex":
      case
        when Patient.sex = '248153007' then "Male (finding)"
        when Patient.sex = '248152002' then "Female (finding)"
        else null
      end
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "SDE Sex":
      SDE."SDE Sex"
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Qualifying Encounter":
      ["Encounter": "Encounter Inpatient"] InpatientEncounter
        where AgeInYearsAt(date from start of InpatientEncounter.period) >= 18
          and InpatientEncounter.period ends during day of "Measurement Period"
          and InpatientEncounter.status = 'finished'
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Create paring of encounters to hospitalization period so this calculation can be inspected and the result
     * can be reused, making the logic faster.*/

    define "Encounter with Hospitalization Period":
      "Qualifying Encounter" QualifyingHospitalization
        return Tuple {
          encounter: QualifyingHospitalization,
          hospitalizationPeriod: CQMCommon."HospitalizationWithObservation" ( QualifyingHospitalization )
        }
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Using the already calculated pairing of hospitalization periods with encounters, filter on ones with
     * diabetes and return the encounter.*/

    define "Encounter with Existing Diabetes Diagnosis":
      "Encounter with Hospitalization Period" Hospitalization
        with ["ConditionEncounterDiagnosis": "Diabetes"] Diabetes
          such that ( QICoreCommon."ToPrevalenceInterval" ( Diabetes ) starts before end of Hospitalization.hospitalizationPeriod )
        return Hospitalization.encounter
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Using the already calculated pairing of hospitalization periods with encounters, filter on ones with
     * hypoglycemic medicatons and return the encounter.*/

    define "Encounter with Hypoglycemic Medication":
      from
        "Encounter with Hospitalization Period" Hospitalization,
        ["MedicationAdministration": "Hypoglycemics Treatment Medications"] HypoglycemicMed
        where HypoglycemicMed.status in { 'completed', 'in-progress' }
              //and HypoglycemicMed.status != 'not-done'

          and QICoreCommon."ToInterval" ( HypoglycemicMed.effective ) during Hospitalization.hospitalizationPeriod
        return Hospitalization.encounter
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Using the already calculated pairing of hospitalization periods with encounters, filter on ones with
     * any elevated (>= 200) blood glucose reading during the hospitalization*/

    define "Encounter with Elevated Glucose Greater Than or Equal to 200":
      "Encounter with Hospitalization Period" Hospitalization
        with ["LaboratoryResultObservation": "Glucose Lab Test Mass Per Volume"] GlucoseTest
          such that QICoreCommon."Earliest" ( GlucoseTest.effective ) during Hospitalization.hospitalizationPeriod
            and GlucoseTest.status in { 'final', 'amended', 'corrected' }
                //and GlucoseTest.status != 'cancelled'

            and GlucoseTest.value >= 200 'mg/dL'
        return Hospitalization.encounter
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Initial Population":
      "Encounter with Existing Diabetes Diagnosis"
        union "Encounter with Hypoglycemic Medication"
        union "Encounter with Elevated Glucose Greater Than or Equal to 200"
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Denominator":
      "Initial Population"
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Measurement Population":
      "Denominator"
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Days in Hospitalization":
      "Measurement Population" EligibleInpatientHospitalization
        let period: CQMCommon."HospitalizationWithObservation" ( EligibleInpatientHospitalization ),
        relevantPeriod: "Hospital Days Max 10"(period)
        return Tuple {
          encounter: EligibleInpatientHospitalization,
          hospitalizationPeriod: period,
          relevantPeriod: relevantPeriod,
          relevantDays: "Days In Period"(relevantPeriod)
        }
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Days with Glucose Results":
      "Days in Hospitalization" InpatientHospitalDays
        return Tuple {
          encounter: InpatientHospitalDays.encounter,
          relevantPeriod: InpatientHospitalDays.relevantPeriod,
          relevantDays: ( InpatientHospitalDays.relevantDays EncounterDay
              return Tuple {
                dayNumber: EncounterDay.dayNumber,
                dayPeriod: EncounterDay.dayPeriod,
                hasSevereResult: exists ( ["LaboratoryResultObservation": "Glucose Lab Test Mass Per Volume"] GlucoseTest
                    where GlucoseTest.status in { 'final', 'amended', 'corrected' }
                      //and GlucoseTest.status != 'cancelled'

                      and GlucoseTest.value > 300 'mg/dL'
                      and QICoreCommon."Earliest" ( GlucoseTest.effective ) during EncounterDay.dayPeriod
                ),
                hasElevatedResult: exists ( ["LaboratoryResultObservation": "Glucose Lab Test Mass Per Volume"] GlucoseTest
                    where GlucoseTest.status in { 'final', 'amended', 'corrected' }
                      //and GlucoseTest.status != 'cancelled'

                      and GlucoseTest.value >= 200 'mg/dL'
                      and QICoreCommon."Earliest" ( GlucoseTest.effective ) during EncounterDay.dayPeriod
                ),
                hasNoGlucoseTest: not exists ( ["LaboratoryResultObservation": "Glucose Lab Test Mass Per Volume"] GlucoseTest
                    where GlucoseTest.status in { 'final', 'amended', 'corrected' }
                      //and GlucoseTest.status != 'cancelled'

                      and QICoreCommon."Earliest" ( GlucoseTest.effective ) during EncounterDay.dayPeriod
                )
              }
          )
        }
Logic Definition | Library Name: CMS871HHHyperFHIR
    /*# hyper days uses "Relevant Encounters With Glucose Result Days" to find if hyper event on each day. Skips 1st day in 'RelevantDays`. Returns boolean based on: Today high result OR Today no result AND Yesterday high result AND 2 days ago high result*/

    define "Days with Hyperglycemic Events":
      "Days with Glucose Results" EncounterWithResultDays
        let eligibleEventDays: EncounterWithResultDays.relevantDays EncounterDay
          where EncounterDay.dayNumber > 1
          return Tuple {
            dayIndex: EncounterDay.dayNumber,
            dayPeriod: EncounterDay.dayPeriod,
            hasHyperglycemicEvent: ( EncounterDay.hasSevereResult
                or ( EncounterDay.hasNoGlucoseTest
                    and EncounterWithResultDays.relevantDays[EncounterDay.dayNumber - 2].hasElevatedResult
                    and EncounterWithResultDays.relevantDays[EncounterDay.dayNumber - 3].hasElevatedResult
                )
            )
          }
        return Tuple {
          encounter: EncounterWithResultDays.encounter,
          relevantPeriod: EncounterWithResultDays.relevantPeriod,
          eligibleEventDays: eligibleEventDays
        }
Logic Definition | Library Name: CMS871HHHyperFHIR
    /***/

    define "Encounter with Hyperglycemic Events":
      "Days with Hyperglycemic Events" HyperglycemicEventDays
        where exists ( HyperglycemicEventDays.eligibleEventDays EligibleEventDay
            where EligibleEventDay.hasHyperglycemicEvent
        )
        return HyperglycemicEventDays.encounter
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Numerator":
      "Encounter with Hyperglycemic Events"
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start":
      from
        "Initial Population" InpatientHospitalization,
        ["LaboratoryResultObservation": "Glucose Lab Test Mass Per Volume"] GlucoseTest
        let HospitalizationInterval: CQMCommon."HospitalizationWithObservation" ( InpatientHospitalization ),
        GlucoseTestTime: QICoreCommon."Earliest" ( GlucoseTest.effective )
        where GlucoseTest.value as Quantity > 600 'mg/dL'
          and GlucoseTest.status in { 'final', 'amended', 'corrected' }
          and GlucoseTestTime during Interval[( start of HospitalizationInterval - 1 hour ), ( start of HospitalizationInterval + 6 hours )]
        return GlucoseTest
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Glucose Tests Earlier Than Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start":
      from
        "Initial Population" InpatientHospitalization,
        "Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start" GlucoseResult1000,
        ["LaboratoryResultObservation": "Glucose Lab Test Mass Per Volume"] EarlierGlucoseTest
        let HospitalizationInterval: CQMCommon."HospitalizationWithObservation" ( InpatientHospitalization ),
        GlucoseTest1000Time: QICoreCommon."Earliest" ( GlucoseResult1000.effective ),
        EarlierGlucoseTestTime: QICoreCommon."Earliest" ( EarlierGlucoseTest.effective )
        where GlucoseTest1000Time during Interval[( start of HospitalizationInterval - 1 hour ), ( start of HospitalizationInterval + 6 hour )]
          and EarlierGlucoseTestTime during Interval[( start of HospitalizationInterval - 1 hour ), GlucoseTest1000Time )
          and EarlierGlucoseTest.id !~ GlucoseResult1000.id
        return GlucoseResult1000
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Initial Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start":
      "Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start" GlucoseResult1000
        where not ( GlucoseResult1000.id in "Glucose Tests Earlier Than Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start".id )
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Encounter with Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start":
      "Initial Population" InpatientHospitalization
        with "Initial Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start" EarlyGlucoseResult
          such that EarlyGlucoseResult.value as Quantity > 600 'mg/dL'
            and QICoreCommon."Earliest" ( EarlyGlucoseResult.effective ) during Interval[( start of CQMCommon."HospitalizationWithObservation" ( InpatientHospitalization ) - 1 hour ), ( start of CQMCommon."HospitalizationWithObservation" ( InpatientHospitalization ) + 6 hours )]
        return InpatientHospitalization
Logic Definition | Library Name: CMS871HHHyperFHIR
    /***/

    define "Comfort Measures Care":
      ["ServiceRequest": "Comfort Measures"]
        union ["Procedure": "Comfort Measures"]
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Encounter with Comfort Measures during Hospitalization":
      "Initial Population" InpatientHospitalization
        with "Comfort Measures Care" ComfortCare
          such that Coalesce(ComfortCare.performed.toInterval(), ComfortCare.authoredOn.toInterval()) during CQMCommon."HospitalizationWithObservation" ( InpatientHospitalization )
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Encounter with Discharge for Hospice Care":
      "Initial Population" InpatientHospitalization
        where InpatientHospitalization.hospitalization.dischargeDisposition in "Discharged to Home for Hospice Care"
          or InpatientHospitalization.hospitalization.dischargeDisposition in "Discharged to Health Care Facility for Hospice Care"
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Encounter with Early Glucose Greater Than 600 or with Comfort or Hospice Care":
      "Encounter with Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start"
        union "Encounter with Comfort Measures during Hospitalization"
        union "Encounter with Discharge for Hospice Care"
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Numerator Exclusions":
      "Encounter with Early Glucose Greater Than 600 or with Comfort or Hospice Care"
Logic Definition | Library Name: SupplementalDataElements
    define "SDE Payer":
      [Coverage: type in "Payer Type"] Payer
        return {
          code: Payer.type,
          period: Payer.period
        }
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "SDE Payer":
      SDE."SDE Payer"
Logic Definition | Library Name: SupplementalDataElements
    define "SDE Ethnicity":
      Patient.ethnicity E
        return Tuple {
          codes: { E.ombCategory } union E.detailed,
          display: E.text
        }
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "SDE Ethnicity":
      SDE."SDE Ethnicity"
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Denominator Exclusions":
      "Encounter with Early Glucose Greater Than 600 or with Comfort or Hospice Care"
Logic Definition | Library Name: SupplementalDataElements
    define "SDE Race":
      Patient.race R
        return Tuple {
          codes: R.ombCategory union R.detailed,
          display: R.text
        }
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "SDE Race":
      SDE."SDE Race"
Logic Definition | Library Name: FHIRHelpers
    define function ToString(value uri): value.value
Logic Definition | Library Name: FHIRHelpers
    /*
    @description: Converts the given [Period](https://hl7.org/fhir/datatypes.html#Period)
    value to a CQL DateTime Interval
    @comment: If the start value of the given period is unspecified, the starting
    boundary of the resulting interval will be open (meaning the start of the interval
    is unknown, as opposed to interpreted as the beginning of time).
    */
    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]
Logic Definition | Library Name: CQMCommon
    /*
    @description: 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
    @deprecated: This function is deprecated. Use the fluent function `hospitalizationWithObservation()` instead.
    */
    define function "HospitalizationWithObservation"(TheEncounter Encounter ):
      TheEncounter Visit
      		let ObsVisit: Last([Encounter: "Observation Services"] LastObs
      				where LastObs.status = 'finished'
                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.status = 'finished'
                and 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]
Logic Definition | Library Name: QICoreCommon
    /*
    @description: Returns an interval representing the normalized prevalence period of a given Condition.
    @comment: Uses the ToInterval and ToAbatementInterval functions to determine the widest potential interval from
    onset to abatement as specified in the given Condition. If the condition is active, or has an abatement date the resulting
    interval will have a closed ending boundary. Otherwise, the resulting interval will have an open ending boundary.
    @deprecated: This function is deprecated. Use the `prevalenceInterval()` fluent function instead
    */
    define function ToPrevalenceInterval(condition Choice<"ConditionEncounterDiagnosis", "ConditionProblemsHealthConcerns">):
    if condition.clinicalStatus ~ "active"
      or condition.clinicalStatus ~ "recurrence"
      or condition.clinicalStatus ~ "relapse" then
      Interval[start of ToInterval(condition.onset), end of ToAbatementInterval(condition)]
    else
       (end of ToAbatementInterval(condition)) abatementDate
        return if abatementDate is null then
          Interval[start of ToInterval(condition.onset), abatementDate)
        else
          Interval[start of ToInterval(condition.onset), abatementDate]
Logic Definition | Library Name: QICoreCommon
    /*
    @description: Given an interval, return the starting point if the interval has a starting boundary specified,
    otherwise, return the ending point
    @deprecated: This function is deprecated. Use the fluent function `earliest()` instead
    */
    define function "Earliest"(choice Choice<DateTime, Quantity, Interval<DateTime>, Interval<Quantity>> ):
      (choice.toInterval()) period
        return
          if (HasStart(period)) then start of period
          else end of period
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Crops an interval to a maximum length of 10 days.*/

    define function "Hospital Days Max 10"(Period Interval<DateTime>):
      Interval[start of Period, Min({
        end of Period, start of Period + 10 days }
      )]
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Creates a list of 24 hour long intervals in an interval paired with the index (1 indexed) to which 24 hour interval it is.*/

    define function "Days In Period"(Period Interval<DateTime>):
      ( "Interval To Day Numbers"(Period) ) DayNumber
        let startPeriod: start of Period + ( 24 hours * ( DayNumber - 1 ) ),
        endPeriod: if ( hours between startPeriod and end of Period < 24 ) then startPeriod
          else start of Period + ( 24 hours * DayNumber )
        return Tuple {
          dayNumber: DayNumber,
          dayPeriod: Interval[startPeriod, endPeriod )
        }
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Creates a list of integers from 1 to how many days are in the interval. Note, this wont create an index for
     * the final day if it is less than 24 hours. This also includes the first 24 hour period.*/

    define function "Interval To Day Numbers"(Period Interval<DateTime>):
      ( expand { Interval[1, duration in days between start of Period and end of Period]} ) DayExpand
        return end of DayExpand
Logic Definition | Library Name: QICoreCommon
    /*
    @description: Normalizes a value that is a choice of timing-valued types to an equivalent interval
    @comment: Normalizes a choice type of DateTime, Quanitty, Interval<DateTime>, or Interval<Quantity> 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 QICore, allowing this function to be used across any resource.
    The input can be provided as a DateTime, Quantity, Interval<DateTime> or Interval<Quantity>.
    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 Quantity, the quantity is expected to be a calendar-duration interpreted as an Age,
    and the result is a DateTime Interval beginning on the Date the patient turned that age and ending immediately before one year later.
    If the input is a DateTime Interval, the result is the input.
    If the input is a Quantity Interval, the quantities are expected to be calendar-durations interpreted as an Age, and the result
    is a DateTime Interval beginning on the date the patient turned the age given as the start of the quantity interval, and ending
    immediately before one year later than the date the patient turned the age given as the end of the quantity interval.
    If the input is a Timing, an error will be thrown indicating that Timing calculations are not implemented. Any other input will reslt in a null DateTime Interval
    */
    define fluent function toInterval(choice Choice<DateTime, Quantity, Interval<DateTime>, Interval<Quantity>, Timing>):
      case
    	  when choice is DateTime then
        	Interval[choice as DateTime, choice as DateTime]
    		when choice is Interval<DateTime> then
      		choice as Interval<DateTime>
    		when choice is Quantity then
    		  Interval[Patient.birthDate + (choice as Quantity),
    			  Patient.birthDate + (choice as Quantity) + 1 year)
    		when choice is Interval<Quantity> then
    		  Interval[Patient.birthDate + (choice.low as Quantity),
    			  Patient.birthDate + (choice.high as Quantity) + 1 year)
    		when choice is Timing then
          Message(null, true, 'NOT_IMPLEMENTED', 'Error', 'Calculation of an interval from a Timing value is not supported') as Interval<DateTime>
    		else
    			null as Interval<DateTime>
    	end
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Counts the number of eligible days in an encounter. This simply filters and counts the data built in
     * "Relevant Encounters With Hyperglycemic Event Days".*/

    define function "Denominator Observations"(QualifyingEncounter Encounter):
      if QualifyingEncounter.id in "Denominator Exclusions".id then singleton from ( "Days with Hyperglycemic Events" EncounterWithEventDays
          where EncounterWithEventDays.encounter = QualifyingEncounter
          return 0
      )
        else singleton from ( "Days with Hyperglycemic Events" EncounterWithEventDays
          where EncounterWithEventDays.encounter = QualifyingEncounter
          return Count(EncounterWithEventDays.eligibleEventDays)
      )
Logic Definition | Library Name: FHIRHelpers
    /*
    @description: Converts the given FHIR [Coding](https://hl7.org/fhir/datatypes.html#Coding) value to a CQL Code.
    */
    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
            }
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Counts the number of eligible days with a hyperglycemic event in an encounter. This simply filters and counts the data built in
     * "Relevant Encounters With Hyperglycemic Event Days".*/

    define function "Numerator Observations"(QualifyingEncounter Encounter):
      if QualifyingEncounter.id in "Denominator Exclusions".id then singleton from ( "Days with Hyperglycemic Events" EncounterWithEventDays
          where EncounterWithEventDays.encounter = QualifyingEncounter
          return 0
      )
        else singleton from ( "Days with Hyperglycemic Events" EncounterWithEventDays
          where EncounterWithEventDays.encounter = QualifyingEncounter
          return Count(EncounterWithEventDays.eligibleEventDays EligibleEventDay
              where EligibleEventDay.hasHyperglycemicEvent
          )
      )
Dependency | Description: Library SDE Resource: https://madie.cms.gov/Library/SupplementalDataElements|5.1.000 Canonical URL: `https://madie.cms.gov/Library/SupplementalDataElements|5.1.000`
Dependency | Description: Library FHIRHelpers Resource: https://madie.cms.gov/Library/FHIRHelpers|4.4.000 Canonical URL: `https://madie.cms.gov/Library/FHIRHelpers|4.4.000`
Dependency | Description: Library CQMCommon Resource: https://madie.cms.gov/Library/CQMCommon|4.0.000 Canonical URL: `https://madie.cms.gov/Library/CQMCommon|4.0.000`
Dependency | Description: Library QICoreCommon Resource: https://madie.cms.gov/Library/QICoreCommon|4.0.000 Canonical URL: `https://madie.cms.gov/Library/QICoreCommon|4.0.000`
Dependency | Description: Code system SNOMEDCT Resource: http://snomed.info/sct Canonical URL: `http://snomed.info/sct`
Dependency | Description: Value set Encounter Inpatient Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.666.5.307 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.666.5.307`
Dependency | Description: Value set Observation Services Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1111.143 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1111.143`
Dependency | Description: Value set Emergency Department Visit Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.117.1.7.1.292 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.117.1.7.1.292`
Dependency | Description: Value set Diabetes Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.464.1003.103.12.1001 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.464.1003.103.12.1001`
Dependency | Description: Value set Hypoglycemics Treatment Medications Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1196.394 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1196.394`
Dependency | Description: Value set Glucose Lab Test Mass Per Volume Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1248.34 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1248.34`
Dependency | Description: Value set Comfort Measures Resource: http://cts.nlm.nih.gov/fhir/ValueSet/1.3.6.1.4.1.33895.1.3.0.45 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/1.3.6.1.4.1.33895.1.3.0.45`
Dependency | Description: Value set Discharged to Home for Hospice Care Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.117.1.7.1.209 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.117.1.7.1.209`
Dependency | Description: Value set Discharged to Health Care Facility for Hospice Care Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.117.1.7.1.207 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.117.1.7.1.207`
Dependency | Description: Value set Payer Type Resource: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.114222.4.11.3591 Canonical URL: `http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.114222.4.11.3591`
Direct Reference Code | Display: Male (finding) Code: 248153007 System: `http://snomed.info/sct`
Direct Reference Code | Display: Female (finding) Code: 248152002 System: `http://snomed.info/sct`
Parameter | Name: Measurement Period Use: in Min Cardinality: 0 Max Cardinality: 1 Type: Period
Parameter | Name: Numerator Use: out Min Cardinality: 0 Max Cardinality: * Type: Resource
Parameter | Name: Denominator Use: out Min Cardinality: 0 Max Cardinality: * Type: Resource
Parameter | Name: Numerator Exclusions Use: out Min Cardinality: 0 Max Cardinality: * Type: Resource
Parameter | Name: Initial Population Use: out Min Cardinality: 0 Max Cardinality: * Type: Resource
Parameter | Name: Denominator Exclusions Use: out Min Cardinality: 0 Max Cardinality: * Type: Resource
Parameter | Name: SDE Sex Use: out Min Cardinality: 0 Max Cardinality: 1 Type: Coding
Parameter | Name: SDE Payer Use: out Min Cardinality: 0 Max Cardinality: * Type: Resource
Parameter | Name: SDE Ethnicity Use: out Min Cardinality: 0 Max Cardinality: 1 Type: Resource
Parameter | Name: SDE Race Use: out Min Cardinality: 0 Max Cardinality: 1 Type: Resource
Measure Logic Data Requirements
Data Requirement | Type: Patient Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-patient Must Support Elements: extension, birthDate, birthDate.value, url
Data Requirement | Type: Encounter Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-encounter Must Support Elements: type, status, status.value, period, hospitalization, hospitalization.dischargeDisposition Code Filter(s): Path: type ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1111.143
Data Requirement | Type: Encounter Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-encounter Must Support Elements: type, status, status.value, period, hospitalization, hospitalization.dischargeDisposition Code Filter(s): Path: type ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.117.1.7.1.292
Data Requirement | Type: Encounter Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-encounter Must Support Elements: type, period, status, status.value, hospitalization, hospitalization.dischargeDisposition, hospitalizationPeriod, encounter Code Filter(s): Path: type ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.666.5.307
Data Requirement | Type: Condition Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-condition-encounter-diagnosis Must Support Elements: code Code Filter(s): Path: code ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.464.1003.103.12.1001
Data Requirement | Type: MedicationAdministration Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-medicationadministration Must Support Elements: medication, status, status.value, effective Code Filter(s): Path: medication ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1196.394
Data Requirement | Type: MedicationAdministration Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-medicationadministration Must Support Elements: medication.reference.value, status, status.value, effective
Data Requirement | Type: Medication Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-medication Must Support Elements: id.value, code
Data Requirement | Type: Observation Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-observation-lab Must Support Elements: code, effective, status, status.value, value, id, id.value Code Filter(s): Path: code ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1248.34
Data Requirement | Type: ServiceRequest Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-servicerequest Must Support Elements: code Code Filter(s): Path: code ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/1.3.6.1.4.1.33895.1.3.0.45
Data Requirement | Type: Procedure Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-procedure Must Support Elements: code Code Filter(s): Path: code ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/1.3.6.1.4.1.33895.1.3.0.45
Data Requirement | Type: Coverage Profile(s): http://hl7.org/fhir/us/qicore/StructureDefinition/qicore-coverage Must Support Elements: type, period Code Filter(s): Path: type ValueSet: http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.114222.4.11.3591
Measure Logic Definitions
Logic Definition | Library Name: SupplementalDataElements
    define "SDE Sex":
      case
        when Patient.sex = '248153007' then "Male (finding)"
        when Patient.sex = '248152002' then "Female (finding)"
        else null
      end
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "SDE Sex":
      SDE."SDE Sex"
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Qualifying Encounter":
      ["Encounter": "Encounter Inpatient"] InpatientEncounter
        where AgeInYearsAt(date from start of InpatientEncounter.period) >= 18
          and InpatientEncounter.period ends during day of "Measurement Period"
          and InpatientEncounter.status = 'finished'
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Create paring of encounters to hospitalization period so this calculation can be inspected and the result
     * can be reused, making the logic faster.*/

    define "Encounter with Hospitalization Period":
      "Qualifying Encounter" QualifyingHospitalization
        return Tuple {
          encounter: QualifyingHospitalization,
          hospitalizationPeriod: CQMCommon."HospitalizationWithObservation" ( QualifyingHospitalization )
        }
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Using the already calculated pairing of hospitalization periods with encounters, filter on ones with
     * diabetes and return the encounter.*/

    define "Encounter with Existing Diabetes Diagnosis":
      "Encounter with Hospitalization Period" Hospitalization
        with ["ConditionEncounterDiagnosis": "Diabetes"] Diabetes
          such that ( QICoreCommon."ToPrevalenceInterval" ( Diabetes ) starts before end of Hospitalization.hospitalizationPeriod )
        return Hospitalization.encounter
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Using the already calculated pairing of hospitalization periods with encounters, filter on ones with
     * hypoglycemic medicatons and return the encounter.*/

    define "Encounter with Hypoglycemic Medication":
      from
        "Encounter with Hospitalization Period" Hospitalization,
        ["MedicationAdministration": "Hypoglycemics Treatment Medications"] HypoglycemicMed
        where HypoglycemicMed.status in { 'completed', 'in-progress' }
              //and HypoglycemicMed.status != 'not-done'

          and QICoreCommon."ToInterval" ( HypoglycemicMed.effective ) during Hospitalization.hospitalizationPeriod
        return Hospitalization.encounter
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Using the already calculated pairing of hospitalization periods with encounters, filter on ones with
     * any elevated (>= 200) blood glucose reading during the hospitalization*/

    define "Encounter with Elevated Glucose Greater Than or Equal to 200":
      "Encounter with Hospitalization Period" Hospitalization
        with ["LaboratoryResultObservation": "Glucose Lab Test Mass Per Volume"] GlucoseTest
          such that QICoreCommon."Earliest" ( GlucoseTest.effective ) during Hospitalization.hospitalizationPeriod
            and GlucoseTest.status in { 'final', 'amended', 'corrected' }
                //and GlucoseTest.status != 'cancelled'

            and GlucoseTest.value >= 200 'mg/dL'
        return Hospitalization.encounter
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Initial Population":
      "Encounter with Existing Diabetes Diagnosis"
        union "Encounter with Hypoglycemic Medication"
        union "Encounter with Elevated Glucose Greater Than or Equal to 200"
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Denominator":
      "Initial Population"
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Measurement Population":
      "Denominator"
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Days in Hospitalization":
      "Measurement Population" EligibleInpatientHospitalization
        let period: CQMCommon."HospitalizationWithObservation" ( EligibleInpatientHospitalization ),
        relevantPeriod: "Hospital Days Max 10"(period)
        return Tuple {
          encounter: EligibleInpatientHospitalization,
          hospitalizationPeriod: period,
          relevantPeriod: relevantPeriod,
          relevantDays: "Days In Period"(relevantPeriod)
        }
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Days with Glucose Results":
      "Days in Hospitalization" InpatientHospitalDays
        return Tuple {
          encounter: InpatientHospitalDays.encounter,
          relevantPeriod: InpatientHospitalDays.relevantPeriod,
          relevantDays: ( InpatientHospitalDays.relevantDays EncounterDay
              return Tuple {
                dayNumber: EncounterDay.dayNumber,
                dayPeriod: EncounterDay.dayPeriod,
                hasSevereResult: exists ( ["LaboratoryResultObservation": "Glucose Lab Test Mass Per Volume"] GlucoseTest
                    where GlucoseTest.status in { 'final', 'amended', 'corrected' }
                      //and GlucoseTest.status != 'cancelled'

                      and GlucoseTest.value > 300 'mg/dL'
                      and QICoreCommon."Earliest" ( GlucoseTest.effective ) during EncounterDay.dayPeriod
                ),
                hasElevatedResult: exists ( ["LaboratoryResultObservation": "Glucose Lab Test Mass Per Volume"] GlucoseTest
                    where GlucoseTest.status in { 'final', 'amended', 'corrected' }
                      //and GlucoseTest.status != 'cancelled'

                      and GlucoseTest.value >= 200 'mg/dL'
                      and QICoreCommon."Earliest" ( GlucoseTest.effective ) during EncounterDay.dayPeriod
                ),
                hasNoGlucoseTest: not exists ( ["LaboratoryResultObservation": "Glucose Lab Test Mass Per Volume"] GlucoseTest
                    where GlucoseTest.status in { 'final', 'amended', 'corrected' }
                      //and GlucoseTest.status != 'cancelled'

                      and QICoreCommon."Earliest" ( GlucoseTest.effective ) during EncounterDay.dayPeriod
                )
              }
          )
        }
Logic Definition | Library Name: CMS871HHHyperFHIR
    /*# hyper days uses "Relevant Encounters With Glucose Result Days" to find if hyper event on each day. Skips 1st day in 'RelevantDays`. Returns boolean based on: Today high result OR Today no result AND Yesterday high result AND 2 days ago high result*/

    define "Days with Hyperglycemic Events":
      "Days with Glucose Results" EncounterWithResultDays
        let eligibleEventDays: EncounterWithResultDays.relevantDays EncounterDay
          where EncounterDay.dayNumber > 1
          return Tuple {
            dayIndex: EncounterDay.dayNumber,
            dayPeriod: EncounterDay.dayPeriod,
            hasHyperglycemicEvent: ( EncounterDay.hasSevereResult
                or ( EncounterDay.hasNoGlucoseTest
                    and EncounterWithResultDays.relevantDays[EncounterDay.dayNumber - 2].hasElevatedResult
                    and EncounterWithResultDays.relevantDays[EncounterDay.dayNumber - 3].hasElevatedResult
                )
            )
          }
        return Tuple {
          encounter: EncounterWithResultDays.encounter,
          relevantPeriod: EncounterWithResultDays.relevantPeriod,
          eligibleEventDays: eligibleEventDays
        }
Logic Definition | Library Name: CMS871HHHyperFHIR
    /***/

    define "Encounter with Hyperglycemic Events":
      "Days with Hyperglycemic Events" HyperglycemicEventDays
        where exists ( HyperglycemicEventDays.eligibleEventDays EligibleEventDay
            where EligibleEventDay.hasHyperglycemicEvent
        )
        return HyperglycemicEventDays.encounter
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Numerator":
      "Encounter with Hyperglycemic Events"
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start":
      from
        "Initial Population" InpatientHospitalization,
        ["LaboratoryResultObservation": "Glucose Lab Test Mass Per Volume"] GlucoseTest
        let HospitalizationInterval: CQMCommon."HospitalizationWithObservation" ( InpatientHospitalization ),
        GlucoseTestTime: QICoreCommon."Earliest" ( GlucoseTest.effective )
        where GlucoseTest.value as Quantity > 600 'mg/dL'
          and GlucoseTest.status in { 'final', 'amended', 'corrected' }
          and GlucoseTestTime during Interval[( start of HospitalizationInterval - 1 hour ), ( start of HospitalizationInterval + 6 hours )]
        return GlucoseTest
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Glucose Tests Earlier Than Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start":
      from
        "Initial Population" InpatientHospitalization,
        "Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start" GlucoseResult1000,
        ["LaboratoryResultObservation": "Glucose Lab Test Mass Per Volume"] EarlierGlucoseTest
        let HospitalizationInterval: CQMCommon."HospitalizationWithObservation" ( InpatientHospitalization ),
        GlucoseTest1000Time: QICoreCommon."Earliest" ( GlucoseResult1000.effective ),
        EarlierGlucoseTestTime: QICoreCommon."Earliest" ( EarlierGlucoseTest.effective )
        where GlucoseTest1000Time during Interval[( start of HospitalizationInterval - 1 hour ), ( start of HospitalizationInterval + 6 hour )]
          and EarlierGlucoseTestTime during Interval[( start of HospitalizationInterval - 1 hour ), GlucoseTest1000Time )
          and EarlierGlucoseTest.id !~ GlucoseResult1000.id
        return GlucoseResult1000
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Initial Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start":
      "Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start" GlucoseResult1000
        where not ( GlucoseResult1000.id in "Glucose Tests Earlier Than Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start".id )
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Encounter with Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start":
      "Initial Population" InpatientHospitalization
        with "Initial Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start" EarlyGlucoseResult
          such that EarlyGlucoseResult.value as Quantity > 600 'mg/dL'
            and QICoreCommon."Earliest" ( EarlyGlucoseResult.effective ) during Interval[( start of CQMCommon."HospitalizationWithObservation" ( InpatientHospitalization ) - 1 hour ), ( start of CQMCommon."HospitalizationWithObservation" ( InpatientHospitalization ) + 6 hours )]
        return InpatientHospitalization
Logic Definition | Library Name: CMS871HHHyperFHIR
    /***/

    define "Comfort Measures Care":
      ["ServiceRequest": "Comfort Measures"]
        union ["Procedure": "Comfort Measures"]
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Encounter with Comfort Measures during Hospitalization":
      "Initial Population" InpatientHospitalization
        with "Comfort Measures Care" ComfortCare
          such that Coalesce(ComfortCare.performed.toInterval(), ComfortCare.authoredOn.toInterval()) during CQMCommon."HospitalizationWithObservation" ( InpatientHospitalization )
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Encounter with Discharge for Hospice Care":
      "Initial Population" InpatientHospitalization
        where InpatientHospitalization.hospitalization.dischargeDisposition in "Discharged to Home for Hospice Care"
          or InpatientHospitalization.hospitalization.dischargeDisposition in "Discharged to Health Care Facility for Hospice Care"
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Encounter with Early Glucose Greater Than 600 or with Comfort or Hospice Care":
      "Encounter with Glucose Greater Than 600 within 1 Hour Prior To and 6 Hours After Encounter Start"
        union "Encounter with Comfort Measures during Hospitalization"
        union "Encounter with Discharge for Hospice Care"
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Numerator Exclusions":
      "Encounter with Early Glucose Greater Than 600 or with Comfort or Hospice Care"
Logic Definition | Library Name: SupplementalDataElements
    define "SDE Payer":
      [Coverage: type in "Payer Type"] Payer
        return {
          code: Payer.type,
          period: Payer.period
        }
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "SDE Payer":
      SDE."SDE Payer"
Logic Definition | Library Name: SupplementalDataElements
    define "SDE Ethnicity":
      Patient.ethnicity E
        return Tuple {
          codes: { E.ombCategory } union E.detailed,
          display: E.text
        }
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "SDE Ethnicity":
      SDE."SDE Ethnicity"
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "Denominator Exclusions":
      "Encounter with Early Glucose Greater Than 600 or with Comfort or Hospice Care"
Logic Definition | Library Name: SupplementalDataElements
    define "SDE Race":
      Patient.race R
        return Tuple {
          codes: R.ombCategory union R.detailed,
          display: R.text
        }
Logic Definition | Library Name: CMS871HHHyperFHIR
    define "SDE Race":
      SDE."SDE Race"
Logic Definition | Library Name: FHIRHelpers
    define function ToString(value uri): value.value
Logic Definition | Library Name: FHIRHelpers
    /*
    @description: Converts the given [Period](https://hl7.org/fhir/datatypes.html#Period)
    value to a CQL DateTime Interval
    @comment: If the start value of the given period is unspecified, the starting
    boundary of the resulting interval will be open (meaning the start of the interval
    is unknown, as opposed to interpreted as the beginning of time).
    */
    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]
Logic Definition | Library Name: CQMCommon
    /*
    @description: 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
    @deprecated: This function is deprecated. Use the fluent function `hospitalizationWithObservation()` instead.
    */
    define function "HospitalizationWithObservation"(TheEncounter Encounter ):
      TheEncounter Visit
      		let ObsVisit: Last([Encounter: "Observation Services"] LastObs
      				where LastObs.status = 'finished'
                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.status = 'finished'
                and 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]
Logic Definition | Library Name: QICoreCommon
    /*
    @description: Returns an interval representing the normalized prevalence period of a given Condition.
    @comment: Uses the ToInterval and ToAbatementInterval functions to determine the widest potential interval from
    onset to abatement as specified in the given Condition. If the condition is active, or has an abatement date the resulting
    interval will have a closed ending boundary. Otherwise, the resulting interval will have an open ending boundary.
    @deprecated: This function is deprecated. Use the `prevalenceInterval()` fluent function instead
    */
    define function ToPrevalenceInterval(condition Choice<"ConditionEncounterDiagnosis", "ConditionProblemsHealthConcerns">):
    if condition.clinicalStatus ~ "active"
      or condition.clinicalStatus ~ "recurrence"
      or condition.clinicalStatus ~ "relapse" then
      Interval[start of ToInterval(condition.onset), end of ToAbatementInterval(condition)]
    else
       (end of ToAbatementInterval(condition)) abatementDate
        return if abatementDate is null then
          Interval[start of ToInterval(condition.onset), abatementDate)
        else
          Interval[start of ToInterval(condition.onset), abatementDate]
Logic Definition | Library Name: QICoreCommon
    /*
    @description: Given an interval, return the starting point if the interval has a starting boundary specified,
    otherwise, return the ending point
    @deprecated: This function is deprecated. Use the fluent function `earliest()` instead
    */
    define function "Earliest"(choice Choice<DateTime, Quantity, Interval<DateTime>, Interval<Quantity>> ):
      (choice.toInterval()) period
        return
          if (HasStart(period)) then start of period
          else end of period
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Crops an interval to a maximum length of 10 days.*/

    define function "Hospital Days Max 10"(Period Interval<DateTime>):
      Interval[start of Period, Min({
        end of Period, start of Period + 10 days }
      )]
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Creates a list of 24 hour long intervals in an interval paired with the index (1 indexed) to which 24 hour interval it is.*/

    define function "Days In Period"(Period Interval<DateTime>):
      ( "Interval To Day Numbers"(Period) ) DayNumber
        let startPeriod: start of Period + ( 24 hours * ( DayNumber - 1 ) ),
        endPeriod: if ( hours between startPeriod and end of Period < 24 ) then startPeriod
          else start of Period + ( 24 hours * DayNumber )
        return Tuple {
          dayNumber: DayNumber,
          dayPeriod: Interval[startPeriod, endPeriod )
        }
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Creates a list of integers from 1 to how many days are in the interval. Note, this wont create an index for
     * the final day if it is less than 24 hours. This also includes the first 24 hour period.*/

    define function "Interval To Day Numbers"(Period Interval<DateTime>):
      ( expand { Interval[1, duration in days between start of Period and end of Period]} ) DayExpand
        return end of DayExpand
Logic Definition | Library Name: QICoreCommon
    /*
    @description: Normalizes a value that is a choice of timing-valued types to an equivalent interval
    @comment: Normalizes a choice type of DateTime, Quanitty, Interval<DateTime>, or Interval<Quantity> 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 QICore, allowing this function to be used across any resource.
    The input can be provided as a DateTime, Quantity, Interval<DateTime> or Interval<Quantity>.
    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 Quantity, the quantity is expected to be a calendar-duration interpreted as an Age,
    and the result is a DateTime Interval beginning on the Date the patient turned that age and ending immediately before one year later.
    If the input is a DateTime Interval, the result is the input.
    If the input is a Quantity Interval, the quantities are expected to be calendar-durations interpreted as an Age, and the result
    is a DateTime Interval beginning on the date the patient turned the age given as the start of the quantity interval, and ending
    immediately before one year later than the date the patient turned the age given as the end of the quantity interval.
    If the input is a Timing, an error will be thrown indicating that Timing calculations are not implemented. Any other input will reslt in a null DateTime Interval
    */
    define fluent function toInterval(choice Choice<DateTime, Quantity, Interval<DateTime>, Interval<Quantity>, Timing>):
      case
    	  when choice is DateTime then
        	Interval[choice as DateTime, choice as DateTime]
    		when choice is Interval<DateTime> then
      		choice as Interval<DateTime>
    		when choice is Quantity then
    		  Interval[Patient.birthDate + (choice as Quantity),
    			  Patient.birthDate + (choice as Quantity) + 1 year)
    		when choice is Interval<Quantity> then
    		  Interval[Patient.birthDate + (choice.low as Quantity),
    			  Patient.birthDate + (choice.high as Quantity) + 1 year)
    		when choice is Timing then
          Message(null, true, 'NOT_IMPLEMENTED', 'Error', 'Calculation of an interval from a Timing value is not supported') as Interval<DateTime>
    		else
    			null as Interval<DateTime>
    	end
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Counts the number of eligible days in an encounter. This simply filters and counts the data built in
     * "Relevant Encounters With Hyperglycemic Event Days".*/

    define function "Denominator Observations"(QualifyingEncounter Encounter):
      if QualifyingEncounter.id in "Denominator Exclusions".id then singleton from ( "Days with Hyperglycemic Events" EncounterWithEventDays
          where EncounterWithEventDays.encounter = QualifyingEncounter
          return 0
      )
        else singleton from ( "Days with Hyperglycemic Events" EncounterWithEventDays
          where EncounterWithEventDays.encounter = QualifyingEncounter
          return Count(EncounterWithEventDays.eligibleEventDays)
      )
Logic Definition | Library Name: FHIRHelpers
    /*
    @description: Converts the given FHIR [Coding](https://hl7.org/fhir/datatypes.html#Coding) value to a CQL Code.
    */
    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
            }
Logic Definition | Library Name: CMS871HHHyperFHIR
    /**
     * Counts the number of eligible days with a hyperglycemic event in an encounter. This simply filters and counts the data built in
     * "Relevant Encounters With Hyperglycemic Event Days".*/

    define function "Numerator Observations"(QualifyingEncounter Encounter):
      if QualifyingEncounter.id in "Denominator Exclusions".id then singleton from ( "Days with Hyperglycemic Events" EncounterWithEventDays
          where EncounterWithEventDays.encounter = QualifyingEncounter
          return 0
      )
        else singleton from ( "Days with Hyperglycemic Events" EncounterWithEventDays
          where EncounterWithEventDays.encounter = QualifyingEncounter
          return Count(EncounterWithEventDays.eligibleEventDays EligibleEventDay
              where EligibleEventDay.hasHyperglycemicEvent
          )
      )
Generated using version 0.4.6 of the sample-content-ig Liquid templates