jadex.rules.rulesystem.rete.builder.ReteBuilder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jadex-rules Show documentation
Show all versions of jadex-rules Show documentation
Jadex Rules is a small lightweight rule engine, which currently
employs the well-known Rete algorithm for highly efficient rule
matching. Jadex rules is therefore similar to other rule engines
like JESS and Drools. Despite the similarities there are also
important differences between these systems:
* Jadex Rules is very small and
intended to be used as component
of other software. Even though rules can be specified in a Java
dialect as well as (a small variation of) the CLIPS language
its primary usage is on the API level. Jadex Rules is currently
the core component of the Jadex BDI reasoning engine.
* Jadex Rules cleanly separates between state and rule representation.
This allows the state implementation as well as the matcher to be
flexibly exchanged. Some experiments have e.g. been conducted with
a Jena representation. Regarding the matcher, it is planned to
support also the Treat algorithm, which has a lower memory footprint
than Rete.
* Jadex Rules pays close attention to rule debugging. The state as
well as the rete engine can be observed at runtime. The rule debugger
provides functionalities to execute a rule program stepwise and also
use rule breakpoints to stop the execution at those points.
package jadex.rules.rulesystem.rete.builder;
import jadex.rules.rulesystem.ICondition;
import jadex.rules.rulesystem.IRule;
import jadex.rules.rulesystem.rete.constraints.AndConstraintEvaluator;
import jadex.rules.rulesystem.rete.constraints.ConstraintEvaluator;
import jadex.rules.rulesystem.rete.constraints.ConstraintIndexer;
import jadex.rules.rulesystem.rete.constraints.IConstraintEvaluator;
import jadex.rules.rulesystem.rete.constraints.NotConstraintEvaluator;
import jadex.rules.rulesystem.rete.constraints.OrConstraintEvaluator;
import jadex.rules.rulesystem.rete.extractors.ChainedExtractor;
import jadex.rules.rulesystem.rete.extractors.ConstantExtractor;
import jadex.rules.rulesystem.rete.extractors.FunctionExtractor;
import jadex.rules.rulesystem.rete.extractors.IValueExtractor;
import jadex.rules.rulesystem.rete.extractors.JavaArrayExtractor;
import jadex.rules.rulesystem.rete.extractors.JavaMethodExtractor;
import jadex.rules.rulesystem.rete.extractors.JavaObjectExtractor;
import jadex.rules.rulesystem.rete.extractors.JavaPrefixExtractor;
import jadex.rules.rulesystem.rete.extractors.JavaTupleExtractor;
import jadex.rules.rulesystem.rete.extractors.MultifieldExtractor;
import jadex.rules.rulesystem.rete.extractors.ObjectExtractor;
import jadex.rules.rulesystem.rete.extractors.PrefixExtractor;
import jadex.rules.rulesystem.rete.extractors.StateExtractor;
import jadex.rules.rulesystem.rete.extractors.TupleExtractor;
import jadex.rules.rulesystem.rete.nodes.AlphaNode;
import jadex.rules.rulesystem.rete.nodes.BetaNode;
import jadex.rules.rulesystem.rete.nodes.CollectNode;
import jadex.rules.rulesystem.rete.nodes.INode;
import jadex.rules.rulesystem.rete.nodes.IObjectConsumerNode;
import jadex.rules.rulesystem.rete.nodes.IObjectSourceNode;
import jadex.rules.rulesystem.rete.nodes.ITupleConsumerNode;
import jadex.rules.rulesystem.rete.nodes.ITupleSourceNode;
import jadex.rules.rulesystem.rete.nodes.InitialFactNode;
import jadex.rules.rulesystem.rete.nodes.LeftInputAdapterNode;
import jadex.rules.rulesystem.rete.nodes.NotNode;
import jadex.rules.rulesystem.rete.nodes.ReteNode;
import jadex.rules.rulesystem.rete.nodes.RightInputAdapterNode;
import jadex.rules.rulesystem.rete.nodes.SplitNode;
import jadex.rules.rulesystem.rete.nodes.TerminalNode;
import jadex.rules.rulesystem.rete.nodes.TestNode;
import jadex.rules.rulesystem.rete.nodes.TypeNode;
import jadex.rules.rulesystem.rules.AndCondition;
import jadex.rules.rulesystem.rules.AndConstraint;
import jadex.rules.rulesystem.rules.ArraySelector;
import jadex.rules.rulesystem.rules.BoundConstraint;
import jadex.rules.rulesystem.rules.CollectCondition;
import jadex.rules.rulesystem.rules.Constant;
import jadex.rules.rulesystem.rules.Constraint;
import jadex.rules.rulesystem.rules.FunctionCall;
import jadex.rules.rulesystem.rules.IConstraint;
import jadex.rules.rulesystem.rules.IOperator;
import jadex.rules.rulesystem.rules.LiteralConstraint;
import jadex.rules.rulesystem.rules.LiteralReturnValueConstraint;
import jadex.rules.rulesystem.rules.MethodCall;
import jadex.rules.rulesystem.rules.NotCondition;
import jadex.rules.rulesystem.rules.ObjectCondition;
import jadex.rules.rulesystem.rules.OrCondition;
import jadex.rules.rulesystem.rules.OrConstraint;
import jadex.rules.rulesystem.rules.PredicateConstraint;
import jadex.rules.rulesystem.rules.ReturnValueConstraint;
import jadex.rules.rulesystem.rules.TestCondition;
import jadex.rules.rulesystem.rules.ValueSourceReturnValueConstraint;
import jadex.rules.rulesystem.rules.Variable;
import jadex.rules.rulesystem.rules.VariableReturnValueConstraint;
import jadex.rules.state.OAVAttributeType;
import jadex.rules.state.OAVJavaAttributeType;
import jadex.rules.state.OAVJavaType;
import jadex.rules.state.OAVObjectType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* The rete builder class has the purpose to generate
* a rete network for a condition.
*/
public class ReteBuilder
{
//-------- constants --------
/** The flag for turning on/off reporting. */
public static boolean REPORTING = false;
//-------- attributes --------
/** Flag to turn on/off indexing. */
protected boolean indexing;
/** Flag to turn on/off nodesharing. */
protected boolean nodesharing;
/** Flag to turn on/off placing join constraints in a not node
* (otherwise separate beta nodes will be created and not nodes will have no constraints). */
protected boolean notjoin;
/** The build report. */
protected BuildReport report;
//-------- constructors --------
/**
* Create a new rete builder.
*/
public ReteBuilder()
{
this.indexing = true;
this.nodesharing = true;
this.notjoin = true;
if(REPORTING)
this.report = new BuildReport();
}
//-------- methods --------
/**
* Add a new rule to the network.
* @param root The root node (when null a new network will be created).
* @param rule The rule to add.
*/
public ReteNode addRule(ReteNode root, IRule rule)
{
// todo: or, exists conditions
// System.nanoTime() : @since 1.5
//long start = System.nanoTime();
long start = System.currentTimeMillis();
BuildContext context = new BuildContext(root, rule);
ICondition cond = rule.getCondition();
buildCondition(cond, context);
addTerminalNode(rule, context);
ReteNode ret = context.getRootNode();
// System.nanoTime() : @since 1.5
//long end = System.nanoTime();
long end = System.currentTimeMillis();
if(REPORTING)
report.addInfo(rule, (end-start));
return ret;
}
/**
* Remove a rule from a rete network.
* @param root The root node.
* @param rule The rule to remove.
*/
public void removeRule(ReteNode root, IRule rule)
{
// Find terminal node that is associated with the rule
// and call node usage removal.
TerminalNode tnode = root.getTerminalNode(rule);
removeNodeUsage(tnode);
}
/**
* Get the build report.
* @return The build report.
*/
public BuildReport getBuildReport()
{
return report;
}
/**
* Build any kind condition.
*/
public void buildCondition(ICondition curcond, BuildContext context)
{
if(curcond instanceof AndCondition)
{
buildAndCondition((AndCondition)curcond, context);
}
else if(curcond instanceof OrCondition)
{
buildOrCondition((OrCondition)curcond, context);
}
else if(curcond instanceof NotCondition)
{
buildNotCondition((NotCondition)curcond, context);
}
else if(curcond instanceof ObjectCondition)
{
buildObjectCondition((ObjectCondition)curcond, context);
}
else if(curcond instanceof TestCondition)
{
buildTestCondition((TestCondition)curcond, context);
}
else if(curcond instanceof CollectCondition)
{
buildCollectCondition((CollectCondition)curcond, context);
}
else
{
throw new RuntimeException("Unknown condition type: "+curcond);
}
}
/**
* Build an and condition.
*/
public void buildAndCondition(AndCondition curcond, BuildContext context)
{
List conds = curcond.getConditions();
for(int i=0; i0)
evaluators.addAll(tmp);
}
}
IConstraintEvaluator[] evas = evaluators.size()==0? null:
(IConstraintEvaluator[])evaluators.toArray(new IConstraintEvaluator[evaluators.size()]);
ConstraintIndexer[] ids = indexers.size()==0? null:
(ConstraintIndexer[])indexers.toArray(new ConstraintIndexer[indexers.size()]);
addBetaNode(evas, ids, context);
}
else if(!betaconsts.isEmpty())
{
throw new RuntimeException("Cannot build constraints: "+context.getRule().getName()+", "+curcond);
}
else
{
context.setLastBetaNode(context.getLastAlphaNode());
}
// Update the tuple cnt in the context.
context.setLastAlphaNode(null);
context.setTupleCount(context.getTupleCount()+1);
}
/**
* Build a test condition.
*/
public void buildTestCondition(TestCondition curcond, BuildContext context)
{
List evas = buildConstraintEvaluator(curcond, curcond.getConstraint(), context);
if(evas.size()!=1)
throw new RuntimeException("Test condition must result in exactly one evaluator: "+evas);
if(context.getLastBetaNode()==null)
addInitialFactNode(context);
addTestNode((IConstraintEvaluator)evas.get(0), context);
}
/**
* Build a collect condition.
*/
public void buildCollectCondition(CollectCondition curcond, BuildContext context)
{
// It is assumed that the first object condition defines the object to collect.
int tuplecnt = context.getTupleCount();
List ocons = curcond.getObjectConditions();
if(ocons.size()>1)
buildAndCondition(new AndCondition(ocons), context);
else
buildObjectCondition((ObjectCondition)ocons.get(0), context);
// Todo: remove variable infos from inner object condition?
// Tuple cnt has already been updated, but collect condition adds no object -> temporarily reset
context.setTupleCount(context.getTupleCount()-ocons.size());
context.setRightUnavailable(true);
List consts = curcond.getConstraints();
List evas = null;
if(consts!=null && consts.size()>0)
{
for(int i=0; i0)
{
if(evas==null)
evas = newevas;
else
evas.addAll(newevas);
}
}
}
addCollectNode(evas!=null? (IConstraintEvaluator[])evas.toArray(
new IConstraintEvaluator[evas.size()]): null, tuplecnt, context);
context.setRightUnavailable(false);
context.setTupleCount(context.getTupleCount()+ocons.size());
}
/**
* Remove a node usage.
* @param node The node usage to remove.
*/
protected void removeNodeUsage(INode node)
{
// Traverse backwards through the network
// and delete a node and its connections if
// it has no children any more
int cnt = getChildCount(node);
if(node instanceof ITupleConsumerNode)
{
ITupleConsumerNode consumer = (ITupleConsumerNode)node;
ITupleSourceNode source = consumer.getTupleSource();
if(cnt==0 && source!=null)
{
consumer.setTupleSource(null);
source.removeTupleConsumer(consumer);
removeNodeUsage(source);
}
}
if(node instanceof IObjectConsumerNode)
{
IObjectConsumerNode consumer = (IObjectConsumerNode)node;
IObjectSourceNode source = consumer.getObjectSource();
if(cnt==0 && source!=null)
{
consumer.setObjectSource(null);
source.removeObjectConsumer(consumer);
removeNodeUsage(source);
}
}
}
/**
* Count the number of children.
* @param node The node.
* @return The number of children.
*/
protected int getChildCount(INode node)
{
int ret = 0;
if(node instanceof ITupleSourceNode)
{
ITupleSourceNode tsn = (ITupleSourceNode)node;
ITupleConsumerNode[] cs = tsn.getTupleConsumers();
ret += cs==null? 0: cs.length;
}
if(node instanceof IObjectSourceNode)
{
IObjectSourceNode tsn = (IObjectSourceNode)node;
IObjectConsumerNode[] cs = tsn.getObjectConsumers();
ret += cs==null? 0: cs.length;
}
return ret;
}
/**
* Connect two nodes by attaching the source to the left (tuple) input of the consumer.
* @param source The source node.
* @param consumer The consumer node.
*/
protected void connectLeft(INode source, INode consumer, BuildContext context)
{
// Connect compatible nodes directly.
if(source instanceof ITupleSourceNode && consumer instanceof ITupleConsumerNode)
{
ITupleSourceNode s = (ITupleSourceNode)source;
ITupleConsumerNode c = (ITupleConsumerNode)consumer;
s.addTupleConsumer(c);
c.setTupleSource(s);
}
// Use left input adapter to connect nodes.
else if(source instanceof IObjectSourceNode && consumer instanceof ITupleConsumerNode)
{
IObjectSourceNode s = (IObjectSourceNode)source;
ITupleConsumerNode c = (ITupleConsumerNode)consumer;
// Try to reuse existing adapter
LeftInputAdapterNode lia = null;
if(nodesharing)
{
IObjectConsumerNode[] ocon = s.getObjectConsumers();
for(int i=0; lia==null && ocon!=null && i