eCQM QICore Content Implementation Guide
2024.0.0 - CI Build

eCQM QICore Content Implementation Guide, published by cqframework. This guide is not an authorized publication; it is the continuous build for version 2024.0.0 built by the FHIR (HL7® FHIR® Standard) CI Build. This version is based on the current content of https://github.com/cqframework/ecqm-content-qicore-2024/ and changes regularly. See the Directory of published versions

Measure: Hospital Harm - Severe HyperglycemiaFHIR

Official URL: https://madie.cms.gov/Measure/HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Version: 0.1.000
Draft as of 2024-07-09 Responsible: Centers for Medicare & Medicaid Services (CMS) Computable Name: HospitalHarmHyperglycemiainHospitalizedPatientsFHIR
Other Identifiers: Short Name (use: usual, ), UUID:c44ca609-d795-4715-a8fc-1b0b30e46048 (use: official, ), UUID:c7dbf77f-5869-42a0-b5e6-12e18004d2f4 (use: official, ), Endorser (use: official, ), Publisher (use: official, )

Copyright/Legal: 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-2023 Regenstrief Institute, Inc. This material contains SNOMED Clinical Terms(R) (SNOMED CT[R]) copyright 2004-2023 International Health Terminology Standards Development Organisation. ICD-10 copyright 2023 World Health Organization. All Rights Reserved.

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

UNKNOWN

Title: Hospital Harm - Severe HyperglycemiaFHIR
Id: HospitalHarmHyperglycemiainHospitalizedPatientsFHIR
Version: 0.1.000
Url: Hospital Harm - Severe HyperglycemiaFHIR
short-name identifier:

CMS871FHIR

version-independent identifier:

urn:uuid:c44ca609-d795-4715-a8fc-1b0b30e46048

version-specific identifier:

urn:uuid:c7dbf77f-5869-42a0-b5e6-12e18004d2f4

endorser (CMS Consensus Based Entity) identifier:

3533e

publisher (CMS) identifier:

871FHIR

Effective Period: 2025-01-01..2025-12-31
Status: draft
Publisher: Centers for Medicare & Medicaid Services (CMS)
Author: American Institutes for Research (AIR)
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

Purpose:

UNKNOWN

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-2023 Regenstrief Institute, Inc. This material contains SNOMED Clinical Terms(R) (SNOMED CT[R]) copyright 2004-2023 International Health Terminology Standards Development Organisation. ICD-10 copyright 2023 World Health Organization. All Rights Reserved.

Disclaimer:

This performance measure is not a clinical guideline and 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.

Due to technical limitations, registered trademarks are indicated by (R) or [R] and unregistered trademarks are indicated by (TM) or [TM].

Scoring:

Proportion

Rationale:

Hyperglycemia, i.e., elevated glucose level, is common among hospitalized patients, especially those with preexisting diabetes (Umpierrez et al., 2012) and account 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 parenteral (intravenous) or enteral (tube) feeding.

Severe hyperglycemia, i.e., 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 reduce costs for healthcare payers (Krinsley et al., 2016). The rate of hyperglycemia varies across hospitals, suggesting opportunities for improvement in inpatient glycemic management (Seisa et al., 2022; Bersoux et al., 2013). 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).

From the Endocrine Society clinical practice guideline on the Management of Hyperglycemia in Hospitalized Patients in Non-critical Care Setting, 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.

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 Medical Care in Diabetes by the American Diabetes Association, (American Diabetes Association, 2023):

16.4 Insulin therapy should be initiated for the treatment of persistent hyperglycemia starting at a threshold ≥180 mg/dL (10.0 mmol/L) (checked on two occasions). Once insulin therapy is started, a target glucose range of 140–180 mg/dL (7.8–10.0 mmol/L) is recommended for most critically ill and noncritically ill patients.

16.5 More stringent goals, such as 110–140 mg/dL (6.1–7.8 mmol/L) or 100–180 mg/dL (5.6–10.0 mmol/L), may be appropriate for selected patients and are acceptable if they can be achieved without significant hypoglycemia.

From the Endocrine Society clinical practice guideline on the Management of Hyperglycemia in Hospitalized Patients in Non-critical Care Setting (2022):

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, 2023; Umpierrez et al, 2012, 2015; Jamesen et al., 2015; Donihi et al., 2011; Mendez et al, 2015; Seisa et al., 2022). BGL <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 >250 mg/dL (13.9 mmol/L) may be acceptable in terminally ill patients with short life expectancy. In these individuals, less aggressive insulin regimens to minimize glucosuria, dehydration, and electrolyte disturbances are often more appropriate. (ElSayed et al., 2023). 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/dLin the ICU didn’t significantly reduce perioperative complications compared with target glucose of 141and180mg/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 fluid resuscitation of these patients to prevent cerebral edema, which carries a high mortality rate. (Gosmanov et al., 2021).

From the Endocrine Society clinical practice guideline on the Management of Hyperglycemia in Hospitalized Patients in Non-critical Care Setting, 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.

Guidance (Usage): The measure is using mg/dL as the unit of measurement for glucose results. 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 emergency department (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. 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. Although the measure does not count any hyperglycemic events that occur in the first 24 hours as a hyperglycemic event day in Measure Observation 2, the first 24 hours of the encounter is considered day 1. This is because if there was a day during the encounter where a glucose result is not found, the measure evaluates the two days preceding to see if each had a glucose value >=200 mg/dL. The measure allows the first 24 hours of the encounter, i.e., day 1, to be one of the preceding days. 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. The specimen source for the glucose test is blood, serum, plasma, or interstitial fluid, and can be obtained by a laboratory test, a Point of Care (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: CMS871v4. 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-Core4.1.1 (https://hl7.org/fhir/us/qicore/STU4.1.1/qdm-to-qicore.html).
Population Criteria:
6501fe8dda013638e7b3dc0d
Initial Population: 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
Denominator: Equals Initial Population
Denominator Exclusion: -Inpatient hospitalizations for patients with a glucose result of >=1000 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 home or to a health care facility for hospice care
Numerator: 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
Measure Observation: None
Measure Observation: None
Supplemental Data Elements:

SDE Ethnicity

SDE Payer

SDE Race

SDE Sex

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
Libraries:
HospitalHarmHyperglycemiainHospitalizedPatientsFHIR
Terminology and Other Dependencies:
  • Library/SupplementalDataElements|3.5.000
  • Library/FHIRHelpers|4.4.000
  • Library/CQMCommon|2.2.000
  • Library/QICoreCommon|2.1.000
  • AdministrativeGender
  • Encounter Inpatient
  • Observation Services
  • Emergency Department Visit
  • Diabetes
  • http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1196.394
  • http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1248.34
  • Payer
  • Parameters:
    name use min max type
    Measurement Period In 0 1 Period
    SDE Sex Out 0 1 Coding
    Numerator Out 0 * Resource
    Denominator Out 0 * Resource
    SDE Payer Out 0 * Resource
    Initial Population Out 0 * Resource
    SDE Ethnicity Out 0 1 Resource
    Denominator Exclusions Out 0 * Resource
    SDE Race Out 0 1 Resource
    DataRequirements:
    Resource Type Resource Elements Valueset Name Valueset
    Patient(QICorePatient) ethnicity race
    Encounter(QICoreEncounter) type status status.value period Observation Services Observation Services
    Encounter(QICoreEncounter) type status status.value period Emergency Department Visit Emergency Department Visit
    Encounter(QICoreEncounter) type period status status.value hospitalizationPeriod encounter Encounter Inpatient Encounter Inpatient
    Condition(QICoreCondition) code Diabetes Diabetes
    MedicationAdministration(QICoreMedicationAdministration) medication status status.value effective Hypoglycemics Treatment Medications http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1196.394
    Observation(QICoreObservation) code effective status status.value value id id.value Glucose Lab Test Mass Per Volume http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1248.34
    Observation(QICoreObservation) code effective value status status.value id id.value Glucose Lab Test Mass Per Volume http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1248.34
    Coverage(QICoreCoverage) type period Payer Type Payer
    Direct Reference Codes:
    display code system
    Male M http://hl7.org/fhir/administrative-gender
    Female F http://hl7.org/fhir/administrative-gender
    Logic Definitions:
    Group Scoring Population Criteria Expression
    6501fe8dda013638e7b3dc0d Group scoring: ratio Measure scoring:

    Proportion

    Type:

    Outcome

    Rate Aggregation: None
    Improvement Notation:

    decrease

    Initial Population
    define "Initial Population":
      "Encounter with Existing Diabetes Diagnosis"
        union "Encounter with Hypoglycemic Medication"
        union "Encounter with Elevated Glucose Greater Than or Equal to 200"
    Denominator
    define "Denominator":
      "Initial Population"
    Denominator Exclusion
    define "Denominator Exclusions":
      "Encounter with First Glucose Greater Than or Equal to 1000"
    Numerator
    define "Numerator":
      "Encounter with Hyperglycemic Events"
    Measure Observation
    /**
     * 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)
      )
    Measure Observation
    /**
     * 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
          )
      )
    Library Name Name
    SupplementalDataElements SDE Sex
    define "SDE Sex":
      case
        when Patient.gender = 'male' then "M"
        when Patient.gender = 'female' then "F"
        else null
      end
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR SDE Sex
    define "SDE Sex":
      SDE."SDE Sex"
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Qualifying Encounter
    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'
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Encounter with Hospitalization Period
    /**
     * 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 )
        }
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Encounter with Existing Diabetes Diagnosis
    /**
     * 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 ["Condition": "Diabetes"] Diabetes
          such that ( QICoreCommon."ToPrevalenceInterval" ( Diabetes ) starts before end of Hospitalization.hospitalizationPeriod )
        return Hospitalization.encounter
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Encounter with Hypoglycemic Medication
    /**
     * 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 = 'completed'
          and HypoglycemicMed.status != 'not-done'
          and QICoreCommon."ToInterval" ( HypoglycemicMed.effective ) during Hospitalization.hospitalizationPeriod
        return Hospitalization.encounter
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Encounter with Elevated Glucose Greater Than or Equal to 200
    /**
     * 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 ["Observation": "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
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Initial Population
    define "Initial Population":
      "Encounter with Existing Diabetes Diagnosis"
        union "Encounter with Hypoglycemic Medication"
        union "Encounter with Elevated Glucose Greater Than or Equal to 200"
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Denominator
    define "Denominator":
      "Initial Population"
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Measurement Population
    define "Measurement Population":
      "Denominator"
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Days in Hospitalization
    /***/
    
    
    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)
        }
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Days with Glucose Results
    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 ( ["Observation": "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 ( ["Observation": "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 ( ["Observation": "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
                )
              }
          )
        }
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Days with Hyperglycemic Events
    /*# 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
        }
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Encounter with Hyperglycemic Events
    /***/
    
    
    define "Encounter with Hyperglycemic Events":
      "Days with Hyperglycemic Events" HyperglycemicEventDays
        where exists ( HyperglycemicEventDays.eligibleEventDays EligibleEventDay
            where EligibleEventDay.hasHyperglycemicEvent
        )
        return HyperglycemicEventDays.encounter
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Numerator
    define "Numerator":
      "Encounter with Hyperglycemic Events"
    Library Name Name
    SupplementalDataElements SDE Payer
    define "SDE Payer":
      [Coverage: type in "Payer Type"] Payer
        return {
          code: Payer.type,
          period: Payer.period
        }
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR SDE Payer
    define "SDE Payer":
      SDE."SDE Payer"
    Library Name Name
    SupplementalDataElements SDE Ethnicity
    define "SDE Ethnicity":
      Patient.ethnicity E
        return Tuple {
          codes: { E.ombCategory } union E.detailed,
          display: E.text
        }
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR SDE Ethnicity
    define "SDE Ethnicity":
      SDE."SDE Ethnicity"
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Glucose Greater Than or Equal to 1000 within 1 Hour Prior To and 6 Hours After Encounter Start
    define "Glucose Greater Than or Equal to 1000 within 1 Hour Prior To and 6 Hours After Encounter Start":
      from
        "Initial Population" InpatientHospitalization,
        ["Observation": "Glucose Lab Test Mass Per Volume"] GlucoseTest
        let HospitalizationInterval: CQMCommon."HospitalizationWithObservation" ( InpatientHospitalization ),
        GlucoseTestTime: QICoreCommon."Earliest" ( GlucoseTest.effective )
        where GlucoseTest.value as Quantity >= 1000 '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
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Glucose Tests Earlier Than Glucose Greater Than or Equal to 1000 within 1 Hour Prior To and 6 Hours After Encounter Start
    define "Glucose Tests Earlier Than Glucose Greater Than or Equal to 1000 within 1 Hour Prior To and 6 Hours After Encounter Start":
      from
        "Initial Population" InpatientHospitalization,
        "Glucose Greater Than or Equal to 1000 within 1 Hour Prior To and 6 Hours After Encounter Start" GlucoseResult1000,
        ["Observation": "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
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Initial Glucose Greater Than or Equal to 1000 within 1 Hour Prior To and 6 Hours After Encounter Start
    define "Initial Glucose Greater Than or Equal to 1000 within 1 Hour Prior To and 6 Hours After Encounter Start":
      "Glucose Greater Than or Equal to 1000 within 1 Hour Prior To and 6 Hours After Encounter Start" GlucoseResult1000
        where not ( GlucoseResult1000.id in "Glucose Tests Earlier Than Glucose Greater Than or Equal to 1000 within 1 Hour Prior To and 6 Hours After Encounter Start".id )
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Encounter with First Glucose Greater Than or Equal to 1000
    define "Encounter with First Glucose Greater Than or Equal to 1000":
      "Initial Population" InpatientHospitalization
        with "Initial Glucose Greater Than or Equal to 1000 within 1 Hour Prior To and 6 Hours After Encounter Start" FirstGlucoseResult
          such that FirstGlucoseResult.value as Quantity >= 1000 'mg/dL'
            and QICoreCommon."Earliest" ( FirstGlucoseResult.effective ) during Interval[( start of CQMCommon."HospitalizationWithObservation" ( InpatientHospitalization ) - 1 hour ), ( start of CQMCommon."HospitalizationWithObservation" ( InpatientHospitalization ) + 6 hours )]
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Denominator Exclusions
    define "Denominator Exclusions":
      "Encounter with First Glucose Greater Than or Equal to 1000"
    Library Name Name
    SupplementalDataElements SDE Race
    define "SDE Race":
      Patient.race R
        return Tuple {
          codes: R.ombCategory union R.detailed,
          display: R.text
        }
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR SDE Race
    define "SDE Race":
      SDE."SDE Race"
    Library Name Name
    CQMCommon HospitalizationWithObservation
    /*
    @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]
    Library Name Name
    QICoreCommon ToPrevalenceInterval
    /*
    @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 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
       (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]
    Library Name Name
    QICoreCommon Earliest
    /*
    @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
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Hospital Days Max 10
    /**
     * 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 }
      )]
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Days In Period
    /**
     * 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 )
        }
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Interval To Day Numbers
    /**
     * 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
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Denominator Observations
    /**
     * 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)
      )
    Library Name Name
    FHIRHelpers ToString
    define function ToString(value uri): value.value
    Library Name Name
    FHIRHelpers ToCode
    /*
    @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
            }
    Library Name Name
    HospitalHarmHyperglycemiainHospitalizedPatientsFHIR Numerator Observations
    /**
     * 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
          )
      )