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: Antidepressant Medication ManagementFHIR

Official URL: https://madie.cms.gov/Measure/AntidepressantMedicationManagementFHIR Version: 0.1.001
Draft as of 2024-07-09 Responsible: National Committee for Quality Assurance Computable Name: AntidepressantMedicationManagementFHIR
Other Identifiers: Short Name (use: usual, ), UUID:009a2432-6ee9-48d5-b32a-d727f847f8d2 (use: official, ), UUID:5f26d7bc-2d67-41a7-a66b-4a044f7d21e0 (use: official, ), Publisher (use: official, )

Copyright/Legal: This Physician Performance Measure (Measure) and related data specifications are owned and were developed by the National Committee for Quality Assurance (NCQA). NCQA is not responsible for any use of the Measure. NCQA makes no representations, warranties, or endorsement about the quality of any organization or physician that uses or reports performance measures and NCQA has no liability to anyone who relies on such measures or specifications. NCQA holds a copyright in the Measure. The Measure can be reproduced and distributed, without modification, for noncommercial purposes (e.g., use by healthcare providers in connection with their practices) without obtaining approval from NCQA. Commercial use is defined as the sale, licensing, or distribution of the Measure for commercial gain, or incorporation of the Measure into a product or service that is sold, licensed or distributed for commercial gain. All commercial uses or requests for modification must be approved by NCQA and are subject to a license at the discretion of NCQA. (C) 2012-2024 National Committee for Quality Assurance. All Rights Reserved. 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. NCQA disclaims all liability for use or accuracy of any third-party codes contained in the specifications. CPT(R) codes, descriptions and other data are copyright 2024. American Medical Association. All rights reserved. CPT is a trademark of the American Medical Association. Fee schedules, relative value units, conversion factors and/or related components are not assigned by the AMA, are not part of CPT, and the AMA is not recommending their use. The AMA does not directly or indirectly practice medicine or dispense medical services. The AMA assumes no liability for data contained or not contained herein. Applicable FARS/DFARS restrictions apply to government use. Some measure specifications contain coding from LOINC(R) (http://loinc.org). The LOINC table, LOINC codes, LOINC panels and form file, LOINC linguistic variants file, LOINC/RSNA Radiology Playbook, and LOINC/IEEE Medical Device Code Mapping Table are copyright 2004-2024 Regenstrief Institute, Inc. and the Logical Observation Identifiers Names and Codes (LOINC) Committee, and are available at no cost under the license at http://loinc.org/terms-of-use. This material contains SNOMED Clinical Terms(R) (SNOMED CT[R]) copyright 2004-2023 International Health Terminology Standards Development Organisation. ICD-10 copyright 2024 World Health Organization. All Rights Reserved. Some measures use RxNorm, a standardized nomenclature and coding for clinical drugs and drug delivery devices, which is made publicly available courtesy of the U.S. National Library of Medicine (NLM), National Institutes of Health, Department of Health and Human Services. NLM is not responsible for the measures and does not endorse or recommend this or any other product. “HL7” is the registered trademark of Health Level Seven International.

Percentage of patients 18 years of age and older who were treated with antidepressant medication, had a diagnosis of major depression, and who remained on an antidepressant medication treatment. Two rates are reported. a. Percentage of patients who remained on an antidepressant medication for at least 84 days (12 weeks). b. Percentage of patients who remained on an antidepressant medication for at least 180 days (6 months).

UNKNOWN

Title: Antidepressant Medication ManagementFHIR
Id: AntidepressantMedicationManagementFHIR
Version: 0.1.001
Url: Antidepressant Medication ManagementFHIR
short-name identifier:

CMS128FHIR

version-independent identifier:

urn:uuid:009a2432-6ee9-48d5-b32a-d727f847f8d2

version-specific identifier:

urn:uuid:5f26d7bc-2d67-41a7-a66b-4a044f7d21e0

publisher (CMS) identifier:

128FHIR

Effective Period: 2025-01-01..2025-12-31
Status: draft
Publisher: National Committee for Quality Assurance
Author: National Committee for Quality Assurance
Description:

Percentage of patients 18 years of age and older who were treated with antidepressant medication, had a diagnosis of major depression, and who remained on an antidepressant medication treatment. Two rates are reported. a. Percentage of patients who remained on an antidepressant medication for at least 84 days (12 weeks). b. Percentage of patients who remained on an antidepressant medication for at least 180 days (6 months).

Purpose:

UNKNOWN

Copyright:

This Physician Performance Measure (Measure) and related data specifications are owned and were developed by the National Committee for Quality Assurance (NCQA). NCQA is not responsible for any use of the Measure. NCQA makes no representations, warranties, or endorsement about the quality of any organization or physician that uses or reports performance measures and NCQA has no liability to anyone who relies on such measures or specifications. NCQA holds a copyright in the Measure. The Measure can be reproduced and distributed, without modification, for noncommercial purposes (e.g., use by healthcare providers in connection with their practices) without obtaining approval from NCQA. Commercial use is defined as the sale, licensing, or distribution of the Measure for commercial gain, or incorporation of the Measure into a product or service that is sold, licensed or distributed for commercial gain. All commercial uses or requests for modification must be approved by NCQA and are subject to a license at the discretion of NCQA. (C) 2012-2024 National Committee for Quality Assurance. All Rights Reserved. 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. NCQA disclaims all liability for use or accuracy of any third-party codes contained in the specifications. CPT(R) codes, descriptions and other data are copyright 2024. American Medical Association. All rights reserved. CPT is a trademark of the American Medical Association. Fee schedules, relative value units, conversion factors and/or related components are not assigned by the AMA, are not part of CPT, and the AMA is not recommending their use. The AMA does not directly or indirectly practice medicine or dispense medical services. The AMA assumes no liability for data contained or not contained herein. Applicable FARS/DFARS restrictions apply to government use. Some measure specifications contain coding from LOINC(R) (http://loinc.org). The LOINC table, LOINC codes, LOINC panels and form file, LOINC linguistic variants file, LOINC/RSNA Radiology Playbook, and LOINC/IEEE Medical Device Code Mapping Table are copyright 2004-2024 Regenstrief Institute, Inc. and the Logical Observation Identifiers Names and Codes (LOINC) Committee, and are available at no cost under the license at http://loinc.org/terms-of-use. This material contains SNOMED Clinical Terms(R) (SNOMED CT[R]) copyright 2004-2023 International Health Terminology Standards Development Organisation. ICD-10 copyright 2024 World Health Organization. All Rights Reserved. Some measures use RxNorm, a standardized nomenclature and coding for clinical drugs and drug delivery devices, which is made publicly available courtesy of the U.S. National Library of Medicine (NLM), National Institutes of Health, Department of Health and Human Services. NLM is not responsible for the measures and does not endorse or recommend this or any other product. “HL7” is the registered trademark of Health Level Seven International.

Disclaimer:

The 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 MEASURE 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].

Rationale:

Depression affects over 17 million adults in the U.S. (NIMH, 2021) and is estimated to affect nearly a quarter of adults in their lifetime (Burcusa & Iacono, 2007). Symptoms of depression include disturbances in appetite and sleep, anxiety, decreased concentration, and suicidal ideation (NAMI, 2017; Charbonneau et al., 2005). When left untreated, depression can have a dramatic effect on one’s quality of life, causing constant feelings of hopelessness, loss of interest in daily activities and in some cases suicidal ideation (SAMHSA, 2014). The American Psychiatric Association (APA) recommends use of antidepressant medication and behavioral therapies, such as psychotherapy, for the treatment and management of depression (APA, 2010). For the past 60 years, antidepressant medication has proven to be effective, especially for patients with more severe symptoms (Fournier et al., 2010). However, studies analyzing adherence to antidepressant medications found that prevalence of nonadherence was high, ranging from 13 percent to 55.7 percent (Sansone, 2012). Clinical guidelines for depression emphasize the importance of effective clinical management in increasing patients’ medication compliance, monitoring treatment effectiveness, and identifying and managing side effects. If pharmacological treatment is initiated, appropriate dosing and continuation of therapy through the acute and continuation phases decrease recurrence of symptoms. Thus, the evaluation of the duration of pharmacological treatment serves as an important indicator in understanding patient compliance with establishing and maintaining an effective medication regimen.

Clinical recommendation statement:

American Psychological Association (2019): - "For initial treatment of adult patients with depression, the panel recommends the following in the context of sharing decision-making with the patient when considering options: 1. That clinicians offer either psychotherapy or second-generation antidepressant. 2. If considering combined treatment, the panel recommends cognitive-behavioral therapy or interpersonal psychotherapy plus a second-generation antidepressant.” - “For initial treatment of older adult patients with depression, the panel recommends the following in the context of shared decision-making with the patient: 1. Either group life review treatment or Group Cognitive Behavioral Therapy (either alone or added to usual care) over no treatment 2. Combined pharmacotherapy and interpersonal psychotherapy (IPT) over IPT alone. Of note, while the study upon which this is based used nortriptyline, the panel recommends a second-generation antidepressant due to the reduced risk of side effects.” American Psychiatric Association (2010): - “An antidepressant medication is recommended as an initial treatment choice for patients with mild to moderate major depressive disorder [I: Recommended with substantial clinical confidence] and definitely should be provided for those with severe major depressive disorder unless electroconvulsive therapy (ECT) is planned [I: Recommended with substantial clinical confidence].” - "Patients should be given a realistic notion of what can be expected during the different phases of treatment, including the likely time course of symptom response and the importance of adherence for successful treatment and prophylaxis [I]." - "During the acute phase of treatment, patients should be carefully and systematically monitored on a regular basis to assess their response to pharmacotherapy, identify the emergence of side effects (e.g., gastrointestinal symptoms, sedation, insomnia, activation, changes in weight, and cardiovascular, neurological, anticholinergic, or sexual side effects), and assess patient safety [I]." - “During the continuation phase of treatment, the patient should be carefully monitored for signs of possible relapse [I: Recommended with substantial clinical confidence]. Systematic assessment of symptoms, side effects, adherence, and functional status is essential [I: Recommended with substantial clinical confidence], and may be facilitated through the use of clinician- and/or patient-administered rating scales [II: Recommended with moderate clinical confidence]. To reduce the risk of relapse, patients who have been treated successfully with antidepressant medications in the acute phase should continue treatment with these agents for 4–9 months [I: Recommended with substantial clinical confidence].” Department of Veterans Affairs, and Health Affairs, Department of Defense (2022): - “For patients with major depressive disorder (MDD), we suggest using a quantitative measure of depression severity in the initial treatment planning and to monitor treatment progress at regular intervals to guide shared treatment decision making.” [Weak For] - “In patients with MDD who achieve remission with antidepressant medication, we recommend continuation of antidepressants at the therapeutic dose for at least six months to decrease risk of relapse.” [Strong For] Department of Veterans Affairs, and Health Affairs, Department of Defense (2016): - ”In patients at high risk for recurrent depressive episodes and who are treated with pharmacotherapy, we recommend offering maintenance pharmacotherapy for at least 12 months and possibly indefinitely.” [Strong For] - “After initiation of therapy or a change in treatment, we recommend monitoring patients at least monthly until the patient achieves remission. At minimum, assessments should include a measure of symptoms, adherence to medication and psychotherapy, and emergence of adverse effects.” [Strong For] - “In patients with MDD who achieve remission with antidepressant medication, we recommend continuation of antidepressants at the therapeutic dose for at least six months to decrease risk of relapse.” [Strong For]

Guidance (Usage): To identify new treatment episodes for major depression, there must be a 105-day negative medication history (a period during which the patient was not taking antidepressant medication) prior to the dispensing event associated with the IPSD. This eCQM is a patient-based measure. This FHIR-based measure has been derived from the QDM-based measure: CMS128v13. 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).
Population Criteria:
6621259b0f0a9077c1d5b582
Initial Population: Patients 18 years of age and older as of the IPSD who were dispensed antidepressant medications during the Intake Period, and were diagnosed with major depression 60 days prior to, or 60 days after the dispensing event and had a visit 60 days prior to, or 60 days after the dispensing event
Denominator: Equals Initial Population
Denominator Exclusion: Exclude patients who are in hospice care for any part of the measurement period. Patients who were actively on an antidepressant medication in the 105 days prior to the IPSD.
Numerator: Numerator 1: Patients who have received antidepressant medication for at least 84 days (12 weeks) of continuous treatment beginning on the IPSD through 114 days after the IPSD (115 total days).
6621259b0f0a9077c1d5b583
Initial Population: None
Denominator: None
Denominator Exclusion: Exclude patients who are in hospice care for any part of the measurement period. Patients who were actively on an antidepressant medication in the 105 days prior to the IPSD.
Numerator: Numerator 2: Patients who have received antidepressant medications for at least 180 days (6 months) of continuous treatment beginning on the IPSD through 231 days after the IPSD (232 total days).
Libraries:
AntidepressantMedicationManagementFHIR
Terminology and Other Dependencies:
  • Library/Status|1.8.000
  • Library/CumulativeMedicationDuration|4.1.000
  • Library/FHIRHelpers|4.4.000
  • Library/QICoreCommon|2.1.000
  • Library/Hospice|6.12.000
  • Library/CQMCommon|2.2.000
  • SNOMED CT (all versions)
  • Observation Category Codes
  • Logical Observation Identifiers, Names and Codes (LOINC)
  • Antidepressant Medication
  • Major Depression
  • Office Visit
  • Preventive Care Services - Established Office Visit, 18 and Up
  • Preventive Care Services-Initial Office Visit, 18 and Up
  • Home Healthcare Services
  • Annual Wellness Visit
  • Nursing Facility Visit
  • Psych Visit - Diagnostic Evaluation
  • Psych Visit - Psychotherapy
  • Telephone Visits
  • http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.464.1003.101.12.1089
  • Encounter Inpatient
  • http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.464.1003.1003
  • Hospice Care Ambulatory
  • http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.464.1003.1165
  • Parameters:
    name use min max type
    ErrorLevel In 0 1 string
    Measurement Period In 0 1 Period
    Denominator Out 0 1 boolean
    Numerator 1 Out 0 1 boolean
    Numerator 2 Out 0 1 boolean
    Initial Population Out 0 1 boolean
    Denominator Exclusions Out 0 1 boolean
    DataRequirements:
    Resource Type Resource Elements Valueset Name Valueset
    Patient(QICorePatient)
    MedicationDispense(QICoreMedicationDispense) medication status status.value dosageInstruction daysSupply whenHandedOver whenHandedOver.value whenPrepared whenPrepared.value quantity quantity.value Antidepressant Medication Antidepressant Medication
    Condition(QICoreCondition) code Major Depression Major Depression
    Condition(QICoreCondition) code Hospice Diagnosis http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.464.1003.1165
    Encounter(QICoreEncounter) type status status.value period Office Visit Office Visit
    Encounter(QICoreEncounter) type status status.value period Preventive Care Services Established Office Visit, 18 and Up Preventive Care Services - Established Office Visit, 18 and Up
    Encounter(QICoreEncounter) type status status.value period Preventive Care Services Initial Office Visit, 18 and Up Preventive Care Services-Initial Office Visit, 18 and Up
    Encounter(QICoreEncounter) type status status.value period Home Healthcare Services Home Healthcare Services
    Encounter(QICoreEncounter) type status status.value period Annual Wellness Visit Annual Wellness Visit
    Encounter(QICoreEncounter) type status status.value period Nursing Facility Visit Nursing Facility Visit
    Encounter(QICoreEncounter) type status status.value period Psych Visit Diagnostic Evaluation Psych Visit - Diagnostic Evaluation
    Encounter(QICoreEncounter) type status status.value period Psych Visit Psychotherapy Psych Visit - Psychotherapy
    Encounter(QICoreEncounter) type status status.value period Telephone Visits Telephone Visits
    Encounter(QICoreEncounter) type status status.value period Virtual Encounter http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.464.1003.101.12.1089
    Encounter(QICoreEncounter) type hospitalization hospitalization.dischargeDisposition period status status.value Encounter Inpatient Encounter Inpatient
    Encounter(QICoreEncounter) type period status status.value Hospice Encounter http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.464.1003.1003
    Observation(QICoreObservation) code value effective status status.value category
    ServiceRequest(QICoreServiceRequest) code authoredOn authoredOn.value status status.value intent intent.value Hospice Care Ambulatory Hospice Care Ambulatory
    Procedure(QICoreProcedure) code performed status status.value Hospice Care Ambulatory Hospice Care Ambulatory
    Medication(QICoreMedication) id
    MedicationRequest(QICoreMedicationRequest) medication.reference status status.value intent intent.value dosageInstruction dispenseRequest dispenseRequest.expectedSupplyDuration dispenseRequest.quantity dispenseRequest.numberOfRepeatsAllowed dispenseRequest.numberOfRepeatsAllowed.value authoredOn authoredOn.value dispenseRequest.validityPeriod
    MedicationRequest(QICoreMedicationRequest) medication status status.value intent intent.value dosageInstruction dispenseRequest dispenseRequest.expectedSupplyDuration dispenseRequest.quantity dispenseRequest.numberOfRepeatsAllowed dispenseRequest.numberOfRepeatsAllowed.value authoredOn authoredOn.value dispenseRequest.validityPeriod Antidepressant Medication Antidepressant Medication
    Direct Reference Codes:
    display code system
    Discharge to home for hospice care (procedure) 428361000124107 http://snomed.info/sct
    Discharge to healthcare facility for hospice care (procedure) 428371000124100 http://snomed.info/sct
    survey survey http://terminology.hl7.org/CodeSystem/observation-category
    Yes (qualifier value) 373066001 http://snomed.info/sct
    Hospice care [Minimum Data Set] 45755-6 http://loinc.org
    Logic Definitions:
    Group Scoring Population Criteria Expression
    6621259b0f0a9077c1d5b582 Group scoring: proportion
    Type:

    Process

    Rate Aggregation: None
    Improvement Notation:

    increase

    Initial Population
    define "Initial Population":
      AgeInYearsAt(date from "IPSD") >= 18
        and "Has IPSD and Major Depression Diagnosis"
        and exists "Qualifying Encounters"
    Denominator
    define "Denominator":
      "Initial Population"
    Denominator Exclusion
    define "Denominator Exclusions":
      Hospice."Has Hospice Services"
        or exists ( ( ( ( [MedicationRequest: "Antidepressant Medication"] ).isMedicationActive ( ) ) ActiveAntidepressant
              where "IPSD" is not null
                and CQMCommon.ToDateInterval ( ActiveAntidepressant.medicationRequestPeriod ( ) ) overlaps Interval["IPSD" - 105 days, "IPSD" )
          )
        )
    Numerator
    define "Numerator 1":
      "Cumulative Medication Duration Greater Than or Equal to 84 Days"
    6621259b0f0a9077c1d5b583 Group scoring: proportion
    Type:

    Process

    Rate Aggregation: None
    Improvement Notation:

    Increased score indicates improvement

    Initial Population
    define "Initial Population":
      AgeInYearsAt(date from "IPSD") >= 18
        and "Has IPSD and Major Depression Diagnosis"
        and exists "Qualifying Encounters"
    Denominator
    define "Denominator":
      "Initial Population"
    Denominator Exclusion
    define "Denominator Exclusions":
      Hospice."Has Hospice Services"
        or exists ( ( ( ( [MedicationRequest: "Antidepressant Medication"] ).isMedicationActive ( ) ) ActiveAntidepressant
              where "IPSD" is not null
                and CQMCommon.ToDateInterval ( ActiveAntidepressant.medicationRequestPeriod ( ) ) overlaps Interval["IPSD" - 105 days, "IPSD" )
          )
        )
    Numerator
    define "Numerator 2":
      "Cumulative Medication Duration Greater Than or Equal to 180 Days"
    Library Name Name
    AntidepressantMedicationManagementFHIR May 1 of the Year Prior to the Measurement Period
    define "May 1 of the Year Prior to the Measurement Period":
      DateTime((year from start of "Measurement Period" - 1), 5, 1, 0, 0, 0, 0, 0)
    Library Name Name
    AntidepressantMedicationManagementFHIR April 30 of the Measurement Period
    define "April 30 of the Measurement Period":
      DateTime((year from start of "Measurement Period"), 4, 30, 23, 59, 59, 0, 0)
    Library Name Name
    AntidepressantMedicationManagementFHIR Intake Period
    define "Intake Period":
      Interval["May 1 of the Year Prior to the Measurement Period", "April 30 of the Measurement Period"]
    Library Name Name
    AntidepressantMedicationManagementFHIR Earliest Antidepressant Dispensed During Intake Period
    define "Earliest Antidepressant Dispensed During Intake Period":
      First((([MedicationDispense: "Antidepressant Medication"]).isMedicationDispensed()) Antidepressant
          where start of Antidepressant.medicationDispensePeriod() in day of "Intake Period"
          return {
            AntidepressantDate: date from start of Antidepressant.medicationDispensePeriod()
          }
          sort by AntidepressantDate
      ).AntidepressantDate
    Library Name Name
    AntidepressantMedicationManagementFHIR IPSD
    define "IPSD":
      "Earliest Antidepressant Dispensed During Intake Period"
    Library Name Name
    AntidepressantMedicationManagementFHIR Has IPSD and Major Depression Diagnosis
    define "Has IPSD and Major Depression Diagnosis":
      exists ( [Condition: "Major Depression"] MajorDepression
          where "IPSD" is not null
            and date from start of MajorDepression.prevalenceInterval ( ) within 60 days of "IPSD"
      )
    Library Name Name
    AntidepressantMedicationManagementFHIR Qualifying Encounters
    define "Qualifying Encounters":
      ( ( [Encounter: "Office Visit"]
          union [Encounter: "Preventive Care Services Established Office Visit, 18 and Up"]
          union [Encounter: "Preventive Care Services Initial Office Visit, 18 and Up"]
          union [Encounter: "Home Healthcare Services"]
          union [Encounter: "Annual Wellness Visit"]
          union [Encounter: "Nursing Facility Visit"]
          union [Encounter: "Psych Visit Diagnostic Evaluation"]
          union [Encounter: "Psych Visit Psychotherapy"]
          union [Encounter: "Telephone Visits"]
          union [Encounter: "Virtual Encounter"]
      ).isEncounterPerformed ( ) ) ValidEncounter
        where date from start of ValidEncounter.period.toInterval ( ) within 60 days of "IPSD"
    Library Name Name
    AntidepressantMedicationManagementFHIR Initial Population
    define "Initial Population":
      AgeInYearsAt(date from "IPSD") >= 18
        and "Has IPSD and Major Depression Diagnosis"
        and exists "Qualifying Encounters"
    Library Name Name
    AntidepressantMedicationManagementFHIR Denominator
    define "Denominator":
      "Initial Population"
    Library Name Name
    AntidepressantMedicationManagementFHIR Antidepressant Medication Period Between IPSD and 114 Days After IPSD
    define "Antidepressant Medication Period Between IPSD and 114 Days After IPSD":
      ( ( [MedicationDispense: "Antidepressant Medication"] ).isMedicationDispensed ( ) ) Antidepressant
        let MedicationPeriod: Antidepressant.medicationDispensePeriod ( )
        return MedicationPeriod
          intersect Interval["IPSD", "IPSD" + 114 days]
    Library Name Name
    AntidepressantMedicationManagementFHIR Cumulative Medication Duration Greater Than or Equal to 84 Days
    define "Cumulative Medication Duration Greater Than or Equal to 84 Days":
      ( "Antidepressant Medication Period Between IPSD and 114 Days After IPSD".cumulativeDuration ( ) ) >= 84
    Library Name Name
    AntidepressantMedicationManagementFHIR Numerator 1
    define "Numerator 1":
      "Cumulative Medication Duration Greater Than or Equal to 84 Days"
    Library Name Name
    AntidepressantMedicationManagementFHIR Antidepressant Medication Period Between IPSD and 231 Days After IPSD
    define "Antidepressant Medication Period Between IPSD and 231 Days After IPSD":
      ( ( [MedicationDispense: "Antidepressant Medication"] ).isMedicationDispensed ( ) ) Antidepressant
        let MedicationPeriod: Antidepressant.medicationDispensePeriod ( )
        return MedicationPeriod
          intersect Interval["IPSD", "IPSD" + 231 days]
    Library Name Name
    AntidepressantMedicationManagementFHIR Cumulative Medication Duration Greater Than or Equal to 180 Days
    define "Cumulative Medication Duration Greater Than or Equal to 180 Days":
      ( "Antidepressant Medication Period Between IPSD and 231 Days After IPSD".cumulativeDuration ( ) ) >= 180
    Library Name Name
    AntidepressantMedicationManagementFHIR Numerator 2
    define "Numerator 2":
      "Cumulative Medication Duration Greater Than or Equal to 180 Days"
    Library Name Name
    Hospice Has Hospice Services
    define "Has Hospice Services":
      exists ((([Encounter: "Encounter Inpatient"]).isEncounterPerformed()) InpatientEncounter
          where (InpatientEncounter.hospitalization.dischargeDisposition ~ "Discharge to home for hospice care (procedure)"
              or InpatientEncounter.hospitalization.dischargeDisposition ~ "Discharge to healthcare facility for hospice care (procedure)"
          )
            and InpatientEncounter.period.toInterval() ends during day of "Measurement Period"
      )
        or exists ((([Encounter: "Hospice Encounter"]).isEncounterPerformed()) HospiceEncounter
            where HospiceEncounter.period.toInterval() overlaps day of "Measurement Period"
        )
        or exists ((([Observation: "Hospice care [Minimum Data Set]"]).isAssessmentPerformed()) HospiceAssessment
            where HospiceAssessment.value ~ "Yes (qualifier value)"
              and HospiceAssessment.effective.toInterval() overlaps day of "Measurement Period"
        )
        or exists ((([ServiceRequest: "Hospice Care Ambulatory"]).isInterventionOrder()) HospiceOrder
            where HospiceOrder.authoredOn.toInterval() during day of "Measurement Period"
            // and HospiceOrder.doNotPerform is not true
            // https://oncprojectracking.healthit.gov/support/browse/CQLIT-447
        )
        or exists ((([Procedure: "Hospice Care Ambulatory"]).isInterventionPerformed()) HospicePerformed
            where HospicePerformed.performed.toInterval() overlaps day of "Measurement Period"
        )
        or exists (([Condition: "Hospice Diagnosis"]) HospiceCareDiagnosis
            where HospiceCareDiagnosis.prevalenceInterval() overlaps day of "Measurement Period"
        )
    Library Name Name
    AntidepressantMedicationManagementFHIR Denominator Exclusions
    define "Denominator Exclusions":
      Hospice."Has Hospice Services"
        or exists ( ( ( ( [MedicationRequest: "Antidepressant Medication"] ).isMedicationActive ( ) ) ActiveAntidepressant
              where "IPSD" is not null
                and CQMCommon.ToDateInterval ( ActiveAntidepressant.medicationRequestPeriod ( ) ) overlaps Interval["IPSD" - 105 days, "IPSD" )
          )
        )
    Library Name Name
    Status isMedicationDispensed
    //Medication, Dispensed
    define fluent function isMedicationDispensed(Med List<MedicationDispense>):
      Med M
        where M.status in { 'completed', 'in-progress', 'on-hold' }
    Library Name Name
    CumulativeMedicationDuration medicationDispensePeriod
    /*
    Calculates Medication Period for a given MedicationDispense
    MedicationDispense instances provided to this function are expected
    to conform to the [TODO: MMEMedicationDispense](http://build.fhir.org/ig/cqframework/opioid-mme-r4/StructureDefinition-mmemedicationdispense.html)
    profile, which expects:
    * 1 and only 1 dosageInstruction, multiple dosageInstruction elements will result in an error
    * 1 and only 1 doseAndRate, multiple doseAndRate elements will result in an error
    * 1 timing with 1 repeat, missing timing or repeat elements will result in a null
    * frequency, frequencyMax, defaulting to 1
    * period, periodUnit, defaulting to 1 'd'
    * timeOfDay
    * doseQuantity or doseRange, missing doseQuantity and doseRange will result in a null
    * whenHandedOver or whenPrepared, if missing both whenHandedOver and whenPrepared will result in a null
    Note that MedicationDispense status is not considered by this calculation, as the
    list of MedicationDispense instances provided to this function should already have
    considered appropriate statuses, depending on the use case, typically `completed`,
    especially since whenHandedOver would be expected to be present for a completed
    MedicationDispense.
    Note also that the dosage information recorded in a dispense is expected to be a copy of the
    dispense information from the related medication request. As such, the boundsPeriod would be expected
    to cover the entire range, and should _not_ be used for timing of the event.
    There is also active discussion in the Pharmacy WG about what date should be used if whenPrepared/whenHandedOver is not present.
    This may take the form of an "original creation date", but may also be a "status change date" for dispense events that are updating
    status of an existing dispense. That discussion is ongoing, so until that is resolved, this logic will return
    null if whenPrepared/whenHandedOver are not available.
    */
    define fluent function medicationDispensePeriod(Dispense "MedicationDispense"):
      Dispense D
        let
          dosage: singleton from D.dosageInstruction,
          doseAndRate: singleton from dosage.doseAndRate,
          timing: dosage.timing,
          frequency: Coalesce(timing.repeat.frequencyMax, timing.repeat.frequency),
          period: Quantity(timing.repeat.period, timing.repeat.periodUnit),
          doseRange: doseAndRate.dose,
          doseQuantity: doseAndRate.dose,
          dose: Coalesce(end of doseRange, doseQuantity),
          daysSupply: (convert D.daysSupply to days).value,
          dosesPerDay: Coalesce(ToDaily(frequency, period), Count(timing.repeat.timeOfDay), 1.0),
          startDate:
            Coalesce(
              date from D.whenHandedOver,
              date from D.whenPrepared
            ),
          totalDaysSupplied: Coalesce(daysSupply, D.quantity.value / (dose.value * dosesPerDay))
        return
          if startDate is not null and totalDaysSupplied is not null then
            Interval[startDate, startDate + Quantity(totalDaysSupplied - 1, 'day')]
          else
            null
    Library Name Name
    CumulativeMedicationDuration Quantity
    /**********************************************************************/
    /* Functions in this region are copied from opioid-mme-r4             */
    /**********************************************************************/
    
    define function Quantity(value Decimal, unit String):
      if value is not null then
        System.Quantity { value: value, unit: unit }
      else
        null
    Library Name Name
    CumulativeMedicationDuration ToDaily
    /*
     Goal is to get to number of days
     Two broad approaches to the calculation:
      1) Based on supply and frequency, calculate the number of expected days the medication will cover/has covered
      2) Based on relevant period, determine a covered interval and calculate the length of that interval in days
    This topic covers several use cases and illustrates how to calculate Cumulative
    Medication Duration for each type of medication resource using the supply and
    frequency approach.
    */
    
    /*
      For the first approach, we need to get from frequency to a frequency/day
      So we define ToDaily
    */
    
    /*
      Calculates daily frequency given frequency within a period
    */
    define function ToDaily(frequency System.Integer, period System.Quantity):
      case period.unit
        when 'h' then frequency * (24.0 / period.value)
        when 'min' then frequency * (24.0 / period.value) * 60
        when 's' then frequency * (24.0 / period.value) * 60 * 60
        when 'd' then frequency * (24.0 / period.value) / 24
        when 'wk' then frequency * (24.0 / period.value) / (24 * 7)
        when 'mo' then frequency * (24.0 / period.value) / (24 * 30) /* assuming 30 days in month */
        when 'a' then frequency * (24.0 / period.value) / (24 * 365) /* assuming 365 days in year */
        when 'hour' then frequency * (24.0 / period.value)
        when 'minute' then frequency * (24.0 / period.value) * 60
        when 'second' then frequency * (24.0 / period.value) * 60 * 60
        when 'day' then frequency * (24.0 / period.value) / 24
        when 'week' then frequency * (24.0 / period.value) / (24 * 7)
        when 'month' then frequency * (24.0 / period.value) / (24 * 30) /* assuming 30 days in month */
        when 'year' then frequency * (24.0 / period.value) / (24 * 365) /* assuming 365 days in year */
        when 'hours' then frequency * (24.0 / period.value)
        when 'minutes' then frequency * (24.0 / period.value) * 60
        when 'seconds' then frequency * (24.0 / period.value) * 60 * 60
        when 'days' then frequency * (24.0 / period.value) / 24
        when 'weeks' then frequency * (24.0 / period.value) / (24 * 7)
        when 'months' then frequency * (24.0 / period.value) / (24 * 30) /* assuming 30 days in month */
        when 'years' then frequency * (24.0 / period.value) / (24 * 365) /* assuming 365 days in year */
        else Message(null, true, 'CMDLogic.ToDaily.UnknownUnit', ErrorLevel, 'Unknown unit ' & period.unit)
      end
    Library Name Name
    QICoreCommon prevalenceInterval
    /*
    @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.
    */
    define fluent function prevalenceInterval(condition Condition):
    if condition.clinicalStatus ~ "active"
      or condition.clinicalStatus ~ "recurrence"
      or condition.clinicalStatus ~ "relapse" then
      Interval[start of condition.onset.toInterval(), end of condition.abatementInterval()]
    else
        (end of condition.abatementInterval()) abatementDate
        return if abatementDate is null then
          Interval[start of condition.onset.toInterval(), abatementDate)
        else
          Interval[start of condition.onset.toInterval(), abatementDate]
    Library Name Name
    Status isEncounterPerformed
    //Encounter, Performed
    //General usage unless required otherwise by measure intent (e.g., follow-up encounters)
    define fluent function isEncounterPerformed(Enc List<Encounter>):
      Enc E
        where E.status in {'finished', 'arrived', 'triaged', 'in-progress', 'onleave'}
    Library Name Name
    QICoreCommon toInterval
    /*
    @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
    Library Name Name
    CumulativeMedicationDuration cumulativeDuration
    /*
    Now that we have functions for determining the medication period for individual
    prescriptions, administrations, and dispenses, we can combine those using
    an overall cumulative medication duration calculation.
    There are two broad approaches to calculating cumulative duration, one that _collapses_
    overlapping intervals so that calculations are not duplicated, and one that _rolls out_
    overlapping intervals so that the durations are laid end-to-end.
    First, we define a function that simply calculates CumulativeDuration of a set of
    intervals:
    */
    define fluent function cumulativeDuration(Intervals List<Interval<Date>>):
       if Intervals is not null then ( Sum((collapse Intervals per day)X
            return all(difference in days between start of X and 
              end of X
            )+ 1
        )
      ) 
        else null
    Library Name Name
    Status isAssessmentPerformed
    //This library contains functions that are based on QDM 5.6 to QICore 4.1.1 March 2023 (https://github.com/cqframework/CQL-Formatting-and-Usage-Wiki/wiki/Authoring-Patterns---QICore-v4.1.1). The functions may appear similar to some QICoreCommon functions but different in that they have constraints that are relevant for measures authored by NCQA.
    
    //Assessment, Performed
    define fluent function isAssessmentPerformed(Obs List<Observation>):
      Obs O
        where O.status in { 'final', 'amended', 'corrected' }
              and exists ( O.category ObservationCategory
              where ( ObservationCategory ) ~ "survey"
          )
    Library Name Name
    FHIRHelpers ToConcept
    /*
    @description: Converts the given FHIR [CodeableConcept](https://hl7.org/fhir/datatypes.html#CodeableConcept) value to a CQL Concept.
    */
    define function ToConcept(concept FHIR.CodeableConcept):
        if concept is null then
            null
        else
            System.Concept {
                codes: concept.coding C return ToCode(C),
                display: concept.text.value
            }
    Library Name Name
    Status isInterventionOrder
    //Intervention, Order: active and completed only    
    define fluent function isInterventionOrder(ServiceRequest List<ServiceRequest>):
      ServiceRequest S
        where S.status in { 'active', 'completed' }
          and S.intent = 'order'
    Library Name Name
    Status isInterventionPerformed
    //Intervention, Performed
    define fluent function isInterventionPerformed(Proc List<Procedure>):
      Proc P
        where P.status ~ 'completed'
    Library Name Name
    Status isMedicationActive
    //Medication, Active
    define fluent function isMedicationActive(MedicationRequest List<MedicationRequest>):
      MedicationRequest M
        where M.status = 'active'
          and M.intent = 'order'
    Library Name Name
    CQMCommon ToDateInterval
    /*
    @description: Returns an interval of date values extracted from the input interval of date-time values
    @comment: This function returns an interval constructed using the `date from` extractor on the start
    and end values of the input date-time interval. Note that using a precision specifier such as `day of`
    as part of a timing phrase is preferred to communicate intent to perform day-level comparison, as well
    as for general readability.
    */
    define function "ToDateInterval"(period Interval<DateTime>):
      Interval[date from start of period, date from end of period]
    Library Name Name
    CumulativeMedicationDuration medicationRequestPeriod
    define fluent function medicationRequestPeriod(Request "MedicationRequest"):
      Request R
        let
          dosage: singleton from R.dosageInstruction,
          doseAndRate: singleton from dosage.doseAndRate,
          timing: dosage.timing,
          frequency: Coalesce(timing.repeat.frequencyMax, timing.repeat.frequency),
          period: Quantity(timing.repeat.period, timing.repeat.periodUnit),
          doseRange: doseAndRate.dose,
          doseQuantity: doseAndRate.dose,
          dose: Coalesce(end of doseRange, doseQuantity),
          dosesPerDay: Coalesce(ToDaily(frequency, period), Count(timing.repeat.timeOfDay), 1.0),
          boundsPeriod: timing.repeat.bounds as Interval<DateTime>,
          daysSupply: (convert R.dispenseRequest.expectedSupplyDuration to days).value,
          quantity: R.dispenseRequest.quantity,
          refills: Coalesce(R.dispenseRequest.numberOfRepeatsAllowed, 0),
          startDate:
            Coalesce(
              date from start of boundsPeriod,
              date from R.authoredOn,
              date from start of R.dispenseRequest.validityPeriod
            ),
          totalDaysSupplied: Coalesce(daysSupply, quantity.value / (dose.value * dosesPerDay)) * (1 + refills)
        return
          if startDate is not null and totalDaysSupplied is not null then
            Interval[startDate, startDate + Quantity(totalDaysSupplied - 1, 'day') ]
          else if startDate is not null and boundsPeriod."high" is not null then
            Interval[startDate, date from end of boundsPeriod]
          else
            null