All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jadex.rules.rulesystem.rete.nodes.AbstractBetaNode Maven / Gradle / Ivy

Go to download

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.

There is a newer version: 2.4
Show newest version
package jadex.rules.rulesystem.rete.nodes;

import jadex.rules.rulesystem.AbstractAgenda;
import jadex.rules.rulesystem.rete.Tuple;
import jadex.rules.rulesystem.rete.constraints.ConstraintIndexer;
import jadex.rules.rulesystem.rete.constraints.IConstraintEvaluator;
import jadex.rules.rulesystem.rete.extractors.AttributeSet;
import jadex.rules.state.IOAVState;
import jadex.rules.state.IProfiler;
import jadex.rules.state.OAVAttributeType;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 *  A beta node has the purpose to perform a constraints check
 *  between (at least) two objects. The beta node has to incoming
 *  coming connections which both can activate the node.
 */
public abstract class AbstractBetaNode extends AbstractNode implements IObjectConsumerNode,
	ITupleConsumerNode, ITupleSourceNode
{
	//-------- attributes --------
	
	/** The tuple consumers. */
	protected ITupleConsumerNode[] tconsumers;
	
	/** The object source. */
	protected IObjectSourceNode osource;
	
	/** The tuple source. */
	protected ITupleSourceNode tsource;
	
	/** The constraint evaluator. */
	protected IConstraintEvaluator[] evaluators;
	
	/** The indexed constraint indexers. */
	protected ConstraintIndexer[] indexers;

	/** The set of relevant attributes. */
	protected AttributeSet relevants;

	/** The set of indirect attributes. */
	protected AttributeSet indirects;

	//-------- constructors --------
	
	/**
	 *  Create a new beta node.
	 */
	public AbstractBetaNode(int nodeid, IConstraintEvaluator[] evaluators, ConstraintIndexer[] xevaluators)
	{
		super(nodeid);
		this.evaluators	= evaluators;
		this.indexers = xevaluators;
	}
	
	//-------- tuple source interface --------
	
	/**
	 *  Add an tuple consumer node.
	 *  @param node A new consumer node.
	 */
	public void addTupleConsumer(ITupleConsumerNode node)
	{
		if(tconsumers==null)
		{
			tconsumers = new ITupleConsumerNode[]{node};
		}
		else
		{
			ITupleConsumerNode[]	tmp	= new ITupleConsumerNode[tconsumers.length+1];
			System.arraycopy(tconsumers, 0, tmp, 0, tconsumers.length);
			tmp[tconsumers.length]	= node;
			tconsumers	= tmp;
		}

		relevants	= null;	// Will be recalculated on next access;
	}
	
	/**
	 *  Remove an tuple consumer.
	 *  @param node The consumer node.
	 */
	public void removeTupleConsumer(ITupleConsumerNode node)
	{
		if(tconsumers!=null)
		{
			for(int i=0; i0)
							System.arraycopy(tconsumers, 0, tmp, 0, i);
						if(i add match
					if(!contains && check)
						addMatch(left, right, state, mem, agenda);

					// Tuple no longer valid -> remove match
					else if(contains && !check)
						removeMatch(left, right, state, mem, agenda);
				
					// Tuple changed in memory -> propagate modification
					else if(contains)
						propagateModification(left, right, tupleindex, type, 
							oldvalue, newvalue, state, mem, agenda);
				}
			}
			
			// Handle objects no longer in object memory (only when indexers are present,
			// otherwise complete object memory is already handled before). 
			if(indexers!=null)
			{
				if(changed && oldmem!=null)
				{
					for(Iterator it=oldmem.iterator(); it.hasNext(); )
					{
						Object right = it.next();
						boolean contains = isMatchContained(state, left, right, mem);
		
						// Remove matches, when object in old memory but not in new memory.
						if(contains && (newmem==null || !newmem.contains(right)))
							removeMatch(left, right, state, mem, agenda);
					}
				}
			}
		}
		
		state.getProfiler().stop(IProfiler.TYPE_NODEEVENT, IProfiler.NODEEVENT_TUPLEMODIFIED);
		state.getProfiler().stop(IProfiler.TYPE_NODE, this);
	}

	/**
	 *  Set the tuple source of this node.
	 *  @param node The tuple source node.
	 */
	public void setTupleSource(ITupleSourceNode node)
	{
		this.tsource = node;
	}
	
	/**
	 *  Get the tuple source of this node.
	 *  @return The object source node.
	 */
	public ITupleSourceNode getTupleSource()
	{
		return tsource;
	}
	
	//-------- object consumer interface (right) --------
	
	/**
	 *  Send an object to this node.
	 *  @param object The object.
	 */
	public void addObject(Object right, IOAVState state, ReteMemory mem, AbstractAgenda agenda)
	{
//		if(getNodeId()==530)
//			System.out.println(this+".addObject: "+right);

//		System.out.println("Add object called: "+this+" "+right);
		state.getProfiler().start(IProfiler.TYPE_NODE, this);
		state.getProfiler().start(IProfiler.TYPE_NODEEVENT, IProfiler.NODEEVENT_OBJECTADDED);
		
		// Update the indexed memories
		if(indexers!=null)
		{
			BetaMemory bmem = (BetaMemory)mem.getNodeMemory(this);
			for(int i=0; i0)
//		if(this instanceof NotNode)
//		{
//			if(mem.debug==null)
//			{
//				mem.debug	= new ArrayList();
//			}
//			mem.debug.add("+++Remove object called: "+this+" "+right+", "+mem.getNodeMemory(this));
//		}
	
		state.getProfiler().start(IProfiler.TYPE_NODE, this);
		state.getProfiler().start(IProfiler.TYPE_NODEEVENT, IProfiler.NODEEVENT_OBJECTREMOVED);
		
		Collection tmem = fetchTupleMemory(state, right, mem);
		if(tmem!=null)
		{
			// Simply tries to remove all found entries
			for(Iterator it=tmem.iterator(); it.hasNext(); )
			{
				removeMatch((Tuple)it.next(), right, state, mem, agenda);
			}
		}

		// Remove object from indexed memories
		if(indexers!=null)
		{
			BetaMemory bmem = (BetaMemory)mem.getNodeMemory(this);
			for(int i=0; i add match
					if(!contains && check)
					{
//						if(getNodeId()==530)
//							System.out.println("add: "+left+" "+right);
						addMatch(left, right, state, mem, agenda);
					}
					
					// Tuple no longer valid -> remove match
					else if(contains && !check)
						removeMatch(left, right, state, mem, agenda);
				
					// Tuple changed in memory -> propagate modification
					else if(contains)
						propagateModification(left, right, left.size(), type, oldvalue, newvalue, state, mem, agenda);
				}
			}

			// Handle tuples no longer in tuple memory (only when indexers are present,
			// otherwise complete tuple memory is already handled before). 
			if(indexers!=null)
			{
				if(changed && oldmem!=null)
				{
					for(Iterator it=oldmem.iterator(); it.hasNext(); )
					{
						Tuple left = (Tuple)it.next();
						boolean contains = isMatchContained(state, left, right, mem);
		
						// Remove matches, when object in old memory but not in new memory.
						if(contains && (newmem==null || !newmem.contains(left)))
							removeMatch(left, right, state, mem, agenda);
					}
				}
			}			
		}
		
		// else
		// propagation of unaffected nodes is handled by subtypes.

//		if(this instanceof NotNode)
//			checkConsistency(mem);
		state.getProfiler().stop(IProfiler.TYPE_NODEEVENT, IProfiler.NODEEVENT_OBJECTMODIFIED);
		state.getProfiler().stop(IProfiler.TYPE_NODE, this);
	}

	/**
	 *  Propagate an indirect object change to this node.
	 *  @param id The changed object.
	 */
	public void modifyIndirectObject(Object object, OAVAttributeType type, Object oldvalue, Object newvalue, IOAVState state, ReteMemory mem, AbstractAgenda agenda)
	{
		Collection	linput	= getTupleSource().getNodeMemory(mem);
		if(linput!=null)
		{
			// Todo: Use index for avoiding the need for checking all tuple/object pairs.
			for(Iterator it=linput.iterator(); it.hasNext(); )
			{
				Tuple	left	= (Tuple)it.next();
				// Get indexed objects for tuple. (Todo: Indices need to be rebuilt!?)
				Collection omem = fetchObjectMemory(state, left, mem);
				if(omem!=null)
				{
					for(Iterator it2=omem.iterator(); it2.hasNext(); )
					{
						Object	right	= it2.next();
						boolean	contains	= isMatchContained(state, left, right, mem);
						boolean check = checkNonindexedConstraints(left, right, state);
		
						// Object no longer valid -> remove
						if(contains && !check)
						{
							removeMatch(left, right, state, mem, agenda);
						}
		
						// Object newly valid -> add
						else if(!contains && check)
						{
							addMatch(left, right, state, mem, agenda);
						}
					}
				}
			}
		}
	}

	/**
	 *  Set the object source of this node.
	 *  @param node The object source node.
	 */
	public void setObjectSource(IObjectSourceNode node)
	{
		this.osource = node;
	}
	
	/**
	 *  Get the object source of this node.
	 *  @return The object source node.
	 */
	public IObjectSourceNode getObjectSource()
	{
		return osource;
	}
	
	//-------- methods --------
	
	/**
	 *  Create the node memory.
	 *  @param state	The state.
	 *  @return The node memory.
	 */
	public Object createNodeMemory(IOAVState state)
	{
		return new BetaMemory(state);
	}
	
	/**
	 *  Get the indexers.
	 *  @return The indexers.
	 */
	public ConstraintIndexer[] getConstraintIndexers()
	{
		return indexers;
	}
	
	/**
	 *  Get the evaluators.
	 *  @return The evaluators.
	 */
	public IConstraintEvaluator[] getConstraintEvaluators()
	{
		return evaluators;
	}
	
	//-------- helpers --------
	
	/**
	 *  Compute the intersection of two collections.
	 *  @param c1 The first collection.
	 *  @param c2 The second collection.
	 *  @return The intersection.
	 */
	protected Collection intersection(IOAVState state, Collection c1, Collection c2)
	{
		if(c1==null || c2==null)
			return null;
		
		Collection ret = new LinkedHashSet();
		for(Iterator it=c1.iterator(); it.hasNext(); )
		{
			Object o1 = it.next();
			if(c2.contains(o1))
				ret.add(o1);
		}
		return ret;
	}	
	/**
	 *  Compute the intersection of two collections.
	 *  @param c1 The first collection.
	 *  @param c2 The second collection.
	 *  @return The intersection.
	 */
	protected Collection identityIntersection(IOAVState state, Collection c1, Collection c2)
	{
		if(c1==null || c2==null)
			return null;
		
		Collection ret = state.isJavaIdentity() ? (Set)new MixedIdentityHashSet(state) : new LinkedHashSet();
		for(Iterator it=c1.iterator(); it.hasNext(); )
		{
			Object o1 = it.next();
			if(c2.contains(o1))
				ret.add(o1);
		}
		return ret;
	}
	
	/**
	 *  Fetch the tuple memory for a given object.
	 *  @param right The right object.
	 *  @param mem The rete memory.
	 *  @param state The state.
	 *  @return The tuple memory matching that object (or complete).
	 */
	protected Collection fetchTupleMemory(IOAVState state, Object right, ReteMemory mem)
	{
		// Evaluate the indexed constraints
		Collection ret = null;
		if(indexers!=null)
		{
			if(mem.hasNodeMemory(this))
			{
				BetaMemory bmem = (BetaMemory)mem.getNodeMemory(this);	
				ret = indexers[0].findTuples(right, bmem);
	
				for(int i=1; ret!=null && i
            


© 2015 - 2024 Weber Informatics LLC | Privacy Policy