Search in sources :

Example 26 with ParameterDefinition

use of org.hl7.fhir.r5.model.ParameterDefinition in project clinical_quality_language by cqframework.

the class DataRequirementsProcessorTest method TestLibraryDataRequirements.

@Test
public void TestLibraryDataRequirements() {
    CqlTranslatorOptions cqlTranslatorOptions = new CqlTranslatorOptions();
    cqlTranslatorOptions.getFormats().add(CqlTranslator.Format.JSON);
    try {
        // CqlTranslator translator = createTranslator("/ecqm/resources/library-EXM506-2.2.000.json", cqlTranslatorOptions);
        CqlTranslator translator = createTranslator("CompositeMeasures/cql/BCSComponent.cql", cqlTranslatorOptions);
        translator.toELM();
        assertTrue(translator.getErrors().isEmpty());
        libraryManager.cacheLibrary(translator.getTranslatedLibrary());
        DataRequirementsProcessor dqReqTrans = new DataRequirementsProcessor();
        org.hl7.fhir.r5.model.Library moduleDefinitionLibrary = dqReqTrans.gatherDataRequirements(libraryManager, translator.getTranslatedLibrary(), cqlTranslatorOptions, null, false);
        assertTrue(moduleDefinitionLibrary.getType().getCode("http://terminology.hl7.org/CodeSystem/library-type").equalsIgnoreCase("module-definition"));
        List<Extension> directReferenceCodes = moduleDefinitionLibrary.getExtensionsByUrl("http://hl7.org/fhir/us/cqfmeasures/StructureDefinition/cqfm-directReferenceCode");
        assertTrue(directReferenceCodes.size() == 5);
        Extension directReferenceCode = directReferenceCodes.get(0);
        Coding coding = directReferenceCode.getValueCoding();
        assertEquals("http://loinc.org", coding.getSystem());
        assertEquals("21112-8", coding.getCode());
        assertEquals("Birth date", coding.getDisplay());
        assertTrue(moduleDefinitionLibrary.getRelatedArtifact().size() >= 45);
        RelatedArtifact loincCodeSystem = null;
        for (RelatedArtifact relatedArtifact : moduleDefinitionLibrary.getRelatedArtifact()) {
            if (relatedArtifact.getType() == RelatedArtifact.RelatedArtifactType.DEPENDSON && relatedArtifact.getResource() != null && relatedArtifact.getResource().equals("http://loinc.org")) {
                loincCodeSystem = relatedArtifact;
                break;
            }
        }
        assertTrue(loincCodeSystem != null);
        assertTrue(moduleDefinitionLibrary.getParameter().size() >= 16);
        ParameterDefinition measurementPeriod = null;
        for (ParameterDefinition parameter : moduleDefinitionLibrary.getParameter()) {
            if (parameter.getName().equals("Measurement Period")) {
                measurementPeriod = parameter;
                break;
            }
        }
        assertTrue(measurementPeriod != null);
        assertTrue(moduleDefinitionLibrary.getDataRequirement().size() >= 15);
        DataRequirement diagnosisRequirement = null;
        for (DataRequirement requirement : moduleDefinitionLibrary.getDataRequirement()) {
            if (requirement.getType() == Enumerations.FHIRAllTypes.CONDITION && requirement.getCodeFilter().size() == 1) {
                DataRequirement.DataRequirementCodeFilterComponent cfc = requirement.getCodeFilterFirstRep();
                if (cfc.hasPath() && cfc.getPath().equals("code") && cfc.hasValueSet() && cfc.getValueSet().equals("http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113883.3.464.1003.198.12.1071")) {
                    diagnosisRequirement = requirement;
                    break;
                }
            }
        }
        assertTrue(diagnosisRequirement != null);
        FhirContext context = getFhirContext();
        IParser parser = context.newJsonParser();
        String moduleDefString = parser.setPrettyPrint(true).encodeResourceToString(moduleDefinitionLibrary);
        logger.debug(moduleDefString);
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) IOException(java.io.IOException) org.hl7.fhir.r5.model(org.hl7.fhir.r5.model) IParser(ca.uhn.fhir.parser.IParser) Test(org.testng.annotations.Test)

Example 27 with ParameterDefinition

use of org.hl7.fhir.r5.model.ParameterDefinition in project clinical_quality_language by cqframework.

the class DataRequirementsProcessor method extractParameters.

private List<ParameterDefinition> extractParameters(ElmRequirementsContext context, ElmRequirements requirements, VersionedIdentifier libraryIdentifier, Iterable<ExpressionDef> expressionDefs) {
    List<ParameterDefinition> result = new ArrayList<>();
    // TODO: Support library qualified parameters
    // Until then, name clashes should result in a warning
    Map<String, ParameterDefinition> pds = new HashMap<String, ParameterDefinition>();
    for (ElmRequirement def : requirements.getParameterDefs()) {
        ParameterDefinition pd = toParameterDefinition(def.getLibraryIdentifier(), (ParameterDef) def.getElement());
        if (pds.containsKey(pd.getName())) {
            ParameterDefinition existingPd = pds.get(pd.getName());
            if (!isEquivalentDefinition(existingPd, pd)) {
                // Issue a warning that the parameter has a duplicate name but an incompatible type
                validationMessages.add(new ValidationMessage(ValidationMessage.Source.Publisher, ValidationMessage.IssueType.NOTSUPPORTED, "CQL Library Packaging", String.format("Parameter declaration %s.%s is already defined in a different library with a different type. Parameter binding may result in errors during evaluation.", def.getLibraryIdentifier().getId(), pd.getName()), ValidationMessage.IssueSeverity.WARNING));
            }
        } else {
            pds.put(pd.getName(), pd);
            result.add(pd);
        }
    }
    for (ExpressionDef def : expressionDefs) {
        if (def != null && !(def instanceof FunctionDef) && (def.getAccessLevel() == null || def.getAccessLevel() == AccessModifier.PUBLIC)) {
            result.add(toOutputParameterDefinition(libraryIdentifier, def));
        }
    }
    return result;
}
Also used : ValidationMessage(org.hl7.fhir.utilities.validation.ValidationMessage) ElmRequirement(org.cqframework.cql.elm.requirements.ElmRequirement)

Example 28 with ParameterDefinition

use of org.hl7.fhir.r5.model.ParameterDefinition in project quality-measure-and-cohort-service by Alvearie.

the class FHIRRestUtils method toMeasureParameterInfo.

private static MeasureParameterInfo toMeasureParameterInfo(ParameterDefinition parameterDefinition) {
    MeasureParameterInfo retVal = new MeasureParameterInfo();
    String defaultValue = complicatedTypes.contains(parameterDefinition.getType()) ? complicatedTypeValueConstructor(parameterDefinition) : null;
    retVal.name(parameterDefinition.getName()).type(parameterDefinition.getType()).min(parameterDefinition.getMin()).max(parameterDefinition.getMax()).documentation(parameterDefinition.getDocumentation());
    Optional.ofNullable(parameterDefinition.getUse()).map(ParameterUse::getDisplay).ifPresent(retVal::setUse);
    parameterDefinition.getExtension().stream().filter(MeasureEvaluationSeeder::isDefaultValue).findFirst().map(Extension::getValue).map(x -> {
        if (defaultValue != null) {
            return defaultValue;
        } else
            return x.toString();
    }).ifPresent(retVal::setDefaultValue);
    return retVal;
}
Also used : Extension(org.hl7.fhir.r4.model.Extension) Identifier(org.hl7.fhir.r4.model.Identifier) IBMFhirServerConfig(com.ibm.cohort.fhir.client.config.IBMFhirServerConfig) Range(org.hl7.fhir.r4.model.Range) Measure(org.hl7.fhir.r4.model.Measure) ArrayList(java.util.ArrayList) FhirContext(ca.uhn.fhir.context.FhirContext) FhirVersionEnum(ca.uhn.fhir.context.FhirVersionEnum) JsonNode(com.fasterxml.jackson.databind.JsonNode) Quantity(org.hl7.fhir.r4.model.Quantity) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) ResourceNotFoundException(ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException) MeasureParameterInfo(com.ibm.cohort.engine.api.service.model.MeasureParameterInfo) FhirResourceResolver(com.ibm.cohort.cql.fhir.resolver.FhirResourceResolver) Patient(org.hl7.fhir.r4.model.Patient) IParser(ca.uhn.fhir.parser.IParser) ParameterUse(org.hl7.fhir.r4.model.ParameterDefinition.ParameterUse) Period(org.hl7.fhir.r4.model.Period) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DefaultFhirClientBuilder(com.ibm.cohort.fhir.client.config.DefaultFhirClientBuilder) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ParameterDefinition(org.hl7.fhir.r4.model.ParameterDefinition) Collectors(java.util.stream.Collectors) Base64(java.util.Base64) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Optional(java.util.Optional) MeasureEvaluationSeeder(com.ibm.cohort.engine.measure.seed.MeasureEvaluationSeeder) Extension(org.hl7.fhir.r4.model.Extension) MeasureParameterInfo(com.ibm.cohort.engine.api.service.model.MeasureParameterInfo) MeasureEvaluationSeeder(com.ibm.cohort.engine.measure.seed.MeasureEvaluationSeeder)

Example 29 with ParameterDefinition

use of org.hl7.fhir.r5.model.ParameterDefinition in project quality-measure-and-cohort-service by Alvearie.

the class FHIRRestUtilsTest method testConstructAppropriateJsonPeriod.

@Test
public void testConstructAppropriateJsonPeriod() {
    ParameterDefinition definition = new ParameterDefinition();
    definition.setType("Period");
    Extension extension = new Extension();
    extension.setUrl("http://ibm.com/fhir/cdm/StructureDefinition/default-value");
    Period period = new Period();
    Date startDate = Date.from(LocalDate.of(2020, 1, 1).atStartOfDay(ZoneId.systemDefault()).toInstant());
    DateTimeType startElement = new DateTimeType(startDate, TemporalPrecisionEnum.DAY);
    Date endDate = Date.from(LocalDate.of(2021, 1, 1).atStartOfDay(ZoneId.systemDefault()).toInstant());
    DateTimeType endElement = new DateTimeType(endDate, TemporalPrecisionEnum.DAY);
    period.setStartElement(startElement);
    period.setEndElement(endElement);
    extension.setValue(period);
    List<Extension> extensions = new ArrayList<>();
    extensions.add(extension);
    definition.setExtension(extensions);
    String defaultResult = FHIRRestUtils.complicatedTypeValueConstructor(definition);
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    assertEquals("{\"start\":\"" + formatter.format(startDate) + "\",\"end\":\"" + formatter.format(endDate) + "\"}", defaultResult);
}
Also used : Extension(org.hl7.fhir.r4.model.Extension) DateTimeType(org.hl7.fhir.r4.model.DateTimeType) ArrayList(java.util.ArrayList) Period(org.hl7.fhir.r4.model.Period) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) LocalDate(java.time.LocalDate) ParameterDefinition(org.hl7.fhir.r4.model.ParameterDefinition) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 30 with ParameterDefinition

use of org.hl7.fhir.r5.model.ParameterDefinition in project quality-measure-and-cohort-service by Alvearie.

the class MeasureEvaluationSeeder method create.

public IMeasureEvaluationSeed create(Measure measure, String periodStart, String periodEnd, String productLine, Map<String, Parameter> parameters) {
    // Gather the primary library and all of its dependencies
    List<Library> fhirLibraries = libraryDependencyGatherer.gatherForMeasure(measure);
    if (CollectionUtils.isEmpty(fhirLibraries)) {
        throw new IllegalArgumentException(String.format("No libraries were able to be loaded for %s", measure.getId()));
    }
    // the "primary" library is always the first library loaded for the measure
    Library primaryFhirLibrary = fhirLibraries.get(0);
    VersionedIdentifier libraryIdentifier = new VersionedIdentifier().withId(primaryFhirLibrary.getName()).withVersion(primaryFhirLibrary.getVersion());
    LibraryLoader libraryLoader = new R4TranslatingLibraryLoader(libraryResolver, new CqlToElmTranslator());
    org.cqframework.cql.elm.execution.Library primaryLibrary = libraryLoader.load(libraryIdentifier);
    List<Triple<String, String, String>> usingDefs = UsingHelper.getUsingUrlAndVersion(primaryLibrary.getUsings());
    if (usingDefs.size() > 1) {
        throw new IllegalArgumentException("Evaluation of Measure using multiple Models is not supported at this time.");
    }
    // Per the above condition, we should only have one model per measure
    String lastModelUri = usingDefs.get(usingDefs.size() - 1).getRight();
    DataProvider dataProvider = dataProviders.get(lastModelUri);
    Context context = createContext(primaryLibrary, lastModelUri, dataProvider, productLine, libraryLoader);
    // fhir path: Measure.extension[measureParameter][].valueParameterDefinition.extension[defaultValue]
    measure.getExtension().stream().filter(MeasureEvaluationSeeder::isMeasureParameter).map(parameter -> dataProvider.resolvePath(parameter, "valueParameterDefinition")).map(ParameterDefinition.class::cast).forEach(parameterDefinition -> setDefaultValue(context, parameterDefinition));
    if (parameters != null) {
        parameters.entrySet().stream().forEach(e -> context.setParameter(null, e.getKey(), e.getValue().toCqlType()));
    }
    // Set measurement period last to make sure we respect periodStart
    // and periodEnd date boundaries for an execution.
    Interval measurementPeriod = createMeasurePeriod(periodStart, periodEnd);
    context.setParameter(null, MEASUREMENT_PERIOD, measurementPeriod);
    return new CustomMeasureEvaluationSeed(measure, context, measurementPeriod, dataProvider);
}
Also used : CDMContext(com.ibm.cohort.engine.cqfruler.CDMContext) Context(org.opencds.cqf.cql.engine.execution.Context) CqlToElmTranslator(com.ibm.cohort.cql.translation.CqlToElmTranslator) R4TranslatingLibraryLoader(com.ibm.cohort.cql.hapi.R4TranslatingLibraryLoader) LibraryLoader(org.opencds.cqf.cql.engine.execution.LibraryLoader) Triple(org.apache.commons.lang3.tuple.Triple) CqlDataProvider(com.ibm.cohort.cql.data.CqlDataProvider) DataProvider(org.opencds.cqf.cql.engine.data.DataProvider) VersionedIdentifier(org.cqframework.cql.elm.execution.VersionedIdentifier) Library(org.hl7.fhir.r4.model.Library) R4TranslatingLibraryLoader(com.ibm.cohort.cql.hapi.R4TranslatingLibraryLoader) Interval(org.opencds.cqf.cql.engine.runtime.Interval)

Aggregations

ParameterDefinition (org.hl7.fhir.r4.model.ParameterDefinition)32 Test (org.junit.Test)26 Extension (org.hl7.fhir.r4.model.Extension)14 DatetimeParameter (com.ibm.cohort.cql.evaluation.parameters.DatetimeParameter)9 ArrayList (java.util.ArrayList)9 DateTimeType (org.hl7.fhir.r4.model.DateTimeType)9 QuantityParameter (com.ibm.cohort.cql.evaluation.parameters.QuantityParameter)8 StringParameter (com.ibm.cohort.cql.evaluation.parameters.StringParameter)8 Quantity (org.hl7.fhir.r4.model.Quantity)8 Range (org.hl7.fhir.r4.model.Range)8 CodeParameter (com.ibm.cohort.cql.evaluation.parameters.CodeParameter)7 IntervalParameter (com.ibm.cohort.cql.evaluation.parameters.IntervalParameter)7 Period (org.hl7.fhir.r4.model.Period)7 BooleanParameter (com.ibm.cohort.cql.evaluation.parameters.BooleanParameter)6 ConceptParameter (com.ibm.cohort.cql.evaluation.parameters.ConceptParameter)6 DateParameter (com.ibm.cohort.cql.evaluation.parameters.DateParameter)6 DecimalParameter (com.ibm.cohort.cql.evaluation.parameters.DecimalParameter)6 IntegerParameter (com.ibm.cohort.cql.evaluation.parameters.IntegerParameter)6 RatioParameter (com.ibm.cohort.cql.evaluation.parameters.RatioParameter)6 TimeParameter (com.ibm.cohort.cql.evaluation.parameters.TimeParameter)6