org.opencds.cqf.cql.execution.Context Java Examples

The following examples show how to use org.opencds.cqf.cql.execution.Context. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExpressionDefEvaluator.java    From cql_engine with Apache License 2.0 7 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    if (this.getContext() != null) {
        context.enterContext(this.getContext());
    }
    try {
        if (context.isExpressionCachingEnabled() && context.isExpressionInCache(this.getName())) {
            return context.getExpressionResultFromCache(this.getName());
        }

        Object result = this.getExpression().evaluate(context);

        if (context.isExpressionCachingEnabled() && !context.isExpressionInCache(this.getName())) {
            context.addExpressionToCache(this.getName(), result);
        }

        return result;
    }
    finally {
        if (this.getContext() != null) {
            context.exitContext();
        }
    }
}
 
Example #2
Source File: ContainsEvaluator.java    From cql_engine with Apache License 2.0 6 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    Object left = getOperand().get(0).evaluate(context);
    Object right = getOperand().get(1).evaluate(context);
    String precision = getPrecision() == null ? null : getPrecision().value();

    if (left == null && right == null) {
        return null;
    }

    // null left operand case
    if (getOperand().get(0) instanceof AsEvaluator) {
        if (((AsEvaluator) getOperand().get(0)).getAsTypeSpecifier() instanceof IntervalTypeSpecifier) {
            return InEvaluator.in(right, left, precision);
        }
        else {
            return InEvaluator.in(right, left, null);
        }
    }

    return contains(left, right, precision);
}
 
Example #3
Source File: CqlExecutionProvider.java    From cqf-ruler with Apache License 2.0 6 votes vote down vote up
public Object evaluateInContext(DomainResource instance, String cql, String patientId) {
    Iterable<CanonicalType> libraries = getLibraryReferences(instance);

    String source = String.format(
            "library LocalLibrary using FHIR version '4.0.0' include FHIRHelpers version '4.0.0' called FHIRHelpers %s parameter %s %s parameter \"%%context\" %s define Expression: %s",
            buildIncludes(libraries), instance.fhirType(), instance.fhirType(), instance.fhirType(), cql);
    
    LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.getLibraryResourceProvider());
    
    org.cqframework.cql.elm.execution.Library library = TranslatorHelper.translateLibrary(source,
            libraryLoader.getLibraryManager(), libraryLoader.getModelManager());
    
    // resolve execution context
    Context context = setupContext(instance, patientId, libraryLoader, library);
    return context.resolveExpressionRef("Expression").evaluate(context);
}
 
Example #4
Source File: PropertyEvaluator.java    From cql_engine with Apache License 2.0 6 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    Object target = null;

    if (this.getSource() != null) {
        target = getSource().evaluate(context);
        // Tuple element access
        if (target instanceof Tuple) {
          // NOTE: translator will throw error if Tuple does not contain the specified element -- no need for x.containsKey() check
          return ((Tuple)target).getElements().get(this.getPath());
        }
    }
    else if (this.getScope() != null) {
        target = context.resolveVariable(this.getScope(), true).getValue();
    }

    if (target == null) {
        return null;
    }

    if (target instanceof Iterable) {

    }

    return context.resolvePath(target, this.getPath());
}
 
Example #5
Source File: NegateEvaluator.java    From cql_engine with Apache License 2.0 6 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    Expression operand = getOperand();

    // Special case to handle literals of the minimum Integer value
    // since usual implementation would try to cast 2147483648 as a
    // signed 32 bit signed integer and throw
    // java.lang.NumberFormatException: For input string: "2147483648".
    if (operand instanceof LiteralEvaluator && ((LiteralEvaluator)operand).getValue().equals("2147483648"))
    {
        return Integer.MIN_VALUE;
    }

    Object source = operand.evaluate(context);

    return negate(source);
}
 
Example #6
Source File: MeasureEvaluation.java    From cqf-ruler with Apache License 2.0 6 votes vote down vote up
public MeasureReport evaluatePatientMeasure(Measure measure, Context context, String patientId) {
    logger.info("Generating individual report");

    if (patientId == null) {
        return evaluatePopulationMeasure(measure, context);
    }

    Patient patient = registry.getResourceDao(Patient.class).read(new IdType(patientId));
    // Iterable<Object> patientRetrieve = provider.retrieve("Patient", "id",
    // patientId, "Patient", null, null, null, null, null, null, null, null);
    // Patient patient = null;
    // if (patientRetrieve.iterator().hasNext()) {
    // patient = (Patient) patientRetrieve.iterator().next();
    // }

    return evaluate(measure, context,
            patient == null ? Collections.emptyList() : Collections.singletonList(patient),
            MeasureReport.MeasureReportType.INDIVIDUAL);
}
 
Example #7
Source File: MinValueEvaluator.java    From cql_engine with Apache License 2.0 6 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    String type = this.getValueType().getLocalPart();
    if (type == null) {
        return null;
    }

    if (type.endsWith("Integer")) {
        return Value.MIN_INT;
    }
    if (type.endsWith("Decimal")) {
        return Value.MIN_DECIMAL;
    }
    if (type.endsWith("Date")) {
        return new Date(1, 1, 1).setPrecision(Precision.DAY);
    }
    if (type.endsWith("DateTime")) {
        return new DateTime(TemporalHelper.zoneToOffset(context.getEvaluationDateTime().getDateTime().getOffset()), 1, 1, 1, 0, 0, 0, 0).withEvaluationOffset(context.getEvaluationDateTime().getDateTime().getOffset());
    }
    if (type.endsWith("Time")) {
        return new Time(TemporalHelper.zoneToOffset(context.getEvaluationDateTime().getDateTime().getOffset()), 0, 0, 0, 0).withEvaluationOffset(context.getEvaluationDateTime().getDateTime().getOffset());
    }

    throw new InvalidOperatorArgument(String.format("The Minimum operator is not implemented for type %s", type));
}
 
Example #8
Source File: TestFhirLibrary.java    From cql_engine with Apache License 2.0 6 votes vote down vote up
public void TestCMS9v4_CQM() throws IOException, JAXBException {
      File xmlFile = new File(URLDecoder.decode(TestFhirLibrary.class.getResource("CMS9v4_CQM.xml").getFile(), "UTF-8"));
      Library library = CqlLibraryReader.read(xmlFile);

      Context context = new Context(library);

      FhirContext fhirContext = FhirContext.forDstu3();

Dstu3FhirModelResolver modelResolver = new Dstu3FhirModelResolver();
RestFhirRetrieveProvider retrieveProvider = new RestFhirRetrieveProvider(new SearchParameterResolver(fhirContext),  fhirContext.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3"));
CompositeDataProvider provider = new CompositeDataProvider(modelResolver, retrieveProvider);
      //BaseFhirDataProvider provider = new FhirDataProviderStu3().setEndpoint("http://fhirtest.uhn.ca/baseDstu3");
      //BaseFhirDataProvider provider = new FhirDataProviderStu3().setEndpoint("http://fhir3.healthintersections.com.au/open/");
      //BaseFhirDataProvider provider = new FhirDataProviderStu3().setEndpoint("http://wildfhir.aegis.net/fhir");
      context.registerDataProvider("http://hl7.org/fhir", provider);

      Object result = context.resolveExpressionRef("Breastfeeding Intention Assessment").evaluate(context);
      assertThat(result, instanceOf(Iterable.class));
      for (Object element : (Iterable)result) {
          assertThat(element, instanceOf(RiskAssessment.class));
      }
  }
 
Example #9
Source File: ExpressionProcessor.java    From synthea with Apache License 2.0 6 votes vote down vote up
/**
 * ExpressionProcessor constructor.
 * @param expression Expression to evaluate for each future set of parameters.
 * @param paramTypeMap Map of parameter names to their corresponding CQL types.
 */
public ExpressionProcessor(String expression, Map<String,String> paramTypeMap) {
  this.cqlParamMap = HashBiMap.create();
  this.paramTypeMap = paramTypeMap;
  
  String cleanExpression = replaceParameters(expression);
  String wrappedExpression = convertParameterizedExpressionToCql(cleanExpression);

  // Compile our constructed CQL expression into elm once for execution
  this.elm = cqlToElm(wrappedExpression);
  try {
    this.library = CqlLibraryReader.read(new ByteArrayInputStream(
        elm.getBytes(StandardCharsets.UTF_8)));
  } catch (IOException | JAXBException ex) {
    throw new RuntimeException(ex);
  }
  this.context = new Context(library);
  this.expression = expression;
}
 
Example #10
Source File: EndsEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    Object left = getOperand().get(0).evaluate(context);
    Object right = getOperand().get(1).evaluate(context);
    String precision = getPrecision() == null ? null : getPrecision().value();

    return ends(left, right, precision);
}
 
Example #11
Source File: RepeatEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    Object source = getSource().evaluate(context);
    Object element = getElement().evaluate(context);
    String scope = getScope();

    return repeat(source, element, scope);
}
 
Example #12
Source File: StartsEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    Object left = getOperand().get(0).evaluate(context);
    Object right = getOperand().get(1).evaluate(context);
    String precision = getPrecision() == null ? null : getPrecision().value();

    return starts(left, right, precision);
}
 
Example #13
Source File: CqlExecutionProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
public Object evaluateInContext(DomainResource instance, String cql, String patientId, Boolean aliasedExpression) {
    Iterable<CanonicalType> libraries = getLibraryReferences(instance);
    if (aliasedExpression) {
        Object result = null;
        for (CanonicalType reference : libraries) {
            Library lib =this.libraryResourceProvider.resolveLibraryById(CanonicalHelper.getId(reference));
            if (lib == null)
            {
                throw new RuntimeException("Library with id " + reference.getIdBase() + "not found");
            }
            LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.getLibraryResourceProvider());
            // resolve primary library
            org.cqframework.cql.elm.execution.Library library = LibraryHelper.resolveLibraryById(lib.getId(), libraryLoader, this.libraryResourceProvider);

            // resolve execution context
            Context context = setupContext(instance, patientId, libraryLoader, library);
            result = context.resolveExpressionRef(cql).evaluate(context);
            if (result != null) {
                return result;
            }
        }
        throw new RuntimeException("Could not find Expression in Referenced Libraries");
    }
    else {
        return evaluateInContext(instance, cql, patientId);
    }
}
 
Example #14
Source File: ProperContainsEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    Object left = getOperand().get(0).evaluate(context);
    Object right = getOperand().get(1).evaluate(context);
    String precision = getPrecision() != null ? getPrecision().value() : null;

    return properContains(left, right, precision);
}
 
Example #15
Source File: ForEachEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
public Object forEach(Object source, Object element, Context context) {
    if (source == null || element == null) {
        return null;
    }

    List<Object> retVal = new ArrayList<>();
    for (Object o : (Iterable) source) {
        retVal.add(context.resolvePath(o, element.toString()));
    }
    return retVal;
}
 
Example #16
Source File: OverlapsAfterEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    Object left = getOperand().get(0).evaluate(context);
    Object right = getOperand().get(1).evaluate(context);
    String precision = getPrecision() == null ? null : getPrecision().value();

    return overlapsAfter(left, right, precision);
}
 
Example #17
Source File: MessageEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    Object source = getSource().evaluate(context);
    Boolean condition = (Boolean) getCondition().evaluate(context);
    String code = (String) getCode().evaluate(context);
    String severity = (String) getSeverity().evaluate(context);
    String message = (String) getMessage().evaluate(context);

    return message(source, condition, code, severity, message);
}
 
Example #18
Source File: Executable.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
public Object evaluate(Context context) throws CqlException
{
    try {
        return internalEvaluate(context);
    }
    catch (Exception e) {
        if (e instanceof CqlException) {
            throw e;
        }
        else {
            throw new CqlException(e);
        }
    }
}
 
Example #19
Source File: ExpandEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context)
{
    Iterable<Interval> list = (Iterable<Interval>) getOperand().get(0).evaluate(context);
    Quantity per = (Quantity) getOperand().get(1).evaluate(context);

    return expand(list, per);
}
 
Example #20
Source File: EndsWithEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    String argument = (String) getOperand().get(0).evaluate(context);
    String suffix = (String) getOperand().get(1).evaluate(context);

    return endsWith(argument, suffix);
}
 
Example #21
Source File: DifferenceBetweenEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    Object left = getOperand().get(0).evaluate(context);
    Object right = getOperand().get(1).evaluate(context);
    String precision = getPrecision().value();

    return difference(left, right, Precision.fromString(precision));
}
 
Example #22
Source File: IdentifierRefEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {

    String name = this.getName();

    if (name == null) {
        return null;
    }

    return context.resolveIdentifierRef(name);
}
 
Example #23
Source File: LessEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    Object left = getOperand().get(0).evaluate(context);
    Object right = getOperand().get(1).evaluate(context);

    return less(left, right);
}
 
Example #24
Source File: EqualEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    Object left = getOperand().get(0).evaluate(context);
    Object right = getOperand().get(1).evaluate(context);

    return equal(left, right);
}
 
Example #25
Source File: IntervalEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    Object low = getLow() != null ? getLow().evaluate(context) : null;
    Boolean lowClosed = getLowClosedExpression() != null ? (Boolean)getLowClosedExpression().evaluate(context) : this.lowClosed;
    Object high = getHigh() != null ? getHigh().evaluate(context) : null;
    Boolean highClosed = getHighClosedExpression() != null ? (Boolean)getHighClosedExpression().evaluate(context) : this.highClosed;

    // An interval with no boundaries is not an interval
    // TODO: the spec states that it is possible to have an interval with null boundaries, but the ELM is not providing a way to get the Interval type
    if (low == null && high == null) {
        return null;
    }

    return new org.opencds.cqf.cql.runtime.Interval(low, lowClosed == null ? true : lowClosed, high, highClosed == null ? true : highClosed);
}
 
Example #26
Source File: MeetsBeforeEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    Object left = getOperand().get(0).evaluate(context);
    Object right = getOperand().get(1).evaluate(context);
    String precision = getPrecision() == null ? null : getPrecision().value();

    return meetsBefore(left, right, precision);
}
 
Example #27
Source File: CombineEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    Object source = this.getSource().evaluate(context);
    String separator = this.getSeparator() == null ? "" : (String) this.getSeparator().evaluate(context);

    return combine(source, separator);
}
 
Example #28
Source File: IntersectEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context)
{
    Object left = getOperand().get(0).evaluate(context);
    Object right = getOperand().get(1).evaluate(context);

    return intersect(left, right);
}
 
Example #29
Source File: IndexOfEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    Object source = getSource().evaluate(context);
    Object elementToFind = getElement().evaluate(context);

    return indexOf(source, elementToFind);
}
 
Example #30
Source File: FunctionRefEvaluator.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Override
protected Object internalEvaluate(Context context) {
    ArrayList<Object> arguments = new ArrayList<>();
    for (Expression operand : this.getOperand()) {
        arguments.add(operand.evaluate(context));
    }

    boolean enteredLibrary = context.enterLibrary(this.getLibraryName());
    try {
        // TODO: Use type specifiers from the operands here if they are available
        FunctionDef functionDef = context.resolveFunctionRef(this.getName(), arguments, this.getLibraryName());
        if (Optional.ofNullable(functionDef.isExternal()).orElse(false)) {
            return context.getExternalFunctionProvider().evaluate(functionDef.getName(), arguments);
        }
        else {
            context.pushWindow();
            try {
                for (int i = 0; i < arguments.size(); i++) {
                    context.push(new Variable().withName(functionDef.getOperand().get(i).getName()).withValue(arguments.get(i)));
                }
                return functionDef.getExpression().evaluate(context);
            }
            finally {
                context.popWindow();
            }
        }
    }
    finally {
        context.exitLibrary(enteredLibrary);
    }
}