use of org.cqframework.cql.elm.execution.ExpressionDef in project quality-measure-and-cohort-service by Alvearie.
the class MeasureSupplementalDataEvaluationTest method getSDEAccumulators.
private Map<String, Map<String, Integer>> getSDEAccumulators(String defineName, String text, Object expressionRetval, Map<String, Map<String, Integer>> initialAccumulators) {
Map<String, Map<String, Integer>> sdeAccumulators = initialAccumulators;
ExpressionDef mockExpressionDef = Mockito.mock(ExpressionDef.class);
CDMContext context = Mockito.mock(CDMContext.class);
Mockito.when(context.resolveExpressionRef(defineName)).thenReturn(mockExpressionDef);
Mockito.when(mockExpressionDef.evaluate(context)).thenReturn(expressionRetval);
MeasureSupplementalDataEvaluation.populateSDEAccumulators(context, mockPatient(), sdeAccumulators, Arrays.asList(createSupplementalDataComponent(defineName, text)));
return sdeAccumulators;
}
use of org.cqframework.cql.elm.execution.ExpressionDef in project quality-measure-and-cohort-service by Alvearie.
the class MeasureEvaluation method evaluateCriteria.
@SuppressWarnings("unchecked")
private Iterable<Resource> evaluateCriteria(Context context, Patient patient, Measure.MeasureGroupPopulationComponent pop) {
if (pop == null || !pop.hasCriteria()) {
return Collections.emptyList();
}
context.setContextValue(PATIENT, patient.getIdElement().getIdPart());
ExpressionDef populationExpressionDef = context.resolveExpressionRef(pop.getCriteria().getExpression());
Object result = populationExpressionDef.evaluate(context);
if (result == null) {
return Collections.emptyList();
}
if (result instanceof Boolean) {
if (((Boolean) result)) {
return Collections.singletonList(patient);
} else {
return Collections.emptyList();
}
}
return (Iterable<Resource>) result;
}
use of org.cqframework.cql.elm.execution.ExpressionDef in project quality-measure-and-cohort-service by Alvearie.
the class CqlEvaluator method evaluate.
public CqlEvaluationResult evaluate(CqlVersionedIdentifier topLevelLibraryIdentifier, Map<String, Parameter> parameters, Pair<String, String> context, Set<String> expressions, CqlDebug debug, ZonedDateTime batchDateTime) throws CqlLibraryDeserializationException {
if (this.libraryProvider == null) {
throw new IllegalArgumentException("Missing libraryProvider");
} else if (this.dataProvider == null) {
throw new IllegalArgumentException("Missing dataProvider");
} else if (this.terminologyProvider == null) {
throw new IllegalArgumentException("Missing terminologyProvider");
} else if (topLevelLibraryIdentifier == null) {
throw new IllegalArgumentException("Missing library identifier");
}
CqlContextFactory contextFactory = new CqlContextFactory();
contextFactory.setExternalFunctionProvider(this.externalFunctionProvider);
contextFactory.setCacheContexts(cacheContexts);
Context cqlContext = contextFactory.createContext(libraryProvider, topLevelLibraryIdentifier, terminologyProvider, dataProvider, batchDateTime, context, parameters, debug);
if (expressions == null) {
expressions = cqlContext.getCurrentLibrary().getStatements().getDef().stream().map(ExpressionDef::getName).collect(Collectors.toCollection(LinkedHashSet::new));
}
Map<String, Object> results = new LinkedHashMap<>();
for (String expression : expressions) {
ExpressionDef expressionDef = cqlContext.resolveExpressionRef(expression);
// also explicitly skips over FunctionDefs.
if (!(expressionDef instanceof FunctionDef)) {
Object result = cqlContext.resolveExpressionRef(expression).evaluate(cqlContext);
results.put(expression, result);
}
}
if (context != null) {
cqlContext.setContextValue(context.getLeft(), context.getRight());
}
return new CqlEvaluationResult(results);
}
use of org.cqframework.cql.elm.execution.ExpressionDef in project synthea by synthetichealth.
the class ExpressionProcessor method evaluate.
/**
* Evaluates the expression with the given parameters.
* @param params parameters as a map of variable names to values
* @return evaluation result
*/
public Object evaluate(Map<String, Object> params) {
// Keep track to make sure all parameters are set
Set<String> setParams = new HashSet<String>();
for (Entry<String, Object> entry : params.entrySet()) {
// Set the CQL compatible parameter name in the context
context.setParameter(null, cqlParamMap.get(entry.getKey()), entry.getValue());
setParams.add(entry.getKey());
}
Set<String> missing = Sets.difference(cqlParamMap.keySet(), setParams);
Set<String> extra = Sets.difference(setParams, cqlParamMap.keySet());
if (missing.size() > 0) {
throw new IllegalArgumentException("Missing parameter(s): " + String.join(", ", missing) + " for expression \"" + expression + "\"");
}
if (extra.size() > 0) {
Logger.getLogger(ExpressionProcessor.class.getName()).log(Level.WARNING, "unused parameter(s) provided for expression \"{0}\": {1}", new Object[] { expression, String.join(", ", extra) });
}
Object retVal = null;
for (ExpressionDef statement : library.getStatements().getDef()) {
retVal = statement.evaluate(context);
}
try {
return retVal;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
use of org.cqframework.cql.elm.execution.ExpressionDef in project quality-measure-and-cohort-service by Alvearie.
the class SparkSchemaCreator method calculateSchemaForContext.
public StructType calculateSchemaForContext(String contextName) throws Exception {
List<CqlEvaluationRequest> filteredRequests = requests.getEvaluationsForContext(contextName);
StructType resultsSchema = new StructType();
Set<Tuple2<String, String>> usingInfo = new HashSet<>();
for (CqlEvaluationRequest filteredRequest : filteredRequests) {
CqlLibraryDescriptor descriptor = filteredRequest.getDescriptor();
String libraryId = descriptor.getLibraryId();
for (String expression : filteredRequest.getExpressionNames()) {
CqlLibrary providedLibrary = libraryProvider.getLibrary(new CqlLibraryDescriptor().setLibraryId(libraryId).setVersion(descriptor.getVersion()).setFormat(Format.ELM));
if (providedLibrary == null) {
throw new IllegalArgumentException("Library not found: " + descriptor.getLibraryId() + "-" + descriptor.getVersion());
}
Library library = CqlLibraryReader.read(providedLibrary.getContentAsStream());
// Track the set of non-system using statements across libraries.
// Information is used later to access ModelInfos when searching
// for context key column type information.
usingInfo.addAll(library.getUsings().getDef().stream().filter(x -> !x.getLocalIdentifier().equals("System")).map(x -> new Tuple2<>(x.getLocalIdentifier(), x.getVersion())).collect(Collectors.toList()));
List<ExpressionDef> expressionDefs = library.getStatements().getDef().stream().filter(x -> x.getName().equals(expression)).collect(Collectors.toList());
if (expressionDefs.isEmpty()) {
throw new IllegalArgumentException("Expression " + expression + " is configured in the CQL jobs file, but not found in " + descriptor.getLibraryId() + "-" + descriptor.getVersion());
} else if (expressionDefs.size() > 1) {
throw new IllegalArgumentException("Expression " + expression + " was defined multiple times in library: " + descriptor.getLibraryId() + "-" + descriptor.getVersion());
}
QName resultTypeName = expressionDefs.get(0).getExpression().getResultTypeName();
if (resultTypeName == null) {
throw new IllegalArgumentException("Expression " + expression + " has a null result type: " + descriptor.getLibraryId() + "-" + descriptor.getVersion());
}
// The column name encoder already performed duplicate checking. We just need to make sure
// we add each uniquely named column to the output one time.
String columnName = sparkOutputColumnEncoder.getColumnName(filteredRequest, expression);
if (resultsSchema.getFieldIndex(columnName).isEmpty()) {
resultsSchema = resultsSchema.add(columnName, QNameToDataTypeConverter.getFieldType(resultTypeName), true);
}
}
}
if (resultsSchema.fields().length > 0) {
Tuple2<String, DataType> keyInformation = getDataTypeForContextKey(contextName, usingInfo);
StructType fullSchema = new StructType().add(keyInformation._1(), keyInformation._2(), false).add(getParametersColumnName(), DataTypes.StringType, false);
for (StructField field : resultsSchema.fields()) {
fullSchema = fullSchema.add(field);
}
resultsSchema = fullSchema;
}
return resultsSchema;
}
Aggregations