Create Accumulate function on Drools Decision table - drools

I am trying to create accumulate function condition on Decision table. Please help me that How to create on Decision table.
My accumulate rule function is
when
$i : Double(doubleValue > 1000 ) from accumulate( Product($productQty:quantity),sum($productQty))
then
System.out.println( "The quantity is exceeded more than 1000 and the total value is " + $i );

You can create a column
rows
n condition
n+1 $i : Double() from accumulate( Product($productQty:quantity),sum($productQty))
n+2 doubleValue > $param
n+3 add quantitities and check
n+4 1000
Two comments.
This is not well-suited for decision tables unless you plan to check for different ranges of the accumulated value.
Why do you use double for counting what is, most likely, integral quantities? I'd be surprise if the accumulated stock exceeds Integer.MAX_VALUE. In short: use Number in the pattern and intValue in the constraint.

Related

Drools rule using accumulate

Hello I it is my first time involved in drools project. I have created some simple rules that work fine, however I have trouble with more complex rules that use the accumulate function. Below I have this rule.
rule "1"
no-loop
when
$msg : Declaration(header.totalGrossMassMeasure != null,
header.totalGrossMassMeasure.compareTo(BigDecimal.ZERO) > 0 )
result : ValidationResult()
$netValue : Number() from accumulate (
GoodsItemsType($net : netNetWeightMeasure),
sum($net.doubleValue())
)
eval($netValue.doubleValue() > ($msg.getHeader().getTotalGrossMassMeasure().doubleValue() + (0.45 * $msg.getGoodsItems().size())))
then
RulesValidationError error = new RulesValidationError();
error.setErrorType(ErrorType.INCORECT_VALUE);
result.getErrorsList().add(error);
end
the concept is to sum the net value from a list of goodsItemType object and compare the sum to the total gross mass measure multiplied by one buffer number. The problem is I have been trying last couple of days not being able to fire the rule with anything. Could someone please help me?

Drools - Sliding window not working as expected

I'm new to drools. I've defined the following rule to add the last two numbers in the stream together. I then send in a stream of 100 events, with the values set from 1 to 100. So I would expect the output to be 0, 1, 3, 5, 7, 9, 11, 13 etc.
declare TestEvent
#role( event )
value : int
end
rule "Simple Rule"
when
$sum : Integer() from accumulate ( TestEvent( $value : value ) over window:length( 2 ); sum( $value) )
then
System.out.println("Value: " + $sum );
end
The session is started using "fireUntilHalt" in a separate thread. If I put a delay of 10 milliseconds between every event inserted it works as expected. However when I don't have the delay, the results aren't as expected. Usually it just prints 0 and 197. Sometimes I might get a number or two in-between as well.
Why does this happen and what I should do to fix?
Ok, I finally understand it.
Having fireUntilHalt running in a separate thread means that the rules are only evaluated every now and then (not sure what that time period is). My assumption was that they would be evaluated on every insert. So on every insert the accumulator values are updated, but the rules evaluated aren't evaluated. So because my rules are inserted quickly (in about one second), the first and last insert is all that seems to be evaluated.
To get this to work so every insert is evaluated, I removed the fireUntilHalt, and did a separate fireAllRules after each insert.
Sliding windows are a crutch. Replace it by simple logic.
class Pred {
Integer pred;
}
rule procInt1
when
$p: Pred( pred == null )
$i: Integer()
then
modify( $p ){ setPred( $i ); }
end
rule procInt
when
$p: Pred( $i1: pred != null )
$i2: Integer()
then
System.out.println( $i1 + $i2 );
modify( $p ){ setPred( $i2 ); }
end
The fact that you have two threads doesn't mean that you can't have race conditions. The thread inserting events isn't suspended and so everything is possible.
Time related rules rely on 'time'. Smallest time tick for drools seems to be 1ms. Rules will be evaluated on each insertion (and respective consequences will be added to the agenda) but agenda will be executed on next millisecond tick (or when you explicitly fire all rules).

Can't make accumulate to work properly

I have the following class structure (Class A contains Class B):
class A {
B object;
...
}
and I'm trying to do something whenever the average of the accumulation of a specific field in class B is above a given value.
so I'm trying to write the following :
when
A($var1 : object)
accumulate( B($num:num) from $var1;
$avg1 : avg ($num); $avg1 < 10000)
then ...
what happens is that instead of accumulating all entities in the session and calculating the average for all of them, the average is being calculated on each entity separately.
so if the session already contains 5 numeric values which bigger than 10000 and another one is inserted then the "then" part is invoked 6 times (each one with average value the equals to the numeric value itself) instead of only once.
Do you have some hint that might help me to solve that?
thanks.
You have to accumulate over all A facts accessing the field num of field object.
when
accumulate( A( $var1: object );
$avg1: avg($var1.getNum()); $avg1 < 10000)
then ...
Inserting all B objects as facts as well would permit you to write the straightforward
when
accumulate( B( $num: num );
$avg1: avg($num); $avg1 < 10000)
then ...

To satisfy x out of y constraints

I am making a timetabling program which does one to one matches from SubjectTeacherPeriod (planning entity) to Period. There comes a case when I need to: "for y periods, atleast x of the SubjectTeacherPeriod must match a match_condition"
For example, I want to constrain 3 particular periods, atleast two of them to be taught by teachers who match to asst prof.
Here is the data structure holding such a constraint:
Class XOfYPeriods
SomeType match_condition
int x
List<Period> Periods //problem
SubjectTeacherPeriod has a Period, of course
class SubjectTeacherPeriod
int id
SomeType attrib
Period period
How do I write a rule that evaluates individual Periods from a list to check if x number of SubjectTeacherPeriods that are allocated those Periods meet the match condition?
Do correct me if I am defining my classes in bad form.
For the sake of example, here is a statement to be evaluated to determine a match: eval(matches($stp_attrib,$match_condition))
Sorry for the use of Pseudocode if it confused more than clarified. The SomeType is actually List< String> and thus the match condition is checked with a Collections.disjoint
I will give it a try, but not sure I completely understand your problem statement:
rule "X of Y Periods"
when
$c : XOfYPeriods( )
$list : List( size > $c.x ) from
accumulate( $stp : SubjectTeacherPeriod( matches(attrib, $c.match_condition),
period memberOf $c.periods ),
collectList( $stp ) )
then
// $list of STP that match the condition and
// whose period matches one of the periods in the list
end
Hope it helps.

Conceptual meaning of 'not' keyword; evaluating between objects

I am trying to find a BucketTotal object which has the smallest total in a Drools Planner project. I adapted this from example code.
rule "insertMinimumBucketTotal"
when
$b : BucketTotal($total : total)
not BucketTotal(total > $total) // CONFUSED HERE
then
insertLogical(new MinimumBucketTotal($total));
end
As far as my reasoning went, it meant "find BucketTotal object $b, such that there doesnt exist another BucketTotal object whose total is greater than total of $b".
Turns out, it meant the opposite (and I corrected it).
Please explain how Drools reasons that statement to find $b.
Indeed your are confusing things. "not" means "not exists". So if you want to find the minimum total you can do:
rule "minimum"
when
BucketTotal( $min : total )
not BucketTotal( total < $min )
then
// do something with $min
end
The above is usually the more performant way of doing it, but you can also use accumulate if you prefer:
rule "minimum"
when
accumulate( BucketTotal( $total : total ),
$min : min( $total ) )
then
// do something with $min
end