astra.core.EventBeliefManager Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of astra-interpreter Show documentation
Show all versions of astra-interpreter Show documentation
Core interpreter artifact for the ASTRA Language
package astra.core;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import astra.event.BeliefEvent;
import astra.event.Event;
import astra.event.ScopedBeliefEvent;
import astra.formula.Formula;
import astra.formula.Predicate;
import astra.reasoner.Queryable;
public class EventBeliefManager implements Queryable {
BeliefStore store = new BeliefStore();
Agent agent;
List addedBeliefs = Collections.synchronizedList(new LinkedList());
List droppedBeliefs = Collections.synchronizedList(new LinkedList());
public EventBeliefManager(Agent agent) {
this.agent = agent;
}
public void addBelief(Predicate belief) {
addedBeliefs.add(belief);
}
public void dropBelief(Predicate belief) {
// System.out.println("[EBM.dropBelief()] Adding: " + belief);
droppedBeliefs.add(belief);
}
public void update() {
while (!addedBeliefs.isEmpty()) {
Predicate belief = addedBeliefs.remove(0);
if (store.addBelief(belief)) {
String scope = scopes.remove(belief);
if (scope != null) {
agent.addEvent(new ScopedBeliefEvent(scope, new BeliefEvent(Event.ADDITION, belief)));
} else {
agent.addEvent(new BeliefEvent(Event.ADDITION, belief));
}
}
}
while (!droppedBeliefs.isEmpty()) {
Predicate belief = droppedBeliefs.remove(0);
// System.out.println("[EBM.update()] Removing: " + belief);
if (store.removeBelief(belief)) {
String scope = scopes.remove(belief);
if (scope != null) {
agent.addEvent(new ScopedBeliefEvent(scope, new BeliefEvent(Event.REMOVAL, belief)));
} else {
agent.addEvent(new BeliefEvent(BeliefEvent.REMOVAL, belief));
}
}
}
// dumpBeliefs();
}
public int size() {
return store.size();
}
public List beliefs() {
return store.beliefs();
}
public void dumpBeliefs() {
for (Formula belief : store.beliefs()) {
System.err.println(belief);
}
}
public boolean hasUpdates() {
return !addedBeliefs.isEmpty() || !droppedBeliefs.isEmpty();
}
private Map scopes = new HashMap();
public void addScopedBelief(String scope, Predicate belief) {
scopes.put(belief, scope);
addBelief(belief);
}
public void dropScopedBelief(String scope, Predicate belief) {
scopes.put(belief, scope);
dropBelief(belief);
}
public BeliefStore store() {
return this.store;
}
@Override
public void addMatchingFormulae(Queue queue, Formula formula) {
if (formula instanceof Predicate) {
store.addMatchingBeliefs(queue, (Predicate) formula);
}
}
@Override
public Iterator iterator(Formula target) {
return store.iterator(target);
}
}