Search in sources :

Example 1 with ExpressionDef

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;
}
Also used : ExpressionDef(org.cqframework.cql.elm.execution.ExpressionDef) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with ExpressionDef

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;
}
Also used : ExpressionDef(org.cqframework.cql.elm.execution.ExpressionDef)

Example 3 with ExpressionDef

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);
}
Also used : Context(org.opencds.cqf.cql.engine.execution.Context) LinkedHashSet(java.util.LinkedHashSet) ExpressionDef(org.cqframework.cql.elm.execution.ExpressionDef) FunctionDef(org.cqframework.cql.elm.execution.FunctionDef) LinkedHashMap(java.util.LinkedHashMap)

Example 4 with ExpressionDef

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);
    }
}
Also used : ExpressionDef(org.cqframework.cql.elm.execution.ExpressionDef) IOException(java.io.IOException) JAXBException(javax.xml.bind.JAXBException) HashSet(java.util.HashSet)

Example 5 with ExpressionDef

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;
}
Also used : DataType(org.apache.spark.sql.types.DataType) ModelInfo(org.hl7.elm_modelinfo.r1.ModelInfo) CqlToElmTranslator(com.ibm.cohort.cql.translation.CqlToElmTranslator) HashMap(java.util.HashMap) Format(com.ibm.cohort.cql.library.Format) ExpressionDef(org.cqframework.cql.elm.execution.ExpressionDef) ClassInfo(org.hl7.elm_modelinfo.r1.ClassInfo) HashSet(java.util.HashSet) ContextDefinition(com.ibm.cohort.cql.spark.aggregation.ContextDefinition) Map(java.util.Map) CqlLibraryReader(org.opencds.cqf.cql.engine.execution.CqlLibraryReader) CqlEvaluationRequest(com.ibm.cohort.cql.evaluation.CqlEvaluationRequest) ModelUtils(com.ibm.cohort.cql.spark.optimizer.ModelUtils) DataTypes(org.apache.spark.sql.types.DataTypes) StructField(org.apache.spark.sql.types.StructField) StructType(org.apache.spark.sql.types.StructType) ModelManager(org.cqframework.cql.cql2elm.ModelManager) Collection(java.util.Collection) VersionedIdentifier(org.hl7.elm.r1.VersionedIdentifier) Set(java.util.Set) CqlLibrary(com.ibm.cohort.cql.library.CqlLibrary) CqlLibraryProvider(com.ibm.cohort.cql.library.CqlLibraryProvider) Tuple2(scala.Tuple2) Collectors(java.util.stream.Collectors) CqlLibraryDescriptor(com.ibm.cohort.cql.library.CqlLibraryDescriptor) List(java.util.List) CqlEvaluationRequests(com.ibm.cohort.cql.evaluation.CqlEvaluationRequests) Library(org.cqframework.cql.elm.execution.Library) ClassInfoElement(org.hl7.elm_modelinfo.r1.ClassInfoElement) QName(javax.xml.namespace.QName) ContextDefinitions(com.ibm.cohort.cql.spark.aggregation.ContextDefinitions) StructType(org.apache.spark.sql.types.StructType) ExpressionDef(org.cqframework.cql.elm.execution.ExpressionDef) QName(javax.xml.namespace.QName) CqlEvaluationRequest(com.ibm.cohort.cql.evaluation.CqlEvaluationRequest) CqlLibrary(com.ibm.cohort.cql.library.CqlLibrary) StructField(org.apache.spark.sql.types.StructField) Tuple2(scala.Tuple2) DataType(org.apache.spark.sql.types.DataType) CqlLibrary(com.ibm.cohort.cql.library.CqlLibrary) Library(org.cqframework.cql.elm.execution.Library) CqlLibraryDescriptor(com.ibm.cohort.cql.library.CqlLibraryDescriptor) HashSet(java.util.HashSet)

Aggregations

ExpressionDef (org.cqframework.cql.elm.execution.ExpressionDef)6 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Map (java.util.Map)2 Collectors (java.util.stream.Collectors)2 JAXBException (javax.xml.bind.JAXBException)2 Library (org.cqframework.cql.elm.execution.Library)2 CqlEvaluationRequest (com.ibm.cohort.cql.evaluation.CqlEvaluationRequest)1 CqlEvaluationRequests (com.ibm.cohort.cql.evaluation.CqlEvaluationRequests)1 ShortAndEvaluator (com.ibm.cohort.cql.evaluator.ShortAndEvaluator)1 ShortOrEvaluator (com.ibm.cohort.cql.evaluator.ShortOrEvaluator)1 CqlLibrary (com.ibm.cohort.cql.library.CqlLibrary)1 CqlLibraryDescriptor (com.ibm.cohort.cql.library.CqlLibraryDescriptor)1 CqlLibraryProvider (com.ibm.cohort.cql.library.CqlLibraryProvider)1 Format (com.ibm.cohort.cql.library.Format)1 ContextDefinition (com.ibm.cohort.cql.spark.aggregation.ContextDefinition)1 ContextDefinitions (com.ibm.cohort.cql.spark.aggregation.ContextDefinitions)1 ModelUtils (com.ibm.cohort.cql.spark.optimizer.ModelUtils)1 CqlToElmTranslator (com.ibm.cohort.cql.translation.CqlToElmTranslator)1