Search in sources :

Example 11 with CqlVersionedIdentifier

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

the class CqlTemporalTests method anEventDoesFollow.

@Test
public void anEventDoesFollow() throws Exception {
    Patient patient = getPatient("123", Enumerations.AdministrativeGender.FEMALE, null);
    FhirServerConfig fhirConfig = getFhirServerConfig();
    mockFhirResourceRetrieval("/Encounter?subject=Patient%2F123&_format=json", getFhirParser(), ENCOUNTER_1, fhirConfig);
    mockFhirResourceRetrieval("/Condition?subject=Patient%2F123&_format=json", getFhirParser(), CONDITION_IN, fhirConfig);
    CqlEvaluator evaluator = setupTestFor(patient, "cql.temporal", ClasspathCqlLibraryProvider.FHIR_HELPERS_CLASSPATH);
    String expression = "NotFollowedByCondition";
    CqlEvaluationResult actual = evaluator.evaluate(new CqlVersionedIdentifier("Test4", "1.0.0"), null, newPatientContext("123"), Collections.singleton(expression));
    Map<String, Object> expected = new HashMap<>();
    expected.put(expression, false);
    Assert.assertEquals(expected, actual.getExpressionResults());
}
Also used : HashMap(java.util.HashMap) Patient(org.hl7.fhir.r4.model.Patient) FhirServerConfig(com.ibm.cohort.fhir.client.config.FhirServerConfig) 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 12 with CqlVersionedIdentifier

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

the class DataRowDataProviderTest method testEvaluateSuccess.

@Test
public void testEvaluateSuccess() throws Exception {
    CqlLibraryProvider backingProvider = new ClasspathCqlLibraryProvider("cql");
    CqlToElmTranslator translator = new CqlToElmTranslator();
    try (Reader r = new FileReader(new File("src/test/resources/modelinfo/mock-modelinfo-1.0.0.xml"))) {
        translator.registerModelInfo(r);
    }
    CqlLibraryProvider libraryProvider = new TranslatingCqlLibraryProvider(backingProvider, translator);
    CqlVersionedIdentifier topLevelLibraryIdentifier = new CqlVersionedIdentifier("SampleLibrary", "1.0.0");
    CqlTerminologyProvider terminologyProvider = new UnsupportedTerminologyProvider();
    Map<String, Object> row = new HashMap<>();
    row.put("id", "123");
    row.put("gender", "female");
    row.put("birthDate", new DateTime(OffsetDateTime.now()));
    Map<String, Iterable<Object>> data = new HashMap<>();
    data.put("Patient", Arrays.asList(new SimpleDataRow(row)));
    DataRowRetrieveProvider retrieveProvider = new DataRowRetrieveProvider(data, terminologyProvider);
    CqlDataProvider dataProvider = new CompositeCqlDataProvider(new DataRowModelResolver(SimpleDataRow.class), retrieveProvider);
    CqlEvaluator evaluator = new CqlEvaluator().setLibraryProvider(libraryProvider).setTerminologyProvider(terminologyProvider).setDataProvider(dataProvider).setCacheContexts(false);
    CqlEvaluationResult result = evaluator.evaluate(topLevelLibraryIdentifier);
    assertEquals(2, result.getExpressionResults().size());
    Object perDefineResult = result.getExpressionResults().get("IsFemale");
    assertEquals(Boolean.TRUE, perDefineResult);
}
Also used : UnsupportedTerminologyProvider(com.ibm.cohort.cql.terminology.UnsupportedTerminologyProvider) TranslatingCqlLibraryProvider(com.ibm.cohort.cql.translation.TranslatingCqlLibraryProvider) HashMap(java.util.HashMap) Reader(java.io.Reader) FileReader(java.io.FileReader) CompositeCqlDataProvider(com.ibm.cohort.cql.data.CompositeCqlDataProvider) CqlToElmTranslator(com.ibm.cohort.cql.translation.CqlToElmTranslator) CqlEvaluationResult(com.ibm.cohort.cql.evaluation.CqlEvaluationResult) ClasspathCqlLibraryProvider(com.ibm.cohort.cql.library.ClasspathCqlLibraryProvider) CqlLibraryProvider(com.ibm.cohort.cql.library.CqlLibraryProvider) TranslatingCqlLibraryProvider(com.ibm.cohort.cql.translation.TranslatingCqlLibraryProvider) OffsetDateTime(java.time.OffsetDateTime) DateTime(org.opencds.cqf.cql.engine.runtime.DateTime) SimpleDataRow(com.ibm.cohort.datarow.model.SimpleDataRow) FileReader(java.io.FileReader) ClasspathCqlLibraryProvider(com.ibm.cohort.cql.library.ClasspathCqlLibraryProvider) CqlTerminologyProvider(com.ibm.cohort.cql.terminology.CqlTerminologyProvider) File(java.io.File) CqlDataProvider(com.ibm.cohort.cql.data.CqlDataProvider) CompositeCqlDataProvider(com.ibm.cohort.cql.data.CompositeCqlDataProvider) CqlEvaluator(com.ibm.cohort.cql.evaluation.CqlEvaluator) CqlVersionedIdentifier(com.ibm.cohort.cql.library.CqlVersionedIdentifier) Test(org.junit.Test)

Example 13 with CqlVersionedIdentifier

use of com.ibm.cohort.cql.library.CqlVersionedIdentifier 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 14 with CqlVersionedIdentifier

use of com.ibm.cohort.cql.library.CqlVersionedIdentifier 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 15 with CqlVersionedIdentifier

use of com.ibm.cohort.cql.library.CqlVersionedIdentifier 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)

Aggregations

CqlVersionedIdentifier (com.ibm.cohort.cql.library.CqlVersionedIdentifier)33 CqlEvaluator (com.ibm.cohort.cql.evaluation.CqlEvaluator)31 Test (org.junit.Test)31 Patient (org.hl7.fhir.r4.model.Patient)29 CqlEvaluationResult (com.ibm.cohort.cql.evaluation.CqlEvaluationResult)27 HashMap (java.util.HashMap)27 FhirServerConfig (com.ibm.cohort.fhir.client.config.FhirServerConfig)14 Date (java.util.Date)7 IntegerParameter (com.ibm.cohort.cql.evaluation.parameters.IntegerParameter)6 Parameter (com.ibm.cohort.cql.evaluation.parameters.Parameter)6 DateTimeType (org.hl7.fhir.r4.model.DateTimeType)6 Observation (org.hl7.fhir.r4.model.Observation)6 DatetimeParameter (com.ibm.cohort.cql.evaluation.parameters.DatetimeParameter)4 IntervalParameter (com.ibm.cohort.cql.evaluation.parameters.IntervalParameter)4 ClasspathCqlLibraryProvider (com.ibm.cohort.cql.library.ClasspathCqlLibraryProvider)4 CqlTerminologyProvider (com.ibm.cohort.cql.terminology.CqlTerminologyProvider)4 TranslatingCqlLibraryProvider (com.ibm.cohort.cql.translation.TranslatingCqlLibraryProvider)4 Bundle (org.hl7.fhir.r4.model.Bundle)4 Condition (org.hl7.fhir.r4.model.Condition)4 Reference (org.hl7.fhir.r4.model.Reference)4