Search in sources :

Example 6 with CountAccumulateFunction

use of org.drools.core.base.accumulators.CountAccumulateFunction in project drools by kiegroup.

the class KiePackagesBuilder method buildAccumulate.

private Accumulate buildAccumulate(RuleContext ctx, AccumulatePattern accPattern, RuleConditionElement source, Pattern pattern, Set<String> usedVariableName, Collection<Binding> bindings) {
    boolean isGroupBy = accPattern instanceof GroupByPattern;
    AccumulateFunction[] accFunctions = accPattern.getAccumulateFunctions();
    Declaration groupByDeclaration = null;
    Class selfType = (isGroupBy || accFunctions.length > 1) ? Object[].class : accFunctions[0].getResult().getType();
    InternalReadAccessor selfReader = new SelfReferenceClassFieldReader(selfType);
    int arrayIndexOffset = 0;
    if (isGroupBy) {
        if (accFunctions.length == 0) {
            // In this situation the result is anonymous, but it still uses element position 0.
            // For this reason the i used to populate hte array index must be offset by 1.
            accFunctions = new AccumulateFunction[] { new AccumulateFunction(null, CountAccumulateFunction::new) };
            arrayIndexOffset = 1;
        }
        // GroupBy  key is always the last element in the result array
        Variable groupVar = ((GroupByPattern<?, ?>) accPattern).getVarKey();
        groupByDeclaration = new Declaration(groupVar.getName(), new ArrayElementReader(selfReader, accFunctions.length, groupVar.getType()), pattern, true);
        pattern.addDeclaration(groupByDeclaration);
    }
    Accumulate accumulate;
    Accumulator[] accumulators = new Accumulator[accFunctions.length];
    List<Declaration> requiredDeclarationList = new ArrayList<>();
    for (int i = 0; i < accFunctions.length; i++) {
        Variable boundVar = processFunctions(ctx, accPattern, source, pattern, usedVariableName, bindings, isGroupBy, accFunctions[i], selfReader, accumulators, requiredDeclarationList, arrayIndexOffset, i);
        if (isGroupBy) {
            ctx.addGroupByDeclaration(((GroupByPattern) accPattern).getVarKey(), groupByDeclaration);
        }
    }
    if (accFunctions.length == 1) {
        accumulate = new SingleAccumulate(source, requiredDeclarationList.toArray(new Declaration[requiredDeclarationList.size()]), accumulators[0]);
    } else {
        if (source instanceof Pattern) {
            requiredDeclarationList.forEach(((Pattern) source)::addDeclaration);
        }
        accumulate = new MultiAccumulate(source, new Declaration[0], accumulators, // if this is a groupby +1 for the key
        accumulators.length + ((isGroupBy) ? 1 : 0));
    }
    if (isGroupBy) {
        GroupByPatternImpl groupBy = (GroupByPatternImpl) accPattern;
        Declaration[] groupingDeclarations = new Declaration[groupBy.getVars().length];
        for (int i = 0; i < groupBy.getVars().length; i++) {
            groupingDeclarations[i] = ctx.getDeclaration(groupBy.getVars()[i]);
        }
        accumulate = new LambdaGroupByAccumulate(accumulate, groupingDeclarations, groupBy.getGroupingFunction());
    }
    for (Variable boundVar : accPattern.getBoundVariables()) {
        ctx.addAccumulateSource(boundVar, accumulate);
    }
    return accumulate;
}
Also used : LambdaAccumulator(org.drools.modelcompiler.constraints.LambdaAccumulator) Accumulator(org.drools.core.spi.Accumulator) QueryCallPattern(org.drools.model.patterns.QueryCallPattern) AccumulatePattern(org.drools.model.AccumulatePattern) Pattern(org.drools.core.rule.Pattern) GroupByPattern(org.drools.model.GroupByPattern) PrototypeVariable(org.drools.model.PrototypeVariable) Variable(org.drools.model.Variable) MultiAccumulate(org.drools.core.rule.MultiAccumulate) ArrayList(java.util.ArrayList) SingleAccumulate(org.drools.core.rule.SingleAccumulate) SingleConstraint(org.drools.model.SingleConstraint) QueryNameConstraint(org.drools.core.rule.constraint.QueryNameConstraint) LambdaConstraint(org.drools.modelcompiler.constraints.LambdaConstraint) UnificationConstraint(org.drools.modelcompiler.constraints.UnificationConstraint) EntryPoint(org.drools.model.EntryPoint) AbstractConstraint(org.drools.modelcompiler.constraints.AbstractConstraint) Constraint(org.drools.model.Constraint) CombinedConstraint(org.drools.modelcompiler.constraints.CombinedConstraint) AbstractSingleConstraint(org.drools.model.constraints.AbstractSingleConstraint) DSL.entryPoint(org.drools.model.DSL.entryPoint) LambdaGroupByAccumulate(org.drools.modelcompiler.constraints.LambdaGroupByAccumulate) MultiAccumulate(org.drools.core.rule.MultiAccumulate) SingleAccumulate(org.drools.core.rule.SingleAccumulate) Accumulate(org.drools.core.rule.Accumulate) GroupByPattern(org.drools.model.GroupByPattern) LambdaGroupByAccumulate(org.drools.modelcompiler.constraints.LambdaGroupByAccumulate) SelfReferenceClassFieldReader(org.drools.core.base.extractors.SelfReferenceClassFieldReader) GroupByPatternImpl(org.drools.model.patterns.GroupByPatternImpl) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) ArrayElementReader(org.drools.core.base.extractors.ArrayElementReader) Declaration(org.drools.core.rule.Declaration) WindowDeclaration(org.drools.core.rule.WindowDeclaration) TypeDeclarationUtil.createTypeDeclaration(org.drools.modelcompiler.util.TypeDeclarationUtil.createTypeDeclaration) TypeDeclaration(org.drools.core.rule.TypeDeclaration) CountAccumulateFunction(org.drools.core.base.accumulators.CountAccumulateFunction) AccumulateFunction(org.drools.model.functions.accumulate.AccumulateFunction)

Example 7 with CountAccumulateFunction

use of org.drools.core.base.accumulators.CountAccumulateFunction in project drools by kiegroup.

the class GroupByTest method testNestedGroupBy3.

@Test
// <- FIXME, see comment inside (@mario)
@Ignore
public void testNestedGroupBy3() throws Exception {
    // DROOLS-6045
    final Global<List> var_results = D.globalOf(List.class, "defaultpkg", "results");
    final Variable<Object> var_$key = D.declarationOf(Object.class);
    final Variable<Object> var_$keyOuter = D.declarationOf(Object.class);
    final Variable<Person> var_$p = D.declarationOf(Person.class);
    final Variable<Object> var_$accresult = D.declarationOf(Object.class);
    final Rule rule1 = PatternDSL.rule("R1").build(D.groupBy(D.and(D.groupBy(// Patterns
    D.pattern(var_$p), // Grouping Function
    var_$p, var_$key, Person::getName, D.accFunction(CountAccumulateFunction::new).as(var_$accresult)), // Bindings
    D.pattern(var_$accresult).expr(// FIXME var_$accresult is collection of Long, how did this pass before(mdp) ?
    c -> ((Integer) c) > 0)), var_$key, var_$accresult, var_$keyOuter, Pair::create), // Consequence
    D.on(var_$keyOuter, var_results).execute(($outerKey, results) -> {
        results.add($outerKey);
    }));
    final Model model = new ModelImpl().addRule(rule1).addGlobal(var_results);
    final KieSession ksession = KieBaseBuilder.createKieBaseFromModel(model).newKieSession();
    final List<Object> results = new ArrayList<>();
    ksession.setGlobal("results", results);
    ksession.insert("A");
    ksession.insert("test");
    ksession.insert(new Person("Mark", 42));
    assertThat(ksession.fireAllRules()).isEqualTo(1);
    assertThat(results).containsOnly(Pair.create("Mark", 1L));
}
Also used : Arrays(java.util.Arrays) InternalFactHandle(org.drools.core.common.InternalFactHandle) Accumulator(org.drools.core.spi.Accumulator) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Global(org.drools.model.Global) RuleEventListener(org.kie.internal.event.rule.RuleEventListener) DSL(org.drools.model.DSL) Child(org.drools.modelcompiler.domain.Child) Match(org.kie.api.runtime.rule.Match) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) Declaration(org.drools.core.rule.Declaration) Assertions(org.assertj.core.api.Assertions) KieSession(org.kie.api.runtime.KieSession) Parent(org.drools.modelcompiler.domain.Parent) Set(java.util.Set) Index(org.drools.model.Index) ConsequenceBuilder(org.drools.model.consequences.ConsequenceBuilder) EvaluationUtil(org.drools.modelcompiler.util.EvaluationUtil) Objects(java.util.Objects) List(java.util.List) Tuple(org.drools.core.spi.Tuple) CountAccumulateFunction(org.drools.core.base.accumulators.CountAccumulateFunction) Person(org.drools.modelcompiler.domain.Person) DSL.from(org.drools.model.DSL.from) ModelImpl(org.drools.model.impl.ModelImpl) HashMap(java.util.HashMap) PatternDSL(org.drools.model.PatternDSL) ArrayList(java.util.ArrayList) Function1(org.drools.model.functions.Function1) CollectListAccumulateFunction(org.drools.core.base.accumulators.CollectListAccumulateFunction) RuleEventManager(org.kie.internal.event.rule.RuleEventManager) KieBase(org.kie.api.KieBase) LinkedHashSet(java.util.LinkedHashSet) Model(org.drools.model.Model) IntegerMaxAccumulateFunction(org.drools.core.base.accumulators.IntegerMaxAccumulateFunction) ReteEvaluator(org.drools.core.common.ReteEvaluator) ViewItem(org.drools.model.view.ViewItem) Pair(org.apache.commons.math3.util.Pair) Variable(org.drools.model.Variable) D(org.drools.modelcompiler.dsl.pattern.D) IntegerSumAccumulateFunction(org.drools.core.base.accumulators.IntegerSumAccumulateFunction) ToIntFunction(java.util.function.ToIntFunction) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) GroupKey(org.drools.model.functions.accumulate.GroupKey) FactHandle(org.kie.api.runtime.rule.FactHandle) KieBaseBuilder(org.drools.modelcompiler.builder.KieBaseBuilder) Assert.assertNull(org.junit.Assert.assertNull) Ignore(org.junit.Ignore) Rule(org.drools.model.Rule) ExprViewItem(org.drools.model.view.ExprViewItem) RuleTerminalNodeLeftTuple(org.drools.core.reteoo.RuleTerminalNodeLeftTuple) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Model(org.drools.model.Model) List(java.util.List) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) Rule(org.drools.model.Rule) ModelImpl(org.drools.model.impl.ModelImpl) Person(org.drools.modelcompiler.domain.Person) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 8 with CountAccumulateFunction

use of org.drools.core.base.accumulators.CountAccumulateFunction in project drools by kiegroup.

the class GroupByTest method testDecomposedGroupByKeyAndAccumulate.

@Test
public void testDecomposedGroupByKeyAndAccumulate() throws Exception {
    // DROOLS-6031
    final Global<List> var_results = D.globalOf(List.class, "defaultpkg", "results");
    final Variable<Pair<String, String>> var_$key = (Variable) D.declarationOf(Pair.class);
    final Variable<Person> var_$p = D.declarationOf(Person.class);
    final Variable<String> var_$subkeyA = D.declarationOf(String.class);
    final Variable<String> var_$subkeyB = D.declarationOf(String.class);
    final Variable<Long> var_$accresult = D.declarationOf(Long.class);
    final Rule rule1 = PatternDSL.rule("R1").build(D.groupBy(// Patterns
    PatternDSL.pattern(var_$p), // Grouping Function
    var_$p, var_$key, person -> Pair.create(person.getName().substring(0, 1), person.getName().substring(1, 2)), D.accFunction(CountAccumulateFunction::new).as(var_$accresult)), // Bindings
    D.pattern(var_$key).bind(var_$subkeyA, Pair::getKey).bind(var_$subkeyB, Pair::getValue), D.pattern(var_$accresult).expr(l -> l > 0), // Consequence
    D.on(var_$subkeyA, var_$subkeyB, var_$accresult, var_results).execute(($a, $b, $accresult, results) -> {
        results.add($a);
        results.add($b);
        results.add($accresult);
    }));
    final Model model = new ModelImpl().addRule(rule1).addGlobal(var_results);
    final KieSession ksession = KieBaseBuilder.createKieBaseFromModel(model).newKieSession();
    final List<Object> results = new ArrayList<>();
    ksession.setGlobal("results", results);
    ksession.insert("A");
    ksession.insert("test");
    ksession.insert(new Person("Mark", 42));
    assertThat(ksession.fireAllRules()).isEqualTo(1);
    Assertions.assertThat(results.size()).isEqualTo(3);
    Assertions.assertThat(results.get(0)).isEqualTo("M");
    Assertions.assertThat(results.get(1)).isEqualTo("a");
    Assertions.assertThat(results.get(2)).isEqualTo(1L);
}
Also used : Arrays(java.util.Arrays) InternalFactHandle(org.drools.core.common.InternalFactHandle) Accumulator(org.drools.core.spi.Accumulator) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Global(org.drools.model.Global) RuleEventListener(org.kie.internal.event.rule.RuleEventListener) DSL(org.drools.model.DSL) Child(org.drools.modelcompiler.domain.Child) Match(org.kie.api.runtime.rule.Match) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) Declaration(org.drools.core.rule.Declaration) Assertions(org.assertj.core.api.Assertions) KieSession(org.kie.api.runtime.KieSession) Parent(org.drools.modelcompiler.domain.Parent) Set(java.util.Set) Index(org.drools.model.Index) ConsequenceBuilder(org.drools.model.consequences.ConsequenceBuilder) EvaluationUtil(org.drools.modelcompiler.util.EvaluationUtil) Objects(java.util.Objects) List(java.util.List) Tuple(org.drools.core.spi.Tuple) CountAccumulateFunction(org.drools.core.base.accumulators.CountAccumulateFunction) Person(org.drools.modelcompiler.domain.Person) DSL.from(org.drools.model.DSL.from) ModelImpl(org.drools.model.impl.ModelImpl) HashMap(java.util.HashMap) PatternDSL(org.drools.model.PatternDSL) ArrayList(java.util.ArrayList) Function1(org.drools.model.functions.Function1) CollectListAccumulateFunction(org.drools.core.base.accumulators.CollectListAccumulateFunction) RuleEventManager(org.kie.internal.event.rule.RuleEventManager) KieBase(org.kie.api.KieBase) LinkedHashSet(java.util.LinkedHashSet) Model(org.drools.model.Model) IntegerMaxAccumulateFunction(org.drools.core.base.accumulators.IntegerMaxAccumulateFunction) ReteEvaluator(org.drools.core.common.ReteEvaluator) ViewItem(org.drools.model.view.ViewItem) Pair(org.apache.commons.math3.util.Pair) Variable(org.drools.model.Variable) D(org.drools.modelcompiler.dsl.pattern.D) IntegerSumAccumulateFunction(org.drools.core.base.accumulators.IntegerSumAccumulateFunction) ToIntFunction(java.util.function.ToIntFunction) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) GroupKey(org.drools.model.functions.accumulate.GroupKey) FactHandle(org.kie.api.runtime.rule.FactHandle) KieBaseBuilder(org.drools.modelcompiler.builder.KieBaseBuilder) Assert.assertNull(org.junit.Assert.assertNull) Ignore(org.junit.Ignore) Rule(org.drools.model.Rule) ExprViewItem(org.drools.model.view.ExprViewItem) RuleTerminalNodeLeftTuple(org.drools.core.reteoo.RuleTerminalNodeLeftTuple) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) Variable(org.drools.model.Variable) ArrayList(java.util.ArrayList) Model(org.drools.model.Model) List(java.util.List) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) Rule(org.drools.model.Rule) ModelImpl(org.drools.model.impl.ModelImpl) Person(org.drools.modelcompiler.domain.Person) Pair(org.apache.commons.math3.util.Pair) Test(org.junit.Test)

Example 9 with CountAccumulateFunction

use of org.drools.core.base.accumulators.CountAccumulateFunction in project drools by kiegroup.

the class GroupByTest method testUnexpectedRuleMatch.

@Test
public void testUnexpectedRuleMatch() {
    final Global<List> var_results = D.globalOf(List.class, "defaultpkg", "results");
    // $a: Parent()
    Variable<Parent> patternVar = D.declarationOf(Parent.class);
    PatternDSL.PatternDef<Parent> pattern = D.pattern(patternVar);
    // exists Child($a.getChild() == this)
    Variable<Child> existsPatternVar = D.declarationOf(Child.class);
    PatternDSL.PatternDef<Child> existsPattern = D.pattern(existsPatternVar).expr(patternVar, (child, parent) -> Objects.equals(parent.getChild(), child));
    // count(Parent::getChild)
    Variable<Child> groupKeyVar = D.declarationOf(Child.class);
    Variable<Long> accumulateResult = D.declarationOf(Long.class);
    ExprViewItem groupBy = PatternDSL.groupBy(D.and(pattern, D.exists(existsPattern)), patternVar, groupKeyVar, Parent::getChild, DSL.accFunction(CountAccumulateFunction::new).as(accumulateResult));
    Rule rule1 = D.rule("R1").build(groupBy, D.on(var_results, groupKeyVar, accumulateResult).execute((results, $child, $count) -> results.add(Arrays.asList($child, $count))));
    Model model = new ModelImpl().addRule(rule1).addGlobal(var_results);
    KieSession ksession = KieBaseBuilder.createKieBaseFromModel(model).newKieSession();
    List results = new ArrayList();
    ksession.setGlobal("results", results);
    Child child1 = new Child("Child1", 1);
    Parent parent1 = new Parent("Parent1", child1);
    Child child2 = new Child("Child2", 2);
    Parent parent2 = new Parent("Parent2", child2);
    ksession.insert(parent1);
    ksession.insert(parent2);
    FactHandle toRemove = ksession.insert(child1);
    ksession.insert(child2);
    // Remove child1, therefore it does not exist, therefore there should be no groupBy matches for the child.
    ksession.delete(toRemove);
    // Yet, we still get (Child1, 0).
    ksession.fireAllRules();
    Assertions.assertThat(results).containsOnly(Arrays.asList(child2, 1L));
}
Also used : Arrays(java.util.Arrays) InternalFactHandle(org.drools.core.common.InternalFactHandle) Accumulator(org.drools.core.spi.Accumulator) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Global(org.drools.model.Global) RuleEventListener(org.kie.internal.event.rule.RuleEventListener) DSL(org.drools.model.DSL) Child(org.drools.modelcompiler.domain.Child) Match(org.kie.api.runtime.rule.Match) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) Declaration(org.drools.core.rule.Declaration) Assertions(org.assertj.core.api.Assertions) KieSession(org.kie.api.runtime.KieSession) Parent(org.drools.modelcompiler.domain.Parent) Set(java.util.Set) Index(org.drools.model.Index) ConsequenceBuilder(org.drools.model.consequences.ConsequenceBuilder) EvaluationUtil(org.drools.modelcompiler.util.EvaluationUtil) Objects(java.util.Objects) List(java.util.List) Tuple(org.drools.core.spi.Tuple) CountAccumulateFunction(org.drools.core.base.accumulators.CountAccumulateFunction) Person(org.drools.modelcompiler.domain.Person) DSL.from(org.drools.model.DSL.from) ModelImpl(org.drools.model.impl.ModelImpl) HashMap(java.util.HashMap) PatternDSL(org.drools.model.PatternDSL) ArrayList(java.util.ArrayList) Function1(org.drools.model.functions.Function1) CollectListAccumulateFunction(org.drools.core.base.accumulators.CollectListAccumulateFunction) RuleEventManager(org.kie.internal.event.rule.RuleEventManager) KieBase(org.kie.api.KieBase) LinkedHashSet(java.util.LinkedHashSet) Model(org.drools.model.Model) IntegerMaxAccumulateFunction(org.drools.core.base.accumulators.IntegerMaxAccumulateFunction) ReteEvaluator(org.drools.core.common.ReteEvaluator) ViewItem(org.drools.model.view.ViewItem) Pair(org.apache.commons.math3.util.Pair) Variable(org.drools.model.Variable) D(org.drools.modelcompiler.dsl.pattern.D) IntegerSumAccumulateFunction(org.drools.core.base.accumulators.IntegerSumAccumulateFunction) ToIntFunction(java.util.function.ToIntFunction) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) GroupKey(org.drools.model.functions.accumulate.GroupKey) FactHandle(org.kie.api.runtime.rule.FactHandle) KieBaseBuilder(org.drools.modelcompiler.builder.KieBaseBuilder) Assert.assertNull(org.junit.Assert.assertNull) Ignore(org.junit.Ignore) Rule(org.drools.model.Rule) ExprViewItem(org.drools.model.view.ExprViewItem) RuleTerminalNodeLeftTuple(org.drools.core.reteoo.RuleTerminalNodeLeftTuple) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) ExprViewItem(org.drools.model.view.ExprViewItem) PatternDSL(org.drools.model.PatternDSL) Parent(org.drools.modelcompiler.domain.Parent) InternalFactHandle(org.drools.core.common.InternalFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) ArrayList(java.util.ArrayList) CountAccumulateFunction(org.drools.core.base.accumulators.CountAccumulateFunction) Model(org.drools.model.Model) List(java.util.List) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) Rule(org.drools.model.Rule) ModelImpl(org.drools.model.impl.ModelImpl) Child(org.drools.modelcompiler.domain.Child) Test(org.junit.Test)

Aggregations

CountAccumulateFunction (org.drools.core.base.accumulators.CountAccumulateFunction)9 HashMap (java.util.HashMap)8 Map (java.util.Map)8 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 Model (org.drools.model.Model)8 Rule (org.drools.model.Rule)8 ConsequenceBuilder (org.drools.model.consequences.ConsequenceBuilder)8 ModelImpl (org.drools.model.impl.ModelImpl)8 ExprViewItem (org.drools.model.view.ExprViewItem)8 ViewItem (org.drools.model.view.ViewItem)8 ArrayList (java.util.ArrayList)7 Declaration (org.drools.core.rule.Declaration)7 Accumulator (org.drools.core.spi.Accumulator)7 PatternDSL (org.drools.model.PatternDSL)7 Variable (org.drools.model.Variable)7 Arrays (java.util.Arrays)6 Collections (java.util.Collections)6 LinkedHashSet (java.util.LinkedHashSet)6 List (java.util.List)6 Objects (java.util.Objects)6