Search in sources :

Example 16 with DmnDecisionModel

use of org.kie.kogito.dmn.DmnDecisionModel in project kogito-apps by kiegroup.

the class PrequalificationDmnCounterfactualExplainerTest method getModel.

private PredictionProvider getModel() {
    DMNRuntime dmnRuntime = DMNKogito.createGenericDMNRuntime(new InputStreamReader(getClass().getResourceAsStream("/dmn/Prequalification-1.dmn")));
    assertEquals(1, dmnRuntime.getModels().size());
    final String NS = "http://www.trisotech.com/definitions/_f31e1f8e-d4ce-4a3a-ac3b-747efa6b3401";
    final String NAME = "Prequalification";
    DecisionModel decisionModel = new DmnDecisionModel(dmnRuntime, NS, NAME);
    return new DecisionModelWrapper(decisionModel, List.of("LTV", "LLPA", "DTI", "Loan Payment"));
}
Also used : InputStreamReader(java.io.InputStreamReader) DmnDecisionModel(org.kie.kogito.dmn.DmnDecisionModel) DecisionModel(org.kie.kogito.decision.DecisionModel) DmnDecisionModel(org.kie.kogito.dmn.DmnDecisionModel) DMNRuntime(org.kie.dmn.api.core.DMNRuntime)

Example 17 with DmnDecisionModel

use of org.kie.kogito.dmn.DmnDecisionModel in project kogito-apps by kiegroup.

the class PrequalificationDmnPDPExplainerTest method testPrequalificationDMNExplanation.

@Test
void testPrequalificationDMNExplanation() throws ExecutionException, InterruptedException, TimeoutException {
    DMNRuntime dmnRuntime = DMNKogito.createGenericDMNRuntime(new InputStreamReader(getClass().getResourceAsStream("/dmn/Prequalification-1.dmn")));
    assertEquals(1, dmnRuntime.getModels().size());
    final String NS = "http://www.trisotech.com/definitions/_f31e1f8e-d4ce-4a3a-ac3b-747efa6b3401";
    final String NAME = "Prequalification";
    DecisionModel decisionModel = new DmnDecisionModel(dmnRuntime, NS, NAME);
    PredictionProvider model = new DecisionModelWrapper(decisionModel);
    List<PredictionInput> inputs = DmnTestUtils.randomPrequalificationInputs();
    List<PredictionOutput> predictionOutputs = model.predictAsync(inputs).get(Config.INSTANCE.getAsyncTimeout(), Config.INSTANCE.getAsyncTimeUnit());
    List<Prediction> predictions = new ArrayList<>();
    for (int i = 0; i < predictionOutputs.size(); i++) {
        predictions.add(new SimplePrediction(inputs.get(i), predictionOutputs.get(i)));
    }
    PartialDependencePlotExplainer partialDependencePlotExplainer = new PartialDependencePlotExplainer();
    List<PartialDependenceGraph> pdps = partialDependencePlotExplainer.explainFromPredictions(model, predictions);
    AssertionsForClassTypes.assertThat(pdps).isNotNull();
    Assertions.assertThat(pdps).hasSize(25);
}
Also used : SimplePrediction(org.kie.kogito.explainability.model.SimplePrediction) InputStreamReader(java.io.InputStreamReader) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) SimplePrediction(org.kie.kogito.explainability.model.SimplePrediction) Prediction(org.kie.kogito.explainability.model.Prediction) ArrayList(java.util.ArrayList) DecisionModel(org.kie.kogito.decision.DecisionModel) DmnDecisionModel(org.kie.kogito.dmn.DmnDecisionModel) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) DMNRuntime(org.kie.dmn.api.core.DMNRuntime) PartialDependencePlotExplainer(org.kie.kogito.explainability.global.pdp.PartialDependencePlotExplainer) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) DmnDecisionModel(org.kie.kogito.dmn.DmnDecisionModel) PartialDependenceGraph(org.kie.kogito.explainability.model.PartialDependenceGraph) Test(org.junit.jupiter.api.Test)

Example 18 with DmnDecisionModel

use of org.kie.kogito.dmn.DmnDecisionModel in project kogito-runtimes by kiegroup.

the class RuleSetNodeInstance method internalTrigger.

@Override
public void internalTrigger(KogitoNodeInstance from, String type) {
    try {
        super.internalTrigger(from, type);
        // if node instance was cancelled, abort
        if (getNodeInstanceContainer().getNodeInstance(getStringId()) == null) {
            return;
        }
        if (!Node.CONNECTION_DEFAULT_TYPE.equals(type)) {
            throw new IllegalArgumentException("A RuleSetNode only accepts default incoming connections!");
        }
        RuleSetNode ruleSetNode = getRuleSetNode();
        KieRuntime kruntime = Optional.ofNullable(getRuleSetNode().getKieRuntime()).orElse(() -> getProcessInstance().getKnowledgeRuntime()).get();
        Map<String, Object> inputs = NodeIoHelper.processInputs(this, varRef -> getVariable(varRef));
        RuleSetNode.RuleType ruleType = ruleSetNode.getRuleType();
        if (ruleType.isDecision()) {
            RuleSetNode.RuleType.Decision decisionModel = (RuleSetNode.RuleType.Decision) ruleType;
            String namespace = resolveExpression(decisionModel.getNamespace());
            String model = resolveExpression(decisionModel.getModel());
            DecisionModel modelInstance = Optional.ofNullable(getRuleSetNode().getDecisionModel()).orElse(() -> new DmnDecisionModel(((KieSession) kruntime).getKieRuntime(DMNRuntime.class), namespace, model)).get();
            // Input Binding
            DMNContext context = DMNJSONUtils.ctx(modelInstance, jsonResolver.resolveAll(inputs));
            DMNResult dmnResult = modelInstance.evaluateAll(context);
            if (dmnResult.hasErrors()) {
                String errors = dmnResult.getMessages(Severity.ERROR).stream().map(Object::toString).collect(Collectors.joining(", "));
                throw new RuntimeException("DMN result errors:: " + errors);
            }
            // Output Binding
            Map<String, Object> outputSet = dmnResult.getContext().getAll();
            NodeIoHelper.processOutputs(this, key -> outputSet.get(key), varName -> this.getVariable(varName));
            triggerCompleted();
        } else if (ruleType.isRuleFlowGroup()) {
            // first set rule flow group
            setRuleFlowGroup(resolveRuleFlowGroup(ruleType.getName()));
            // proceed
            for (Entry<String, Object> entry : inputs.entrySet()) {
                if (FIRE_RULE_LIMIT_PARAMETER.equals(entry.getKey())) {
                    // don't put control parameter for fire limit into working memory
                    continue;
                }
                String inputKey = getRuleFlowGroup() + "_" + getProcessInstance().getStringId() + "_" + entry.getKey();
                factHandles.put(inputKey, kruntime.insert(entry.getValue()));
            }
            if (actAsWaitState()) {
                addRuleSetListener();
                ((InternalAgenda) kruntime.getAgenda()).activateRuleFlowGroup(getRuleFlowGroup(), getProcessInstance().getStringId(), getUniqueId());
            } else {
                int fireLimit = DEFAULT_FIRE_RULE_LIMIT;
                WorkflowProcessInstance processInstance = getProcessInstance();
                if (inputs.containsKey(FIRE_RULE_LIMIT_PARAMETER)) {
                    fireLimit = Integer.parseInt(inputs.get(FIRE_RULE_LIMIT_PARAMETER).toString());
                }
                ((InternalAgenda) kruntime.getAgenda()).activateRuleFlowGroup(getRuleFlowGroup(), processInstance.getStringId(), getUniqueId());
                int fired = ((KieSession) kruntime).fireAllRules(processInstance.getAgendaFilter(), fireLimit);
                if (fired == fireLimit) {
                    throw new RuntimeException("Fire rule limit reached " + fireLimit + ", limit can be set via system property " + FIRE_RULE_LIMIT_PROPERTY + " or via data input of business rule task named " + FIRE_RULE_LIMIT_PARAMETER);
                }
                removeEventListeners();
                retractFacts(kruntime);
                triggerCompleted();
            }
        } else if (ruleType.isRuleUnit()) {
            RuleUnitFactory<RuleUnitData> factory = ruleSetNode.getRuleUnitFactory();
            AbstractProcessContext context = ContextFactory.fromNode(this);
            RuleUnitData model = factory.bind(context);
            RuleUnitInstance<RuleUnitData> instance = factory.unit().createInstance(model);
            instance.fire();
            factory.unbind(context, model);
            triggerCompleted();
        } else {
            throw new UnsupportedOperationException("Unsupported Rule Type: " + ruleType);
        }
    } catch (Exception e) {
        handleException(e);
    }
}
Also used : DMNResult(org.kie.dmn.api.core.DMNResult) AbstractProcessContext(org.drools.core.process.AbstractProcessContext) RuleUnitData(org.kie.kogito.rules.RuleUnitData) RuleSetNode(org.jbpm.workflow.core.node.RuleSetNode) KieRuntime(org.kie.api.runtime.KieRuntime) DMNContext(org.kie.dmn.api.core.DMNContext) DecisionModel(org.kie.kogito.decision.DecisionModel) DmnDecisionModel(org.kie.kogito.dmn.DmnDecisionModel) DMNRuntime(org.kie.dmn.api.core.DMNRuntime) WorkflowRuntimeException(org.jbpm.workflow.instance.WorkflowRuntimeException) Entry(java.util.Map.Entry) WorkflowRuntimeException(org.jbpm.workflow.instance.WorkflowRuntimeException) DmnDecisionModel(org.kie.kogito.dmn.DmnDecisionModel) WorkflowProcessInstance(org.jbpm.workflow.instance.WorkflowProcessInstance)

Example 19 with DmnDecisionModel

use of org.kie.kogito.dmn.DmnDecisionModel in project kogito-runtimes by kiegroup.

the class EvaluateEventJsonGeneratorTest method generate.

private void generate(String executionId, Map<String, Object> contextVariables, BiConsumer<DecisionModel, DMNContext> modelConsumer, int expectedEvents) throws JsonProcessingException {
    final DMNRuntime runtime = createDMNRuntime();
    Consumer<EvaluateEvent> eventConsumer = mock(Consumer.class);
    DecisionTracingListener listener = new DecisionTracingListener(eventConsumer);
    runtime.addListener(listener);
    final DecisionModel model = new DmnDecisionModel(runtime, MODEL_NAMESPACE, MODEL_NAME, () -> executionId);
    final DMNContext context = model.newContext(contextVariables);
    modelConsumer.accept(model, context);
    ArgumentCaptor<EvaluateEvent> eventCaptor = ArgumentCaptor.forClass(EvaluateEvent.class);
    verify(eventConsumer, times(expectedEvents)).accept(eventCaptor.capture());
    System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(eventCaptor.getAllValues()));
}
Also used : DmnDecisionModel(org.kie.kogito.dmn.DmnDecisionModel) DMNContext(org.kie.dmn.api.core.DMNContext) DecisionModel(org.kie.kogito.decision.DecisionModel) DmnDecisionModel(org.kie.kogito.dmn.DmnDecisionModel) DecisionTestUtils.createDMNRuntime(org.kie.kogito.dmn.DecisionTestUtils.createDMNRuntime) DMNRuntime(org.kie.dmn.api.core.DMNRuntime) EvaluateEvent(org.kie.kogito.tracing.decision.event.evaluate.EvaluateEvent)

Aggregations

DmnDecisionModel (org.kie.kogito.dmn.DmnDecisionModel)19 DMNRuntime (org.kie.dmn.api.core.DMNRuntime)18 DecisionModel (org.kie.kogito.decision.DecisionModel)18 InputStreamReader (java.io.InputStreamReader)15 ArrayList (java.util.ArrayList)8 Test (org.junit.jupiter.api.Test)7 Prediction (org.kie.kogito.explainability.model.Prediction)7 PredictionInput (org.kie.kogito.explainability.model.PredictionInput)7 PredictionOutput (org.kie.kogito.explainability.model.PredictionOutput)7 PredictionProvider (org.kie.kogito.explainability.model.PredictionProvider)7 SimplePrediction (org.kie.kogito.explainability.model.SimplePrediction)7 PartialDependencePlotExplainer (org.kie.kogito.explainability.global.pdp.PartialDependencePlotExplainer)4 PartialDependenceGraph (org.kie.kogito.explainability.model.PartialDependenceGraph)4 HashMap (java.util.HashMap)3 Random (java.util.Random)3 DMNContext (org.kie.dmn.api.core.DMNContext)3 LimeConfig (org.kie.kogito.explainability.local.lime.LimeConfig)3 LimeExplainer (org.kie.kogito.explainability.local.lime.LimeExplainer)3 DataDistribution (org.kie.kogito.explainability.model.DataDistribution)3 Feature (org.kie.kogito.explainability.model.Feature)3