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

astra.tr.TRContext Maven / Gradle / Ivy

There is a newer version: 1.4.2
Show newest version
package astra.tr;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import astra.core.AbstractTask;
import astra.core.Agent;
import astra.core.Module;
import astra.formula.Formula;
import astra.formula.Predicate;
import astra.reasoner.Unifier;
import astra.reasoner.util.BindingsEvaluateVisitor;
import astra.term.Primitive;
import astra.term.Term;

public class TRContext {
	List trace = new LinkedList();
	Agent agent;
	int index;
	
	public TRContext(Agent agent, Predicate call) {
		this.agent = agent;
		trace.add(call);
	}
	
	@SuppressWarnings("unchecked")
	public  T getValue(Term term) {
		if (term instanceof Primitive) {
			return (T) ((Primitive) term).value();
		}
		return null;
	}

	public Module getModule(String classname, String key) {
		return agent.getModule(classname, key);
	}
	
	public boolean execute() {
		int index = 0;
		while (index < trace.size()) {
//			System.out.println("handling: " + trace.get(index));
			Function function = agent.getFunction(trace.get(index));
//			System.out.println("function: " + function);
			Map bindings = Unifier.unify(function.identifier, trace.get(index), agent);
			if (bindings == null) {
				System.err.println("ERROR EXECUTING TR FUNCTION: " + trace.get(index));
				for (int i=trace.size()-1; i >= 0; i--) {
					System.err.println(trace.get(i));
				}
				return false;
			}

			// Loop through the function rules until one fires and then
			// exit the loop. If no rules fire, this is okay - we do a
			// skip operation
			for (TRRule rule : function.rules) {
				Map b = new HashMap();
				b.putAll(bindings);
				Formula cond = (Formula) rule.condition.accept(new BindingsEvaluateVisitor(b, agent));
				List> result = agent.query(cond, b);
				if (result != null) {
					if (!result.isEmpty()) {
						bindings.putAll(result.get(0));
					}
//					System.out.println("\tselected: " + rule);
					rule.execute(this, bindings);
					break;
				}
			}

			
			index++;
		}
		return true;
	}

	public void callFunction(Predicate call) {
		trace.add(call);
	}

	public void addBelief(Predicate belief) {
		agent.beliefs().addBelief(belief);
		
	}

	public void removeBelief(Predicate belief) {
		agent.beliefs().dropBelief(belief);
		
	}

	public String name() {
		return agent.name();
	}

	public void schedule(AbstractTask task) {
		agent.schedule(task);
	}

	public void stopFunction() {
		agent.stopFunction();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy