|
From: <jom...@us...> - 2008-03-17 21:13:32
|
Revision: 1158
http://jason.svn.sourceforge.net/jason/?rev=1158&view=rev
Author: jomifred
Date: 2008-03-17 14:13:29 -0700 (Mon, 17 Mar 2008)
Log Message:
-----------
implement make makeVarsAnnots for annotations
Modified Paths:
--------------
trunk/examples/gold-miners-II/asl/miner.asl
trunk/src/jason/asSyntax/Atom.java
trunk/src/jason/asSyntax/ListTermImpl.java
trunk/src/jason/asSyntax/Literal.java
trunk/src/jason/asSyntax/Pred.java
trunk/src/jason/asSyntax/Structure.java
trunk/src/test/TermTest.java
Modified: trunk/examples/gold-miners-II/asl/miner.asl
===================================================================
--- trunk/examples/gold-miners-II/asl/miner.asl 2008-03-17 19:13:28 UTC (rev 1157)
+++ trunk/examples/gold-miners-II/asl/miner.asl 2008-03-17 21:13:29 UTC (rev 1158)
@@ -59,7 +59,7 @@
!change_to_fetch(NewG).
+!choose_goal // there is no worth gold
- : carrying.gold > 0
+ : carrying_gold(NG) & NG > 0
<- !change_to_goto_depot.
+!choose_goal // not carrying gold, be free and search gold
Modified: trunk/src/jason/asSyntax/Atom.java
===================================================================
--- trunk/src/jason/asSyntax/Atom.java 2008-03-17 19:13:28 UTC (rev 1157)
+++ trunk/src/jason/asSyntax/Atom.java 2008-03-17 21:13:29 UTC (rev 1158)
@@ -33,9 +33,9 @@
import java.util.logging.Logger;
/**
- * Represents an atom (a structure with no arguments), it is an
+ * Represents an atom (a structure with no arguments, e.g. "tell", "a"), it is an
* immutable object. It extends Literal, so can be used in place of a
- * Literal, but does not allow operations on terms.
+ * Literal, but does not allow operations on terms/atoms and can not be negated.
*/
public final class Atom extends Literal {
@@ -113,17 +113,27 @@
// an Atom as parameter
return new ArrayList<Term>(2);
}
-
+
@Override
public Term[] getTermsArray() {
- return new Term[0];
+ return emptyTermArray;
}
+ @Override
+ public void setNegated(boolean b) {
+ logger.log(Level.SEVERE, "You should not negate the atom "+this+"\n",new Exception());
+ super.setNegated(b);
+ }
+
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
- if (o instanceof Structure) return getFunctor().equals(((Structure)o).getFunctor());
+ if (o instanceof Structure) {
+ Structure s = (Structure)o;
+ if (!getFunctor().equals(s.getFunctor())) return false;
+ return s.isAtom();
+ }
return false;
}
Modified: trunk/src/jason/asSyntax/ListTermImpl.java
===================================================================
--- trunk/src/jason/asSyntax/ListTermImpl.java 2008-03-17 19:13:28 UTC (rev 1157)
+++ trunk/src/jason/asSyntax/ListTermImpl.java 2008-03-17 21:13:29 UTC (rev 1158)
@@ -182,6 +182,11 @@
}
}
+ @Override
+ public boolean isAtom() {
+ return false;
+ }
+
@Override
public boolean isList() {
return true;
Modified: trunk/src/jason/asSyntax/Literal.java
===================================================================
--- trunk/src/jason/asSyntax/Literal.java 2008-03-17 19:13:28 UTC (rev 1157)
+++ trunk/src/jason/asSyntax/Literal.java 2008-03-17 21:13:29 UTC (rev 1158)
@@ -85,7 +85,10 @@
public static Literal parseLiteral(String sLiteral) {
as2j parser = new as2j(new StringReader(sLiteral));
try {
- return parser.literal();
+ Literal l = parser.literal();
+ if (l instanceof Atom) // force the result as literal
+ l = new Literal(l.getFunctor());
+ return l;
} catch (Exception e) {
logger.log(Level.SEVERE,"Error parsing literal " + sLiteral,e);
return null;
@@ -356,9 +359,9 @@
@SuppressWarnings("serial")
- static class TrueLiteral extends Literal {
+ static final class TrueLiteral extends Literal {
public TrueLiteral() {
- super("true",1);
+ super("true",0);
}
@Override
@@ -373,9 +376,9 @@
}
@SuppressWarnings("serial")
- static class FalseLiteral extends Literal {
+ static final class FalseLiteral extends Literal {
public FalseLiteral() {
- super("false",1);
+ super("false",0);
}
@Override
Modified: trunk/src/jason/asSyntax/Pred.java
===================================================================
--- trunk/src/jason/asSyntax/Pred.java 2008-03-17 19:13:28 UTC (rev 1157)
+++ trunk/src/jason/asSyntax/Pred.java 2008-03-17 21:13:29 UTC (rev 1158)
@@ -404,7 +404,36 @@
return false;
}
+
+ /**
+ * Replaces all variables of the term for unnamed variables (_).
+ *
+ * @param changes is the map of replacements
+ */
@Override
+ protected void makeVarsAnnon(Map<VarTerm,UnnamedVar> changes) {
+ if (annots != null) {
+ Iterator<ListTerm> i = annots.listTermIterator();
+ while (i.hasNext()) {
+ ListTerm lt = i.next();
+ Term ta = lt.getTerm();
+ if (ta.isVar()) {
+ // replace ta to an unnamed var
+ UnnamedVar uv = changes.get(ta);
+ if (uv == null) {
+ uv = new UnnamedVar();
+ changes.put((VarTerm)ta, uv);
+ }
+ lt.setTerm(uv);
+ } else if (ta.isStructure()) {
+ ((Structure)ta).makeVarsAnnon(changes);
+ }
+ }
+ }
+ super.makeVarsAnnon(changes);
+ }
+
+ @Override
public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
Modified: trunk/src/jason/asSyntax/Structure.java
===================================================================
--- trunk/src/jason/asSyntax/Structure.java 2008-03-17 19:13:28 UTC (rev 1157)
+++ trunk/src/jason/asSyntax/Structure.java 2008-03-17 21:13:29 UTC (rev 1158)
@@ -48,6 +48,8 @@
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(Structure.class.getName());
+ protected static final Term[] emptyTermArray = new Term[0]; // just to have a type for toArray in the getTermsArray method
+
private final String functor; // immutable field
private List<Term> terms;
@@ -237,11 +239,7 @@
/** returns the i-th term (first term is 0) */
public Term getTerm(int i) {
- if (terms.size() > i) {
- return terms.get(i);
- } else {
- return null;
- }
+ return terms.get(i);
}
public int getArity() {
@@ -264,8 +262,6 @@
return getArity() > 0; // should use getArity to work for list/atom
}
- private static final Term[] emptyTermArray = new Term[0]; // just to have a type for toArray in the getTermsArray method
-
public Term[] getTermsArray() {
return terms.toArray(emptyTermArray);
}
@@ -277,7 +273,7 @@
@Override
public boolean isAtom() {
- return !hasTerm() && !isList();
+ return !hasTerm();
}
public boolean isGround() {
@@ -300,7 +296,7 @@
*
* @param changes is the map of replacements
*/
- private void makeVarsAnnon(Map<VarTerm,UnnamedVar> changes) {
+ protected void makeVarsAnnon(Map<VarTerm,UnnamedVar> changes) {
final int size = getArity();
for (int i=0; i<size; i++) {
Term ti = getTerm(i);
Modified: trunk/src/test/TermTest.java
===================================================================
--- trunk/src/test/TermTest.java 2008-03-17 19:13:28 UTC (rev 1157)
+++ trunk/src/test/TermTest.java 2008-03-17 21:13:29 UTC (rev 1158)
@@ -7,11 +7,11 @@
import jason.asSyntax.ListTermImpl;
import jason.asSyntax.Literal;
import jason.asSyntax.NumberTermImpl;
+import jason.asSyntax.Plan;
import jason.asSyntax.Pred;
import jason.asSyntax.Structure;
import jason.asSyntax.Term;
import jason.asSyntax.Trigger;
-import jason.asSyntax.Plan;
import jason.asSyntax.VarTerm;
import jason.asSyntax.Trigger.TEOperator;
import jason.asSyntax.Trigger.TEType;
@@ -19,6 +19,8 @@
import jason.bb.BeliefBase;
import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
import junit.framework.TestCase;
@@ -72,8 +74,7 @@
Term tpos = new Atom("pos");
assertFalse(l3.equals(tpos));
- assertTrue(tpos.equals(l3));
- assertTrue(new Atom("pos").equals(l3));
+ assertFalse(tpos.equals(l3));
//System.out.println(new Term("pos")+"="+l3+" --> "+new Term("pos").equals(l3));
assertFalse(new Pred("pos").equals(l3));
@@ -581,6 +582,15 @@
assertEquals(l1.toString(), "calc(32,33,33)");
}
+ public void testMakeVarAnnon3() {
+ Literal l1 = Literal.parseLiteral("calc(AgY,X)[vl(X),source(AgY),bla(Y),X]");
+ l1.makeVarsAnnon();
+ Map<VarTerm, Integer> v = new HashMap<VarTerm, Integer>();
+ l1.countVars(v);
+ assertEquals(3, v.size());
+ assertEquals("vl("+l1.getTerm(1)+")",l1.getAnnots("vl").get(0).toString());
+ }
+
public void testAddAnnots() {
Literal p1 = Literal.parseLiteral("p1");
Literal p2 = Literal.parseLiteral("p2[a1,a2]");
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-18 22:36:43
|
Revision: 1165
http://jason.svn.sourceforge.net/jason/?rev=1165&view=rev
Author: jomifred
Date: 2008-03-18 15:36:40 -0700 (Tue, 18 Mar 2008)
Log Message:
-----------
improve jason-team
. send action to simulator when the agent is going to sleep (nothing else thus to decide)
. dummy has a "persistent goal" of moving
Modified Paths:
--------------
trunk/applications/jason-team/AC-Local-JasonTeam.mas2j
trunk/applications/jason-team/src/asl/dummy.asl
trunk/applications/jason-team/src/java/arch/ACArchitecture.java
trunk/applications/jason-team/src/java/arch/ACProxy.java
trunk/applications/jason-team/src/java/arch/CowboyArch.java
trunk/src/jason/asSyntax/Literal.java
Added Paths:
-----------
trunk/examples/gold-miners-II/miners.mas2j
Removed Paths:
-------------
trunk/examples/gold-miners-II/JasonTeam.mas2j
Modified: trunk/applications/jason-team/AC-Local-JasonTeam.mas2j
===================================================================
--- trunk/applications/jason-team/AC-Local-JasonTeam.mas2j 2008-03-18 21:40:34 UTC (rev 1164)
+++ trunk/applications/jason-team/AC-Local-JasonTeam.mas2j 2008-03-18 22:36:40 UTC (rev 1165)
@@ -15,32 +15,32 @@
host="localhost", port=12300, username=participant1, password="1"]
agentArchClass arch.ACArchitecture
agentClass agent.SelectEvent
- beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)");
+ beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)","corral(_,_,_,_)","pratio(_)");
dummy2 dummy.asl
[verbose=1,host="localhost", port=12300, username=participant2, password="2"]
agentArchClass arch.ACArchitecture
agentClass agent.SelectEvent
- beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)");
+ beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)","corral(_,_,_,_)","pratio(_)");
dummy3 dummy.asl
[verbose=1,host="localhost", port=12300, username=participant3, password="3"]
agentArchClass arch.ACArchitecture
agentClass agent.SelectEvent
- beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)");
+ beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)","corral(_,_,_,_)","pratio(_)");
dummy4 dummy.asl
[verbose=1,host="localhost", port=12300, username=participant4, password="4"]
agentArchClass arch.ACArchitecture
agentClass agent.SelectEvent
- beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)");
+ beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)","corral(_,_,_,_)","pratio(_)");
dummy5 dummy.asl
[verbose=1,host="localhost", port=12300, username=participant5, password="5"]
agentArchClass arch.ACArchitecture
agentClass agent.SelectEvent
- beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)");
+ beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)","corral(_,_,_,_)","pratio(_)");
dummy6 dummy.asl
[verbose=1,host="localhost", port=12300, username=participant6, password="6"]
agentArchClass arch.ACArchitecture
agentClass agent.SelectEvent
- beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)");
+ beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)","corral(_,_,_,_)","pratio(_)");
aslSourcePath: "src/asl";
}
Modified: trunk/applications/jason-team/src/asl/dummy.asl
===================================================================
--- trunk/applications/jason-team/src/asl/dummy.asl 2008-03-18 21:40:34 UTC (rev 1164)
+++ trunk/applications/jason-team/src/asl/dummy.asl 2008-03-18 22:36:40 UTC (rev 1165)
@@ -19,9 +19,6 @@
*/
-// the following plans (+pos....) react to the starting step
-// (since each new step causes a new +pos perception)
-
/* -- useful rules */
// find a free random location
@@ -29,35 +26,56 @@
pos(AgX,AgY,_) &
jia.random(RX,40) & X = (RX-20)+AgX & X > 0 &
jia.random(RY,40,5) & Y = (RY-20)+AgY &
- not jia.obstacle(X,Y) &
- jia.set_target(X,Y).
+ not jia.obstacle(X,Y).
+/* -- initial goal */
-/* -- go to the back pos -- */
+!move.
-// at the back_pos
-+pos(X,Y,_)
- : back_pos(X,Y) | // I am at back pos, find another
- (back_pos(BX,BY) & jia.direction(X, Y, BX, BY, skip)) // impossible to go to back_pos, find another
- <- !define_new_pos.
-+pos(X,Y,_)
- : back_pos(BX,BY) & jia.direction(X, Y, BX, BY, D) // one step towards back_pos
- <- do(D).
-
-/* -- random move -- */
-+pos(_,_,_)
- <- !define_new_pos.
+
+/* -- plans to move to a destination represented in the belief target(X,Y)
+ -- (it is a kind of persistent goal)
+*/
+
+// I still do not know my location
++!move
+ : not pos(_,_,_)
+ <- .print("waiting my location....");
+ .wait("+pos(_,_,_)");
+ !move.
+
+// find a new destination
++!move
+ : pos(X,Y,_) &
+ (not target(_,_) | // I have no target OR
+ target(X,Y) | // I am at target OR
+ (target(BX,BY) & jia.direction(X, Y, BX, BY, skip))) // is impossible to go to target
+ <- !define_new_target;
+ !move.
+
+// does one step towards target
++!move
+ : pos(X,Y,_) &
+ target(BX,BY) &
+ jia.direction(X, Y, BX, BY, D) // jia.direction finds one action D (using A*) towards the target
+ <- do(D); // this action will "block" the intention until it is sent to the simulator (in the end of the cycle)
+ !!move. // continue moving
+
+// in case of failure, move
+-!move
+ <- .current_intention(I); .println("failure in move:",I);
+ !move.
+
+
+/* -- add a belief target random move -- */
-+!define_new_pos
- <- ?pos(X,Y,_);
- ?random_pos(NX,NY);
- //.print("New point ",NX,",",NY);
- -+back_pos(NX,NY);
- jia.direction(X, Y, NX, NY, D);
- do(D).
++!define_new_target
+ <- ?random_pos(NX,NY);
+ jia.set_target(NX,NY);
+ -+target(NX,NY).
-+restart <- .drop_all_desires; !define_new_pos.
++restart <- .print("*** Restart! "); .drop_all_desires; !define_new_target; !move.
/* -- tests -- */
@@ -67,3 +85,4 @@
+cell(X,Y,Type) <- .println("cell = ",X,",",Y," = ",Type).
+pratio(R) <- .println("pratio = ",R).
++pos(X,Y,S) <- .println("pos = ",X,",",Y,"/",S).
\ No newline at end of file
Modified: trunk/applications/jason-team/src/java/arch/ACArchitecture.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-18 21:40:34 UTC (rev 1164)
+++ trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-18 22:36:40 UTC (rev 1165)
@@ -3,7 +3,6 @@
import jason.JasonException;
import jason.asSemantics.ActionExec;
import jason.asSyntax.Literal;
-import jason.asSyntax.Structure;
import jason.mas2j.ClassParameters;
import jason.runtime.Settings;
@@ -11,6 +10,7 @@
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.logging.Level;
import java.util.logging.Logger;
/**
@@ -27,6 +27,7 @@
private ACProxy proxy;
private List<Literal> percepts = new ArrayList<Literal>();
+ private WaitSleep waitSleepThread;
@Override
public void initAg(String agClass, ClassParameters bbPars, String asSrc, Settings stts) throws JasonException {
@@ -44,6 +45,9 @@
username,
password);
new Thread(proxy,"AgentProxy"+username).start();
+
+ waitSleepThread = new WaitSleep();
+ waitSleepThread.start();
}
@@ -51,47 +55,45 @@
public void stopAg() {
super.stopAg();
proxy.finish();
+ waitSleepThread.interrupt();
}
@Override
public List<Literal> perceive() {
- return new ArrayList<Literal>(percepts);
+ return new ArrayList<Literal>(percepts); // it must be a copy!
}
- Queue<ActionExec> toExecute = new ConcurrentLinkedQueue<ActionExec>();
-
+ @Override
+ /** when the agent can sleep, i.e. has nothing else to decide, sent its last action to the simulator */
+ public void sleep() {
+ waitSleepThread.go();
+ super.sleep();
+ }
+
public void startNextStep(int step, List<Literal> p) {
percepts = p;
-
- // set all actions as successfully executed
- List<ActionExec> feedback = getTS().getC().getFeedbackActions();
- while (!toExecute.isEmpty()) {
- ActionExec action = toExecute.poll();
- action.setResult(true);
- feedback.add(action);
- }
-
+ waitSleepThread.newCycle();
getTS().getUserAgArch().getArchInfraTier().wake();
setCycle(step);
}
+ /** all actions block its intention and succeed in the end of the cycle,
+ * only the last action of the cycle will be sent to simulator */
@Override
- public void act(final ActionExec act, List<ActionExec> feedback) {
- final Structure acTerm = act.getActionTerm();
- if (acTerm.getFunctor().equals("do")){
- // (to not block the TS)
- // TODO: use a thread pool
- new Thread() {
- public void run() {
- proxy.sendAction(acTerm.getTerm(0).toString());
- toExecute.offer(act);
- }
- }.start();
+ public void act(ActionExec act, List<ActionExec> feedback) {
+ if (act.getActionTerm().getFunctor().equals("do")) {
+ waitSleepThread.addAction(act);
} else {
- logger.info("ignoring action "+acTerm+", it is not a 'do'.");
+ logger.info("ignoring action "+act+", it is not a 'do'.");
}
}
-
+
+ @Override
+ void simulationEndPerceived(String result) {
+ percepts = new ArrayList<Literal>();
+ super.simulationEndPerceived(result);
+ }
+
// TODO: create a new agent and plug it on the connection
/** this method is called when the agent crashes and other approaches to fix it (fix1 and fix2) does not worked */
@@ -120,5 +122,58 @@
return false;
}
*/
+
+ class WaitSleep extends Thread {
+
+ ActionExec lastAction;
+ Queue<ActionExec> toExecute = new ConcurrentLinkedQueue<ActionExec>();
+ WaitSleep() {
+ super("WaitSpeepToSendAction");
+ }
+
+ synchronized void addAction(ActionExec action) {
+ if (lastAction != null)
+ toExecute.offer(lastAction);
+ lastAction = action;
+ }
+
+ void newCycle() {
+ List<ActionExec> feedback = getTS().getC().getFeedbackActions();
+
+ // set all actions as successfully executed
+ while (!toExecute.isEmpty()) {
+ ActionExec action = toExecute.poll();
+ action.setResult(true);
+ feedback.add(action);
+ }
+ }
+
+ synchronized void go() {
+ notifyAll();
+ }
+ synchronized void waitSleep() throws InterruptedException {
+ wait();
+ }
+
+ @Override
+ synchronized public void run() {
+ while (true) {
+ try {
+ lastAction = null;
+ waitSleep();
+ if (lastAction != null) {
+ proxy.sendAction(lastAction.getActionTerm().getTerm(0).toString());
+ toExecute.offer(lastAction);
+ }
+ } catch (InterruptedException e) {
+ return; // condition to stop the thread
+ } catch (Exception e) {
+ logger.log(Level.SEVERE, "Error sending "+lastAction+" to simulator.",e);
+ toExecute.clear();
+ }
+ }
+ }
+ }
+
}
Modified: trunk/applications/jason-team/src/java/arch/ACProxy.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/ACProxy.java 2008-03-18 21:40:34 UTC (rev 1164)
+++ trunk/applications/jason-team/src/java/arch/ACProxy.java 2008-03-18 22:36:40 UTC (rev 1165)
@@ -5,7 +5,6 @@
import jason.asSyntax.Structure;
import jason.environment.grid.Location;
-import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
@@ -160,6 +159,7 @@
percepts.add(lpos);
int maxx = 0; // max value of some cell'x
+ int enemyId = 1;
// add in perception what is around
NodeList nl = perception.getElementsByTagName("cell");
for (int i=0; i < nl.getLength(); i++) {
@@ -172,7 +172,6 @@
if (cellx > maxx)
maxx = cellx;
- int enemyId = 1;
NodeList cnl = cell.getChildNodes();
for (int j=0; j < cnl.getLength(); j++) {
if (cnl.item(j).getNodeType() == Element.ELEMENT_NODE && cellx != 0 && celly != 0) {
@@ -186,8 +185,8 @@
} else if (type.getAttribute("type").equals("enemy")) {
Structure le = new Literal("enemy");
le.addTerm(new NumberTermImpl( (enemyId++) )); // we need an id to work with UniqueBB
- arq.enemyPerceived(absx, absy);
percepts.add(CowboyArch.createCellPerception(cellx, celly, le));
+ arq.enemyPerceived(absx, absy);
}
} else if (type.getNodeName().equals("cow")) {
@@ -212,8 +211,8 @@
//if (logger.isLoggable(Level.FINE))
logger.info("Request action for "+lpos+" / "+rid + " percepts: "+percepts);
+ arq.perceptionRatioPerceived(maxx);
arq.startNextStep(step, percepts);
- arq.perceptionRatioPerceived(maxx);
} catch (Exception e) {
logger.log(Level.SEVERE, "error processing request",e);
@@ -257,7 +256,10 @@
int d = new Random().nextInt(10000);
try {
while (running) {
- sleep(20000+d);
+ if (isConnected())
+ sleep(20000+d);
+ else
+ sleep(2000);
count++;
ok = false;
sentTime = System.currentTimeMillis();
Modified: trunk/applications/jason-team/src/java/arch/CowboyArch.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/CowboyArch.java 2008-03-18 21:40:34 UTC (rev 1164)
+++ trunk/applications/jason-team/src/java/arch/CowboyArch.java 2008-03-18 22:36:40 UTC (rev 1165)
@@ -41,6 +41,8 @@
int cycle = 0;
+ WriteModelThread writeModelThread = null;
+
protected Logger logger = Logger.getLogger(CowboyArch.class.getName());
public static Atom aOBSTACLE = new Atom("obstacle");
@@ -54,7 +56,8 @@
super.initAg(agClass, bbPars, asSrc, stts);
gui = "yes".equals(stts.getUserParameter("gui"));
if ("yes".equals(stts.getUserParameter("write_model"))) {
- new WriteModelThread().start();
+ writeModelThread = new WriteModelThread();
+ writeModelThread.start();
}
// create the viewer for contest simulator
massimBackDir = stts.getUserParameter("ac_sim_back_dir");
@@ -66,6 +69,7 @@
public void stopAg() {
if (view != null) view.dispose();
if (acView != null) acView.finish();
+ if (writeModelThread != null) writeModelThread.interrupt();
super.stopAg();
}
@@ -192,8 +196,6 @@
getTS().getAg().getBB().abolish(new Atom("restart").getPredicateIndicator());
getTS().getAg().addBel(new Atom("restart"));
lo2 = new Location(-1,-1); // to not restart again in the next cycle
-
- //getTS().stopCycle();
} catch (Exception e) {
logger.info("Error in restart!"+ e);
}
@@ -218,11 +220,6 @@
model.add(WorldModel.COW, x, y);
}
- // not used, the allies send messages with their location
- //void allyPerceived(int x, int y) {
- // model.add(WorldModel.AGENT, x, y);
- //}
-
void enemyPerceived(int x, int y) {
model.add(WorldModel.ENEMY, x, y);
}
@@ -316,9 +313,10 @@
class WriteModelThread extends Thread {
public void run() {
String fileName = "world-state-"+getAgName()+".txt";
+ PrintWriter out = null;
try {
- PrintWriter out = new PrintWriter(fileName);
- while (isRunning()) {
+ out = new PrintWriter(fileName);
+ while (true) {
waitSomeTime();
if (model != null && playing) {
out.println("\n\n** Agent "+getAgName()+" in cycle "+cycle+"\n");
@@ -329,9 +327,11 @@
out.flush();
}
}
- out.close();
+ } catch (InterruptedException e) { // no problem, quit the thread
} catch (Exception e) {
e.printStackTrace();
+ } finally {
+ out.close();
}
}
Deleted: trunk/examples/gold-miners-II/JasonTeam.mas2j
===================================================================
--- trunk/examples/gold-miners-II/JasonTeam.mas2j 2008-03-18 21:40:34 UTC (rev 1164)
+++ trunk/examples/gold-miners-II/JasonTeam.mas2j 2008-03-18 22:36:40 UTC (rev 1165)
@@ -1,41 +0,0 @@
-/*
- * Jason Team for the
- * Multi-Agent Programming Contest 2007
- * (http://cig.in.tu-clausthal.de/AgentContest2007)
- *
- * Configuration for local simulator
- *
- * By Jomi & Rafael
- */
-
-MAS miners {
- infrastructure: Centralised
-
- environment: env.MiningEnvironment(11, 0, yes, "dummy", "miner", 1000)
- // parameters: 1. environment configuration id (from 1 to 13)
- // 11 is Fence in 2007 Contest
- // 12 is Semiramis in 2007 Contest
- // 13 is Overkill in 2007 Contest
- // 2. sleep time (in ms) after each action
- // 3. whether display the gui
- // 4. name of the agents of red team
- // 5. name of the agents of blue team
- // 6. window size
-
- agents:
- // red team
- dummy agentArchClass arch.LocalMinerArch #6;
-
- // blue team
- leader
- beliefBaseClass agent.DiscardBelsBB("my_status","picked","committed_to","cell");
-
- miner
- agentClass agent.SelectEvent
- beliefBaseClass agent.UniqueBelsBB("gsize(_,_,_)","depot(_,_,_)","steps(_,_)","committed_to(_,_,key)")
- agentArchClass arch.LocalMinerArch
- #6;
-
- aslSourcePath: "asl";
-}
-
Copied: trunk/examples/gold-miners-II/miners.mas2j (from rev 1161, trunk/examples/gold-miners-II/JasonTeam.mas2j)
===================================================================
--- trunk/examples/gold-miners-II/miners.mas2j (rev 0)
+++ trunk/examples/gold-miners-II/miners.mas2j 2008-03-18 22:36:40 UTC (rev 1165)
@@ -0,0 +1,41 @@
+/*
+ * Jason Team for the
+ * Multi-Agent Programming Contest 2007
+ * (http://cig.in.tu-clausthal.de/AgentContest2007)
+ *
+ * Configuration for local simulator
+ *
+ * By Jomi & Rafael
+ */
+
+MAS miners {
+ infrastructure: Centralised
+
+ environment: env.MiningEnvironment(11, 0, yes, "dummy", "miner", 1000)
+ // parameters: 1. environment configuration id (from 1 to 13)
+ // 11 is Fence in 2007 Contest
+ // 12 is Semiramis in 2007 Contest
+ // 13 is Overkill in 2007 Contest
+ // 2. sleep time (in ms) after each action
+ // 3. whether display the gui
+ // 4. name of the agents of red team
+ // 5. name of the agents of blue team
+ // 6. window size
+
+ agents:
+ // red team
+ dummy agentArchClass arch.LocalMinerArch #6;
+
+ // blue team
+ leader
+ beliefBaseClass agent.DiscardBelsBB("my_status","picked","committed_to","cell");
+
+ miner
+ agentClass agent.SelectEvent
+ beliefBaseClass agent.UniqueBelsBB("gsize(_,_,_)","depot(_,_,_)","steps(_,_)","committed_to(_,_,key)")
+ agentArchClass arch.LocalMinerArch
+ #6;
+
+ aslSourcePath: "asl";
+}
+
Modified: trunk/src/jason/asSyntax/Literal.java
===================================================================
--- trunk/src/jason/asSyntax/Literal.java 2008-03-18 21:40:34 UTC (rev 1164)
+++ trunk/src/jason/asSyntax/Literal.java 2008-03-18 22:36:40 UTC (rev 1165)
@@ -85,10 +85,7 @@
public static Literal parseLiteral(String sLiteral) {
as2j parser = new as2j(new StringReader(sLiteral));
try {
- Literal l = parser.literal();
- if (l instanceof Atom) // force the result as literal
- l = new Literal(l.getFunctor());
- return l;
+ return parser.literal();
} catch (Exception e) {
logger.log(Level.SEVERE,"Error parsing literal " + sLiteral,e);
return null;
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-20 18:15:48
|
Revision: 1168
http://jason.svn.sourceforge.net/jason/?rev=1168&view=rev
Author: jomifred
Date: 2008-03-20 11:15:42 -0700 (Thu, 20 Mar 2008)
Log Message:
-----------
BRF (belief revision function) may throws an exception
Modified Paths:
--------------
trunk/applications/jason-moise/src/jmoise/OrgAgent.java
trunk/examples/gold-miners-II/arch/MinerArch.java
trunk/examples/sniffer/comm/SnifferCentralised.java
trunk/src/jason/asSemantics/Agent.java
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/bb/TextPersistentBB.java
trunk/src/test/BeliefBaseTest.java
trunk/src/test/StdLibTest.java
Added Paths:
-----------
trunk/src/jason/RevisionFailedException.java
Modified: trunk/applications/jason-moise/src/jmoise/OrgAgent.java
===================================================================
--- trunk/applications/jason-moise/src/jmoise/OrgAgent.java 2008-03-20 08:56:41 UTC (rev 1167)
+++ trunk/applications/jason-moise/src/jmoise/OrgAgent.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -1,6 +1,7 @@
package jmoise;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSemantics.Agent;
import jason.asSemantics.Event;
@@ -129,15 +130,18 @@
logger.log(Level.SEVERE, "Error!", e);
}
} // while
-
- if (updateGoalBels)
- updateGoalBels();
- if (updateGoalEvt)
- generateOrgGoalEvents();
+ try {
+ if (updateGoalBels)
+ updateGoalBels();
+ if (updateGoalEvt)
+ generateOrgGoalEvents();
+ } catch (Exception e) {
+ logger.log(Level.SEVERE, "Error!", e);
+ }
}
- private Literal addAsBel(String b) {
+ private Literal addAsBel(String b) throws RevisionFailedException {
Literal l = Literal.parseLiteral(b);
if (l.isAtom())
l = new Literal(l.getFunctor());
@@ -146,7 +150,7 @@
return l;
}
- void generateObligationPermissionEvents(Pred m) {
+ void generateObligationPermissionEvents(Pred m) throws RevisionFailedException {
// computes this agent obligations in the scheme
String schId = m.getTerm(0).toString();
String grId = m.getTerm(1).toString();
@@ -217,7 +221,7 @@
private static final PredicateIndicator commitmentLiteral = new PredicateIndicator("commitment", 3);
/** removes all bels related to a Scheme */
- void removeBeliefs(String schId) {
+ void removeBeliefs(String schId) throws RevisionFailedException {
Agent ag = getTS().getAg();
ag.abolish(buildLiteralToCleanBB(schId, obligationLiteral, false), null);
ag.abolish(buildLiteralToCleanBB(schId, permissionLiteral, false), null);
@@ -246,7 +250,7 @@
}
/** add/remove bel regarding the goals' state */
- void updateGoalBels() {
+ void updateGoalBels() throws RevisionFailedException {
// for all missions
// for all goals
// if not in BB, add
@@ -258,7 +262,7 @@
}
}
- void updateGoalBels(Pred arg) {
+ void updateGoalBels(Pred arg) throws RevisionFailedException {
String schId = arg.getTerm(0).toString();
String goalId = arg.getTerm(1).toString();
for (SchemeInstance sch : getMyOEAgent().getAllMySchemes()) {
@@ -277,7 +281,7 @@
private static final Atom aImpossible = new Atom("impossible");
private static final Atom aAchieved = new Atom("achieved");
- void updateGoalBels(GoalInstance gi) {
+ void updateGoalBels(GoalInstance gi) throws RevisionFailedException {
Pred gap = Pred.parsePred(gi.getAsProlog());
if (gi.getScheme().getRoot() == gi) {
Modified: trunk/examples/gold-miners-II/arch/MinerArch.java
===================================================================
--- trunk/examples/gold-miners-II/arch/MinerArch.java 2008-03-20 08:56:41 UTC (rev 1167)
+++ trunk/examples/gold-miners-II/arch/MinerArch.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -1,6 +1,7 @@
package arch;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSemantics.Message;
import jason.asSyntax.Atom;
@@ -73,7 +74,7 @@
/** The perception of the grid size is removed from the percepts list
and "directly" added as a belief */
- void gsizePerceived(int w, int h) {
+ void gsizePerceived(int w, int h) throws RevisionFailedException {
if (view != null) {
view.dispose();
}
@@ -87,14 +88,14 @@
/** The perception of the depot location is removed from the percepts list
and "directly" added as a belief */
- void depotPerceived(int x, int y) {
+ void depotPerceived(int x, int y) throws RevisionFailedException {
model.setDepot(x, y);
getTS().getAg().addBel(Literal.parseLiteral("depot("+simId+","+x+","+y+")"));
}
/** The number of steps of the simulation is removed from the percepts list
- and "directly" added as a belief */
- void stepsPerceived(int s) {
+ and "directly" added as a belief */
+ void stepsPerceived(int s) throws RevisionFailedException {
getTS().getAg().addBel(Literal.parseLiteral("steps("+simId+","+s+")"));
model.setMaxSteps(s);
}
@@ -186,7 +187,7 @@
model.add(WorldModel.ENEMY, x, y);
}
- void simulationEndPerceived(String result) {
+ void simulationEndPerceived(String result) throws RevisionFailedException {
getTS().getAg().addBel(Literal.parseLiteral("end_of_simulation("+simId+","+result+")"));
playing = false;
}
Modified: trunk/examples/sniffer/comm/SnifferCentralised.java
===================================================================
--- trunk/examples/sniffer/comm/SnifferCentralised.java 2008-03-20 08:56:41 UTC (rev 1167)
+++ trunk/examples/sniffer/comm/SnifferCentralised.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -1,6 +1,7 @@
package comm;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSemantics.Message;
import jason.asSyntax.Atom;
@@ -61,6 +62,10 @@
e.addTerm(new Atom(m.getSender()));
e.addTerm(new Atom(m.getReceiver()));
e.addTerm(new StringTermImpl(m.getPropCont().toString()));
- getTS().getAg().addBel(e);
+ try {
+ getTS().getAg().addBel(e);
+ } catch (RevisionFailedException e1) {
+ e1.printStackTrace();
+ }
}
}
Added: trunk/src/jason/RevisionFailedException.java
===================================================================
--- trunk/src/jason/RevisionFailedException.java (rev 0)
+++ trunk/src/jason/RevisionFailedException.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -0,0 +1,47 @@
+//----------------------------------------------------------------------------
+// Copyright (C) 2003 Rafael H. Bordini, Jomi F. Hubner, et al.
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// To contact the authors:
+// http://www.dur.ac.uk/r.bordini
+// http://www.inf.furb.br/~jomi
+//
+// CVS information:
+// $Date: 2007-02-19 16:53:54 +0100 (Mon, 19 Feb 2007) $
+// $Revision: 751 $
+// $Log$
+// Revision 1.3 2005/08/12 22:26:08 jomifred
+// add cvs keywords
+//
+//
+//----------------------------------------------------------------------------
+
+package jason;
+
+public class RevisionFailedException extends JasonException {
+
+ public RevisionFailedException() {
+ }
+
+ public RevisionFailedException(String msg) {
+ super(msg);
+ }
+
+ public RevisionFailedException(String msg, Exception cause) {
+ super(msg);
+ initCause(cause);
+ }
+}
Modified: trunk/src/jason/asSemantics/Agent.java
===================================================================
--- trunk/src/jason/asSemantics/Agent.java 2008-03-20 08:56:41 UTC (rev 1167)
+++ trunk/src/jason/asSemantics/Agent.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -24,6 +24,7 @@
package jason.asSemantics;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSyntax.Atom;
import jason.asSyntax.Literal;
@@ -312,7 +313,7 @@
}
/** add the initial beliefs in BB and produce the corresponding events */
- public void addInitialBelsInBB() {
+ public void addInitialBelsInBB() throws RevisionFailedException {
// Once beliefs are stored in a Stack in the BB, insert them in inverse order
for (int i=initialBels.size()-1; i >=0; i--) {
Literal b = initialBels.get(i);
@@ -544,7 +545,7 @@
* nothing change, returns null.
*/
@SuppressWarnings("unchecked")
- public List<Literal>[] brf(Literal beliefToAdd, Literal beliefToDel, Intention i) {
+ public List<Literal>[] brf(Literal beliefToAdd, Literal beliefToDel, Intention i) throws RevisionFailedException {
// This class does not implement belief revision! It
// is supposed that a subclass will do it.
// It simply add/del the belief.
@@ -595,7 +596,7 @@
* events. If <i>bel</i> has no source, add
* <code>source(self)</code>. (the belief is not cloned!)
*/
- public boolean addBel(Literal bel) {
+ public boolean addBel(Literal bel) throws RevisionFailedException {
if (!bel.hasSource()) {
if (bel instanceof Atom)
bel = new Literal(bel.getFunctor());
@@ -614,7 +615,7 @@
* If the agent believes in <i>bel</i>, removes it (calling brf)
* and generate the event.
*/
- public boolean delBel(Literal bel) {
+ public boolean delBel(Literal bel) throws RevisionFailedException {
List<Literal>[] result = brf(null, bel, Intention.EmptyInt);
if (result != null && ts != null) {
ts.updateEvents(result, Intention.EmptyInt);
@@ -627,7 +628,7 @@
/** Removes all occurrences of <i>bel</i> in BB.
If <i>un</i> is null, an empty Unifier is used.
*/
- public void abolish(Literal bel, Unifier un) {
+ public void abolish(Literal bel, Unifier un) throws RevisionFailedException {
List<Literal> toDel = new ArrayList<Literal>();
Iterator<Literal> il = getBB().getRelevant(bel);
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-20 08:56:41 UTC (rev 1167)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -24,6 +24,7 @@
package jason.asSemantics;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSyntax.Atom;
import jason.asSyntax.BodyLiteral;
@@ -516,10 +517,15 @@
// to delete, create events as external to avoid that
// remove/add create two events for the same intention
- List<Literal>[] result = ag.brf(null, bc, conf.C.SI); // the intention is not the new focus
- if (result != null) { // really delete something
- // generate events
- updateEvents(result,Intention.EmptyInt);
+ try {
+ List<Literal>[] result = ag.brf(null, bc, conf.C.SI); // the intention is not the new focus
+ if (result != null) { // really delete something
+ // generate events
+ updateEvents(result,Intention.EmptyInt);
+ }
+ } catch (RevisionFailedException re) {
+ generateGoalDeletion();
+ break;
}
// add the belief, so no break;
@@ -543,15 +549,19 @@
body.makeVarsAnnon();
// call BRF
- result = ag.brf(body,null,conf.C.SI); // the intention is not the new focus
- if (result != null) { // really add something
- // generate events
- updateEvents(result,newfocus);
- if (!setts.sameFocus()) {
- updateIntention();
- }
- } else {
- updateIntention();
+ try {
+ List<Literal>[] result = ag.brf(body,null,conf.C.SI); // the intention is not the new focus
+ if (result != null) { // really add something
+ // generate events
+ updateEvents(result,newfocus);
+ if (!setts.sameFocus()) {
+ updateIntention();
+ }
+ } else {
+ updateIntention();
+ }
+ } catch (RevisionFailedException re) {
+ generateGoalDeletion();
}
break;
@@ -569,16 +579,20 @@
newfocus = conf.C.SI;
// call BRF
- result = ag.brf(null,body, conf.C.SI); // the intention is not the new focus
- if (result != null) { // really change something
- // generate events
- updateEvents(result,newfocus);
- if (!setts.sameFocus()) {
- updateIntention();
- }
- } else {
- updateIntention();
- }
+ try {
+ List<Literal>[] result = ag.brf(null,body, conf.C.SI); // the intention is not the new focus
+ if (result != null) { // really change something
+ // generate events
+ updateEvents(result,newfocus);
+ if (!setts.sameFocus()) {
+ updateIntention();
+ }
+ } else {
+ updateIntention();
+ }
+ } catch (RevisionFailedException re) {
+ generateGoalDeletion();
+ }
break;
}
}
@@ -790,7 +804,7 @@
}
}
-
+ /** generate a failure event for the current intention */
private void generateGoalDeletion() throws JasonException {
IntendedMeans im = conf.C.SI.peek();
if (im.isGoalAdd()) {
Modified: trunk/src/jason/bb/TextPersistentBB.java
===================================================================
--- trunk/src/jason/bb/TextPersistentBB.java 2008-03-20 08:56:41 UTC (rev 1167)
+++ trunk/src/jason/bb/TextPersistentBB.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -1,5 +1,6 @@
package jason.bb;
+import jason.RevisionFailedException;
import jason.asSemantics.Agent;
import jason.asSyntax.Literal;
@@ -21,11 +22,15 @@
File file = null;
public void init(Agent ag, String[] args) {
- file = new File(ag.getTS().getUserAgArch().getAgName() + ".bb");
- logger.fine("reading from file " + file);
- if (file.exists()) {
- ag.parseAS(file.getAbsolutePath());
- ag.addInitialBelsInBB();
+ try {
+ file = new File(ag.getTS().getUserAgArch().getAgName() + ".bb");
+ logger.fine("reading from file " + file);
+ if (file.exists()) {
+ ag.parseAS(file.getAbsolutePath());
+ ag.addInitialBelsInBB();
+ }
+ } catch (RevisionFailedException e) {
+ logger.log(Level.SEVERE,"Error in init.",e);
}
}
Modified: trunk/src/test/BeliefBaseTest.java
===================================================================
--- trunk/src/test/BeliefBaseTest.java 2008-03-20 08:56:41 UTC (rev 1167)
+++ trunk/src/test/BeliefBaseTest.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -1,5 +1,6 @@
package test;
+import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSemantics.Agent;
import jason.asSemantics.Intention;
@@ -519,7 +520,7 @@
@SuppressWarnings("unchecked")
- public void testBelBRF() {
+ public void testBelBRF() throws RevisionFailedException {
Agent ag = new Agent();
AgArch arch = new AgArch();
arch.setArchInfraTier(new CentralisedAgArch());
Modified: trunk/src/test/StdLibTest.java
===================================================================
--- trunk/src/test/StdLibTest.java 2008-03-20 08:56:41 UTC (rev 1167)
+++ trunk/src/test/StdLibTest.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -1,5 +1,6 @@
package test;
+import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSemantics.Agent;
import jason.asSemantics.Circumstance;
@@ -95,7 +96,7 @@
"[ok(10)[source(rafa)],[ok(20)[source(rafa)],ok(30)[source(rafa)],[ok(40)[source(rafa)],ok(50)[source(rafa)],ok(60)[source(rafa)]]]]");
}
- public void testFindAll() {
+ public void testFindAll() throws RevisionFailedException {
Agent ag = new Agent();
ag.setLogger(null);
AgArch arch = new AgArch();
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-21 15:35:45
|
Revision: 1170
http://jason.svn.sourceforge.net/jason/?rev=1170&view=rev
Author: jomifred
Date: 2008-03-21 08:35:38 -0700 (Fri, 21 Mar 2008)
Log Message:
-----------
use Atom class only as term
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java
trunk/applications/jason-moise/src/jmoise/OrgAgent.java
trunk/applications/jason-team/src/java/arch/ACArchitecture.java
trunk/applications/jason-team/src/java/arch/CowboyArch.java
trunk/demos/function/a.asl
trunk/examples/gold-miners-II/arch/MinerArch.java
trunk/src/jason/asSemantics/Agent.java
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/asSyntax/ArithFunctionTerm.java
trunk/src/jason/asSyntax/InternalActionLiteral.java
trunk/src/jason/asSyntax/SourceInfo.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/jason/environment/Environment.java
trunk/src/jason/functions/RuleToFunction.java
trunk/src/test/TermTest.java
Modified: trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -2,11 +2,11 @@
import static org.junit.Assert.fail;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.asSemantics.Agent;
import jason.asSemantics.Event;
import jason.asSemantics.Intention;
import jason.asSemantics.Unifier;
-import jason.asSyntax.Atom;
import jason.asSyntax.Literal;
import jason.asSyntax.LogExpr;
import jason.asSyntax.LogicalFormula;
@@ -76,19 +76,21 @@
super.addBel(Literal.tryParsingLiteral(bel));
} catch (ParseException e) {
fail("Parsing '"+bel+"' as a belief!");
+ } catch (RevisionFailedException e) {
+ fail("BRF error for adding '"+bel+"!");
}
}
public void delBel(String bel) {
try {
Literal l = Literal.tryParsingLiteral(bel);
if (!l.hasSource()) {
- if (l instanceof Atom)
- l = new Literal(l.getFunctor());
l.addAnnot(BeliefBase.TSelf);
}
super.delBel(l);
} catch (ParseException e) {
fail("Parsing '"+bel+"' as a belief!");
+ } catch (RevisionFailedException e) {
+ fail("BRF error for deleting '"+bel+"!");
}
}
Modified: trunk/applications/jason-moise/src/jmoise/OrgAgent.java
===================================================================
--- trunk/applications/jason-moise/src/jmoise/OrgAgent.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/applications/jason-moise/src/jmoise/OrgAgent.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -143,8 +143,6 @@
private Literal addAsBel(String b) throws RevisionFailedException {
Literal l = Literal.parseLiteral(b);
- if (l.isAtom())
- l = new Literal(l.getFunctor());
l.addAnnot(managerSource);
getTS().getAg().addBel(l);
return l;
@@ -189,8 +187,6 @@
alreadyGeneratedEvents.add(gi);
Literal l = Literal.parseLiteral(gi.getAsProlog());
- if (l.isAtom())
- l = new Literal(l.getFunctor());
Literal giID = new Literal("scheme");
giID.addTerm(new Atom(gi.getScheme().getId()));
l.addAnnot(giID);
Modified: trunk/applications/jason-team/src/java/arch/ACArchitecture.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -1,9 +1,9 @@
package arch;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.asSemantics.ActionExec;
import jason.asSyntax.Literal;
-import jason.functions.log;
import jason.mas2j.ClassParameters;
import jason.runtime.Settings;
@@ -90,7 +90,7 @@
}
@Override
- void simulationEndPerceived(String result) {
+ void simulationEndPerceived(String result) throws RevisionFailedException {
percepts = new ArrayList<Literal>();
super.simulationEndPerceived(result);
}
Modified: trunk/applications/jason-team/src/java/arch/CowboyArch.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/CowboyArch.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/applications/jason-team/src/java/arch/CowboyArch.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -1,6 +1,7 @@
package arch;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.asSemantics.Message;
import jason.asSyntax.Atom;
import jason.asSyntax.Literal;
@@ -103,7 +104,7 @@
/** The perception of the grid size is removed from the percepts list
and "directly" added as a belief */
- void gsizePerceived(int w, int h, String opponent) {
+ void gsizePerceived(int w, int h, String opponent) throws RevisionFailedException {
model = new LocalWorldModel(w, h);
getTS().getAg().addBel(Literal.parseLiteral("gsize("+w+","+h+")"));
playing = true;
@@ -125,7 +126,7 @@
/** The perception of the corral location is removed from the percepts list
and "directly" added as a belief */
- void corralPerceived(Location upperLeft, Location downRight) {
+ void corralPerceived(Location upperLeft, Location downRight) throws RevisionFailedException {
model.setCorral(upperLeft, downRight);
if (acView != null) acView.getModel().setCorral(upperLeft, downRight);
getTS().getAg().addBel(Literal.parseLiteral("corral("+upperLeft.x+","+upperLeft.y+","+downRight.x+","+downRight.y+")"));
@@ -133,13 +134,13 @@
/** The number of steps of the simulation is removed from the percepts list
and "directly" added as a belief */
- void stepsPerceived(int s) {
+ void stepsPerceived(int s) throws RevisionFailedException {
getTS().getAg().addBel(Literal.parseLiteral("steps("+s+")"));
model.setMaxSteps(s);
}
/** The perception ratio is discovered */
- void perceptionRatioPerceived(int s) {
+ void perceptionRatioPerceived(int s) throws RevisionFailedException {
if (s != model.getPerceptionRatio()) {
model.setPerceptionRatio(s);
getTS().getAg().addBel(Literal.parseLiteral("pratio("+s+")"));
@@ -199,8 +200,8 @@
logger.info("** Arch adding restart for "+getAgName());
getTS().getC().create();
- getTS().getAg().getBB().abolish(new Atom("restart").getPredicateIndicator());
- getTS().getAg().addBel(new Atom("restart"));
+ getTS().getAg().getBB().abolish(new Literal("restart").getPredicateIndicator());
+ getTS().getAg().addBel(new Literal("restart"));
lo2 = new Location(-1,-1); // to not restart again in the next cycle
} catch (Exception e) {
logger.info("Error in restart!"+ e);
@@ -230,7 +231,7 @@
model.add(WorldModel.ENEMY, x, y);
}
- void simulationEndPerceived(String result) {
+ void simulationEndPerceived(String result) throws RevisionFailedException {
getTS().getAg().addBel(Literal.parseLiteral("end_of_simulation("+result+")"));
playing = false;
}
Modified: trunk/demos/function/a.asl
===================================================================
--- trunk/demos/function/a.asl 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/demos/function/a.asl 2008-03-21 15:35:38 UTC (rev 1170)
@@ -32,7 +32,7 @@
/* Initial goals */
-!show_predef_funtion.
+//!show_predef_funtion.
!show_userdef_funtion.
/* Plans */
Modified: trunk/examples/gold-miners-II/arch/MinerArch.java
===================================================================
--- trunk/examples/gold-miners-II/arch/MinerArch.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/examples/gold-miners-II/arch/MinerArch.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -152,9 +152,9 @@
//logger.info("** Arch adding restart for "+getAgName()+", TS="+getTS().getCurrentTask()+", "+getTS().getC());
getTS().getC().create();
- getTS().getAg().getBB().abolish(new Atom("restart").getPredicateIndicator());
+ getTS().getAg().getBB().abolish(new Literal("restart").getPredicateIndicator());
getTS().getAg().getBB().abolish(new PredicateIndicator("gold",2)); // tira os ouros
- getTS().getAg().addBel(new Atom("restart"));
+ getTS().getAg().addBel(new Literal("restart"));
lo2 = new Location(-1,-1); // to not restart again in the next cycle
//getTS().stopCycle();
Modified: trunk/src/jason/asSemantics/Agent.java
===================================================================
--- trunk/src/jason/asSemantics/Agent.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/asSemantics/Agent.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -26,7 +26,6 @@
import jason.JasonException;
import jason.RevisionFailedException;
import jason.architecture.AgArch;
-import jason.asSyntax.Atom;
import jason.asSyntax.Literal;
import jason.asSyntax.LogicalFormula;
import jason.asSyntax.Plan;
@@ -598,8 +597,6 @@
*/
public boolean addBel(Literal bel) throws RevisionFailedException {
if (!bel.hasSource()) {
- if (bel instanceof Atom)
- bel = new Literal(bel.getFunctor());
bel.addAnnot(BeliefBase.TSelf);
}
List<Literal>[] result = brf(bel, null, Intention.EmptyInt);
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -508,8 +508,6 @@
if (!body.hasAnnot()) {
// do not add source(self) in case the
// programmer set some annotation
- if (body instanceof Atom)
- body = new Literal(body.getFunctor());
body.addAnnot(BeliefBase.TSelf);
}
Literal bc = (Literal)body.clone();
@@ -535,8 +533,6 @@
if (!body.hasSource()) {
// do not add source(self) in case the
// programmer set the source
- if (body instanceof Atom)
- body = new Literal(body.getFunctor());
body.addAnnot(BeliefBase.TSelf);
}
@@ -569,8 +565,6 @@
if (!body.hasAnnot()) {
// do not add source(self) in case the
// programmer set some annotation
- if (body instanceof Atom)
- body = new Literal(body.getFunctor());
body.addAnnot(BeliefBase.TSelf);
}
Modified: trunk/src/jason/asSyntax/ArithFunctionTerm.java
===================================================================
--- trunk/src/jason/asSyntax/ArithFunctionTerm.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/asSyntax/ArithFunctionTerm.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -35,7 +35,7 @@
public ArithFunctionTerm(ArithFunction function) {
super(function.getName(), 2);
- this.function = function;
+ this.function = function;
}
public ArithFunctionTerm(ArithFunctionTerm af) {
@@ -55,6 +55,11 @@
}
@Override
+ public boolean isAtom() {
+ return false;
+ }
+
+ @Override
public boolean isStructure() {
return false;
}
Modified: trunk/src/jason/asSyntax/InternalActionLiteral.java
===================================================================
--- trunk/src/jason/asSyntax/InternalActionLiteral.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/asSyntax/InternalActionLiteral.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -68,6 +68,11 @@
}
@Override
+ public boolean isAtom() {
+ return false;
+ }
+
+ @Override
public boolean canBeAddedInBB() {
return false;
}
Modified: trunk/src/jason/asSyntax/SourceInfo.java
===================================================================
--- trunk/src/jason/asSyntax/SourceInfo.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/asSyntax/SourceInfo.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -21,6 +21,10 @@
beginSrcLine = o.beginSrcLine;
endSrcLine = o.endSrcLine;
}
+ public void setSrc(Object o) {
+ if (o instanceof SourceInfo)
+ setSrc((SourceInfo)o);
+ }
public void setSrc(String asSource) {
source = asSource;
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-21 15:35:38 UTC (rev 1170)
@@ -310,10 +310,7 @@
( F=literal()
| F=var()
- ) { if (F instanceof Atom)
- F = new Literal(F.getFunctor()); // trigger literal must be a literal and not an atom
- return new Trigger(teOp,teType,F);
- }
+ ) { return new Trigger(teOp,teType,F); }
}
/* Literal */
@@ -329,11 +326,6 @@
throw new ParseException(getSourceRef(F)+" The internal action class for '"+F+"' was not found!");
}
}
- if (F.isAtom() && type == Literal.LPos) {
- Atom a = new Atom(F.getFunctor());
- a.setSrc(F);
- return a;
- }
return new Literal(type,F);
}
)
@@ -436,10 +428,17 @@
}
-Term term() : { Term u; Object o; }
+Term term() : { Term u; Object o; Atom a; }
{
( u=list()
- | o=arithm_expr() { return (Term)o; } // arithm expr includes literals
+ | o=arithm_expr() { u = (Term)o; // arithm expr includes literals/atoms/structures
+ if (u.isAtom()) {
+ a = new Atom( ((Structure)u).getFunctor());
+ a.setSrc(u);
+ return a;
+ }
+ return u;
+ }
| u=string()
)
{ return u; }
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -406,8 +406,6 @@
jj_consume_token(-1);
throw new ParseException();
}
- if (F instanceof Atom)
- F = new Literal(F.getFunctor()); // trigger literal must be a literal and not an atom
{if (true) return new Trigger(teOp,teType,F);}
throw new Error("Missing return statement in function");
}
@@ -438,11 +436,6 @@
{if (true) throw new ParseException(getSourceRef(F)+" The internal action class for '"+F+"' was not found!");}
}
}
- if (F.isAtom() && type == Literal.LPos) {
- Atom a = new Atom(F.getFunctor());
- a.setSrc(F);
- {if (true) return a;}
- }
{if (true) return new Literal(type,F);}
break;
case TK_TRUE:
@@ -655,7 +648,7 @@
}
final public Term term() throws ParseException {
- Term u; Object o;
+ Term u; Object o; Atom a;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 42:
u = list();
@@ -672,7 +665,13 @@
case 35:
case 39:
o = arithm_expr();
- {if (true) return (Term)o;}
+ u = (Term)o; // arithm expr includes literals/atoms/structures
+ if (u.isAtom()) {
+ a = new Atom( ((Structure)u).getFunctor());
+ a.setSrc(u);
+ {if (true) return a;}
+ }
+ {if (true) return u;}
break;
case STRING:
u = string();
@@ -1173,21 +1172,15 @@
return false;
}
- final private boolean jj_3R_16() {
- if (jj_scan_token(35)) return true;
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_22()) jj_scanpos = xsp;
- return false;
- }
-
final private boolean jj_3R_70() {
if (jj_scan_token(TK_INTDIV)) return true;
return false;
}
- final private boolean jj_3R_15() {
- if (jj_scan_token(34)) return true;
+ final private boolean jj_3R_19() {
+ if (jj_scan_token(39)) return true;
+ if (jj_3R_25()) return true;
+ if (jj_scan_token(40)) return true;
return false;
}
@@ -1196,8 +1189,8 @@
return false;
}
- final private boolean jj_3R_14() {
- if (jj_scan_token(36)) return true;
+ final private boolean jj_3R_18() {
+ if (jj_3R_24()) return true;
return false;
}
@@ -1206,13 +1199,13 @@
return false;
}
- final private boolean jj_3R_13() {
- if (jj_scan_token(38)) return true;
+ final private boolean jj_3R_17() {
+ if (jj_3R_23()) return true;
return false;
}
- final private boolean jj_3R_12() {
- if (jj_scan_token(31)) return true;
+ final private boolean jj_3R_22() {
+ if (jj_scan_token(34)) return true;
return false;
}
@@ -1240,6 +1233,34 @@
return false;
}
+ final private boolean jj_3R_16() {
+ if (jj_scan_token(35)) return true;
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_22()) jj_scanpos = xsp;
+ return false;
+ }
+
+ final private boolean jj_3R_15() {
+ if (jj_scan_token(34)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_14() {
+ if (jj_scan_token(36)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_13() {
+ if (jj_scan_token(38)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_12() {
+ if (jj_scan_token(31)) return true;
+ return false;
+ }
+
final private boolean jj_3_2() {
Token xsp;
xsp = jj_scanpos;
@@ -1295,23 +1316,23 @@
return false;
}
- final private boolean jj_3R_29() {
- if (jj_scan_token(TK_FALSE)) return true;
+ final private boolean jj_3R_59() {
+ if (jj_scan_token(53)) return true;
return false;
}
- final private boolean jj_3R_28() {
- if (jj_scan_token(TK_TRUE)) return true;
+ final private boolean jj_3R_29() {
+ if (jj_scan_token(TK_FALSE)) return true;
return false;
}
- final private boolean jj_3R_59() {
- if (jj_scan_token(53)) return true;
+ final private boolean jj_3R_58() {
+ if (jj_scan_token(52)) return true;
return false;
}
- final private boolean jj_3R_58() {
- if (jj_scan_token(52)) return true;
+ final private boolean jj_3R_28() {
+ if (jj_scan_token(TK_TRUE)) return true;
return false;
}
@@ -1345,11 +1366,6 @@
return false;
}
- final private boolean jj_3R_35() {
- if (jj_scan_token(TK_NEG)) return true;
- return false;
- }
-
final private boolean jj_3R_49() {
Token xsp;
xsp = jj_scanpos;
@@ -1378,11 +1394,21 @@
return false;
}
+ final private boolean jj_3R_35() {
+ if (jj_scan_token(TK_NEG)) return true;
+ return false;
+ }
+
final private boolean jj_3R_48() {
if (jj_3R_51()) return true;
return false;
}
+ final private boolean jj_3R_47() {
+ if (jj_3R_50()) return true;
+ return false;
+ }
+
final private boolean jj_3R_27() {
Token xsp;
xsp = jj_scanpos;
@@ -1391,11 +1417,6 @@
return false;
}
- final private boolean jj_3R_47() {
- if (jj_3R_50()) return true;
- return false;
- }
-
final private boolean jj_3R_23() {
Token xsp;
xsp = jj_scanpos;
@@ -1497,26 +1518,38 @@
return false;
}
- final private boolean jj_3R_45() {
- if (jj_3R_50()) return true;
+ final private boolean jj_3R_31() {
+ if (jj_scan_token(UNNAMEDVAR)) return true;
return false;
}
- final private boolean jj_3R_31() {
- if (jj_scan_token(UNNAMEDVAR)) return true;
+ final private boolean jj_3R_30() {
+ if (jj_scan_token(VAR)) return true;
return false;
}
- final private boolean jj_3R_44() {
- if (jj_3R_26()) return true;
+ final private boolean jj_3R_24() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_30()) {
+ jj_scanpos = xsp;
+ if (jj_3R_31()) return true;
+ }
+ xsp = jj_scanpos;
+ if (jj_3R_32()) jj_scanpos = xsp;
return false;
}
- final private boolean jj_3R_30() {
- if (jj_scan_token(VAR)) return true;
+ final private boolean jj_3R_45() {
+ if (jj_3R_50()) return true;
return false;
}
+ final private boolean jj_3R_44() {
+ if (jj_3R_26()) return true;
+ return false;
+ }
+
final private boolean jj_3R_42() {
Token xsp;
xsp = jj_scanpos;
@@ -1530,15 +1563,8 @@
return false;
}
- final private boolean jj_3R_24() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_30()) {
- jj_scanpos = xsp;
- if (jj_3R_31()) return true;
- }
- xsp = jj_scanpos;
- if (jj_3R_32()) jj_scanpos = xsp;
+ final private boolean jj_3R_77() {
+ if (jj_3R_23()) return true;
return false;
}
@@ -1552,17 +1578,6 @@
return false;
}
- final private boolean jj_3R_77() {
- if (jj_3R_23()) return true;
- return false;
- }
-
- final private boolean jj_3R_20() {
- if (jj_scan_token(39)) return true;
- if (jj_3R_41()) return true;
- return false;
- }
-
final private boolean jj_3R_76() {
if (jj_3R_77()) return true;
return false;
@@ -1579,6 +1594,12 @@
return false;
}
+ final private boolean jj_3R_20() {
+ if (jj_scan_token(39)) return true;
+ if (jj_3R_41()) return true;
+ return false;
+ }
+
final private boolean jj_3_1() {
if (jj_scan_token(27)) return true;
if (jj_scan_token(TK_BEGIN)) return true;
@@ -1598,23 +1619,6 @@
return false;
}
- final private boolean jj_3R_11() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_scan_token(20)) {
- jj_scanpos = xsp;
- if (jj_scan_token(14)) {
- jj_scanpos = xsp;
- if (jj_scan_token(15)) return true;
- }
- }
- xsp = jj_scanpos;
- if (jj_3R_20()) jj_scanpos = xsp;
- xsp = jj_scanpos;
- if (jj_3R_21()) jj_scanpos = xsp;
- return false;
- }
-
final private boolean jj_3R_66() {
Token xsp;
xsp = jj_scanpos;
@@ -1634,6 +1638,23 @@
return false;
}
+ final private boolean jj_3R_11() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_scan_token(20)) {
+ jj_scanpos = xsp;
+ if (jj_scan_token(14)) {
+ jj_scanpos = xsp;
+ if (jj_scan_token(15)) return true;
+ }
+ }
+ xsp = jj_scanpos;
+ if (jj_3R_20()) jj_scanpos = xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_21()) jj_scanpos = xsp;
+ return false;
+ }
+
final private boolean jj_3R_67() {
if (jj_scan_token(56)) return true;
return false;
@@ -1647,28 +1668,6 @@
return false;
}
- final private boolean jj_3R_19() {
- if (jj_scan_token(39)) return true;
- if (jj_3R_25()) return true;
- if (jj_scan_token(40)) return true;
- return false;
- }
-
- final private boolean jj_3R_18() {
- if (jj_3R_24()) return true;
- return false;
- }
-
- final private boolean jj_3R_17() {
- if (jj_3R_23()) return true;
- return false;
- }
-
- final private boolean jj_3R_22() {
- if (jj_scan_token(34)) return true;
- return false;
- }
-
public as2jTokenManager token_source;
SimpleCharStream jj_input_stream;
public Token token, jj_nt;
Modified: trunk/src/jason/environment/Environment.java
===================================================================
--- trunk/src/jason/environment/Environment.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/environment/Environment.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -25,7 +25,6 @@
package jason.environment;
import jason.asSemantics.Unifier;
-import jason.asSyntax.Atom;
import jason.asSyntax.Literal;
import jason.asSyntax.Structure;
@@ -172,7 +171,6 @@
public void addPercept(Literal per) {
if (per != null) {
if (! percepts.contains(per)) {
- if (per instanceof Atom) per = new Literal(per.getFunctor());
percepts.add(per);
uptodateAgs.clear();
}
@@ -240,7 +238,6 @@
}
if (! agl.contains(per)) {
uptodateAgs.remove(agName);
- if (per instanceof Atom) per = new Literal(per.getFunctor());
agl.add(per);
}
}
Modified: trunk/src/jason/functions/RuleToFunction.java
===================================================================
--- trunk/src/jason/functions/RuleToFunction.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/functions/RuleToFunction.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -39,6 +39,11 @@
}
@Override
+ public String getName() {
+ return super.getName()+"_{"+literal+"}";
+ }
+
+ @Override
public boolean checkArity(int a) {
return a == arity;
}
Modified: trunk/src/test/TermTest.java
===================================================================
--- trunk/src/test/TermTest.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/test/TermTest.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -725,4 +725,17 @@
assertEquals(0, p.getSingletonVars().size());
}
+
+ public void testAtomParsing() {
+ Literal l = Literal.parseLiteral("b");
+ assertFalse(l instanceof Atom);
+
+ l = Literal.parseLiteral("b(10,a,c(10,x))[ant1,source(c)]");
+ assertTrue(l.getTerm(1) instanceof Atom);
+ assertFalse(l.getTerm(2) instanceof Atom);
+ assertTrue(l.getAnnots().get(0) instanceof Atom);
+
+ l = Literal.parseLiteral("b(a.r)"); // internal actions should not be atoms
+ assertFalse(l.getTerm(0) instanceof Atom);
+ }
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-22 12:30:55
|
Revision: 1171
http://jason.svn.sourceforge.net/jason/?rev=1171&view=rev
Author: jomifred
Date: 2008-03-22 05:30:49 -0700 (Sat, 22 Mar 2008)
Log Message:
-----------
improvement in monitoring of agents' activities
Modified Paths:
--------------
trunk/applications/jason-team/AC-Local-JasonTeam.mas2j
trunk/applications/jason-team/readme.txt
trunk/applications/jason-team/src/asl/dummy.asl
trunk/applications/jason-team/src/java/arch/ACArchitecture.java
trunk/applications/jason-team/src/java/arch/CowboyArch.java
trunk/applications/jason-team/src/java/jia/Search.java
trunk/build.xml
trunk/src/jason/JasonException.java
trunk/src/jason/RevisionFailedException.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
Added Paths:
-----------
trunk/applications/jason-team/src/java/arch/WriteStatusThread.java
Modified: trunk/applications/jason-team/AC-Local-JasonTeam.mas2j
===================================================================
--- trunk/applications/jason-team/AC-Local-JasonTeam.mas2j 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/applications/jason-team/AC-Local-JasonTeam.mas2j 2008-03-22 12:30:49 UTC (rev 1171)
@@ -11,7 +11,7 @@
agents:
dummy1 dummy.asl
- [verbose=1, gui=no, write_model=yes, ac_sim_back_dir="./massim-server/backup",
+ [verbose=1, gui=yes, write_status=yes, ac_sim_back_dir="./massim-server/backup",
host="localhost", port=12300, username=participant1, password="1"]
agentArchClass arch.ACArchitecture
agentClass agent.SelectEvent
Modified: trunk/applications/jason-team/readme.txt
===================================================================
--- trunk/applications/jason-team/readme.txt 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/applications/jason-team/readme.txt 2008-03-22 12:30:49 UTC (rev 1171)
@@ -38,7 +38,7 @@
6. you can get the agents location with the command
- tail -f world-state-dummy1.txt
+ tail -f world-status.txt
7. the get the graphical view of some agent, add gui=yes in
the agent's option (.mas2j file)
Modified: trunk/applications/jason-team/src/asl/dummy.asl
===================================================================
--- trunk/applications/jason-team/src/asl/dummy.asl 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/applications/jason-team/src/asl/dummy.asl 2008-03-22 12:30:49 UTC (rev 1171)
@@ -84,6 +84,6 @@
+steps(MaxSteps) <- .println("steps = ",MaxSteps).
+corral(X1,Y1,X2,Y2) <- .println("corral = ",X1,",",Y1," -- ",X2,",",Y2).
-+cell(X,Y,Type) <- .println("cell = ",X,",",Y," = ",Type).
+//+cell(X,Y,Type) <- .println("cell = ",X,",",Y," = ",Type).
+pratio(R) <- .println("pratio = ",R).
+pos(X,Y,S) <- .println("pos = ",X,",",Y,"/",S).
Modified: trunk/applications/jason-team/src/java/arch/ACArchitecture.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-22 12:30:49 UTC (rev 1171)
@@ -127,9 +127,9 @@
class WaitSleep extends Thread {
ActionExec lastAction;
+ String lastActionInCurrentCycle;
Queue<ActionExec> toExecute = new ConcurrentLinkedQueue<ActionExec>();
- String x;
WaitSleep() {
super("WaitSpeepToSendAction");
@@ -151,8 +151,9 @@
feedback.add(action);
}
- logger.info("last action sent is "+x);
- x = null;
+ logger.info("last action sent is "+lastActionInCurrentCycle);
+ setLastAct(lastActionInCurrentCycle);
+ lastActionInCurrentCycle = null;
}
synchronized void go() {
@@ -169,8 +170,8 @@
lastAction = null;
waitSleep();
if (lastAction != null) {
- x = lastAction.getActionTerm().getTerm(0).toString();
- proxy.sendAction(x);
+ lastActionInCurrentCycle = lastAction.getActionTerm().getTerm(0).toString();
+ proxy.sendAction(lastActionInCurrentCycle);
toExecute.offer(lastAction);
}
} catch (InterruptedException e) {
Modified: trunk/applications/jason-team/src/java/arch/CowboyArch.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/CowboyArch.java 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/applications/jason-team/src/java/arch/CowboyArch.java 2008-03-22 12:30:49 UTC (rev 1171)
@@ -13,12 +13,7 @@
import jason.mas2j.ClassParameters;
import jason.runtime.Settings;
-import java.io.PrintWriter;
-import java.util.HashMap;
import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -46,7 +41,7 @@
int cycle = 0;
- WriteModelThread writeModelThread = null;
+ WriteStatusThread writeStatusThread = null;
protected Logger logger = Logger.getLogger(CowboyArch.class.getName());
@@ -60,10 +55,11 @@
public void initAg(String agClass, ClassParameters bbPars, String asSrc, Settings stts) throws JasonException {
super.initAg(agClass, bbPars, asSrc, stts);
gui = "yes".equals(stts.getUserParameter("gui"));
- if ("yes".equals(stts.getUserParameter("write_model"))) {
- writeModelThread = new WriteModelThread();
- writeModelThread.start();
+ if ("yes".equals(stts.getUserParameter("write_status"))) {
+ writeStatusThread = WriteStatusThread.create(this);
}
+ WriteStatusThread.registerAgent(getAgName(), this);
+
// create the viewer for contest simulator
massimBackDir = stts.getUserParameter("ac_sim_back_dir");
if (massimBackDir != null && massimBackDir.startsWith("\""))
@@ -74,7 +70,7 @@
public void stopAg() {
if (view != null) view.dispose();
if (acView != null) acView.finish();
- if (writeModelThread != null) writeModelThread.interrupt();
+ if (writeStatusThread != null) writeStatusThread.interrupt();
super.stopAg();
}
@@ -120,8 +116,8 @@
acView.setPriority(Thread.MIN_PRIORITY);
acView.start();
}
- if (writeModelThread != null)
- writeModelThread.reset();
+ if (writeStatusThread != null)
+ writeStatusThread.reset();
}
/** The perception of the corral location is removed from the percepts list
@@ -168,10 +164,29 @@
lo5 = new Location(-1,-1),
lo6 = new Location(-1,-1);
+
+ Location oldLoc;
+ /** the location in previous cycle */
+ public Location getLastLocation() {
+ return oldLoc;
+ }
+ protected String lastAct;
+ protected void setLastAct(String act) {
+ lastAct = act;
+ }
+ public String getLastAction() {
+ return lastAct;
+ }
+
+ public int getCycle() {
+ return cycle;
+ }
+
+
/** update the model with the agent location and share this information with team mates */
void locationPerceived(int x, int y) {
- Location oldLoc = model.getAgPos(getMyId());
+ oldLoc = model.getAgPos(getMyId());
if (oldLoc != null) {
model.clearAgView(oldLoc); // clear golds and enemies
}
@@ -239,7 +254,7 @@
void setCycle(int s) {
cycle = s;
if (view != null) view.setCycle(cycle);
- if (writeModelThread != null) writeModelThread.go();
+ if (writeStatusThread != null) writeStatusThread.go();
}
void setScore(int s) {
@@ -315,75 +330,4 @@
return (Integer.parseInt(agName.substring(agName.length()-1))) - 1;
}
-
-
- class WriteModelThread extends Thread {
-
- Map<Integer,List<Location>> locations;
-
- public void reset() {
- // init locations
- locations = new HashMap<Integer, List<Location>>();
- for (int i=0; i<WorldModel.agsByTeam; i++) {
- locations.put(i, new LinkedList<Location>());
- }
- }
-
- public void run() {
- reset();
-
- String fileName = "world-state-"+getAgName()+".txt";
- PrintWriter out = null;
- try {
- out = new PrintWriter(fileName);
- while (true) {
- try {
- waitSomeTime();
- if (model != null && playing) {
- //out.println("\n\n** Agent "+getAgName()+" in cycle "+cycle+"\n");
- //for (int i=0; i<model.getNbOfAgs(); i++) {
- // out.println("miner"+(i+1)+" is carrying "+model.getGoldsWithAg(i)+" gold(s), at "+model.getAgPos(i));
- //}
- //out.println(model.toString());
- StringBuilder s = new StringBuilder(String.format("Step %5d : ", cycle));
- for (int i=0; i<WorldModel.agsByTeam; i++) {
- Location agp = model.getAgPos(i);
- if (agp != null) {
- // count how long the agent is in the same location
- int c = 0;
- Iterator<Location> il = locations.get(i).iterator();
- while (il.hasNext() && il.next().equals(agp) && c <= 11) {
- c++;
- }
- String sc = "*";
- if (c < 10) sc = ""+c;
-
- locations.get(i).add(0,agp);
- s.append(String.format("%5d,%2d/%s", agp.x, agp.y, sc));
- }
- }
- logger.info(s.toString());
- out.println(s.toString());
- out.flush();
- }
- } catch (InterruptedException e) { // no problem, quit the thread
- return;
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- out.close();
- }
- }
-
- synchronized private void waitSomeTime() throws InterruptedException {
- wait(4000);
- }
- synchronized private void go() {
- notifyAll();
- }
- }
}
Added: trunk/applications/jason-team/src/java/arch/WriteStatusThread.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/WriteStatusThread.java (rev 0)
+++ trunk/applications/jason-team/src/java/arch/WriteStatusThread.java 2008-03-22 12:30:49 UTC (rev 1171)
@@ -0,0 +1,123 @@
+package arch;
+
+import jason.environment.grid.Location;
+
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Logger;
+
+import env.WorldModel;
+
+public class WriteStatusThread extends Thread {
+
+ protected Logger logger = Logger.getLogger(WriteStatusThread.class.getName());
+
+ // singleton
+ static WriteStatusThread instance = null;
+ private WriteStatusThread() {}
+
+ public static WriteStatusThread create(CowboyArch owner) {
+ if (instance == null) {
+ instance = new WriteStatusThread();
+ instance.owner = owner;
+ instance.start();
+ }
+ return instance;
+ }
+ public static boolean isCreated() {
+ return instance != null;
+ }
+
+ private CowboyArch owner = null;
+
+ private static CowboyArch[] agents = new CowboyArch[WorldModel.agsByTeam];
+
+ public static void registerAgent(String name, CowboyArch arch) {
+ agents[arch.getMyId()] = arch;
+ }
+
+ Map<Integer,List<Location>> locations;
+
+ public void reset() {
+ // init locations
+ locations = new HashMap<Integer, List<Location>>();
+ for (int i=0; i<WorldModel.agsByTeam; i++) {
+ locations.put(i, new LinkedList<Location>());
+ }
+ }
+
+ public void run() {
+ reset();
+
+ String fileName = "world-status.txt";
+ PrintWriter out = null;
+ try {
+ out = new PrintWriter(fileName);
+ while (true) {
+ try {
+ waitNextCycle();
+ //out.println("\n\n** Agent "+getAgName()+" in cycle "+cycle+"\n");
+ //for (int i=0; i<model.getNbOfAgs(); i++) {
+ // out.println("miner"+(i+1)+" is carrying "+model.getGoldsWithAg(i)+" gold(s), at "+model.getAgPos(i));
+ //}
+ //out.println(model.toString());
+ StringBuilder s = new StringBuilder(String.format("Step %5d : ", owner.getCycle()-1));
+ for (int agId=0; agId<WorldModel.agsByTeam; agId++) {
+ Location agp = agents[agId].getLastLocation();
+ if (agp != null) {
+ // count how long the agent is in the same location
+ int c = 0;
+ Iterator<Location> il = locations.get(agId).iterator();
+ while (il.hasNext() && il.next().equals(agp) && c <= 11) {
+ c++;
+ }
+ String sc = "*";
+ if (c < 10) sc = ""+c;
+
+ locations.get(agId).add(0,agp);
+ String lastAct = shortActionFormat(agents[agId].getLastAction());
+ s.append(String.format("%5d,%2d/%s %s", agp.x, agp.y, sc, lastAct));
+ }
+ }
+ logger.info(s.toString());
+ out.println(s.toString());
+ out.flush();
+ } catch (InterruptedException e) { // no problem, quit the thread
+ return;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ out.close();
+ }
+ }
+
+ public String shortActionFormat(String act) {
+ if (act.equals(WorldModel.Move.east.toString())) return "e ";
+ if (act.equals(WorldModel.Move.northeast.toString())) return "ne";
+ if (act.equals(WorldModel.Move.southeast.toString())) return "se";
+ if (act.equals(WorldModel.Move.west.toString())) return "w ";
+ if (act.equals(WorldModel.Move.northwest.toString())) return "nw";
+ if (act.equals(WorldModel.Move.southwest.toString())) return "sw";
+ if (act.equals(WorldModel.Move.north.toString())) return "n ";
+ if (act.equals(WorldModel.Move.south.toString())) return "s ";
+ return act;
+ }
+
+ synchronized private void waitNextCycle() throws InterruptedException {
+ wait(10000);
+ }
+
+ synchronized void go() {
+ notifyAll();
+ }
+
+}
Modified: trunk/applications/jason-team/src/java/jia/Search.java
===================================================================
--- trunk/applications/jason-team/src/java/jia/Search.java 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/applications/jason-team/src/java/jia/Search.java 2008-03-22 12:30:49 UTC (rev 1171)
@@ -177,7 +177,7 @@
if (ia.model.isFreeOfObstacle(newl) && !ia.model.hasObject(WorldModel.CORRAL, newl)) {
if (ia.considerAgentsAsObstacles) {
- if (ia.model.isFree(newl) || ia.from.distance(newl) > 1) {
+ if ((ia.model.isFree(WorldModel.AGENT,newl) && ia.model.isFree(WorldModel.COW,newl)) || ia.from.distance(newl) > 3) {
s.add(new GridState(newl,op,ia));
}
} else {
Modified: trunk/build.xml
===================================================================
--- trunk/build.xml 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/build.xml 2008-03-22 12:30:49 UTC (rev 1171)
@@ -304,7 +304,7 @@
<target name="clean">
<delete failonerror="no" includeEmptyDirs="true" verbose="true">
<fileset defaultexcludes="no" dir="${basedir}" includes="**/*~" />
- <fileset dir="${basedir}" includes="**/*.class" />
+ <fileset dir="${basedir}" includes="**/*.class" excludes="applications/**/*"/>
<fileset dir="${basedir}" includes="**/core" />
<fileset dir="${basedir}/doc/api" includes="**/*" />
<fileset dir="${basedir}" includes="**/.nbattrs" />
Modified: trunk/src/jason/JasonException.java
===================================================================
--- trunk/src/jason/JasonException.java 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/src/jason/JasonException.java 2008-03-22 12:30:49 UTC (rev 1171)
@@ -19,14 +19,6 @@
// http://www.dur.ac.uk/r.bordini
// http://www.inf.furb.br/~jomi
//
-// CVS information:
-// $Date$
-// $Revision$
-// $Log$
-// Revision 1.3 2005/08/12 22:26:08 jomifred
-// add cvs keywords
-//
-//
//----------------------------------------------------------------------------
Modified: trunk/src/jason/RevisionFailedException.java
===================================================================
--- trunk/src/jason/RevisionFailedException.java 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/src/jason/RevisionFailedException.java 2008-03-22 12:30:49 UTC (rev 1171)
@@ -19,14 +19,6 @@
// http://www.dur.ac.uk/r.bordini
// http://www.inf.furb.br/~jomi
//
-// CVS information:
-// $Date: 2007-02-19 16:53:54 +0100 (Mon, 19 Feb 2007) $
-// $Revision: 751 $
-// $Log$
-// Revision 1.3 2005/08/12 22:26:08 jomifred
-// add cvs keywords
-//
-//
//----------------------------------------------------------------------------
package jason;
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-22 12:30:49 UTC (rev 1171)
@@ -57,6 +57,7 @@
private static Config config = Config.get();
public void setAg(Agent ag) { curAg = ag; }
+
private String getSourceRef(Object o) {
if (o instanceof SourceInfo) {
SourceInfo s = (SourceInfo)o;
@@ -65,6 +66,7 @@
return "";
}
}
+
private InternalActionLiteral checkInternalActionsInContext(LogicalFormula f, Agent ag) throws Exception {
if (f != null) {
if (f instanceof InternalActionLiteral) {
@@ -82,6 +84,7 @@
}
return null;
}
+
private ArithFunction getArithFunction(Structure l) {
ArithFunction af = null;
if (curAg != null)
@@ -91,7 +94,19 @@
// try global function
af = FunctionRegister.getFunction(l.getFunctor(), l.getArity());
return af;
- }
+ }
+
+ private Term changeToAtom(Object o) {
+ Term u = (Term)o;
+ if (u.isAtom()) {
+ Atom a = new Atom( ((Structure)u).getFunctor());
+ a.setSrc(u);
+ return a;
+ } else {
+ return u;
+ }
+ }
+
}
PARSER_END(as2j)
@@ -428,30 +443,21 @@
}
-Term term() : { Term u; Object o; Atom a; }
+Term term() : { Object o;}
{
- ( u=list()
- | o=arithm_expr() { u = (Term)o; // arithm expr includes literals/atoms/structures
- if (u.isAtom()) {
- a = new Atom( ((Structure)u).getFunctor());
- a.setSrc(u);
- return a;
- }
- return u;
- }
- | u=string()
+ ( o=list()
+ | o=log_expr() // log expr includes literals/atoms/structures
)
- { return u; }
+ { return changeToAtom(o); }
}
-ListTermImpl list() : { ListTermImpl lt = new ListTermImpl(); ListTerm last;
- Token K; Term f; }
+ListTermImpl list() : { ListTermImpl lt = new ListTermImpl(); ListTerm last; Token K; Term f; }
{
"["
[
- f=term() { last = lt.append(f); lt.setSrcLine(f.getSrcLine()); lt.setSrc(f.getSrc());}
- ( "," f=term() { last = last.append(f); }
+ f=term_in_list() { last = lt.append(f); lt.setSrcLine(f.getSrcLine()); lt.setSrc(f.getSrc());}
+ ( "," f=term_in_list() { last = last.append(f); }
)*
[ "|" ( K=<VAR> { last.setNext(new VarTerm(K.image)); }
| K=<UNNAMEDVAR> { last.setNext(new UnnamedVar(K.image)); }
@@ -462,23 +468,31 @@
"]" { return lt; }
}
+// term_in_list is the same as term, but log_expr must be enclosed by "("....")" to avoid problem with |
+Term term_in_list() : { Object o; }
+{
+ ( o=list()
+ | o=arithm_expr()
+ | o=string()
+ )
+ { return changeToAtom(o); }
+}
+
/* logical expression */
-Object log_expr() :
- { Object t1, t2; }
+Object log_expr() : { Object t1, t2; }
{
t1 = log_expr_trm()
-[ "|" t2 = log_expr() { return new LogExpr((LogicalFormula)t1,LogicalOp.or,(LogicalFormula)t2); } ]
- { return t1; }
+ [ "|" t2 = log_expr() { return new LogExpr((LogicalFormula)t1,LogicalOp.or,(LogicalFormula)t2); } ]
+ { return t1; }
}
-Object log_expr_trm() :
- { Object t1, t2; }
+Object log_expr_trm() : { Object t1, t2; }
{
t1 = log_expr_factor()
-[ "&" t2 = log_expr_trm() { return new LogExpr((LogicalFormula)t1,LogicalOp.and,(LogicalFormula)t2); } ]
- { return t1; }
+[ "&" t2 = log_expr_trm() { return new LogExpr((LogicalFormula)t1,LogicalOp.and,(LogicalFormula)t2); } ]
+ { return t1; }
}
Object log_expr_factor():
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2008-03-22 12:30:49 UTC (rev 1171)
@@ -27,6 +27,7 @@
private static Config config = Config.get();
public void setAg(Agent ag) { curAg = ag; }
+
private String getSourceRef(Object o) {
if (o instanceof SourceInfo) {
SourceInfo s = (SourceInfo)o;
@@ -35,6 +36,7 @@
return "";
}
}
+
private InternalActionLiteral checkInternalActionsInContext(LogicalFormula f, Agent ag) throws Exception {
if (f != null) {
if (f instanceof InternalActionLiteral) {
@@ -52,6 +54,7 @@
}
return null;
}
+
private ArithFunction getArithFunction(Structure l) {
ArithFunction af = null;
if (curAg != null)
@@ -63,6 +66,17 @@
return af;
}
+ private Term changeToAtom(Object o) {
+ Term u = (Term)o;
+ if (u.isAtom()) {
+ Atom a = new Atom( ((Structure)u).getFunctor());
+ a.setSrc(u);
+ return a;
+ } else {
+ return u;
+ }
+ }
+
/* AgentSpeak Grammar */
/* agent ::= bels goals plans
@@ -648,46 +662,37 @@
}
final public Term term() throws ParseException {
- Term u; Object o; Atom a;
+ Object o;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 42:
- u = list();
+ o = list();
break;
case VAR:
case TK_TRUE:
case TK_FALSE:
+ case TK_NOT:
case TK_NEG:
case TK_BEGIN:
case TK_END:
case NUMBER:
+ case STRING:
case ATOM:
case UNNAMEDVAR:
case 35:
case 39:
- o = arithm_expr();
- u = (Term)o; // arithm expr includes literals/atoms/structures
- if (u.isAtom()) {
- a = new Atom( ((Structure)u).getFunctor());
- a.setSrc(u);
- {if (true) return a;}
- }
- {if (true) return u;}
+ o = log_expr();
break;
- case STRING:
- u = string();
- break;
default:
jj_la1[28] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
- {if (true) return u;}
+ {if (true) return changeToAtom(o);}
throw new Error("Missing return statement in function");
}
final public ListTermImpl list() throws ParseException {
- ListTermImpl lt = new ListTermImpl(); ListTerm last;
- Token K; Term f;
+ ListTermImpl lt = new ListTermImpl(); ListTerm last; Token K; Term f;
jj_consume_token(42);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case VAR:
@@ -703,7 +708,7 @@
case 35:
case 39:
case 42:
- f = term();
+ f = term_in_list();
last = lt.append(f); lt.setSrcLine(f.getSrcLine()); lt.setSrc(f.getSrc());
label_10:
while (true) {
@@ -716,7 +721,7 @@
break label_10;
}
jj_consume_token(41);
- f = term();
+ f = term_in_list();
last = last.append(f);
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
@@ -755,38 +760,70 @@
throw new Error("Missing return statement in function");
}
+// term_in_list is the same as term, but log_expr must be enclosed by "("....")" to avoid problem with |
+ final public Term term_in_list() throws ParseException {
+ Object o;
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 42:
+ o = list();
+ break;
+ case VAR:
+ case TK_TRUE:
+ case TK_FALSE:
+ case TK_NEG:
+ case TK_BEGIN:
+ case TK_END:
+ case NUMBER:
+ case ATOM:
+ case UNNAMEDVAR:
+ case 35:
+ case 39:
+ o = arithm_expr();
+ break;
+ case STRING:
+ o = string();
+ break;
+ default:
+ jj_la1[33] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ {if (true) return changeToAtom(o);}
+ throw new Error("Missing return statement in function");
+ }
+
/* logical expression */
final public Object log_expr() throws ParseException {
- Object t1, t2;
+ Object t1, t2;
t1 = log_expr_trm();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 43:
jj_consume_token(43);
t2 = log_expr();
- {if (true) return new LogExpr((LogicalFormula)t1,LogicalOp.or,(LogicalFormula)t2);}
+ {if (true) return new LogExpr((LogicalFormula)t1,LogicalOp.or,(LogicalFormula)t2);}
break;
default:
- jj_la1[33] = jj_gen;
+ jj_la1[34] = jj_gen;
;
}
- {if (true) return t1;}
+ {if (true) return t1;}
throw new Error("Missing return statement in function");
}
final public Object log_expr_trm() throws ParseException {
- Object t1, t2;
+ Object t1, t2;
t1 = log_expr_factor();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 45:
jj_consume_token(45);
t2 = log_expr_trm();
- {if (true) return new LogExpr((LogicalFormula)t1,LogicalOp.and,(LogicalFormula)t2);}
+ {if (true) return new LogExpr((LogicalFormula)t1,LogicalOp.and,(LogicalFormula)t2);}
break;
default:
- jj_la1[34] = jj_gen;
+ jj_la1[35] = jj_gen;
;
}
- {if (true) return t1;}
+ {if (true) return t1;}
throw new Error("Missing return statement in function");
}
@@ -814,7 +851,7 @@
{if (true) return t;}
break;
default:
- jj_la1[35] = jj_gen;
+ jj_la1[36] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -850,7 +887,7 @@
op1 = string();
break;
default:
- jj_la1[36] = jj_gen;
+ jj_la1[37] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -897,7 +934,7 @@
operator = RelationalOp.literalBuilder;
break;
default:
- jj_la1[37] = jj_gen;
+ jj_la1[38] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -922,7 +959,7 @@
op2 = list();
break;
default:
- jj_la1[38] = jj_gen;
+ jj_la1[39] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -933,7 +970,7 @@
{if (true) return new RelExpr((Term)op1, operator, (Term)op2);}
break;
default:
- jj_la1[39] = jj_gen;
+ jj_la1[40] = jj_gen;
;
}
{if (true) return op1;}
@@ -958,7 +995,7 @@
op = ArithmeticOp.minus;
break;
default:
- jj_la1[40] = jj_gen;
+ jj_la1[41] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -972,7 +1009,7 @@
{if (true) return new ArithExpr((NumberTerm)t1, op, (NumberTerm)t2);}
break;
default:
- jj_la1[41] = jj_gen;
+ jj_la1[42] = jj_gen;
;
}
{if (true) return t1;}
@@ -1006,7 +1043,7 @@
op = ArithmeticOp.mod;
break;
default:
- jj_la1[42] = jj_gen;
+ jj_la1[43] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1020,7 +1057,7 @@
{if (true) return ...
[truncated message content] |
|
From: <jom...@us...> - 2008-03-23 13:10:21
|
Revision: 1172
http://jason.svn.sourceforge.net/jason/?rev=1172&view=rev
Author: jomifred
Date: 2008-03-23 06:10:17 -0700 (Sun, 23 Mar 2008)
Log Message:
-----------
1. allows free vars in context (e.g. : P[a] | P[b]).
-- see tests/TestVarInContext.java for more examples
2. minor changes in jason-team
Modified Paths:
--------------
trunk/applications/jason-team/src/asl/dummy.asl
trunk/applications/jason-team/src/java/arch/ACArchitecture.java
trunk/applications/jason-team/src/java/arch/ACProxy.java
trunk/applications/jason-team/src/java/arch/WriteStatusThread.java
trunk/src/jason/asSyntax/LogExpr.java
trunk/src/jason/asSyntax/VarTerm.java
trunk/src/test/VarTermTest.java
Added Paths:
-----------
trunk/applications/as-unit-test/build.xml
trunk/applications/as-unit-test/lib/
trunk/applications/as-unit-test/lib/junit.jar
trunk/applications/as-unit-test/src/jason/tests/TestVarInContext.java
Added: trunk/applications/as-unit-test/build.xml
===================================================================
--- trunk/applications/as-unit-test/build.xml (rev 0)
+++ trunk/applications/as-unit-test/build.xml 2008-03-23 13:10:17 UTC (rev 1172)
@@ -0,0 +1,136 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<project basedir="." default="test" name="Jason AS Unit">
+
+ <property environment="env" />
+
+ <property name="jasondir" value="../.." />
+
+ <property name="asunitjar" value="lib/asunit.jar" />
+
+ <property name="build.dir" value="${basedir}/bin" />
+
+ <property name="dist.properties" value="${basedir}/bin/dist.properties" />
+ <property name="version" value="0" />
+ <property name="release" value="0.1" />
+ <property name="distDir" value="${env.HOME}/tmp/x/ASUnit-${version}.${release}" />
+ <property name="distFile" value="${env.HOME}/ASUnit-${version}.${release}" />
+
+ <path id="project.classpath">
+ <pathelement location="${basedir}/lib/junit.jar" />
+ <pathelement location="${jasondir}/lib/jason.jar" />
+ </path>
+
+ <target name="init" >
+ <mkdir dir="${build.dir}" />
+ <mkdir dir="${basedir}/lib" />
+ </target>
+
+ <target name="compile" depends="init">
+ <javac srcdir="src" destdir="${build.dir}" debug="true" deprecation="true" optimize="true" nowarn="true" source="1.5" target="1.5">
+ <classpath refid="project.classpath" />
+ </javac>
+ </target>
+
+
+ <target name="jar" depends="compile">
+ <jar jarfile="${asunitjar}" >
+ <fileset dir="${build.dir}">
+ <include name="jason/asunit/**/*.class" />
+ </fileset>
+ </jar>
+ </target>
+
+ <target name="test" depends="jar">
+ <ant dir="../.." target="jar" />
+ <junit printsummary="yes" failureProperty="test.failure">
+ <classpath refid="project.classpath" />
+ <classpath path="${build.dir}" />
+ <formatter type="plain" usefile="false" />
+ <batchtest>
+ <fileset dir="${basedir}/src" includes="example/**/Test*.java" />
+ <fileset dir="${basedir}/src" includes="jason/tests/**/Test*.java" />
+ </batchtest>
+ </junit>
+ <fail message="test failed" if="test.failure" />
+ <delete failonerror="no" verbose="false">
+ <fileset dir="${basedir}" includes="bookstore.*" />
+ </delete>
+ </target>
+
+ <target name="apidoc" depends="compile">
+ <javadoc
+ destdir="${basedir}/doc/api"
+ packagenames="jason.asunit.*"
+ sourcepath="${basedir}/src"
+ excludepackagenames="jason.asSyntax.parser,jason.mas2j.parser"
+ use="true"
+ version="true"
+ author="true"
+ windowtitle="Jason - AgentSpeak Unit Test">
+ <classpath refid="project.classpath" />
+ </javadoc>
+ </target>
+
+ <target name="dist" depends="jar" description="Build distribution.">
+
+ <echo message="Generating Jason ASUnit ${version}.${release}" />
+
+ <propertyfile file="${dist.properties}">
+ <entry key="version" value="${version}" />
+ <entry key="release" value="${release}" />
+ <!-- entry default="0" key="build" operation="+" type="int" /-->
+ <entry key="build.date" type="date" value="now" />
+ </propertyfile>
+ <property file="${dist.properties}" />
+
+ <fixcrlf eol="crlf" includes="**/*.txt,**/*.bat" srcdir="${basedir}" />
+
+ <delete failonerror="no" includeEmptyDirs="true">
+ <fileset dir="${distDir}" />
+ </delete>
+ <delete dir="${distDir}/.." />
+
+ <mkdir dir="${distDir}" />
+
+ <copy todir="${distDir}">
+ <fileset dir="${basedir}" includes="*.*" />
+ <fileset dir="${basedir}" includes="LICENSE" />
+ <fileset dir="${basedir}" includes="README" />
+
+ <fileset dir="${basedir}" includes="bin/*" excludes="bin/jedit.tgz" />
+ <fileset dir="${basedir}" includes="bin/jedit/**/*" />
+ <fileset dir="${basedir}" includes="doc/**/*" />
+ <fileset dir="${basedir}" includes="examples/**/*" />
+ <fileset dir="${basedir}" includes="demos/**/*" />
+ <fileset dir="${basedir}" includes="lib/**/*" />
+ <fileset dir="${basedir}" includes="src/**/*" />
+ </copy>
+
+ <delete failonerror="no" includeEmptyDirs="true">
+ <fileset dir="${distDir}" includes=".settings" />
+ <fileset dir="${distDir}" includes=".project" />
+ <fileset dir="${distDir}" includes=".classpath" />
+ </delete>
+ <delete dir="${distDir}/bin/classes" />
+ <delete dir="${distDir}/doc/faq" />
+ <delete dir="${distDir}/doc/mini-tutorial/src" />
+
+ <tar compression="gzip" tarfile="${distFile}.tgz">
+ <tarfileset dir="${distDir}/.." mode="755">
+ <include name="Jason-${version}.${release}/**/*.sh" />
+ <include name="Jason-${version}.${release}/**/asl2*" />
+ </tarfileset>
+ <tarfileset dir="${distDir}/..">
+ <include name="Jason-${version}.${release}/**/*" />
+ <exclude name="Jason-${version}.${release}/**/*.sh" />
+ <exclude name="Jason-${version}.${release}/**/asl2*" />
+ </tarfileset>
+ </tar>
+ </target>
+
+ <target name="clean">
+ <delete dir="${build.dir}" />
+ </target>
+
+</project>
Added: trunk/applications/as-unit-test/lib/junit.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/as-unit-test/lib/junit.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/as-unit-test/src/jason/tests/TestVarInContext.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestVarInContext.java (rev 0)
+++ trunk/applications/as-unit-test/src/jason/tests/TestVarInContext.java 2008-03-23 13:10:17 UTC (rev 1172)
@@ -0,0 +1,42 @@
+package jason.tests;
+
+import jason.asunit.TestAgent;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestVarInContext {
+
+ TestAgent ag;
+
+ // initialisation of the agent test
+ @Before
+ public void setupAg() {
+ ag = new TestAgent();
+ ag.setDebugMode(true);
+
+ // defines the agent's AgentSpeak code
+ ag.parseAScode(
+ "b1[b]. b2[c]. b3[d]. b4[a,d]. "+
+ "+!test1 : P[e] | P[c] <- jason.asunit.print(P). " +
+
+ "+!test2 : P[e] & P[c] <- jason.asunit.print(P). " +
+ "-!test2 <- jason.asunit.print(\"error\"). " +
+
+ "+!test3 : P[a] & P[d] <- jason.asunit.print(P). "
+ );
+ }
+
+ @Test
+ public void testContext() {
+ ag.addGoal("test1");
+ ag.assertPrint("b2", 5);
+
+ ag.addGoal("test2");
+ ag.assertPrint("error", 5);
+
+ ag.addGoal("test3");
+ ag.assertPrint("b4", 5);
+ }
+
+}
Modified: trunk/applications/jason-team/src/asl/dummy.asl
===================================================================
--- trunk/applications/jason-team/src/asl/dummy.asl 2008-03-22 12:30:49 UTC (rev 1171)
+++ trunk/applications/jason-team/src/asl/dummy.asl 2008-03-23 13:10:17 UTC (rev 1172)
@@ -75,7 +75,8 @@
+restart
<- .print("*** restart ***");
- .drop_all_desires;
+ .drop_all_desires;
+ .abolish(target(_,_));
!move.
/* -- tests -- */
Modified: trunk/applications/jason-team/src/java/arch/ACArchitecture.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-22 12:30:49 UTC (rev 1171)
+++ trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-23 13:10:17 UTC (rev 1172)
@@ -142,24 +142,24 @@
}
void newCycle() {
- List<ActionExec> feedback = getTS().getC().getFeedbackActions();
+ logger.info("last action sent is "+lastActionInCurrentCycle+". The following was not sent: "+toExecute);
+ setLastAct(lastActionInCurrentCycle);
+ lastActionInCurrentCycle = null;
// set all actions as successfully executed
+ List<ActionExec> feedback = getTS().getC().getFeedbackActions();
while (!toExecute.isEmpty()) {
ActionExec action = toExecute.poll();
action.setResult(true);
feedback.add(action);
}
-
- logger.info("last action sent is "+lastActionInCurrentCycle);
- setLastAct(lastActionInCurrentCycle);
- lastActionInCurrentCycle = null;
}
synchronized void go() {
notifyAll();
}
synchronized void waitSleep() throws InterruptedException {
+ // TODO: do something by timeout?
wait();
}
Modified: trunk/applications/jason-team/src/java/arch/ACProxy.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/ACProxy.java 2008-03-22 12:30:49 UTC (rev 1171)
+++ trunk/applications/jason-team/src/java/arch/ACProxy.java 2008-03-23 13:10:17 UTC (rev 1172)
@@ -136,6 +136,8 @@
}
}
+ int maxx = 0; // max value of some cell'x
+
public void processRequestAction(Element perception, long currenttime, long deadline) {
try {
@@ -158,8 +160,7 @@
lpos.addTerm(new NumberTermImpl(step));
percepts.add(lpos);
- int maxx = 0; // max value of some cell'x
- int enemyId = 1;
+ int enemyId = 1;
// add in perception what is around
NodeList nl = perception.getElementsByTagName("cell");
for (int i=0; i < nl.getLength(); i++) {
Modified: trunk/applications/jason-team/src/java/arch/WriteStatusThread.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/WriteStatusThread.java 2008-03-22 12:30:49 UTC (rev 1171)
+++ trunk/applications/jason-team/src/java/arch/WriteStatusThread.java 2008-03-23 13:10:17 UTC (rev 1172)
@@ -3,7 +3,6 @@
import jason.environment.grid.Location;
import java.io.PrintWriter;
-import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
Modified: trunk/src/jason/asSyntax/LogExpr.java
===================================================================
--- trunk/src/jason/asSyntax/LogExpr.java 2008-03-22 12:30:49 UTC (rev 1171)
+++ trunk/src/jason/asSyntax/LogExpr.java 2008-03-23 13:10:17 UTC (rev 1172)
@@ -132,12 +132,12 @@
private void get() {
needsUpdate = false;
current = null;
- if (ileft.hasNext())
+ if (ileft != null && ileft.hasNext())
current = ileft.next();
else {
if (iright == null)
iright = getRHS().logicalConsequence(ag,un);
- if (iright.hasNext())
+ if (iright != null && iright.hasNext())
current = iright.next();
}
}
Modified: trunk/src/jason/asSyntax/VarTerm.java
===================================================================
--- trunk/src/jason/asSyntax/VarTerm.java 2008-03-22 12:30:49 UTC (rev 1171)
+++ trunk/src/jason/asSyntax/VarTerm.java 2008-03-23 13:10:17 UTC (rev 1172)
@@ -46,7 +46,7 @@
*
* @author jomi
*/
-public class VarTerm extends InternalActionLiteral implements NumberTerm, ListTerm, StringTerm, ObjectTerm {
+public class VarTerm extends Literal implements NumberTerm, ListTerm, StringTerm, ObjectTerm {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(VarTerm.class.getName());
@@ -110,9 +110,10 @@
}
vl = (Term)vl.clone();
- if (vl.isPred() && this.hasAnnot()) { // if this var has annots, add them in the value's annots (Experimental)
- ((Pred)vl).addAnnots(this.getAnnots());
- }
+ // The below does not conform the rules in manual
+ //if (vl.isPred() && this.hasAnnot()) { // if this var has annots, add them in the value's annots (Experimental)
+ // ((Pred)vl).addAnnots(this.getAnnots());
+ //}
value = vl;
resetHashCodeCache();
@@ -224,6 +225,9 @@
c.apply(un);
if (c.hasValue() && c.getValue() instanceof LogicalFormula) {
return ((LogicalFormula)c.getValue()).logicalConsequence(ag, un);
+ } else {
+ // the variable is still a Var, find all bels that unify.
+ return super.logicalConsequence(ag, un);
}
}
}
Modified: trunk/src/test/VarTermTest.java
===================================================================
--- trunk/src/test/VarTermTest.java 2008-03-22 12:30:49 UTC (rev 1171)
+++ trunk/src/test/VarTermTest.java 2008-03-23 13:10:17 UTC (rev 1172)
@@ -1,5 +1,9 @@
package test;
+import jason.RevisionFailedException;
+import jason.architecture.AgArch;
+import jason.asSemantics.Agent;
+import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ArithExpr;
import jason.asSyntax.DefaultTerm;
@@ -16,6 +20,7 @@
import jason.asSyntax.parser.SimpleCharStream;
import jason.asSyntax.parser.Token;
import jason.asSyntax.parser.as2jTokenManager;
+import jason.infra.centralised.CentralisedAgArch;
import java.io.StringReader;
import java.util.Iterator;
@@ -287,6 +292,7 @@
assertFalse(u.unifies(v2, Literal.parseLiteral("open[source(a)]")));
}
+ /*
public void testVarWithAnnots5() {
// P -> open[source(a)]
// P[source(self)]
@@ -297,7 +303,37 @@
v1.apply(u);
assertEquals(v1.getAnnots().size(), 2);
}
+ */
+
+
+ public void testVarWithAnnotsInLogCons() throws RevisionFailedException {
+ Agent ag = new Agent();
+ AgArch arch = new AgArch();
+ arch.setArchInfraTier(new CentralisedAgArch());
+ ag.setTS(new TransitionSystem(ag, null, null, arch));
+ ag.addBel(Literal.parseLiteral("b1[b]"));
+ ag.addBel(Literal.parseLiteral("b2[d]"));
+
+ Unifier u = new Unifier();
+ VarTerm v1 = VarTerm.parseVar("P[d]");
+ assertEquals(2, iteratorSize(ag.getBB().getRelevant(v1)));
+ Iterator<Unifier> i = v1.logicalConsequence(ag, u);
+ assertTrue(i.hasNext());
+ u = i.next(); // u = {P[d]=b2}
+ v1.apply(u);
+ assertEquals("b2",v1.toString());
+ }
+
+ @SuppressWarnings("unchecked")
+ private int iteratorSize(Iterator i) {
+ int c = 0;
+ while (i.hasNext()) {
+ i.next();
+ c++;
+ }
+ return c;
+ }
public static void main(String[] a) {
new VarTermTest().testVarWithAnnots3();
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-24 20:37:38
|
Revision: 1173
http://jason.svn.sourceforge.net/jason/?rev=1173&view=rev
Author: jomifred
Date: 2008-03-24 13:37:34 -0700 (Mon, 24 Mar 2008)
Log Message:
-----------
add a new test in ASUnit to check the KQML performatives
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java
trunk/applications/as-unit-test/src/jason/asunit/TestArch.java
trunk/applications/as-unit-test/src/jason/tests/TestVarInContext.java
trunk/src/jason/asSemantics/Unifier.java
trunk/src/jason/asSyntax/Literal.java
trunk/src/jason/asSyntax/PlanLibrary.java
trunk/src/jason/asSyntax/VarTerm.java
trunk/src/jason/infra/centralised/CentralisedAgArch.java
trunk/src/jason/infra/centralised/CentralisedEnvironment.java
trunk/src/jason/infra/centralised/RunCentralisedMAS.java
trunk/src/test/RuleTest.java
trunk/src/test/VarTermTest.java
Added Paths:
-----------
trunk/applications/as-unit-test/src/jason/tests/TestKQML.java
Modified: trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -14,6 +14,7 @@
import jason.asSyntax.Trigger;
import jason.asSyntax.parser.ParseException;
import jason.bb.BeliefBase;
+import jason.infra.centralised.RunCentralisedMAS;
import jason.runtime.Settings;
import java.io.StringReader;
@@ -21,9 +22,23 @@
public class TestAgent extends Agent {
+ // creates the masRunner
+ static {
+ new RunCentralisedMAS();
+ }
+
+
public TestAgent() {
+ this(null);
+ }
+
+ public TestAgent(String agName) {
try {
- TestArch arch = new TestArch();
+ TestArch arch = null;
+ if (agName == null)
+ arch = new TestArch();
+ else
+ arch = new TestArch(agName);
arch.getUserAgArch().setTS(initAg(arch.getUserAgArch(), null, null, new Settings()));
} catch (JasonException e) {
logger.log(Level.SEVERE, "Error creating TestArch", e);
@@ -32,10 +47,16 @@
public boolean parseAScode(String aslCode) {
try {
+ getPL().clear(); // to force KQML plans to be after string plans
setASLSrc("stringcode");
parseAS(new StringReader(aslCode));
addInitialBelsInBB();
addInitialGoalsInTS();
+
+ // kqml Plans at the end of the ag PS
+ setASLSrc("kqmlPlans.asl");
+ parseAS(JasonException.class.getResource("/asl/kqmlPlans.asl"));
+ setASLSrc("stringcode");
return true;
} catch (Exception e) {
logger.log(Level.SEVERE, "Error parsing\n"+aslCode+": "+e.getMessage());
@@ -105,14 +126,14 @@
fail("Parsing '"+formula+"' as a formula failed!");
}
}
- public void assertBel(final LogicalFormula bel, final int maxCycles) {
+ public void assertBel(final LogicalFormula belief, final int maxCycles) {
Condition c = new Condition() {
public boolean test(TestArch arch) {
- return believes(bel, new Unifier());
+ return believes(belief, new Unifier());
}
};
if (!assertMaxCyclesAndAnotherCondition(c, maxCycles))
- fail("failed assertBel("+bel+")");
+ fail("failed assertBel("+belief+")");
}
@@ -167,8 +188,7 @@
public void assertPrint(final String out, final int maxCycles) {
Condition c = new Condition() {
public boolean test(TestArch arch) {
- boolean result = arch.getOutput().indexOf(out) >= 0;
- return result;
+ return arch.getOutput().indexOf(out) >= 0;
}
};
if (assertMaxCyclesAndAnotherCondition(c, maxCycles))
Modified: trunk/applications/as-unit-test/src/jason/asunit/TestArch.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/asunit/TestArch.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/applications/as-unit-test/src/jason/asunit/TestArch.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -24,14 +24,16 @@
StringBuilder output = new StringBuilder();
- private static RunCentralisedMAS runner = new RunCentralisedMAS();
-
public TestArch() {
- setAgName("ASUnitTest" + (nameCount++));
+ this("ASUnitTest" + (nameCount++));
+ }
+
+ public TestArch(String agName) {
+ setAgName(agName);
AgArch a = new AgArch();
a.setArchInfraTier(this);
setUserAgArch(a);
- runner.addAg(this);
+ RunCentralisedMAS.getRunner().addAg(this);
}
public int getCycle() {
@@ -62,7 +64,7 @@
public void setEnv(Environment env) {
try {
- CentralisedEnvironment infraEnv = new CentralisedEnvironment(null, runner);
+ CentralisedEnvironment infraEnv = new CentralisedEnvironment(null, RunCentralisedMAS.getRunner());
infraEnv.setUserEnvironment(env);
env.setEnvironmentInfraTier(infraEnv);
setEnvInfraTier(infraEnv);
Added: trunk/applications/as-unit-test/src/jason/tests/TestKQML.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestKQML.java (rev 0)
+++ trunk/applications/as-unit-test/src/jason/tests/TestKQML.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -0,0 +1,115 @@
+package jason.tests;
+
+import jason.asunit.TestAgent;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestKQML {
+
+ TestAgent bob, maria;
+
+ // initialisation of the agents
+ @Before
+ public void setupAgs() {
+ bob = new TestAgent("bob");
+ maria = new TestAgent("maria");
+
+ // defines the agent's AgentSpeak code
+ bob.parseAScode(
+ "+!simple_send <- .send(maria, tell, vl(10)); "+
+ " .send(maria, achieve, goto(10,2)). " +
+
+ "+!send_ask1 <- .send(maria, askOne, vl(_), vl(X)); " +
+ " .send(maria, askOne, vl(_)); " +
+ " act1(X). "+
+ "+!send_ask2 <- .send(maria, askOne, t2(_), A); "+
+ " jason.asunit.print(A). " +
+ "+!send_ask3 <- .send(maria, askOne, t1(_), A); "+
+ " jason.asunit.print(t1,\" \",A). "+
+ "+!send_ask4 <- .send(maria, askOne, fullname, A); "+
+ " jason.asunit.print(A). "+
+
+ "+!send_askAll1 <- .send(maria, askAll, vl(_), L); "+
+ " jason.asunit.print(L). "+
+ "+!send_askAll2 <- .send(maria, askAll, t1(_), L); "+
+ " jason.asunit.print(L). "+
+
+ "+!send_tellHow <- .plan_label(Plan,hp);"+
+ " .send(maria,tellHow,Plan); "+
+ " .send(maria,achieve, hello(bob)). "+
+ "+!send_untellHow <- .send(maria,untellHow,hp). "+
+
+ "@hp +!hello(Who) <- jason.asunit.print(\"Hello \",Who)."
+ );
+
+ maria.parseAScode(
+ "vl(1). vl(2). " +
+ "+!goto(X,Y)[source(Ag)] <- act(X,Y,Ag). "+
+ "+?t2(X) : vl(Y) <- X = 10 + Y."+
+ "+!kqml_received(Sender, askOne, fullname, ReplyWith) <- .send(Sender,tell,\"Maria dos Santos\", ReplyWith). "
+ );
+
+ }
+
+ @Test
+ public void testSend() {
+ bob.addGoal("simple_send");
+ bob.assertIdle(5); // bob sent the messages
+ maria.assertBel("vl(10)", 5); // maria received tell
+ maria.assertAct("act(10,2,bob)", 5); // maria received achieved
+ }
+
+ @Test
+ public void testAsk() {
+ bob.addGoal("send_ask1");
+ bob.addGoal("send_ask2");
+ bob.assertIdle(10); // let bob to send the messages
+ maria.assertIdle(10); // let maria to process the messages
+ bob.assertAct("act1(1)", 5);
+ maria.assertIdle(5);
+ bob.assertBel("vl(1)[source(maria)]", 5); // answer of maria for second askOne (assynchronous)
+
+ bob.assertPrint("t2(11)", 5); // answer for ask2
+ }
+
+ @Test
+ public void testAsk3() {
+ bob.addGoal("send_ask3");
+ bob.assertIdle(10); // let bob to send the messages
+ maria.assertIdle(10); // let maria to process the messages
+ bob.assertPrint("t1 false", 5); // answer for ask3
+
+ bob.addGoal("send_ask4");
+ bob.assertIdle(10);
+ maria.assertIdle(10);
+ bob.assertPrint("Maria dos Santos", 5); // answer for ask3
+ }
+
+ @Test
+ public void testAskAll() {
+ bob.addGoal("simple_send");
+ bob.addGoal("send_askAll1");
+ bob.assertIdle(10);
+ maria.assertIdle(10);
+ bob.assertPrint("[vl(10),vl(1),vl(2)]", 5);
+
+ bob.addGoal("send_askAll2");
+ bob.assertIdle(10);
+ maria.assertIdle(10);
+ bob.assertPrint("[]", 5);
+ }
+
+ @Test
+ public void testTellHow() {
+ bob.addGoal("send_tellHow");
+ bob.assertIdle(10);
+ maria.assertPrint("Hello bob", 10);
+
+ bob.addGoal("send_untellHow");
+ bob.assertIdle(10);
+ maria.assertIdle(10);
+ Assert.assertTrue(maria.getPL().get("hp") == null);
+ }
+}
Modified: trunk/applications/as-unit-test/src/jason/tests/TestVarInContext.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestVarInContext.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/applications/as-unit-test/src/jason/tests/TestVarInContext.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -31,6 +31,8 @@
public void testContext() {
ag.addGoal("test1");
ag.assertPrint("b2", 5);
+ ag.addGoal("test1"); // test twice to see if nothing was changed
+ ag.assertPrint("b2", 5);
ag.addGoal("test2");
ag.assertPrint("error", 5);
Modified: trunk/src/jason/asSemantics/Unifier.java
===================================================================
--- trunk/src/jason/asSemantics/Unifier.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/jason/asSemantics/Unifier.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -136,8 +136,11 @@
boolean ok = unifyTerms(t1g, t2g);
// if np1 is a var that was unified, clear its annots, as in
- // X[An] = p(1)[a]
- // X is mapped to p(1) and not p(1)[a]
+ // X[An] = p(1)[a,b]
+ // X is mapped to p(1) and not p(1)[a,b]
+ // (if the user wants the "remaining" annots, s/he should write
+ // X[An|R] = p(1)[a,b]
+ // X = p(1), An = a, R=[b]
if (ok && np1 != null) { // they are predicates
if (np1.isVar() && np1.hasAnnot()) {
Term np1vl = function.get((VarTerm) np1);
@@ -306,10 +309,10 @@
if (currentVl != null && currentVl instanceof VarsCluster) {
VarsCluster cluster = (VarsCluster) currentVl;
for (VarTerm cvt : cluster)
- function.put(cvt, value); //(Term) value.clone());
+ function.put(cvt, value); //(Term) value.clone()); // the clone is done in apply
} else {
// no value in cluster
- function.put((VarTerm) vt.clone(), value); //(Term) value.clone());
+ function.put((VarTerm) vt.clone(), value); //(Term) value.clone()); // the clone is done in apply
}
return true;
}
Modified: trunk/src/jason/asSyntax/Literal.java
===================================================================
--- trunk/src/jason/asSyntax/Literal.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/jason/asSyntax/Literal.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -125,11 +125,8 @@
*
* Returns an iterator for all unifiers that are logCons.
*/
- @SuppressWarnings("unchecked")
public Iterator<Unifier> logicalConsequence(final Agent ag, final Unifier un) {
- final Literal lclone = (Literal)this.clone();
- lclone.apply(un);
- final Iterator<Literal> il = ag.getBB().getRelevant(lclone);
+ final Iterator<Literal> il = ag.getBB().getRelevant(this);
if (il == null) // no relevant bels
return LogExpr.EMPTY_UNIF_LIST.iterator();
@@ -137,7 +134,7 @@
Unifier current = null;
Iterator<Unifier> ruleIt = null; // current rule solutions iterator
Rule rule; // current rule
- Literal lcloneAnnon = null; // a copy of lclone with makeVarsAnnon
+ Literal cloneAnnon = null; // a copy of the literal with makeVarsAnnon
AgArch arch = ag.getTS().getUserAgArch();
boolean needsUpdate = true;
@@ -169,7 +166,7 @@
rhead.apply(ruleUn);
Unifier unC = (Unifier) un.clone();
- if (unC.unifiesNoUndo(lclone, rhead)) {
+ if (unC.unifiesNoUndo(Literal.this, rhead)) {
current = unC;
return;
}
@@ -185,12 +182,13 @@
// make its vars anonymous,
// it is used to define what will be the unifier used
// inside the rule.
- if (lcloneAnnon == null) {
- lcloneAnnon = (Literal)lclone.clone();
- lcloneAnnon.makeVarsAnnon();
+ if (cloneAnnon == null) {
+ cloneAnnon = (Literal)Literal.this.clone();
+ cloneAnnon.apply(un);
+ cloneAnnon.makeVarsAnnon();
}
Unifier ruleUn = new Unifier();
- if (ruleUn.unifiesNoUndo(lcloneAnnon, rule)) { // the rule head unifies with the literal
+ if (ruleUn.unifiesNoUndo(cloneAnnon, rule)) { // the rule head unifies with the literal
ruleIt = rule.getBody().logicalConsequence(ag,ruleUn);
get();
if (current != null) { // if it get a value
@@ -198,35 +196,8 @@
}
}
} else {
- /* -- the problem below was solved by translating test_rule(A,A) to test_rule(A,A):-true.
- if (!b.isGround()) {
- // All the code below is necessary for situations like
- // test_rule(A,A).
- // !test(test_wrong_value).
- // +!test(A) : test_rule(Test,test_right_value) <- .println("Test = ",Test).
- // where a local variable has the same name as a variable in the belief.
- //
- // So, the solution is
- // 1. create a new empy unifier to unify lclone with b
- // ; lclone is test_rule(Test,test_right_value)
- // ; b is test_rule(A,A)
- // ; u is {A=test_right_value, Test=test_right_value}
- // ; note the value of A in this unifier
- // 2. create another clone b of lclone to apply this
- // unifier u ; c after apply is test_rule(test_right_value,test_right_value)
- // 3. create the result unifier as a clone of the current (un)
- // 4. using the new unifier, unify lclone and
- // b to get only the value of Test and not the A
- // in the result unifier
- Unifier u = new Unifier();
- if (u.unifies(lclone, b)) {
- b = (Literal)lclone.clone();
- b.apply(u);
- }
- }
- */
Unifier u = (Unifier) un.clone();
- if (u.unifiesNoUndo(lclone, b)) {
+ if (u.unifiesNoUndo(Literal.this, b)) {
current = u;
return;
}
Modified: trunk/src/jason/asSyntax/PlanLibrary.java
===================================================================
--- trunk/src/jason/asSyntax/PlanLibrary.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/jason/asSyntax/PlanLibrary.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -183,7 +183,14 @@
return plans.iterator();
}
-
+ /** remove all plans */
+ public void clear() {
+ planLabels.clear();
+ plans.clear();
+ varPlans.clear();
+ relPlans.clear();
+ }
+
/**
* Remove a plan represented by the label <i>pLabel</i>.
* In case the plan has many sources, only the plan's source is removed.
Modified: trunk/src/jason/asSyntax/VarTerm.java
===================================================================
--- trunk/src/jason/asSyntax/VarTerm.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/jason/asSyntax/VarTerm.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -109,7 +109,7 @@
return false;
}
- vl = (Term)vl.clone();
+ vl = (Term)vl.clone(); // should clone here, since there is no cloning in unify
// The below does not conform the rules in manual
//if (vl.isPred() && this.hasAnnot()) { // if this var has annots, add them in the value's annots (Experimental)
// ((Pred)vl).addAnnots(this.getAnnots());
Modified: trunk/src/jason/infra/centralised/CentralisedAgArch.java
===================================================================
--- trunk/src/jason/infra/centralised/CentralisedAgArch.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/jason/infra/centralised/CentralisedAgArch.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -60,7 +60,7 @@
protected CentralisedEnvironment infraEnv = null;
private CentralisedExecutionControl infraControl = null;
- private RunCentralisedMAS masRunner = null;
+ private RunCentralisedMAS masRunner = RunCentralisedMAS.getRunner();
/** The user implementation of the architecture */
protected AgArch userAgArch;
Modified: trunk/src/jason/infra/centralised/CentralisedEnvironment.java
===================================================================
--- trunk/src/jason/infra/centralised/CentralisedEnvironment.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/jason/infra/centralised/CentralisedEnvironment.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -44,7 +44,7 @@
/** the user customisation class for the environment */
private Environment userEnv;
- private RunCentralisedMAS masRunner = null;
+ private RunCentralisedMAS masRunner = RunCentralisedMAS.getRunner();
private boolean running = true;
private static Logger logger = Logger.getLogger(CentralisedEnvironment.class.getName());
Modified: trunk/src/jason/infra/centralised/RunCentralisedMAS.java
===================================================================
--- trunk/src/jason/infra/centralised/RunCentralisedMAS.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/jason/infra/centralised/RunCentralisedMAS.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -86,6 +86,10 @@
public JButton btDebug;
+ public RunCentralisedMAS() {
+ runner = this;
+ }
+
public static void main(String[] args) {
runner = new RunCentralisedMAS();
runner.init(args);
Modified: trunk/src/test/RuleTest.java
===================================================================
--- trunk/src/test/RuleTest.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/test/RuleTest.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -107,8 +107,7 @@
// min([C|T],V,M) :- C < V & min(T,C,M).
// min([_|T],V,M) :- min(T,V,M).
//ag.getBB().add(Literal.parseLiteral("min([],M,M)"));
- ag.getBB().add(new Rule(Literal.parseLiteral("min([],M,M)"),
- LogExpr.parseExpr(".println(fim,M)")));
+ ag.getBB().add(new Rule(Literal.parseLiteral("min([],M,M)"), Literal.LTrue));
ag.getBB().add(new Rule(Literal.parseLiteral("min([op(C)|T], op(V), M)"),
LogExpr.parseExpr("C < V & min(T,op(C),M)")));
ag.getBB().add(new Rule(Literal.parseLiteral("min([op(C)|T], op(V), M)"),
Modified: trunk/src/test/VarTermTest.java
===================================================================
--- trunk/src/test/VarTermTest.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/test/VarTermTest.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -6,6 +6,7 @@
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ArithExpr;
+import jason.asSyntax.Atom;
import jason.asSyntax.DefaultTerm;
import jason.asSyntax.ListTerm;
import jason.asSyntax.ListTermImpl;
@@ -268,6 +269,11 @@
// X[a,b] = Y[a] - not ok
u = new Unifier();
assertFalse(u.unifies(v2, v1));
+
+ assertTrue(u.unifies(v1, v2));
+ assertTrue(u.unifies(new Atom("vvv"), v1));
+ v1.apply(u);
+ assertEquals("vvv", v1.toString());
}
public void testVarWithAnnots3() {
@@ -276,7 +282,7 @@
VarTerm v2 = VarTerm.parseVar("Y[a,c|R]");
Unifier u = new Unifier();
assertTrue(u.unifies(v1, v2));
- assertEquals(u.get("R").toString(),"[b,d]");
+ assertEquals("[b,d]",u.get("R").toString());
}
public void testVarWithAnnots4() {
@@ -292,6 +298,19 @@
assertFalse(u.unifies(v2, Literal.parseLiteral("open[source(a)]")));
}
+ public void testVarWithAnnots5() {
+ // X[A|R] = p(1)[a,b,c] - ok and
+ // X = p(1), A = a, R=[b,c]
+ VarTerm v = VarTerm.parseVar("X[A|R]");
+ Unifier u = new Unifier();
+ assertTrue(u.unifies(v, Literal.parseLiteral("p(1)[a,b,c]")));
+ assertEquals("[b,c]", u.get("R").toString());
+ assertEquals("a", u.get("A").toString());
+ assertEquals("p(1)", u.get(v).toString());
+ v.apply(u);
+ assertEquals("p(1)", v.toString());
+ }
+
/*
public void testVarWithAnnots5() {
// P -> open[source(a)]
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-26 09:15:46
|
Revision: 1175
http://jason.svn.sourceforge.net/jason/?rev=1175&view=rev
Author: jomifred
Date: 2008-03-26 02:15:42 -0700 (Wed, 26 Mar 2008)
Log Message:
-----------
add a TestAll class in AS-Unit to run all tests
Modified Paths:
--------------
trunk/applications/as-unit-test/build.xml
trunk/demos/directives/b.asl
trunk/demos/sync-environment/dcount.asl
Added Paths:
-----------
trunk/applications/as-unit-test/src/jason/tests/TestAll.java
Modified: trunk/applications/as-unit-test/build.xml
===================================================================
--- trunk/applications/as-unit-test/build.xml 2008-03-24 21:15:02 UTC (rev 1174)
+++ trunk/applications/as-unit-test/build.xml 2008-03-26 09:15:42 UTC (rev 1175)
@@ -49,7 +49,7 @@
<formatter type="plain" usefile="false" />
<batchtest>
<fileset dir="${basedir}/src" includes="example/**/Test*.java" />
- <fileset dir="${basedir}/src" includes="jason/tests/**/Test*.java" />
+ <fileset dir="${basedir}/src" includes="jason/tests/TestAll.java" />
</batchtest>
</junit>
<fail message="test failed" if="test.failure" />
@@ -72,63 +72,6 @@
</javadoc>
</target>
- <target name="dist" depends="jar" description="Build distribution.">
-
- <echo message="Generating Jason ASUnit ${version}.${release}" />
-
- <propertyfile file="${dist.properties}">
- <entry key="version" value="${version}" />
- <entry key="release" value="${release}" />
- <!-- entry default="0" key="build" operation="+" type="int" /-->
- <entry key="build.date" type="date" value="now" />
- </propertyfile>
- <property file="${dist.properties}" />
-
- <fixcrlf eol="crlf" includes="**/*.txt,**/*.bat" srcdir="${basedir}" />
-
- <delete failonerror="no" includeEmptyDirs="true">
- <fileset dir="${distDir}" />
- </delete>
- <delete dir="${distDir}/.." />
-
- <mkdir dir="${distDir}" />
-
- <copy todir="${distDir}">
- <fileset dir="${basedir}" includes="*.*" />
- <fileset dir="${basedir}" includes="LICENSE" />
- <fileset dir="${basedir}" includes="README" />
-
- <fileset dir="${basedir}" includes="bin/*" excludes="bin/jedit.tgz" />
- <fileset dir="${basedir}" includes="bin/jedit/**/*" />
- <fileset dir="${basedir}" includes="doc/**/*" />
- <fileset dir="${basedir}" includes="examples/**/*" />
- <fileset dir="${basedir}" includes="demos/**/*" />
- <fileset dir="${basedir}" includes="lib/**/*" />
- <fileset dir="${basedir}" includes="src/**/*" />
- </copy>
-
- <delete failonerror="no" includeEmptyDirs="true">
- <fileset dir="${distDir}" includes=".settings" />
- <fileset dir="${distDir}" includes=".project" />
- <fileset dir="${distDir}" includes=".classpath" />
- </delete>
- <delete dir="${distDir}/bin/classes" />
- <delete dir="${distDir}/doc/faq" />
- <delete dir="${distDir}/doc/mini-tutorial/src" />
-
- <tar compression="gzip" tarfile="${distFile}.tgz">
- <tarfileset dir="${distDir}/.." mode="755">
- <include name="Jason-${version}.${release}/**/*.sh" />
- <include name="Jason-${version}.${release}/**/asl2*" />
- </tarfileset>
- <tarfileset dir="${distDir}/..">
- <include name="Jason-${version}.${release}/**/*" />
- <exclude name="Jason-${version}.${release}/**/*.sh" />
- <exclude name="Jason-${version}.${release}/**/asl2*" />
- </tarfileset>
- </tar>
- </target>
-
<target name="clean">
<delete dir="${build.dir}" />
</target>
Added: trunk/applications/as-unit-test/src/jason/tests/TestAll.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestAll.java (rev 0)
+++ trunk/applications/as-unit-test/src/jason/tests/TestAll.java 2008-03-26 09:15:42 UTC (rev 1175)
@@ -0,0 +1,14 @@
+package jason.tests;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+import org.junit.runners.Suite.SuiteClasses;
+
+@RunWith(Suite.class)
+@SuiteClasses({
+ BugVarsInInitBels.class,
+ TestAddLogExprInBB.class,
+ TestKQML.class,
+ TestVarInContext.class
+ })
+public class TestAll { }
Modified: trunk/demos/directives/b.asl
===================================================================
--- trunk/demos/directives/b.asl 2008-03-24 21:15:02 UTC (rev 1174)
+++ trunk/demos/directives/b.asl 2008-03-26 09:15:42 UTC (rev 1175)
@@ -2,13 +2,13 @@
+!start : true <- myp.list_plans; !d(1); !d(2).
{ begin ld }
-+!d(X) <- act.
-+!d(X) <- act.
++!d(X) <- act(X).
++!d(X) <- act(X).
{ end }
/*
The above plans will be changed by the directive to:
- +!d(X) <- .print("Entering ",d(X)); .print(d1); .print("Leaving ",d(X)).
- +!d(X) <- .print("Entering ",d(X)); .print(d2); .print("Leaving ",d(X)).
+ +!d(X) <- .print("Entering ",d(X)); act(X); .print("Leaving ",d(X)).
+ +!d(X) <- .print("Entering ",d(X)); act(X); .print("Leaving ",d(X)).
*/
Modified: trunk/demos/sync-environment/dcount.asl
===================================================================
--- trunk/demos/sync-environment/dcount.asl 2008-03-24 21:15:02 UTC (rev 1174)
+++ trunk/demos/sync-environment/dcount.asl 2008-03-26 09:15:42 UTC (rev 1175)
@@ -1,9 +1,10 @@
// this agent has TWO intentions to act
+vl(0).
+
!i1.
!i2.
-vl(0).
/* Plans */
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-28 18:08:02
|
Revision: 1178
http://jason.svn.sourceforge.net/jason/?rev=1178&view=rev
Author: jomifred
Date: 2008-03-28 11:07:59 -0700 (Fri, 28 Mar 2008)
Log Message:
-----------
body literal extends list term
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/tests/BugVarsInInitBels.java
trunk/applications/jason-moise/example/auction/ag3.asl
trunk/applications/jason-moise/src/jmoise/OrgAgent.java
trunk/src/jason/asSemantics/IntendedMeans.java
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/asSyntax/ArithExpr.java
trunk/src/jason/asSyntax/BinaryStructure.java
trunk/src/jason/asSyntax/BodyLiteral.java
trunk/src/jason/asSyntax/ListTermImpl.java
trunk/src/jason/asSyntax/Plan.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/jason/stdlib/send.java
trunk/src/test/ASParserTest.java
trunk/src/test/PlanTest.java
trunk/src/test/StdLibTest.java
Modified: trunk/applications/as-unit-test/src/jason/tests/BugVarsInInitBels.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/BugVarsInInitBels.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/applications/as-unit-test/src/jason/tests/BugVarsInInitBels.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -17,7 +17,7 @@
// defines the agent's AgentSpeak code
ag.parseAScode(
- "test_rule(A,A). "+
+ "test_rule(A,A). "+ // do not replace A by _ (the test is just the name A for the var)
"!test. "+
"+!test <- A = test_wrong_value; "+
" ?test_rule(T,right_value); "+
Modified: trunk/applications/jason-moise/example/auction/ag3.asl
===================================================================
--- trunk/applications/jason-moise/example/auction/ag3.asl 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/applications/jason-moise/example/auction/ag3.asl 2008-03-28 18:07:59 UTC (rev 1178)
@@ -46,7 +46,7 @@
.send(A,tell,alliance).
// remember the winners
-+goal_state(Sch, winner(W), satisfied)
++goal_state(Sch, winner(W), achieved)
: goal_state(Sch, auction(N), _)
<- +winner(N,W).
-
+
Modified: trunk/applications/jason-moise/src/jmoise/OrgAgent.java
===================================================================
--- trunk/applications/jason-moise/src/jmoise/OrgAgent.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/applications/jason-moise/src/jmoise/OrgAgent.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -309,7 +309,8 @@
if (!u.get(S).equals(gState) || !gap.equals(gilInBB.getTerm(1))) {
if (!getTS().getAg().delBel(gilInBB))
logger.warning("Belief "+gilInBB+" should be deleted, but was not!");
- else if (logger.isLoggable(Level.FINE)) logger.fine("Remove goal belief: " + gil);
+ else
+ if (logger.isLoggable(Level.FINE)) logger.fine("Remove goal belief: " + gil);
}
}
Modified: trunk/src/jason/asSemantics/IntendedMeans.java
===================================================================
--- trunk/src/jason/asSemantics/IntendedMeans.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSemantics/IntendedMeans.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -70,16 +70,18 @@
// used for clone
}
- /** removes the current action of the IM */
- public BodyLiteral removeCurrentStep() {
- if (!plan.getBody().isEmpty())
- return plan.getBody().remove(0);
- else
+ /** removes the current action of the IM and returns the term of the body */
+ public Term removeCurrentStep() {
+ BodyLiteral current = plan.getBody();
+ if (current.isEmpty()) {
return null;
+ } else {
+ return current.remove(0);
+ }
}
public BodyLiteral getCurrentStep() {
- return plan.getBody().get(0);
+ return plan.getBody();
}
@@ -127,9 +129,9 @@
Structure im = new Structure("im");
im.addTerm(new StringTermImpl(plan.getLabel().toString()));
ListTerm lt = new ListTermImpl();
- for (BodyLiteral bd: plan.getBody()) {
- BodyLiteral c = (BodyLiteral)bd.clone();
- c.getLogicalFormula().apply(unif);
+ for (Term bd: plan.getBody()) {
+ Term c = (Term)bd.clone();
+ c.apply(unif);
lt.add(new StringTermImpl(c.toString()));
}
im.addTerm(lt);
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -35,6 +35,7 @@
import jason.asSyntax.LogicalFormula;
import jason.asSyntax.Plan;
import jason.asSyntax.PlanLibrary;
+import jason.asSyntax.Structure;
import jason.asSyntax.Term;
import jason.asSyntax.Trigger;
import jason.asSyntax.Trigger.TEOperator;
@@ -158,15 +159,15 @@
// .send(ag1,askOne, value, X)
// if the answer was tell 3, unifies X=3
// if the answer was untell 3, unifies X=false
- BodyLiteral send = intention.peek().removeCurrentStep();
+ Structure send = (Structure)intention.peek().removeCurrentStep();
if (m.isUnTell()) {
- if (send.getLiteralFormula().getTerm(1).toString().equals("askOne")) {
+ if (send.getTerm(1).toString().equals("askOne")) {
content = Literal.LFalse;
} else { // the .send is askAll
content = new ListTermImpl(); // the answer is an empty list
}
}
- if (intention.peek().getUnif().unifies(send.getLiteralFormula().getTerm(3), content)) {
+ if (intention.peek().getUnif().unifies(send.getTerm(3), content)) {
getC().addIntention(intention);
} else {
conf.C.SI = intention;
@@ -402,12 +403,13 @@
}
Unifier u = im.unif;
BodyLiteral h = im.getCurrentStep();
-
- h.getLogicalFormula().apply(u);
+ Term bTerm = h.getTerm();
+ bTerm.apply(u);
+
Literal body = null;
- if (h.getLogicalFormula() instanceof Literal)
- body = h.getLiteralFormula();
+ if (bTerm instanceof Literal)
+ body = (Literal)bTerm;
switch (h.getType()) {
@@ -446,7 +448,7 @@
break;
case constraint:
- Iterator<Unifier> iu = h.getLogicalFormula().logicalConsequence(ag, u);
+ Iterator<Unifier> iu = ((LogicalFormula)bTerm).logicalConsequence(ag, u);
if (iu.hasNext()) {
im.unif = iu.next();
updateIntention();
@@ -475,7 +477,7 @@
// Rule Test
case test:
- LogicalFormula f = h.getLogicalFormula();
+ LogicalFormula f = (LogicalFormula)bTerm;
if (conf.ag.believes(f, u)) {
updateIntention();
} else {
@@ -633,12 +635,12 @@
im = i.peek(); // +!s or +?s
if (!im.isFinished()) {
// removes !b or ?s
- BodyLiteral g = im.removeCurrentStep();
+ Term g = im.removeCurrentStep();
// make the TE of finished plan ground and unify that
// with goal in the body
Literal tel = topIM.getPlan().getTrigger().getLiteral();
tel.apply(topIM.unif);
- im.unif.unifies(tel, g.getLiteralFormula());
+ im.unif.unifies(tel, g);
}
}
@@ -699,70 +701,7 @@
}
return ap;
}
-
- /*
- class ApplPlanTimeOut extends Thread {
- List<Option> ap = null;
- List<Option> rp = null;
- boolean finish = false;
-
- List<Option> get(List<Option> rp) {
- this.rp = rp;
- start();
- waitEvaluation();
- return ap;
- }
-
- synchronized void waitEvaluation() {
- try {
- if (!finish) {
- wait(3000); // wait 5 seconds for the evaluation!
- if (!finish) {
- logger.warning("*** Evaluation of appl plan do not finish in 3 seconds!"+C+"\bBB="+getAg().getBB());
- }
- }
- finish = true;
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- synchronized void finishEvaluation() {
- finish = true;
- notify();
- }
-
- public void run() {
- for (Option opt: rp) {
- LogicalFormula context = opt.plan.getContext();
- if (context == null) { // context is true
- if (ap == null) ap = new LinkedList<Option>();
- ap.add(opt);
- } else {
- boolean allUnifs = opt.getPlan().isAllUnifs();
- Iterator<Unifier> r = context.logicalConsequence(ag, opt.unif);
- if (r != null) {
- while (r.hasNext()) {
- opt.unif = r.next();
-
- if (ap == null) ap = new LinkedList<Option>();
- ap.add(opt);
-
- if (!allUnifs) break; // returns only the first unification
- if (r.hasNext()) {
- // create a new option for the next loop step
- opt = new Option((Plan)opt.plan.clone(), null);
- }
- }
- }
- }
- }
- finishEvaluation();
- }
- }
- */
-
public void updateEvents(List<Literal>[] result, Intention focus) {
if (result == null) return;
// create the events
Modified: trunk/src/jason/asSyntax/ArithExpr.java
===================================================================
--- trunk/src/jason/asSyntax/ArithExpr.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSyntax/ArithExpr.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -133,7 +133,7 @@
super(oper.toString(),1);
addTerm(t1);
op = oper;
- if (t1 instanceof SourceInfo) setSrc((SourceInfo)t1);
+ setSrc(t1);
}
private ArithExpr(ArithExpr ae) { // for clone
Modified: trunk/src/jason/asSyntax/BinaryStructure.java
===================================================================
--- trunk/src/jason/asSyntax/BinaryStructure.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSyntax/BinaryStructure.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -45,7 +45,7 @@
public BinaryStructure(String id, Term arg) {
super(id,1);
addTerm( arg );
- if (arg instanceof SourceInfo) setSrc((SourceInfo)arg);
+ setSrc(arg);
}
public boolean isUnary() {
Modified: trunk/src/jason/asSyntax/BodyLiteral.java
===================================================================
--- trunk/src/jason/asSyntax/BodyLiteral.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSyntax/BodyLiteral.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -26,8 +26,13 @@
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-/** Represents an item of a plan body (achieve, test, action, ...) */
-public class BodyLiteral extends SourceInfo implements Cloneable {
+/**
+ * Represents a plan body item (achieve, test, action, ...) and its successors,
+ * it is thus like a list term.
+ *
+ * @author Jomi
+ */
+public class BodyLiteral extends ListTermImpl implements Cloneable {
public enum BodyType {
action { public String toString() { return ""; }},
@@ -41,24 +46,15 @@
constraint { public String toString() { return ""; }}
}
- private LogicalFormula formula;
private BodyType formType;
- /** used of actions, internal actions, test goals, achieve goals, adds, removes */
- public BodyLiteral(BodyType t, Literal l) {
- formula = (Literal) l.clone();
- formType = t;
- if (l.isInternalAction())
- formType = BodyType.internalAction;
- setSrc(l);
+ public BodyLiteral() {
}
-
- /** used for test goals and constraints (the argument is a logical formula) */
- public BodyLiteral(BodyType t, LogicalFormula lf) {
- formula = (LogicalFormula) lf.clone();
+
+ public BodyLiteral(BodyType t, Term b) {
+ setTerm(b);
+ setSrc(b);
formType = t;
- if (lf instanceof SourceInfo)
- setSrc((SourceInfo)lf);
}
public BodyType getType() {
@@ -66,40 +62,55 @@
}
public Literal getLiteralFormula() {
- if (formula instanceof Literal)
- return (Literal)formula;
+ Term t = getTerm();
+ if (t instanceof Literal)
+ return (Literal)t;
else
return null;
}
- public LogicalFormula getLogicalFormula() {
- return formula;
- }
-
@Override
public boolean equals(Object o) {
- if (o != null && o instanceof BodyLiteral) {
- BodyLiteral b = (BodyLiteral) o;
- return formType == b.formType && formula.equals(b.formula);
+ if (o == null) return false;
+ if (o == this) return true;
+ if (o instanceof BodyLiteral) {
+ BodyLiteral b = (BodyLiteral)o;
+ return formType == b.formType && super.equals(o);
}
return false;
}
@Override
public int hashCode() {
- return formType.hashCode() + formula.hashCode();
+ return formType.hashCode() + super.hashCode();
}
public Object clone() {
- if (formType == BodyType.test || formType == BodyType.constraint) {
- return new BodyLiteral(formType, formula);
+ BodyLiteral c;
+ Term t = getTerm();
+ if (t == null) { // empty body
+ c = new BodyLiteral();
} else {
- return new BodyLiteral(formType, (Literal)formula);
+ c = new BodyLiteral(formType, (Term)t.clone());
+ c.setNext((Term)getNext().clone());
}
+ return c;
}
+ @Override
+ protected void setValuesFrom(ListTerm lt) {
+ super.setValuesFrom(lt);
+ formType = ((BodyLiteral)lt).formType;
+ }
+
+
public String toString() {
- return formType + formula.toString();
+ if (isEmpty())
+ return "";
+ else if (getNext().isEmpty())
+ return formType.toString() + getTerm() + ".";
+ else
+ return formType.toString() + getTerm() + "; " + getNext();
}
/** get as XML */
@@ -108,7 +119,7 @@
if (formType.toString().length() > 0) {
u.setAttribute("type", formType.toString());
}
- u.appendChild(formula.getAsDOM(document));
+ u.appendChild( ((Structure)getTerm()).getAsDOM(document));
return u;
}
}
Modified: trunk/src/jason/asSyntax/ListTermImpl.java
===================================================================
--- trunk/src/jason/asSyntax/ListTermImpl.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSyntax/ListTermImpl.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -127,10 +127,10 @@
}
public ListTerm getNext() {
- try {
+ if (next instanceof ListTerm)
return (ListTerm)next;
- } catch (Exception e){}
- return null;
+ else
+ return null;
}
@@ -544,12 +544,16 @@
};
}
+ protected void setValuesFrom(ListTerm lt) {
+ this.term = lt.getTerm();
+ this.next = lt.getNext();
+ }
+
public Term remove(int index) {
if (index == 0) {
Term bt = this.term;
if (getNext() != null) {
- this.term = getNext().getTerm();
- this.next = (Term)getNext().getNext();
+ setValuesFrom(getNext());
} else {
clear();
}
@@ -563,8 +567,7 @@
public boolean remove(Object o) {
if (term != null && term.equals(o)) {
if (getNext() != null) {
- this.term = getNext().getTerm();
- this.next = (Term)getNext().getNext();
+ setValuesFrom(getNext());
} else {
clear();
}
Modified: trunk/src/jason/asSyntax/Plan.java
===================================================================
--- trunk/src/jason/asSyntax/Plan.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSyntax/Plan.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -29,10 +29,8 @@
import java.io.Serializable;
import java.io.StringReader;
import java.util.ArrayList;
-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.logging.Level;
@@ -54,8 +52,9 @@
private Pred label = null;
private Trigger tevent = null;
private LogicalFormula context;
- private List<BodyLiteral> body;
+ private BodyLiteral body;
+
private boolean isAtomic = false;
private boolean isAllUnifs = false;
private boolean hasBreakpoint = false;
@@ -65,12 +64,12 @@
}
// used by parser
- public Plan(Pred label, Trigger te, LogicalFormula ct, List<BodyLiteral> bd) {
+ public Plan(Pred label, Trigger te, LogicalFormula ct, BodyLiteral bd) {
tevent = te;
setLabel(label);
setContext(ct);
if (bd == null)
- body = Collections.emptyList();
+ body = new BodyLiteral();
else
body = bd;
}
@@ -123,7 +122,7 @@
return context;
}
- public List<BodyLiteral> getBody() {
+ public BodyLiteral getBody() {
return body;
}
@@ -170,9 +169,7 @@
tevent.getLiteral().countVars(all);
if (context != null)
context.countVars(all);
- if (body != null)
- for (BodyLiteral bl: body)
- bl.getLogicalFormula().countVars(all);
+ body.countVars(all);
List<VarTerm> r = new ArrayList<VarTerm>();
for (VarTerm k: all.keySet()) {
@@ -187,7 +184,7 @@
int code = 37;
if (context != null) code += context.hashCode();
if (tevent != null) code += tevent.hashCode();
- if (body != null) code += body.hashCode();
+ code += body.hashCode();
return code;
}
@@ -205,10 +202,7 @@
if (context != null)
p.context = (LogicalFormula)context.clone();
- p.body = new LinkedList<BodyLiteral>(); // the plan will be "consumed" by remove(0), so linkedlist
- for (BodyLiteral l : body) {
- p.body.add((BodyLiteral) l.clone());
- }
+ p.body = (BodyLiteral)body.clone();
p.setSrc(this);
@@ -226,39 +220,22 @@
p.tevent = (Trigger)tevent.clone();
p.context = context;
+ p.body = (BodyLiteral)body.clone();
- p.body = new LinkedList<BodyLiteral>(); // the plan will be "consumed" by remove(0), so linkedlist
- for (BodyLiteral l : body) {
- p.body.add((BodyLiteral) l.clone());
- }
-
p.setSrc(this);
return p;
}
- private String listToString(List<BodyLiteral> l, String separator) {
- StringBuffer s = new StringBuffer();
- Iterator<BodyLiteral> i = l.iterator();
- while (i.hasNext()) {
- s.append(i.next().toString());
- if (i.hasNext()) {
- s.append(separator);
- }
- }
- return s.toString();
- }
-
public String toString() {
return toASString();
}
/** returns this plan in a string complaint with AS syntax */
public String toASString() {
- return (((label == null) ? "" : "@" + label + " ") +
- tevent + ((context == null) ? "" : " : " + context) +
- ((body.size() == 0) ? "" : " <- " + listToString(body, "; ")) +
- ".");
+ return ((label == null) ? "" : "@" + label + " ") +
+ tevent + ((context == null) ? "" : " : " + context) +
+ " <- " + body;
}
/** get as XML */
@@ -279,8 +256,9 @@
if (body.size() > 0) {
Element eb = (Element) document.createElement("body");
- for (BodyLiteral bl : body) {
- eb.appendChild(bl.getAsDOM(document));
+ Iterator<ListTerm> i = body.listTermIterator();
+ while (i.hasNext()) {
+ eb.appendChild(i.next().getAsDOM(document));
}
u.appendChild(eb);
}
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-28 18:07:59 UTC (rev 1178)
@@ -287,13 +287,13 @@
/* Plan */
Plan plan() : { Token k; Pred L = null;
Trigger T; Object C = null;
- ArrayList B = new ArrayList();
+ BodyLiteral B = null;
int start = -1, end;}
{
[ k = <TK_LABEL_AT> L=pred() { start = k.beginLine; } ]
T=trigger()
[ k = ":" C=log_expr() { if (start == -1) start = k.beginLine; } ]
- [ k = "<-" plan_body(B) { if (start == -1) start = k.beginLine; } ]
+ [ k = "<-" B = plan_body() { if (start == -1) start = k.beginLine; } ]
k = "." { if (start == -1) start = k.beginLine; }
{ end = k.beginLine;
InternalActionLiteral ial = null;
@@ -303,8 +303,9 @@
Plan p = new Plan(L,T,(LogicalFormula)C,B);
p.setSrcLines(start,end);
p.setSrc(asSource);
- return p;}
+ return p;
}
+}
/* Trigger */
Trigger trigger() :
@@ -351,14 +352,19 @@
/* Plan body */
-void plan_body(List bd) : { BodyLiteral F; }
+BodyLiteral plan_body() : { BodyLiteral F; BodyLiteral R = null; }
{
- F=body_formula() { if (! F.getLogicalFormula().equals(Literal.LTrue)) {
- bd.add(F);
- }
+ F = body_formula()
+
+ [ ";" R = plan_body() ]
+ { if (F.getTerm().equals(Literal.LTrue))
+ return R;
+ if (R == null)
+ F.setNext(new BodyLiteral());
+ else
+ F.setNext(R);
+ return F;
}
-
- [ ";" plan_body(bd) ]
}
@@ -377,13 +383,15 @@
B = log_expr()
{ if (B instanceof Literal) {
+ if ( ((Literal)B).isInternalAction() )
+ formType = BodyType.internalAction;
return new BodyLiteral(formType, (Literal)B);
} else if (formType == BodyType.action && B instanceof RelExpr) {
return new BodyLiteral(BodyType.constraint, (RelExpr)B); // constraint
} else {
if (formType == BodyType.test) {
if (B instanceof LogicalFormula)
- return new BodyLiteral(BodyType.test, (LogicalFormula)B); // used in ?(a & b)
+ return new BodyLiteral(BodyType.test, (Term)B); // used in ?(a & b)
else
throw new ParseException(getSourceRef(B)+" The argument for ? is not a logical formula.");
} else {
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -314,7 +314,7 @@
final public Plan plan() throws ParseException {
Token k; Pred L = null;
Trigger T; Object C = null;
- ArrayList B = new ArrayList();
+ BodyLiteral B = null;
int start = -1, end;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case TK_LABEL_AT:
@@ -340,7 +340,7 @@
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 33:
k = jj_consume_token(33);
- plan_body(B);
+ B = plan_body();
if (start == -1) start = k.beginLine;
break;
default:
@@ -469,21 +469,26 @@
}
/* Plan body */
- final public void plan_body(List bd) throws ParseException {
- BodyLiteral F;
+ final public BodyLiteral plan_body() throws ParseException {
+ BodyLiteral F; BodyLiteral R = null;
F = body_formula();
- if (! F.getLogicalFormula().equals(Literal.LTrue)) {
- bd.add(F);
- }
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 37:
jj_consume_token(37);
- plan_body(bd);
+ R = plan_body();
break;
default:
jj_la1[19] = jj_gen;
;
}
+ if (F.getTerm().equals(Literal.LTrue))
+ {if (true) return R;}
+ if (R == null)
+ F.setNext(new BodyLiteral());
+ else
+ F.setNext(R);
+ {if (true) return F;}
+ throw new Error("Missing return statement in function");
}
final public BodyLiteral body_formula() throws ParseException {
@@ -536,13 +541,15 @@
}
B = log_expr();
if (B instanceof Literal) {
+ if ( ((Literal)B).isInternalAction() )
+ formType = BodyType.internalAction;
{if (true) return new BodyLiteral(formType, (Literal)B);}
} else if (formType == BodyType.action && B instanceof RelExpr) {
{if (true) return new BodyLiteral(BodyType.constraint, (RelExpr)B);} // constraint
} else {
if (formType == BodyType.test) {
if (B instanceof LogicalFormula)
- {if (true) return new BodyLiteral(BodyType.test, (LogicalFormula)B);} // used in ?(a & b)
+ {if (true) return new BodyLiteral(BodyType.test, (Term)B);} // used in ?(a & b)
else
{if (true) throw new ParseException(getSourceRef(B)+" The argument for ? is not a logical formula.");}
} else {
@@ -1156,6 +1163,11 @@
finally { jj_save(0, xla); }
}
+ final private boolean jj_3R_12() {
+ if (jj_scan_token(39)) return true;
+ return false;
+ }
+
final private boolean jj_3_1() {
if (jj_scan_token(27)) return true;
if (jj_scan_token(TK_BEGIN)) return true;
@@ -1191,11 +1203,6 @@
return false;
}
- final private boolean jj_3R_12() {
- if (jj_scan_token(39)) return true;
- return false;
- }
-
public as2jTokenManager token_source;
SimpleCharStream jj_input_stream;
public Token token, jj_nt;
Modified: trunk/src/jason/stdlib/send.java
===================================================================
--- trunk/src/jason/stdlib/send.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/stdlib/send.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -31,7 +31,6 @@
import jason.asSemantics.Message;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
-import jason.asSyntax.BodyLiteral;
import jason.asSyntax.ListTerm;
import jason.asSyntax.NumberTerm;
import jason.asSyntax.Pred;
@@ -238,8 +237,8 @@
Intention intention = c.getPendingIntentions().remove(idInPending);
if (intention != null) {
// unify "timeout" with the fourth parameter of .send
- BodyLiteral send = intention.peek().removeCurrentStep();
- intention.peek().getUnif().unifies(send.getLiteralFormula().getTerm(3), timeoutTerm);
+ Structure send = (Structure)intention.peek().removeCurrentStep();
+ intention.peek().getUnif().unifies(send.getTerm(3), timeoutTerm);
// add the intention back in C.I
c.addIntention(intention);
}
Modified: trunk/src/test/ASParserTest.java
===================================================================
--- trunk/src/test/ASParserTest.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/test/ASParserTest.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -40,7 +40,7 @@
assertTrue(ag.parseAS("examples/auction/ag1.asl"));
Plan p = ag.getPL().get("l__0");
assertEquals(p.getBody().size(), 1);
- assertEquals(p.getBody().get(0).getType(), BodyLiteral.BodyType.internalAction);
+ assertEquals(((BodyLiteral)p.getBody()).getType(), BodyLiteral.BodyType.internalAction);
assertTrue(ag.parseAS("examples/auction/ag2.asl"));
assertTrue(ag.parseAS("examples/auction/ag3.asl"));
}
Modified: trunk/src/test/PlanTest.java
======================================...
[truncated message content] |
|
From: <jom...@us...> - 2008-03-29 23:55:57
|
Revision: 1179
http://jason.svn.sourceforge.net/jason/?rev=1179&view=rev
Author: jomifred
Date: 2008-03-29 16:55:50 -0700 (Sat, 29 Mar 2008)
Log Message:
-----------
first implementation of body plan as term
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java
trunk/applications/as-unit-test/src/jason/asunit/TestArch.java
trunk/applications/as-unit-test/src/jason/tests/TestAll.java
trunk/src/jason/asSyntax/BodyLiteral.java
trunk/src/jason/asSyntax/DefaultTerm.java
trunk/src/jason/asSyntax/InternalActionLiteral.java
trunk/src/jason/asSyntax/ListTermImpl.java
trunk/src/jason/asSyntax/Plan.java
trunk/src/jason/asSyntax/Term.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/jason/jeditplugin/JasonID.java
trunk/src/test/ASParserTest.java
trunk/src/test/PlanTest.java
Added Paths:
-----------
trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java
Modified: trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -166,7 +166,6 @@
public void assertAct(final Structure act, final int maxCycles) {
Condition c = new Condition() {
public boolean test(TestArch arch) {
- //System.out.println(arch.getCycle() + " " + arch.getActions()+ getTS().getC().getFeedbackActions());
return arch.getActions().contains(act);
}
};
Modified: trunk/applications/as-unit-test/src/jason/asunit/TestArch.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/asunit/TestArch.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/applications/as-unit-test/src/jason/asunit/TestArch.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -5,6 +5,8 @@
import jason.asSemantics.ActionExec;
import jason.asSyntax.Literal;
import jason.asSyntax.Structure;
+import jason.asSyntax.Term;
+import jason.asSyntax.VarTerm;
import jason.environment.Environment;
import jason.infra.centralised.CentralisedAgArch;
import jason.infra.centralised.CentralisedEnvironment;
@@ -83,9 +85,18 @@
@Override
public void act(ActionExec action, List<ActionExec> feedback) {
+ Term t = action.getActionTerm();
+ if (t instanceof VarTerm) {
+ t = ((VarTerm)t).getValue();
+ }
actions.add(action.getActionTerm());
- if (getEnvInfraTier() != null)
+ System.out.println("*"+action.getActionTerm().getClass().getName()+" "+t.getClass().getName());
+ if (getEnvInfraTier() != null) {
super.act(action, feedback); //env.scheduleAction(getAgName(), action.getActionTerm(), action);
+ } else {
+ action.setResult(true);
+ feedback.add(action);
+ }
}
public void print(String s) {
Modified: trunk/applications/as-unit-test/src/jason/tests/TestAll.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestAll.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/applications/as-unit-test/src/jason/tests/TestAll.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -9,6 +9,7 @@
BugVarsInInitBels.class,
TestAddLogExprInBB.class,
TestKQML.class,
- TestVarInContext.class
+ TestVarInContext.class,
+ TestPlanbodyAsTerm.class
})
public class TestAll { }
Added: trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java (rev 0)
+++ trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -0,0 +1,34 @@
+package jason.tests;
+
+import jason.asunit.TestAgent;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestPlanbodyAsTerm {
+
+ TestAgent ag;
+
+ // initialisation of the agent test
+ @Before
+ public void setupAg() {
+ ag = new TestAgent();
+
+ // defines the agent's AgentSpeak code
+ ag.parseAScode(
+ "+!start <- +g(a; b; c); ?g(X); !g(X). "+
+ "+!g(A; R) <- A; !g(R). "+
+ "+!g(A) <- .print(A); A; .print(end)."
+ );
+ }
+
+ @Test
+ public void testProgram() {
+ ag.addGoal("start");
+ ag.assertBel("g(a;b;c)", 5);
+ ag.assertAct("a", 4);
+ ag.assertAct("b", 4);
+ ag.assertAct("c", 4);
+ }
+
+}
Modified: trunk/src/jason/asSyntax/BodyLiteral.java
===================================================================
--- trunk/src/jason/asSyntax/BodyLiteral.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/asSyntax/BodyLiteral.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -1,40 +1,14 @@
-//----------------------------------------------------------------------------
-// Copyright (C) 2003 Rafael H. Bordini, Jomi F. Hubner, et al.
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// To contact the authors:
-// http://www.dur.ac.uk/r.bordini
-// http://www.inf.furb.br/~jomi
-//
-//----------------------------------------------------------------------------
-
package jason.asSyntax;
+import java.util.Iterator;
+
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-/**
- * Represents a plan body item (achieve, test, action, ...) and its successors,
- * it is thus like a list term.
- *
- * @author Jomi
- */
-public class BodyLiteral extends ListTermImpl implements Cloneable {
+public class BodyLiteral extends Structure implements Iterable<BodyLiteral> {
public enum BodyType {
+ none { public String toString() { return ""; }},
action { public String toString() { return ""; }},
internalAction { public String toString() { return ""; }},
achieve { public String toString() { return "!"; }},
@@ -46,28 +20,100 @@
constraint { public String toString() { return ""; }}
}
- private BodyType formType;
+ public static final String BODY_PLAN_FUNCTOR = ";";
+
+ private Term term = null;
+ private BodyLiteral next = null;
+ private BodyType formType = BodyType.none;
+ /** constructor for empty plan body */
public BodyLiteral() {
+ super(BODY_PLAN_FUNCTOR, 0);
}
public BodyLiteral(BodyType t, Term b) {
- setTerm(b);
+ super(BODY_PLAN_FUNCTOR, 0);
+ term = b;
+ formType = t;
setSrc(b);
- formType = t;
}
+ public void setNext(BodyLiteral next) {
+ this.next = next;
+ }
+ public BodyLiteral getNext() {
+ return next;
+ }
+
+ public boolean isEmpty() {
+ return term == null;
+ }
+
public BodyType getType() {
return formType;
}
-
+
+ public Term getTerm() {
+ return term;
+ }
+
public Literal getLiteralFormula() {
- Term t = getTerm();
- if (t instanceof Literal)
- return (Literal)t;
+ if (term instanceof Literal)
+ return (Literal)term;
else
return null;
}
+
+ public Iterator<BodyLiteral> iterator() {
+ return new Iterator<BodyLiteral>() {
+ BodyLiteral current = BodyLiteral.this;
+ public boolean hasNext() {
+ return current != null && current.term != null && current.next != null;
+ }
+ public BodyLiteral next() {
+ BodyLiteral r = current;
+ if (current != null)
+ current = current.next;
+ return r;
+ }
+ public void remove() { }
+ };
+ }
+
+ // Override some structure methods to work with unification/equals
+ @Override
+ public int getArity() {
+ if (term == null)
+ return 0;
+ else if (next == null)
+ return 1;
+ else
+ return 2;
+ }
+
+ @Override
+ public Term getTerm(int i) {
+ if (i == 0) return term;
+ if (i == 1) {
+ if (next != null && next.term.isVar() && next.next == null)
+ // if next is the last VAR, return that var
+ return next.term;
+ else
+ return next;
+ }
+ return null;
+ }
+
+ @Override
+ public void setTerm(int i, Term t) {
+ if (i == 0) term = t;
+ if (i == 1) System.out.println("Should not set next of body literal!");
+ }
+
+ @Override
+ public boolean isPlanBody() {
+ return true;
+ }
@Override
public boolean equals(Object o) {
@@ -81,36 +127,82 @@
}
@Override
- public int hashCode() {
- return formType.hashCode() + super.hashCode();
+ public int calcHashCode() {
+ return formType.hashCode() + super.calcHashCode();
}
- public Object clone() {
- BodyLiteral c;
- Term t = getTerm();
- if (t == null) { // empty body
- c = new BodyLiteral();
- } else {
- c = new BodyLiteral(formType, (Term)t.clone());
- c.setNext((Term)getNext().clone());
+ public boolean add(BodyLiteral bl) {
+ if (term == null)
+ swap(bl);
+ else if (next == null)
+ next = bl;
+ else
+ next.add(bl);
+ return true;
+ }
+
+ public boolean add(int index, BodyLiteral bl) {
+ if (index == 0) {
+ swap(bl);
+ this.next = bl;
+ } else {
+ next.add(index - 1, bl);
}
- return c;
+ return true;
}
- @Override
- protected void setValuesFrom(ListTerm lt) {
- super.setValuesFrom(lt);
- formType = ((BodyLiteral)lt).formType;
+ public Term remove(int index) {
+ if (index == 0) {
+ if (next == null) {
+ term = null; // becomes an empty
+ } else {
+ Term oldvalue = term;
+ swap(next); // get values of text
+ next = next.next;
+ return oldvalue;
+ }
+ return this;
+ } else {
+ return next.remove(index - 1);
+ }
}
+
+ public int size() {
+ if (term == null)
+ return 0;
+ else if (next == null)
+ return 1;
+ else
+ return next.size() + 1;
+ }
+
+ private void swap(BodyLiteral bl) {
+ BodyType bt = this.formType;
+ this.formType = bl.formType;
+ bl.formType = bt;
+
+ Term l = this.term;
+ this.term = bl.term;
+ bl.term = l;
+ }
+
+ public Object clone() {
+ if (term == null) // empty
+ return new BodyLiteral();
+
+ BodyLiteral c = new BodyLiteral(formType, (Term)term.clone());
+ if (next != null)
+ c.setNext((BodyLiteral)getNext().clone());
+ return c;
+ }
-
public String toString() {
- if (isEmpty())
+ if (term == null)
return "";
- else if (getNext().isEmpty())
- return formType.toString() + getTerm() + ".";
+ else if (next == null)
+ return formType.toString() + term;
else
- return formType.toString() + getTerm() + "; " + getNext();
+ return formType.toString() + term + "; " + next;
}
/** get as XML */
@@ -119,7 +211,7 @@
if (formType.toString().length() > 0) {
u.setAttribute("type", formType.toString());
}
- u.appendChild( ((Structure)getTerm()).getAsDOM(document));
+ u.appendChild( ((Structure)term).getAsDOM(document));
return u;
}
-}
+}
\ No newline at end of file
Modified: trunk/src/jason/asSyntax/DefaultTerm.java
===================================================================
--- trunk/src/jason/asSyntax/DefaultTerm.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/asSyntax/DefaultTerm.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -63,6 +63,7 @@
public boolean isPred() { return false; }
public boolean isStructure() { return false; }
public boolean isAtom() { return false; }
+ public boolean isPlanBody() { return false; }
public boolean isGround() { return true; }
public boolean hasVar(VarTerm t) { return false; }
Modified: trunk/src/jason/asSyntax/InternalActionLiteral.java
===================================================================
--- trunk/src/jason/asSyntax/InternalActionLiteral.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/asSyntax/InternalActionLiteral.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -117,7 +117,7 @@
public Object clone() {
InternalActionLiteral c = new InternalActionLiteral(this);
c.predicateIndicatorCache = this.predicateIndicatorCache;
- c.hashCodeCache = this.hashCodeCache;
+ c.hashCodeCache = this.hashCodeCache;
return c;
}
Modified: trunk/src/jason/asSyntax/ListTermImpl.java
===================================================================
--- trunk/src/jason/asSyntax/ListTermImpl.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/asSyntax/ListTermImpl.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -280,8 +280,7 @@
*/
public ListTerm concat(ListTerm lt) {
if (isEmpty()) {
- term = lt.getTerm();
- next = (Term)lt.getNext();
+ setValuesFrom(lt);
} else if (((ListTerm)next).isEmpty() ) {
next = (Term)lt;
} else {
@@ -420,7 +419,7 @@
public void add(int index, Term o) {
if (index == 0) {
- ListTermImpl n = new ListTermImpl(term,next);
+ ListTerm n = new ListTermImpl(term,next);
this.term = o;
this.next = n;
} else if (index > 0 && getNext() != null) {
Modified: trunk/src/jason/asSyntax/Plan.java
===================================================================
--- trunk/src/jason/asSyntax/Plan.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/asSyntax/Plan.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -30,7 +30,6 @@
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
@@ -235,7 +234,8 @@
public String toASString() {
return ((label == null) ? "" : "@" + label + " ") +
tevent + ((context == null) ? "" : " : " + context) +
- " <- " + body;
+ (body.isEmpty() ? "" : " <- " + body) +
+ ".";
}
/** get as XML */
@@ -256,10 +256,15 @@
if (body.size() > 0) {
Element eb = (Element) document.createElement("body");
+ for (BodyLiteral bl: body) {
+ eb.appendChild(bl.getAsDOM(document));
+ }
+ /*
Iterator<ListTerm> i = body.listTermIterator();
while (i.hasNext()) {
eb.appendChild(i.next().getAsDOM(document));
}
+ */
u.appendChild(eb);
}
Modified: trunk/src/jason/asSyntax/Term.java
===================================================================
--- trunk/src/jason/asSyntax/Term.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/asSyntax/Term.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -35,6 +35,8 @@
public boolean isAtom();
+ public boolean isPlanBody();
+
public boolean hasVar(VarTerm t);
public void countVars(Map<VarTerm, Integer> c);
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-29 23:55:50 UTC (rev 1179)
@@ -171,7 +171,7 @@
Literal g;
Plan p;
curAg = a;
- if (a != null) asSource = a.getASLSrc();
+ if (a != null && a.getASLSrc() != null) asSource = a.getASLSrc();
boolean endDir = false;
}
{
@@ -229,6 +229,7 @@
{
Pred dir = null;
Agent resultOfDirective = null;
+ Agent bakAg = curAg;
boolean isEOF = false;
}
{
@@ -253,6 +254,7 @@
// import bels, plans and initial goals from agent resultOfDirective
outerAg.importComponents(resultOfDirective);
}
+ curAg = bakAg;
return false;
}
}
@@ -286,13 +288,14 @@
/* Plan */
Plan plan() : { Token k; Pred L = null;
- Trigger T; Object C = null;
- BodyLiteral B = null;
+ Trigger T;
+ Object C = null; BodyLiteral bl = null;
+ Object B = null;
int start = -1, end;}
{
[ k = <TK_LABEL_AT> L=pred() { start = k.beginLine; } ]
T=trigger()
- [ k = ":" C=log_expr() { if (start == -1) start = k.beginLine; } ]
+ [ k = ":" C = log_expr() { if (start == -1) start = k.beginLine; } ]
[ k = "<-" B = plan_body() { if (start == -1) start = k.beginLine; } ]
k = "." { if (start == -1) start = k.beginLine; }
{ end = k.beginLine;
@@ -300,7 +303,14 @@
try { ial = checkInternalActionsInContext((LogicalFormula)C, curAg); } catch (Exception e) {}
if (ial != null)
throw new ParseException(getSourceRef(ial)+" The internal action '"+ial+"' can not be used in plan's context!");
- Plan p = new Plan(L,T,(LogicalFormula)C,B);
+ if (B != null) {
+ if (!(B instanceof BodyLiteral))
+ throw new ParseException(getSourceRef(B)+" Unknown body formula:"+B);
+ bl = (BodyLiteral)B;
+ if (bl.getTerm().equals(Literal.LTrue))
+ bl = (BodyLiteral)bl.getNext();
+ }
+ Plan p = new Plan(L,T,(LogicalFormula)C, bl);
p.setSrcLines(start,end);
p.setSrc(asSource);
return p;
@@ -352,23 +362,22 @@
/* Plan body */
-BodyLiteral plan_body() : { BodyLiteral F; BodyLiteral R = null; }
+Object plan_body() : { Object F; Object R = null; }
{
F = body_formula()
- [ ";" R = plan_body() ]
- { if (F.getTerm().equals(Literal.LTrue))
- return R;
- if (R == null)
- F.setNext(new BodyLiteral());
- else
- F.setNext(R);
+ [ ";" { if (!(F instanceof BodyLiteral)) throw new ParseException(getSourceRef(F)+" "+F+" is not a body literal!"); }
+ R = plan_body() { if (!(R instanceof BodyLiteral)) throw new ParseException(getSourceRef(R)+" "+R+" is not a body literal!"); }
+ ]
+ { if (F instanceof BodyLiteral && R instanceof BodyLiteral) {
+ ((BodyLiteral)F).setNext( (BodyLiteral)R );
+ }
return F;
}
}
-BodyLiteral body_formula() :
+Object body_formula() :
{ BodyType formType = BodyType.action; Object B; }
{
[ "!" { formType = BodyType.achieve; }
@@ -395,7 +404,7 @@
else
throw new ParseException(getSourceRef(B)+" The argument for ? is not a logical formula.");
} else {
- throw new ParseException(getSourceRef(B)+" Unknown body formula.");
+ return B;
}
}
}
@@ -440,9 +449,17 @@
Term term() : { Object o;}
{
( o=list()
- | o=log_expr() // log expr includes literals/atoms/structures
+ | o=plan_body() // plan_body includes literals/atoms/structures
)
- { return changeToAtom(o); }
+ { // if the result is a BodyLiteral action with size = 1, it is indeed a literal and not a body literal
+ if (o instanceof BodyLiteral) {
+ BodyLiteral bl = (BodyLiteral)o;
+ if (bl.getType() == BodyType.action && bl.size() == 1) {
+ o = bl.getTerm();
+ }
+ }
+ return changeToAtom(o);
+ }
}
@@ -462,7 +479,7 @@
"]" { return lt; }
}
-// term_in_list is the same as term, but log_expr must be enclosed by "("....")" to avoid problem with |
+// term_in_list is the same as term, but log_expr/plan_body must be enclosed by "("....")" to avoid problem with |
Term term_in_list() : { Object o; }
{
( o=list()
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -89,7 +89,7 @@
Literal g;
Plan p;
curAg = a;
- if (a != null) asSource = a.getASLSrc();
+ if (a != null && a.getASLSrc() != null) asSource = a.getASLSrc();
boolean endDir = false;
label_1:
while (true) {
@@ -237,6 +237,7 @@
final public boolean directive(Agent outerAg) throws ParseException, jason.JasonException {
Pred dir = null;
Agent resultOfDirective = null;
+ Agent bakAg = curAg;
boolean isEOF = false;
if (jj_2_1(4)) {
jj_consume_token(27);
@@ -270,6 +271,7 @@
// import bels, plans and initial goals from agent resultOfDirective
outerAg.importComponents(resultOfDirective);
}
+ curAg = bakAg;
{if (true) return false;}
throw new Error("Missing return statement in function");
}
@@ -313,8 +315,9 @@
/* Plan */
final public Plan plan() throws ParseException {
Token k; Pred L = null;
- Trigger T; Object C = null;
- BodyLiteral B = null;
+ Trigger T;
+ Object C = null; BodyLiteral bl = null;
+ Object B = null;
int start = -1, end;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case TK_LABEL_AT:
@@ -354,7 +357,14 @@
try { ial = checkInternalActionsInContext((LogicalFormula)C, curAg); } catch (Exception e) {}
if (ial != null)
{if (true) throw new ParseException(getSourceRef(ial)+" The internal action '"+ial+"' can not be used in plan's context!");}
- Plan p = new Plan(L,T,(LogicalFormula)C,B);
+ if (B != null) {
+ if (!(B instanceof BodyLiteral))
+ {if (true) throw new ParseException(getSourceRef(B)+" Unknown body formula:"+B);}
+ bl = (BodyLiteral)B;
+ if (bl.getTerm().equals(Literal.LTrue))
+ bl = (BodyLiteral)bl.getNext();
+ }
+ Plan p = new Plan(L,T,(LogicalFormula)C, bl);
p.setSrcLines(start,end);
p.setSrc(asSource);
{if (true) return p;}
@@ -469,29 +479,28 @@
}
/* Plan body */
- final public BodyLiteral plan_body() throws ParseException {
- BodyLiteral F; BodyLiteral R = null;
+ final public Object plan_body() throws ParseException {
+ Object F; Object R = null;
F = body_formula();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 37:
jj_consume_token(37);
+ if (!(F instanceof BodyLiteral)) {if (true) throw new ParseException(getSourceRef(F)+" "+F+" is not a body literal!");}
R = plan_body();
+ if (!(R instanceof BodyLiteral)) {if (true) throw new ParseException(getSourceRef(R)+" "+R+" is not a body literal!");}
break;
default:
jj_la1[19] = jj_gen;
;
}
- if (F.getTerm().equals(Literal.LTrue))
- {if (true) return R;}
- if (R == null)
- F.setNext(new BodyLiteral());
- else
- F.setNext(R);
+ if (F instanceof BodyLiteral && R instanceof BodyLiteral) {
+ ((BodyLiteral)F).setNext( (BodyLiteral)R );
+ }
{if (true) return F;}
throw new Error("Missing return statement in function");
}
- final public BodyLiteral body_formula() throws ParseException {
+ final public Object body_formula() throws ParseException {
BodyType formType = BodyType.action; Object B;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 31:
@@ -553,7 +562,7 @@
else
{if (true) throw new ParseException(getSourceRef(B)+" The argument for ? is not a logical formula.");}
} else {
- {if (true) throw new ParseException(getSourceRef(B)+" Unknown body formula.");}
+ {if (true) return B;}
}
}
throw new Error("Missing return statement in function");
@@ -644,15 +653,26 @@
case STRING:
case ATOM:
case UNNAMEDVAR:
+ case 31:
+ case 34:
case 35:
+ case 36:
+ case 38:
case 39:
- o = log_expr();
+ o = plan_body();
break;
default:
jj_la1[27] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
+ // if the result is a BodyLiteral action with size = 1, it is indeed a literal and not a body literal
+ if (o instanceof BodyLiteral) {
+ BodyLiteral bl = (BodyLiteral)o;
+ if (bl.getType() == BodyType.action && bl.size() == 1) {
+ o = bl.getTerm();
+ }
+ }
{if (true) return changeToAtom(o);}
throw new Error("Missing return statement in function");
}
@@ -726,7 +746,7 @@
throw new Error("Missing return statement in function");
}
-// term_in_list is the same as term, but log_expr must be enclosed by "("....")" to avoid problem with |
+// term_in_list is the same as term, but log_expr/plan_body must be enclosed by "("....")" to avoid problem with |
final public Term term_in_list() throws ParseException {
Object o;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
@@ -1163,11 +1183,6 @@
finally { jj_save(0, xla); }
}
- final private boolean jj_3R_12() {
- if (jj_scan_token(39)) return true;
- return false;
- }
-
final private boolean jj_3_1() {
if (jj_scan_token(27)) return true;
if (jj_scan_token(TK_BEGIN)) return true;
@@ -1176,6 +1191,16 @@
return false;
}
+ final private boolean jj_3R_14() {
+ if (jj_scan_token(42)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_12() {
+ if (jj_scan_token(39)) return true;
+ return false;
+ }
+
final private boolean jj_3R_11() {
Token xsp;
xsp = jj_scanpos;
@@ -1193,11 +1218,6 @@
return false;
}
- final private boolean jj_3R_14() {
- if (jj_scan_token(42)) return true;
- return false;
- }
-
final private boolean jj_3R_13() {
if (jj_3R_14()) retur...
[truncated message content] |
|
From: <jom...@us...> - 2008-03-30 14:25:07
|
Revision: 1180
http://jason.svn.sourceforge.net/jason/?rev=1180&view=rev
Author: jomifred
Date: 2008-03-30 07:24:59 -0700 (Sun, 30 Mar 2008)
Log Message:
-----------
variables can be unified with BodyLiteral
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/asunit/TestArch.java
trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java
trunk/demos/directives/myp/LoggerDirective.java
trunk/demos/failure/a.asl
trunk/src/jason/asSemantics/ActionExec.java
trunk/src/jason/asSemantics/IntendedMeans.java
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/asSyntax/BodyLiteral.java
trunk/src/jason/asSyntax/Plan.java
trunk/src/jason/asSyntax/Term.java
trunk/src/jason/asSyntax/VarTerm.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/jason/asSyntax/patterns/goal/DG.java
trunk/src/jason/asSyntax/patterns/goal/EBDG.java
trunk/src/jason/stdlib/wait.java
trunk/src/test/ASParserTest.java
trunk/src/test/PlanTest.java
trunk/src/xml/agInspection.xsl
trunk/src/xml/asl2html.xsl
Added Paths:
-----------
trunk/src/jason/asSyntax/BodyLiteralImpl.java
Modified: trunk/applications/as-unit-test/src/jason/asunit/TestArch.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/asunit/TestArch.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/applications/as-unit-test/src/jason/asunit/TestArch.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -5,8 +5,6 @@
import jason.asSemantics.ActionExec;
import jason.asSyntax.Literal;
import jason.asSyntax.Structure;
-import jason.asSyntax.Term;
-import jason.asSyntax.VarTerm;
import jason.environment.Environment;
import jason.infra.centralised.CentralisedAgArch;
import jason.infra.centralised.CentralisedEnvironment;
@@ -85,12 +83,7 @@
@Override
public void act(ActionExec action, List<ActionExec> feedback) {
- Term t = action.getActionTerm();
- if (t instanceof VarTerm) {
- t = ((VarTerm)t).getValue();
- }
- actions.add(action.getActionTerm());
- System.out.println("*"+action.getActionTerm().getClass().getName()+" "+t.getClass().getName());
+ actions.add(action.getActionTerm());
if (getEnvInfraTier() != null) {
super.act(action, feedback); //env.scheduleAction(getAgName(), action.getActionTerm(), action);
} else {
Modified: trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -16,19 +16,27 @@
// defines the agent's AgentSpeak code
ag.parseAScode(
- "+!start <- +g(a; b; c); ?g(X); !g(X). "+
+ "+!start <- +g(a(1); b; c); ?g(X); !g(X). "+
+ "+!test2 <- !g(!g2(1)). "+
"+!g(A; R) <- A; !g(R). "+
- "+!g(A) <- .print(A); A; .print(end)."
+ "+!g(A) <- A." +
+ "+!g2(A) <- jason.asunit.print(A)."
);
}
@Test
- public void testProgram() {
+ public void testProgram1() {
ag.addGoal("start");
- ag.assertBel("g(a;b;c)", 5);
- ag.assertAct("a", 4);
+ ag.assertBel("g(a(1);b;c)", 5);
+ ag.assertAct("a(1)", 4);
ag.assertAct("b", 4);
ag.assertAct("c", 4);
}
+ @Test
+ public void testProgram2() {
+ ag.addGoal("test2");
+ ag.assertPrint("1", 5);
+ }
+
}
Modified: trunk/demos/directives/myp/LoggerDirective.java
===================================================================
--- trunk/demos/directives/myp/LoggerDirective.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/demos/directives/myp/LoggerDirective.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -3,6 +3,7 @@
import jason.asSemantics.Agent;
import jason.asSyntax.BodyLiteral;
+import jason.asSyntax.BodyLiteralImpl;
import jason.asSyntax.Literal;
import jason.asSyntax.Plan;
import jason.asSyntax.Pred;
@@ -27,11 +28,11 @@
// add .print(te) in the begin and end of the plan
for (Plan p: innerContent.getPL()) {
Literal print1 = Literal.parseLiteral(".print(\"Entering \","+p.getTrigger().getLiteral()+")");
- BodyLiteral b1 = new BodyLiteral(BodyType.internalAction, print1);
+ BodyLiteral b1 = new BodyLiteralImpl(BodyType.internalAction, print1);
p.getBody().add(0,b1);
Literal print2 = Literal.parseLiteral(".print(\"Leaving \","+p.getTrigger().getLiteral()+")");
- BodyLiteral b2 = new BodyLiteral(BodyType.internalAction, print2);
+ BodyLiteral b2 = new BodyLiteralImpl(BodyType.internalAction, print2);
p.getBody().add(b2);
newAg.getPL().add(p);
Modified: trunk/demos/failure/a.asl
===================================================================
--- trunk/demos/failure/a.asl 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/demos/failure/a.asl 2008-03-30 14:24:59 UTC (rev 1180)
@@ -8,5 +8,13 @@
+!g5(_) : true <- .fail.
-!g3(failure) : true
<- .current_intention(I);
- .print("In failure handling plan, current intention is: ",I).
+ .print("In failure handling plan, current intention is: ",I);
+ I = intention(Id,IntendedMeans);
+ .println;
+ .println("* Intention ",Id, " IM stack:");
+ !print_im(IntendedMeans).
++!print_im([]).
++!print_im([im(_Planlabel,Body)|R])
+ <- .println("* ",Body);
+ !print_im(R).
Modified: trunk/src/jason/asSemantics/ActionExec.java
===================================================================
--- trunk/src/jason/asSemantics/ActionExec.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSemantics/ActionExec.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -61,8 +61,9 @@
}
public Structure getActionTerm() {
- return action;
+ return action;
}
+
public Intention getIntention() {
return intention;
}
Modified: trunk/src/jason/asSemantics/IntendedMeans.java
===================================================================
--- trunk/src/jason/asSemantics/IntendedMeans.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSemantics/IntendedMeans.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -25,6 +25,7 @@
package jason.asSemantics;
import jason.asSyntax.BodyLiteral;
+import jason.asSyntax.BodyLiteralImpl;
import jason.asSyntax.ListTerm;
import jason.asSyntax.ListTermImpl;
import jason.asSyntax.Literal;
@@ -73,10 +74,10 @@
/** removes the current action of the IM and returns the term of the body */
public Term removeCurrentStep() {
BodyLiteral current = plan.getBody();
- if (current.isEmpty()) {
+ if (current.isEmptyBody()) {
return null;
} else {
- return current.remove(0);
+ return current.removeBody(0);
}
}
@@ -106,7 +107,7 @@
}
public boolean isFinished() {
- return plan.getBody().isEmpty();
+ return plan.getBody().isEmptyBody();
}
public boolean isGoalAdd() {
@@ -128,13 +129,15 @@
public Term getAsTerm() {
Structure im = new Structure("im");
im.addTerm(new StringTermImpl(plan.getLabel().toString()));
- ListTerm lt = new ListTermImpl();
- for (Term bd: plan.getBody()) {
- Term c = (Term)bd.clone();
- c.apply(unif);
- lt.add(new StringTermImpl(c.toString()));
+ if (plan.getBody() instanceof BodyLiteralImpl) {
+ ListTerm lt = new ListTermImpl();
+ for (BodyLiteral bd: (BodyLiteralImpl)plan.getBody()) {
+ BodyLiteral c = (BodyLiteral)bd.clone();
+ c.apply(unif);
+ lt.add(new StringTermImpl(c.getBodyType().toString()+c.getBodyTerm()));
+ }
+ im.addTerm(lt);
}
- im.addTerm(lt);
return im;
}
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -402,16 +402,15 @@
return;
}
Unifier u = im.unif;
- BodyLiteral h = im.getCurrentStep();
- Term bTerm = h.getTerm();
+ BodyLiteral h = im.getCurrentStep();
+ h.apply(u);
- bTerm.apply(u);
-
- Literal body = null;
+ Literal body = null;
+ Term bTerm = h.getBodyTerm();
if (bTerm instanceof Literal)
body = (Literal)bTerm;
- switch (h.getType()) {
+ switch (h.getBodyType()) {
// Rule Action
case action:
Modified: trunk/src/jason/asSyntax/BodyLiteral.java
===================================================================
--- trunk/src/jason/asSyntax/BodyLiteral.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSyntax/BodyLiteral.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -1,12 +1,7 @@
package jason.asSyntax;
-import java.util.Iterator;
+public interface BodyLiteral extends Term {
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class BodyLiteral extends Structure implements Iterable<BodyLiteral> {
-
public enum BodyType {
none { public String toString() { return ""; }},
action { public String toString() { return ""; }},
@@ -20,198 +15,19 @@
constraint { public String toString() { return ""; }}
}
- public static final String BODY_PLAN_FUNCTOR = ";";
+ public BodyType getBodyType();
+ public Term getBodyTerm();
+ public BodyLiteral getBodyNext();
- private Term term = null;
- private BodyLiteral next = null;
- private BodyType formType = BodyType.none;
-
- /** constructor for empty plan body */
- public BodyLiteral() {
- super(BODY_PLAN_FUNCTOR, 0);
- }
-
- public BodyLiteral(BodyType t, Term b) {
- super(BODY_PLAN_FUNCTOR, 0);
- term = b;
- formType = t;
- setSrc(b);
- }
+ public boolean isEmptyBody();
+ public int getPlanSize();
- public void setNext(BodyLiteral next) {
- this.next = next;
- }
- public BodyLiteral getNext() {
- return next;
- }
-
- public boolean isEmpty() {
- return term == null;
- }
+ public void setBodyType(BodyType bt);
+ public void setBodyTerm(Term t);
+ public void setBodyNext(BodyLiteral bl);
- public BodyType getType() {
- return formType;
- }
- public Term getTerm() {
- return term;
- }
-
- public Literal getLiteralFormula() {
- if (term instanceof Literal)
- return (Literal)term;
- else
- return null;
- }
-
- public Iterator<BodyLiteral> iterator() {
- return new Iterator<BodyLiteral>() {
- BodyLiteral current = BodyLiteral.this;
- public boolean hasNext() {
- return current != null && current.term != null && current.next != null;
- }
- public BodyLiteral next() {
- BodyLiteral r = current;
- if (current != null)
- current = current.next;
- return r;
- }
- public void remove() { }
- };
- }
-
- // Override some structure methods to work with unification/equals
- @Override
- public int getArity() {
- if (term == null)
- return 0;
- else if (next == null)
- return 1;
- else
- return 2;
- }
-
- @Override
- public Term getTerm(int i) {
- if (i == 0) return term;
- if (i == 1) {
- if (next != null && next.term.isVar() && next.next == null)
- // if next is the last VAR, return that var
- return next.term;
- else
- return next;
- }
- return null;
- }
-
- @Override
- public void setTerm(int i, Term t) {
- if (i == 0) term = t;
- if (i == 1) System.out.println("Should not set next of body literal!");
- }
-
- @Override
- public boolean isPlanBody() {
- return true;
- }
-
- @Override
- public boolean equals(Object o) {
- if (o == null) return false;
- if (o == this) return true;
- if (o instanceof BodyLiteral) {
- BodyLiteral b = (BodyLiteral)o;
- return formType == b.formType && super.equals(o);
- }
- return false;
- }
-
- @Override
- public int calcHashCode() {
- return formType.hashCode() + super.calcHashCode();
- }
-
- public boolean add(BodyLiteral bl) {
- if (term == null)
- swap(bl);
- else if (next == null)
- next = bl;
- else
- next.add(bl);
- return true;
- }
-
- public boolean add(int index, BodyLiteral bl) {
- if (index == 0) {
- swap(bl);
- this.next = bl;
- } else {
- next.add(index - 1, bl);
- }
- return true;
- }
-
- public Term remove(int index) {
- if (index == 0) {
- if (next == null) {
- term = null; // becomes an empty
- } else {
- Term oldvalue = term;
- swap(next); // get values of text
- next = next.next;
- return oldvalue;
- }
- return this;
- } else {
- return next.remove(index - 1);
- }
- }
-
- public int size() {
- if (term == null)
- return 0;
- else if (next == null)
- return 1;
- else
- return next.size() + 1;
- }
-
- private void swap(BodyLiteral bl) {
- BodyType bt = this.formType;
- this.formType = bl.formType;
- bl.formType = bt;
-
- Term l = this.term;
- this.term = bl.term;
- bl.term = l;
- }
-
- public Object clone() {
- if (term == null) // empty
- return new BodyLiteral();
-
- BodyLiteral c = new BodyLiteral(formType, (Term)term.clone());
- if (next != null)
- c.setNext((BodyLiteral)getNext().clone());
- return c;
- }
-
- public String toString() {
- if (term == null)
- return "";
- else if (next == null)
- return formType.toString() + term;
- else
- return formType.toString() + term + "; " + next;
- }
-
- /** get as XML */
- public Element getAsDOM(Document document) {
- Element u = (Element) document.createElement("body-literal");
- if (formType.toString().length() > 0) {
- u.setAttribute("type", formType.toString());
- }
- u.appendChild( ((Structure)term).getAsDOM(document));
- return u;
- }
+ public boolean add(BodyLiteral bl);
+ public boolean add(int index, BodyLiteral bl);
+ public Term removeBody(int index);
}
\ No newline at end of file
Added: trunk/src/jason/asSyntax/BodyLiteralImpl.java
===================================================================
--- trunk/src/jason/asSyntax/BodyLiteralImpl.java (rev 0)
+++ trunk/src/jason/asSyntax/BodyLiteralImpl.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -0,0 +1,236 @@
+package jason.asSyntax;
+
+import jason.asSemantics.Unifier;
+
+import java.util.Iterator;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * Represents a plan body item (achieve, test, action, ...) and its successors.
+ *
+ * A plan body like <code>a1; ?t; !g</code> is represented by the following structure
+ * <code>(a1, (?t, (!g)))</code>.
+ *
+ * @author Jomi
+ */
+public class BodyLiteralImpl extends Structure implements BodyLiteral, Iterable<BodyLiteral> {
+
+ public static final String BODY_PLAN_FUNCTOR = ";";
+
+ private Term term = null;
+ private BodyLiteral next = null;
+ private BodyType formType = BodyType.none;
+
+ /** constructor for empty plan body */
+ public BodyLiteralImpl() {
+ super(BODY_PLAN_FUNCTOR, 0);
+ }
+
+ public BodyLiteralImpl(BodyType t, Term b) {
+ super(BODY_PLAN_FUNCTOR, 0);
+ term = b;
+ formType = t;
+ setSrc(b);
+ }
+
+ public void setBodyNext(BodyLiteral next) {
+ this.next = next;
+ }
+ public BodyLiteral getBodyNext() {
+ return next;
+ }
+
+ public boolean isEmptyBody() {
+ return term == null;
+ }
+
+ public BodyType getBodyType() {
+ return formType;
+ }
+ public void setBodyType(BodyType bt) {
+ formType = bt;
+ }
+
+ public Term getBodyTerm() {
+ return term;
+ }
+ public void setBodyTerm(Term t) {
+ term = t;
+ }
+
+ @Override
+ public boolean isPlanBody() {
+ return true;
+ }
+
+ public Iterator<BodyLiteral> iterator() {
+ return new Iterator<BodyLiteral>() {
+ BodyLiteral current = BodyLiteralImpl.this;
+ public boolean hasNext() {
+ return current != null && current.getBodyTerm() != null;
+ }
+ public BodyLiteral next() {
+ BodyLiteral r = current;
+ if (current != null)
+ current = current.getBodyNext();
+ return r;
+ }
+ public void remove() { }
+ };
+ }
+
+ // Override some structure methods to work with unification/equals
+ @Override
+ public int getArity() {
+ if (term == null)
+ return 0;
+ else if (next == null)
+ return 1;
+ else
+ return 2;
+ }
+
+ @Override
+ public Term getTerm(int i) {
+ if (i == 0)
+ return term;
+ if (i == 1) {
+ if (next != null && next.getBodyTerm().isVar() && next.getBodyNext() == null)
+ // if next is the last VAR, return that var
+ return next.getBodyTerm();
+ else
+ return next;
+ }
+ return null;
+ }
+
+ @Override
+ public void setTerm(int i, Term t) {
+ if (i == 0) term = t;
+ if (i == 1) System.out.println("Should not set next of body literal!");
+ }
+
+ @Override
+ public boolean apply(Unifier u) {
+ // do not apply in next!
+ resetHashCodeCache();
+ if (term != null && term.apply(u)) {
+ if (term.isPlanBody()) { // we can not have "inner" body literals
+ formType = ((BodyLiteral)term).getBodyType();
+ term = ((BodyLiteral)term).getBodyTerm();
+ }
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null) return false;
+ if (o == this) return true;
+
+ if (o instanceof BodyLiteral) {
+ BodyLiteral b = (BodyLiteral)o;
+ return formType == b.getBodyType() && super.equals(o);
+ }
+ return false;
+ }
+
+ @Override
+ public int calcHashCode() {
+ return formType.hashCode() + super.calcHashCode();
+ }
+
+ public boolean add(BodyLiteral bl) {
+ if (term == null)
+ swap(bl);
+ else if (next == null)
+ next = bl;
+ else
+ next.add(bl);
+ return true;
+ }
+
+ public boolean add(int index, BodyLiteral bl) {
+ if (index == 0) {
+ swap(bl);
+ this.next = bl;
+ } else {
+ next.add(index - 1, bl);
+ }
+ return true;
+ }
+
+ public Term removeBody(int index) {
+ if (index == 0) {
+ if (next == null) {
+ term = null; // becomes an empty
+ } else {
+ Term oldvalue = term;
+ swap(next); // get values of text
+ next = next.getBodyNext();
+ return oldvalue;
+ }
+ return this;
+ } else {
+ return next.removeBody(index - 1);
+ }
+ }
+
+ public int getPlanSize() {
+ if (term == null)
+ return 0;
+ else if (next == null)
+ return 1;
+ else
+ return next.getPlanSize() + 1;
+ }
+
+ private void swap(BodyLiteral bl) {
+ BodyType bt = this.formType;
+ this.formType = bl.getBodyType();
+ bl.setBodyType(bt);
+
+ Term l = this.term;
+ this.term = bl.getBodyTerm();
+ bl.setBodyTerm(l);
+ }
+
+ public Object clone() {
+ if (term == null) // empty
+ return new BodyLiteralImpl();
+
+ BodyLiteralImpl c = new BodyLiteralImpl(formType, (Term)term.clone());
+ if (next != null)
+ c.setBodyNext((BodyLiteral)getBodyNext().clone());
+ return c;
+ }
+
+ public String toString() {
+ if (term == null)
+ return "";
+ else if (next == null)
+ return formType.toString() + term;
+ else
+ return formType.toString() + term + "; " + next;
+ }
+
+ /** get as XML */
+ public Element getAsDOM(Document document) {
+ Element eb = (Element) document.createElement("body");
+ BodyLiteral bl = this;
+ while (bl != null && !bl.isEmptyBody()) {
+ Element u = (Element) document.createElement("body-literal");
+ if (bl.getBodyType().toString().length() > 0) {
+ u.setAttribute("type", bl.getBodyType().toString());
+ }
+ u.appendChild( ((Structure)bl.getBodyTerm()).getAsDOM(document));
+ eb.appendChild(u);
+
+ bl = bl.getBodyNext();
+ }
+ return eb;
+ }
+}
Modified: trunk/src/jason/asSyntax/Plan.java
===================================================================
--- trunk/src/jason/asSyntax/Plan.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSyntax/Plan.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -68,7 +68,7 @@
setLabel(label);
setContext(ct);
if (bd == null)
- body = new BodyLiteral();
+ body = new BodyLiteralImpl();
else
body = bd;
}
@@ -234,7 +234,7 @@
public String toASString() {
return ((label == null) ? "" : "@" + label + " ") +
tevent + ((context == null) ? "" : " : " + context) +
- (body.isEmpty() ? "" : " <- " + body) +
+ (body.isEmptyBody() ? "" : " <- " + body) +
".";
}
@@ -254,18 +254,8 @@
u.appendChild(ec);
}
- if (body.size() > 0) {
- Element eb = (Element) document.createElement("body");
- for (BodyLiteral bl: body) {
- eb.appendChild(bl.getAsDOM(document));
- }
- /*
- Iterator<ListTerm> i = body.listTermIterator();
- while (i.hasNext()) {
- eb.appendChild(i.next().getAsDOM(document));
- }
- */
- u.appendChild(eb);
+ if (!body.isEmptyBody()) {
+ u.appendChild(body.getAsDOM(document));
}
return u;
Modified: trunk/src/jason/asSyntax/Term.java
===================================================================
--- trunk/src/jason/asSyntax/Term.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSyntax/Term.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -12,33 +12,20 @@
public interface Term extends Cloneable, Comparable<Term>, Serializable, ToDOM {
public boolean isVar();
-
public boolean isLiteral();
-
public boolean isRule();
-
public boolean isList();
-
public boolean isString();
-
public boolean isInternalAction();
-
public boolean isArithExpr();
-
public boolean isNumeric();
-
public boolean isPred();
-
public boolean isGround();
-
public boolean isStructure();
-
public boolean isAtom();
-
public boolean isPlanBody();
public boolean hasVar(VarTerm t);
-
public void countVars(Map<VarTerm, Integer> c);
public Object clone();
@@ -56,4 +43,6 @@
public int getSrcLine();
public String getSrc();
+ public String getErrorMsg(); // info for error messages
+
}
Modified: trunk/src/jason/asSyntax/VarTerm.java
===================================================================
--- trunk/src/jason/asSyntax/VarTerm.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSyntax/VarTerm.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -46,7 +46,7 @@
*
* @author jomi
*/
-public class VarTerm extends Literal implements NumberTerm, ListTerm, StringTerm, ObjectTerm {
+public class VarTerm extends Literal implements NumberTerm, ListTerm, StringTerm, ObjectTerm, BodyLiteral {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(VarTerm.class.getName());
@@ -312,6 +312,11 @@
public boolean isString() {
return value != null && getValue().isString();
}
+
+ @Override
+ public boolean isPlanBody() {
+ return value != null && getValue().isPlanBody();
+ }
@Override
public boolean isNumeric() {
@@ -863,6 +868,82 @@
return null;
}
+ // -----------------------
+ // BodyLiteral interface implementation
+ // -----------------------
+
+ public BodyType getBodyType() {
+ if (value != null && getValue() instanceof BodyLiteral)
+ return ((BodyLiteral) getValue()).getBodyType();
+ else
+ return BodyType.none;
+ }
+
+ public Term getBodyTerm() {
+ if (value != null && getValue() instanceof BodyLiteral)
+ return ((BodyLiteral) getValue()).getBodyTerm();
+ else
+ return null;
+ }
+
+ public BodyLiteral getBodyNext() {
+ if (value != null && getValue() instanceof BodyLiteral)
+ return ((BodyLiteral) getValue()).getBodyNext();
+ else
+ return null;
+ }
+
+ public boolean isEmptyBody() {
+ if (value != null && getValue() instanceof BodyLiteral)
+ return ((BodyLiteral) getValue()).isEmptyBody();
+ else
+ return true;
+ }
+
+ public int getPlanSize() {
+ if (value != null && getValue() instanceof BodyLiteral)
+ return ((BodyLiteral) getValue()).getPlanSize();
+ else
+ return 0;
+ }
+
+ public void setBodyType(BodyType bt) {
+ if (value != null && getValue() instanceof BodyLiteral)
+ ((BodyLiteral) getValue()).setBodyType(bt);
+ }
+
+ public void setBodyTerm(Term t) {
+ if (value != null && getValue() instanceof BodyLiteral)
+ ((BodyLiteral) getValue()).setBodyTerm(t);
+ }
+
+ public void setBodyNext(BodyLiteral bl) {
+ if (value != null && getValue() instanceof BodyLiteral)
+ ((BodyLiteral) getValue()).setBodyNext(bl);
+ }
+
+ public boolean add(BodyLiteral bl) {
+ if (value != null && getValue() instanceof BodyLiteral)
+ return ((BodyLiteral) getValue()).add(bl);
+ else
+ return false;
+ }
+
+ public boolean add(int index, BodyLiteral bl) {
+ if (value != null && getValue() instanceof BodyLiteral)
+ return ((BodyLiteral) getValue()).add(index, bl);
+ else
+ return false;
+ }
+
+ public Term removeBody(int index) {
+ if (value != null && getValue() instanceof BodyLiteral)
+ return ((BodyLiteral) getValue()).removeBody(index);
+ else
+ return null;
+ }
+
+
/** get as XML */
public Element getAsDOM(Document document) {
if (hasValue()) {
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-30 14:24:59 UTC (rev 1180)
@@ -307,8 +307,8 @@
if (!(B instanceof BodyLiteral))
throw new ParseException(getSourceRef(B)+" Unknown body formula:"+B);
bl = (BodyLiteral)B;
- if (bl.getTerm().equals(Literal.LTrue))
- bl = (BodyLiteral)bl.getNext();
+ if (bl.getBodyTerm().equals(Literal.LTrue))
+ bl = (BodyLiteral)bl.getBodyNext();
}
Plan p = new Plan(L,T,(LogicalFormula)C, bl);
p.setSrcLines(start,end);
@@ -370,7 +370,7 @@
R = plan_body() { if (!(R instanceof BodyLiteral)) throw new ParseException(getSourceRef(R)+" "+R+" is not a body literal!"); }
]
{ if (F instanceof BodyLiteral && R instanceof BodyLiteral) {
- ((BodyLiteral)F).setNext( (BodyLiteral)R );
+ ((BodyLiteral)F).setBodyNext( (BodyLiteral)R );
}
return F;
}
@@ -394,13 +394,13 @@
{ if (B instanceof Literal) {
if ( ((Literal)B).isInternalAction() )
formType = BodyType.internalAction;
- return new BodyLiteral(formType, (Literal)B);
+ return new BodyLiteralImpl(for...
[truncated message content] |
|
From: <jom...@us...> - 2008-03-30 20:41:49
|
Revision: 1181
http://jason.svn.sourceforge.net/jason/?rev=1181&view=rev
Author: jomifred
Date: 2008-03-30 13:41:40 -0700 (Sun, 30 Mar 2008)
Log Message:
-----------
undo terms as plan's body
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/tests/TestAll.java
trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/test/ASParserTest.java
trunk/src/test/PlanTest.java
Modified: trunk/applications/as-unit-test/src/jason/tests/TestAll.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestAll.java 2008-03-30 14:24:59 UTC (rev 1180)
+++ trunk/applications/as-unit-test/src/jason/tests/TestAll.java 2008-03-30 20:41:40 UTC (rev 1181)
@@ -9,7 +9,7 @@
BugVarsInInitBels.class,
TestAddLogExprInBB.class,
TestKQML.class,
- TestVarInContext.class,
- TestPlanbodyAsTerm.class
+ TestVarInContext.class /*,
+ TestPlanbodyAsTerm.class*/
})
public class TestAll { }
Modified: trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java 2008-03-30 14:24:59 UTC (rev 1180)
+++ trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java 2008-03-30 20:41:40 UTC (rev 1181)
@@ -18,6 +18,7 @@
ag.parseAScode(
"+!start <- +g(a(1); b; c); ?g(X); !g(X). "+
"+!test2 <- !g(!g2(1)). "+
+ "+!test3 <- !g2(-1 + 2). "+
"+!g(A; R) <- A; !g(R). "+
"+!g(A) <- A." +
"+!g2(A) <- jason.asunit.print(A)."
@@ -39,4 +40,10 @@
ag.assertPrint("1", 5);
}
+ @Test
+ public void testProgram3() {
+ ag.addGoal("test3");
+ ag.assertPrint("1", 5);
+ }
+
}
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-30 14:24:59 UTC (rev 1180)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-30 20:41:40 UTC (rev 1181)
@@ -449,15 +449,15 @@
Term term() : { Object o;}
{
( o=list()
- | o=plan_body() // plan_body includes literals/atoms/structures
+ | o=log_expr() //plan_body() // plan_body includes literals/atoms/structures
)
{ // if the result is a BodyLiteral action with size = 1, it is indeed a literal and not a body literal
- if (o instanceof BodyLiteral) {
+ /*if (o instanceof BodyLiteral) {
BodyLiteral bl = (BodyLiteral)o;
if (bl.getBodyType() == BodyType.action && bl.getPlanSize() == 1) {
o = bl.getBodyTerm();
}
- }
+ }*/
return changeToAtom(o);
}
}
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2008-03-30 14:24:59 UTC (rev 1180)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2008-03-30 20:41:40 UTC (rev 1181)
@@ -653,13 +653,9 @@
case STRING:
case ATOM:
case UNNAMEDVAR:
- case 31:
- case 34:
case 35:
- case 36:
- case 38:
case 39:
- o = plan_body();
+ o = log_expr();
break;
default:
jj_la1[27] = jj_gen;
@@ -667,12 +663,12 @@
throw new ParseException();
}
// if the result is a BodyLiteral action with size = 1, it is indeed a literal and not a body literal
- if (o instanceof BodyLiteral) {
+ /*if (o instanceof BodyLiteral) {
BodyLiteral bl = (BodyLiteral)o;
if (bl.getBodyType() == BodyType.action && bl.getPlanSize() == 1) {
o = bl.getBodyTerm();
}
- }
+ }*/
{if (true) return changeToAtom(o);}
throw new Error("Missing return statement in function");
}
@@ -1240,10 +1236,10 @@
jj_la1_1();
}
private static void jj_la1_0() {
- jj_la1_0 = new int[] {0x8000000,0x10cb00,0x8000000,0x80000000,0x8000000,0x10000,0x10cb00,0x8000000,0x8000000,0x20000000,0x10000,0x0,0x0,0x0,0x80000000,0x80000000,0x30cb80,0x800,0x10cb00,0x0,0x0,0x80000000,0x80000000,0x10c000,0x0,0x0,0x0,0x803acf80,0x0,0x200080,0x0,0x3acb80,0x3acb80,0x0,0x0,0x3acf80,0x3acb80,0x0,0x3acb80,0x0,0x0,0x0,0x3000,0x3000,0x0,0x32cb80,0x200080,0x0,};
+ jj_la1_0 = new int[] {0x8000000,0x10cb00,0x8000000,0x80000000,0x8000000,0x10000,0x10cb00,0x8000000,0x8000000,0x20000000,0x10000,0x0,0x0,0x0,0x80000000,0x80000000,0x30cb80,0x800,0x10cb00,0x0,0x0,0x80000000,0x80000000,0x10c000,0x0,0x0,0x0,0x3acf80,0x0,0x200080,0x0,0x3acb80,0x3acb80,0x0,0x0,0x3acf80,0x3acb80,0x0,0x3acb80,0x0,0x0,0x0,0x3000,0x3000,0x0,0x32cb80,0x200080,0x0,};
}
private static void jj_la1_1() {
- jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0xc,0x0,0x0,0x0,0x0,0x0,0x1,0x2,0xc,0x10,0x10,0x0,0x0,0x0,0x20,0x4,0x5c,0x5c,0x0,0x80,0x400,0x200,0x4dc,0x200,0x400,0x800,0x488,0x488,0x800,0x2000,0x88,0x88,0x3fc000,0x488,0x3fc000,0xc,0xc,0xc00000,0xc00000,0x1000000,0x88,0x0,0x400,};
+ jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0xc,0x0,0x0,0x0,0x0,0x0,0x1,0x2,0xc,0x10,0x10,0x0,0x0,0x0,0x20,0x4,0x5c,0x5c,0x0,0x80,0x400,0x200,0x488,0x200,0x400,0x800,0x488,0x488,0x800,0x2000,0x88,0x88,0x3fc000,0x488,0x3fc000,0xc,0xc,0xc00000,0xc00000,0x1000000,0x88,0x0,0x400,};
}
final private JJCalls[] jj_2_rtns = new JJCalls[1];
private boolean jj_rescan = false;
Modified: trunk/src/test/ASParserTest.java
===================================================================
--- trunk/src/test/ASParserTest.java 2008-03-30 14:24:59 UTC (rev 1180)
+++ trunk/src/test/ASParserTest.java 2008-03-30 20:41:40 UTC (rev 1181)
@@ -5,7 +5,6 @@
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.BodyLiteral;
-import jason.asSyntax.Literal;
import jason.asSyntax.LogExpr;
import jason.asSyntax.LogicalFormula;
import jason.asSyntax.NumberTerm;
@@ -165,6 +164,8 @@
}
public void testParsingPlanBody() {
+ // TODO: think about this
+ /*
Literal l = Literal.parseLiteral("p(a1;a2, a3, !g, ?b;.print(oi), 10)");
assertEquals(5,l.getArity());
assertTrue(l.getTerm(0) instanceof BodyLiteral);
@@ -174,7 +175,7 @@
assertTrue(l.getTerm(2).isPlanBody());
assertTrue(l.getTerm(3).isPlanBody());
assertFalse(l.getTerm(4).isPlanBody());
-
+ */
}
public void testParsingAllSources() {
Modified: trunk/src/test/PlanTest.java
===================================================================
--- trunk/src/test/PlanTest.java 2008-03-30 14:24:59 UTC (rev 1180)
+++ trunk/src/test/PlanTest.java 2008-03-30 20:41:40 UTC (rev 1181)
@@ -55,7 +55,7 @@
assertEquals(0, pls.size());
}
- public void testParser() {
+ public void testParser1() {
Plan p = Plan.parse("+te : a & b <- a1; a2; .print(a); !g1; !!g2; ?test1; 10 > 3; +b1; -b2; -+b3.");
p = (Plan)p.clone();
Iterator<BodyLiteral> i = ((BodyLiteralImpl)p.getBody()).iterator();
@@ -72,7 +72,7 @@
assertEquals( BodyLiteral.BodyType.delAddBel, ((BodyLiteral)i.next()).getBodyType());
assertFalse(i.hasNext());
}
-
+
public void testDelete() {
Plan p = Plan.parse("+te : a & b <- !a1; ?a2; .print(a); !g1.");
assertEquals(4, p.getBody().getPlanSize());
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-31 19:25:04
|
Revision: 1182
http://jason.svn.sourceforge.net/jason/?rev=1182&view=rev
Author: jomifred
Date: 2008-03-31 12:25:02 -0700 (Mon, 31 Mar 2008)
Log Message:
-----------
rename some methods:
BB: getRelevant(Literal l) -> getCandidateBeliefs(Literal l, Unifier u)
PL: isRelevant(Trigger te) -> hasCandidatePlan(Trigger te)
getAllRelevant(Trigger te) -> getCandidatePlans(Trigger te)
Modified Paths:
--------------
trunk/demos/persistent-belief-base/VoidBB.java
trunk/demos/tell-rule/rules/get_rules.java
trunk/examples/gold-miners-II/agent/UniqueBelsBB.java
trunk/src/jason/asSemantics/Agent.java
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/asSyntax/Literal.java
trunk/src/jason/asSyntax/PlanLibrary.java
trunk/src/jason/bb/BeliefBase.java
trunk/src/jason/bb/DefaultBeliefBase.java
trunk/src/jason/bb/JDBCPersistentBB.java
trunk/src/test/BeliefBaseTest.java
trunk/src/test/PlanTest.java
trunk/src/test/RuleTest.java
trunk/src/test/VarTermTest.java
Modified: trunk/demos/persistent-belief-base/VoidBB.java
===================================================================
--- trunk/demos/persistent-belief-base/VoidBB.java 2008-03-30 20:41:40 UTC (rev 1181)
+++ trunk/demos/persistent-belief-base/VoidBB.java 2008-03-31 19:25:02 UTC (rev 1182)
@@ -55,6 +55,10 @@
return true;
}
+ public Iterator<Literal> getCandidateBeliefs(Literal l, Unifier u) {
+ return new ArrayList<Literal>().iterator();
+ }
+
public Iterator<Literal> getRelevant(Literal l) {
return new ArrayList<Literal>().iterator();
}
Modified: trunk/demos/tell-rule/rules/get_rules.java
===================================================================
--- trunk/demos/tell-rule/rules/get_rules.java 2008-03-30 20:41:40 UTC (rev 1181)
+++ trunk/demos/tell-rule/rules/get_rules.java 2008-03-31 19:25:02 UTC (rev 1182)
@@ -22,7 +22,7 @@
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
try {
Literal pattern = (Literal)args[0];
- Iterator<Literal> i = ts.getAg().getBB().getRelevant(pattern);
+ Iterator<Literal> i = ts.getAg().getBB().getCandidateBeliefs(pattern, un);
ListTerm result = new ListTermImpl();
while (i.hasNext()) {
Literal l = i.next();
Modified: trunk/examples/gold-miners-II/agent/UniqueBelsBB.java
===================================================================
--- trunk/examples/gold-miners-II/agent/UniqueBelsBB.java 2008-03-30 20:41:40 UTC (rev 1181)
+++ trunk/examples/gold-miners-II/agent/UniqueBelsBB.java 2008-03-31 19:25:02 UTC (rev 1182)
@@ -44,7 +44,7 @@
Literal linbb = null;
boolean remove = false;
- Iterator<Literal> relevant = getRelevant(bel);
+ Iterator<Literal> relevant = getCandidateBeliefs(bel, null);
if (relevant != null) {
while (relevant.hasNext() && !remove) {
linbb = relevant.next();
Modified: trunk/src/jason/asSemantics/Agent.java
===================================================================
--- trunk/src/jason/asSemantics/Agent.java 2008-03-30 20:41:40 UTC (rev 1181)
+++ trunk/src/jason/asSemantics/Agent.java 2008-03-31 19:25:02 UTC (rev 1182)
@@ -457,7 +457,7 @@
perceptsInBB.remove(); // remove l as perception from BB
Trigger te = new Trigger(TEOperator.del, TEType.belief, l);
- if (ts.getC().hasListener() || pl.isRelevant(te)) {
+ if (ts.getC().hasListener() || pl.hasCandidatePlan(te)) {
l = (Literal)l.clone();
l.clearAnnots();
l.addAnnot(BeliefBase.TPercept);
@@ -519,7 +519,7 @@
* The unifier <i>un</i> is updated by the method.
*/
public Literal findBel(Literal bel, Unifier un) {
- Iterator<Literal> relB = bb.getRelevant(bel);
+ Iterator<Literal> relB = bb.getCandidateBeliefs(bel, un);
if (relB != null) {
while (relB.hasNext()) {
Literal b = relB.next();
@@ -628,7 +628,7 @@
public void abolish(Literal bel, Unifier un) throws RevisionFailedException {
List<Literal> toDel = new ArrayList<Literal>();
- Iterator<Literal> il = getBB().getRelevant(bel);
+ Iterator<Literal> il = getBB().getCandidateBeliefs(bel, un);
if (il != null) {
while (il.hasNext()) {
Literal inBB = il.next();
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-30 20:41:40 UTC (rev 1181)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-31 19:25:02 UTC (rev 1182)
@@ -297,7 +297,7 @@
// get all relevant plans for the selected event
//Trigger te = (Trigger) conf.C.SE.trigger.clone();
- List<Plan> candidateRPs = conf.ag.pl.getAllRelevant(conf.C.SE.trigger);
+ List<Plan> candidateRPs = conf.ag.pl.getCandidatePlans(conf.C.SE.trigger);
if (candidateRPs != null) {
for (Plan pl : candidateRPs) {
Unifier relUn = pl.isRelevant(conf.C.SE.trigger);
@@ -486,7 +486,7 @@
if (body.isLiteral()) { // in case body is a var with content that is not a literal (note the VarTerm pass in the instanceof Literal)
body.makeVarsAnnon();
Trigger te = new Trigger(TEOperator.add, TEType.test, body);
- if (ag.getPL().isRelevant(te)) {
+ if (ag.getPL().hasCandidatePlan(te)) {
Event evt = new Event(te, conf.C.SI);
if (logger.isLoggable(Level.FINE)) logger.fine("Test Goal '" + h + "' failed as simple query. Generating internal event for it: "+te);
conf.C.addEvent(evt);
@@ -655,7 +655,7 @@
public List<Option> relevantPlans(Trigger teP) throws JasonException {
Trigger te = (Trigger) teP.clone();
List<Option> rp = null;
- List<Plan> candidateRPs = conf.ag.pl.getAllRelevant(te);
+ List<Plan> candidateRPs = conf.ag.pl.getCandidatePlans(te);
if (candidateRPs != null) {
for (Plan pl : candidateRPs) {
Unifier relUn = pl.isRelevant(te);
@@ -707,10 +707,12 @@
for (Literal ladd: result[0]) {
Trigger te = new Trigger(TEOperator.add, TEType.belief, ladd);
updateEvents(new Event(te, focus));
+ focus = Intention.EmptyInt;
}
for (Literal lrem: result[1]) {
Trigger te = new Trigger(TEOperator.del, TEType.belief, lrem);
updateEvents(new Event(te, focus));
+ focus = Intention.EmptyInt;
}
}
@@ -719,7 +721,7 @@
// Note: we have to add events even if they are not relevant to
// a) allow the user to override selectOption and then provide an "unknown" plan; or then
// b) create the failure event (it is done by SelRelPlan)
- if (e.isInternal() || C.hasListener() || ag.getPL().isRelevant(e.trigger)) {
+ if (e.isInternal() || C.hasListener() || ag.getPL().hasCandidatePlan(e.trigger)) {
C.addEvent(e);
if (logger.isLoggable(Level.FINE)) logger.fine("Added event " + e);
}
@@ -794,14 +796,14 @@
Trigger failTrigger = new Trigger(TEOperator.del, tevent.getType(), tevent.getLiteral());
if (i != Intention.EmptyInt) {
ListIterator<IntendedMeans> ii = i.iterator();
- while (!getAg().getPL().isRelevant(failTrigger) && ii.hasPrevious()) {
+ while (!getAg().getPL().hasCandidatePlan(failTrigger) && ii.hasPrevious()) {
IntendedMeans im = ii.previous();
tevent = im.getTrigger();
failTrigger = new Trigger(TEOperator.del, tevent.getType(), tevent.getLiteral());
}
}
// if some failure handling plan is found
- if (tevent.isGoal() && getAg().getPL().isRelevant(failTrigger)) {
+ if (tevent.isGoal() && getAg().getPL().hasCandidatePlan(failTrigger)) {
return new Event(failTrigger, i);
}
return null;
Modified: trunk/src/jason/asSyntax/Literal.java
===================================================================
--- trunk/src/jason/asSyntax/Literal.java 2008-03-30 20:41:40 UTC (rev 1181)
+++ trunk/src/jason/asSyntax/Literal.java 2008-03-31 19:25:02 UTC (rev 1182)
@@ -126,7 +126,7 @@
* Returns an iterator for all unifiers that are logCons.
*/
public Iterator<Unifier> logicalConsequence(final Agent ag, final Unifier un) {
- final Iterator<Literal> il = ag.getBB().getRelevant(this);
+ final Iterator<Literal> il = ag.getBB().getCandidateBeliefs(this, un);
if (il == null) // no relevant bels
return LogExpr.EMPTY_UNIF_LIST.iterator();
Modified: trunk/src/jason/asSyntax/PlanLibrary.java
===================================================================
--- trunk/src/jason/asSyntax/PlanLibrary.java 2008-03-30 20:41:40 UTC (rev 1181)
+++ trunk/src/jason/asSyntax/PlanLibrary.java 2008-03-31 19:25:02 UTC (rev 1182)
@@ -233,12 +233,23 @@
return p;
}
+ /** @deprecated use hasCandidatePlan(te) instead */
public boolean isRelevant(Trigger te) {
- List<Plan> l = getAllRelevant(te);
+ return hasCandidatePlan(te);
+ }
+
+ public boolean hasCandidatePlan(Trigger te) {
+ List<Plan> l = getCandidatePlans(te);
return l != null && ! l.isEmpty();
}
+
+ /** @deprecated use getCandidatePlans(te) instead */
public List<Plan> getAllRelevant(Trigger te) {
+ return getCandidatePlans(te);
+ }
+
+ public List<Plan> getCandidatePlans(Trigger te) {
List<Plan> l = relPlans.get(te.getPredicateIndicator());
if ((l == null || l.isEmpty()) && !varPlans.isEmpty()) { // no rel plan, try varPlan
l = new ArrayList<Plan>();
Modified: trunk/src/jason/bb/BeliefBase.java
===================================================================
--- trunk/src/jason/bb/BeliefBase.java 2008-03-30 20:41:40 UTC (rev 1181)
+++ trunk/src/jason/bb/BeliefBase.java 2008-03-31 19:25:02 UTC (rev 1182)
@@ -24,10 +24,11 @@
package jason.bb;
import jason.asSemantics.Agent;
+import jason.asSemantics.Unifier;
+import jason.asSyntax.DefaultTerm;
import jason.asSyntax.Literal;
import jason.asSyntax.PredicateIndicator;
import jason.asSyntax.Term;
-import jason.asSyntax.DefaultTerm;
import java.util.Iterator;
@@ -76,12 +77,18 @@
/**
* Returns an iterator for all literals relevant for l's predicate
* indicator, if l is a var, returns all beliefs.<br>
+ *
+ * The unifier <i>u</i> may contain values for variables in <i>l</i>.
*
* Example, if BB={a(10),a(20),a(2,1),b(f)}, then
- * <code>getRelevant(a(5))</code> = {{a(10),a(20)}.<br>
- * if BB={a(10),a(20)}, then <code>getRelevant(X)</code> =
- * {{a(10),a(20)}.
+ * <code>getCandidateBeliefs(a(5), {})</code> = {{a(10),a(20)}.<br>
+ * if BB={a(10),a(20)}, then <code>getCandidateBeliefs(X)</code> =
+ * {{a(10),a(20)}. The <code>getCandidateBeliefs(a(X), {X -> 5})</code>
+ * should also return {{a(10),a(20)}.<br>
*/
+ public Iterator<Literal> getCandidateBeliefs(Literal l, Unifier u);
+
+ /** @deprecated use getCandidateBeliefs(l,null) instead */
public Iterator<Literal> getRelevant(Literal l);
/**
Modified: trunk/src/jason/bb/DefaultBeliefBase.java
===================================================================
--- trunk/src/jason/bb/DefaultBeliefBase.java 2008-03-30 20:41:40 UTC (rev 1181)
+++ trunk/src/jason/bb/DefaultBeliefBase.java 2008-03-31 19:25:02 UTC (rev 1182)
@@ -24,6 +24,7 @@
package jason.bb;
import jason.asSemantics.Agent;
+import jason.asSemantics.Unifier;
import jason.asSyntax.Literal;
import jason.asSyntax.PredicateIndicator;
@@ -222,7 +223,7 @@
}
}
- public Iterator<Literal> getRelevant(Literal l) {
+ public Iterator<Literal> getCandidateBeliefs(Literal l, Unifier u) {
if (l.isVar()) {
// all bels are relevant
return iterator();
@@ -235,6 +236,11 @@
}
}
}
+
+ /** @deprecated use getCandidateBeliefs(l,null) instead */
+ public Iterator<Literal> getRelevant(Literal l) {
+ return getCandidateBeliefs(l, null);
+ }
public String toString() {
return belsMap.toString();
Modified: trunk/src/jason/bb/JDBCPersistentBB.java
===================================================================
--- trunk/src/jason/bb/JDBCPersistentBB.java 2008-03-30 20:41:40 UTC (rev 1181)
+++ trunk/src/jason/bb/JDBCPersistentBB.java 2008-03-31 19:25:02 UTC (rev 1182)
@@ -1,6 +1,7 @@
package jason.bb;
import jason.asSemantics.Agent;
+import jason.asSemantics.Unifier;
import jason.asSyntax.DefaultTerm;
import jason.asSyntax.ListTerm;
import jason.asSyntax.ListTermImpl;
@@ -318,10 +319,10 @@
@Override
- public Iterator<Literal> getRelevant(Literal l) {
+ public Iterator<Literal> getCandidateBeliefs(Literal l, Unifier u) {
final PredicateIndicator pi = l.getPredicateIndicator();
if (belsDB.get(pi) == null)
- return super.getRelevant(l);
+ return super.getCandidateBeliefs(l, u);
if (l.isVar()) {
// all bels are relevant
Modified: trunk/src/test/BeliefBaseTest.java
===================================================================
--- trunk/src/test/BeliefBaseTest.java 2008-03-30 20:41:40 UTC (rev 1181)
+++ trunk/src/test/BeliefBaseTest.java 2008-03-31 19:25:02 UTC (rev 1182)
@@ -119,7 +119,7 @@
l5 = new Literal(true, new Pred("garb"));
l5.addTerm(new Structure("r1"));
assertTrue(bb.remove(l5));
- assertEquals(bb.getRelevant(l5), null);
+ assertEquals(bb.getCandidateBeliefs(l5, null), null);
assertEquals(bb.size(), 3);
l4 = new Literal(true, new Pred("pos"));
@@ -127,7 +127,7 @@
l4.addTerm(new Structure("6"));
l4.addAnnot(BeliefBase.TPercept);
assertTrue(bb.remove(l4));
- assertEquals(iteratorSize(bb.getRelevant(l4)), 1);
+ assertEquals(iteratorSize(bb.getCandidateBeliefs(l4, null)), 1);
assertEquals(bb.size(), 2);
assertEquals(iteratorSize(bb.iterator()), 2);
@@ -141,7 +141,7 @@
l4.addTerm(new Structure("2"));
l4.addAnnot(BeliefBase.TPercept);
assertTrue(bb.remove(l4));
- assertEquals(bb.getRelevant(l4), null);
+ assertEquals(bb.getCandidateBeliefs(l4, null), null);
assertEquals(bb.size(), 1);
assertEquals(iteratorSize(bb.getPercepts()), 1);
@@ -513,7 +513,7 @@
//while (ir.hasNext()) {
// System.out.println(ir.next());
//}
- assertEquals(iteratorSize(bb.getRelevant(Literal.parseLiteral("book_author(_,_)"))),5);
+ assertEquals(iteratorSize(bb.getCandidateBeliefs(Literal.parseLiteral("book_author(_,_)"),null)),5);
bb.stop();
}
Modified: trunk/src/test/PlanTest.java
===================================================================
--- trunk/src/test/PlanTest.java 2008-03-30 20:41:40 UTC (rev 1181)
+++ trunk/src/test/PlanTest.java 2008-03-31 19:25:02 UTC (rev 1182)
@@ -42,16 +42,16 @@
pl.add(Plan.parse("+!X <- .print(a)."));
- List<Plan> pls = pl.getAllRelevant(Trigger.parseTrigger("+p(3)"));
+ List<Plan> pls = pl.getCandidatePlans(Trigger.parseTrigger("+p(3)"));
assertEquals(2, pls.size());
- pls = pl.getAllRelevant(Trigger.parseTrigger("+!p(3)"));
+ pls = pl.getCandidatePlans(Trigger.parseTrigger("+!p(3)"));
assertEquals(3, pls.size());
- pls = pl.getAllRelevant(Trigger.parseTrigger("+!bla"));
+ pls = pl.getCandidatePlans(Trigger.parseTrigger("+!bla"));
assertEquals(1, pls.size());
- pls = pl.getAllRelevant(Trigger.parseTrigger("+bla"));
+ pls = pl.getCandidatePlans(Trigger.parseTrigger("+bla"));
assertEquals(0, pls.size());
}
Modified: trunk/src/test/RuleTest.java
===================================================================
--- trunk/src/test/RuleTest.java 2008-03-30 20:41:40 UTC (rev 1181)
+++ trunk/src/test/RuleTest.java 2008-03-31 19:25:02 UTC (rev 1182)
@@ -119,7 +119,7 @@
assertEquals(u.get("M").toString(),"20");
Literal cons = Literal.parseLiteral("min([op(5),op(3),op(8),op(1),op(40)],op(1000),op(M))");
- Iterator<Literal> il = ag.getBB().getRelevant(cons);
+ Iterator<Literal> il = ag.getBB().getCandidateBeliefs(cons, null);
assertEquals(3,iteratorSize(il));
iun = cons.logicalConsequence(ag, new Unifier());
Modified: trunk/src/test/VarTermTest.java
===================================================================
--- trunk/src/test/VarTermTest.java 2008-03-30 20:41:40 UTC (rev 1181)
+++ trunk/src/test/VarTermTest.java 2008-03-31 19:25:02 UTC (rev 1182)
@@ -336,7 +336,7 @@
Unifier u = new Unifier();
VarTerm v1 = VarTerm.parseVar("P[d]");
- assertEquals(2, iteratorSize(ag.getBB().getRelevant(v1)));
+ assertEquals(2, iteratorSize(ag.getBB().getCandidateBeliefs(v1, null)));
Iterator<Unifier> i = v1.logicalConsequence(ag, u);
assertTrue(i.hasNext());
u = i.next(); // u = {P[d]=b2}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-31 20:04:25
|
Revision: 1183
http://jason.svn.sourceforge.net/jason/?rev=1183&view=rev
Author: jomifred
Date: 2008-03-31 13:04:20 -0700 (Mon, 31 Mar 2008)
Log Message:
-----------
rename BodyLiteral to BodyPlan (old class is still there, but deprecated)
Modified Paths:
--------------
trunk/demos/directives/myp/LoggerDirective.java
trunk/src/jason/asSemantics/IntendedMeans.java
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/asSyntax/BodyLiteral.java
trunk/src/jason/asSyntax/Plan.java
trunk/src/jason/asSyntax/PlanLibrary.java
trunk/src/jason/asSyntax/VarTerm.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/jason/asSyntax/parser/as2jTokenManager.java
trunk/src/jason/asSyntax/patterns/goal/DG.java
trunk/src/jason/asSyntax/patterns/goal/EBDG.java
trunk/src/jason/stdlib/remove_plan.java
trunk/src/jason/stdlib/wait.java
trunk/src/test/ASParserTest.java
trunk/src/test/PlanTest.java
Removed Paths:
-------------
trunk/src/jason/asSyntax/BodyLiteralImpl.java
trunk/src/jason/stdlib/myName.java
Modified: trunk/demos/directives/myp/LoggerDirective.java
===================================================================
--- trunk/demos/directives/myp/LoggerDirective.java 2008-03-31 19:25:02 UTC (rev 1182)
+++ trunk/demos/directives/myp/LoggerDirective.java 2008-03-31 20:04:20 UTC (rev 1183)
@@ -2,12 +2,12 @@
package myp;
import jason.asSemantics.Agent;
-import jason.asSyntax.BodyLiteral;
-import jason.asSyntax.BodyLiteralImpl;
+import jason.asSyntax.PlanBody;
+import jason.asSyntax.PlanBodyImpl;
import jason.asSyntax.Literal;
import jason.asSyntax.Plan;
import jason.asSyntax.Pred;
-import jason.asSyntax.BodyLiteral.BodyType;
+import jason.asSyntax.PlanBody.BodyType;
import jason.asSyntax.directives.Directive;
import java.util.logging.Level;
@@ -28,11 +28,11 @@
// add .print(te) in the begin and end of the plan
for (Plan p: innerContent.getPL()) {
Literal print1 = Literal.parseLiteral(".print(\"Entering \","+p.getTrigger().getLiteral()+")");
- BodyLiteral b1 = new BodyLiteralImpl(BodyType.internalAction, print1);
+ PlanBody b1 = new PlanBodyImpl(BodyType.internalAction, print1);
p.getBody().add(0,b1);
Literal print2 = Literal.parseLiteral(".print(\"Leaving \","+p.getTrigger().getLiteral()+")");
- BodyLiteral b2 = new BodyLiteralImpl(BodyType.internalAction, print2);
+ PlanBody b2 = new PlanBodyImpl(BodyType.internalAction, print2);
p.getBody().add(b2);
newAg.getPL().add(p);
Modified: trunk/src/jason/asSemantics/IntendedMeans.java
===================================================================
--- trunk/src/jason/asSemantics/IntendedMeans.java 2008-03-31 19:25:02 UTC (rev 1182)
+++ trunk/src/jason/asSemantics/IntendedMeans.java 2008-03-31 20:04:20 UTC (rev 1183)
@@ -24,8 +24,8 @@
package jason.asSemantics;
-import jason.asSyntax.BodyLiteral;
-import jason.asSyntax.BodyLiteralImpl;
+import jason.asSyntax.PlanBody;
+import jason.asSyntax.PlanBodyImpl;
import jason.asSyntax.ListTerm;
import jason.asSyntax.ListTermImpl;
import jason.asSyntax.Literal;
@@ -73,7 +73,7 @@
/** removes the current action of the IM and returns the term of the body */
public Term removeCurrentStep() {
- BodyLiteral current = plan.getBody();
+ PlanBody current = plan.getBody();
if (current.isEmptyBody()) {
return null;
} else {
@@ -81,7 +81,7 @@
}
}
- public BodyLiteral getCurrentStep() {
+ public PlanBody getCurrentStep() {
return plan.getBody();
}
@@ -129,10 +129,10 @@
public Term getAsTerm() {
Structure im = new Structure("im");
im.addTerm(new StringTermImpl(plan.getLabel().toString()));
- if (plan.getBody() instanceof BodyLiteralImpl) {
+ if (plan.getBody() instanceof PlanBodyImpl) {
ListTerm lt = new ListTermImpl();
- for (BodyLiteral bd: (BodyLiteralImpl)plan.getBody()) {
- BodyLiteral c = (BodyLiteral)bd.clone();
+ for (PlanBody bd: (PlanBodyImpl)plan.getBody()) {
+ PlanBody c = (PlanBody)bd.clone();
c.apply(unif);
lt.add(new StringTermImpl(c.getBodyType().toString()+c.getBodyTerm()));
}
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-31 19:25:02 UTC (rev 1182)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-31 20:04:20 UTC (rev 1183)
@@ -27,7 +27,7 @@
import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSyntax.Atom;
-import jason.asSyntax.BodyLiteral;
+import jason.asSyntax.PlanBody;
import jason.asSyntax.DefaultTerm;
import jason.asSyntax.InternalActionLiteral;
import jason.asSyntax.ListTermImpl;
@@ -286,11 +286,11 @@
}
/**
- * This step is new in Jason 1.0.2 and replaces the steps RelPl->ApplPl->SelAppl when the user
+ * This step is new in Jason 1.1 and replaces the steps RelPl->ApplPl->SelAppl when the user
* does not customise selectOption. This version does not create the RP and AP lists and thus
* optimise the reasoning cycle. It searches for the first option and automatically selects it.
*
- * @since 1.0.2
+ * @since 1.1
*/
private void applyFindOp() throws JasonException {
confP.step = State.AddIM; // default next step
@@ -402,7 +402,7 @@
return;
}
Unifier u = im.unif;
- BodyLiteral h = im.getCurrentStep();
+ PlanBody h = im.getCurrentStep();
h.apply(u);
Literal body = null;
Modified: trunk/src/jason/asSyntax/BodyLiteral.java
===================================================================
--- trunk/src/jason/asSyntax/BodyLiteral.java 2008-03-31 19:25:02 UTC (rev 1182)
+++ trunk/src/jason/asSyntax/BodyLiteral.java 2008-03-31 20:04:20 UTC (rev 1183)
@@ -1,7 +1,12 @@
package jason.asSyntax;
-public interface BodyLiteral extends Term {
+/**
+ * @deprecated use PlanBodyImpl instead.
+ */
+public class BodyLiteral extends PlanBodyImpl {
+
+ /** @deprecated Use BodyType of PlanBody instead */
public enum BodyType {
none { public String toString() { return ""; }},
action { public String toString() { return ""; }},
@@ -15,19 +20,24 @@
constraint { public String toString() { return ""; }}
}
- public BodyType getBodyType();
- public Term getBodyTerm();
- public BodyLiteral getBodyNext();
+ public BodyLiteral(BodyType t, Term b) {
+ super(oldToNew(t),b);
+ }
+
+ private static PlanBody.BodyType oldToNew(BodyType old) {
+ // TODO: implement it!
+ switch (old) {
+ case action: return PlanBody.BodyType.action;
+ case internalAction: return PlanBody.BodyType.internalAction;
+ case achieve: return PlanBody.BodyType.achieve;
+ case test: return PlanBody.BodyType.test;
+ case addBel: return PlanBody.BodyType.addBel;
+ case delBel: return PlanBody.BodyType.delBel;
+ case delAddBel: return PlanBody.BodyType.delAddBel;
+ case achieveNF: return PlanBody.BodyType.achieveNF;
+ case constraint: return PlanBody.BodyType.constraint;
+ }
+ return PlanBody.BodyType.none;
+ }
- public boolean isEmptyBody();
- public int getPlanSize();
-
- public void setBodyType(BodyType bt);
- public void setBodyTerm(Term t);
- public void setBodyNext(BodyLiteral bl);
-
-
- public boolean add(BodyLiteral bl);
- public boolean add(int index, BodyLiteral bl);
- public Term removeBody(int index);
-}
\ No newline at end of file
+}
Deleted: trunk/src/jason/asSyntax/BodyLiteralImpl.java
===================================================================
--- trunk/src/jason/asSyntax/BodyLiteralImpl.java 2008-03-31 19:25:02 UTC (rev 1182)
+++ trunk/src/jason/asSyntax/BodyLiteralImpl.java 2008-03-31 20:04:20 UTC (rev 1183)
@@ -1,236 +0,0 @@
-package jason.asSyntax;
-
-import jason.asSemantics.Unifier;
-
-import java.util.Iterator;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-/**
- * Represents a plan body item (achieve, test, action, ...) and its successors.
- *
- * A plan body like <code>a1; ?t; !g</code> is represented by the following structure
- * <code>(a1, (?t, (!g)))</code>.
- *
- * @author Jomi
- */
-public class BodyLiteralImpl extends Structure implements BodyLiteral, Iterable<BodyLiteral> {
-
- public static final String BODY_PLAN_FUNCTOR = ";";
-
- private Term term = null;
- private BodyLiteral next = null;
- private BodyType formType = BodyType.none;
-
- /** constructor for empty plan body */
- public BodyLiteralImpl() {
- super(BODY_PLAN_FUNCTOR, 0);
- }
-
- public BodyLiteralImpl(BodyType t, Term b) {
- super(BODY_PLAN_FUNCTOR, 0);
- term = b;
- formType = t;
- setSrc(b);
- }
-
- public void setBodyNext(BodyLiteral next) {
- this.next = next;
- }
- public BodyLiteral getBodyNext() {
- return next;
- }
-
- public boolean isEmptyBody() {
- return term == null;
- }
-
- public BodyType getBodyType() {
- return formType;
- }
- public void setBodyType(BodyType bt) {
- formType = bt;
- }
-
- public Term getBodyTerm() {
- return term;
- }
- public void setBodyTerm(Term t) {
- term = t;
- }
-
- @Override
- public boolean isPlanBody() {
- return true;
- }
-
- public Iterator<BodyLiteral> iterator() {
- return new Iterator<BodyLiteral>() {
- BodyLiteral current = BodyLiteralImpl.this;
- public boolean hasNext() {
- return current != null && current.getBodyTerm() != null;
- }
- public BodyLiteral next() {
- BodyLiteral r = current;
- if (current != null)
- current = current.getBodyNext();
- return r;
- }
- public void remove() { }
- };
- }
-
- // Override some structure methods to work with unification/equals
- @Override
- public int getArity() {
- if (term == null)
- return 0;
- else if (next == null)
- return 1;
- else
- return 2;
- }
-
- @Override
- public Term getTerm(int i) {
- if (i == 0)
- return term;
- if (i == 1) {
- if (next != null && next.getBodyTerm().isVar() && next.getBodyNext() == null)
- // if next is the last VAR, return that var
- return next.getBodyTerm();
- else
- return next;
- }
- return null;
- }
-
- @Override
- public void setTerm(int i, Term t) {
- if (i == 0) term = t;
- if (i == 1) System.out.println("Should not set next of body literal!");
- }
-
- @Override
- public boolean apply(Unifier u) {
- // do not apply in next!
- resetHashCodeCache();
- if (term != null && term.apply(u)) {
- if (term.isPlanBody()) { // we can not have "inner" body literals
- formType = ((BodyLiteral)term).getBodyType();
- term = ((BodyLiteral)term).getBodyTerm();
- }
- return true;
- }
- return false;
- }
-
- @Override
- public boolean equals(Object o) {
- if (o == null) return false;
- if (o == this) return true;
-
- if (o instanceof BodyLiteral) {
- BodyLiteral b = (BodyLiteral)o;
- return formType == b.getBodyType() && super.equals(o);
- }
- return false;
- }
-
- @Override
- public int calcHashCode() {
- return formType.hashCode() + super.calcHashCode();
- }
-
- public boolean add(BodyLiteral bl) {
- if (term == null)
- swap(bl);
- else if (next == null)
- next = bl;
- else
- next.add(bl);
- return true;
- }
-
- public boolean add(int index, BodyLiteral bl) {
- if (index == 0) {
- swap(bl);
- this.next = bl;
- } else {
- next.add(index - 1, bl);
- }
- return true;
- }
-
- public Term removeBody(int index) {
- if (index == 0) {
- if (next == null) {
- term = null; // becomes an empty
- } else {
- Term oldvalue = term;
- swap(next); // get values of text
- next = next.getBodyNext();
- return oldvalue;
- }
- return this;
- } else {
- return next.removeBody(index - 1);
- }
- }
-
- public int getPlanSize() {
- if (term == null)
- return 0;
- else if (next == null)
- return 1;
- else
- return next.getPlanSize() + 1;
- }
-
- private void swap(BodyLiteral bl) {
- BodyType bt = this.formType;
- this.formType = bl.getBodyType();
- bl.setBodyType(bt);
-
- Term l = this.term;
- this.term = bl.getBodyTerm();
- bl.setBodyTerm(l);
- }
-
- public Object clone() {
- if (term == null) // empty
- return new BodyLiteralImpl();
-
- BodyLiteralImpl c = new BodyLiteralImpl(formType, (Term)term.clone());
- if (next != null)
- c.setBodyNext((BodyLiteral)getBodyNext().clone());
- return c;
- }
-
- public String toString() {
- if (term == null)
- return "";
- else if (next == null)
- return formType.toString() + term;
- else
- return formType.toString() + term + "; " + next;
- }
-
- /** get as XML */
- public Element getAsDOM(Document document) {
- Element eb = (Element) document.createElement("body");
- BodyLiteral bl = this;
- while (bl != null && !bl.isEmptyBody()) {
- Element u = (Element) document.createElement("body-literal");
- if (bl.getBodyType().toString().length() > 0) {
- u.setAttribute("type", bl.getBodyType().toString());
- }
- u.appendChild( ((Structure)bl.getBodyTerm()).getAsDOM(document));
- eb.appendChild(u);
-
- bl = bl.getBodyNext();
- }
- return eb;
- }
-}
Modified: trunk/src/jason/asSyntax/Plan.java
===================================================================
--- trunk/src/jason/asSyntax/Plan.java 2008-03-31 19:25:02 UTC (rev 1182)
+++ trunk/src/jason/asSyntax/Plan.java 2008-03-31 20:04:20 UTC (rev 1183)
@@ -51,7 +51,7 @@
private Pred label = null;
private Trigger tevent = null;
private LogicalFormula context;
- private BodyLiteral body;
+ private PlanBody body;
private boolean isAtomic = false;
@@ -63,12 +63,12 @@
}
// used by parser
- public Plan(Pred label, Trigger te, LogicalFormula ct, BodyLiteral bd) {
+ public Plan(Pred label, Trigger te, LogicalFormula ct, PlanBody bd) {
tevent = te;
setLabel(label);
setContext(ct);
if (bd == null)
- body = new BodyLiteralImpl();
+ body = new PlanBodyImpl();
else
body = bd;
}
@@ -121,7 +121,7 @@
return context;
}
- public BodyLiteral getBody() {
+ public PlanBody getBody() {
return body;
}
@@ -201,7 +201,7 @@
if (context != null)
p.context = (LogicalFormula)context.clone();
- p.body = (BodyLiteral)body.clone();
+ p.body = (PlanBody)body.clone();
p.setSrc(this);
@@ -219,7 +219,7 @@
p.tevent = (Trigger)tevent.clone();
p.context = context;
- p.body = (BodyLiteral)body.clone();
+ p.body = (PlanBody)body.clone();
p.setSrc(this);
Modified: trunk/src/jason/asSyntax/PlanLibrary.java
===================================================================
--- trunk/src/jason/asSyntax/PlanLibrary.java 2008-03-31 19:25:02 UTC (rev 1182)
+++ trunk/src/jason/asSyntax/PlanLibrary.java 2008-03-31 20:04:20 UTC (rev 1183)
@@ -195,7 +195,7 @@
* Remove a plan represented by the label <i>pLabel</i>.
* In case the plan has many sources, only the plan's source is removed.
*/
- public boolean removePlan(Structure pLabel, Structure source) {
+ public boolean remove(Structure pLabel, Structure source) {
// find the plan
Plan p = get(pLabel.getFunctor());
if (p != null) {
Modified: trunk/src/jason/asSyntax/VarTerm.java
===================================================================
--- trunk/src/jason/asSyntax/VarTerm.java 2008-03-31 19:25:02 UTC (rev 1182)
+++ trunk/src/jason/asSyntax/VarTerm.java 2008-03-31 20:04:20 UTC (rev 1183)
@@ -46,7 +46,7 @@
*
* @author jomi
*/
-public class VarTerm extends Literal implements NumberTerm, ListTerm, StringTerm, ObjectTerm, BodyLiteral {
+public class VarTerm extends Literal implements NumberTerm, ListTerm, StringTerm, ObjectTerm, PlanBody {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(VarTerm.class.getName());
@@ -873,72 +873,72 @@
// -----------------------
public BodyType getBodyType() {
- if (value != null && getValue() instanceof BodyLiteral)
- return ((BodyLiteral) getValue()).getBodyType();
+ if (value != null && getValue() instanceof PlanBody)
+ return ((PlanBody) getValue()).getBodyType();
else
return BodyType.none;
}
public Term getBodyTerm() {
- if (value != null && getValue() instanceof BodyLiteral)
- return ((BodyLiteral) getValue()).getBodyTerm();
+ if (value != null && getValue() instanceof PlanBody)
+ return ((PlanBody) getValue()).getBodyTerm();
else
return null;
}
- public BodyLiteral getBodyNext() {
- if (value != null && getValue() instanceof BodyLiteral)
- return ((BodyLiteral) getValue()).getBodyNext();
+ public PlanBody getBodyNext() {
+ if (value != null && getValue() instanceof PlanBody)
+ return ((PlanBody) getValue()).getBodyNext();
else
return null;
}
public boolean isEmptyBody() {
- if (value != null && getValue() instanceof BodyLiteral)
- return ((BodyLiteral) getValue()).isEmptyBody();
+ if (value != null && getValue() instanceof PlanBody)
+ return ((PlanBody) getValue()).isEmptyBody();
else
return true;
}
public int getPlanSize() {
- if (value != null && getValue() instanceof BodyLiteral)
- return ((BodyLiteral) getValue()).getPlanSize();
+ if (value != null && getValue() instanceof PlanBody)
+ return ((PlanBody) getValue()).getPlanSize();
else
return 0;
}
public void setBodyType(BodyType bt) {
- if (value != null && getValue() instanceof BodyLiteral)
- ((BodyLiteral) getValue()).setBodyType(bt);
+ if (value != null && getValue() instanceof PlanBody)
+ ((PlanBody) getValue()).setBodyType(bt);
}
public void setBodyTerm(Term t) {
- if (value != null && getValue() instanceof BodyLiteral)
- ((BodyLiteral) getValue()).setBodyTerm(t);
+ if (value != null && getValue() instanceof PlanBody)
+ ((PlanBody) getValue()).setBodyTerm(t);
}
- public void setBodyNext(BodyLiteral bl) {
- if (value != null && getValue() instanceof BodyLiteral)
- ((BodyLiteral) getValue()).setBodyNext(bl);
+ public void setBodyNext(PlanBody bl) {
+ if (value != null && getValue() instanceof PlanBody)
+ ((PlanBody) getValue()).setBodyNext(bl);
}
- public boolean add(BodyLiteral bl) {
- if (value != null && getValue() instanceof BodyLiteral)
- return ((BodyLiteral) getValue()).add(bl);
+ public boolean add(PlanBody bl) {
+ if (value != null && getValue() instanceof PlanBody)
+ return ((PlanBody) getValue()).add(bl);
else
return false;
}
- public boolean add(int index, BodyLiteral bl) {
- if (value != null && getValue() instanceof BodyLiteral)
- return ((BodyLiteral) getValue()).add(index, bl);
+ public boolean add(int index, PlanBody bl) {
+ if (value != null && getValue() instanceof PlanBody)
+ return ((PlanBody) getValue()).add(index, bl);
else
return false;
}
public Term removeBody(int index) {
- if (value != null && getValue() instanceof BodyLiteral)
- return ((BodyLiteral) getValue()).removeBody(index);
+ if (value != null && getValue() instanceof PlanBody)
+ return ((PlanBody) getValue()).removeBody(index);
else
return null;
}
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-31 19:25:02 UTC (rev 1182)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-31 20:04:20 UTC (rev 1183)
@@ -43,7 +43,7 @@
import jason.asSyntax.ArithExpr.ArithmeticOp;
import jason.asSyntax.LogExpr.LogicalOp;
import jason.asSyntax.RelExpr.RelationalOp;
- import jason.asSyntax.BodyLiteral.BodyType;
+ import jason.asSyntax.PlanBody.BodyType;
import jason.asSyntax.Trigger.TEOperator;
import jason.asSyntax.Trigger.TEType;
import jason.jeditplugin.*;
@@ -289,7 +289,7 @@
/* Plan */
Plan plan() : { Token k; Pred L = null;
Trigger T;
- Object C = null; BodyLiteral bl = null;
+ Object C = null; PlanBody bl = null;
Object B = null;
int start = -1, end;}
{
@@ -304,11 +304,11 @@
if (ial != null)
throw new ParseException(getSourceRef(ial)+" The internal action '"+ial+"' can not be used in plan's context!");
if (B != null) {
- if (!(B instanceof BodyLiteral))
+ if (!(B instanceof PlanBody))
throw new ParseException(getSourceRef(B)+" Unknown body formula:"+B);
- bl = (BodyLiteral)B;
+ bl = (PlanBody)B;
if (bl.getBodyTerm().equals(Literal.LTrue))
- bl = (BodyLiteral)bl.getBodyNext();
+ bl = (PlanBody)bl.getBodyNext();
}
Plan p = new Plan(L,T,(LogicalFormula)C, bl);
p.setSrcLines(start,end);
@@ -366,11 +366,11 @@
{
F = body_formula()
- [ ";" { if (!(F instanceof BodyLiteral)) throw new ParseException(getSourceRef(F)+" "+F+" is not a body literal!"); }
- R = plan_body() { if (!(R instanceof BodyLiteral)) throw new ParseException(getSourceRef(R)+" "+R+" is not a body literal!"); }
+ [ ";" { if (!(F instanceof PlanBody)) throw new ParseException(getSourceRef(F)+" "+F+" is not a body literal!"); }
+ R = plan_body() { if (!(R instanceof PlanBody)) throw new ParseException(getSourceRef(R)+" "+R+" is not a body literal!"); }
]
- { if (F instanceof BodyLiteral && R instanceof BodyLiteral) {
- ((BodyLiteral)F).setBodyNext( (BodyLiteral)R );
+ { if (F instanceof PlanBody && R instanceof PlanBody) {
+ ((PlanBody)F).setBodyNext( (PlanBody)R );
}
return F;
}
@@ -394,13 +394,13 @@
{ if (B instanceof Literal) {
if ( ((Literal)B).isInternalAction() )
formType = BodyType.internalAction;
- return new BodyLiteralImpl(formType, (Literal)B);
+ return new PlanBodyImpl(formType, (Literal)B);
} else if (formType == BodyType.action && B instanceof RelExpr) {
- return new BodyLiteralImpl(BodyType.constraint, (RelExpr)B); // constraint
+ return new PlanBodyImpl(BodyType.constraint, (RelExpr)B); // constraint
} else {
if (formType == BodyType.test) {
if (B instanceof LogicalFormula)
- return new BodyLiteralImpl(BodyType.test, (Term)B); // used in ?(a & b)
+ return new PlanBodyImpl(BodyType.test, (Term)B); // used in ?(a & b)
else
throw new ParseException(getSourceRef(B)+" The argument for ? is not a logical formula.");
} else {
@@ -451,9 +451,9 @@
( o=list()
| o=log_expr() //plan_body() // plan_body includes literals/atoms/structures
)
- { // if the result is a BodyLiteral action with size = 1, it is indeed a literal and not a body literal
- /*if (o instanceof BodyLiteral) {
- BodyLiteral bl = (BodyLiteral)o;
+ { // if the result is a PlanBody action with size = 1, it is indeed a literal and not a body literal
+ /*if (o instanceof PlanBody) {
+ PlanBody bl = (PlanBody)o;
if (bl.getBodyType() == BodyType.action && bl.getPlanSize() == 1) {
o = bl.getBodyTerm();
}
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2008-03-31 19:25:02 UTC (rev 1182)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2008-03-31 20:04:20 UTC (rev 1183)
@@ -13,7 +13,7 @@
import jason.asSyntax.ArithExpr.ArithmeticOp;
import jason.asSyntax.LogExpr.LogicalOp;
import jason.asSyntax.RelExpr.RelationalOp;
- import jason.asSyntax.BodyLiteral.BodyType;
+ import jason.asSyntax.PlanBody.BodyType;
import jason.asSyntax.Trigger.TEOperator;
import jason.asSyntax.Trigger.TEType;
import jason.jeditplugin.*;
@@ -316,7 +316,7 @@
final public Plan plan() throws ParseException {
Token k; Pred L = null;
Trigger T;
- Object C = null; BodyLiteral bl = null;
+ Object C = null; PlanBody bl = null;
Object B = null;
int start = -1, end;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
@@ -358,11 +358,11 @@
if (ial != null)
{if (true) throw new ParseException(getSourceRef(ial)+" The internal action '"+ial+"' can not be used in plan's context!");}
if (B != null) {
- if (!(B instanceof BodyLiteral))
+ if (!(B instanceof PlanBody))
{if (true) throw new ParseException(getSourceRef(B)+" Unknown body formula:"+B);}
- bl = (BodyLiteral)B;
+ bl = (PlanBody)B;
if (bl.getBodyTerm().equals(Literal.LTrue))
- bl = (BodyLiteral)bl.getBodyNext();
+ bl = (PlanBody)bl.getBodyNext();
}
Plan p = new Plan(L,T,(LogicalFormula)C, bl);
p.setSrcLines(start,end);
@@ -485,16 +485,16 @@
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 37:
jj_consume_token(37);
- if (!(F instanceof BodyLiteral)) {if (true) throw new ParseException(getSourceRef(F)+" "+F+" is not a body literal!");}
+ if (!(F instanceof PlanBody)) {if (true) throw new ParseException(getSourceRef(F)+" "+F+" is not a body literal!");}
R = plan_body();
- if (!(R instanceof BodyLiteral)) {if (true) throw new ParseException(getSourceRef(R)+" "+R+" is not a body literal!");}
+ if (!(R instanceof PlanBody)) {if (true) throw new ParseException(getSourceRef(R)+" "+R+" is not a body literal!");}
break;
default:
jj_la1[19] = jj_gen;
;
}
- if (F instanceof BodyLiteral && R instanceof BodyLiteral) {
- ((BodyLiteral)F).setBodyNext( (BodyLiteral)R );
+ if (F instanceof PlanBody && R instanceof PlanBody) {
+ ((PlanBody)F).setBodyNext( (PlanBody)R );
}
{if (true) return F;}
throw new Error("Missing return statement in function");
@@ -552,13 +552,13 @@
if (B instanceof Literal) {
if ( ((Literal)B).isInternalAction() )
formType = BodyType.internalAction;
- {if (true) return new BodyLiteralImpl(formType, (Literal)B);}
+ {if (true) return new PlanBodyImpl(formType, (Literal)B);}
} else if (formType == BodyType.action && B instanceof R...
[truncated message content] |
|
From: <jom...@us...> - 2008-04-07 13:27:41
|
Revision: 1205
http://jason.svn.sourceforge.net/jason/?rev=1205&view=rev
Author: jomifred
Date: 2008-04-07 06:27:34 -0700 (Mon, 07 Apr 2008)
Log Message:
-----------
set next version as 1.1
Modified Paths:
--------------
trunk/applications/jason-eclipse-plugin/README-jason-eclipse-plugin.txt
trunk/applications/jason-team/readme.txt
trunk/build.xml
trunk/doc/faq/faq.tex
trunk/release-notes.txt
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
Modified: trunk/applications/jason-eclipse-plugin/README-jason-eclipse-plugin.txt
===================================================================
--- trunk/applications/jason-eclipse-plugin/README-jason-eclipse-plugin.txt 2008-04-07 12:21:23 UTC (rev 1204)
+++ trunk/applications/jason-eclipse-plugin/README-jason-eclipse-plugin.txt 2008-04-07 13:27:34 UTC (rev 1205)
@@ -1,7 +1,7 @@
-Jason Plugin for Eclipse
-
-Requirements
-. Jason >= 1.0.1
-. Eclipse >= 3.2
-
-More information at http://jasonplugin.wikidot.com
\ No newline at end of file
+Jason Plugin for Eclipse
+
+Requirements
+. Jason >= 1.0.1
+. Eclipse >= 3.2
+
+More information at http://jasonplugin.wikidot.com
Modified: trunk/applications/jason-team/readme.txt
===================================================================
--- trunk/applications/jason-team/readme.txt 2008-04-07 12:21:23 UTC (rev 1204)
+++ trunk/applications/jason-team/readme.txt 2008-04-07 13:27:34 UTC (rev 1205)
@@ -1,66 +1,66 @@
-/*
- * Jason Team for the
- * Multi-Agent Programming Contest 2008
- * (http://cig.in.tu-clausthal.de/agentcontest2008)
- *
- * By
- * Jomi F. Hubner (EMSE, France)
- * Rafael H. Bordini (Durhma, UK)
- * Gauthier Picard (EMSE, France)
- */
-
-
-To run this team:
-
-1. update sources of Jason
- cd Jason-svn
- svn update
- ant plugin
-
-2. run massim-server
- cd applications/jason-team/massim-server
- ./startServer.sh
-
-3. run massim-agents (6 agents developed by the ContestTeam)
- cd ../massim-agents
- ./startAgents.sh
-
-4. run Jason dummies (for now we do not have a team)
- a. by JasonIDE
- ../../bin/jason.sh
- open an run AC-Local-JasonTeam.mas2j
-
- b. by Ant (only after run once by JasonIDE)
- ant -f bin/build.xml
-
-5. start the simulation
- go to shell running startServer.sh and press ENTER
-
-6. you can get the agents location with the command
-
- tail -f world-status.txt
-
-7. the get the graphical view of some agent, add gui=yes in
- the agent's option (.mas2j file)
-
-
-
----- OLD ----
-
-Our team can run in three configurations (Jason 1.0.2 is required):
-
-1. With a local simulator developed by us to test the team.
-
- Using JasonIDE, open the project Local-JasonTeam.mas2j and
- run it.
-
-2. With the competition simulator running at localhost.
-
- Using JasonIDE, open the project AC-Local-JasonTeam.mas2j
- and run it.
-
-3. With the competition simulator (during the tournament)
-
- Using JasonIDE, open the project AC-JasonTeam.mas2j
- and run it.
-
+/*
+ * Jason Team for the
+ * Multi-Agent Programming Contest 2008
+ * (http://cig.in.tu-clausthal.de/agentcontest2008)
+ *
+ * By
+ * Jomi F. Hubner (EMSE, France)
+ * Rafael H. Bordini (Durhma, UK)
+ * Gauthier Picard (EMSE, France)
+ */
+
+
+To run this team:
+
+1. update sources of Jason
+ cd Jason-svn
+ svn update
+ ant plugin
+
+2. run massim-server
+ cd applications/jason-team/massim-server
+ ./startServer.sh
+
+3. run massim-agents (6 agents developed by the ContestTeam)
+ cd ../massim-agents
+ ./startAgents.sh
+
+4. run Jason dummies (for now we do not have a team)
+ a. by JasonIDE
+ ../../bin/jason.sh
+ open an run AC-Local-JasonTeam.mas2j
+
+ b. by Ant (only after run once by JasonIDE)
+ ant -f bin/build.xml
+
+5. start the simulation
+ go to shell running startServer.sh and press ENTER
+
+6. you can get the agents location with the command
+
+ tail -f world-status.txt
+
+7. the get the graphical view of some agent, add gui=yes in
+ the agent's option (.mas2j file)
+
+
+
+---- OLD ----
+
+Our team can run in three configurations (Jason 1.0.2 is required):
+
+1. With a local simulator developed by us to test the team.
+
+ Using JasonIDE, open the project Local-JasonTeam.mas2j and
+ run it.
+
+2. With the competition simulator running at localhost.
+
+ Using JasonIDE, open the project AC-Local-JasonTeam.mas2j
+ and run it.
+
+3. With the competition simulator (during the tournament)
+
+ Using JasonIDE, open the project AC-JasonTeam.mas2j
+ and run it.
+
Modified: trunk/build.xml
===================================================================
--- trunk/build.xml 2008-04-07 12:21:23 UTC (rev 1204)
+++ trunk/build.xml 2008-04-07 13:27:34 UTC (rev 1205)
@@ -14,7 +14,7 @@
<property name="dist.properties" value="${basedir}/bin/dist.properties" />
<property name="version" value="1" />
- <property name="release" value="0.2" />
+ <property name="release" value="1" />
<property name="distDir" value="${env.HOME}/tmp/x/Jason-${version}.${release}" />
<property name="distFile" value="${env.HOME}/Jason-${version}.${release}" />
Modified: trunk/doc/faq/faq.tex
===================================================================
--- trunk/doc/faq/faq.tex 2008-04-07 12:21:23 UTC (rev 1204)
+++ trunk/doc/faq/faq.tex 2008-04-07 13:27:34 UTC (rev 1205)
@@ -17,7 +17,7 @@
\html{\begin{rawhtml}<h0><b><i>Jason</i></b> FAQ
- <br><font size="-1">(for version 1.0.1)</font></h0>
+ <br><font size="-1">(for version 1.1)</font></h0>
\end{rawhtml}}
\latex{\begin{center}{\Huge\jason FAQ}\end{center}}
Modified: trunk/release-notes.txt
===================================================================
--- trunk/release-notes.txt 2008-04-07 12:21:23 UTC (rev 1204)
+++ trunk/release-notes.txt 2008-04-07 13:27:34 UTC (rev 1205)
@@ -20,8 +20,8 @@
. A list of goals can be sent with the "achieve" performative:
.send(bob,achieve,[g1,g2,g3])
- Note that each will become a separate intention of bob (if
- the message is accepted).
+ Note that each goal will become a separate intention of bob
+ (if the message is accepted).
New example:
. the Jason team used in the Agent Contest 2007 was added to the
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-04-07 12:21:23 UTC (rev 1204)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-04-07 13:27:34 UTC (rev 1205)
@@ -339,28 +339,7 @@
) { return new Trigger(teOp,teType,F); }
}
-/* Literal */
-Literal literal() : { Pred F; Token k; boolean type = Literal.LPos; }
-{
- ( ( [ <TK_NEG> { type = Literal.LNeg; }
- ]
- F=pred() { if (F.getFunctor().indexOf(".") >= 0) {
- try {
- return new InternalActionLiteral(F, curAg);
- } catch (Exception e) {
- if (getArithFunction(F) == null) // it is not a registered function
- throw new ParseException(getSourceRef(F)+" The internal action class for '"+F+"' was not found!");
- }
- }
- return new Literal(type,F);
- }
- )
- | k=<TK_TRUE> { return Literal.LTrue; }
- | k=<TK_FALSE> { return Literal.LFalse; }
- )
-}
-
/* Plan body */
Object plan_body() : { Object F; Object R = null; }
{
@@ -411,6 +390,27 @@
}
+/* Literal */
+Literal literal() : { Pred F; Token k; boolean type = Literal.LPos; }
+{
+ ( ( [ <TK_NEG> { type = Literal.LNeg; }
+ ]
+ F=pred() { if (F.getFunctor().indexOf(".") >= 0) {
+ try {
+ return new InternalActionLiteral(F, curAg);
+ } catch (Exception e) {
+ if (getArithFunction(F) == null) // it is not a registered function
+ throw new ParseException(getSourceRef(F)+" The internal action class for '"+F+"' was not found!");
+ }
+ }
+ return new Literal(type,F);
+ }
+ )
+ | k=<TK_TRUE> { return Literal.LTrue; }
+ | k=<TK_FALSE> { return Literal.LFalse; }
+ )
+}
+
/* Annotated Formulae */
Pred pred() : { Token K; Pred p; List l; ListTerm lt;}
{
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2008-04-07 12:21:23 UTC (rev 1204)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2008-04-07 13:27:34 UTC (rev 1205)
@@ -434,50 +434,6 @@
throw new Error("Missing return statement in function");
}
-/* Literal */
- final public Literal literal() throws ParseException {
- Pred F; Token k; boolean type = Literal.LPos;
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case TK_NEG:
- case TK_BEGIN:
- case TK_END:
- case ATOM:
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case TK_NEG:
- jj_consume_token(TK_NEG);
- type = Literal.LNeg;
- break;
- default:
- jj_la1[17] = jj_gen;
- ;
- }
- F = pred();
- if (F.getFunctor().indexOf(".") >= 0) {
- try {
- {if (true) return new InternalActionLiteral(F, curAg);}
- } catch (Exception e) {
- if (getArithFunction(F) == null) // it is not a registered function
- {if (true) throw new ParseException(getSourceRef(F)+" The internal action class for '"+F+"' was not found!");}
- }
- }
- {if (true) return new Literal(type,F);}
- break;
- case TK_TRUE:
- k = jj_consume_token(TK_TRUE);
- {if (true) return Literal.LTrue;}
- break;
- case TK_FALSE:
- k = jj_consume_token(TK_FALSE);
- {if (true) return Literal.LFalse;}
- break;
- default:
- jj_la1[18] = jj_gen;
- jj_consume_token(-1);
- throw new ParseException();
- }
- throw new Error("Missing return statement in function");
- }
-
/* Plan body */
final public Object plan_body() throws ParseException {
Object F; Object R = null;
@@ -490,7 +446,7 @@
if (!(R instanceof PlanBody)) {if (true) throw new ParseException(getSourceRef(R)+" "+R+" is not a body literal!");}
break;
default:
- jj_la1[19] = jj_gen;
+ jj_la1[17] = jj_gen;
;
}
if (F instanceof PlanBody && R instanceof PlanBody) {
@@ -534,18 +490,18 @@
formType = BodyType.delAddBel;
break;
default:
- jj_la1[20] = jj_gen;
+ jj_la1[18] = jj_gen;
;
}
break;
default:
- jj_la1[21] = jj_gen;
+ jj_la1[19] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
break;
default:
- jj_la1[22] = jj_gen;
+ jj_la1[20] = jj_gen;
;
}
B = log_expr();
@@ -568,6 +524,50 @@
throw new Error("Missing return statement in function");
}
+/* Literal */
+ final public Literal literal() throws ParseException {
+ Pred F; Token k; boolean type = Literal.LPos;
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case TK_NEG:
+ case TK_BEGIN:
+ case TK_END:
+ case ATOM:
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case TK_NEG:
+ jj_consume_token(TK_NEG);
+ type = Literal.LNeg;
+ break;
+ default:
+ jj_la1[21] = jj_gen;
+ ;
+ }
+ F = pred();
+ if (F.getFunctor().indexOf(".") >= 0) {
+ try {
+ {if (true) return new InternalActionLiteral(F, curAg);}
+ } catch (Exception e) {
+ if (getArithFunction(F) == null) // it is not a registered function
+ {if (true) throw new ParseException(getSourceRef(F)+" The internal action class for '"+F+"' was not found!");}
+ }
+ }
+ {if (true) return new Literal(type,F);}
+ break;
+ case TK_TRUE:
+ k = jj_consume_token(TK_TRUE);
+ {if (true) return Literal.LTrue;}
+ break;
+ case TK_FALSE:
+ k = jj_consume_token(TK_FALSE);
+ {if (true) return Literal.LFalse;}
+ break;
+ default:
+ jj_la1[22] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ throw new Error("Missing return statement in function");
+ }
+
/* Annotated Formulae */
final public Pred pred() throws ParseException {
Token K; Pred p; List l; ListTerm lt;
@@ -1236,10 +1236,10 @@
jj_la1_1();
}
private static void jj_la1_0() {
- jj_la1_0 = new int[] {0x8000000,0x10cb00,0x8000000,0x80000000,0x8000000,0x10000,0x10cb00,0x8000000,0x8000000,0x20000000,0x10000,0x0,0x0,0x0,0x80000000,0x80000000,0x30cb80,0x800,0x10cb00,0x0,0x0,0x80000000,0x80000000,0x10c000,0x0,0x0,0x0,0x3acf80,0x0,0x200080,0x0,0x3acb80,0x3acb80,0x0,0x0,0x3acf80,0x3acb80,0x0,0x3acb80,0x0,0x0,0x0,0x3000,0x3000,0x0,0x32cb80,0x200080,0x0,};
+ jj_la1_0 = new int[] {0x8000000,0x10cb00,0x8000000,0x80000000,0x8000000,0x10000,0x10cb00,0x8000000,0x8000000,0x20000000,0x10000,0x0,0x0,0x0,0x80000000,0x80000000,0x30cb80,0x0,0x0,0x80000000,0x80000000,0x800,0x10cb00,0x10c000,0x0,0x0,0x0,0x3acf80,0x0,0x200080,0x0,0x3acb80,0x3acb80,0x0,0x0,0x3acf80,0x3acb80,0x0,0x3acb80,0x0,0x0,0x0,0x3000,0x3000,0x0,0x32cb80,0x200080,0x0,};
}
private static void jj_la1_1() {
- jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0xc,0x0,0x0,0x0,0x0,0x0,0x1,0x2,0xc,0x10,0x10,0x0,0x0,0x0,0x20,0x4,0x5c,0x5c,0x0,0x80,0x400,0x200,0x488,0x200,0x400,0x800,0x488,0x488,0x800,0x2000,0x88,0x88,0x3fc000,0x488,0x3fc000,0xc,0xc,0xc00000,0xc00000,0x1000000,0x88,0x0,0x400,};
+ jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0xc,0x0,0x0,0x0,0x0,0x0,0x1,0x2,0xc,0x10,0x10,0x0,0x20,0x4,0x5c,0x5c,0x0,0x0,0x0,0x80,0x400,0x200,0x488,0x200,0x400,0x800,0x488,0x488,0x800,0x2000,0x88,0x88,0x3fc000,0x488,0x3fc000,0xc,0xc,0xc00000,0xc00000,0x1000000,0x88,0x0,0x400,};
}
final private JJCalls[] jj_2_rtns = new JJCalls[1];
private boolean jj_rescan = false;
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-04-08 16:38:36
|
Revision: 1206
http://jason.svn.sourceforge.net/jason/?rev=1206&view=rev
Author: jomifred
Date: 2008-04-08 09:38:29 -0700 (Tue, 08 Apr 2008)
Log Message:
-----------
jason team: dummies can push cows!
Modified Paths:
--------------
trunk/applications/jason-team/AC-Local-JasonTeam.mas2j
trunk/applications/jason-team/src/asl/dummy.asl
trunk/applications/jason-team/src/java/arch/ACProxy.java
trunk/applications/jason-team/src/java/arch/CowboyArch.java
trunk/applications/jason-team/src/java/arch/LocalWorldModel.java
trunk/applications/jason-team/src/java/env/WorldModel.java
trunk/applications/jason-team/src/java/jia/Search.java
trunk/applications/jason-team/src/java/jia/direction.java
trunk/src/jason/environment/grid/Location.java
Added Paths:
-----------
trunk/applications/jason-team/src/java/jia/Vec.java
trunk/applications/jason-team/src/java/jia/herd_position.java
trunk/applications/jason-team/src/java/test/
trunk/applications/jason-team/src/java/test/TestBasicHerding.java
Modified: trunk/applications/jason-team/AC-Local-JasonTeam.mas2j
===================================================================
--- trunk/applications/jason-team/AC-Local-JasonTeam.mas2j 2008-04-07 13:27:34 UTC (rev 1205)
+++ trunk/applications/jason-team/AC-Local-JasonTeam.mas2j 2008-04-08 16:38:29 UTC (rev 1206)
@@ -42,5 +42,5 @@
agentClass agent.SelectEvent
beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)","corral(_,_,_,_)","pratio(_)");
- aslSourcePath: "src/asl";
+ aslSourcePath: "src/asl";
}
Modified: trunk/applications/jason-team/src/asl/dummy.asl
===================================================================
--- trunk/applications/jason-team/src/asl/dummy.asl 2008-04-07 13:27:34 UTC (rev 1205)
+++ trunk/applications/jason-team/src/asl/dummy.asl 2008-04-08 16:38:29 UTC (rev 1206)
@@ -33,13 +33,31 @@
!move.
+/* -- reaction to cows -- */
+
++pos(_,_,_) // new cycle
+ : cell(_,_,cow(_)) // I see cows
+ <- jia.herd_position(X,Y); // compute new location
+ .print("COWS! going to ",X,",",Y);
+ -+target(X,Y). // go to there
+
+
+/* -- what todo when arrive at location */
+
++!decide_target // chose a new random pos
+ : not cell(_,_,cow(_))
+ <- ?random_pos(NX,NY);
+ -+target(NX,NY).
++!decide_target.
+
/* -- plans to move to a destination represented in the belief target(X,Y)
-- (it is a kind of persistent goal)
*/
// if the target is changed, "restart" move
-+target(_,_)
++target(NX,NY)
<- .drop_desire(move);
+ jia.set_target(NX,NY);
!!move.
// I still do not know my location
@@ -55,9 +73,7 @@
(not target(_,_) | // I have no target OR
target(X,Y) | // I am at target OR
(target(BX,BY) & jia.direction(X, Y, BX, BY, skip))) // is impossible to go to target
- <- ?random_pos(NX,NY);
- jia.set_target(NX,NY);
- -+target(NX,NY).
+ <- !decide_target.
// does one step towards target
+!move
Modified: trunk/applications/jason-team/src/java/arch/ACProxy.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/ACProxy.java 2008-04-07 13:27:34 UTC (rev 1205)
+++ trunk/applications/jason-team/src/java/arch/ACProxy.java 2008-04-08 16:38:29 UTC (rev 1206)
@@ -160,7 +160,9 @@
lpos.addTerm(new NumberTermImpl(step));
percepts.add(lpos);
- int enemyId = 1;
+ arq.getModel().clearCowsList();
+
+ int enemyId = 1;
// add in perception what is around
NodeList nl = perception.getElementsByTagName("cell");
for (int i=0; i < nl.getLength(); i++) {
Modified: trunk/applications/jason-team/src/java/arch/CowboyArch.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/CowboyArch.java 2008-04-07 13:27:34 UTC (rev 1205)
+++ trunk/applications/jason-team/src/java/arch/CowboyArch.java 2008-04-08 16:38:29 UTC (rev 1206)
@@ -237,9 +237,8 @@
return l;
}
-
void cowPerceived(int x, int y) {
- model.add(WorldModel.COW, x, y);
+ model.addCow(x,y);
}
void enemyPerceived(int x, int y) {
Modified: trunk/applications/jason-team/src/java/arch/LocalWorldModel.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/LocalWorldModel.java 2008-04-07 13:27:34 UTC (rev 1205)
+++ trunk/applications/jason-team/src/java/arch/LocalWorldModel.java 2008-04-08 16:38:29 UTC (rev 1206)
@@ -2,6 +2,8 @@
import jason.environment.grid.Location;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Random;
import env.WorldModel;
@@ -19,6 +21,8 @@
private Random random = new Random();
+ List<Location> cows = new ArrayList<Location>();
+
//private Logger logger = Logger.getLogger("jasonTeamSimLocal.mas2j." + LocalWorldModel.class.getName());
public static LocalWorldModel create(int w, int h, int nbAg) {
@@ -40,6 +44,33 @@
}
}
+ public void clearCowsList() {
+ cows.clear();
+ }
+ public void addCow(int x, int y) {
+ add(WorldModel.COW, x, y);
+ cows.add(new Location(x,y));
+ }
+ public void addCow(Location l) {
+ addCow(l.x, l.y);
+ }
+ public List<Location> getCows() {
+ return cows;
+ }
+
+ public Location nearFree(Location l) throws Exception {
+ int w = 1;
+ while (true) {
+ for (int x=l.x-w; x<=l.x+w;x++)
+ if (isFree(x,l.y))
+ return new Location(x,l.y);
+ for (int y=l.y-w; y<=l.y+w;y++)
+ if (isFree(l.x,y))
+ return new Location(l.x,y);
+ w++;
+ }
+ }
+
public int getVisited(Location l) {
return visited[l.x][l.y];
}
Modified: trunk/applications/jason-team/src/java/env/WorldModel.java
===================================================================
--- trunk/applications/jason-team/src/java/env/WorldModel.java 2008-04-07 13:27:34 UTC (rev 1205)
+++ trunk/applications/jason-team/src/java/env/WorldModel.java 2008-04-08 16:38:29 UTC (rev 1206)
@@ -77,6 +77,10 @@
return l.x >= corralUL.x && l.x <= corralDR.x &&
l.y >= corralUL.y && l.y <= corralDR.y;
}
+
+ public Location getCorralCenter() {
+ return new Location( (corralUL.x + corralDR.x)/2, (corralUL.y + corralDR.y)/2);
+ }
public int getCowsBlue() {
return cowsBlue;
@@ -228,4 +232,19 @@
return s.toString();
}
+
+ public static Location getNewLocationForAction(Location pos, WorldModel.Move action) {
+ switch (action) {
+ case west : return new Location(pos.x-1,pos.y);
+ case east : return new Location(pos.x+1,pos.y);
+ case north : return new Location(pos.x,pos.y-1);
+ case northeast: return new Location(pos.x+1,pos.y-1);
+ case northwest: return new Location(pos.x-1,pos.y-1);
+ case south : return new Location(pos.x,pos.y+1);
+ case southeast: return new Location(pos.x+1,pos.y+1);
+ case southwest: return new Location(pos.x-1,pos.y+1);
+ }
+ return null;
+ }
+
}
Modified: trunk/applications/jason-team/src/java/jia/Search.java
===================================================================
--- trunk/applications/jason-team/src/java/jia/Search.java 2008-04-07 13:27:34 UTC (rev 1205)
+++ trunk/applications/jason-team/src/java/jia/Search.java 2008-04-08 16:38:29 UTC (rev 1206)
@@ -22,19 +22,32 @@
final LocalWorldModel model;
final Location from, to;
final boolean considerAgentsAsObstacles;
- int[] actionsOrder;
+ final boolean considerCorralAsObstacles;
+ final boolean considerCowsAsObstacles;
+ WorldModel.Move[] actionsOrder;
int nbStates = 0;
AgArch agArch;
- static final int[] defaultActions = { 1, 2, 3, 4, 5, 6, 7, 8 }; // initial order of actions
+ public static final WorldModel.Move[] defaultActions = { // initial order of actions
+ WorldModel.Move.west,
+ WorldModel.Move.east,
+ WorldModel.Move.north,
+ WorldModel.Move.northeast,
+ WorldModel.Move.northwest,
+ WorldModel.Move.south,
+ WorldModel.Move.southeast,
+ WorldModel.Move.southwest
+ };
Logger logger = Logger.getLogger(Search.class.getName());
- Search(LocalWorldModel m, Location from, Location to, int[] actions, boolean considerAgentsAsObstacles, AgArch agArch) {
+ public Search(LocalWorldModel m, Location from, Location to, WorldModel.Move[] actions, boolean considerAgentsAsObstacles, boolean considerCorralAsObstacles, boolean considerCowsAsObstacles, AgArch agArch) {
this.model = m;
this.from = from;
this.to = to;
this.considerAgentsAsObstacles = considerAgentsAsObstacles;
+ this.considerCorralAsObstacles = considerCorralAsObstacles;
+ this.considerCowsAsObstacles = considerCowsAsObstacles;
this.agArch = agArch;
if (actions != null) {
this.actionsOrder = actions;
@@ -45,14 +58,14 @@
/** used normally to discover the distance from 'from' to 'to' */
Search(LocalWorldModel m, Location from, Location to, AgArch agArch) {
- this(m,from,to,null,false, agArch);
+ this(m,from,to,null,false, false, false, agArch);
}
public Nodo search() throws Exception {
Busca searchAlg = new AEstrela();
//searchAlg.ssetMaxAbertos(1000);
- GridState root = new GridState(from, WorldModel.Move.skip, this);
- root.setIsRoot();
+ GridState root = new GridState(from, WorldModel.Move.skip, this, 1);
+ root.setAsRoot();
return searchAlg.busca(root);
}
@@ -113,22 +126,24 @@
final Search ia;
final int hashCode;
boolean isRoot = false;
+ int cost = 1;
- public GridState(Location l, WorldModel.Move op, Search ia) {
- this.pos = l;
- this.op = op;
- this.ia = ia;
- hashCode = pos.hashCode();
+ public GridState(Location l, WorldModel.Move op, Search ia, int cost) {
+ this.pos = l;
+ this.op = op;
+ this.ia = ia;
+ this.cost = cost;
+ hashCode = pos.hashCode();
ia.nbStates++;
}
- public void setIsRoot() {
+ public void setAsRoot() {
isRoot = true;
}
public int custo() {
- return 1;
+ return cost;
}
public boolean ehMeta() {
@@ -140,7 +155,7 @@
}
public int h() {
- return pos.distance(ia.to);
+ return pos.maxBorder(ia.to);
}
public List<Estado> sucessores() {
@@ -148,22 +163,13 @@
if (ia.nbStates > 50000) {
ia.logger.info("*** It seems I am in a loop!");
return s;
- } else if (!ia.agArch.isRunning()) {
+ } else if (ia.agArch != null && !ia.agArch.isRunning()) {
return s;
}
// all directions
for (int a = 0; a < ia.actionsOrder.length; a++) {
- switch (ia.actionsOrder[a]) {
- case 1: suc(s,new Location(pos.x-1,pos.y), WorldModel.Move.west); break;
- case 2: suc(s,new Location(pos.x+1,pos.y), WorldModel.Move.east); break;
- case 3: suc(s,new Location(pos.x,pos.y-1), WorldModel.Move.north); break;
- case 4: suc(s,new Location(pos.x+1,pos.y-1), WorldModel.Move.northeast); break;
- case 5: suc(s,new Location(pos.x-1,pos.y-1), WorldModel.Move.northwest); break;
- case 6: suc(s,new Location(pos.x,pos.y+1), WorldModel.Move.south); break;
- case 7: suc(s,new Location(pos.x+1,pos.y+1), WorldModel.Move.southeast); break;
- case 8: suc(s,new Location(pos.x-1,pos.y+1), WorldModel.Move.southwest); break;
- }
+ suc(s, WorldModel.getNewLocationForAction(pos, ia.actionsOrder[a]), ia.actionsOrder[a]);
}
// if it is root state, sort the option by least visited
@@ -172,18 +178,51 @@
}
return s;
}
-
+
private void suc(List<Estado> s, Location newl, WorldModel.Move op) {
- if (ia.model.isFreeOfObstacle(newl) && !ia.model.hasObject(WorldModel.CORRAL, newl)) {
- if (ia.considerAgentsAsObstacles) {
- if ((ia.model.isFree(WorldModel.AGENT,newl) && ia.model.isFree(WorldModel.COW,newl)) || ia.from.distance(newl) > 3) {
- s.add(new GridState(newl,op,ia));
- }
- } else {
- s.add(new GridState(newl,op,ia));
+ if (!ia.model.inGrid(newl))
+ return;
+ if (ia.model.hasObject(WorldModel.OBSTACLE, newl))
+ return;
+ if (ia.considerCorralAsObstacles && ia.model.hasObject(WorldModel.CORRAL, newl))
+ return;
+ if (ia.considerAgentsAsObstacles && ia.model.hasObject(WorldModel.AGENT,newl) && ia.from.maxBorder(newl) <= 2)
+ return;
+ if (ia.considerCowsAsObstacles && ia.model.hasObject(WorldModel.COW,newl) && ia.from.maxBorder(newl) <= 2)
+ return;
+
+ int cost = 1;
+
+ if (ia.considerCowsAsObstacles) {
+ cost += countCowsBeside(newl,1);
+ cost += countCowsBeside(newl,2);
+ }
+
+ s.add(new GridState(newl,op,ia, cost));
+ }
+
+ private int countCowsBeside(Location l, int d) {
+ int c = 0;
+ for (int x = l.x-d; x <= l.x+d; x++) {
+ for (int y = l.y-d; y <= l.y+d; y++) {
+ if (ia.model.hasObject(WorldModel.COW, x, y)) {
+ c++;
+ }
}
- }
+ }
+ return c;
+ /*
+ if (ia.model.hasObject(WorldModel.COW, l.x, l.y)) c++;
+ if (ia.model.hasObject(WorldModel.COW, l.x+1, l.y)) c++;
+ if (ia.model.hasObject(WorldModel.COW, l.x-1, l.y)) c++;
+ if (ia.model.hasObject(WorldModel.COW, l.x, l.y+1)) c++;
+ if (ia.model.hasObject(WorldModel.COW, l.x, l.y-1)) c++;
+ if (ia.model.hasObject(WorldModel.COW, l.x+1, l.y+1)) c++;
+ if (ia.model.hasObject(WorldModel.COW, l.x-1, l.y+1)) c++;
+ if (ia.model.hasObject(WorldModel.COW, l.x+1, l.y-1)) c++;
+ if (ia.model.hasObject(WorldModel.COW, l.x-1, l.y-1)) c++;
+ */
}
public boolean equals(Object o) {
Added: trunk/applications/jason-team/src/java/jia/Vec.java
===================================================================
--- trunk/applications/jason-team/src/java/jia/Vec.java (rev 0)
+++ trunk/applications/jason-team/src/java/jia/Vec.java 2008-04-08 16:38:29 UTC (rev 1206)
@@ -0,0 +1,101 @@
+package jia;
+
+import jason.environment.grid.Location;
+
+import java.util.List;
+
+import arch.LocalWorldModel;
+
+
+public class Vec {
+
+ public final int x,y;
+
+ public Vec(int x, int y) {
+ this.x = x;
+ this.y = y;
+ }
+
+ /** create a vector based on a location in the model */
+ public Vec(LocalWorldModel model, Location l) {
+ this.x = l.x;
+ this.y = model.getHeight()-l.y-1;
+ }
+
+ public int getX() { return x; }
+ public int getY() { return y; }
+ public Location getLocation(LocalWorldModel model) {
+ return new Location(x, model.getHeight()-y-1);
+ }
+
+ public double magnitude() {
+ return Math.sqrt(x*x + y*y);
+ }
+
+ public Vec add(Vec v) {
+ return new Vec(x + v.x, y + v.y);
+ }
+ public Vec sub(Vec v) {
+ return new Vec(x - v.x, y - v.y);
+ }
+ public Vec product(double e) {
+ return new Vec((int)(x * e), (int)(y *e));
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null) return false;
+ if (o == this) return true;
+ if (o instanceof Vec) {
+ Vec v = (Vec)o;
+ return (x == v.x) && (y == v.y);
+ }
+ return false;
+ }
+
+ public static Vec max(List<Vec> vs) {
+ Vec max = null;
+ if (vs.size() > 0)
+ max = vs.get(0);
+ for (Vec v: vs) {
+ if (max.magnitude() < v.magnitude())
+ max = v;
+ }
+ return max;
+ }
+
+ public static Vec mean(List<Vec> vs) {
+ if (vs.isEmpty())
+ return new Vec(0,0);
+ int x = 0, y = 0;
+ for (Vec v: vs) {
+ x += v.x;
+ y += v.y;
+ }
+ return new Vec(x/vs.size(), y/vs.size());
+ }
+
+
+
+
+ public static Vec stddev(List<Vec> vs) {
+ if (vs.isEmpty())
+ return new Vec(0,0);
+ Vec mean = mean(vs);
+ int x = 0, y = 0;
+ for (Vec v: vs) {
+ x += Math.pow(v.x - mean.x,2);
+ y += Math.pow(v.y - mean.y,2);
+ }
+ x = x / vs.size();
+ y = y / vs.size();
+
+ return new Vec( (int)Math.sqrt(x), (int)Math.sqrt(y));
+ }
+
+
+ @Override
+ public String toString() {
+ return x + "," + y;
+ }
+}
Modified: trunk/applications/jason-team/src/java/jia/direction.java
===================================================================
--- trunk/applications/jason-team/src/java/jia/direction.java 2008-04-07 13:27:34 UTC (rev 1205)
+++ trunk/applications/jason-team/src/java/jia/direction.java 2008-04-08 16:38:29 UTC (rev 1206)
@@ -11,9 +11,10 @@
import java.util.Random;
import java.util.logging.Level;
+import busca.Nodo;
+
import arch.CowboyArch;
import arch.LocalWorldModel;
-import busca.Nodo;
import env.WorldModel;
/**
@@ -24,9 +25,15 @@
*/
public class direction extends DefaultInternalAction {
- int[] actionsOrder = { 1, 2, 3, 4, 5, 6, 7, 8}; // initial order of actions
+ WorldModel.Move[] actionsOrder = new WorldModel.Move[WorldModel.nbActions];
Random random = new Random();
+ public direction() {
+ for (int i=0; i<WorldModel.nbActions; i++) {
+ actionsOrder[i] = Search.defaultActions[i];
+ }
+ }
+
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] terms) throws Exception {
try {
@@ -50,11 +57,11 @@
// randomly change the place of two actions in actionsOrder
int i1 = random.nextInt(WorldModel.nbActions);
int i2 = random.nextInt(WorldModel.nbActions);
- int temp = actionsOrder[i2];
+ WorldModel.Move temp = actionsOrder[i2];
actionsOrder[i2] = actionsOrder[i1];
actionsOrder[i1] = temp;
- Search astar = new Search(model, from, to, actionsOrder, true, ts.getUserAgArch());
+ Search astar = new Search(model, from, to, actionsOrder, true, true, true, ts.getUserAgArch());
Nodo solution = astar.search();
if (solution != null) {
WorldModel.Move m = astar.firstAction(solution);
Added: trunk/applications/jason-team/src/java/jia/herd_position.java
===================================================================
--- trunk/applications/jason-team/src/java/jia/herd_position.java (rev 0)
+++ trunk/applications/jason-team/src/java/jia/herd_position.java 2008-04-08 16:38:29 UTC (rev 1206)
@@ -0,0 +1,67 @@
+package jia;
+
+import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.TransitionSystem;
+import jason.asSemantics.Unifier;
+import jason.asSyntax.NumberTermImpl;
+import jason.asSyntax.Term;
+import jason.environment.grid.Location;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Level;
+
+import arch.CowboyArch;
+import arch.LocalWorldModel;
+import env.WorldModel;
+
+/**
+ * Gives a good location to herd cows
+ *
+ * @author jomi
+ */
+public class herd_position extends DefaultInternalAction {
+
+ public static final double maxStdDev = 3;
+
+ @Override
+ public Object execute(TransitionSystem ts, Unifier un, Term[] terms) throws Exception {
+ try {
+
+ LocalWorldModel model = ((CowboyArch)ts.getUserAgArch()).getModel();
+
+ Location agTarget = model.nearFree(getAgTarget(model));
+ return un.unifies(terms[0], new NumberTermImpl(agTarget.x)) &&
+ un.unifies(terms[1], new NumberTermImpl(agTarget.y));
+ } catch (Throwable e) {
+ ts.getLogger().log(Level.SEVERE, "herd_position error: "+e, e);
+ }
+ return false;
+ }
+
+ public Location getAgTarget(LocalWorldModel model) throws Exception {
+ List<Vec> cowsTarget = new ArrayList<Vec>();
+ for (Location c: model.getCows()) {
+ Search s = new Search(model, c, model.getCorralCenter(), null, false, false, false, null);
+ Location cowTarget = WorldModel.getNewLocationForAction(c, s.firstAction(s.search()));
+ cowsTarget.add(new Vec(model, cowTarget));
+ }
+
+ Vec stddev = Vec.stddev(cowsTarget);
+
+ // remove max if stddev is too big
+ while (stddev.magnitude() > maxStdDev) {
+ cowsTarget.remove(Vec.max(cowsTarget));
+ stddev = Vec.stddev(cowsTarget);
+ }
+
+ Vec mean = Vec.mean(cowsTarget);
+ if (mean.magnitude() > 0) {
+ double incvalue = (Vec.max(cowsTarget).sub(mean).magnitude()+2) / mean.magnitude();
+ return mean.product(incvalue+1).getLocation(model);
+ } else {
+ return null;
+ }
+ }
+}
+
Added: trunk/applications/jason-team/src/java/test/TestBasicHerding.java
===================================================================
--- trunk/applications/jason-team/src/java/test/TestBasicHerding.java (rev 0)
+++ trunk/applications/jason-team/src/java/test/TestBasicHerding.java 2008-04-08 16:38:29 UTC (rev 1206)
@@ -0,0 +1,124 @@
+package test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import jason.environment.grid.Location;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import jia.Search;
+import jia.Vec;
+import jia.herd_position;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import arch.LocalWorldModel;
+import busca.Nodo;
+import env.WorldModel;
+
+public class TestBasicHerding {
+
+ Vec cow;
+ Vec[] cows;
+ Vec cowboy;
+ LocalWorldModel model;
+
+ @Before
+ public void scenario() {
+ model = new LocalWorldModel(50,50);
+ model.setCorral(new Location(0,49), new Location(2,49));
+
+ cow = new Vec(6,7);
+ cowboy = new Vec(3,5);
+
+ cows = new Vec[4];
+ cows[0] = cow;
+ cows[1] = new Vec(5,30);
+ cows[2] = new Vec(4,8);
+ cows[3] = new Vec(5,10);
+
+ for (int i=0; i<cows.length; i++)
+ model.addCow(cows[i].getLocation(model));
+
+ }
+
+ @Test
+ public void testVect() {
+ //assertEquals(new Vec(6,7), cow.add(cowboy));
+ //assertEquals(new Location(6,42), cow.add(cowboy).getLocation(model));
+ assertEquals(new Location(3,44), cowboy.getLocation(model));
+ assertEquals(new Location(1,49), model.getCorralCenter());
+ assertEquals(new Vec(3,2), cow.sub(cowboy)); //new Vec(model, cowboy.getLocation(model), cow.add(cowboy).getLocation(model)));
+ }
+
+ /*
+ @Test
+ public void oneCow() throws Exception {
+ // get the location the cow should go
+ Location cowLocation = cow.getLocation(model);
+
+ // search cow desired location
+ Search s = new Search(model, cowLocation, model.getCorralCenter(), null, false, false, false, null);
+ Nodo path = s.search();
+ assertEquals(8, path.g()); //firstAction(path));
+
+ // cow target in direction to corral
+ Location cowTarget = WorldModel.getNewLocationForAction(cowLocation, s.firstAction(path));
+ //assertEquals(new Location(5,43), cowTarget);
+ Vec cowVecTarget = new Vec(model, cowTarget);
+ //assertEquals(new Vec(5,6), cowVecTarget);
+
+ // agent target to push cow into corral
+ Vec agVecTarget = cow.sub(cowVecTarget).product(2).add(cow);
+ Location agTarget = agVecTarget.getLocation(model);
+ //assertEquals(new Location(8,40), agTarget);
+
+ s = new Search(model, cowboy.getLocation(model), agTarget, null, true, true, true, null);
+ path = s.search();
+ System.out.println(path.g() + " " + path.montaCaminho());
+ assertEquals(12, path.g());
+ }
+ */
+
+
+ @Test
+ public void moreCows() throws Exception {
+ // get the location the cows should go
+ List<Vec> cowsTarget = new ArrayList<Vec>();
+ for (int i=0; i<cows.length; i++) {
+ Search s = new Search(model, cows[i].getLocation(model), model.getCorralCenter(), null, false, false, false, null);
+ Location cowTarget = WorldModel.getNewLocationForAction(cows[i].getLocation(model), s.firstAction(s.search()));
+ cowsTarget.add(new Vec(model, cowTarget));
+ }
+ //System.out.println(cowsTarget);
+
+ Vec stddev = Vec.stddev(cowsTarget);
+ assertEquals(new Vec(0,9), stddev);
+
+ // remove max if stddev is too big
+ while (stddev.magnitude() > 3) {
+ cowsTarget.remove(Vec.max(cowsTarget));
+ stddev = Vec.stddev(cowsTarget);
+ }
+ assertTrue(stddev.magnitude() < 3);
+
+ Vec mean = Vec.mean(cowsTarget);
+ assertEquals(new Vec(5,7), mean);
+ double incvalue = (Vec.max(cowsTarget).sub(mean).magnitude()+2) / mean.magnitude();
+ //System.out.println( incvalue);
+ Vec agTarget = mean.product(incvalue+1);
+ //System.out.println(agTarget);
+ assertEquals(new Vec(7,10), agTarget);
+
+ Location byIA = new herd_position().getAgTarget(model);
+ assertEquals(byIA, agTarget.getLocation(model));
+
+ Search s = new Search(model, cowboy.getLocation(model), agTarget.getLocation(model), null, true, true, true, null);
+ Nodo path = s.search();
+ //System.out.println(path.g() + " " + path.montaCaminho());
+ assertEquals(14, path.g());
+
+ }
+}
Modified: trunk/src/jason/environment/grid/Location.java
===================================================================
--- trunk/src/jason/environment/grid/Location.java 2008-04-07 13:27:34 UTC (rev 1205)
+++ trunk/src/jason/environment/grid/Location.java 2008-04-08 16:38:29 UTC (rev 1206)
@@ -1,7 +1,7 @@
package jason.environment.grid;
public final class Location {
- public int x, y;
+ public final int x, y;
public Location(int x, int y) {
this.x = x;
@@ -13,6 +13,16 @@
return Math.abs(x - l.x) + Math.abs(y - l.y);
}
+ /** calculates the Euclidean distance between two points */
+ public double distanceEuclidean(Location l) {
+ return Math.sqrt(Math.pow(x - l.x, 2) + Math.pow(y - l.y, 2));
+ }
+
+ /** returns Math.max( Math.abs(this.x - l.x) , Math.abs(this.y - l.y)) */
+ public int maxBorder(Location l) {
+ return Math.max( Math.abs(this.x - l.x) , Math.abs(this.y - l.y));
+ }
+
public boolean isNeigbour(Location l) {
return
distance(l) == 1 ||
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-04-09 19:05:14
|
Revision: 1210
http://jason.svn.sourceforge.net/jason/?rev=1210&view=rev
Author: jomifred
Date: 2008-04-09 12:05:06 -0700 (Wed, 09 Apr 2008)
Log Message:
-----------
fix bug in jar generation (windows)
Modified Paths:
--------------
trunk/build.xml
trunk/src/jason/asSemantics/Agent.java
trunk/src/jason/environment/grid/Location.java
Modified: trunk/build.xml
===================================================================
--- trunk/build.xml 2008-04-09 17:07:30 UTC (rev 1209)
+++ trunk/build.xml 2008-04-09 19:05:06 UTC (rev 1210)
@@ -15,7 +15,7 @@
<property name="dist.properties" value="${basedir}/bin/dist.properties" />
<property name="version" value="1" />
- <property name="release" value="1" />
+ <property name="release" value="1.1" />
<property name="distDir" value="${env.HOME}/tmp/x/Jason-${version}.${release}" />
<property name="distFile" value="${env.HOME}/Jason-${version}.${release}" />
Modified: trunk/src/jason/asSemantics/Agent.java
===================================================================
--- trunk/src/jason/asSemantics/Agent.java 2008-04-09 17:07:30 UTC (rev 1209)
+++ trunk/src/jason/asSemantics/Agent.java 2008-04-09 19:05:06 UTC (rev 1210)
@@ -131,6 +131,7 @@
if (asSrc.startsWith(Include.CRPrefix)) {
// loads the class from a jar file (for example)
+ asSrc = asSrc.replaceAll("\\\\", "/");
parseAS(Agent.class.getResource(asSrc.substring(Include.CRPrefix.length())).openStream());
} else {
// check whether source is an URL string
Modified: trunk/src/jason/environment/grid/Location.java
===================================================================
--- trunk/src/jason/environment/grid/Location.java 2008-04-09 17:07:30 UTC (rev 1209)
+++ trunk/src/jason/environment/grid/Location.java 2008-04-09 19:05:06 UTC (rev 1210)
@@ -1,7 +1,7 @@
package jason.environment.grid;
public final class Location {
- public final int x, y;
+ public int x, y;
public Location(int x, int y) {
this.x = x;
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-04-10 07:17:12
|
Revision: 1211
http://jason.svn.sourceforge.net/jason/?rev=1211&view=rev
Author: jomifred
Date: 2008-04-10 00:17:08 -0700 (Thu, 10 Apr 2008)
Log Message:
-----------
use / instead of File.separator in Include class.
Modified Paths:
--------------
trunk/applications/as-unit-test/src/example/TestExample.java
trunk/applications/jason-moise/build.xml
trunk/applications/jason-moise/readme.txt
trunk/src/jason/asSemantics/Agent.java
trunk/src/jason/asSyntax/directives/Include.java
trunk/src/jason/bb/TextPersistentBB.java
trunk/src/jason/util/asl2xml.java
trunk/src/test/ASParserTest.java
Modified: trunk/applications/as-unit-test/src/example/TestExample.java
===================================================================
--- trunk/applications/as-unit-test/src/example/TestExample.java 2008-04-09 19:05:06 UTC (rev 1210)
+++ trunk/applications/as-unit-test/src/example/TestExample.java 2008-04-10 07:17:08 UTC (rev 1211)
@@ -23,9 +23,9 @@
}
@Test
- public void testBels() {
- ag.assertBel("b(20)",0);
- ag.assertBel("not b",0);
+ public void testInitialBels() {
+ ag.assertBel("b(20)",0); // agent must believe "b(20)" without any reasoning
+ ag.assertBel("not b",0);
ag.assertBel("not b(5)",0);
ag.assertBel("b(10) & b(20) & not b(60)",0);
}
Modified: trunk/applications/jason-moise/build.xml
===================================================================
--- trunk/applications/jason-moise/build.xml 2008-04-09 19:05:06 UTC (rev 1210)
+++ trunk/applications/jason-moise/build.xml 2008-04-10 07:17:08 UTC (rev 1211)
@@ -8,7 +8,7 @@
<property environment="env"/>
<property name="version" value="1"/>
- <property name="release" value="0.1"/>
+ <property name="release" value="1"/>
<property name="moiseDir" value="${env.HOME}/Moise/Moise-svn" />
<property name="distDir" value="${env.HOME}/tmp/jmoise-${version}.${release}" />
<property name="distFile" value="${env.HOME}/jason-moise-${version}.${release}" />
Modified: trunk/applications/jason-moise/readme.txt
===================================================================
--- trunk/applications/jason-moise/readme.txt 2008-04-09 19:05:06 UTC (rev 1210)
+++ trunk/applications/jason-moise/readme.txt 2008-04-10 07:17:08 UTC (rev 1211)
@@ -9,4 +9,4 @@
and start it. The chapter 4 of doc/tutorial.pdf explains in details
the examples.
-Note: Jason 1.0.1 is required.
+Note: Jason 1.1 is required.
Modified: trunk/src/jason/asSemantics/Agent.java
===================================================================
--- trunk/src/jason/asSemantics/Agent.java 2008-04-09 19:05:06 UTC (rev 1210)
+++ trunk/src/jason/asSemantics/Agent.java 2008-04-10 07:17:08 UTC (rev 1211)
@@ -127,18 +127,18 @@
boolean parsingOk = true;
if (asSrc != null) {
+ asSrc = asSrc.replaceAll("\\\\", "/");
setASLSrc(asSrc);
if (asSrc.startsWith(Include.CRPrefix)) {
// loads the class from a jar file (for example)
- asSrc = asSrc.replaceAll("\\\\", "/");
parseAS(Agent.class.getResource(asSrc.substring(Include.CRPrefix.length())).openStream());
} else {
// check whether source is an URL string
try {
parsingOk = parseAS(new URL(asSrc));
} catch (MalformedURLException e) {
- parsingOk = parseAS(asSrc);
+ parsingOk = parseAS(new File(asSrc));
}
}
}
@@ -192,7 +192,7 @@
}
public void setASLSrc(String file) {
- if (file != null && file.startsWith("."+File.separator))
+ if (file != null && file.startsWith("./"))
file = file.substring(2);
aslSource = file;
}
@@ -214,17 +214,17 @@
}
/** Adds beliefs and plans form a file */
- public boolean parseAS(String asFileName) {
+ public boolean parseAS(File asFile) {
try {
- parseAS(new FileInputStream(asFileName));
- logger.fine("as2j: AgentSpeak program '" + asFileName + "' parsed successfully!");
+ parseAS(new FileInputStream(asFile));
+ logger.fine("as2j: AgentSpeak program '" + asFile + "' parsed successfully!");
return true;
} catch (FileNotFoundException e) {
- logger.log(Level.SEVERE, "as2j: the AgentSpeak source file '"+asFileName+"' was not found!");
+ logger.log(Level.SEVERE, "as2j: the AgentSpeak source file '"+asFile+"' was not found!");
} catch (ParseException e) {
logger.log(Level.SEVERE, "as2j: parsing error:" + e.getMessage());
} catch (Exception e) {
- logger.log(Level.SEVERE, "as2j: error parsing \"" + asFileName + "\"", e);
+ logger.log(Level.SEVERE, "as2j: error parsing \"" + asFile + "\"", e);
}
return false;
}
Modified: trunk/src/jason/asSyntax/directives/Include.java
===================================================================
--- trunk/src/jason/asSyntax/directives/Include.java 2008-04-09 19:05:06 UTC (rev 1210)
+++ trunk/src/jason/asSyntax/directives/Include.java 2008-04-10 07:17:08 UTC (rev 1211)
@@ -27,7 +27,7 @@
public Agent process(Pred directive, Agent outerContent, Agent innerContent) {
if (outerContent == null)
return null;
- String file = ((StringTerm)directive.getTerm(0)).getString();
+ String file = ((StringTerm)directive.getTerm(0)).getString().replaceAll("\\\\", "/");
try {
String outerPrefix = outerContent.getASLSrc(); // the source file that has the include directive
InputStream in;
@@ -38,7 +38,7 @@
file = checkPathAndFixWithSourcePath(file, aslSourcePath, outerPrefix);
in = new URL(file).openStream();
- } if (outerPrefix.startsWith(CRPrefix)) {
+ } if (outerPrefix.startsWith(CRPrefix)) {
// outer is loaded from a resource ("application".jar) file, used for java web start
int posSlash = outerPrefix.lastIndexOf("/");
@@ -89,7 +89,7 @@
return f;
} else if (srcpath != null) {
for (String path: srcpath) {
- File newname = new File(path + File.separator + f.toString());
+ File newname = new File(path + "/" + f.toString());
if (newname.exists()) {
try {
return newname.getCanonicalFile().toString();
@@ -104,7 +104,7 @@
return urlPrefix + f;
} else if (srcpath != null) {
for (String path: srcpath) {
- String newname = urlPrefix + path + File.separator + f;
+ String newname = urlPrefix + path + "/" + f;
if (testURLSrc(newname)) {
return newname;
}
Modified: trunk/src/jason/bb/TextPersistentBB.java
===================================================================
--- trunk/src/jason/bb/TextPersistentBB.java 2008-04-09 19:05:06 UTC (rev 1210)
+++ trunk/src/jason/bb/TextPersistentBB.java 2008-04-10 07:17:08 UTC (rev 1211)
@@ -26,7 +26,7 @@
file = new File(ag.getTS().getUserAgArch().getAgName() + ".bb");
logger.fine("reading from file " + file);
if (file.exists()) {
- ag.parseAS(file.getAbsolutePath());
+ ag.parseAS(file.getAbsoluteFile());
ag.addInitialBelsInBB();
}
} catch (RevisionFailedException e) {
Modified: trunk/src/jason/util/asl2xml.java
===================================================================
--- trunk/src/jason/util/asl2xml.java 2008-04-09 19:05:06 UTC (rev 1210)
+++ trunk/src/jason/util/asl2xml.java 2008-04-10 07:17:08 UTC (rev 1211)
@@ -2,6 +2,7 @@
import jason.asSemantics.Agent;
+import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
@@ -43,7 +44,7 @@
Agent loadAg(String file) throws Exception {
Agent ag = new Agent();
- if (ag.parseAS(file)) {
+ if (ag.parseAS(new File(file))) {
ag.setASLSrc(file);
ag.addInitialBelsInBB();
return ag;
Modified: trunk/src/test/ASParserTest.java
===================================================================
--- trunk/src/test/ASParserTest.java 2008-04-09 19:05:06 UTC (rev 1210)
+++ trunk/src/test/ASParserTest.java 2008-04-10 07:17:08 UTC (rev 1211)
@@ -36,13 +36,13 @@
arch.setArchInfraTier(new CentralisedAgArch());
ag.setTS(new TransitionSystem(ag, null, null, arch));
- assertTrue(ag.parseAS("src/asl/kqmlPlans.asl"));
- assertTrue(ag.parseAS("examples/auction/ag1.asl"));
+ assertTrue(ag.parseAS(new File("src/asl/kqmlPlans.asl")));
+ assertTrue(ag.parseAS(new File("examples/auction/ag1.asl")));
Plan p = ag.getPL().get("l__0");
assertEquals(p.getBody().getPlanSize(), 1);
assertEquals(((PlanBody)p.getBody()).getBodyType(), PlanBody.BodyType.internalAction);
- assertTrue(ag.parseAS("examples/auction/ag2.asl"));
- assertTrue(ag.parseAS("examples/auction/ag3.asl"));
+ assertTrue(ag.parseAS(new File("examples/auction/ag2.asl")));
+ assertTrue(ag.parseAS(new File("examples/auction/ag3.asl")));
}
public void testLogicalExpr() throws Exception {
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-04-10 15:27:07
|
Revision: 1212
http://jason.svn.sourceforge.net/jason/?rev=1212&view=rev
Author: jomifred
Date: 2008-04-10 08:26:59 -0700 (Thu, 10 Apr 2008)
Log Message:
-----------
improvement in jason team (32 cows)
Modified Paths:
--------------
trunk/applications/jason-team/massim-server/conf/serverconfig.xml
trunk/applications/jason-team/src/java/arch/LocalWorldModel.java
trunk/applications/jason-team/src/java/jia/Search.java
trunk/applications/jason-team/src/java/jia/Vec.java
trunk/applications/jason-team/src/java/jia/herd_position.java
trunk/applications/jason-team/src/java/test/TestBasicHerding.java
trunk/src/templates/build-template.xml
Modified: trunk/applications/jason-team/massim-server/conf/serverconfig.xml
===================================================================
--- trunk/applications/jason-team/massim-server/conf/serverconfig.xml 2008-04-10 07:17:08 UTC (rev 1211)
+++ trunk/applications/jason-team/massim-server/conf/serverconfig.xml 2008-04-10 15:26:59 UTC (rev 1212)
@@ -12,14 +12,17 @@
xmlobserverpath="."
xmlstatisticsobserver="massim.simulation.GridSimulationXMLStatisticsObserver"
file-simulationlog="./log"
- visualisationobserver="massim.simulation.GridSimulationVisualizationObserver"
+ visualisationobserver=""
>
+
+<!-- visualisationobserver="massim.simulation.GridSimulationVisualizationObserver" -->
+
<configuration
xmlns:meta="http://www.tu-clausthal.de/"
sizex="70"
sizey="70"
- maxNumberOfSteps="500"
+ maxNumberOfSteps="700"
numberOfAgents="12"
numberOfObstacles="200"
Modified: trunk/applications/jason-team/src/java/arch/LocalWorldModel.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/LocalWorldModel.java 2008-04-10 07:17:08 UTC (rev 1211)
+++ trunk/applications/jason-team/src/java/arch/LocalWorldModel.java 2008-04-10 15:26:59 UTC (rev 1212)
@@ -62,11 +62,9 @@
int w = 0;
while (true) {
for (int x=l.x-w; x<=l.x+w;x++)
- if (isFree(x,l.y))
- return new Location(x,l.y);
- for (int y=l.y-w; y<=l.y+w;y++)
- if (isFree(l.x,y))
- return new Location(l.x,y);
+ for (int y=l.y-w; y<=l.y+w;y++)
+ if (isFree(x,y))
+ return new Location(x,y);
w++;
}
}
Modified: trunk/applications/jason-team/src/java/jia/Search.java
===================================================================
--- trunk/applications/jason-team/src/java/jia/Search.java 2008-04-10 07:17:08 UTC (rev 1211)
+++ trunk/applications/jason-team/src/java/jia/Search.java 2008-04-10 15:26:59 UTC (rev 1212)
@@ -6,6 +6,7 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
+import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
@@ -71,6 +72,19 @@
return searchAlg.busca(root);
}
+ public List<Nodo> normalPath(Nodo n) {
+ List<Nodo> r = new LinkedList<Nodo>();
+ while (n != null) {
+ r.add(0,n);
+ n = n.getPai();
+ }
+ return r;
+ }
+
+ public Location getNodeLocation(Nodo n) {
+ return ((GridState)n.getEstado()).pos;
+ }
+
public WorldModel.Move firstAction(Nodo solution) {
Nodo root = solution;
Estado prev1 = null;
Modified: trunk/applications/jason-team/src/java/jia/Vec.java
===================================================================
--- trunk/applications/jason-team/src/java/jia/Vec.java 2008-04-10 07:17:08 UTC (rev 1211)
+++ trunk/applications/jason-team/src/java/jia/Vec.java 2008-04-10 15:26:59 UTC (rev 1212)
@@ -64,6 +64,15 @@
return max;
}
+ public static void cluster(List<Vec> vs, int maxstddev) {
+ Vec stddev = Vec.stddev(vs);
+ // remove max if stddev is too big
+ while (stddev.magnitude() > maxstddev) {
+ vs.remove(Vec.max(vs));
+ stddev = Vec.stddev(vs);
+ }
+ }
+
public static Vec mean(List<Vec> vs) {
if (vs.isEmpty())
return new Vec(0,0);
@@ -75,9 +84,6 @@
return new Vec(x/vs.size(), y/vs.size());
}
-
-
-
public static Vec stddev(List<Vec> vs) {
if (vs.isEmpty())
return new Vec(0,0);
Modified: trunk/applications/jason-team/src/java/jia/herd_position.java
===================================================================
--- trunk/applications/jason-team/src/java/jia/herd_position.java 2008-04-10 07:17:08 UTC (rev 1211)
+++ trunk/applications/jason-team/src/java/jia/herd_position.java 2008-04-10 15:26:59 UTC (rev 1212)
@@ -13,7 +13,7 @@
import arch.CowboyArch;
import arch.LocalWorldModel;
-import env.WorldModel;
+import busca.Nodo;
/**
* Gives a good location to herd cows
@@ -30,7 +30,6 @@
LocalWorldModel model = ((CowboyArch)ts.getUserAgArch()).getModel();
-
Location agTarget = getAgTarget(model);
if (agTarget != null) {
agTarget = model.nearFree(agTarget);
@@ -44,6 +43,29 @@
}
public Location getAgTarget(LocalWorldModel model) throws Exception {
+ List<Vec> cows = new ArrayList<Vec>();
+ for (Location c: model.getCows()) {
+ cows.add(new Vec(model, c));
+ }
+ if (cows.isEmpty())
+ return null;
+
+ Vec.cluster(cows, 3); // find center/clusterise
+
+ Vec mean = Vec.mean(cows);
+
+ // run A* to see the cluster target in n steps
+ Search s = new Search(model, mean.getLocation(model), model.getCorralCenter(), null, false, false, false, null);
+ List<Nodo> np = s.normalPath(s.search());
+
+ int stepsFromCenter = (int)Vec.max(cows).sub(mean).magnitude()+1;
+ int n = Math.min(stepsFromCenter, np.size());
+
+ Vec ctarget = new Vec(model, s.getNodeLocation(np.get(n)));
+ Vec agTarget = mean.sub(ctarget).add(mean); // .product(1.5)
+ return agTarget.getLocation(model);
+
+ /*
List<Vec> cowsTarget = new ArrayList<Vec>();
for (Location c: model.getCows()) {
Search s = new Search(model, c, model.getCorralCenter(), null, false, false, false, null);
@@ -66,6 +88,7 @@
} else {
return null;
}
+ */
}
}
Modified: trunk/applications/jason-team/src/java/test/TestBasicHerding.java
===================================================================
--- trunk/applications/jason-team/src/java/test/TestBasicHerding.java 2008-04-10 07:17:08 UTC (rev 1211)
+++ trunk/applications/jason-team/src/java/test/TestBasicHerding.java 2008-04-10 15:26:59 UTC (rev 1212)
@@ -16,11 +16,9 @@
import arch.LocalWorldModel;
import busca.Nodo;
-import env.WorldModel;
public class TestBasicHerding {
- Vec cow;
Vec[] cows;
Vec cowboy;
LocalWorldModel model;
@@ -29,12 +27,14 @@
public void scenario() {
model = new LocalWorldModel(50,50);
model.setCorral(new Location(0,49), new Location(2,49));
-
- cow = new Vec(6,7);
+ model.wall(7, 44, 7, 49);
+ }
+
+ public void scenario1() {
cowboy = new Vec(3,5);
cows = new Vec[4];
- cows[0] = cow;
+ cows[0] = new Vec(6,7);
cows[1] = new Vec(5,30);
cows[2] = new Vec(4,8);
cows[3] = new Vec(5,10);
@@ -44,13 +44,33 @@
}
+ public void scenario2() {
+ cowboy = new Vec(11,3);
+
+ cows = new Vec[9];
+ cows[0] = new Vec(8,0);
+ cows[1] = new Vec(9,0);
+ cows[2] = new Vec(10,0);
+ cows[3] = new Vec(8,1);
+ cows[4] = new Vec(9,1);
+ cows[5] = new Vec(10,1);
+ cows[6] = new Vec(8,2);
+ cows[7] = new Vec(9,2);
+ cows[8] = new Vec(10,2);
+
+ for (int i=0; i<cows.length; i++)
+ model.addCow(cows[i].getLocation(model));
+
+ }
+
@Test
public void testVect() {
+ scenario1();
//assertEquals(new Vec(6,7), cow.add(cowboy));
//assertEquals(new Location(6,42), cow.add(cowboy).getLocation(model));
assertEquals(new Location(3,44), cowboy.getLocation(model));
assertEquals(new Location(1,49), model.getCorralCenter());
- assertEquals(new Vec(3,2), cow.sub(cowboy)); //new Vec(model, cowboy.getLocation(model), cow.add(cowboy).getLocation(model)));
+ assertEquals(new Vec(3,2), new Vec(6,7).sub(cowboy)); //new Vec(model, cowboy.getLocation(model), cow.add(cowboy).getLocation(model)));
}
/*
@@ -83,8 +103,9 @@
*/
+ /*
@Test
- public void moreCows() throws Exception {
+ public void moveCows1() throws Exception {
// get the location the cows should go
List<Vec> cowsTarget = new ArrayList<Vec>();
for (int i=0; i<cows.length; i++) {
@@ -119,6 +140,86 @@
Nodo path = s.search();
//System.out.println(path.g() + " " + path.montaCaminho());
assertEquals(14, path.g());
+ }
+ */
+
+ @Test
+ public void moveCows2() throws Exception {
+ scenario1();
+ List<Vec> cowsTarget = new ArrayList<Vec>();
+ for (int i=0; i<cows.length; i++) {
+ cowsTarget.add(cows[i]);
+ }
+
+ // find center/clusterise
+ Vec stddev = Vec.stddev(cowsTarget);
+ assertEquals(new Vec(0,9), stddev);
+
+ // remove max if stddev is too big
+ while (stddev.magnitude() > 3) {
+ cowsTarget.remove(Vec.max(cowsTarget));
+ stddev = Vec.stddev(cowsTarget);
+ }
+ assertTrue(stddev.magnitude() < 3);
+
+ Vec mean = Vec.mean(cowsTarget);
+ assertEquals(new Vec(5,8), mean);
+
+ int stepsFromCenter = (int)Vec.max(cowsTarget).sub(mean).magnitude()+1;
+ assertEquals(3, stepsFromCenter);
+
+ // run A* to see the cluster target in n steps
+ Search s = new Search(model, mean.getLocation(model), model.getCorralCenter(), null, false, false, false, null);
+ List<Nodo> np = s.normalPath(s.search());
+ int n = Math.min(stepsFromCenter, np.size());
+ assertEquals(3, n);
+
+ Vec ctarget = new Vec(model, s.getNodeLocation(np.get(n)));
+ assertEquals(new Vec(3,5), ctarget);
+
+ Vec agTarget = mean.sub(ctarget).product(1.0).add(mean);
+ assertEquals(new Vec(7,11), agTarget);
+
+ Location byIA = new herd_position().getAgTarget(model);
+ assertEquals(byIA, agTarget.getLocation(model));
}
+
+ @Test
+ public void moveCows3() throws Exception {
+ scenario2();
+ List<Vec> cowsTarget = new ArrayList<Vec>();
+ for (int i=0; i<cows.length; i++) {
+ cowsTarget.add(cows[i]);
+ }
+
+ // find center/clusterise
+ Vec.cluster(cowsTarget, 3);
+ Vec stddev = Vec.stddev(cowsTarget);
+ assertTrue(stddev.magnitude() < 3);
+
+ Vec mean = Vec.mean(cowsTarget);
+ assertEquals(new Vec(9,1), mean);
+
+ // run A* to see the cluster target in n steps
+ Search s = new Search(model, mean.getLocation(model), model.getCorralCenter(), null, false, false, false, null);
+ List<Nodo> np = s.normalPath(s.search());
+ //System.out.println(np);
+
+ int stepsFromCenter = (int)Vec.max(cowsTarget).sub(mean).magnitude()+1;
+ assertEquals(2, stepsFromCenter);
+ int n = Math.min(stepsFromCenter, np.size());
+ assertEquals(2, n);
+
+ Vec ctarget = new Vec(model, s.getNodeLocation(np.get(n)));
+ assertEquals(new Vec(8,3), ctarget);
+
+ Vec agTarget = mean.sub(ctarget).add(mean);
+ Location agLoc = model.nearFree(agTarget.getLocation(model));
+ assertEquals(new Location(11,49), agLoc);
+
+ Location byIA = new herd_position().getAgTarget(model);
+ assertEquals(byIA, agTarget.getLocation(model));
+ }
+
}
Modified: trunk/src/templates/build-template.xml
===================================================================
--- trunk/src/templates/build-template.xml 2008-04-10 07:17:08 UTC (rev 1211)
+++ trunk/src/templates/build-template.xml 2008-04-10 15:26:59 UTC (rev 1212)
@@ -37,7 +37,10 @@
</target>
<target name="compile" depends="init">
- <javac srcdir="${basedir}" destdir="${build.dir}" debug="true" optimize="true" >
+ <condition property="srcdir" value="${basedir}/src/java" else="${basedir}" >
+ <available file="${basedir}/src/java" />
+ </condition>
+ <javac srcdir="${srcdir}" destdir="${build.dir}" debug="true" optimize="true" >
<classpath refid="project.classpath"/>
</javac>
</target>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-04-13 10:45:13
|
Revision: 1214
http://jason.svn.sourceforge.net/jason/?rev=1214&view=rev
Author: jomifred
Date: 2008-04-13 03:45:08 -0700 (Sun, 13 Apr 2008)
Log Message:
-----------
fix bug in communication: use nested source annotation
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/asunit/TestArch.java
trunk/applications/as-unit-test/src/jason/tests/TestKQML.java
trunk/release-notes.txt
trunk/src/asl/kqmlPlans.asl
trunk/src/jason/asSyntax/Pred.java
trunk/src/jason/asSyntax/VarTerm.java
trunk/src/jason/stdlib/add_annot.java
trunk/src/jason/stdlib/package.html
trunk/src/jason/stdlib/send.java
trunk/src/test/ListTermTest.java
trunk/src/test/VarTermTest.java
Added Paths:
-----------
trunk/src/jason/stdlib/add_nested_source.java
Modified: trunk/applications/as-unit-test/src/jason/asunit/TestArch.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/asunit/TestArch.java 2008-04-10 21:40:07 UTC (rev 1213)
+++ trunk/applications/as-unit-test/src/jason/asunit/TestArch.java 2008-04-13 10:45:08 UTC (rev 1214)
@@ -93,7 +93,7 @@
}
public void print(String s) {
- System.out.println(s);
+ //System.out.println(s);
output.append(s+"\n");
}
Modified: trunk/applications/as-unit-test/src/jason/tests/TestKQML.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestKQML.java 2008-04-10 21:40:07 UTC (rev 1213)
+++ trunk/applications/as-unit-test/src/jason/tests/TestKQML.java 2008-04-13 10:45:08 UTC (rev 1214)
@@ -19,7 +19,8 @@
// defines the agent's AgentSpeak code
bob.parseAScode(
"+!simple_send <- .send(maria, tell, vl(10)); "+
- " .send(maria, achieve, goto(10,2)). " +
+ " .send(maria, achieve, goto(10,2)); " +
+ " .send(maria, tell, loves(maria,bob)[source(maria), source(mog)]). " +
"+!send_ask1 <- .send(maria, askOne, vl(_), vl(X)); " +
" .send(maria, askOne, vl(_)); " +
@@ -56,9 +57,10 @@
@Test
public void testSend() {
bob.addGoal("simple_send");
- bob.assertIdle(5); // bob sent the messages
- maria.assertBel("vl(10)", 5); // maria received tell
- maria.assertAct("act(10,2,bob)", 5); // maria received achieved
+ bob.assertIdle(5); // bob sent the messages
+ maria.assertBel("vl(10)[source(bob)]", 5); // maria received tell
+ maria.assertAct("act(10,2,bob)", 5); // maria received achieved
+ maria.assertBel("loves(maria,bob)[source(bob)[source(maria),source(mog)]]", 5);
}
@Test
@@ -92,7 +94,7 @@
bob.addGoal("simple_send");
bob.addGoal("send_askAll1");
bob.assertIdle(10);
- maria.assertIdle(10);
+ maria.assertIdle(15);
bob.assertPrint("[vl(10),vl(1),vl(2)]", 5);
bob.addGoal("send_askAll2");
Modified: trunk/release-notes.txt
===================================================================
--- trunk/release-notes.txt 2008-04-10 21:40:07 UTC (rev 1213)
+++ trunk/release-notes.txt 2008-04-13 10:45:08 UTC (rev 1214)
@@ -1,7 +1,14 @@
------------
-version 1.1
------------
+-------------
+version 1.1.1
+-------------
+Bugs fixed:
+. use nested source annotations in communication
+
+-------------
+version 1.1.0
+-------------
+
New features
. Performance improvements: in general, applications run 30%
faster.
Modified: trunk/src/asl/kqmlPlans.asl
===================================================================
--- trunk/src/asl/kqmlPlans.asl 2008-04-10 21:40:07 UTC (rev 1213)
+++ trunk/src/asl/kqmlPlans.asl 2008-04-13 10:45:08 UTC (rev 1214)
@@ -15,7 +15,7 @@
: .structure(Content) &
.ground(Content) &
not .list(Content)
- <- .add_annot(Content, source(Sender), CA);
+ <- .add_nested_source(Content, Sender, CA);
+CA.
@kqmlReceivedTellList
+!kqml_received(Sender, tell, Content, _)
@@ -29,7 +29,7 @@
+!add_all_kqml_received(S,[H|T])
: .structure(H) &
.ground(H)
- <- .add_annot(H, source(S), CA);
+ <- .add_nested_source(H, Sender, CA);
+CA;
!add_all_kqml_received(S,T).
@@ -39,7 +39,7 @@
@kqmlReceivedUnTell
+!kqml_received(Sender, untell, Content, _)
- <- .add_annot(Content, source(Sender), CA);
+ <- .add_nested_source(Content, Sender, CA);
-CA.
@@ -48,7 +48,7 @@
@kqmlReceivedAchieve
+!kqml_received(Sender, achieve, Content, _)
: not .list(Content)
- <- .add_annot(Content, source(Sender), CA);
+ <- .add_nested_source(Content, Sender, CA);
!!CA.
@kqmlReceivedAchieveList
+!kqml_received(Sender, achieve, Content, _)
@@ -61,7 +61,7 @@
@kqmlReceivedAchieveList2
+!add_all_kqml_achieve(Sender,[H|T])
- <- .add_annot(H, source(Sender), CA);
+ <- .add_nested_source(H, Sender, CA);
!!CA;
!add_all_kqml_achieve(Sender,T).
Modified: trunk/src/jason/asSyntax/Pred.java
===================================================================
--- trunk/src/jason/asSyntax/Pred.java 2008-04-10 21:40:07 UTC (rev 1213)
+++ trunk/src/jason/asSyntax/Pred.java 2008-04-13 10:45:08 UTC (rev 1214)
@@ -65,7 +65,7 @@
}
/** to be used by atom */
- protected Pred(String functor, int termsSize) {
+ public Pred(String functor, int termsSize) {
super(functor, termsSize);
}
@@ -123,7 +123,7 @@
}
public void addAnnots(List<Term> l) {
- if (l == null) return;
+ if (l == null || l.isEmpty()) return;
ListTerm tail;
if (annots == null) {
annots = new ListTermImpl();
@@ -309,7 +309,7 @@
*/
public void addSource(Structure agName) {
if (agName != null) {
- Structure ts = new Structure("source");
+ Structure ts = new Structure("source", 1);
ts.addTerm(agName);
addAnnot(ts);
}
Modified: trunk/src/jason/asSyntax/VarTerm.java
===================================================================
--- trunk/src/jason/asSyntax/VarTerm.java 2008-04-10 21:40:07 UTC (rev 1213)
+++ trunk/src/jason/asSyntax/VarTerm.java 2008-04-13 10:45:08 UTC (rev 1214)
@@ -111,9 +111,8 @@
vl = (Term)vl.clone(); // should clone here, since there is no cloning in unify
// The below does not conform the rules in manual
- //if (vl.isPred() && this.hasAnnot()) { // if this var has annots, add them in the value's annots (Experimental)
- // ((Pred)vl).addAnnots(this.getAnnots());
- //}
+ //if (vl.isPred() && this.hasAnnot()) // if this var has annots, add them in the value's annots (Experimental)
+ // ((Pred)vl).addAnnots(this.getAnnots());
value = vl;
resetHashCodeCache();
@@ -128,7 +127,7 @@
public boolean apply(Unifier u) {
if (value == null) {
Term vl = u.get(this);
- // System.out.println("applying="+t+"="+vl+" un="+this);
+ //System.out.println("applying "+this+"="+vl+" un="+u);
if (vl != null && !(vl instanceof VarsCluster)) {
setValue(vl);
value.apply(u); // in case t has var args
@@ -153,7 +152,7 @@
if (t == this) return true;
if (t instanceof Term) {
Term vl = getValue();
- // System.out.println("cheking equals form "+tAsTerm.getFunctor()+"
+ // System.out.println("checking equals form "+tAsTerm.getFunctor()+"
// and this "+this.getFunctor()+" my value "+vl);
if (vl != null) {
// compare the values
Modified: trunk/src/jason/stdlib/add_annot.java
===================================================================
--- trunk/src/jason/stdlib/add_annot.java 2008-04-10 21:40:07 UTC (rev 1213)
+++ trunk/src/jason/stdlib/add_annot.java 2008-04-13 10:45:08 UTC (rev 1214)
@@ -64,6 +64,8 @@
unifies with <code>[a1[source(jomi)], a2[source(jomi)]]</code>.</li>
</ul>
+
+ @see jason.stdlib.add_nested_source
*/
public class add_annot extends DefaultInternalAction {
Added: trunk/src/jason/stdlib/add_nested_source.java
===================================================================
--- trunk/src/jason/stdlib/add_nested_source.java (rev 0)
+++ trunk/src/jason/stdlib/add_nested_source.java 2008-04-13 10:45:08 UTC (rev 1214)
@@ -0,0 +1,118 @@
+//----------------------------------------------------------------------------
+// Copyright (C) 2003 Rafael H. Bordini, Jomi F. Hubner, et al.
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// To contact the authors:
+// http://www.dur.ac.uk/r.bordini
+// http://www.inf.furb.br/~jomi
+//
+//----------------------------------------------------------------------------
+
+
+package jason.stdlib;
+
+import jason.JasonException;
+import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.TransitionSystem;
+import jason.asSemantics.Unifier;
+import jason.asSyntax.ListTerm;
+import jason.asSyntax.ListTermImpl;
+import jason.asSyntax.Literal;
+import jason.asSyntax.Pred;
+import jason.asSyntax.Structure;
+import jason.asSyntax.Term;
+
+/**
+ <p>Internal action: <b><code>.add_nested_source</code></b>.
+
+ <p>Description: adds a source annotation to a literal (used in communication).
+
+ <p>Parameters:<ul>
+
+ <li>+ belief(s) (literal or list): the literal where the source annotation
+ is to be added. If this parameter is a list, all literals in the list
+ will have the source added.<br/>
+
+ <li>+ source (atom): the source.<br/>
+
+ <li>+/- annotated beliefs(s) (literal or list): this argument
+ unifies with the result of the source addition.<br/>
+
+ </ul>
+
+ <p>Examples:<ul>
+
+ <li> <code>.add_nested_source(a,jomi,B)</code>: <code>B</code>
+ unifies with <code>a[source(jomi)]</code>.</li>
+
+ <li> <code>.add_nested_source(a[source(bob)],jomi,B)</code>: <code>B</code>
+ unifies with <code>a[source(jomi)[source(bob)]]</code>.</li>
+
+ <li> <code>.add_annot([a1,a2], jomi, B)</code>: <code>B</code>
+ unifies with <code>[a1[source(jomi)], a2[source(jomi)]]</code>.</li>
+
+ </ul>
+
+ @see jason.stdlib.add_annot
+
+ */
+public class add_nested_source extends DefaultInternalAction {
+
+ @Override
+ public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
+ try {
+ Term result = addAnnotToList(un, args[0], (Structure)args[1].clone());
+ return un.unifies(result,args[2]);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ throw new JasonException("The internal action 'add_nested_source' requires three arguments.");
+ }
+ }
+
+ public Term addAnnotToList(Unifier unif, Term l, Structure source) {
+ if (l.isList()) {
+ ListTerm result = new ListTermImpl();
+ for (Term lTerm: (ListTerm)l) {
+ Term t = addAnnotToList( unif, lTerm, source);
+ if (t != null) {
+ result.add(t);
+ }
+ }
+ return result;
+ } else {
+ try {
+ // if it can be parsed as a literal and is not an atom, OK to add annot
+ Literal result;
+ if (l.isAtom())
+ result = new Literal(((Structure)l).getFunctor());
+ else
+ result = Literal.parseLiteral(l.toString());
+
+ // create the source annots
+ Pred ts = new Pred("source",1);
+ ts.addTerm(source);
+ ts.addAnnots(result.getAnnots("source"));
+
+ result.delSources();
+ result.addAnnot(ts);
+ return result;
+ } catch (Exception e) {
+ // no problem, the content is not a pred (it is a number,
+ // string, ....) received in a message, for instance
+ }
+ }
+ return null;
+ }
+}
Modified: trunk/src/jason/stdlib/package.html
===================================================================
--- trunk/src/jason/stdlib/package.html 2008-04-10 21:40:07 UTC (rev 1213)
+++ trunk/src/jason/stdlib/package.html 2008-04-13 10:45:08 UTC (rev 1214)
@@ -90,6 +90,7 @@
<li>{@link jason.stdlib.string}: check whether an argument is a string.</li>
<li>{@link jason.stdlib.ground}: check whether an argument is ground.</li>
<li>{@link jason.stdlib.add_annot}: add an annotation in a literal.</li>
+ <li>{@link jason.stdlib.add_nested_source}: add a source in a literal.</li>
</ul>
Modified: trunk/src/jason/stdlib/send.java
===================================================================
--- trunk/src/jason/stdlib/send.java 2008-04-10 21:40:07 UTC (rev 1213)
+++ trunk/src/jason/stdlib/send.java 2008-04-13 10:45:08 UTC (rev 1214)
@@ -33,7 +33,6 @@
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
import jason.asSyntax.NumberTerm;
-import jason.asSyntax.Pred;
import jason.asSyntax.StringTerm;
import jason.asSyntax.Structure;
import jason.asSyntax.Term;
@@ -141,9 +140,10 @@
}
// remove source annots in the content (in case it is a pred)
- try {
- ((Pred)pcnt).delSources();
- } catch (Exception e) {}
+ // -- CHANGE: use nested annots
+ //try {
+ // ((Pred)pcnt).delSources();
+ //} catch (Exception e) {}
} catch (ArrayIndexOutOfBoundsException e) {
throw new JasonException("The internal action 'send' to '"+to+"' has not received three arguments.");
Modified: trunk/src/test/ListTermTest.java
===================================================================
--- trunk/src/test/ListTermTest.java 2008-04-10 21:40:07 UTC (rev 1213)
+++ trunk/src/test/ListTermTest.java 2008-04-13 10:45:08 UTC (rev 1214)
@@ -1,6 +1,7 @@
package test;
import jason.asSemantics.Unifier;
+import jason.asSyntax.Atom;
import jason.asSyntax.ListTerm;
import jason.asSyntax.ListTermImpl;
import jason.asSyntax.Structure;
@@ -177,6 +178,15 @@
assertEquals(lt5.getTail(), null);
}
+ public void testTailUnify() {
+ ListTerm lt5 = ListTermImpl.parseList("[H|T]");
+ Unifier u = new Unifier();
+ u.unifies(new VarTerm("H"), new Atom("a"));
+ u.unifies(new VarTerm("T"), ListTermImpl.parseList("[b,c]"));
+ lt5.apply(u);
+ assertEquals("[a,b,c]",lt5.toString());
+ }
+
public void testGround() {
ListTerm l = ListTermImpl.parseList("[c,b,a,x,y,d]");
assertTrue(l.isGround());
Modified: trunk/src/test/VarTermTest.java
===================================================================
--- trunk/src/test/VarTermTest.java 2008-04-10 21:40:07 UTC (rev 1213)
+++ trunk/src/test/VarTermTest.java 2008-04-13 10:45:08 UTC (rev 1214)
@@ -6,7 +6,6 @@
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ArithExpr;
-import jason.asSyntax.Atom;
import jason.asSyntax.DefaultTerm;
import jason.asSyntax.ListTerm;
import jason.asSyntax.ListTermImpl;
@@ -255,11 +254,13 @@
// X[a,b,c] = p[a,c,b,d] ok (X is p)
assertTrue(u.unifies(v1, p1));
assertEquals(u.get("X").toString(), "p(t1,t2)");
+ v1.apply(u);
+ assertEquals("p(t1,t2)",v1.toString());
}
public void testVarWithAnnots2() {
// test vars annots
-
+
// X[a] = Y[a,b] - ok
VarTerm v1 = VarTerm.parseVar("X[a]");
VarTerm v2 = VarTerm.parseVar("Y[a,b]");
@@ -271,7 +272,7 @@
assertFalse(u.unifies(v2, v1));
assertTrue(u.unifies(v1, v2));
- assertTrue(u.unifies(new Atom("vvv"), v1));
+ assertTrue(u.unifies(new Literal("vvv"), v1));
v1.apply(u);
assertEquals("vvv", v1.toString());
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-04-13 11:03:22
|
Revision: 1215
http://jason.svn.sourceforge.net/jason/?rev=1215&view=rev
Author: jomifred
Date: 2008-04-13 04:03:11 -0700 (Sun, 13 Apr 2008)
Log Message:
-----------
fig bug: add source(self) in goals without source
Modified Paths:
--------------
trunk/release-notes.txt
trunk/src/jason/asSemantics/TransitionSystem.java
Added Paths:
-----------
trunk/applications/as-unit-test/src/jason/tests/TestGoalSource.java
Added: trunk/applications/as-unit-test/src/jason/tests/TestGoalSource.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestGoalSource.java (rev 0)
+++ trunk/applications/as-unit-test/src/jason/tests/TestGoalSource.java 2008-04-13 11:03:11 UTC (rev 1215)
@@ -0,0 +1,30 @@
+package jason.tests;
+
+import jason.asunit.TestAgent;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestGoalSource {
+
+ TestAgent ag;
+
+ // initialisation of the agent test
+ @Before
+ public void setupAg() {
+ ag = new TestAgent();
+
+ // defines the agent's AgentSpeak code
+ ag.parseAScode(
+ "+!begin <- !g; !g[source(bob)]. "+
+ "+!g[source(A)] <- jason.asunit.print(A)."
+ );
+ }
+
+ @Test
+ public void testGoalSrouce() {
+ ag.addGoal("begin");
+ ag.assertPrint("self", 5);
+ ag.assertPrint("bob", 5);
+ }
+}
Property changes on: trunk/applications/as-unit-test/src/jason/tests/TestGoalSource.java
___________________________________________________________________
Name: svn:executable
+ *
Modified: trunk/release-notes.txt
===================================================================
--- trunk/release-notes.txt 2008-04-13 10:45:08 UTC (rev 1214)
+++ trunk/release-notes.txt 2008-04-13 11:03:11 UTC (rev 1215)
@@ -4,7 +4,9 @@
Bugs fixed:
. use nested source annotations in communication
+. add "source(self)" in goals without source
+
-------------
version 1.1.0
-------------
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2008-04-13 10:45:08 UTC (rev 1214)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2008-04-13 11:03:11 UTC (rev 1215)
@@ -461,6 +461,11 @@
case achieve:
// free variables in an event cannot conflict with those in the plan
body = (Literal)body.clone();
+ if (!body.hasSource()) {
+ // do not add source(self) in case the
+ // programmer set some annotation
+ body.addAnnot(BeliefBase.TSelf);
+ }
body.makeVarsAnnon();
conf.C.addAchvGoal(body, conf.C.SI);
confP.step = State.StartRC;
@@ -469,6 +474,11 @@
// Rule Achieve as a New Focus (the !! operator)
case achieveNF:
body = (Literal)body.clone();
+ if (!body.hasSource()) {
+ // do not add source(self) in case the
+ // programmer set some annotation
+ body.addAnnot(BeliefBase.TSelf);
+ }
body.makeVarsAnnon();
conf.C.addAchvGoal(body, Intention.EmptyInt);
updateIntention();
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-04-15 11:51:28
|
Revision: 1216
http://jason.svn.sourceforge.net/jason/?rev=1216&view=rev
Author: jomifred
Date: 2008-04-15 04:51:25 -0700 (Tue, 15 Apr 2008)
Log Message:
-----------
changes in class Vec of jason team
Modified Paths:
--------------
trunk/applications/jason-team/AC-Local-JasonTeam.mas2j
trunk/applications/jason-team/src/asl/dummy.asl
trunk/applications/jason-team/src/java/arch/LocalWorldModel.java
trunk/applications/jason-team/src/java/jia/Vec.java
trunk/applications/jason-team/src/java/jia/herd_position.java
trunk/applications/jason-team/src/java/test/TestBasicHerding.java
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/asSyntax/Literal.java
trunk/src/jason/asSyntax/VarTerm.java
Modified: trunk/applications/jason-team/AC-Local-JasonTeam.mas2j
===================================================================
--- trunk/applications/jason-team/AC-Local-JasonTeam.mas2j 2008-04-13 11:03:11 UTC (rev 1215)
+++ trunk/applications/jason-team/AC-Local-JasonTeam.mas2j 2008-04-15 11:51:25 UTC (rev 1216)
@@ -11,7 +11,7 @@
agents:
gaucho1 dummy.asl
- [verbose=1, gui=yes, write_status=yes, ac_sim_back_dir="./massim-server/backup",
+ [verbose=1, gui=no, write_status=yes, ac_sim_back_dir="./massim-server/backup",
host="localhost", port=12300, username=participant1, password="1"]
agentArchClass arch.ACArchitecture
agentClass agent.SelectEvent
Modified: trunk/applications/jason-team/src/asl/dummy.asl
===================================================================
--- trunk/applications/jason-team/src/asl/dummy.asl 2008-04-13 11:03:11 UTC (rev 1215)
+++ trunk/applications/jason-team/src/asl/dummy.asl 2008-04-15 11:51:25 UTC (rev 1216)
@@ -45,27 +45,28 @@
+pos(_,_,_) // new cycle
: cell(_,_,cow(_)) // I see cows
- <- jia.herd_position(X,Y); // compute new location
- .print("COWS! going to ",X,",",Y);
- -+target(X,Y). // go to there
-
-+pos(_,_,_)
- : not cell(_,_,cow(_)) // I see no cow
- <- -target(_,_);
- !move.
+ <- !decide_target.
/* -- what todo when arrive at location */
++!decide_target
+ : jia.herd_position(X,Y) & // compute new location
+ (not target(_,_) | (target(TX,TY) & (TX \== X | TY \== Y))) // no target OR new target?
+ <- .print("COWS! going to ",X,",",Y," previous target ",TX,",",TY);
+ -+target(X,Y).
+
+!decide_target // chose a new random pos
: not cell(_,_,cow(_))
<- ?random_pos(NX,NY);
.print("New random target: ",NX,",",NY);
-+target(NX,NY).
+
+!decide_target
<- .print("No need for a new target, consider last herding location.");
do(skip). // send an action so that the simulator does not wait for me.
+
/* -- plans to move to a destination represented in the belief target(X,Y)
-- (it is a kind of persistent goal)
*/
@@ -73,7 +74,7 @@
// if the target is changed, "restart" move
+target(NX,NY)
<- .drop_desire(move);
- jia.set_target(NX,NY);
+ jia.set_target(NX,NY);
!!move.
// I still do not know my location
Modified: trunk/applications/jason-team/src/java/arch/LocalWorldModel.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/LocalWorldModel.java 2008-04-13 11:03:11 UTC (rev 1215)
+++ trunk/applications/jason-team/src/java/arch/LocalWorldModel.java 2008-04-15 11:51:25 UTC (rev 1216)
@@ -60,11 +60,17 @@
public Location nearFree(Location l) throws Exception {
int w = 0;
+ List<Location> options = new ArrayList<Location>();
while (true) {
- for (int x=l.x-w; x<=l.x+w;x++)
- for (int y=l.y-w; y<=l.y+w;y++)
- if (isFree(x,y))
- return new Location(x,y);
+ options.clear();
+ for (int x=l.x-w; x<=l.x+w;x++) {
+ if (isFree(x,l.y-w))
+ options.add(new Location(x,l.y-w));
+ if (isFree(x,l.y+w))
+ options.add(new Location(x,l.y+w));
+ }
+ if (!options.isEmpty())
+ return options.get(random.nextInt(options.size()));
w++;
}
}
Modified: trunk/applications/jason-team/src/java/jia/Vec.java
===================================================================
--- trunk/applications/jason-team/src/java/jia/Vec.java 2008-04-13 11:03:11 UTC (rev 1215)
+++ trunk/applications/jason-team/src/java/jia/Vec.java 2008-04-15 11:51:25 UTC (rev 1216)
@@ -2,36 +2,41 @@
import jason.environment.grid.Location;
+import java.util.ArrayList;
import java.util.List;
import arch.LocalWorldModel;
-public class Vec {
+public class Vec implements Cloneable {
public final int x,y;
+ public final double r,t;
public Vec(int x, int y) {
this.x = x;
this.y = y;
+ this.r = Math.sqrt(x*x + y*y);
+ this.t = Math.atan2(y,x);
}
/** create a vector based on a location in the model */
public Vec(LocalWorldModel model, Location l) {
this.x = l.x;
this.y = model.getHeight()-l.y-1;
+ this.r = Math.sqrt(x*x + y*y);
+ this.t = Math.atan2(y,x);
}
public int getX() { return x; }
public int getY() { return y; }
+ public double magnitude() { return r; }
+ public double angle() { return t; }
+
public Location getLocation(LocalWorldModel model) {
return new Location(x, model.getHeight()-y-1);
}
- public double magnitude() {
- return Math.sqrt(x*x + y*y);
- }
-
public Vec add(Vec v) {
return new Vec(x + v.x, y + v.y);
}
@@ -52,25 +57,69 @@
}
return false;
}
+
+ public Object clone() {
+ return this; // it is an immutable object, no need to create a new one
+ }
+
+
+ /**
+ * Provides info on which octant (0-7) the vector lies in.
+ * 0 indicates 0 radians +- PI/8 1-7 continue CCW.
+ * @return 0 - 7, depending on which direction the vector is pointing.
+ */
+ public int octant() {
+ double temp = t + Math.PI/8;
+ if (temp<0)
+ temp += Math.PI*2;
+ return ((int)(temp/(Math.PI/4))%8);
+ }
+
+ /**
+ * Provides info on which quadrant (0-3) the vector lies in.
+ * 0 indicates 0 radians +- PI/4 1-3 continue CCW.
+ * @return 0 - 3, depending on which direction the vector is pointing.
+ */
+ public int quadrant() {
+ double temp = t + Math.PI/4;
+ if (temp<0) temp += Math.PI*2;
+ return ((int)(temp/(Math.PI/2))%4);
+ }
+
+
+ //
+ // Useful static methods for list of vecs
+ //
+
public static Vec max(List<Vec> vs) {
Vec max = null;
- if (vs.size() > 0)
- max = vs.get(0);
for (Vec v: vs) {
- if (max.magnitude() < v.magnitude())
+ if (max == null || max.magnitude() < v.magnitude())
max = v;
}
return max;
}
- public static void cluster(List<Vec> vs, int maxstddev) {
+ public static List<Vec> sub(List<Vec> vs, Vec ref) {
+ List<Vec> r = new ArrayList<Vec>(vs.size());
+ for (Vec v: vs) {
+ r.add(v.sub(ref));
+ }
+ return r;
+ }
+
+ public static List<Vec> cluster(List<Vec> vs, int maxstddev) {
+ vs = new ArrayList<Vec>(vs);
Vec stddev = Vec.stddev(vs);
// remove max if stddev is too big
while (stddev.magnitude() > maxstddev) {
- vs.remove(Vec.max(vs));
+ Vec mean = Vec.mean(vs);
+ Vec max = Vec.max(Vec.sub(vs, mean));
+ vs.remove(max.add(mean));
stddev = Vec.stddev(vs);
}
+ return vs;
}
public static Vec mean(List<Vec> vs) {
Modified: trunk/applications/jason-team/src/java/jia/herd_position.java
===================================================================
--- trunk/applications/jason-team/src/java/jia/herd_position.java 2008-04-13 11:03:11 UTC (rev 1215)
+++ trunk/applications/jason-team/src/java/jia/herd_position.java 2008-04-15 11:51:25 UTC (rev 1216)
@@ -50,7 +50,7 @@
if (cows.isEmpty())
return null;
- Vec.cluster(cows, 3); // find center/clusterise
+ cows = Vec.cluster(cows, 2); // find center/clusterise
Vec mean = Vec.mean(cows);
Modified: trunk/applications/jason-team/src/java/test/TestBasicHerding.java
===================================================================
--- trunk/applications/jason-team/src/java/test/TestBasicHerding.java 2008-04-13 11:03:11 UTC (rev 1215)
+++ trunk/applications/jason-team/src/java/test/TestBasicHerding.java 2008-04-15 11:51:25 UTC (rev 1216)
@@ -33,11 +33,12 @@
public void scenario1() {
cowboy = new Vec(3,5);
- cows = new Vec[4];
+ cows = new Vec[5];
cows[0] = new Vec(6,7);
cows[1] = new Vec(5,30);
cows[2] = new Vec(4,8);
cows[3] = new Vec(5,10);
+ cows[4] = new Vec(0,1);
for (int i=0; i<cows.length; i++)
model.addCow(cows[i].getLocation(model));
@@ -153,14 +154,8 @@
}
// find center/clusterise
+ cowsTarget = Vec.cluster(cowsTarget, 2);
Vec stddev = Vec.stddev(cowsTarget);
- assertEquals(new Vec(0,9), stddev);
-
- // remove max if stddev is too big
- while (stddev.magnitude() > 3) {
- cowsTarget.remove(Vec.max(cowsTarget));
- stddev = Vec.stddev(cowsTarget);
- }
assertTrue(stddev.magnitude() < 3);
Vec mean = Vec.mean(cowsTarget);
@@ -194,9 +189,7 @@
}
// find center/clusterise
- Vec.cluster(cowsTarget, 3);
- Vec stddev = Vec.stddev(cowsTarget);
- assertTrue(stddev.magnitude() < 3);
+ cowsTarget = Vec.cluster(cowsTarget, 2);
Vec mean = Vec.mean(cowsTarget);
assertEquals(new Vec(9,1), mean);
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2008-04-13 11:03:11 UTC (rev 1215)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2008-04-15 11:51:25 UTC (rev 1216)
@@ -420,7 +420,7 @@
case internalAction:
boolean ok = false;
try {
- InternalAction ia = ((InternalActionLiteral)body).getIA(ag);
+ InternalAction ia = ((InternalActionLiteral)bTerm).getIA(ag);
Object oresult = ia.execute(this, u, body.getTermsArray());
if (oresult != null) {
ok = oresult instanceof Boolean && (Boolean)oresult;
Modified: trunk/src/jason/asSyntax/Literal.java
===================================================================
--- trunk/src/jason/asSyntax/Literal.java 2008-04-13 11:03:11 UTC (rev 1215)
+++ trunk/src/jason/asSyntax/Literal.java 2008-04-15 11:51:25 UTC (rev 1216)
@@ -77,20 +77,21 @@
}
public Literal(Literal l) {
- super((Pred) l);
- type = l.type;
+ super((Pred) l);
+ type = l.type;
}
public static Literal parseLiteral(String sLiteral) {
- as2j parser = new as2j(new StringReader(sLiteral));
try {
- return parser.literal();
+ as2j parser = new as2j(new StringReader(sLiteral));
+ return parser.literal();
} catch (Exception e) {
logger.log(Level.SEVERE,"Error parsing literal " + sLiteral,e);
return null;
}
- }
+ }
+
public static Literal tryParsingLiteral(String sLiteral) throws ParseException {
return new as2j(new StringReader(sLiteral)).literal();
}
Modified: trunk/src/jason/asSyntax/VarTerm.java
===================================================================
--- trunk/src/jason/asSyntax/VarTerm.java 2008-04-13 11:03:11 UTC (rev 1215)
+++ trunk/src/jason/asSyntax/VarTerm.java 2008-04-15 11:51:25 UTC (rev 1216)
@@ -110,7 +110,13 @@
}
vl = (Term)vl.clone(); // should clone here, since there is no cloning in unify
- // The below does not conform the rules in manual
+ // TODO: decide whether to use var annots in apply
+ // X = p[a]
+ // !X[b]
+ // what's the event:
+ // +!p[a]
+ // or
+ // +!p[a,b]
//if (vl.isPred() && this.hasAnnot()) // if this var has annots, add them in the value's annots (Experimental)
// ((Pred)vl).addAnnots(this.getAnnots());
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-04-16 16:46:53
|
Revision: 1218
http://jason.svn.sourceforge.net/jason/?rev=1218&view=rev
Author: jomifred
Date: 2008-04-16 09:46:46 -0700 (Wed, 16 Apr 2008)
Log Message:
-----------
correctly handle failure events caused by no relevant plans
minor changes in the jason team
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/tests/TestAll.java
trunk/applications/jason-team/logging.properties
trunk/applications/jason-team/src/java/arch/ACArchitecture.java
trunk/applications/jason-team/src/java/arch/IdentifyCrashed.java
trunk/applications/jason-team/src/java/arch/WriteStatusThread.java
trunk/release-notes.txt
trunk/src/jason/asSemantics/TransitionSystem.java
Added Paths:
-----------
trunk/applications/as-unit-test/src/jason/tests/TestPlanFailure.java
Modified: trunk/applications/as-unit-test/src/jason/tests/TestAll.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestAll.java 2008-04-15 12:09:22 UTC (rev 1217)
+++ trunk/applications/as-unit-test/src/jason/tests/TestAll.java 2008-04-16 16:46:46 UTC (rev 1218)
@@ -8,8 +8,10 @@
@SuiteClasses({
BugVarsInInitBels.class,
TestAddLogExprInBB.class,
+ TestGoalSource.class,
TestKQML.class,
- TestVarInContext.class /*,
- TestPlanbodyAsTerm.class*/
+ /* TestPlanbodyAsTerm.class, */
+ TestPlanFailure.class,
+ TestVarInContext.class
})
public class TestAll { }
Added: trunk/applications/as-unit-test/src/jason/tests/TestPlanFailure.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestPlanFailure.java (rev 0)
+++ trunk/applications/as-unit-test/src/jason/tests/TestPlanFailure.java 2008-04-16 16:46:46 UTC (rev 1218)
@@ -0,0 +1,49 @@
+package jason.tests;
+
+import jason.asunit.TestAgent;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestPlanFailure {
+
+ TestAgent ag;
+
+ // initialisation of the agent test
+ @Before
+ public void setupAg() {
+ ag = new TestAgent();
+
+ // defines the agent's AgentSpeak code
+ ag.parseAScode(
+ "+!test : true <- !g1(X); endtest; end(X). "+
+
+ "+!g1(X) : true <- inig1; !g2(X); endg1. "+
+ "+!g2(X) : true <- inig2; !g3(X); endg2. "+
+ "+!g3(X) : true <- inig2; !g4(X); endg3. "+
+ "+!g4(X) : true <- inig4; !g5(X); endg4. "+
+ "+!g5(_) : true <- .fail. "+
+ "-!g3(failure) : true <- infailg3. "+
+
+ "+!norel <- !j; endnorel. "+
+ "-!j <- infailj. "
+ );
+ }
+
+ @Test
+ public void testFailurePlan() {
+ ag.addGoal("test");
+ ag.assertAct("inig4", 10);
+ ag.assertAct("infailg3", 5);
+ ag.assertAct("endg2", 5);
+ ag.assertAct("endtest", 5);
+ ag.assertAct("end(failure)", 5);
+ }
+
+ @Test
+ public void testNoRelPlan() {
+ ag.addGoal("norel");
+ ag.assertAct("infailj", 10);
+ ag.assertAct("endnorel", 5);
+ }
+}
Modified: trunk/applications/jason-team/logging.properties
===================================================================
--- trunk/applications/jason-team/logging.properties 2008-04-15 12:09:22 UTC (rev 1217)
+++ trunk/applications/jason-team/logging.properties 2008-04-16 16:46:46 UTC (rev 1218)
@@ -4,10 +4,10 @@
#
# default Jason MAS Console
-handlers = jason.runtime.MASConsoleLogHandler, java.util.logging.FileHandler
+#handlers = jason.runtime.MASConsoleLogHandler, java.util.logging.FileHandler
# To use the ConsoleHandler, use the following line instead.
-#handlers= java.util.logging.ConsoleHandler, java.util.logging.FileHandler
+handlers= java.util.logging.ConsoleHandler, java.util.logging.FileHandler
# Default logging level. Other values are:
# SEVERE (only severe messages)
Modified: trunk/applications/jason-team/src/java/arch/ACArchitecture.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-04-15 12:09:22 UTC (rev 1217)
+++ trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-04-16 16:46:46 UTC (rev 1218)
@@ -61,6 +61,7 @@
@Override
public List<Literal> perceive() {
+ agDidPerceive(); // for crash control
return new ArrayList<Literal>(percepts); // it must be a copy!
}
Modified: trunk/applications/jason-team/src/java/arch/IdentifyCrashed.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/IdentifyCrashed.java 2008-04-15 12:09:22 UTC (rev 1217)
+++ trunk/applications/jason-team/src/java/arch/IdentifyCrashed.java 2008-04-16 16:46:46 UTC (rev 1218)
@@ -42,27 +42,23 @@
@Override
public List<Literal> perceive() {
- agThread = Thread.currentThread();
- doPercept();
+ agThread = Thread.currentThread();
+ agDidPerceive();
return super.perceive();
}
- private synchronized void doPercept() {
+ public synchronized void agDidPerceive() {
didPercept = true;
notifyAll();
}
- public boolean didPercept() {
- return didPercept;
+ private synchronized void waitPerceive() throws InterruptedException {
+ wait(maxCycleTime);
}
-
+
public boolean isCrashed() {
return !didPercept;
}
-
- private synchronized void waitPercept() throws InterruptedException {
- wait(maxCycleTime);
- }
@Override
public void stopAg() {
@@ -78,7 +74,7 @@
dead = true;
// gives some time to TS get the change in state
- waitPercept();
+ waitPerceive();
try {
if (isCrashed()) {
return fix2();
@@ -94,17 +90,23 @@
/** try to fix the agent: approach 2: interrupt the agent thread */
protected boolean fix2() throws Exception {
- getTS().getLogger().warning("fix2: I am still dead! Interrupting the agent thread...");
- // try to interrupt the agent thread.
- agThread.interrupt();
+ if (agThread != null) {
+ getTS().getLogger().warning("fix2: I am still dead! Interrupting the agent thread...");
+ // try to interrupt the agent thread.
+
+ agThread.interrupt();
- waitPercept();
- if (isCrashed()) {
- getTS().getLogger().warning("Interrupt doesn't work!!! The agent remains dead!");
- return fix3();
+ waitPerceive();
+ if (isCrashed()) {
+ getTS().getLogger().warning("Interrupt doesn't work!!! The agent remains dead!");
+ return fix3();
+ } else {
+ getTS().getLogger().warning("fix2: I am Ok now!");
+ return true;
+ }
} else {
- getTS().getLogger().warning("fix2: I am Ok now!");
- return true;
+ getTS().getLogger().warning("fix2: can not be used (thread == null).");
+ return fix3();
}
}
Modified: trunk/applications/jason-team/src/java/arch/WriteStatusThread.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/WriteStatusThread.java 2008-04-15 12:09:22 UTC (rev 1217)
+++ trunk/applications/jason-team/src/java/arch/WriteStatusThread.java 2008-04-16 16:46:46 UTC (rev 1218)
@@ -109,6 +109,7 @@
if (act.equals(WorldModel.Move.southwest.toString())) return "sw";
if (act.equals(WorldModel.Move.north.toString())) return "n ";
if (act.equals(WorldModel.Move.south.toString())) return "s ";
+ if (act.equals(WorldModel.Move.skip.toString())) return "sk";
return act;
}
Modified: trunk/release-notes.txt
===================================================================
--- trunk/release-notes.txt 2008-04-15 12:09:22 UTC (rev 1217)
+++ trunk/release-notes.txt 2008-04-16 16:46:46 UTC (rev 1218)
@@ -5,6 +5,7 @@
Bugs fixed:
. use nested source annotations in communication
. add "source(self)" in goals without source
+. correctly handle failure event caused by no relevant plans
-------------
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2008-04-15 12:09:22 UTC (rev 1217)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2008-04-16 16:46:46 UTC (rev 1218)
@@ -459,13 +459,13 @@
// Rule Achieve
case achieve:
- // free variables in an event cannot conflict with those in the plan
- body = (Literal)body.clone();
if (!body.hasSource()) {
// do not add source(self) in case the
// programmer set some annotation
body.addAnnot(BeliefBase.TSelf);
}
+ // free variables in an event cannot conflict with those in the plan
+ body = (Literal)body.clone();
body.makeVarsAnnon();
conf.C.addAchvGoal(body, conf.C.SI);
confP.step = State.StartRC;
@@ -473,12 +473,12 @@
// Rule Achieve as a New Focus (the !! operator)
case achieveNF:
- body = (Literal)body.clone();
if (!body.hasSource()) {
// do not add source(self) in case the
// programmer set some annotation
body.addAnnot(BeliefBase.TSelf);
}
+ body = (Literal)body.clone();
body.makeVarsAnnon();
conf.C.addAchvGoal(body, Intention.EmptyInt);
updateIntention();
@@ -635,8 +635,13 @@
// +!s: !b; !z
// should became
// +!s: !z
- im = i.pop(); // +!c above, old
- while (!im.unif.unifies(topIM.getTrigger().getLiteral(), im.getTrigger().getLiteral()) && i.size() > 0) {
+ im = i.peek();
+ if (im.isFinished() || !im.unif.unifies(topIM.getTrigger().getLiteral(), im.getCurrentStep().getBodyTerm()))
+ im = i.pop(); // +!c above
+
+ while (i.size() > 0 &&
+ !im.unif.unifies(topIM.getTrigger().getLiteral(), im.getTrigger().getLiteral()) &&
+ !im.unif.unifies(topIM.getTrigger().getLiteral(), im.getCurrentStep().getBodyTerm())) {
im = i.pop();
}
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-04-17 17:34:18
|
Revision: 1219
http://jason.svn.sourceforge.net/jason/?rev=1219&view=rev
Author: jomifred
Date: 2008-04-17 10:34:11 -0700 (Thu, 17 Apr 2008)
Log Message:
-----------
plans body as term
first implementation (experimental) of .if internal action
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/tests/TestAll.java
trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java
trunk/release-notes.txt
trunk/src/jason/asSyntax/PlanBody.java
trunk/src/jason/asSyntax/PlanBodyImpl.java
trunk/src/jason/asSyntax/VarTerm.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/test/ASParserTest.java
Added Paths:
-----------
trunk/applications/as-unit-test/src/jason/tests/TestIF.java
trunk/src/jason/stdlib/conditional.java
Modified: trunk/applications/as-unit-test/src/jason/tests/TestAll.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestAll.java 2008-04-16 16:46:46 UTC (rev 1218)
+++ trunk/applications/as-unit-test/src/jason/tests/TestAll.java 2008-04-17 17:34:11 UTC (rev 1219)
@@ -9,8 +9,9 @@
BugVarsInInitBels.class,
TestAddLogExprInBB.class,
TestGoalSource.class,
+ TestIF.class,
TestKQML.class,
- /* TestPlanbodyAsTerm.class, */
+ TestPlanbodyAsTerm.class,
TestPlanFailure.class,
TestVarInContext.class
})
Added: trunk/applications/as-unit-test/src/jason/tests/TestIF.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestIF.java (rev 0)
+++ trunk/applications/as-unit-test/src/jason/tests/TestIF.java 2008-04-17 17:34:11 UTC (rev 1219)
@@ -0,0 +1,42 @@
+package jason.tests;
+
+import jason.asunit.TestAgent;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestIF {
+
+ TestAgent ag;
+
+ // initialisation of the agent test
+ @Before
+ public void setupAg() {
+ ag = new TestAgent();
+
+ // defines the agent's AgentSpeak code
+ ag.parseAScode(
+ "b(3). " +
+ "+!test1 <- a1; "+
+ " .conditional(b(X), {jason.asunit.print(X); b1}, {jason.asunit.print(no);b2}); "+
+ " a2. "+
+ "+!test2 <- -b(_); !test1. "
+ );
+ }
+
+ @Test
+ public void test1() {
+ ag.addGoal("test1");
+ ag.assertPrint("3", 5);
+ ag.assertAct("b1", 5);
+ ag.assertAct("a2", 5);
+ }
+
+ @Test
+ public void test2() {
+ ag.addGoal("test2");
+ ag.assertPrint("no", 5);
+ ag.assertAct("b2", 5);
+ ag.assertAct("a2", 5);
+ }
+}
Modified: trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java 2008-04-16 16:46:46 UTC (rev 1218)
+++ trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java 2008-04-17 17:34:11 UTC (rev 1219)
@@ -16,23 +16,33 @@
// defines the agent's AgentSpeak code
ag.parseAScode(
- "+!start <- +g(a(1); b; c); ?g(X); !g(X). "+
- "+!test2 <- !g(!g2(1)). "+
- "+!test3 <- !g2(-1 + 2). "+
- "+!g(A; R) <- A; !g(R). "+
- "+!g(A) <- A." +
- "+!g2(A) <- jason.asunit.print(A)."
+ "+!start <- +g( {a(1); b; c}); ?g(X); !g(X). " +
+ "+!test2 <- !g( {!g2(1)}). "+
+ "+!test3 <- !g2(-1 + 2)."+
+ "+!test4 <- X = {a(1); b; c}; !g(X)."+
+
+ "+!g({A; R}) <- A; !g(R). "+
+ "+!g(A) <- A." +
+ "+!g2(A) <- jason.asunit.print(A)."
);
}
@Test
- public void testProgram1() {
+ public void testProgram1a() {
ag.addGoal("start");
- ag.assertBel("g(a(1);b;c)", 5);
+ ag.assertBel("g({a(1);b;c})", 5);
ag.assertAct("a(1)", 4);
ag.assertAct("b", 4);
ag.assertAct("c", 4);
}
+
+ @Test
+ public void testProgram1b() {
+ ag.addGoal("test4");
+ ag.assertAct("a(1)", 4);
+ ag.assertAct("b", 4);
+ ag.assertAct("c", 4);
+ }
@Test
public void testProgram2() {
Modified: trunk/release-notes.txt
===================================================================
--- trunk/release-notes.txt 2008-04-16 16:46:46 UTC (rev 1218)
+++ trunk/release-notes.txt 2008-04-17 17:34:11 UTC (rev 1219)
@@ -2,6 +2,11 @@
version 1.1.1
-------------
+New features
+. Terms can be body plans enclosed by |{ ... }", as in the following
+ example:
+ test({ a1; !g; ?b(X); .print(X) }, 10)
+
Bugs fixed:
. use nested source annotations in communication
. add "source(self)" in goals without source
Modified: trunk/src/jason/asSyntax/PlanBody.java
===================================================================
--- trunk/src/jason/asSyntax/PlanBody.java 2008-04-16 16:46:46 UTC (rev 1218)
+++ trunk/src/jason/asSyntax/PlanBody.java 2008-04-17 17:34:11 UTC (rev 1219)
@@ -17,7 +17,7 @@
public BodyType getBodyType();
public Term getBodyTerm();
- public PlanBody getBodyNext();
+ public PlanBody getBodyNext();
public boolean isEmptyBody();
public int getPlanSize();
@@ -25,7 +25,10 @@
public void setBodyType(BodyType bt);
public void setBodyTerm(Term t);
public void setBodyNext(PlanBody bl);
+ public PlanBody getLastBody();
+ public boolean isBodyTerm();
+ public void setAsBodyTerm(boolean b);
public boolean add(PlanBody bl);
public boolean add(int index, PlanBody bl);
Modified: trunk/src/jason/asSyntax/PlanBodyImpl.java
===================================================================
--- trunk/src/jason/asSyntax/PlanBodyImpl.java 2008-04-16 16:46:46 UTC (rev 1218)
+++ trunk/src/jason/asSyntax/PlanBodyImpl.java 2008-04-17 17:34:11 UTC (rev 1219)
@@ -20,9 +20,11 @@
public static final String BODY_PLAN_FUNCTOR = ";";
private Term term = null;
- private PlanBody next = null;
+ private PlanBody next = null;
private BodyType formType = BodyType.none;
+ private boolean isTerm = false;
+
/** constructor for empty plan body */
public PlanBodyImpl() {
super(BODY_PLAN_FUNCTOR, 0);
@@ -60,6 +62,13 @@
term = t;
}
+ public boolean isBodyTerm() {
+ return isTerm;
+ }
+ public void setAsBodyTerm(boolean b) {
+ isTerm = b;
+ }
+
@Override
public boolean isPlanBody() {
return true;
@@ -152,12 +161,23 @@
next.add(bl);
return true;
}
+
+ public PlanBody getLastBody() {
+ if (next == null)
+ return this;
+ else
+ return next.getLastBody();
+ }
public boolean add(int index, PlanBody bl) {
if (index == 0) {
swap(bl);
- this.next = bl;
- } else {
+ PlanBody bak = this.next;
+ this.next = bl.getBodyNext();
+ PlanBody last = bl.getLastBody();
+ bl.setBodyNext(bak);
+ last.setBodyNext(bl);
+ } else if (next != null) {
next.add(index - 1, bl);
}
return true;
@@ -203,18 +223,29 @@
return new PlanBodyImpl();
PlanBodyImpl c = new PlanBodyImpl(formType, (Term)term.clone());
+ c.isTerm = isTerm;
if (next != null)
c.setBodyNext((PlanBody)getBodyNext().clone());
return c;
}
public String toString() {
- if (term == null)
+ if (term == null) {
return "";
- else if (next == null)
- return formType.toString() + term;
- else
- return formType.toString() + term + "; " + next;
+ } else {
+ String b, e;
+ if (isTerm) {
+ b = "{ ";
+ e = " }";
+ } else {
+ b = "";
+ e = "";
+ }
+ if (next == null)
+ return b+formType.toString() + term+e;
+ else
+ return b+formType.toString() + term + "; " + next+e;
+ }
}
/** get as XML */
Modified: trunk/src/jason/asSyntax/VarTerm.java
===================================================================
--- trunk/src/jason/asSyntax/VarTerm.java 2008-04-16 16:46:46 UTC (rev 1218)
+++ trunk/src/jason/asSyntax/VarTerm.java 2008-04-17 17:34:11 UTC (rev 1219)
@@ -874,7 +874,7 @@
}
// -----------------------
- // BodyLiteral interface implementation
+ // PlanBody interface implementation
// -----------------------
public BodyType getBodyType() {
@@ -898,6 +898,13 @@
return null;
}
+ public PlanBody getLastBody() {
+ if (value != null && getValue() instanceof PlanBody)
+ return ((PlanBody) getValue()).getLastBody();
+ else
+ return null;
+ }
+
public boolean isEmptyBody() {
if (value != null && getValue() instanceof PlanBody)
return ((PlanBody) getValue()).isEmptyBody();
@@ -927,6 +934,18 @@
((PlanBody) getValue()).setBodyNext(bl);
}
+ public boolean isBodyTerm() {
+ if (value != null && getValue() instanceof PlanBody)
+ return ((PlanBody) getValue()).isBodyTerm();
+ else
+ return false;
+ }
+
+ public void setAsBodyTerm(boolean b) {
+ if (value != null && getValue() instanceof PlanBody)
+ ((PlanBody) getValue()).setAsBodyTerm(b);
+ }
+
public boolean add(PlanBody bl) {
if (value != null && getValue() instanceof PlanBody)
return ((PlanBody) getValue()).add(bl);
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-04-16 16:46:46 UTC (rev 1218)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-04-17 17:34:11 UTC (rev 1219)
@@ -289,8 +289,8 @@
/* Plan */
Plan plan() : { Token k; Pred L = null;
Trigger T;
- Object C = null; PlanBody bl = null;
- Object B = null;
+ Object C = null;
+ PlanBody B = null;
int start = -1, end;}
{
[ k = <TK_LABEL_AT> L=pred() { start = k.beginLine; } ]
@@ -303,14 +303,13 @@
try { ial = checkInternalActionsInContext((LogicalFormula)C, curAg); } catch (Exception e) {}
if (ial != null)
throw new ParseException(getSourceRef(ial)+" The internal action '"+ial+"' can not be used in plan's context!");
- if (B != null) {
- if (!(B instanceof PlanBody))
- throw new ParseException(getSourceRef(B)+" Unknown body formula:"+B);
- bl = (PlanBody)B;
- if (bl.getBodyTerm().equals(Literal.LTrue))
- bl = (PlanBody)bl.getBodyNext();
- }
- Plan p = new Plan(L,T,(LogicalFormula)C, bl);
+ //if (B != null) {
+ //if (!(B instanceof PlanBody))
+ // throw new ParseException(getSourceRef(B)+" Unknown body formula:"+B);
+ //bl = (PlanBody)B;
+ if (B != null && B.getBodyTerm().equals(Literal.LTrue))
+ B = (PlanBody)B.getBodyNext();
+ Plan p = new Plan(L,T,(LogicalFormula)C, B);
p.setSrcLines(start,end);
p.setSrc(asSource);
return p;
@@ -341,21 +340,31 @@
/* Plan body */
-Object plan_body() : { Object F; Object R = null; }
+PlanBody plan_body() : { Object F; PlanBody R = null; }
{
F = body_formula()
[ ";" { if (!(F instanceof PlanBody)) throw new ParseException(getSourceRef(F)+" "+F+" is not a body literal!"); }
- R = plan_body() { if (!(R instanceof PlanBody)) throw new ParseException(getSourceRef(R)+" "+R+" is not a body literal!"); }
+ R = plan_body()
]
- { if (F instanceof PlanBody && R instanceof PlanBody) {
- ((PlanBody)F).setBodyNext( (PlanBody)R );
+ { if (F instanceof PlanBody) {
+ ((PlanBody)F).setBodyNext( R );
}
- return F;
+ return (PlanBody)F;
}
}
+PlanBody plan_body_term(): { PlanBody B = null; }
+{
+ "{"
+ B = plan_body()
+ "}"
+ { B.setAsBodyTerm(true);
+ return B;
+ }
+}
+
Object body_formula() :
{ BodyType formType = BodyType.action; Object B; }
{
@@ -448,18 +457,11 @@
Term term() : { Object o;}
{
- ( o=list()
- | o=log_expr() //plan_body() // plan_body includes literals/atoms/structures
+ ( o=list()
+ | o=plan_body_term()
+ | o=log_expr() // log_expr includes literals/atoms/structures
)
- { // if the result is a PlanBody action with size = 1, it is indeed a literal and not a body literal
- /*if (o instanceof PlanBody) {
- PlanBody bl = (PlanBody)o;
- if (bl.getBodyType() == BodyType.action && bl.getPlanSize() == 1) {
- o = bl.getBodyTerm();
- }
- }*/
- return changeToAtom(o);
- }
+ { return changeToAtom(o); }
}
@@ -548,6 +550,7 @@
( op2 = arithm_expr()
| op2 = string()
| op2 = list()
+ | op2 = plan_body_term()
)
{ if ( ((Term)op1).isInternalAction() && operator != RelationalOp.literalBuilder)
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2008-04-16 16:46:46 UTC (rev 1218)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2008-04-17 17:34:11 UTC (rev 1219)
@@ -316,8 +316,8 @@
final public Plan plan() throws ParseException {
Token k; Pred L = null;
Trigger T;
- Object C = null; PlanBody bl = null;
- Object B = null;
+ Object C = null;
+ PlanBody B = null;
int start = -1, end;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case TK_LABEL_AT:
@@ -357,14 +357,13 @@
try { ial = checkInternalActionsInContext((LogicalFormula)C, curAg); } catch (Exception e) {}
if (ial != null)
{if (true) throw new ParseException(getSourceRef(ial)+" The internal action '"+ial+"' can not be used in plan's context!");}
- if (B != null) {
- if (!(B instanceof PlanBody))
- {if (true) throw new ParseException(getSourceRef(B)+" Unknown body formula:"+B);}
- bl = (PlanBody)B;
- if (bl.getBodyTerm().equals(Literal.LTrue))
- bl = (PlanBody)bl.getBodyNext();
- }
- Plan p = new Plan(L,T,(LogicalFormula)C, bl);
+ //if (B != null) {
+ //if (!(B instanceof PlanBody))
+ // throw new ParseException(getSourceRef(B)+" Unknown body formula:"+B);
+ //bl = (PlanBody)B;
+ if (B != null && B.getBodyTerm().equals(Literal.LTrue))
+ B = (PlanBody)B.getBodyNext();
+ Plan p = new Plan(L,T,(LogicalFormula)C, B);
p.setSrcLines(start,end);
p.setSrc(asSource);
{if (true) return p;}
@@ -435,27 +434,36 @@
}
/* Plan body */
- final public Object plan_body() throws ParseException {
- Object F; Object R = null;
+ final public PlanBody plan_body() throws ParseException {
+ Object F; PlanBody R = null;
F = body_formula();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 37:
jj_consume_token(37);
if (!(F instanceof PlanBody)) {if (true) throw new ParseException(getSourceRef(F)+" "+F+" is not a body literal!");}
R = plan_body();
- if (!(R instanceof PlanBody)) {if (true) throw new ParseException(getSourceRef(R)+" "+R+" is not a body literal!");}
break;
default:
jj_la1[17] = jj_gen;
;
}
- if (F instanceof PlanBody && R instanceof PlanBody) {
- ((PlanBody)F).setBodyNext( (PlanBody)R );
+ if (F instanceof PlanBody) {
+ ((PlanBody)F).setBodyNext( R );
}
- {if (true) return F;}
+ {if (true) return (PlanBody)F;}
throw new Error("Missing return statement in function");
}
+ final public PlanBody plan_body_term() throws ParseException {
+ PlanBody B = null;
+ jj_consume_token(27);
+ B = plan_body();
+ jj_consume_token(28);
+ B.setAsBodyTerm(true);
+ {if (true) return B;}
+ throw new Error("Missing return statement in function");
+ }
+
final public Object body_formula() throws ParseException {
BodyType formType = BodyType.action; Object B;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
@@ -642,6 +650,9 @@
case 42:
o = list();
break;
+ case 27:
+ o = plan_body_term();
+ break;
case VAR:
case TK_TRUE:
case TK_FALSE:
@@ -662,13 +673,6 @@
jj_consume_token(-1);
throw new ParseException();
}
- // if the result is a PlanBody action with size = 1, it is indeed a literal and not a body literal
- /*if (o instanceof PlanBody) {
- PlanBody bl = (PlanBody)o;
- if (bl.getBodyType() == BodyType.action && bl.getPlanSize() == 1) {
- o = bl.getBodyTerm();
- }
- }*/
{if (true) return changeToAtom(o);}
throw new Error("Missing return statement in function");
}
@@ -940,6 +944,9 @@
case 42:
op2 = list();
break;
+ case 27:
+ op2 = plan_body_term();
+ break;
default:
jj_la1[38] = jj_gen;
jj_consume_token(-1);
@@ -1187,8 +1194,8 @@
return false;
}
- final private boolean jj_3R_14() {
- if (jj_scan_token(42)) return true;
+ final private boolean jj_3R_13() {
+ if (jj_3R_14()) return true;
return false;
}
@@ -1197,6 +1204,11 @@
return false;
}
+ final private boolean jj_3R_14() {
+ if (jj_scan_token(42)) return true;
+ return false;
+ }
+
final private boolean jj_3R_11() {
Token xsp;
xsp = jj_scanpos;
@@ -1214,11 +1226,6 @@
return false;
}
- final private boolean jj_3R_13() {
- if (jj_3R_14()) return true;
- return false;
- }
-
public as2jTokenManager token_source;
SimpleCharStream jj_input_stream;
public Token token, jj_nt;
@@ -1236,7 +1243,7 @@
jj_la1_1();
}
private static void jj_la1_0() {
- jj_la1_0 = new int[] {0x8000000,0x10cb00,0x8000000,0x80000000,0x8000000,0x10000,0x10cb00,0x8000000,0x8000000,0x20000000,0x10000,0x0,0x0,0x0,0x80000000,0x80000000,0x30cb80,0x0,0x0,0x80000000,0x80000000,0x800,0x10cb00,0x10c000,0x0,0x0,0x0,0x3acf80,0x0,0x200080,0x0,0x3acb80,0x3acb80,0x0,0x0,0x3acf80,0x3acb80,0x0,0x3acb80,0x0,0x0,0x0,0x3000,0x3000,0x0,0x32cb80,0x200080,0x0,};
+ jj_la1_0 = new int[] {0x8000000,0x10cb00,0x8000000,0x80000000,0x8000000,0x10000,0x10cb00,0x8000000,0x8000000,0x20000000,0x10000,0x0,0x0,0x0,0x80000000,0x80000000,0x30cb80,0x0,0x0,0x80000000,0x80000000,0x800,0x10cb00,0x10c000,0x0,0x0,0x0,0x83acf80,0x0,0x200080,0x0,0x3acb80,0x3acb80,0x0,0x0,0x3acf80,0x3acb80,0x0,0x83acb80,0x0,0x0,0x0,0x3000,0x3000,0x0,0x32cb80,0x200080,0x0,};
}
private static void jj_la1_1() {
jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0xc,0x0,0x0,0x0,0x0,0x0,0x1,0x2,0xc,0x10,0x10,0x0,0x20,0x4,0x5c,0x5c,0x0,0x0,0x0,0x80,0x400,0x200,0x488,0x200,0x400,0x800,0x488,0x488,0x800,0x2000,0x88,0x88,0x3fc000,0x488,0x3fc000,0xc,0xc,0xc00000,0xc00000,0x1000000,0x88,0x0,0x400,};
Added: trunk/src/jason/stdlib/conditional.java
===================================================================
--- trunk/src/jason/stdlib/conditional.java (rev 0)
+++ trunk/src/jason/stdlib/conditional.java 2008-04-17 17:34:11 UTC (rev 1219)
@@ -0,0 +1,81 @@
+//----------------------------------------------------------------------------
+// Copyright (C) 2003 Rafael H. Bordini, Jomi F. Hubner, et al.
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// To contact the authors:
+// http://www.dur.ac.uk/r.bordini
+// http://www.inf.furb.br/~jomi
+//
+//----------------------------------------------------------------------------
+
+package jason.stdlib;
+
+import java.util.Iterator;
+
+import jason.JasonException;
+import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.IntendedMeans;
+import jason.asSemantics.TransitionSystem;
+import jason.asSemantics.Unifier;
+import jason.asSyntax.LogicalFormula;
+import jason.asSyntax.PlanBody;
+import jason.asSyntax.Term;
+
+// TODO: comments
+// TODO: find a way to change the name of the IA to .if
+public class conditional extends DefaultInternalAction {
+
+ @Override
+ public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
+ try {
+ if ( !(args[0] instanceof LogicalFormula))
+ throw new JasonException("The first argument of .if must be a logical formula.");
+
+ LogicalFormula logExpr = (LogicalFormula)args[0];
+ PlanBody whattoadd = null;
+
+ Iterator<Unifier> iu = logExpr.logicalConsequence(ts.getAg(), un);
+ if (iu.hasNext()) {
+ // THEN
+ un.compose(iu.next());
+ whattoadd = (PlanBody)args[1];
+ } else if (args.length == 3) {
+ // ELSE
+ whattoadd = (PlanBody)args[2];
+ }
+
+ if (whattoadd != null) {
+ if ( !whattoadd.isPlanBody())
+ throw new JasonException("The second and third arguments of .if must be a plan body term.");
+
+ IntendedMeans im = ts.getC().getSelectedIntention().peek();
+ PlanBody ifia = im.getCurrentStep();
+ whattoadd.setAsBodyTerm(false);
+ if (ifia.getPlanSize() == 1)
+ ifia.add(whattoadd);
+ else
+ ifia.add(1,whattoadd);
+ }
+ return true;
+ } catch (ArrayIndexOutOfBoundsException e) {
+ throw new JasonException("The internal action 'if' has not received the required arguments.");
+ } catch (JasonException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new JasonException("Error in internal action 'if': " + e, e);
+ }
+ }
+}
Modified: trunk/src/test/ASParserTest.java
===================================================================
--- trunk/src/test/ASParserTest.java 2008-04-16 16:46:46 UTC (rev 1218)
+++ trunk/src/test/ASParserTest.java 2008-04-17 17:34:11 UTC (rev 1219)
@@ -4,11 +4,12 @@
import jason.asSemantics.Agent;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
-import jason.asSyntax.PlanBody;
+import jason.asSyntax.Literal;
import jason.asSyntax.LogExpr;
import jason.asSyntax.LogicalFormula;
import jason.asSyntax.NumberTerm;
import jason.asSyntax.Plan;
+import jason.asSyntax.PlanBody;
import jason.asSyntax.RelExpr;
import jason.asSyntax.parser.as2j;
import jason.infra.centralised.CentralisedAgArch;
@@ -164,18 +165,18 @@
}
public void testParsingPlanBody() {
- // TODO: think about this
- /*
- Literal l = Literal.parseLiteral("p(a1;a2, a3, !g, ?b;.print(oi), 10)");
+ Literal l = Literal.parseLiteral("p( {a1(f);a2}, a3, {!g}, {?b;.print(oi) }, 10)");
+ assertEquals("p({ a1(f); a2 },a3,{ !g },{ ?b; .print(oi) },10)", l.toString());
assertEquals(5,l.getArity());
- assertTrue(l.getTerm(0) instanceof BodyLiteral);
+ assertTrue(l.getTerm(0) instanceof PlanBody);
assertTrue(l.getTerm(0).isPlanBody());
+ PlanBody pb = (PlanBody)l.getTerm(0);
+ assertTrue(pb.isBodyTerm());
assertFalse(l.getTerm(1).isPlanBody());
assertTrue(l.getTerm(2).isPlanBody());
assertTrue(l.getTerm(3).isPlanBody());
assertFalse(l.getTerm(4).isPlanBody());
- */
}
public void testParsingAllSources() {
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-04-17 21:52:47
|
Revision: 1220
http://jason.svn.sourceforge.net/jason/?rev=1220&view=rev
Author: jomifred
Date: 2008-04-17 14:52:42 -0700 (Thu, 17 Apr 2008)
Log Message:
-----------
allows singletons internal actions
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/asunit/print.java
trunk/applications/as-unit-test/src/jason/tests/TestIF.java
trunk/examples/domestic-robot/HouseEnv.java
trunk/src/jason/asSemantics/Agent.java
trunk/src/jason/asSyntax/PlanBodyImpl.java
trunk/src/jason/stdlib/add_annot.java
trunk/src/jason/stdlib/add_nested_source.java
trunk/src/jason/stdlib/atom.java
trunk/src/jason/stdlib/concat.java
trunk/src/jason/stdlib/conditional.java
trunk/src/jason/stdlib/date.java
trunk/src/jason/stdlib/delete.java
trunk/src/jason/stdlib/difference.java
trunk/src/jason/stdlib/fail.java
trunk/src/jason/stdlib/ground.java
trunk/src/jason/stdlib/intersection.java
trunk/src/jason/stdlib/length.java
trunk/src/jason/stdlib/list.java
trunk/src/jason/stdlib/literal.java
trunk/src/jason/stdlib/max.java
trunk/src/jason/stdlib/member.java
trunk/src/jason/stdlib/min.java
trunk/src/jason/stdlib/my_name.java
trunk/src/jason/stdlib/nth.java
trunk/src/jason/stdlib/number.java
trunk/src/jason/stdlib/plan_label.java
trunk/src/jason/stdlib/print.java
trunk/src/jason/stdlib/println.java
trunk/src/jason/stdlib/random.java
trunk/src/jason/stdlib/reverse.java
trunk/src/jason/stdlib/sort.java
trunk/src/jason/stdlib/string.java
trunk/src/jason/stdlib/structure.java
trunk/src/jason/stdlib/substring.java
trunk/src/jason/stdlib/time.java
trunk/src/jason/stdlib/union.java
Modified: trunk/applications/as-unit-test/src/jason/asunit/print.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/asunit/print.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/applications/as-unit-test/src/jason/asunit/print.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -1,5 +1,6 @@
package jason.asunit;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Term;
@@ -7,6 +8,10 @@
public class print extends println {
+ public static InternalAction create() {
+ return new print();
+ }
+
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
TestArch arch = (TestArch)ts.getUserAgArch().getArchInfraTier();
Modified: trunk/applications/as-unit-test/src/jason/tests/TestIF.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestIF.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/applications/as-unit-test/src/jason/tests/TestIF.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -18,7 +18,7 @@
ag.parseAScode(
"b(3). " +
"+!test1 <- a1; "+
- " .conditional(b(X), {jason.asunit.print(X); b1}, {jason.asunit.print(no);b2}); "+
+ " .if( b(X), {jason.asunit.print(X); b1}, {jason.asunit.print(no)}); "+
" a2. "+
"+!test2 <- -b(_); !test1. "
);
@@ -36,7 +36,6 @@
public void test2() {
ag.addGoal("test2");
ag.assertPrint("no", 5);
- ag.assertAct("b2", 5);
ag.assertAct("a2", 5);
}
}
Modified: trunk/examples/domestic-robot/HouseEnv.java
===================================================================
--- trunk/examples/domestic-robot/HouseEnv.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/examples/domestic-robot/HouseEnv.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -62,7 +62,7 @@
@Override
public boolean executeAction(String ag, Structure action) {
- logger.fine("Agent "+ag+" doing "+action+" in the environment");
+ System.out.println("["+ag+"] doing: "+action);
boolean result = false;
if (action.equals(of)) { // of = open(fridge)
result = model.openFridge();
Modified: trunk/src/jason/asSemantics/Agent.java
===================================================================
--- trunk/src/jason/asSemantics/Agent.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/asSemantics/Agent.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -44,6 +44,7 @@
import jason.functions.Count;
import jason.functions.RuleToFunction;
import jason.runtime.Settings;
+import jason.stdlib.conditional;
import java.io.File;
import java.io.FileInputStream;
@@ -238,14 +239,24 @@
parser.agent(this);
}
- public InternalAction getIA(Structure action) throws Exception {
+ @SuppressWarnings("unchecked")
+ public InternalAction getIA(Structure action) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
String iaName = action.getFunctor();
+ if (iaName.equals(".if"))
+ return conditional.create();
if (iaName.charAt(0) == '.')
iaName = "jason.stdlib" + iaName;
InternalAction objIA = internalActions.get(iaName);
if (objIA == null) {
- objIA = (InternalAction) Class.forName(iaName).newInstance();
- internalActions.put(iaName, objIA);
+ Class iaclass = Class.forName(iaName);
+ try {
+ // check if the class has "create" method -- singleton implementation
+ Method create = iaclass.getMethod("create", (Class[])null);
+ return (InternalAction)create.invoke(null, (Object[])null);
+ } catch (Exception e) {}
+
+ objIA = (InternalAction)iaclass.newInstance();
+ internalActions.put(iaName, objIA);
}
return objIA;
}
Modified: trunk/src/jason/asSyntax/PlanBodyImpl.java
===================================================================
--- trunk/src/jason/asSyntax/PlanBodyImpl.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/asSyntax/PlanBodyImpl.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -171,12 +171,11 @@
public boolean add(int index, PlanBody bl) {
if (index == 0) {
+ PlanBody newpb = new PlanBodyImpl(this.formType, this.term);
+ newpb.setBodyNext(next);
swap(bl);
- PlanBody bak = this.next;
this.next = bl.getBodyNext();
- PlanBody last = bl.getLastBody();
- bl.setBodyNext(bak);
- last.setBodyNext(bl);
+ this.getLastBody().setBodyNext(newpb);
} else if (next != null) {
next.add(index - 1, bl);
}
Modified: trunk/src/jason/stdlib/add_annot.java
===================================================================
--- trunk/src/jason/stdlib/add_annot.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/add_annot.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -26,6 +26,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
@@ -70,6 +71,13 @@
*/
public class add_annot extends DefaultInternalAction {
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new add_annot();
+ return singleton;
+ }
+
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
try {
Modified: trunk/src/jason/stdlib/add_nested_source.java
===================================================================
--- trunk/src/jason/stdlib/add_nested_source.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/add_nested_source.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -26,6 +26,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
@@ -71,7 +72,14 @@
*/
public class add_nested_source extends DefaultInternalAction {
- @Override
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new add_nested_source();
+ return singleton;
+ }
+
+ @Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
try {
Term result = addAnnotToList(un, args[0], (Structure)args[1].clone());
Modified: trunk/src/jason/stdlib/atom.java
===================================================================
--- trunk/src/jason/stdlib/atom.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/atom.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -2,6 +2,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Term;
@@ -40,7 +41,14 @@
*/
public class atom extends DefaultInternalAction {
- @Override
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new atom();
+ return singleton;
+ }
+
+ @Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
try {
return args[0].isAtom();
Modified: trunk/src/jason/stdlib/concat.java
===================================================================
--- trunk/src/jason/stdlib/concat.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/concat.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -25,6 +25,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
@@ -69,6 +70,13 @@
*/
public class concat extends DefaultInternalAction {
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new concat();
+ return singleton;
+ }
+
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
Modified: trunk/src/jason/stdlib/conditional.java
===================================================================
--- trunk/src/jason/stdlib/conditional.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/conditional.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -28,6 +28,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
import jason.asSemantics.IntendedMeans;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.LogicalFormula;
@@ -35,9 +36,15 @@
import jason.asSyntax.Term;
// TODO: comments
-// TODO: find a way to change the name of the IA to .if
public class conditional extends DefaultInternalAction {
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new conditional();
+ return singleton;
+ }
+
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
try {
@@ -48,19 +55,18 @@
PlanBody whattoadd = null;
Iterator<Unifier> iu = logExpr.logicalConsequence(ts.getAg(), un);
- if (iu.hasNext()) {
- // THEN
+ if (iu.hasNext()) { // .if THEN
+ if ( !args[1].isPlanBody())
+ throw new JasonException("The second argument of .if must be a plan body term.");
+ whattoadd = (PlanBody)args[1];
un.compose(iu.next());
- whattoadd = (PlanBody)args[1];
- } else if (args.length == 3) {
- // ELSE
+ } else if (args.length == 3) { // .if ELSE
+ if ( !args[2].isPlanBody())
+ throw new JasonException("The third argument of .if must be a plan body term.");
whattoadd = (PlanBody)args[2];
}
if (whattoadd != null) {
- if ( !whattoadd.isPlanBody())
- throw new JasonException("The second and third arguments of .if must be a plan body term.");
-
IntendedMeans im = ts.getC().getSelectedIntention().peek();
PlanBody ifia = im.getCurrentStep();
whattoadd.setAsBodyTerm(false);
Modified: trunk/src/jason/stdlib/date.java
===================================================================
--- trunk/src/jason/stdlib/date.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/date.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -2,6 +2,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.NumberTermImpl;
@@ -38,7 +39,14 @@
*/
public class date extends DefaultInternalAction {
- /** date(YY,MM,DD) */
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new date();
+ return singleton;
+ }
+
+ /** date(YY,MM,DD) */
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
try {
Modified: trunk/src/jason/stdlib/delete.java
===================================================================
--- trunk/src/jason/stdlib/delete.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/delete.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -25,6 +25,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
@@ -71,6 +72,13 @@
*/
public class delete extends DefaultInternalAction {
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new delete();
+ return singleton;
+ }
+
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
try {
Modified: trunk/src/jason/stdlib/difference.java
===================================================================
--- trunk/src/jason/stdlib/difference.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/difference.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -25,6 +25,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
@@ -63,6 +64,13 @@
*/
public class difference extends DefaultInternalAction {
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new difference();
+ return singleton;
+ }
+
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
Modified: trunk/src/jason/stdlib/fail.java
===================================================================
--- trunk/src/jason/stdlib/fail.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/fail.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -24,6 +24,7 @@
package jason.stdlib;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Term;
@@ -44,7 +45,14 @@
*/
public class fail extends DefaultInternalAction {
- @Override
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new fail();
+ return singleton;
+ }
+
+ @Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
return false;
}
Modified: trunk/src/jason/stdlib/ground.java
===================================================================
--- trunk/src/jason/stdlib/ground.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/ground.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -2,6 +2,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Term;
@@ -35,6 +36,13 @@
*/
public class ground extends DefaultInternalAction {
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new ground();
+ return singleton;
+ }
+
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
try {
Modified: trunk/src/jason/stdlib/intersection.java
===================================================================
--- trunk/src/jason/stdlib/intersection.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/intersection.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -25,6 +25,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
@@ -63,6 +64,13 @@
*/
public class intersection extends DefaultInternalAction {
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new intersection();
+ return singleton;
+ }
+
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
Modified: trunk/src/jason/stdlib/length.java
===================================================================
--- trunk/src/jason/stdlib/length.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/length.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -24,6 +24,7 @@
package jason.stdlib;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
@@ -68,6 +69,13 @@
*/
public class length extends DefaultInternalAction {
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new length();
+ return singleton;
+ }
+
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
Term l1 = args[0];
Modified: trunk/src/jason/stdlib/list.java
===================================================================
--- trunk/src/jason/stdlib/list.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/list.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -2,6 +2,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Term;
@@ -35,6 +36,13 @@
*/
public class list extends DefaultInternalAction {
+
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new list();
+ return singleton;
+ }
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
Modified: trunk/src/jason/stdlib/literal.java
===================================================================
--- trunk/src/jason/stdlib/literal.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/literal.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -2,6 +2,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Term;
@@ -35,6 +36,13 @@
@see jason.stdlib.ground
*/
public class literal extends DefaultInternalAction {
+
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new literal();
+ return singleton;
+ }
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
Modified: trunk/src/jason/stdlib/max.java
===================================================================
--- trunk/src/jason/stdlib/max.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/max.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -1,5 +1,6 @@
package jason.stdlib;
+import jason.asSemantics.InternalAction;
import jason.asSyntax.Term;
/**
@@ -52,6 +53,13 @@
*/
public class max extends min {
+
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new max();
+ return singleton;
+ }
@Override
protected boolean compare(Term a, Term t) {
Modified: trunk/src/jason/stdlib/member.java
===================================================================
--- trunk/src/jason/stdlib/member.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/member.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -2,6 +2,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
@@ -46,6 +47,13 @@
*/
public class member extends DefaultInternalAction {
+
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new member();
+ return singleton;
+ }
@Override
public Object execute(TransitionSystem ts, final Unifier un, Term[] args) throws Exception {
Modified: trunk/src/jason/stdlib/min.java
===================================================================
--- trunk/src/jason/stdlib/min.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/min.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -2,6 +2,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
@@ -59,6 +60,13 @@
*/
public class min extends DefaultInternalAction {
+
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new min();
+ return singleton;
+ }
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
Modified: trunk/src/jason/stdlib/my_name.java
===================================================================
--- trunk/src/jason/stdlib/my_name.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/my_name.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -25,6 +25,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Atom;
@@ -57,6 +58,13 @@
*/
public class my_name extends DefaultInternalAction {
+
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new my_name();
+ return singleton;
+ }
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
Modified: trunk/src/jason/stdlib/nth.java
===================================================================
--- trunk/src/jason/stdlib/nth.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/nth.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -39,6 +39,13 @@
*/
public class nth extends DefaultInternalAction {
+
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new nth();
+ return singleton;
+ }
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
Modified: trunk/src/jason/stdlib/number.java
===================================================================
--- trunk/src/jason/stdlib/number.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/number.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -2,6 +2,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Term;
@@ -32,6 +33,13 @@
*/
public class number extends DefaultInternalAction {
+
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new number();
+ return singleton;
+ }
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
Modified: trunk/src/jason/stdlib/plan_label.java
===================================================================
--- trunk/src/jason/stdlib/plan_label.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/plan_label.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -25,6 +25,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Plan;
@@ -58,6 +59,13 @@
*/
public class plan_label extends DefaultInternalAction {
+
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new plan_label();
+ return singleton;
+ }
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
Modified: trunk/src/jason/stdlib/print.java
===================================================================
--- trunk/src/jason/stdlib/print.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/print.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -58,6 +58,13 @@
*/
public class print extends println implements InternalAction {
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new println();
+ return singleton;
+ }
+
@Override
protected String getNewLine() {
return "";
Modified: trunk/src/jason/stdlib/println.java
===================================================================
--- trunk/src/jason/stdlib/println.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/println.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -23,6 +23,7 @@
package jason.stdlib;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.StringTerm;
@@ -43,6 +44,13 @@
*/
public class println extends DefaultInternalAction {
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new println();
+ return singleton;
+ }
+
protected String getNewLine() {
return "\n";
}
Modified: trunk/src/jason/stdlib/random.java
===================================================================
--- trunk/src/jason/stdlib/random.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/random.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -2,6 +2,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.NumberTermImpl;
@@ -28,6 +29,13 @@
*/
public class random extends DefaultInternalAction {
+
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new random();
+ return singleton;
+ }
private Random random = new Random();
Modified: trunk/src/jason/stdlib/reverse.java
===================================================================
--- trunk/src/jason/stdlib/reverse.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/reverse.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -25,6 +25,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
@@ -64,6 +65,13 @@
*/
public class reverse extends DefaultInternalAction {
+
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new reverse();
+ return singleton;
+ }
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
Modified: trunk/src/jason/stdlib/sort.java
===================================================================
--- trunk/src/jason/stdlib/sort.java 2008-04-17 17:34:11 UTC (rev 1219)
+++ trunk/src/jason/stdlib/sort.java 2008-04-17 21:52:42 UTC (rev 1220)
@@ -26,6 +26,7 @@
import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
@@ -81,6 +82,13 @@
*/
public class sort extends DefaultInternalAction {
+
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new sort();
+ return singleton;
+ }
@Override
public Object execute(TransitionSystem ts, Uni...
[truncated message content] |