Search in sources :

Example 16 with CqlEvaluator

use of com.ibm.cohort.cql.evaluation.CqlEvaluator in project quality-measure-and-cohort-service by Alvearie.

the class CohortCLI method runWithArgs.

/**
 * Simulate main method behavior in a non-static context for use in testing
 * tools. This method is intended to be called only once. Multiple calls for the
 * same library path will attempt duplicate library loading.
 *
 * @param args parameter values
 * @param out  location where contents that would normally go to stdout should
 *             be written
 * @return CQLEvaluator
 * @throws IOException IOException
 */
public CqlEvaluator runWithArgs(String[] args, PrintStream out) throws IOException {
    Arguments arguments = new Arguments();
    Console console = new DefaultConsole(out);
    JCommander jc = JCommander.newBuilder().programName("cql-engine").console(console).addObject(arguments).build();
    jc.parse(args);
    CqlEvaluator wrapper = null;
    if (arguments.isDisplayHelp) {
        jc.usage();
    } else {
        FhirClientBuilderFactory factory = FhirClientBuilderFactory.newInstance();
        FhirClientBuilder fhirClientBuilder = factory.newFhirClientBuilder();
        readConnectionConfiguration(arguments);
        MapCqlLibraryProviderFactory libraryProviderFactory = new MapCqlLibraryProviderFactory();
        String[] filters = null;
        if (arguments.filters != null) {
            filters = arguments.filters.toArray(new String[arguments.filters.size()]);
        }
        CqlLibraryProvider backingLibraryProvider;
        Path libraryFolder = Paths.get(arguments.libraryPath);
        if (libraryFolder.toFile().isDirectory()) {
            out.println(String.format("Loading libraries from folder '%s'", libraryFolder.toString()));
            backingLibraryProvider = libraryProviderFactory.fromDirectory(libraryFolder, filters);
        } else if (FileHelpers.isZip(libraryFolder.toFile())) {
            out.println(String.format("Loading libraries from ZIP '%s'", libraryFolder.toString()));
            backingLibraryProvider = libraryProviderFactory.fromZipFile(libraryFolder, filters);
        } else {
            out.println(String.format("Loading libraries from FHIR Library '%s'", libraryFolder.toString()));
            IGenericClient measureClient = fhirClientBuilder.createFhirClient(measureServerConfig);
            FhirResourceResolver<Library> libraryResolver = R4FhirServerResourceResolverFactory.createLibraryResolver(measureClient);
            R4LibraryDependencyGatherer dependencyGatherer = new R4LibraryDependencyGatherer(libraryResolver);
            List<Library> cqlLibraries = dependencyGatherer.gatherForLibraryId(arguments.libraryPath);
            Map<CqlLibraryDescriptor, CqlLibrary> cqlLibraryMap = toCqlLibraryMap(cqlLibraries);
            backingLibraryProvider = new MapCqlLibraryProvider(cqlLibraryMap);
        }
        CqlLibraryProvider fhirClasspathProvider = new ClasspathCqlLibraryProvider();
        backingLibraryProvider = new PriorityCqlLibraryProvider(backingLibraryProvider, fhirClasspathProvider);
        CqlToElmTranslator translator = new CqlToElmTranslator();
        if (arguments.modelInfoFile != null && arguments.modelInfoFile.exists()) {
            translator.registerModelInfo(arguments.modelInfoFile);
        }
        boolean isForceTranslation = arguments.sourceFormat == Format.CQL;
        CqlLibraryProvider libraryProvider = new TranslatingCqlLibraryProvider(backingLibraryProvider, translator, isForceTranslation);
        IGenericClient dataClient = fhirClientBuilder.createFhirClient(dataServerConfig);
        IGenericClient termClient = fhirClientBuilder.createFhirClient(terminologyServerConfig);
        CqlTerminologyProvider termProvider = new R4RestFhirTerminologyProvider(termClient);
        Map<String, com.ibm.cohort.cql.evaluation.parameters.Parameter> parameters = null;
        if (arguments.parameters != null) {
            parameters = parseParameterArguments(arguments.parameters);
        }
        CqlVersionedIdentifier libraryIdentifier = new CqlVersionedIdentifier(arguments.libraryName, arguments.libraryVersion);
        List<Pair<String, String>> contexts;
        if (arguments.contextIds == null || arguments.contextIds.isEmpty()) {
            // If no context ids are provided, perform one run using a null context
            contexts = Collections.singletonList(null);
        } else {
            contexts = arguments.contextIds.stream().map(x -> new ImmutablePair<>(arguments.contextName, x)).collect(Collectors.toList());
        }
        try (RetrieveCacheContext cacheContext = new DefaultRetrieveCacheContext()) {
            CqlDataProvider dataProvider = R4DataProviderFactory.createDataProvider(dataClient, termProvider, cacheContext, R4FhirModelResolverFactory.createCachingResolver(), !arguments.enableTerminologyOptimization, arguments.searchPageSize);
            wrapper = new CqlEvaluator().setLibraryProvider(libraryProvider).setDataProvider(dataProvider).setTerminologyProvider(termProvider);
            ZonedDateTime evaluationDateTime = ZonedDateTime.now();
            for (Pair<String, String> context : contexts) {
                String contextLabel = context == null ? "null" : context.getRight();
                out.println("Context: " + contextLabel);
                CqlEvaluationResult result = wrapper.evaluate(libraryIdentifier, parameters, context, arguments.expressions, arguments.loggingLevel, evaluationDateTime);
                out.print(prettyPrintResult(result));
                out.println("---");
            }
        }
    }
    return wrapper;
}
Also used : FhirResourceResolver(com.ibm.cohort.cql.fhir.resolver.FhirResourceResolver) DefaultConsole(com.beust.jcommander.internal.DefaultConsole) TranslatingCqlLibraryProvider(com.ibm.cohort.cql.translation.TranslatingCqlLibraryProvider) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) R4RestFhirTerminologyProvider(com.ibm.cohort.engine.terminology.R4RestFhirTerminologyProvider) DefaultRetrieveCacheContext(com.ibm.cohort.engine.measure.cache.DefaultRetrieveCacheContext) RetrieveCacheContext(com.ibm.cohort.engine.measure.cache.RetrieveCacheContext) CqlToElmTranslator(com.ibm.cohort.cql.translation.CqlToElmTranslator) MapCqlLibraryProvider(com.ibm.cohort.cql.library.MapCqlLibraryProvider) CqlLibraryProvider(com.ibm.cohort.cql.library.CqlLibraryProvider) PriorityCqlLibraryProvider(com.ibm.cohort.cql.library.PriorityCqlLibraryProvider) TranslatingCqlLibraryProvider(com.ibm.cohort.cql.translation.TranslatingCqlLibraryProvider) ClasspathCqlLibraryProvider(com.ibm.cohort.cql.library.ClasspathCqlLibraryProvider) ZonedDateTime(java.time.ZonedDateTime) JCommander(com.beust.jcommander.JCommander) Console(com.beust.jcommander.internal.Console) DefaultConsole(com.beust.jcommander.internal.DefaultConsole) R4LibraryDependencyGatherer(com.ibm.cohort.cql.hapi.R4LibraryDependencyGatherer) List(java.util.List) MapCqlLibraryProviderFactory(com.ibm.cohort.cql.library.MapCqlLibraryProviderFactory) CqlTerminologyProvider(com.ibm.cohort.cql.terminology.CqlTerminologyProvider) CqlDataProvider(com.ibm.cohort.cql.data.CqlDataProvider) Pair(org.apache.commons.lang3.tuple.Pair) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) Path(java.nio.file.Path) FhirClientBuilder(com.ibm.cohort.fhir.client.config.FhirClientBuilder) ParameterHelper.parseParameterArguments(com.ibm.cohort.cli.ParameterHelper.parseParameterArguments) MapCqlLibraryProvider(com.ibm.cohort.cql.library.MapCqlLibraryProvider) CqlEvaluationResult(com.ibm.cohort.cql.evaluation.CqlEvaluationResult) DefaultRetrieveCacheContext(com.ibm.cohort.engine.measure.cache.DefaultRetrieveCacheContext) PriorityCqlLibraryProvider(com.ibm.cohort.cql.library.PriorityCqlLibraryProvider) FhirClientBuilderFactory(com.ibm.cohort.fhir.client.config.FhirClientBuilderFactory) Parameter(com.beust.jcommander.Parameter) ClasspathCqlLibraryProvider(com.ibm.cohort.cql.library.ClasspathCqlLibraryProvider) Map(java.util.Map) HashMap(java.util.HashMap) CqlEvaluator(com.ibm.cohort.cql.evaluation.CqlEvaluator) CqlVersionedIdentifier(com.ibm.cohort.cql.library.CqlVersionedIdentifier)

Example 17 with CqlEvaluator

use of com.ibm.cohort.cql.evaluation.CqlEvaluator in project quality-measure-and-cohort-service by Alvearie.

the class CqlEvaluatorIntegrationTest method testCannotConnectToFHIRDataServer.

// @Test
// @Ignore // uncomment when JSON ELMs start working -
// // https://github.com/DBCG/cql_engine/issues/405
// public void testJsonCQLWithIncludes() throws Exception {
// Patient patient = getPatient("123", Enumerations.AdministrativeGender.FEMALE, "1978-05-06");
// 
// CqlEvaluator wrapper = setupTestFor(patient, "cql/includes/Breast-Cancer-Screening.json");
// 
// final AtomicBoolean found = new AtomicBoolean(false);
// final AtomicInteger count = new AtomicInteger(0);
// wrapper.evaluate("Breast-Cancer-Screening", "1", /* parameters= */null, null, Arrays.asList("123"),
// (p, e, r) -> {
// count.incrementAndGet();
// if (e.equals("MeetsInclusionCriteria")) {
// assertEquals("Unexpected value for expression result", Boolean.TRUE, r);
// found.set(true);
// }
// });
// assertEquals("Missing expression result", true, found.get());
// verify(1, getRequestedFor(urlEqualTo("/Patient/123?_format=json")));
// }
@Test(expected = CqlException.class)
public void testCannotConnectToFHIRDataServer() throws Exception {
    Patient patient = new Patient();
    patient.setGender(Enumerations.AdministrativeGender.FEMALE);
    FhirServerConfig fhirConfig = new FhirServerConfig();
    fhirConfig.setEndpoint("http://its.not.me");
    CqlEvaluator evaluator = setupTestFor(patient, fhirConfig, "cql.basic");
    evaluator.evaluate(new CqlVersionedIdentifier("Test", "1.0.0"), null, newPatientContext("123"), Collections.singleton("Female"));
}
Also used : Patient(org.hl7.fhir.r4.model.Patient) FhirServerConfig(com.ibm.cohort.fhir.client.config.FhirServerConfig) CqlEvaluator(com.ibm.cohort.cql.evaluation.CqlEvaluator) CqlVersionedIdentifier(com.ibm.cohort.cql.library.CqlVersionedIdentifier) Test(org.junit.Test)

Example 18 with CqlEvaluator

use of com.ibm.cohort.cql.evaluation.CqlEvaluator in project quality-measure-and-cohort-service by Alvearie.

the class CqlEvaluatorIntegrationTest method testValueSetMembership.

@Test
public /**
 * This test exists to validate the the engine correctly expands a valueset
 * and correctly determines resources that overlap the valueset membership.
 *
 * @throws Exception on any error.
 */
void testValueSetMembership() throws Exception {
    Patient patient = getPatient("123", Enumerations.AdministrativeGender.FEMALE, "1983-12-02");
    Condition condition = new Condition();
    condition.setId("Condition");
    condition.setSubject(new Reference(patient));
    condition.getCode().addCoding().setSystem("SNOMED-CT").setCode("1234");
    // This stub works for [Condition] c where c.code in "ValueSet"
    mockFhirResourceRetrieval("/Condition?subject=Patient%2F123&_format=json", condition);
    // These stub works for [Condition: "ValueSet"]
    mockFhirResourceRetrieval("/Condition?code=SNOMED-CT%7C1234&subject=Patient%2F123&_format=json", makeBundle(condition));
    mockFhirResourceRetrieval("/Condition?code=SNOMED-CT%7C5678&subject=Patient%2F123&_format=json", makeBundle());
    mockValueSetRetrieval("https://cts.nlm.nih.gov/fhir/ValueSet/1.2.3.4", "SNOMED-CT", "1234");
    mockValueSetRetrieval("https://cts.nlm.nih.gov/fhir/ValueSet/5.6.7.8", "SNOMED-CT", "5678");
    // We have to add a one off mock valueset endpoint for when the engine checks if 1234 is in the 5.6.7.8 valueset
    Parameters response = new Parameters();
    response.addParameter().setValue(new BooleanType(false));
    mockFhirResourceRetrieval("/ValueSet/5.6.7.8/$validate-code?code=1234&system=SNOMED-CT&_format=json", response);
    CqlEvaluator evaluator = setupTestFor(patient, "cql.valueset", ClasspathCqlLibraryProvider.FHIR_HELPERS_CLASSPATH);
    CqlEvaluationResult actual = evaluator.evaluate(new CqlVersionedIdentifier("Test", "1.0.0"), newPatientContext("123"));
    Map<String, Object> results = actual.getExpressionResults();
    Assert.assertEquals(5, results.size());
    Assert.assertEquals(true, results.get("RHSRetrieveMatches"));
    Assert.assertEquals(true, results.get("RHSInOperatorMatches"));
    Assert.assertEquals(true, results.get("RHSRetrieveNotMatches"));
    Assert.assertEquals(true, results.get("RHSInOperatorNotMatches"));
    assertFhirEquals(patient, (IBaseResource) results.get("Patient"));
}
Also used : Condition(org.hl7.fhir.r4.model.Condition) Parameters(org.hl7.fhir.r4.model.Parameters) Reference(org.hl7.fhir.r4.model.Reference) BooleanType(org.hl7.fhir.r4.model.BooleanType) Patient(org.hl7.fhir.r4.model.Patient) CqlEvaluationResult(com.ibm.cohort.cql.evaluation.CqlEvaluationResult) CqlEvaluator(com.ibm.cohort.cql.evaluation.CqlEvaluator) CqlVersionedIdentifier(com.ibm.cohort.cql.library.CqlVersionedIdentifier) Test(org.junit.Test)

Example 19 with CqlEvaluator

use of com.ibm.cohort.cql.evaluation.CqlEvaluator in project quality-measure-and-cohort-service by Alvearie.

the class CqlEvaluatorIntegrationTest method testConditionClinicalStatusActiveIsMatched.

@Test
public void testConditionClinicalStatusActiveIsMatched() throws Exception {
    Patient patient = getPatient("123", Enumerations.AdministrativeGender.FEMALE, null);
    Condition condition = new Condition();
    condition.setId("condition");
    condition.setSubject(new Reference("Patient/123"));
    condition.setClinicalStatus(new CodeableConcept().addCoding(new Coding().setCode("active").setSystem("http://terminology.hl7.org/CodeSystem/condition-clinical")).setText("Active"));
    mockFhirResourceRetrieval("/Condition?subject=Patient%2F123&_format=json", condition);
    FhirServerConfig fhirConfig = getFhirServerConfig();
    CqlEvaluator evaluator = setupTestFor(patient, fhirConfig, "cql.condition", ClasspathCqlLibraryProvider.FHIR_HELPERS_CLASSPATH);
    String expression = "HasActiveCondition";
    CqlEvaluationResult actual = evaluator.evaluate(new CqlVersionedIdentifier("TestStatusActive", "1.0.0"), null, newPatientContext("123"), Collections.singleton(expression));
    Map<String, Object> expected = new HashMap<>();
    expected.put(expression, true);
    Assert.assertEquals(expected, actual.getExpressionResults());
}
Also used : Condition(org.hl7.fhir.r4.model.Condition) HashMap(java.util.HashMap) Reference(org.hl7.fhir.r4.model.Reference) Patient(org.hl7.fhir.r4.model.Patient) CqlEvaluationResult(com.ibm.cohort.cql.evaluation.CqlEvaluationResult) Coding(org.hl7.fhir.r4.model.Coding) FhirServerConfig(com.ibm.cohort.fhir.client.config.FhirServerConfig) CqlEvaluator(com.ibm.cohort.cql.evaluation.CqlEvaluator) CodeableConcept(org.hl7.fhir.r4.model.CodeableConcept) CqlVersionedIdentifier(com.ibm.cohort.cql.library.CqlVersionedIdentifier) Test(org.junit.Test)

Example 20 with CqlEvaluator

use of com.ibm.cohort.cql.evaluation.CqlEvaluator in project quality-measure-and-cohort-service by Alvearie.

the class CqlEvaluatorIntegrationTest method runUnsupportedValueSetPropertyTest.

private void runUnsupportedValueSetPropertyTest(String expression) throws Exception {
    Patient patient = getPatient("123", Enumerations.AdministrativeGender.FEMALE, "1983-12-02");
    Condition condition = new Condition();
    condition.setId("Condition");
    condition.setSubject(new Reference(patient));
    condition.getCode().addCoding().setSystem("SNOMED-CT").setCode("1234");
    // This stub works for [Condition] c where c.code in "ValueSet"
    mockFhirResourceRetrieval("/Condition?subject=Patient%2F123&_format=json", condition);
    CqlEvaluator evaluator = setupTestFor(patient, "cql.valueset", ClasspathCqlLibraryProvider.FHIR_HELPERS_CLASSPATH);
    CqlException ex = assertThrows("Missing expected exception", CqlException.class, () -> {
        evaluator.evaluate(new CqlVersionedIdentifier("TestUnsupported", "1.0.0"), null, newPatientContext("123"), Collections.singleton(expression));
    });
    assertTrue("Unexpected exception message: " + ex.getMessage(), ex.getMessage().contains("version and code system bindings are not supported at this time"));
}
Also used : Condition(org.hl7.fhir.r4.model.Condition) Reference(org.hl7.fhir.r4.model.Reference) Patient(org.hl7.fhir.r4.model.Patient) CqlEvaluator(com.ibm.cohort.cql.evaluation.CqlEvaluator) CqlException(org.opencds.cqf.cql.engine.exception.CqlException) CqlVersionedIdentifier(com.ibm.cohort.cql.library.CqlVersionedIdentifier)

Aggregations

CqlEvaluator (com.ibm.cohort.cql.evaluation.CqlEvaluator)34 CqlVersionedIdentifier (com.ibm.cohort.cql.library.CqlVersionedIdentifier)31 Patient (org.hl7.fhir.r4.model.Patient)29 Test (org.junit.Test)29 CqlEvaluationResult (com.ibm.cohort.cql.evaluation.CqlEvaluationResult)28 HashMap (java.util.HashMap)26 FhirServerConfig (com.ibm.cohort.fhir.client.config.FhirServerConfig)14 Date (java.util.Date)7 CqlDataProvider (com.ibm.cohort.cql.data.CqlDataProvider)5 DateTimeType (org.hl7.fhir.r4.model.DateTimeType)5 Observation (org.hl7.fhir.r4.model.Observation)5 DatetimeParameter (com.ibm.cohort.cql.evaluation.parameters.DatetimeParameter)4 IntegerParameter (com.ibm.cohort.cql.evaluation.parameters.IntegerParameter)4 IntervalParameter (com.ibm.cohort.cql.evaluation.parameters.IntervalParameter)4 Parameter (com.ibm.cohort.cql.evaluation.parameters.Parameter)4 List (java.util.List)4 Condition (org.hl7.fhir.r4.model.Condition)4 Reference (org.hl7.fhir.r4.model.Reference)4 ClasspathCqlLibraryProvider (com.ibm.cohort.cql.library.ClasspathCqlLibraryProvider)3 CqlLibraryProvider (com.ibm.cohort.cql.library.CqlLibraryProvider)3