PATH MER Indicators
0.1.0 - STU1 International flag

PATH MER Indicators, published by PATH. This is not an authorized publication; it is the continuous build for version 0.1.0). This version is based on the current content of https://github.com/PATH-Global-Health/MERindicators and changes regularly. See the Directory of published versions

Example Bundle: KEMRBundle

Bundle KEMRBundle of type transaction


Entry 1 - fullUrl = https://path-global-health.github.io/MERindicators/CodeSystem/CIEL

Request:

PUT CodeSystem/CIEL

Resource CodeSystem:

This case-insensitive code system https://openconceptlab.org/orgs/CIEL/sources/CIEL defines the following codes:

CodeDisplay
1065 YES
1066 NO
1067 Unknown
1434 Currently pregnant
138405 Human immunodeficiency virus (HIV) disease
160119 CURRENTLY TAKING ARV
116128 Malaria
160540 Method of enrollment
160542 Outpatient department
1193 CURRENT DRUGS USED
5096 RETURN VISIT DATE
164384AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Treatment end date
164384 Treatment end date
160104 Efavirenz / Lamivudine / Stavudine
160105 Efavirenz / Stavudine / Zidovudine
160124 Efavirenz / Lamivudine / Zidovudine
161361 efavirenz / lamivudine / tenofovir disoproxil
161363 lamivudine / stavudine
161364 Lamivudine / tenofovir disoproxil
1652 Lamivudine / nevirapine / zidovudine
5424 Other antiretroviral drug
5811 Unknown antiretroviral drug
630 Lamivudine / zidovudine
103166 Abacavir / lamivudine
70056 Abacavir
71647 Atazanavir
74807 Didanosine
75523 Efavirenz
75628 Efavirenz
77995 Indinavir
78643 Lamivudine
79040 Lopinavir
792 Lamivudine / nevirapine / stavudine
794 Lopinavir / ritonavir
80487 Nelfinavir
80586 Nevirapine
83412 Ritonavir
84309 Stavudine
84795 Tenofovir
86663 Zidovudine
01234 Tenofovir / Lamivudine / Dolutegravir


Entry 2 - fullUrl = https://path-global-health.github.io/MERindicators/CodeSystem/EnrollmentMethods

Request:

PUT CodeSystem/EnrollmentMethods

Resource CodeSystem:

This code system https://path-global-health.github.io/MERindicators/CodeSystem/EnrollmentMethods defines the following codes:

CodeDisplay
159938AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA HBTC
160539AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA VCT Site
159937AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA MCH
160536AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA IPD-Adult
160537AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA IPD-Child
160541AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA TB Clinic
160542AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA OPD
162050AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA CCC
160551AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Self Test
5622AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Other(eg STI)


Entry 3 - fullUrl = https://path-global-health.github.io/MERindicators/CodeSystem/OpenHIE

Request:

PUT CodeSystem/OpenHIE

Resource CodeSystem:

This case-insensitive code system https://path-global-health.github.io/MERindicators/CodeSystem/OpenHIE defines the following codes:

CodeDisplay
cohort cohort
432101000124108 History of antiretroviral therapy (situation)


Entry 4 - fullUrl = https://path-global-health.github.io/MERindicators/ValueSet/OnARV

Request:

PUT ValueSet/OnARV

Resource ValueSet:

This value set includes codes based on the following rules:


Entry 5 - fullUrl = https://path-global-health.github.io/MERindicators/ValueSet/Pregnant

Request:

PUT ValueSet/Pregnant

Resource ValueSet:

This value set includes codes based on the following rules:


Entry 6 - fullUrl = https://path-global-health.github.io/MERindicators/ValueSet/SyntheaHIVMedications

Request:

PUT ValueSet/SyntheaHIVMedications

Resource ValueSet:

  • Include these codes as defined in http://www.nlm.nih.gov/research/umls/rxnorm
    CodeDisplay
    199663zidovudine 300 MG Oral Tablet
    284988didanosine 400 MG Delayed Release Oral Capsule
    313760zalcitabine 0.75 MG Oral Tablet
    313110stavudine 40 MG Oral Capsule
    349491lamivudine 300 MG Oral Tablet
    200082lamivudine 150 MG / zidovudine 300 MG Oral Tablet
    310988indinavir 400 MG Oral Capsule
    859863saquinavir mesylate 500 MG Oral Tablet
    317150ritonavir 100 MG Oral Capsule
    403978nelfinavir 625 MG Oral Tablet
    349477efavirenz 600 MG Oral Tablet
    597730lopinavir 200 MG / ritonavir 50 MG Oral Tablet
    349251tenofovir disoproxil fumarate 300 MG Oral Tablet
    403875emtricitabine 200 MG Oral Capsule
    476556emtricitabine 200 MG / tenofovir disoproxil fumarate 300 MG Oral Tablet
    1147334emtricitabine 200 MG / rilpivirine 25 MG / tenofovir disoproxil fumarate 300 MG Oral Tablet
    643066efavirenz 600 MG / emtricitabine 200 MG / tenofovir disoproxil fumarate 300 MG Oral Tablet
    1306292cobicistat 150 MG / elvitegravir 150 MG / emtricitabine 200 MG / tenofovir disoproxil fumarate 300 MG Oral Tablet
    744842raltegravir 400 MG Oral Tablet
    1433873dolutegravir 50 MG Oral Tablet
    402109fosamprenavir 700 MG Oral Tablet
    664741atazanavir 300 MG Oral Capsule
    1359269darunavir 800 MG Oral Tablet
    2003249lamivudine 300 MG / tenofovir disoproxil fumarate 300 MG Oral Tablet
    1747691emtricitabine 200 MG / tenofovir alafenamide 25 MG Oral Table
    1999667bictegravir 50 MG / emtricitabine 200 MG / tenofovir alafenamide 25 MG Oral Tablet
    1721613cobicistat 150 MG / elvitegravir 150 MG / emtricitabine 200 MG / tenofovir alafenamide 10 MG Oral Tablet
    2122519dolutegravir 50 MG / lamivudine 300 MG Oral Tablet


Entry 7 - fullUrl = https://path-global-health.github.io/MERindicators/ValueSet/CIELHIVMedications

Request:

PUT ValueSet/CIELHIVMedications

Resource ValueSet:


Entry 8 - fullUrl = https://path-global-health.github.io/MERindicators/ValueSet/EnrollmentMethodsforHIVProgram

Request:

PUT ValueSet/EnrollmentMethodsforHIVProgram

Resource ValueSet:


Entry 9 - fullUrl = https://path-global-health.github.io/MERindicators/Library/FHIRCommon

Request:

PUT Library/FHIRCommon

Resource Library:

Contents

text/cql

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

using FHIR version '4.0.1'

include FHIRHelpers version '4.0.1'

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

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

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

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

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

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

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

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

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

context Patient

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


Entry 10 - fullUrl = https://path-global-health.github.io/MERindicators/Library/FHIRHelpers

Request:

PUT Library/FHIRHelpers

Resource Library:

Contents

text/cql

library FHIRHelpers version '4.0.1'

using FHIR version '4.0.1'

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

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

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

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

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

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

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

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

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


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


Entry 11 - fullUrl = https://path-global-health.github.io/MERindicators/Library/Debug

Request:

PUT Library/Debug

Resource Library:

Contents

text/cql

library Debug version '0.1.0'

using FHIR version '4.0.1'

include FHIRHelpers version '4.0.1'
include FHIRCommon version '4.0.1' called FC
include KenyaEMRConcepts called Cx
include KenyaEMRStratifiers called Stratifiers


// Provide a default interval or period-based tests will fail when evaluating CQL against test cases
// Need DateTime eg @2014-01-25T not Date, eg not this: @2014-01-25
// The $evaluate-measure operation's parameters 'periodStart' and 'periodEnd' override this in any case
parameter "Measurement Period" Interval<DateTime> default Interval[@1990-01-01T, @2023-12-31T]


// Start with the patient and traverse their clinical resources
context Patient



Entry 12 - fullUrl = https://path-global-health.github.io/MERindicators/Library/KenyaEMRConcepts

Request:

PUT Library/KenyaEMRConcepts

Resource Library:

Contents

text/cql

library KenyaEMRConcepts version '0.1.0'

using FHIR version '4.0.1'

include FHIRHelpers version '4.0.1'
include FHIRCommon version '4.0.1' called FC

// codesystems
codesystem "SNOMED-CT": 'http://snomed.info/sct'
codesystem "LOINC": 'http://loinc.org'
codesystem "RxNorm": 'http://www.nlm.nih.gov/research/umls/rxnorm'

// local codesystems
codesystem "CIEL": 'https://openconceptlab.org/orgs/CIEL/sources/CIEL'
codesystem "OpenHIE": 'https://openhie.org'

// FHIR CS and VS
valueset "HL7 Administrative Gender": 'http://hl7.org/fhir/ValueSet/administrative-gender'

code "HIV Positive": '165816005' from "SNOMED-CT" display 'HIV Positive'

// codes

// The display "Pregnancy (finding)" is not a valid display for the code {http://snomed.info/sct}77386006
code "Pregnancy (finding)": '77386006' from "SNOMED-CT" display 'Pregnancy (finding)'
code "Pregnant": '146789000' from "SNOMED-CT" display 'Pregnant'
// code "Breastfeeding": '169750002' from "SNOMED-CT" display 'Breastfeeding'
code "Prenatal initial visit (regime/therapy)": '424441002' from "SNOMED-CT" display 'Prenatal initial visit (regime/therapy)'
code "Pregnancy status - Reported": '11449-6' from "LOINC" display 'Pregnancy status - Reported'
// code "Livebirth (finding)": '281050002' from "SNOMED-CT" display 'Livebirth (finding)'
// code "Postpartum state (finding)": '86569001' from "SNOMED-CT" display 'Postpartum state (finding)'
// code "Normal breast feeding (finding)": '69840006' from "SNOMED-CT" display 'Normal breast feeding (finding)'


// ciel hiv/other
code "Currently taking ARV": '160119' from "CIEL" display 'Currently taking ARV'
code "Coded Answer": '1065' from "CIEL" display 'Yes'
code "Method of enrollment": '160540' from "CIEL" display 'Method of enrollment'
code "Outpatient department": '160542' from "CIEL" display 'Outpatient department'
code "Outpatient department SNOMED": '33022008' from "SNOMED-CT" display 'Outpatient department'
code "CURRENT DRUGS USED": '1193' from "CIEL" display 'CURRENT DRUGS USED'
code "RETURN VISIT DATE": '5096' from "CIEL" display 'RETURN VISIT DATE'


// snomed and other hiv testing, results, conditions, art
code "Acquired immune deficiency syndrome (disorder)": '62479008' from "SNOMED-CT" display 'Acquired immune deficiency syndrome (disorder)'
code "HIV Condition Positive": '86406008' from "SNOMED-CT" display 'HIV infection'
code "HIV Negative": '165815009' from "SNOMED-CT" display 'HIV Negative'
code "History of antiretroviral therapy (situation)": '432101000124108' from "OpenHIE" display 'History of antiretroviral therapy (situation)'
code "Institutional entry point HIV treatment": '45252-4' from "LOINC" display 'Institutional entry point HIV treatment'
// code "New on ART": 'new-on-art' from "PMTCT ART Status Codes" display 'New on ART'
// need to change to valueset
code "Reason for discontinuation of program": '161555' from "CIEL" display 'Reason for discontinuation of program'
code "Treatment end date": '164384' from "CIEL" display 'Treatment end date'

// valuesets
valueset AgeRangesTXCURR: 'https://path-global-health.github.io/MERindicators/ValueSet/AgeRangesTXCURR'
// valueset "HIV Testing Services": 'https://path-global-health.github.io/MERindicators/ValueSet/HIVTestingServices' // Should use HIV tests
// viral load tests, results
// commenting out for now and the union
// valueset "Human Immunodeficiency Virus (HIV) Laboratory Test Codes (Ab and Ag)": 'urn:oid:2.16.840.1.113762.1.4.1056.50' // Used by CMS349
code "HIV 1 and 2 tests - Meaningful Use set": '75622-1' from "LOINC" display 'HIV 1 and 2 tests - Meaningful Use set'
valueset "Viral Load Test": 'https://path-global-health.github.io/MERindicators/ValueSet/ViralLoadTest'
// valueset "Synthea HIV Medications": 'https://path-global-health.github.io/MERindicators/ValueSet/SyntheaHIVMedications'
valueset "ART Medications": 'https://path-global-health.github.io/MERindicators/ValueSet/SyntheaHIVMedications'
valueset "CIELHIVMedications": 'https://path-global-health.github.io/MERindicators/ValueSet/CIELHIVMedications'
// valueset "EnrollmentMethods": 


Entry 13 - fullUrl = https://path-global-health.github.io/MERindicators/Library/KenyaEMRStratifiers

Request:

PUT Library/KenyaEMRStratifiers

Resource Library:

Contents

text/cql

library KenyaEMRStratifiers version '0.1.0'

using FHIR version '4.0.1'

include FHIRHelpers version '4.0.1'
include FHIRCommon version '4.0.1' called FC

include KenyaEMRConcepts called Cx


codesystem "KEMR Periods": 'http://ohie.org/CodeSystem/kemr-periods'
code "<1": '<1' from "KEMR Periods" display '<1'
code "1-9": '1-9' from "KEMR Periods" display '1-9'
code "10-14": '10-14' from "KEMR Periods" display '10-14'
code "15-19": '15-19' from "KEMR Periods" display '15-19'
code "20-24": '20-24' from "KEMR Periods" display '20-24'
code "25+": '25+' from "KEMR Periods" display '25+'


parameter "Measurement Period" Interval<DateTime> default Interval[@2023-04-01T00:00:00.0, @2023-06-30T00:00:00.0]


context Patient


define "Sex":
  Patient.gender.value


define "Age Group":
  case
    when AgeInYearsAt(start of "Measurement Period") in Interval[0, 1) then "<1"
    when AgeInYearsAt(start of "Measurement Period") in Interval[1, 9) then "1-9"
    when AgeInYearsAt(start of "Measurement Period") in Interval[10, 14) then "10-14"
    when AgeInYearsAt(start of "Measurement Period") in Interval[15, 19) then "15-19"
    when AgeInYearsAt(start of "Measurement Period") in Interval[20, 24) then "20-24"
    when AgeInYearsAt(start of "Measurement Period") in Interval[25, null] then "25+"
    else null
  end


define "Age Group/Sex":
  "Age Group".code + ':' + "Sex"


define "Last Location":
  Last([Encounter] E
    return singleton from (E.location L
      return L.location.reference
    ).value
  )


// http://fhir.openmrs.org/ext/patient/identifier#location

define "OpenMRS Location":
  [Patient] P
    // this url is in the ig, but is not correct: 'http://fhir.openmrs.org/core/StructureDefinition/omrs-patient-identifier-location'}
    where singleton from {P.identifier.extension[0].url ~ 'http://fhir.openmrs.org/ext/patient/identifier'}
    or singleton from {P.identifier.extension[0].url ~ 'http://fhir.openmrs.org/ext/patient/identifier#location'}
    // or singleton from {P.identifier.extension[1].url ~ 'http://fhir.openmrs.org/ext/patient/identifier'}
    // or singleton from {P.identifier.extension[1].url ~ 'http://fhir.openmrs.org/ext/patient/identifier#location'}
    return singleton from {P.identifier.extension[0].value.reference.value}


define "Last serviceProvider":
  // Some of the Synthea encounters do not have a serviceProvider, so this can return nothing
  // Filter out those that are null, then take the last
  [Encounter] E
    where E.serviceProvider is not null
  return Last([Encounter]).serviceProvider.reference.value


// if..then..else
define "Location Deux":
  if "Last Location" is not null then ("Last Location")
  else if "Last serviceProvider" is not null then ("Last serviceProvider")
  else if "OpenMRS Location" is not null then ("OpenMRS Location")
  else null


define "Location":
  case
    // location identifier on patient
    when "OpenMRS Location" is not null then ("OpenMRS Location")
    // then location of last encounter
    when "Last Location" is not null then ("Last Location")
    // then organization of last encounter
    when "Last serviceProvider" is not null then ("Last serviceProvider")
    else null
  end


define "Debug location": 
  Combine({ "Location", "Sex"}, ':')


define "Age Group/Sex/Location":
  "Age Group".code & ':' & "Sex" & ':' & "Location"


define "Age Group/Sex/Location TXCURR":
  "Age Group".code + ':' + "Sex" + ':' + "Location"


define "Age Group/Sex/Location Case Switch":
  "Age Group".code + ':' + "Sex" + ':' + "Location"


Entry 14 - fullUrl = https://path-global-health.github.io/MERindicators/Library/KenyaEMRTXCURR

Request:

PUT Library/KenyaEMRTXCURR

Resource Library:

Contents

text/cql

library KenyaEMRTXCURR version '0.1.0'

// Test cases are located in /input/tests/<Library Name>/<Patient.id>/<bundle source>

using FHIR version '4.0.1'

include FHIRHelpers version '4.0.1'
include FHIRCommon version '4.0.1' called FC
include KenyaEMRConcepts called Cx
include KenyaEMRStratifiers called Stratifiers


// Provide a default interval or period-based tests will fail when evaluating CQL against test cases
// The $evaluate-measure operation's parameters 'periodStart' and 'periodEnd' override this in any case
parameter "Measurement Period" Interval<DateTime> default Interval[@1990-01-01T, @2023-06-30T]


context Patient


/*
On ART is any patient with a regimen history as below:

Patients started on ART drugs (participating in program)
who made a clinic visit during the reporting period

PLUS

Patient who made a clinic visit in the past and were given medicine to last the reporting 
period and beyond

PLUS

Patients who missed their appointment AND 30 days (one month) have not passed since the last missed appointment.
[30 days since last missed appointment]

Exclude those who interrupted treatment for any reason, etc, etc. "Measure Population Exclusion"
*/


// Initial Population
// Patients who have started an ART drugs program

/*
PLHIV are enrolled in an HIV program.
On Observation resource: $CIEL#160540 "Method of enrollment"
Observation.status is not in example bundle, can't do 'Obs.status in {'final', 'amended', 'corrected'}'
Using the CIEL codes only, even if others are provided.
Use the equivalent operator (~) rather than equality (=) which checks the code system version.
*/



define "PLHIV Observation":
  ["Observation": Cx."Method of enrollment"] Obs
    where (Obs.effective before end of "Measurement Period")


define "PLHIV Boolean": exists "PLHIV Observation"


define "Initial Population": 
  "PLHIV Boolean"


/*
Someone visits 1 July. 
Given appt in 1 month - 1 August.
Check that patient had visit by 24th August/by 30 days.
+ add 30 days.
*/


// "RETURN VISIT DATE"
// Patients started on ART drugs (participating in program)
// who made a clinic visit during the reporting period (Q: Any type? A: yes)

define "Return Visit Observations":
  ["Observation": Cx."RETURN VISIT DATE"]

// return visit during period
define "Return Visits During Period":
  ("Return Visit Observations") Obs
  where (Obs.effective before end of "Measurement Period")
  sort by date from (effective as FHIR.dateTime) desc

define "Any Return Visit During Period": 
  exists "Return Visits During Period"

define "Most Recent Return Visit During Period":
  First("Return Visits During Period")

define "Return Visit Date":
  "Most Recent Return Visit During Period".value.value

// Get last visit during measure period, "return visit date" + 30 days > end of the period
// Does the most recent "return visit date" need to be within the period as long as the value is after it?
define "Return Visit within 30 days of Period":
  ("Most Recent Return Visit During Period".value as FHIR.dateTime) + 30 days after end of "Measurement Period"


// "CURRENT DRUGS USED" are prescriptions
// effectivedatetime captures when those drugs started
// the other datetime fields are not used
// checks on being started on ART, this is not 'picking up drugs'

define "Current Drugs Used Observations":
  ["Observation": Cx."CURRENT DRUGS USED"]

define "Has started ART":
  exists("Current Drugs Used Observations")


/*
Additional notes:
The assumption is that a patient is considered to be on a particular regimen until there is a change, substitution, or stop events.
Drugs are prescribed and noted in an Observation.
The actual drugs are coded concepts in Observation.value.coding but are missing a system identifier.
The return dates are appointment dates for when the prescription ends and the patient is expected to return.
The EMR does not use a pharmacy module, and is reliant on appointment dates (return dates) which are based on the amount of drugs given.
The drugs observation tells when a patient was first started on drugs. 
'current drugs' concept captures regimen changes
more of a history of regimen of original and most current - there may be original and current regimen
bundle includes original regimen
*/

// Patient who made a clinic visit in the past and were given medicine to last the reporting period and beyond


define "Measure Population": 
  "Return Visit within 30 days of Period" and "Has started ART"


// Measure Population Exclusion
// Deceased and those who interrupted treatment for any reason, etc, etc.


/*
Deceased patients are not in numerator.
In FHIR, deceased[x] is a choice type, of either boolean or datetime.
It also has a cardinality of 0..1. so deceasedBoolean and deceasedDateTime cannot coexist.
There can only be one deceased[x] element.
If true is used, there's no way to know from that field when the patient died. DateTime is better for accuracy.
*/


// This expression allows deceasedBoolean which has no datetime.
define "Deceased Boolean":
  Patient.deceased is not null 
  and ((Patient.deceased as FHIR.boolean) is true or (Patient.deceased as FHIR.dateTime) on or before end of "Measurement Period")


// This expression requires patients to have datetime on Patient.deceased (more accurate).
define "Deceased DateTime Only":
  Patient.deceased is not null 
  and Patient.deceased on or before end of "Measurement Period"



// Todo: double check: "effectiveDateTime": "2023-05-31T11:30:14+03:00",
define "Discontinuation":
  ["Observation": Cx."Reason for discontinuation of program"] Obs
  where Obs.effective before end of "Measurement Period" and Obs.effective after "Most Recent Return Visit During Period".effective


// valueDateTime
define "Transfer Out":
  ["Observation": Cx."Treatment end date"] Obs
  where Obs.value before end of "Measurement Period" and Obs.value after "Most Recent Return Visit During Period".effective


define "Discontinuation Boolean": exists "Discontinuation"


define "Transfer Out Boolean": exists "Transfer Out"


define "Measure Population Exclusion": 
  "Discontinuation Boolean"
  or "Transfer Out Boolean"
  or "Deceased Boolean"
  //or ("Deceased Boolean" is true or "Deceased DateTime Only" is true)



// Stratifiers


// should work without #location
// how to clean it up with identifier[].extension[]
// todo: debugging needed on location
define "OpenMRS Location":
  [Patient] P
    // this url is in the ig, but is not correct: 'http://fhir.openmrs.org/core/StructureDefinition/omrs-patient-identifier-location'}
    where singleton from {P.identifier.extension[0].url ~ 'http://fhir.openmrs.org/ext/patient/identifier'}
    or singleton from {P.identifier.extension[0].url ~ 'http://fhir.openmrs.org/ext/patient/identifier#location'}
    or singleton from {P.identifier.extension[1].url ~ 'http://fhir.openmrs.org/ext/patient/identifier'}
    or singleton from {P.identifier.extension[1].url ~ 'http://fhir.openmrs.org/ext/patient/identifier#location'}
    return singleton from {P.identifier.extension[0].value.reference.value}


define "Stratification": 
  Stratifiers."Age Group/Sex"


// define "Stratifier": "Stratification"


Entry 15 - fullUrl = https://path-global-health.github.io/MERindicators/Measure/KEMRTXCURR

Request:

PUT Measure/KEMRTXCURR

Resource Measure:

Generated Narrative: Measure

Resource Measure "KEMRTXCURR"

url: https://path-global-health.github.io/MERindicators/Measure/KEMRTXCURR

identifier: id: KEMRTXCURR

version: 0.1.0

name: KEMRTXCURR

title: KEMRTXCURR

status: DRAFT

experimental: true

date: 2023-07-01

publisher: PATH

description: KEMRTXCURR

library: KenyaEMRTXCURR

scoring: Continuous Variable (MeasureScoring#continuous-variable)

group

population

code: Initial Population (MeasurePopulationType#initial-population)

description: Initial Population

Criteria

-LanguageExpression
*text/cqlInitial Population

population

code: Measure Population (MeasurePopulationType#measure-population)

description: Measure Population

Criteria

-LanguageExpression
*text/cqlMeasure Population

population

code: Measure Population Exclusion (MeasurePopulationType#measure-population-exclusion)

description: Measure Population Exclusion

Criteria

-LanguageExpression
*text/cqlMeasure Population Exclusion

stratifier

Criteria

-LanguageExpression
*text/cqlStratification