Search in sources :

Example 6 with Context

use of org.opencds.cqf.cql.engine.execution.Context in project CRD by HL7-DaVinci.

the class CqlExecutionContextBuilder method getExecutionContext.

public static Context getExecutionContext(CqlRule cqlRule, HashMap<String, Resource> cqlParams, String baseUrl) {
    ModelManager modelManager = new ModelManager();
    LibraryManager libraryManager = new LibraryManager(modelManager);
    libraryManager.getLibrarySourceLoader().clearProviders();
    Library library = null;
    LibraryLoader libraryLoader = null;
    if (cqlRule.isPrecompiled()) {
    // todo
    } else {
        libraryManager.getLibrarySourceLoader().registerProvider(cqlRule.getRawCqlLibrarySourceProvider(CQL_VERSION));
        libraryLoader = new LocalLibraryLoader(libraryManager);
        try {
            library = CqlExecution.translate(cqlRule.getRawMainCqlLibrary(CQL_VERSION), libraryManager, modelManager);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    FhirContext fhirContext = FhirContext.forR4();
    Context context = new Context(library);
    context.registerLibraryLoader(libraryLoader);
    context.setExpressionCaching(true);
    R4FhirModelResolver modelResolver = new R4FhirModelResolver();
    RestFhirRetrieveProvider retrieveProvider = new RestFhirRetrieveProvider(new SearchParameterResolver(fhirContext), fhirContext.newRestfulGenericClient("http://fhirtest.uhn.ca/baseR4"));
    CompositeDataProvider provider = new CompositeDataProvider(modelResolver, retrieveProvider);
    context.registerDataProvider("http://hl7.org/fhir", provider);
    for (Map.Entry<String, org.hl7.fhir.r4.model.Resource> entry : cqlParams.entrySet()) {
        context.setParameter(null, entry.getKey(), entry.getValue());
    }
    context.setParameter(null, "base_url", baseUrl);
    return context;
}
Also used : Context(org.opencds.cqf.cql.engine.execution.Context) FhirContext(ca.uhn.fhir.context.FhirContext) FhirContext(ca.uhn.fhir.context.FhirContext) Resource(org.hl7.fhir.r4.model.Resource) ModelManager(org.cqframework.cql.cql2elm.ModelManager) LibraryLoader(org.opencds.cqf.cql.engine.execution.LibraryLoader) LocalLibraryLoader(org.hl7.davinci.endpoint.cql.LocalLibraryLoader) R4FhirModelResolver(org.opencds.cqf.cql.engine.fhir.model.R4FhirModelResolver) SearchParameterResolver(org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver) LocalLibraryLoader(org.hl7.davinci.endpoint.cql.LocalLibraryLoader) RestFhirRetrieveProvider(org.opencds.cqf.cql.engine.fhir.retrieve.RestFhirRetrieveProvider) LibraryManager(org.cqframework.cql.cql2elm.LibraryManager) CompositeDataProvider(org.opencds.cqf.cql.engine.data.CompositeDataProvider) Library(org.cqframework.cql.elm.execution.Library) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with Context

use of org.opencds.cqf.cql.engine.execution.Context in project cqf-ruler by DBCG.

the class ExpressionEvaluation method evaluateInContext.

/* Evaluates the given CQL expression in the context of the given resource */
/*
	 * If the resource has a library extension, or a library element, that library
	 * is loaded into the context for the expression
	 */
public Object evaluateInContext(DomainResource instance, String cql, Boolean aliasedExpression, String patientId, RequestDetails theRequest) {
    JpaFhirDal jpaFhirDal = jpaFhirDalFactory.create(theRequest);
    List<Reference> libraries = getLibraryReferences(instance, jpaFhirDal, theRequest);
    // String fhirVersion =
    // this.context.getVersion().getVersion().getFhirVersionString();
    String fhirVersion = "3.0.0";
    // temporary LibraryLoader to resolve library dependencies when building
    // includes
    LibraryLoader tempLibraryLoader = libraryLoaderFactory.create(new ArrayList<LibraryContentProvider>(Arrays.asList(jpaLibraryContentProviderFactory.create(theRequest))));
    String source = "";
    if (aliasedExpression) {
        if (libraries.size() != 1) {
            throw new RuntimeException("If an aliased expression is provided, there must be exactly one primary Library");
        }
        VersionedIdentifier vi = getVersionedIdentifierFromReference(libraries.get(0));
        // Still not the best way to build include, but at least checks dal for an
        // existing library
        // Check if id works for LibraryRetrieval
        org.cqframework.cql.elm.execution.Library executionLibrary = null;
        try {
            executionLibrary = tempLibraryLoader.load(vi);
        } catch (Exception e) {
        // log error
        }
        if (executionLibrary == null) {
            Library library = (Library) jpaFhirDal.read(new IdType("Library", vi.getId()));
            vi.setId(library.getName());
            if (library.getVersion() != null) {
                vi.setVersion(library.getVersion());
            }
        }
        // Provide the instance as the value of the '%context' parameter, as well as the
        // value of a parameter named the same as the resource
        // This enables expressions to access the resource by root, as well as through
        // the %context attribute
        source = String.format("library LocalLibrary using FHIR version '" + fhirVersion + "' include FHIRHelpers version '" + fhirVersion + "' called FHIRHelpers %s parameter %s %s parameter \"%%context\" %s define Expression: %s", buildIncludes(tempLibraryLoader, jpaFhirDal, libraries), instance.fhirType(), instance.fhirType(), instance.fhirType(), vi.getId() + ".\"" + cql + "\"");
    // String source = String.format("library LocalLibrary using FHIR version '1.8'
    // include FHIRHelpers version '1.8' called FHIRHelpers %s parameter %s %s
    // parameter \"%%context\" %s define Expression: %s",
    // buildIncludes(libraries), instance.fhirType(), instance.fhirType(),
    // instance.fhirType(), cql);
    } else {
        // Provide the instance as the value of the '%context' parameter, as well as the
        // value of a parameter named the same as the resource
        // This enables expressions to access the resource by root, as well as through
        // the %context attribute
        source = String.format("library LocalLibrary using FHIR version '" + fhirVersion + "' include FHIRHelpers version '" + fhirVersion + "' called FHIRHelpers %s parameter %s %s parameter \"%%context\" %s define Expression: %s", buildIncludes(tempLibraryLoader, jpaFhirDal, libraries), instance.fhirType(), instance.fhirType(), instance.fhirType(), cql);
    }
    LibraryLoader libraryLoader = libraryLoaderFactory.create(new ArrayList<LibraryContentProvider>(Arrays.asList(jpaLibraryContentProviderFactory.create(theRequest), new InMemoryLibraryContentProvider(Arrays.asList(source)))));
    // Remove LocalLibrary from cache first...
    VersionedIdentifier localLibraryIdentifier = new VersionedIdentifier().withId("LocalLibrary");
    globalLibraryCache.remove(localLibraryIdentifier);
    Context context = new Context(libraryLoader.load(localLibraryIdentifier));
    context.setDebugMap(getDebugMap());
    context.setParameter(null, instance.fhirType(), instance);
    context.setParameter(null, "%context", instance);
    context.setExpressionCaching(true);
    context.registerLibraryLoader(libraryLoader);
    context.setContextValue("Patient", patientId);
    TerminologyProvider terminologyProvider = jpaTerminologyProviderFactory.create(theRequest);
    context.registerTerminologyProvider(terminologyProvider);
    DataProvider dataProvider = jpaDataProviderFactory.create(theRequest, terminologyProvider);
    context.registerDataProvider("http://hl7.org/fhir", dataProvider);
    return context.resolveExpressionRef("Expression").evaluate(context);
}
Also used : Context(org.opencds.cqf.cql.engine.execution.Context) LibraryContentProvider(org.opencds.cqf.cql.evaluator.cql2elm.content.LibraryContentProvider) InMemoryLibraryContentProvider(org.opencds.cqf.cql.evaluator.cql2elm.content.InMemoryLibraryContentProvider) InMemoryLibraryContentProvider(org.opencds.cqf.cql.evaluator.cql2elm.content.InMemoryLibraryContentProvider) Reference(org.hl7.fhir.dstu3.model.Reference) JpaFhirDal(org.opencds.cqf.ruler.cql.JpaFhirDal) LibraryLoader(org.opencds.cqf.cql.engine.execution.LibraryLoader) IdType(org.hl7.fhir.dstu3.model.IdType) DataProvider(org.opencds.cqf.cql.engine.data.DataProvider) VersionedIdentifier(org.cqframework.cql.elm.execution.VersionedIdentifier) TerminologyProvider(org.opencds.cqf.cql.engine.terminology.TerminologyProvider) Library(org.hl7.fhir.dstu3.model.Library)

Example 8 with Context

use of org.opencds.cqf.cql.engine.execution.Context in project cqf-ruler by DBCG.

the class ExpressionEvaluation method setupContext.

private Context setupContext(DomainResource instance, String patientId, LibraryLoader libraryLoader, RequestDetails theRequest) {
    // Provide the instance as the value of the '%context' parameter, as well as the
    // value of a parameter named the same as the resource
    // This enables expressions to access the resource by root, as well as through
    // the %context attribute
    Context context = new Context(libraryLoader.load(new VersionedIdentifier().withId("LocalLibrary")));
    context.setDebugMap(getDebugMap());
    context.setParameter(null, instance.fhirType(), instance);
    context.setParameter(null, "%context", instance);
    context.setExpressionCaching(true);
    context.registerLibraryLoader(libraryLoader);
    context.setContextValue("Patient", patientId);
    TerminologyProvider terminologyProvider = jpaTerminologyProviderFactory.create(theRequest);
    context.registerTerminologyProvider(terminologyProvider);
    DataProvider dataProvider = jpaDataProviderFactory.create(theRequest, terminologyProvider);
    context.registerDataProvider("http://hl7.org/fhir", dataProvider);
    return context;
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) Context(org.opencds.cqf.cql.engine.execution.Context) DataProvider(org.opencds.cqf.cql.engine.data.DataProvider) VersionedIdentifier(org.cqframework.cql.elm.execution.VersionedIdentifier) TerminologyProvider(org.opencds.cqf.cql.engine.terminology.TerminologyProvider)

Example 9 with Context

use of org.opencds.cqf.cql.engine.execution.Context in project quality-measure-and-cohort-service by Alvearie.

the class MeasureEvaluationSeeder method createContext.

protected Context createContext(org.cqframework.cql.elm.execution.Library library, String modelUri, DataProvider dataProvider, String productLine, LibraryLoader libraryLoader) {
    Context context = createDefaultContext(library);
    context.registerLibraryLoader(libraryLoader);
    context.registerTerminologyProvider(terminologyProvider);
    context.registerDataProvider(modelUri, dataProvider);
    if (productLine != null) {
        context.setParameter(null, "Product Line", productLine);
    }
    if (enableExpressionCaching) {
        context.setExpressionCaching(true);
    }
    if (debugMode) {
        DebugMap debugMap = new DebugMap();
        debugMap.setIsLoggingEnabled(true);
        context.setDebugMap(debugMap);
    }
    return context;
}
Also used : CDMContext(com.ibm.cohort.engine.cqfruler.CDMContext) Context(org.opencds.cqf.cql.engine.execution.Context) DebugMap(org.opencds.cqf.cql.engine.debug.DebugMap)

Example 10 with Context

use of org.opencds.cqf.cql.engine.execution.Context in project quality-measure-and-cohort-service by Alvearie.

the class MeasureEvaluationSeeder method create.

public IMeasureEvaluationSeed create(Measure measure, String periodStart, String periodEnd, String productLine, Map<String, Parameter> parameters) {
    // Gather the primary library and all of its dependencies
    List<Library> fhirLibraries = libraryDependencyGatherer.gatherForMeasure(measure);
    if (CollectionUtils.isEmpty(fhirLibraries)) {
        throw new IllegalArgumentException(String.format("No libraries were able to be loaded for %s", measure.getId()));
    }
    // the "primary" library is always the first library loaded for the measure
    Library primaryFhirLibrary = fhirLibraries.get(0);
    VersionedIdentifier libraryIdentifier = new VersionedIdentifier().withId(primaryFhirLibrary.getName()).withVersion(primaryFhirLibrary.getVersion());
    LibraryLoader libraryLoader = new R4TranslatingLibraryLoader(libraryResolver, new CqlToElmTranslator());
    org.cqframework.cql.elm.execution.Library primaryLibrary = libraryLoader.load(libraryIdentifier);
    List<Triple<String, String, String>> usingDefs = UsingHelper.getUsingUrlAndVersion(primaryLibrary.getUsings());
    if (usingDefs.size() > 1) {
        throw new IllegalArgumentException("Evaluation of Measure using multiple Models is not supported at this time.");
    }
    // Per the above condition, we should only have one model per measure
    String lastModelUri = usingDefs.get(usingDefs.size() - 1).getRight();
    DataProvider dataProvider = dataProviders.get(lastModelUri);
    Context context = createContext(primaryLibrary, lastModelUri, dataProvider, productLine, libraryLoader);
    // fhir path: Measure.extension[measureParameter][].valueParameterDefinition.extension[defaultValue]
    measure.getExtension().stream().filter(MeasureEvaluationSeeder::isMeasureParameter).map(parameter -> dataProvider.resolvePath(parameter, "valueParameterDefinition")).map(ParameterDefinition.class::cast).forEach(parameterDefinition -> setDefaultValue(context, parameterDefinition));
    if (parameters != null) {
        parameters.entrySet().stream().forEach(e -> context.setParameter(null, e.getKey(), e.getValue().toCqlType()));
    }
    // Set measurement period last to make sure we respect periodStart
    // and periodEnd date boundaries for an execution.
    Interval measurementPeriod = createMeasurePeriod(periodStart, periodEnd);
    context.setParameter(null, MEASUREMENT_PERIOD, measurementPeriod);
    return new CustomMeasureEvaluationSeed(measure, context, measurementPeriod, dataProvider);
}
Also used : CDMContext(com.ibm.cohort.engine.cqfruler.CDMContext) Context(org.opencds.cqf.cql.engine.execution.Context) CqlToElmTranslator(com.ibm.cohort.cql.translation.CqlToElmTranslator) R4TranslatingLibraryLoader(com.ibm.cohort.cql.hapi.R4TranslatingLibraryLoader) LibraryLoader(org.opencds.cqf.cql.engine.execution.LibraryLoader) Triple(org.apache.commons.lang3.tuple.Triple) CqlDataProvider(com.ibm.cohort.cql.data.CqlDataProvider) DataProvider(org.opencds.cqf.cql.engine.data.DataProvider) VersionedIdentifier(org.cqframework.cql.elm.execution.VersionedIdentifier) Library(org.hl7.fhir.r4.model.Library) R4TranslatingLibraryLoader(com.ibm.cohort.cql.hapi.R4TranslatingLibraryLoader) Interval(org.opencds.cqf.cql.engine.runtime.Interval)

Aggregations

Context (org.opencds.cqf.cql.engine.execution.Context)13 VersionedIdentifier (org.cqframework.cql.elm.execution.VersionedIdentifier)6 LibraryLoader (org.opencds.cqf.cql.engine.execution.LibraryLoader)6 FhirContext (ca.uhn.fhir.context.FhirContext)4 TerminologyProvider (org.opencds.cqf.cql.engine.terminology.TerminologyProvider)4 Map (java.util.Map)3 Test (org.junit.Test)3 DataProvider (org.opencds.cqf.cql.engine.data.DataProvider)3 SystemRequestDetails (ca.uhn.fhir.jpa.partition.SystemRequestDetails)2 RequestDetails (ca.uhn.fhir.rest.api.server.RequestDetails)2 BaseServerResponseException (ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException)2 InvalidRequestException (ca.uhn.fhir.rest.server.exceptions.InvalidRequestException)2 JsonParser (com.google.gson.JsonParser)2 CqlDataProvider (com.ibm.cohort.cql.data.CqlDataProvider)2 Parameter (com.ibm.cohort.cql.evaluation.parameters.Parameter)2 CqlVersionedIdentifier (com.ibm.cohort.cql.library.CqlVersionedIdentifier)2 CqlToElmTranslator (com.ibm.cohort.cql.translation.CqlToElmTranslator)2 CDMContext (com.ibm.cohort.engine.cqfruler.CDMContext)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2