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;
}
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"));
}
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"));
}
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());
}
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"));
}
Aggregations