|
From: <jom...@us...> - 2009-02-16 09:17:13
|
Revision: 1446
http://jason.svn.sourceforge.net/jason/?rev=1446&view=rev
Author: jomifred
Date: 2009-02-16 09:17:07 +0000 (Mon, 16 Feb 2009)
Log Message:
-----------
update release-notes.txt with latest changes
Modified Paths:
--------------
trunk/release-notes.txt
trunk/src/jason/asSyntax/Atom.java
trunk/src/jason/asSyntax/Literal.java
trunk/src/jason/asSyntax/Rule.java
trunk/src/jason/asSyntax/StringTerm.java
Modified: trunk/release-notes.txt
===================================================================
--- trunk/release-notes.txt 2009-02-15 11:13:20 UTC (rev 1445)
+++ trunk/release-notes.txt 2009-02-16 09:17:07 UTC (rev 1446)
@@ -2,9 +2,21 @@
version 1.2.1
---------------------------
+Changes in communication
+- for messages sent to itself, the sender is 'self' now,
+ and not the agent's name as in previous releases
+
+Changes in internal actions
+- .relevant_plans has a third argument that gets the labels
+ of the plans
+- .create_agent accepts strings for the name of the agents
+
+
Bugs fixed
- arithmetic expressions are considered as Literal, causing
- failures in unification
+ failures in unification
+- variable unified with atom cannot be added in BB, as in
+ X = p; +X;
---------------------------
Modified: trunk/src/jason/asSyntax/Atom.java
===================================================================
--- trunk/src/jason/asSyntax/Atom.java 2009-02-15 11:13:20 UTC (rev 1445)
+++ trunk/src/jason/asSyntax/Atom.java 2009-02-16 09:17:07 UTC (rev 1446)
@@ -30,7 +30,7 @@
import org.w3c.dom.Element;
/**
- * Represents an atom (a positive literal with no arguments and no annotations, e.g. "tell", "a").
+ * Represents an atom (a positive literal with no argument and no annotation, e.g. "tell", "a").
*/
public class Atom extends Literal {
Modified: trunk/src/jason/asSyntax/Literal.java
===================================================================
--- trunk/src/jason/asSyntax/Literal.java 2009-02-15 11:13:20 UTC (rev 1445)
+++ trunk/src/jason/asSyntax/Literal.java 2009-02-16 09:17:07 UTC (rev 1446)
@@ -120,13 +120,13 @@
/** returns all singleton vars (that appears once) in this literal */
public List<VarTerm> getSingletonVars() { return new ArrayList<VarTerm>(); }
- /** Replaces all terms by unnamed variables (_). */
+ /** replaces all terms by unnamed variables (_). */
public void makeTermsAnnon() {}
- /** Replaces all variables by unnamed variables (_). */
+ /** replaces all variables by unnamed variables (_). */
public void makeVarsAnnon() {}
/**
- * Replaces all variables of the term for unnamed variables (_).
+ * replaces all variables of the term for unnamed variables (_).
*
* @param un is the unifier that contains the map of replacements
*/
@@ -192,35 +192,34 @@
/* Not implemented methods */
// structure
- public void addTerm(Term t) { logger.log(Level.SEVERE, "addTerm is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); }
- public void delTerm(int index) { logger.log(Level.SEVERE, "delTerm is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); }
+ public void addTerm(Term t) { logger.log(Level.SEVERE, "addTerm is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); }
+ public void delTerm(int index) { logger.log(Level.SEVERE, "delTerm is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); }
/** adds some terms and return this */
- public Literal addTerms(Term ... ts ) { logger.log(Level.SEVERE, "addTerms is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
+ public Literal addTerms(Term ... ts ) { logger.log(Level.SEVERE, "addTerms is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
/** adds some terms and return this */
- public Literal addTerms(List<Term> l) { logger.log(Level.SEVERE, "addTerms is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
+ public Literal addTerms(List<Term> l) { logger.log(Level.SEVERE, "addTerms is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
/** returns the i-th term (first term is 0) */
- public Term getTerm(int i) { logger.log(Level.SEVERE, "getTerm(i) is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
+ public Term getTerm(int i) { logger.log(Level.SEVERE, "getTerm(i) is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
/** set all terms of the literal and return this */
- public Literal setTerms(List<Term> l) { logger.log(Level.SEVERE, "setTerms is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
- public void setTerm(int i, Term t) { logger.log(Level.SEVERE, "setTerm is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); }
+ public Literal setTerms(List<Term> l) { logger.log(Level.SEVERE, "setTerms is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
+ public void setTerm(int i, Term t) { logger.log(Level.SEVERE, "setTerm is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); }
// pred
- public void setAnnots(ListTerm l) { logger.log(Level.SEVERE, "setAnnots is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); }
- public boolean addAnnot(Term t) { logger.log(Level.SEVERE, "addAnnot is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return false; }
+ public void setAnnots(ListTerm l) { logger.log(Level.SEVERE, "setAnnots is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); }
+ public boolean addAnnot(Term t) { logger.log(Level.SEVERE, "addAnnot is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return false; }
/** adds some annots and return this */
public Literal addAnnots(Term ... terms) { logger.log(Level.SEVERE, "addAnnots is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
/** adds some annots and return this */
- public Literal addAnnots(List<Term> l) { logger.log(Level.SEVERE, "addAnnots is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
- //public void addAnnot(int index, Term t) { logger.log(Level.SEVERE, "addAnnot is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); }
- public void delAnnot(Term t) { logger.log(Level.SEVERE, "delAnnot is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); }
+ public Literal addAnnots(List<Term> l) { logger.log(Level.SEVERE, "addAnnots is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
+ public void delAnnot(Term t) { logger.log(Level.SEVERE, "delAnnot is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); }
/**
* removes all annots in this pred that are in the list <i>l</i>.
* @return true if some annot was removed.
*/
- public boolean delAnnots(List<Term> l) { logger.log(Level.SEVERE, "delAnnots is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return false; }
+ public boolean delAnnots(List<Term> l) { logger.log(Level.SEVERE, "delAnnots is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return false; }
/**
* "import" annots from another predicate <i>p</i>. p will be changed
@@ -233,18 +232,18 @@
*
* @return true if some annot was imported.
*/
- public boolean importAnnots(Literal p) { logger.log(Level.SEVERE, "importAnnots is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return false; }
+ public boolean importAnnots(Literal p) { logger.log(Level.SEVERE, "importAnnots is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return false; }
/** adds the annotation source(<i>agName</i>) */
- public void addSource(Term agName) { logger.log(Level.SEVERE, "addSource is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); }
+ public void addSource(Term agName) { logger.log(Level.SEVERE, "addSource is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); }
/** deletes one source(<i>agName</i>) annotation, return true if deleted */
- public boolean delSource(Term agName) { logger.log(Level.SEVERE, "delSource is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return false; }
+ public boolean delSource(Term agName) { logger.log(Level.SEVERE, "delSource is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return false; }
/** deletes all source annotations */
- public void delSources() { logger.log(Level.SEVERE, "delSources is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); }
+ public void delSources() { logger.log(Level.SEVERE, "delSources is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); }
// literal
/** changes the negation of the literal and return this */
- public Literal setNegated(boolean b) { logger.log(Level.SEVERE, "setNegated is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
+ public Literal setNegated(boolean b) { logger.log(Level.SEVERE, "setNegated is not implemented in the class "+this.getClass().getSimpleName(), new Exception()); return null; }
/**
Modified: trunk/src/jason/asSyntax/Rule.java
===================================================================
--- trunk/src/jason/asSyntax/Rule.java 2009-02-15 11:13:20 UTC (rev 1445)
+++ trunk/src/jason/asSyntax/Rule.java 2009-02-16 09:17:07 UTC (rev 1446)
@@ -31,7 +31,7 @@
import org.w3c.dom.Element;
/**
- A rule is a Literal (head) with an optional body, as in "a :- b & c".
+ A rule is a Literal (head) with a body, as in "a :- b & c".
@navassoc - body - LogicalFormula
*/
Modified: trunk/src/jason/asSyntax/StringTerm.java
===================================================================
--- trunk/src/jason/asSyntax/StringTerm.java 2009-02-15 11:13:20 UTC (rev 1445)
+++ trunk/src/jason/asSyntax/StringTerm.java 2009-02-16 09:17:07 UTC (rev 1446)
@@ -5,6 +5,9 @@
* @opt nodefillcolor lightgoldenrodyellow
*/
public interface StringTerm extends Term {
+ /** gets the Java string represented by this term, it
+ normally does not return the same string as toString
+ (which enclose the string by quotes) */
public String getString();
public int length();
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-02-18 14:31:03
|
Revision: 1448
http://jason.svn.sourceforge.net/jason/?rev=1448&view=rev
Author: jomifred
Date: 2009-02-18 14:30:59 +0000 (Wed, 18 Feb 2009)
Log Message:
-----------
method forceFullLiteralImpl is applied only for atoms (not for
expressions, for instance)
Modified Paths:
--------------
trunk/applications/jason-team/src/java/agent/OrgMaintenanceGoal.java
trunk/applications/jason-team/src/java/arch/CowboyArch.java
trunk/applications/jason-team/src/java/test/MindView.java
trunk/demos/gui/gui2/sample.asl
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/asSyntax/Literal.java
trunk/src/jason/asSyntax/Plan.java
trunk/src/jason/asSyntax/PlanBodyImpl.java
trunk/src/jason/asSyntax/PlanLibrary.java
trunk/src/jason/asSyntax/patterns/goal/BC.java
trunk/src/jason/asSyntax/patterns/goal/BDG.java
trunk/src/jason/asSyntax/patterns/goal/DG.java
trunk/src/jason/asSyntax/patterns/goal/EBDG.java
trunk/src/jason/asSyntax/patterns/goal/MG.java
trunk/src/jason/asSyntax/patterns/goal/OMC.java
trunk/src/jason/asSyntax/patterns/goal/RC.java
trunk/src/jason/asSyntax/patterns/goal/SGA.java
trunk/src/jason/asSyntax/patterns/goal/SMC.java
trunk/src/jason/control/ExecutionControlGUI.java
trunk/src/jason/stdlib/add_annot.java
trunk/src/jason/stdlib/add_plan.java
trunk/src/test/StdLibTest.java
trunk/src/test/TSTest.java
trunk/src/test/VarTermTest.java
Modified: trunk/applications/jason-team/src/java/agent/OrgMaintenanceGoal.java
===================================================================
--- trunk/applications/jason-team/src/java/agent/OrgMaintenanceGoal.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/applications/jason-team/src/java/agent/OrgMaintenanceGoal.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -1,6 +1,7 @@
package agent;
import jason.asSemantics.Agent;
+import jason.asSyntax.ASSyntax;
import jason.asSyntax.InternalActionLiteral;
import jason.asSyntax.Literal;
import jason.asSyntax.Plan;
@@ -51,7 +52,7 @@
String sp = "-!"+goal+" <- .current_intention(I); " +
".print(\"ooo Failure in organisational goal "+goal+"\", I); "+
endofplan + ".";
- Plan p = Plan.parse(sp);
+ Plan p = ASSyntax.parsePlan(sp);
newAg.getPL().add(p);
return newAg;
Modified: trunk/applications/jason-team/src/java/arch/CowboyArch.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/CowboyArch.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/applications/jason-team/src/java/arch/CowboyArch.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -298,7 +298,6 @@
}
}
- @SuppressWarnings("unchecked")
@Override
public void checkMail() {
super.checkMail();
Modified: trunk/applications/jason-team/src/java/test/MindView.java
===================================================================
--- trunk/applications/jason-team/src/java/test/MindView.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/applications/jason-team/src/java/test/MindView.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -159,7 +159,6 @@
}
}
- @SuppressWarnings("unchecked")
private void setupSlider() {
int first = -1;
int size = 0;
Modified: trunk/demos/gui/gui2/sample.asl
===================================================================
--- trunk/demos/gui/gui2/sample.asl 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/demos/gui/gui2/sample.asl 2009-02-18 14:30:59 UTC (rev 1448)
@@ -1,4 +1,3 @@
-
/* Initial goals */
!start.
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -626,8 +626,8 @@
// manage the case of var unified with atom
if (body instanceof VarTerm) {
Term v = ((VarTerm)body).getValue();
- if (v != null && v instanceof Literal)
- body = ((Literal)v).forceLiteralImplClass();
+ if (v != null && v.isAtom())
+ body = ((Atom)v).forceFullLiteralImpl();
}
if (!body.hasSource()) {
// do not add source(self) in case the
Modified: trunk/src/jason/asSyntax/Literal.java
===================================================================
--- trunk/src/jason/asSyntax/Literal.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/asSyntax/Literal.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -379,17 +379,18 @@
}
}
- /**
- * Returns 'this' if this class is LiteralImpl, otherwise, create a new instance of LiteralImpl based on 'this'.
- * This method is useful to translate Atoms to LiteralImpl.
- */
- public Literal forceLiteralImplClass() {
- if (this instanceof LiteralImpl)
+ /**
+ * Transforms this into a full literal (which implements all methods of Literal), if it is an Atom;
+ * otherwise returns 'this'
+ */
+ public Literal forceFullLiteralImpl() {
+ if (this.isAtom() && !(this instanceof LiteralImpl))
+ return new LiteralImpl(this);
+ else
return this;
- else // it is Atom, Structure, Pred but not LiteralImpl
- return new LiteralImpl(this);
- }
+ }
+
@SuppressWarnings("serial")
static final class TrueLiteral extends LiteralImpl {
public TrueLiteral() {
Modified: trunk/src/jason/asSyntax/Plan.java
===================================================================
--- trunk/src/jason/asSyntax/Plan.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/asSyntax/Plan.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -107,6 +107,7 @@
context = null;
}
+ /** prefer using ASSyntax.parsePlan */
public static Plan parse(String sPlan) {
as2j parser = new as2j(new StringReader(sPlan));
try {
Modified: trunk/src/jason/asSyntax/PlanBodyImpl.java
===================================================================
--- trunk/src/jason/asSyntax/PlanBodyImpl.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/asSyntax/PlanBodyImpl.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -41,8 +41,8 @@
formType = t;
if (b != null) {
srcInfo = b.getSrcInfo();
- if (b instanceof Literal) {
- b = ((Literal)b).forceLiteralImplClass();
+ if (b.isAtom()) {
+ b = ((Atom)b).forceFullLiteralImpl();
}
}
term = b;
Modified: trunk/src/jason/asSyntax/PlanLibrary.java
===================================================================
--- trunk/src/jason/asSyntax/PlanLibrary.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/asSyntax/PlanLibrary.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -28,6 +28,7 @@
import jason.JasonException;
import jason.asSyntax.Trigger.TEOperator;
import jason.asSyntax.Trigger.TEType;
+import jason.asSyntax.parser.ParseException;
import jason.bb.BeliefBase;
import java.util.ArrayList;
@@ -35,8 +36,6 @@
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import java.util.logging.Level;
-import java.util.logging.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -63,7 +62,7 @@
private static int lastPlanLabel = 0;
- private Logger logger = Logger.getLogger(PlanLibrary.class.getName());
+ //private Logger logger = Logger.getLogger(PlanLibrary.class.getName());
/**
* Add a new plan written as a String. The source
@@ -73,9 +72,9 @@
*
* The plan is added in the end of the PlanLibrary.
*
- * returns the plan added, null if it does not work.
+ * @returns the plan just added
*/
- public Plan add(StringTerm stPlan, Term tSource) {
+ public Plan add(StringTerm stPlan, Term tSource) throws ParseException, JasonException {
return add(stPlan, tSource, false);
}
@@ -89,39 +88,32 @@
* begin of the PlanLibrary; otherwise, it is added in
* the end.
*
- * returns the plan added, null if it does not work.
+ * @returns the plan just added
*/
- public Plan add(StringTerm stPlan, Term tSource, boolean before) {
+ public Plan add(StringTerm stPlan, Term tSource, boolean before) throws ParseException, JasonException {
String sPlan = stPlan.getString();
- try {
- // remove quotes \" -> "
- StringBuilder sTemp = new StringBuilder();
- for (int c=0; c <sPlan.length(); c++) {
- if (sPlan.charAt(c) != '\\') {
- sTemp.append(sPlan.charAt(c));
- }
+ // remove quotes \" -> "
+ StringBuilder sTemp = new StringBuilder();
+ for (int c=0; c <sPlan.length(); c++) {
+ if (sPlan.charAt(c) != '\\') {
+ sTemp.append(sPlan.charAt(c));
}
- sPlan = sTemp.toString();
- Plan p = Plan.parse(sPlan);
- if (p != null) {
- int i = plans.indexOf(p);
- if (i < 0) {
- // add label, if necessary
- if (p.getLabel() == null) {
- p.setLabel(getUniqueLabel());
- }
- p.getLabel().addSource(tSource);
- add(p, before);
- } else {
- p = plans.get(i);
- p.getLabel().addSource(tSource);
- }
- return p;
+ }
+ sPlan = sTemp.toString();
+ Plan p = ASSyntax.parsePlan(sPlan); //Plan.parse(sPlan);
+ int i = plans.indexOf(p);
+ if (i < 0) {
+ // add label, if necessary
+ if (p.getLabel() == null) {
+ p.setLabel(getUniqueLabel());
}
- } catch (Exception e) {
- logger.log(Level.SEVERE,"Error adding plan "+stPlan,e);
+ p.getLabel().addSource(tSource);
+ add(p, before);
+ } else {
+ p = plans.get(i);
+ p.getLabel().addSource(tSource);
}
- return null;
+ return p;
}
Modified: trunk/src/jason/asSyntax/patterns/goal/BC.java
===================================================================
--- trunk/src/jason/asSyntax/patterns/goal/BC.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/asSyntax/patterns/goal/BC.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -1,7 +1,7 @@
package jason.asSyntax.patterns.goal;
import jason.asSemantics.Agent;
-import jason.asSyntax.Plan;
+import jason.asSyntax.ASSyntax;
import jason.asSyntax.Pred;
import jason.asSyntax.Term;
import jason.asSyntax.directives.Directive;
@@ -35,7 +35,7 @@
if (newAg != null) {
// add +!g : true <- !!g.
- newAg.getPL().add(Plan.parse("+!"+goal+" <- !!"+goal+"."));
+ newAg.getPL().add(ASSyntax.parsePlan("+!"+goal+" <- !!"+goal+"."));
return newAg;
}
Modified: trunk/src/jason/asSyntax/patterns/goal/BDG.java
===================================================================
--- trunk/src/jason/asSyntax/patterns/goal/BDG.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/asSyntax/patterns/goal/BDG.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -1,7 +1,7 @@
package jason.asSyntax.patterns.goal;
import jason.asSemantics.Agent;
-import jason.asSyntax.Plan;
+import jason.asSyntax.ASSyntax;
import jason.asSyntax.Pred;
import jason.asSyntax.Term;
@@ -26,7 +26,7 @@
Term goal = directive.getTerm(0);
// add -!g : true <- !!g.
- newAg.getPL().add(Plan.parse("-!"+goal+" <- !!"+goal+"."));
+ newAg.getPL().add(ASSyntax.parsePlan("-!"+goal+" <- !!"+goal+"."));
return newAg;
}
Modified: trunk/src/jason/asSyntax/patterns/goal/DG.java
===================================================================
--- trunk/src/jason/asSyntax/patterns/goal/DG.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/asSyntax/patterns/goal/DG.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -1,6 +1,7 @@
package jason.asSyntax.patterns.goal;
import jason.asSemantics.Agent;
+import jason.asSyntax.ASSyntax;
import jason.asSyntax.PlanBody;
import jason.asSyntax.PlanBodyImpl;
import jason.asSyntax.Literal;
@@ -28,7 +29,7 @@
Literal goal = Literal.parseLiteral(directive.getTerm(0).toString());
// add +!g : g <- true.
- newAg.getPL().add(Plan.parse("+!"+goal+" : " +goal+"."));
+ newAg.getPL().add(ASSyntax.parsePlan("+!"+goal+" : " +goal+"."));
// add ?g in the end of all inner plans
for (Plan p: innerContent.getPL()) {
@@ -38,7 +39,7 @@
}
// add +g : true <- .succeed_goal(g).
- newAg.getPL().add(Plan.parse("+"+goal+" <- .succeed_goal("+goal+")."));
+ newAg.getPL().add(ASSyntax.parsePlan("+"+goal+" <- .succeed_goal("+goal+")."));
return newAg;
} catch (Exception e) {
Modified: trunk/src/jason/asSyntax/patterns/goal/EBDG.java
===================================================================
--- trunk/src/jason/asSyntax/patterns/goal/EBDG.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/asSyntax/patterns/goal/EBDG.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -1,6 +1,7 @@
package jason.asSyntax.patterns.goal;
import jason.asSemantics.Agent;
+import jason.asSyntax.ASSyntax;
import jason.asSyntax.Literal;
import jason.asSyntax.LiteralImpl;
import jason.asSyntax.LogExpr;
@@ -33,7 +34,7 @@
Literal goal = Literal.parseLiteral(directive.getTerm(0).toString());
// add +!g : g <- true.
- newAg.getPL().add(Plan.parse("+!"+goal+" : " +goal+"."));
+ newAg.getPL().add(ASSyntax.parsePlan("+!"+goal+" : " +goal+"."));
// change all inner plans
int i = 0;
@@ -64,13 +65,13 @@
// add -!g : true <- !!g.
- newAg.getPL().add(Plan.parse("-!"+goal+" <- !!"+goal+"."));
+ newAg.getPL().add(ASSyntax.parsePlan("-!"+goal+" <- !!"+goal+"."));
// add +g : true <- .abolish(p__f(_,g)); .succeed_goal(g).
- newAg.getPL().add(Plan.parse("+"+goal+" <- .abolish(p__f(_,"+goal+")); .succeed_goal("+goal+")."));
+ newAg.getPL().add(ASSyntax.parsePlan("+"+goal+" <- .abolish(p__f(_,"+goal+")); .succeed_goal("+goal+")."));
// add -g <- .abolish(p__f(_,g)).
- newAg.getPL().add(Plan.parse("-"+goal+" <- .abolish(p__f(_,"+goal+"))."));
+ newAg.getPL().add(ASSyntax.parsePlan("-"+goal+" <- .abolish(p__f(_,"+goal+"))."));
return newAg;
} catch (Exception e) {
Modified: trunk/src/jason/asSyntax/patterns/goal/MG.java
===================================================================
--- trunk/src/jason/asSyntax/patterns/goal/MG.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/asSyntax/patterns/goal/MG.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -1,12 +1,12 @@
package jason.asSyntax.patterns.goal;
import jason.asSemantics.Agent;
-import jason.bb.BeliefBase;
+import jason.asSyntax.ASSyntax;
import jason.asSyntax.Literal;
-import jason.asSyntax.Plan;
import jason.asSyntax.Pred;
import jason.asSyntax.directives.Directive;
import jason.asSyntax.directives.DirectiveProcessor;
+import jason.bb.BeliefBase;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -40,7 +40,7 @@
newAg.addInitialBel(goal);
// add -g : true <- !g.
- newAg.getPL().add(Plan.parse("-"+goal+" <- !"+goal+"."));
+ newAg.getPL().add(ASSyntax.parsePlan("-"+goal+" <- !"+goal+"."));
return newAg;
}
Modified: trunk/src/jason/asSyntax/patterns/goal/OMC.java
===================================================================
--- trunk/src/jason/asSyntax/patterns/goal/OMC.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/asSyntax/patterns/goal/OMC.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -1,6 +1,7 @@
package jason.asSyntax.patterns.goal;
import jason.asSemantics.Agent;
+import jason.asSyntax.ASSyntax;
import jason.asSyntax.Plan;
import jason.asSyntax.Pred;
import jason.asSyntax.SourceInfo;
@@ -32,12 +33,12 @@
Agent newAg = sd.process(subDir, outerContent, innerContent);
if (newAg != null) {
// add +f : true <- .fail_goal(g).
- Plan pf = Plan.parse("+"+fail+" <- .fail_goal("+goal+").");
+ Plan pf = ASSyntax.parsePlan("+"+fail+" <- .fail_goal("+goal+").");
pf.setSrcInfo(new SourceInfo(outerContent+"/"+directive, 0));
newAg.getPL().add(pf);
// add -m : true <- .succeed_goal(g).
- Plan pm = Plan.parse("-"+motivation+" <- .succeed_goal("+goal+").");
+ Plan pm = ASSyntax.parsePlan("-"+motivation+" <- .succeed_goal("+goal+").");
pm.setSrcInfo(new SourceInfo(outerContent+"/"+directive, 0));
newAg.getPL().add(pm);
Modified: trunk/src/jason/asSyntax/patterns/goal/RC.java
===================================================================
--- trunk/src/jason/asSyntax/patterns/goal/RC.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/asSyntax/patterns/goal/RC.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -1,7 +1,7 @@
package jason.asSyntax.patterns.goal;
import jason.asSemantics.Agent;
-import jason.asSyntax.Plan;
+import jason.asSyntax.ASSyntax;
import jason.asSyntax.Pred;
import jason.asSyntax.Term;
import jason.asSyntax.directives.Directive;
@@ -32,7 +32,7 @@
if (newAg != null) {
// add -m : true <- .succeed_goal(g).
- newAg.getPL().add(Plan.parse("-"+motivation+" <- .succeed_goal("+goal+")."));
+ newAg.getPL().add(ASSyntax.parsePlan("-"+motivation+" <- .succeed_goal("+goal+")."));
return newAg;
}
Modified: trunk/src/jason/asSyntax/patterns/goal/SGA.java
===================================================================
--- trunk/src/jason/asSyntax/patterns/goal/SGA.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/asSyntax/patterns/goal/SGA.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -4,7 +4,6 @@
import jason.asSyntax.ASSyntax;
import jason.asSyntax.LogExpr;
import jason.asSyntax.LogicalFormula;
-import jason.asSyntax.Plan;
import jason.asSyntax.Pred;
import jason.asSyntax.StringTerm;
import jason.asSyntax.Term;
@@ -32,19 +31,19 @@
Agent newAg = new Agent();
// add t : not f__l(_) & c <- !f__g(g).
- newAg.getPL().add(Plan.parse(trigger+" : not f__l(_) & " +context +" <- !f__g("+goal+")."));
+ newAg.getPL().add(ASSyntax.parsePlan(trigger+" : not f__l(_) & " +context +" <- !f__g("+goal+")."));
// add t : f__l(_) & c <- +f__l(g).
- newAg.getPL().add(Plan.parse(trigger+" : f__l(_) & (" +context +") <- +f__l("+goal+")."));
+ newAg.getPL().add(ASSyntax.parsePlan(trigger+" : f__l(_) & (" +context +") <- +f__l("+goal+")."));
// add +!fg(g) : true <- +fl(g); !g; -fl(g)
- newAg.getPL().add(Plan.parse("+!f__g("+goal+") <- +f__l("+goal+"); !"+goal+"; -f__l("+goal+")."));
+ newAg.getPL().add(ASSyntax.parsePlan("+!f__g("+goal+") <- +f__l("+goal+"); !"+goal+"; -f__l("+goal+")."));
// add -!fg(g) : true <- -fl(g)
- newAg.getPL().add(Plan.parse("-!f__g("+goal+") <- -f__l("+goal+")."));
+ newAg.getPL().add(ASSyntax.parsePlan("-!f__g("+goal+") <- -f__l("+goal+")."));
// add -fl(_) : fg(g) <- !fg(g)
- newAg.getPL().add(Plan.parse("-f__l("+goal+") : f__l("+goal+") <- !f__g("+goal+")."));
+ newAg.getPL().add(ASSyntax.parsePlan("-f__l("+goal+") : f__l("+goal+") <- !f__g("+goal+")."));
return newAg;
} catch (Exception e) {
Modified: trunk/src/jason/asSyntax/patterns/goal/SMC.java
===================================================================
--- trunk/src/jason/asSyntax/patterns/goal/SMC.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/asSyntax/patterns/goal/SMC.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -1,7 +1,7 @@
package jason.asSyntax.patterns.goal;
import jason.asSemantics.Agent;
-import jason.asSyntax.Plan;
+import jason.asSyntax.ASSyntax;
import jason.asSyntax.Pred;
import jason.asSyntax.Term;
import jason.asSyntax.directives.Directive;
@@ -32,7 +32,7 @@
if (newAg != null) {
// add +f : true <- .fail_goal(g).
- newAg.getPL().add(Plan.parse("+"+fail+" <- .fail_goal("+goal+")."));
+ newAg.getPL().add(ASSyntax.parsePlan("+"+fail+" <- .fail_goal("+goal+")."));
return newAg;
}
Modified: trunk/src/jason/control/ExecutionControlGUI.java
===================================================================
--- trunk/src/jason/control/ExecutionControlGUI.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/control/ExecutionControlGUI.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -298,7 +298,6 @@
}
}
- @SuppressWarnings("unchecked")
private void setupSlider() {
int size = getCycleNumber();
Hashtable<Integer,Component> labelTable = new Hashtable<Integer,Component>();
Modified: trunk/src/jason/stdlib/add_annot.java
===================================================================
--- trunk/src/jason/stdlib/add_annot.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/stdlib/add_annot.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -97,7 +97,7 @@
}
return result;
} else if (l.isLiteral()) {
- return ((Literal)l).forceLiteralImplClass().copy().addAnnots(annot);
+ return ((Literal)l).forceFullLiteralImpl().copy().addAnnots(annot);
}
return l;
}
Modified: trunk/src/jason/stdlib/add_plan.java
===================================================================
--- trunk/src/jason/stdlib/add_plan.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/jason/stdlib/add_plan.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -102,8 +102,9 @@
before = args[2].toString().equals("begin");
if (plans.isList()) { // arg[0] is a list of strings
- for (Term t: (ListTerm) plans)
- ts.getAg().getPL().add((StringTerm) t, source);
+ for (Term t: (ListTerm) plans) {
+ ts.getAg().getPL().add((StringTerm) t, source, before);
+ }
} else { // args[0] is a plan
ts.getAg().getPL().add((StringTerm) plans, source, before);
}
Modified: trunk/src/test/StdLibTest.java
===================================================================
--- trunk/src/test/StdLibTest.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/test/StdLibTest.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -1,5 +1,6 @@
package test;
+import jason.JasonException;
import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSemantics.Agent;
@@ -140,7 +141,7 @@
assertEquals(lt.size(), 2);
}
- public void testGetRelevantPlansAndAddPlan() {
+ public void testGetRelevantPlansAndAddPlan() throws ParseException, JasonException {
Agent ag = new Agent();
ag.setLogger(null);
StringTerm pt1 = new StringTermImpl("@t1 +a : g(10) <- .print(\"ok 10\").");
Modified: trunk/src/test/TSTest.java
===================================================================
--- trunk/src/test/TSTest.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/test/TSTest.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -1,5 +1,6 @@
package test;
+import jason.JasonException;
import jason.asSemantics.Agent;
import jason.asSemantics.Circumstance;
import jason.asSemantics.Intention;
@@ -26,7 +27,7 @@
super.setUp();
}
- public void testRelevant() throws ParseException {
+ public void testRelevant() throws ParseException, JasonException {
Agent ag = new Agent();
Circumstance c = new Circumstance();
StringTerm pt1 = new StringTermImpl("@t1 +a(X) : g(10) <- .print(\"ok 10\").");
Modified: trunk/src/test/VarTermTest.java
===================================================================
--- trunk/src/test/VarTermTest.java 2009-02-18 13:17:08 UTC (rev 1447)
+++ trunk/src/test/VarTermTest.java 2009-02-18 14:30:59 UTC (rev 1448)
@@ -7,7 +7,6 @@
import jason.asSemantics.Unifier;
import jason.asSyntax.ASSyntax;
import jason.asSyntax.ArithExpr;
-import jason.asSyntax.Atom;
import jason.asSyntax.ListTerm;
import jason.asSyntax.ListTermImpl;
import jason.asSyntax.Literal;
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-02-19 10:51:04
|
Revision: 1450
http://jason.svn.sourceforge.net/jason/?rev=1450&view=rev
Author: jomifred
Date: 2009-02-19 10:50:55 +0000 (Thu, 19 Feb 2009)
Log Message:
-----------
fix a bug related to concurrent execution of .wait and .drop_desire
Modified Paths:
--------------
trunk/demos/gui/gui2/sample.asl
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/asSyntax/InternalActionLiteral.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/jason/stdlib/drop_all_intentions.java
trunk/src/jason/stdlib/drop_desire.java
trunk/src/jason/stdlib/drop_intention.java
trunk/src/jason/stdlib/intend.java
trunk/src/jason/stdlib/wait.java
Modified: trunk/demos/gui/gui2/sample.asl
===================================================================
--- trunk/demos/gui/gui2/sample.asl 2009-02-18 17:07:14 UTC (rev 1449)
+++ trunk/demos/gui/gui2/sample.asl 2009-02-19 10:50:55 UTC (rev 1450)
@@ -11,4 +11,4 @@
// the event !stop is created by the GUI
-+!stop(X) <- .drop_desire(run(X)).
++!stop(X) <- .drop_desire(run(X)); .print("stop ",X).
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2009-02-18 17:07:14 UTC (rev 1449)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2009-02-19 10:50:55 UTC (rev 1450)
@@ -490,27 +490,16 @@
// Rule Achieve
case achieve:
- 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 = body.copy();
- body.makeVarsAnnon(u);
+ body = addSelfSource(body.copy());
+ body.makeVarsAnnon(u); // free variables in an event cannot conflict with those in the plan
conf.C.addAchvGoal(body, conf.C.SI);
confP.step = State.StartRC;
break;
// Rule Achieve as a New Focus (the !! operator)
case achieveNF:
- if (!body.hasSource()) {
- // do not add source(self) in case the
- // programmer set some annotation
- body.addAnnot(BeliefBase.TSelf);
- }
- body = body.copy();
- body.makeVarsAnnon(u);
+ body = addSelfSource(body.copy());
+ body.makeVarsAnnon(u); // free variables in an event cannot conflict with those in the plan
conf.C.addAchvGoal(body, Intention.EmptyInt);
updateIntention();
break;
Modified: trunk/src/jason/asSyntax/InternalActionLiteral.java
===================================================================
--- trunk/src/jason/asSyntax/InternalActionLiteral.java 2009-02-18 17:07:14 UTC (rev 1449)
+++ trunk/src/jason/asSyntax/InternalActionLiteral.java 2009-02-19 10:50:55 UTC (rev 1450)
@@ -62,7 +62,7 @@
}
// used by the parser
- public InternalActionLiteral(Pred p, Agent ag) throws Exception {
+ public InternalActionLiteral(Structure p, Agent ag) throws Exception {
super(p);
if (ag != null)
ia = ag.getIA(getFunctor());
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2009-02-18 17:07:14 UTC (rev 1449)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2009-02-19 10:50:55 UTC (rev 1450)
@@ -403,7 +403,8 @@
/* Literal */
-Literal literal() : { Pred F; Token k; boolean type = Literal.LPos; }
+Literal literal() :
+ { Pred F; Token k; boolean type = Literal.LPos; }
{
( ( [ <TK_NEG> { type = Literal.LNeg; }
]
@@ -417,6 +418,10 @@
}
if (F.getFunctor().indexOf(".") >= 0) {
+ if (F.hasAnnot())
+ throw new ParseException(getSourceRef(F)+" Internal actions cannot have annotations.");
+ if (type == Literal.LNeg)
+ throw new ParseException(getSourceRef(F)+" Internal actions cannot be negated.");
try {
return new InternalActionLiteral(F, curAg);
} catch (Exception e) {
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2009-02-18 17:07:14 UTC (rev 1449)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2009-02-19 10:50:55 UTC (rev 1450)
@@ -562,6 +562,10 @@
}
if (F.getFunctor().indexOf(".") >= 0) {
+ if (F.hasAnnot())
+ {if (true) throw new ParseException(getSourceRef(F)+" Internal actions cannot have annotations.");}
+ if (type == Literal.LNeg)
+ {if (true) throw new ParseException(getSourceRef(F)+" Internal actions cannot be negated.");}
try {
{if (true) return new InternalActionLiteral(F, curAg);}
} catch (Exception e) {
@@ -1208,24 +1212,6 @@
finally { jj_save(0, xla); }
}
- final private boolean jj_3R_15() {
- if (jj_3R_17()) return true;
- return false;
- }
-
- final private boolean jj_3R_14() {
- if (jj_3R_16()) 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;
- if (jj_3R_12()) return true;
- if (jj_scan_token(28)) return true;
- return false;
- }
-
final private boolean jj_3R_17() {
if (jj_scan_token(42)) return true;
return false;
@@ -1236,11 +1222,6 @@
return false;
}
- final private boolean jj_3R_16() {
- if (jj_scan_token(27)) return true;
- return false;
- }
-
final private boolean jj_3R_12() {
Token xsp;
xsp = jj_scanpos;
@@ -1262,6 +1243,29 @@
return false;
}
+ final private boolean jj_3_1() {
+ if (jj_scan_token(27)) return true;
+ if (jj_scan_token(TK_BEGIN)) return true;
+ if (jj_3R_12()) return true;
+ if (jj_scan_token(28)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_15() {
+ if (jj_3R_17()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_16() {
+ if (jj_scan_token(27)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_14() {
+ if (jj_3R_16()) return true;
+ return false;
+ }
+
public as2jTokenManager token_source;
SimpleCharStream jj_input_stream;
public Token token, jj_nt;
Modified: trunk/src/jason/stdlib/drop_all_intentions.java
===================================================================
--- trunk/src/jason/stdlib/drop_all_intentions.java 2009-02-18 17:07:14 UTC (rev 1449)
+++ trunk/src/jason/stdlib/drop_all_intentions.java 2009-02-19 10:50:55 UTC (rev 1450)
@@ -74,8 +74,10 @@
checkArguments(args);
Circumstance C = ts.getC();
- C.clearIntentions();
- C.clearPendingIntentions();
+ synchronized (C) { // do not allow other threads (.wait) to change C meanwhile
+ C.clearIntentions();
+ C.clearPendingIntentions();
+ }
C.clearPendingActions();
// drop intentions in E
Modified: trunk/src/jason/stdlib/drop_desire.java
===================================================================
--- trunk/src/jason/stdlib/drop_desire.java 2009-02-18 17:07:14 UTC (rev 1449)
+++ trunk/src/jason/stdlib/drop_desire.java 2009-02-19 10:50:55 UTC (rev 1450)
@@ -85,12 +85,11 @@
while (ie.hasNext()) {
Event ei = ie.next();
Trigger t = ei.getTrigger();
- if (ei.getIntention() != Intention.EmptyInt) {
+ if (ei.getIntention() != Intention.EmptyInt) { // since the unifier of the intention will not be used, apply it to the event before comparing to the event to be dropped
t = (Trigger) t.clone();
t.apply(ei.getIntention().peek().getUnif());
}
if (un.clone().unifiesNoUndo(te, t)) {
- // old implementation: t.setTrigType(Trigger.TEDel); // Just changing "+!g" to "-!g"
ie.remove();
}
}
Modified: trunk/src/jason/stdlib/drop_intention.java
===================================================================
--- trunk/src/jason/stdlib/drop_intention.java 2009-02-18 17:07:14 UTC (rev 1449)
+++ trunk/src/jason/stdlib/drop_intention.java 2009-02-19 10:50:55 UTC (rev 1450)
@@ -88,12 +88,6 @@
Unifier bak = un.clone();
Trigger g = new Trigger(TEOperator.add, TEType.achieve, l);
- for (Intention i: C.getIntentions()) {
- if (i.hasTrigger(g, un)) {
- C.removeIntention(i);
- un = bak.clone();
- }
- }
// intention may be suspended in E
for (Event e: C.getEvents()) {
@@ -112,13 +106,22 @@
un = bak.clone();
}
}
-
- // intention may be suspended in PI! (in the new semantics)
- for (Intention i: C.getPendingIntentions().values()) {
- if (i.hasTrigger(g, un)) {
- C.dropPendingIntention(i);
- un = bak.clone();
+
+ synchronized (C) { // do not allow other threads (.wait) to change the C meanwhile
+ for (Intention i: C.getIntentions()) {
+ if (i.hasTrigger(g, un)) {
+ C.removeIntention(i);
+ un = bak.clone();
+ }
}
+
+ // intention may be suspended in PI! (in the new semantics)
+ for (Intention i: C.getPendingIntentions().values()) {
+ if (i.hasTrigger(g, un)) {
+ C.dropPendingIntention(i);
+ un = bak.clone();
+ }
+ }
}
}
}
Modified: trunk/src/jason/stdlib/intend.java
===================================================================
--- trunk/src/jason/stdlib/intend.java 2009-02-18 17:07:14 UTC (rev 1449)
+++ trunk/src/jason/stdlib/intend.java 2009-02-19 10:50:55 UTC (rev 1450)
@@ -117,19 +117,21 @@
}
}
- // intention may be suspended in PI! (in the new semantics)
- if (C.hasPendingIntention()) {
- for (Intention intention: C.getPendingIntentions().values()) {
- if (intention.hasTrigger(g, un))
+ synchronized (C) { // do not allow other threads (.wait) to change C meanwhile
+ // intention may be suspended in PI! (in the new semantics)
+ if (C.hasPendingIntention()) {
+ for (Intention intention: C.getPendingIntentions().values()) {
+ if (intention.hasTrigger(g, un))
+ return true;
+ }
+ }
+
+ for (Intention i : C.getIntentions()) {
+ if (i.hasTrigger(g, un))
return true;
}
}
- for (Intention i : C.getIntentions()) {
- if (i.hasTrigger(g, un))
- return true;
- }
-
return false;
}
Modified: trunk/src/jason/stdlib/wait.java
===================================================================
--- trunk/src/jason/stdlib/wait.java 2009-02-18 17:07:14 UTC (rev 1449)
+++ trunk/src/jason/stdlib/wait.java 2009-02-19 10:50:55 UTC (rev 1450)
@@ -167,31 +167,35 @@
// unregister (for not to receive intentionAdded again)
c.removeEventListener(this);
- // add SI again in C.I if it was not removed and this wait was not dropped
- if (c.getPendingIntentions().remove(sTE) == si && !c.getIntentions().contains(si) && !dropped) {
- if (stopByTimeout && te != null && elapsedTimeTerm == null) {
- // fail the .wait by timeout
- if (si.isSuspended()) { // if the intention was suspended by .suspend
- PlanBody body = si.peek().getPlan().getBody();
- body.add(1, new PlanBodyImpl(BodyType.internalAction, new InternalActionLiteral(".fail")));
- c.getPendingIntentions().put(suspend.SUSPENDED_INT+si.getId(), si);
+ synchronized (c) { // block access to C, so that .drop_desire, for instance, will wait this operation to finish;
+ // otherwise the intention disappears between 'remove from PI' and 'add back to I'
+
+ // add SI again in C.I if it was not removed and this wait was not dropped
+ if (c.getPendingIntentions().remove(sTE) == si && !c.getIntentions().contains(si) && !dropped) {
+ if (stopByTimeout && te != null && elapsedTimeTerm == null) {
+ // fail the .wait by timeout
+ if (si.isSuspended()) { // if the intention was suspended by .suspend
+ PlanBody body = si.peek().getPlan().getBody();
+ body.add(1, new PlanBodyImpl(BodyType.internalAction, new InternalActionLiteral(".fail")));
+ c.getPendingIntentions().put(suspend.SUSPENDED_INT+si.getId(), si);
+ } else {
+ ts.generateGoalDeletion(si, JasonException.createBasicErrorAnnots("wait_timeout", "timeout in .wait"));
+ }
} else {
- ts.generateGoalDeletion(si, JasonException.createBasicErrorAnnots("wait_timeout", "timeout in .wait"));
+ si.peek().removeCurrentStep();
+
+ if (elapsedTimeTerm != null) {
+ long elapsedTime = System.currentTimeMillis() - startTime;
+ un.unifies(elapsedTimeTerm, new NumberTermImpl(elapsedTime));
+ }
+ if (si.isSuspended()) { // if the intention was suspended by .suspend
+ c.getPendingIntentions().put(suspend.SUSPENDED_INT+si.getId(), si);
+ } else {
+ c.addIntention(si);
+ }
}
- } else {
- si.peek().removeCurrentStep();
-
- if (elapsedTimeTerm != null) {
- long elapsedTime = System.currentTimeMillis() - startTime;
- un.unifies(elapsedTimeTerm, new NumberTermImpl(elapsedTime));
- }
- if (si.isSuspended()) { // if the intention was suspended by .suspend
- c.getPendingIntentions().put(suspend.SUSPENDED_INT+si.getId(), si);
- } else {
- c.addIntention(si);
- }
+ ts.getUserAgArch().getArchInfraTier().wake();
}
- ts.getUserAgArch().getArchInfraTier().wake();
}
} catch (Exception e) {
ts.getLogger().log(Level.SEVERE, "Error at .wait thread", e);
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-02-19 23:26:18
|
Revision: 1452
http://jason.svn.sourceforge.net/jason/?rev=1452&view=rev
Author: jomifred
Date: 2009-02-19 22:16:36 +0000 (Thu, 19 Feb 2009)
Log Message:
-----------
consider taskToBeDoneNextCycle in the canSleep method
Modified Paths:
--------------
trunk/demos/function/a.asl
trunk/demos/gui/gui1/gui1.mas2j
trunk/examples/domestic-robot/robot.asl
trunk/src/jason/asSemantics/TransitionSystem.java
Modified: trunk/demos/function/a.asl
===================================================================
--- trunk/demos/function/a.asl 2009-02-19 16:00:17 UTC (rev 1451)
+++ trunk/demos/function/a.asl 2009-02-19 22:16:36 UTC (rev 1452)
@@ -32,18 +32,18 @@
/* Initial goals */
-!show_predef_funtion.
-!show_userdef_funtion.
+!show_predef_function.
+!show_userdef_function.
/* Plans */
-+!show_predef_funtion
++!show_predef_function
<- X = math.max(4, math.abs(-10));
.print("Max=",X);
.print("Max=",math.max(4, math.abs(-10)));
.print("Number of b/1 beliefs=", .count(b(_))).
-+!show_userdef_funtion
++!show_userdef_function
<- .print("Sin of 90 =", myf.sin(90));
.print("1+2 =", myf.sum(1,2));
.print("limit =", myf.limit);
Modified: trunk/demos/gui/gui1/gui1.mas2j
===================================================================
--- trunk/demos/gui/gui1/gui1.mas2j 2009-02-19 16:00:17 UTC (rev 1451)
+++ trunk/demos/gui/gui1/gui1.mas2j 2009-02-19 22:16:36 UTC (rev 1452)
@@ -1,6 +1,6 @@
/* Jason Project
- Simple exaple of GUI: and internal action is used to ask something for the user
+ Simple example of GUI: and internal action is used to ask something for the user
*/
Modified: trunk/examples/domestic-robot/robot.asl
===================================================================
--- trunk/examples/domestic-robot/robot.asl 2009-02-19 16:00:17 UTC (rev 1451)
+++ trunk/examples/domestic-robot/robot.asl 2009-02-19 22:16:36 UTC (rev 1452)
@@ -56,7 +56,7 @@
<- +available(beer,fridge);
!has(owner,beer).
-// when the fridge is openned, the beer stock is perceived
+// when the fridge is opened, the beer stock is perceived
// and thus the available belief is updated
+stock(beer,0)
: available(beer,fridge)
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2009-02-19 16:00:17 UTC (rev 1451)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2009-02-19 22:16:36 UTC (rev 1452)
@@ -912,7 +912,9 @@
public boolean canSleep() {
return !conf.C.hasEvent() && !conf.C.hasIntention() &&
- conf.C.MB.isEmpty() && !conf.C.hasFeedbackAction() &&
+ !conf.C.hasFeedbackAction() &&
+ conf.C.MB.isEmpty() &&
+ taskForBeginOfCycle.isEmpty() &&
agArch.canSleep();
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-02-20 20:14:48
|
Revision: 1453
http://jason.svn.sourceforge.net/jason/?rev=1453&view=rev
Author: jomifred
Date: 2009-02-20 20:14:44 +0000 (Fri, 20 Feb 2009)
Log Message:
-----------
fix a bug related to the third argument of .create_agent
Modified Paths:
--------------
trunk/demos/chain-bb/chain-bb.mas2j
trunk/demos/gui/gui2/gui2.mas2j
trunk/examples/game-of-life/LifeEnvironment.java
trunk/examples/game-of-life/game-of-life.mas2j
trunk/release-notes.txt
trunk/src/jason/stdlib/create_agent.java
Modified: trunk/demos/chain-bb/chain-bb.mas2j
===================================================================
--- trunk/demos/chain-bb/chain-bb.mas2j 2009-02-19 22:16:36 UTC (rev 1452)
+++ trunk/demos/chain-bb/chain-bb.mas2j 2009-02-20 20:14:44 UTC (rev 1453)
@@ -4,11 +4,11 @@
The agent bob uses two customisations of BB:
one to persist the beliefs and
- another to have a king of key based BB.
+ another to have a kind of key based BB.
To see the effect of the two BBs, run the program
and, when finished, click on "Debug" mode and then
- select "bob" agent. Notice that the boss beliefs have
+ select "bob" agent. Notice that the 'boss' beliefs have
unique keys. If you run the program again you will
note that beliefs added in previous executions
are persisted (they are stored in the bob.bb file).
Modified: trunk/demos/gui/gui2/gui2.mas2j
===================================================================
--- trunk/demos/gui/gui2/gui2.mas2j 2009-02-19 22:16:36 UTC (rev 1452)
+++ trunk/demos/gui/gui2/gui2.mas2j 2009-02-20 20:14:44 UTC (rev 1453)
@@ -1,7 +1,7 @@
/*
Jason Project
- Example of GUI that create events the agent can react to.
+ Example of GUI that creates events the agent can react to.
-- created on May 30, 2008
*/
Modified: trunk/examples/game-of-life/LifeEnvironment.java
===================================================================
--- trunk/examples/game-of-life/LifeEnvironment.java 2009-02-19 22:16:36 UTC (rev 1452)
+++ trunk/examples/game-of-life/LifeEnvironment.java 2009-02-20 20:14:44 UTC (rev 1453)
@@ -31,11 +31,11 @@
return true;
int ag = getAgIdBasedOnName(agName);
- if (actId.equals("die")) {
+ if (actId.equals("die"))
model.dead(ag);
- } else if (actId.equals("live")) {
+ else if (actId.equals("live"))
model.alive(ag);
- }
+
//updateNeighbors(ag);
return true;
}
@@ -66,7 +66,7 @@
}
}
- void updateNeighbors(int ag) {
+ void updateNeighbors(int ag) {
Location l = model.getAgPos(ag);
updateAgPercept(model.getAgId(l.x - 1, l.y - 1));
updateAgPercept(model.getAgId(l.x - 1, l.y));
@@ -90,12 +90,6 @@
// its location
Location l = model.getAgPos(ag);
- /*
- Literal lpos = new Literal("pos");
- lpos.addTerm(new NumberTermImpl(l.x));
- lpos.addTerm(new NumberTermImpl(l.y));
- addPercept(agName, lpos);
- */
// how many alive neighbours
int alive = 0;
Modified: trunk/examples/game-of-life/game-of-life.mas2j
===================================================================
--- trunk/examples/game-of-life/game-of-life.mas2j 2009-02-19 22:16:36 UTC (rev 1452)
+++ trunk/examples/game-of-life/game-of-life.mas2j 2009-02-20 20:14:44 UTC (rev 1453)
@@ -10,7 +10,7 @@
MAS game_of_life {
// use a thread pool instead of one thread by agent
- // the pool has only one thread
+ // the pool has only two threads
infrastructure: Centralised(pool,2)
environment: LifeEnvironment(60,10) // grid size = 60, initial density = 10%
Modified: trunk/release-notes.txt
===================================================================
--- trunk/release-notes.txt 2009-02-19 22:16:36 UTC (rev 1452)
+++ trunk/release-notes.txt 2009-02-20 20:14:44 UTC (rev 1453)
@@ -17,6 +17,10 @@
failures in unification
- variable unified with atom cannot be added in BB, as in
X = p; +X;
+- The third argument of .create_agent (list of options) can
+ not be used.
+- Some concurrent execution of .wait and .drop_desire/intention
+ does not work (the intention isn't dropped)
---------------------------
Modified: trunk/src/jason/stdlib/create_agent.java
===================================================================
--- trunk/src/jason/stdlib/create_agent.java 2009-02-19 22:16:36 UTC (rev 1452)
+++ trunk/src/jason/stdlib/create_agent.java 2009-02-20 20:14:44 UTC (rev 1453)
@@ -89,7 +89,7 @@
super.checkArguments(args); // check number of arguments
if (!args[1].isString())
throw JasonException.createWrongArgument(this,"second argument must be a string");
- if (args.length == 3 && !args[2].isString())
+ if (args.length == 3 && !args[2].isList())
throw JasonException.createWrongArgument(this,"third argument must be a list");
}
@@ -109,7 +109,6 @@
if (!fSource.exists()) {
throw new JasonException("The source file " + source + " was not found!");
}
-
String agClass = null;
String agArchClass = null;
ClassParameters bbPars = null;
@@ -129,7 +128,6 @@
}
}
-
RuntimeServicesInfraTier rs = ts.getUserAgArch().getArchInfraTier().getRuntimeServices();
return rs.createAgent(name, fSource.getAbsolutePath(), agClass, agArchClass, bbPars, ts.getSettings());
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-02-23 12:21:00
|
Revision: 1454
http://jason.svn.sourceforge.net/jason/?rev=1454&view=rev
Author: jomifred
Date: 2009-02-23 12:20:55 +0000 (Mon, 23 Feb 2009)
Log Message:
-----------
add new internal action:.puts (developed by Felipe Meneguzzi)
Modified Paths:
--------------
trunk/release-notes.txt
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/asSyntax/ASSyntax.java
trunk/src/jason/asSyntax/ArithExpr.java
trunk/src/jason/asSyntax/ArithFunctionTerm.java
trunk/src/jason/asSyntax/BinaryStructure.java
trunk/src/jason/asSyntax/ListTermImpl.java
trunk/src/jason/asSyntax/PlanBodyImpl.java
trunk/src/jason/bb/DefaultBeliefBase.java
Added Paths:
-----------
trunk/src/jason/stdlib/puts.java
Modified: trunk/release-notes.txt
===================================================================
--- trunk/release-notes.txt 2009-02-20 20:14:44 UTC (rev 1453)
+++ trunk/release-notes.txt 2009-02-23 12:20:55 UTC (rev 1454)
@@ -6,6 +6,10 @@
- for messages sent to itself, the sender is 'self' now,
and not the agent's name as in previous releases
+New internal actions
+- .puts: used for printing messages to the console (based on Ruby
+ similar method). Developed by Felipe Meneguzzi.
+
Changes in internal actions
- .relevant_plans has a third argument that gets the labels
of the plans
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2009-02-20 20:14:44 UTC (rev 1453)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2009-02-23 12:20:55 UTC (rev 1454)
@@ -597,7 +597,7 @@
// call BRF
try {
- List<Literal>[] result = ag.brf(null,body, conf.C.SI); // the intention is not the new focus
+ 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);
Modified: trunk/src/jason/asSyntax/ASSyntax.java
===================================================================
--- trunk/src/jason/asSyntax/ASSyntax.java 2009-02-20 20:14:44 UTC (rev 1453)
+++ trunk/src/jason/asSyntax/ASSyntax.java 2009-02-23 12:20:55 UTC (rev 1454)
@@ -78,7 +78,7 @@
}
/**
- * Creates a new structure term, is the functor (a string),
+ * Creates a new structure (compound) term, the first argument is the functor (a string),
* and the n remainder arguments are terms.
*/
public static Structure createStructure(String functor, Term... terms) {
@@ -86,7 +86,7 @@
return (Structure)new Structure(functor, size).addTerms(terms);
}
- /** creates a new Atom term */
+ /** creates a new Atom term (an atom is a structure with 0-arity) */
public static Atom createAtom(String functor) {
return new Atom(functor);
}
@@ -106,6 +106,11 @@
return new VarTerm(functor);
}
+ /** creates a new anonymous (or unnamed) variable */
+ public static VarTerm createVar() {
+ return new UnnamedVar();
+ }
+
/** Creates a new list with n elements, n can be 0 */
public static ListTerm createList(Term... terms) {
ListTerm l = new ListTermImpl();
@@ -164,7 +169,7 @@
return new as2j(new StringReader(sList)).list();
}
- /** creates a new logical formula by parsing a string */
+ /** creates a new logical formula by parsing a string */
public static LogicalFormula parseFormula(String sExpr) throws ParseException {
return (LogicalFormula)new as2j(new StringReader(sExpr)).log_expr();
}
Modified: trunk/src/jason/asSyntax/ArithExpr.java
===================================================================
--- trunk/src/jason/asSyntax/ArithExpr.java 2009-02-20 20:14:44 UTC (rev 1453)
+++ trunk/src/jason/asSyntax/ArithExpr.java 2009-02-23 12:20:55 UTC (rev 1454)
@@ -124,7 +124,8 @@
public ArithExpr(NumberTerm t1, ArithmeticOp oper, NumberTerm t2) {
super(oper.toString(),2);
- addTerms(t1, t2);
+ addTerm(t1);
+ addTerm(t2);
op = oper;
if (t1.getSrcInfo() != null)
srcInfo = t1.getSrcInfo();
Modified: trunk/src/jason/asSyntax/ArithFunctionTerm.java
===================================================================
--- trunk/src/jason/asSyntax/ArithFunctionTerm.java 2009-02-20 20:14:44 UTC (rev 1453)
+++ trunk/src/jason/asSyntax/ArithFunctionTerm.java 2009-02-23 12:20:55 UTC (rev 1454)
@@ -4,6 +4,7 @@
import jason.asSemantics.ArithFunction;
import jason.asSemantics.Unifier;
+import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -138,6 +139,12 @@
}
@Override
+ public Iterator<Unifier> logicalConsequence(Agent ag, Unifier un) {
+ logger.log(Level.WARNING, "Arithmetic term cannot be used for logical consequence!", new Exception());
+ return LogExpr.EMPTY_UNIF_LIST.iterator();
+ }
+
+ @Override
public boolean equals(Object t) {
if (t == null) return false;
if (isEvaluated()) return value.equals(t);
Modified: trunk/src/jason/asSyntax/BinaryStructure.java
===================================================================
--- trunk/src/jason/asSyntax/BinaryStructure.java 2009-02-20 20:14:44 UTC (rev 1453)
+++ trunk/src/jason/asSyntax/BinaryStructure.java 2009-02-23 12:20:55 UTC (rev 1454)
@@ -41,7 +41,8 @@
/** Constructor for binary operator */
public BinaryStructure(Term t1, String id, Term t2) {
super(id,2);
- addTerms( t1, t2 );
+ addTerm(t1);
+ addTerm(t2);
if (t1.getSrcInfo() != null)
srcInfo = t1.getSrcInfo();
else
Modified: trunk/src/jason/asSyntax/ListTermImpl.java
===================================================================
--- trunk/src/jason/asSyntax/ListTermImpl.java 2009-02-20 20:14:44 UTC (rev 1453)
+++ trunk/src/jason/asSyntax/ListTermImpl.java 2009-02-23 12:20:55 UTC (rev 1454)
@@ -23,6 +23,7 @@
package jason.asSyntax;
+import jason.asSemantics.Agent;
import jason.asSemantics.Unifier;
import jason.asSyntax.parser.as2j;
@@ -227,6 +228,12 @@
return false;
}
+ @Override
+ public Iterator<Unifier> logicalConsequence(Agent ag, Unifier un) {
+ logger.log(Level.WARNING, "ListTermImpl cannot be used for logical consequence!", new Exception());
+ return LogExpr.EMPTY_UNIF_LIST.iterator();
+ }
+
public boolean isTail() {
return next != null && next.isVar();
}
Modified: trunk/src/jason/asSyntax/PlanBodyImpl.java
===================================================================
--- trunk/src/jason/asSyntax/PlanBodyImpl.java 2009-02-20 20:14:44 UTC (rev 1453)
+++ trunk/src/jason/asSyntax/PlanBodyImpl.java 2009-02-23 12:20:55 UTC (rev 1454)
@@ -1,8 +1,11 @@
package jason.asSyntax;
+import jason.asSemantics.Agent;
import jason.asSemantics.Unifier;
import java.util.Iterator;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -22,6 +25,7 @@
public class PlanBodyImpl extends Structure implements PlanBody, Iterable<PlanBody> {
private static final long serialVersionUID = 1L;
+ private static final Logger logger = Logger.getLogger(PlanBodyImpl.class.getName());
public static final String BODY_PLAN_FUNCTOR = ";";
@@ -130,7 +134,7 @@
@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!");
+ if (i == 1) System.out.println("Should not setTerm(1) of body literal!");
}
@Override
@@ -146,6 +150,12 @@
}
return false;
}
+
+ @Override
+ public Iterator<Unifier> logicalConsequence(Agent ag, Unifier un) {
+ logger.log(Level.WARNING, "PlanBodyImpl cannot be used for logical consequence!", new Exception());
+ return LogExpr.EMPTY_UNIF_LIST.iterator();
+ }
@Override
public boolean equals(Object o) {
Modified: trunk/src/jason/bb/DefaultBeliefBase.java
===================================================================
--- trunk/src/jason/bb/DefaultBeliefBase.java 2009-02-20 20:14:44 UTC (rev 1453)
+++ trunk/src/jason/bb/DefaultBeliefBase.java 2009-02-23 12:20:55 UTC (rev 1454)
@@ -125,6 +125,7 @@
// add only annots
if (bl.importAnnots(l)) {
// check if it needs to be added in the percepts list
+ // (note that l contains only the annots imported)
if (l.hasAnnot(TPercept)) {
percepts.add(bl);
}
Added: trunk/src/jason/stdlib/puts.java
===================================================================
--- trunk/src/jason/stdlib/puts.java (rev 0)
+++ trunk/src/jason/stdlib/puts.java 2009-02-23 12:20:55 UTC (rev 1454)
@@ -0,0 +1,130 @@
+package jason.stdlib;
+
+import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
+import jason.asSemantics.TransitionSystem;
+import jason.asSemantics.Unifier;
+import jason.asSyntax.ASSyntax;
+import jason.asSyntax.StringTerm;
+import jason.asSyntax.StringTermImpl;
+import jason.asSyntax.Term;
+import jason.asSyntax.parser.ParseException;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * <p>
+ * Internal action: <b><code>.puts</code></b>.
+ *
+ * <p>
+ * Description: used for printing messages to the console where the system is
+ * running, or unifying the message to a variable parameter. It receives one
+ * string parameter, containing escaped variable names that are replaced by
+ * their bindings in the current intention's unifier. Terms are made ground
+ * according to the current unifying function before being printed out. No new
+ * line is printed after the parameters. In this version a user can also
+ * include any Jason expression (logical or arithmetic) that will be replaced
+ * by it's evaluated value.
+ *
+ * <p>
+ * The precise format and output device of the message is defined by the Java
+ * logging configuration as defined in the <code>logging.properties</code>
+ * file in the project directory.
+ *
+ * <p>
+ * Parameters:
+ * <ul>
+ *
+ * <li>+message (string): the string to be printed out.</li>
+ * <li>-output (any variable [optional]): the variable to print the processed
+ * result.</li>
+ *
+ * </ul>
+ *
+ * <p>
+ * Example:
+ * <ul>
+ *
+ * <li> <code>.puts("Testing variable #{A}")</code>: prints out to the
+ * console the supplied string replacing #{A} with the value of variable A.</li>
+ * <li> <code>.puts("Testing variable #{A}, into B", B)</code>: tries to unify
+ * B with the supplied string replacing #{A} with the value of variable A.</li>
+ * <li> <code>.puts("The value of the expression is #{X+2}")</code>: prints out
+ * the result of the X+2 expression. Assuming X is unified to a numeric value,
+ * the printed result will be the sum of X and two, if X is unified to any
+ * other value, the original expression (X+2) will be printed.</li>
+ *
+ * </ul>
+ *
+ * @see act.puts
+ * @author Felipe Meneguzzi (http://www.meneguzzi.eu/felipe)
+ *
+ */
+
+public class puts extends DefaultInternalAction {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private static InternalAction singleton = null;
+
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new puts();
+ return singleton;
+ }
+
+ //Pattern regex = Pattern.compile("#\\{\\p{Upper}\\p{Alnum}*\\}");
+ Pattern regex = Pattern.compile("#\\{\\p{ASCII}+\\}");
+
+ @Override
+ public Object execute(TransitionSystem ts, Unifier un, Term[] args)
+ throws Exception {
+ if (!args[0].isString()) {
+ return false;
+ }
+
+ StringBuffer sb = new StringBuffer();
+ for (Term term : args) {
+ if (!term.isString()) {
+ continue;
+ }
+ StringTerm st = (StringTerm) term;
+ Matcher matcher = regex.matcher(st.getString());
+
+ while (matcher.find()) {
+ /*
+ * System.out.println("I found the text \""+matcher.group()+ "\"
+ * starting at index "+matcher.start()+ " and ending at index
+ * "+matcher.end());
+ */
+ String sVar = matcher.group();
+ sVar = sVar.substring(2, sVar.length() - 1);
+ try {
+ Term t = ASSyntax.parseTerm(sVar);
+ //We use t.apply to evaluate any logical or arithmetic expression in Jason
+ t.apply(un);
+ matcher.appendReplacement(sb, t.toString());
+ } catch (ParseException pe) {
+ // TODO: handle exception
+ // TODO: Decide whether or not we should ignore the exception and print the call instead
+ // Right now, if I get a parse error from ASSyntax, I just print the original escaped
+ // sequence, so a user can see that his/her expression was problematic
+ matcher.appendReplacement(sb, "#{"+sVar+"}");
+ }
+
+ }
+ matcher.appendTail(sb);
+ }
+
+ if (args[args.length - 1].isVar()) {
+ StringTerm stRes = new StringTermImpl(sb.toString());
+ return un.unifies(stRes, args[args.length - 1]);
+ } else {
+ ts.getLogger().info(sb.toString());
+ return true;
+ }
+ }
+}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-02-27 08:11:42
|
Revision: 1455
http://jason.svn.sourceforge.net/jason/?rev=1455&view=rev
Author: jomifred
Date: 2009-02-27 08:11:39 +0000 (Fri, 27 Feb 2009)
Log Message:
-----------
fix a bug related to atom unified with a var that is used as goal
X=a; !X.
no annotation was added in the event.
two close the MAS console, implies to stop the application
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/tests/BugVarsAsArg.java
trunk/applications/as-unit-test/src/jason/tests/TestAll.java
trunk/applications/jason-team/src/team-os.xml
trunk/release-notes.txt
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/runtime/MASConsoleGUI.java
Added Paths:
-----------
trunk/applications/as-unit-test/src/jason/tests/BugVarsAsGoal.java
Modified: trunk/applications/as-unit-test/src/jason/tests/BugVarsAsArg.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/BugVarsAsArg.java 2009-02-23 12:20:55 UTC (rev 1454)
+++ trunk/applications/as-unit-test/src/jason/tests/BugVarsAsArg.java 2009-02-27 08:11:39 UTC (rev 1455)
@@ -5,7 +5,7 @@
import org.junit.Before;
import org.junit.Test;
-/** based on bug found by Stephen Cranefield -- see jason list */
+/** based on bug found by J\xBFrgen Villadsen */
public class BugVarsAsArg {
TestAgent ag;
@@ -17,36 +17,17 @@
// defines the agent's AgentSpeak code
ag.parseAScode(
- "test_rule(A,a(A)). "+
- "ml0(L,L). "+
- "ml(V1,V2,R) :- ml0([V1,V2],R). "+
-
- "append([], L, L). "+
- "append([H|T], L1, [H|L2]) :- append(T, L1, L2). "+
-
- "+!test1 <- ?test_rule(T,A); A = a(V); T=45; jason.asunit.print(V). "+
- "+!test2 <- ?ml(A,B,L); A=1; B=2; jason.asunit.print(L). "+
- "+!test3 <- L=[X,Y]; ?append(L, [Z], L2); Z=a; X=f; Y=i; jason.asunit.print(L2). "
+ "+!g <- +p(ggg); !gg. " +
+ "+!gg : p(X) <- !!X. " +
+ "+!ggg[source(A)] <- jason.asunit.print(A). "
);
}
@Test
- public void testRule1() {
- ag.addGoal("test1");
- ag.assertPrint("45", 5);
+ public void testGoal() {
+ ag.addGoal("g");
+ ag.assertPrint("self", 10);
}
-
- @Test
- public void testRule2() {
- ag.addGoal("test2");
- ag.assertPrint("[1,2]", 5);
- }
-
- @Test
- public void testRule3() {
- ag.addGoal("test3");
- ag.assertPrint("[f,i,a]", 10);
- }
}
Added: trunk/applications/as-unit-test/src/jason/tests/BugVarsAsGoal.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/BugVarsAsGoal.java (rev 0)
+++ trunk/applications/as-unit-test/src/jason/tests/BugVarsAsGoal.java 2009-02-27 08:11:39 UTC (rev 1455)
@@ -0,0 +1,52 @@
+package jason.tests;
+
+import jason.asunit.TestAgent;
+
+import org.junit.Before;
+import org.junit.Test;
+
+/** based on bug found by Stephen Cranefield -- see jason list */
+public class BugVarsAsGoal {
+
+ TestAgent ag;
+
+ // initialisation of the agent test
+ @Before
+ public void setupAg() {
+ ag = new TestAgent();
+
+ // defines the agent's AgentSpeak code
+ ag.parseAScode(
+ "test_rule(A,a(A)). "+
+ "ml0(L,L). "+
+ "ml(V1,V2,R) :- ml0([V1,V2],R). "+
+
+ "append([], L, L). "+
+ "append([H|T], L1, [H|L2]) :- append(T, L1, L2). "+
+
+ "+!test1 <- ?test_rule(T,A); A = a(V); T=45; jason.asunit.print(V). "+
+ "+!test2 <- ?ml(A,B,L); A=1; B=2; jason.asunit.print(L). "+
+ "+!test3 <- L=[X,Y]; ?append(L, [Z], L2); Z=a; X=f; Y=i; jason.asunit.print(L2). "
+ );
+ }
+
+
+
+ @Test
+ public void testRule1() {
+ ag.addGoal("test1");
+ ag.assertPrint("45", 5);
+ }
+
+ @Test
+ public void testRule2() {
+ ag.addGoal("test2");
+ ag.assertPrint("[1,2]", 5);
+ }
+
+ @Test
+ public void testRule3() {
+ ag.addGoal("test3");
+ ag.assertPrint("[f,i,a]", 10);
+ }
+}
Modified: trunk/applications/as-unit-test/src/jason/tests/TestAll.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestAll.java 2009-02-23 12:20:55 UTC (rev 1454)
+++ trunk/applications/as-unit-test/src/jason/tests/TestAll.java 2009-02-27 08:11:39 UTC (rev 1455)
@@ -8,6 +8,7 @@
@SuiteClasses({
BugListReturnUnification.class,
BugVarsAsArg.class,
+ BugVarsAsGoal.class,
BugVarsInInitBels.class,
TestAddLogExprInBB.class,
TestGoalSource.class,
Modified: trunk/applications/jason-team/src/team-os.xml
===================================================================
--- trunk/applications/jason-team/src/team-os.xml 2009-02-23 12:20:55 UTC (rev 1454)
+++ trunk/applications/jason-team/src/team-os.xml 2009-02-27 08:11:39 UTC (rev 1455)
@@ -56,10 +56,10 @@
</sub-groups>
<formation-constraints>
- <compatibility from="explorer" to="herder" type="compatibility"
+ <compatibility from="explorer" to="herder"
scope="intra-group" extends-sub-groups="true"
bi-dir="true"/>
- <compatibility from="scouter" to="herder" type="herdboy"
+ <compatibility from="scouter" to="herder"
scope="intra-group" extends-sub-groups="true"
bi-dir="true"/>
</formation-constraints>
Modified: trunk/release-notes.txt
===================================================================
--- trunk/release-notes.txt 2009-02-23 12:20:55 UTC (rev 1454)
+++ trunk/release-notes.txt 2009-02-27 08:11:39 UTC (rev 1455)
@@ -2,6 +2,10 @@
version 1.2.1
---------------------------
+Changes in the GUI
+- When closing the window of MAS Console, the application is also
+ stopped.
+
Changes in communication
- for messages sent to itself, the sender is 'self' now,
and not the agent's name as in previous releases
@@ -173,7 +177,7 @@
when annotations are used
. print worked like println
. problem in =.. with atoms
-. problem in unification whe unbound vars were used as arguments
+. problem in unification when unbound vars were used as arguments
for rules (as identified by Stephen Cranefield)
-------------
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2009-02-23 12:20:55 UTC (rev 1454)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2009-02-27 08:11:39 UTC (rev 1455)
@@ -620,8 +620,9 @@
if (body instanceof VarTerm) {
Term v = ((VarTerm)body).getValue();
if (v != null && v.isAtom())
- body = ((Atom)v).forceFullLiteralImpl();
+ body = ((Atom)v);
}
+ body = body.forceFullLiteralImpl();
if (!body.hasSource()) {
// do not add source(self) in case the
// programmer set the source
Modified: trunk/src/jason/runtime/MASConsoleGUI.java
===================================================================
--- trunk/src/jason/runtime/MASConsoleGUI.java 2009-02-23 12:20:55 UTC (rev 1454)
+++ trunk/src/jason/runtime/MASConsoleGUI.java 2009-02-27 08:11:39 UTC (rev 1455)
@@ -31,6 +31,7 @@
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
+import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.LogManager;
@@ -199,6 +200,15 @@
masConsole.frame.setVisible(false);
if (out != null)
out.restoreOriginalOut();
+ try {
+ if (RunCentralisedMAS.getRunner() != null) {
+ FileWriter f = new FileWriter(RunCentralisedMAS.stopMASFileName);
+ f.write(32);
+ f.close();
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
masConsole = null;
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-03-02 15:20:45
|
Revision: 1456
http://jason.svn.sourceforge.net/jason/?rev=1456&view=rev
Author: jomifred
Date: 2009-03-02 15:20:39 +0000 (Mon, 02 Mar 2009)
Log Message:
-----------
new internal action: .all_names
Modified Paths:
--------------
trunk/build.xml
trunk/doc/index.html
trunk/release-notes.txt
trunk/src/jason/infra/centralised/CentralisedRuntimeServices.java
trunk/src/jason/infra/jade/JadeRuntimeServices.java
trunk/src/jason/infra/saci/SaciRuntimeServices.java
trunk/src/jason/runtime/RuntimeServicesInfraTier.java
trunk/src/jason/stdlib/create_agent.java
trunk/src/jason/stdlib/my_name.java
trunk/src/jason/stdlib/package.html
Added Paths:
-----------
trunk/src/jason/stdlib/all_names.java
Modified: trunk/build.xml
===================================================================
--- trunk/build.xml 2009-02-27 08:11:39 UTC (rev 1455)
+++ trunk/build.xml 2009-03-02 15:20:39 UTC (rev 1456)
@@ -352,6 +352,7 @@
<delete dir="${distDir}/bin/classes" />
<delete dir="${distDir}/bin/classes-eclipse" />
<delete dir="${distDir}/doc/faq" />
+ <delete dir="${distDir}/doc/api-doxygen" />
<delete dir="${distDir}/doc/mini-tutorial/src" />
<tar compression="gzip" tarfile="${distFile}.tgz" longfile="gnu">
Modified: trunk/doc/index.html
===================================================================
--- trunk/doc/index.html 2009-02-27 08:11:39 UTC (rev 1455)
+++ trunk/doc/index.html 2009-03-02 15:20:39 UTC (rev 1456)
@@ -20,7 +20,7 @@
<li><a href="api/jason/stdlib/package-summary.html#package_description">Stantard internal actions</a> (html)</li>
<li><a href="api/jason/functions/package-summary.html">Stantard arithmetic functions</a> (html)</li>
-<li>API of all classes: generated by <a href="api/index.html">JavaDoc</a> or by <a href="api-doxygen/html/index.html">Doxygen</a>.</li><br>
+<li>API of all classes: generated by <a href="api/index.html">JavaDoc</a>.</li><br>
<li><a href="AS2JavaParser.html">Syntax of AgentSpeak</a> as
interpreted by <a href="http://jason.sf.net"><b><i>Jason</i></b></a> (html
Modified: trunk/release-notes.txt
===================================================================
--- trunk/release-notes.txt 2009-02-27 08:11:39 UTC (rev 1455)
+++ trunk/release-notes.txt 2009-03-02 15:20:39 UTC (rev 1456)
@@ -10,9 +10,11 @@
- for messages sent to itself, the sender is 'self' now,
and not the agent's name as in previous releases
+
New internal actions
- .puts: used for printing messages to the console (based on Ruby
similar method). Developed by Felipe Meneguzzi.
+- .all_names: get the name of all agentes in the system.
Changes in internal actions
- .relevant_plans has a third argument that gets the labels
Modified: trunk/src/jason/infra/centralised/CentralisedRuntimeServices.java
===================================================================
--- trunk/src/jason/infra/centralised/CentralisedRuntimeServices.java 2009-02-27 08:11:39 UTC (rev 1455)
+++ trunk/src/jason/infra/centralised/CentralisedRuntimeServices.java 2009-03-02 15:20:39 UTC (rev 1456)
@@ -78,12 +78,6 @@
return masRunner.getAgs().keySet();
}
- /** @deprecated use getAgentsNames() */
- public Set<String> getAgentsName() {
- return getAgentsNames();
- }
-
-
public int getAgentsQty() {
return masRunner.getAgs().keySet().size();
}
Modified: trunk/src/jason/infra/jade/JadeRuntimeServices.java
===================================================================
--- trunk/src/jason/infra/jade/JadeRuntimeServices.java 2009-02-27 08:11:39 UTC (rev 1455)
+++ trunk/src/jason/infra/jade/JadeRuntimeServices.java 2009-03-02 15:20:39 UTC (rev 1456)
@@ -98,11 +98,6 @@
return null;
}
- /** @deprecated use getAgentsNames() */
- public Set<String> getAgentsName() {
- return getAgentsNames();
- }
-
public int getAgentsQty() {
try {
return getAgentsNames().size();
Modified: trunk/src/jason/infra/saci/SaciRuntimeServices.java
===================================================================
--- trunk/src/jason/infra/saci/SaciRuntimeServices.java 2009-02-27 08:11:39 UTC (rev 1455)
+++ trunk/src/jason/infra/saci/SaciRuntimeServices.java 2009-03-02 15:20:39 UTC (rev 1456)
@@ -94,12 +94,6 @@
return null;
}
- /** @deprecated use getAgentsNames() */
- public Set<String> getAgentsName() {
- return getAgentsNames();
- }
-
-
public int getAgentsQty() {
try {
return facilitator.getAgQty() - 3; // do not include controller,
Modified: trunk/src/jason/runtime/RuntimeServicesInfraTier.java
===================================================================
--- trunk/src/jason/runtime/RuntimeServicesInfraTier.java 2009-02-27 08:11:39 UTC (rev 1455)
+++ trunk/src/jason/runtime/RuntimeServicesInfraTier.java 2009-03-02 15:20:39 UTC (rev 1456)
@@ -47,9 +47,6 @@
/** Returns a set of all agents' name */
public Set<String> getAgentsNames();
- /** @deprecated use getAgentsNames */
- public Set<String> getAgentsName();
-
/** Gets the number of agents in the MAS. */
public int getAgentsQty();
Added: trunk/src/jason/stdlib/all_names.java
===================================================================
--- trunk/src/jason/stdlib/all_names.java (rev 0)
+++ trunk/src/jason/stdlib/all_names.java 2009-03-02 15:20:39 UTC (rev 1456)
@@ -0,0 +1,71 @@
+//----------------------------------------------------------------------------
+// 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.asSemantics.DefaultInternalAction;
+import jason.asSemantics.TransitionSystem;
+import jason.asSemantics.Unifier;
+import jason.asSyntax.Atom;
+import jason.asSyntax.ListTerm;
+import jason.asSyntax.ListTermImpl;
+import jason.asSyntax.Term;
+import jason.runtime.RuntimeServicesInfraTier;
+
+/**
+ <p>Internal action: <b><code>.all_names</code></b>.
+
+ <p>Description: get the names of all agents in the system.
+ This identification is given by the runtime
+ infrastructure of the system (centralised, saci, jade, ...)
+
+ <p>Parameters:<ul>
+ <li>+/- names (list).<br/>
+ </ul>
+
+ <p>Examples:<ul>
+
+ <li> <code>.all_names(L)</code>: unifies with L a list of all agents in the system.</li>
+
+ </ul>
+
+ @see jason.stdlib.my_name
+ @see jason.runtime.RuntimeServicesInfraTier
+*/
+public class all_names extends DefaultInternalAction {
+
+ @Override public int getMinArgs() { return 1; }
+ @Override public int getMaxArgs() { return 1; }
+
+ @Override
+ public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
+ checkArguments(args);
+ RuntimeServicesInfraTier rs = ts.getUserAgArch().getArchInfraTier().getRuntimeServices();
+ ListTerm ln = new ListTermImpl();
+ ListTerm tail = ln;
+ for (String a: rs.getAgentsNames()) {
+ tail = tail.append(new Atom(a));
+ }
+ return un.unifies(args[0], ln);
+ }
+}
Modified: trunk/src/jason/stdlib/create_agent.java
===================================================================
--- trunk/src/jason/stdlib/create_agent.java 2009-02-27 08:11:39 UTC (rev 1455)
+++ trunk/src/jason/stdlib/create_agent.java 2009-03-02 15:20:39 UTC (rev 1456)
@@ -41,7 +41,7 @@
<p>Parameters:<ul>
- <li>+ name (atom): the name for the new agent.<br/>
+ <li>+ name (atom or string): the name for the new agent.<br/>
<li>+ source (string): path to the file where the AgentSpeak code
for the new agent can be found.<br/>
Modified: trunk/src/jason/stdlib/my_name.java
===================================================================
--- trunk/src/jason/stdlib/my_name.java 2009-02-27 08:11:39 UTC (rev 1455)
+++ trunk/src/jason/stdlib/my_name.java 2009-03-02 15:20:39 UTC (rev 1456)
@@ -55,6 +55,8 @@
@see jason.stdlib.send
@see jason.stdlib.broadcast
+ @see jason.stdlib.all_names
+
*/
public class my_name extends DefaultInternalAction {
Modified: trunk/src/jason/stdlib/package.html
===================================================================
--- trunk/src/jason/stdlib/package.html 2009-02-27 08:11:39 UTC (rev 1455)
+++ trunk/src/jason/stdlib/package.html 2009-03-02 15:20:39 UTC (rev 1456)
@@ -50,6 +50,7 @@
<li>{@link jason.stdlib.send send}: send messages. </li>
<li>{@link jason.stdlib.broadcast broadcast}: broadcast messages.</li>
<li>{@link jason.stdlib.my_name my_name}: get the agent's name.</li>
+ <li>{@link jason.stdlib.all_names all_names}: get the names of all agents in the system.</li>
</ul>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-03-03 07:42:20
|
Revision: 1457
http://jason.svn.sourceforge.net/jason/?rev=1457&view=rev
Author: jomifred
Date: 2009-03-03 07:42:18 +0000 (Tue, 03 Mar 2009)
Log Message:
-----------
fix doc of term2string, improve foreach loop
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/tests/BugVarsAsArg.java
trunk/applications/as-unit-test/src/jason/tests/BugVarsAsGoal.java
trunk/src/jason/asSyntax/LiteralImpl.java
trunk/src/jason/asSyntax/Pred.java
trunk/src/jason/asSyntax/Structure.java
trunk/src/jason/stdlib/foreach.java
trunk/src/jason/stdlib/loop.java
trunk/src/jason/stdlib/term2string.java
trunk/src/test/TermTest.java
Modified: trunk/applications/as-unit-test/src/jason/tests/BugVarsAsArg.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/BugVarsAsArg.java 2009-03-02 15:20:39 UTC (rev 1456)
+++ trunk/applications/as-unit-test/src/jason/tests/BugVarsAsArg.java 2009-03-03 07:42:18 UTC (rev 1457)
@@ -5,7 +5,7 @@
import org.junit.Before;
import org.junit.Test;
-/** based on bug found by J\xBFrgen Villadsen */
+/** based on bug found by Stephen Cranefield -- see jason list */
public class BugVarsAsArg {
TestAgent ag;
@@ -17,17 +17,35 @@
// defines the agent's AgentSpeak code
ag.parseAScode(
- "+!g <- +p(ggg); !gg. " +
- "+!gg : p(X) <- !!X. " +
- "+!ggg[source(A)] <- jason.asunit.print(A). "
+ "test_rule(A,a(A)). "+
+ "ml0(L,L). "+
+ "ml(V1,V2,R) :- ml0([V1,V2],R). "+
+
+ "append([], L, L). "+
+ "append([H|T], L1, [H|L2]) :- append(T, L1, L2). "+
+
+ "+!test1 <- ?test_rule(T,A); A = a(V); T=45; jason.asunit.print(V). "+
+ "+!test2 <- ?ml(A,B,L); A=1; B=2; jason.asunit.print(L). "+
+ "+!test3 <- L=[X,Y]; ?append(L, [Z], L2); Z=a; X=f; Y=i; jason.asunit.print(L2). "
);
}
-
-
+
@Test
- public void testGoal() {
- ag.addGoal("g");
- ag.assertPrint("self", 10);
+ public void testRule1() {
+ ag.addGoal("test1");
+ ag.assertPrint("45", 5);
}
+
+ @Test
+ public void testRule2() {
+ ag.addGoal("test2");
+ ag.assertPrint("[1,2]", 5);
+ }
+
+ @Test
+ public void testRule3() {
+ ag.addGoal("test3");
+ ag.assertPrint("[f,i,a]", 10);
+ }
}
Modified: trunk/applications/as-unit-test/src/jason/tests/BugVarsAsGoal.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/BugVarsAsGoal.java 2009-03-02 15:20:39 UTC (rev 1456)
+++ trunk/applications/as-unit-test/src/jason/tests/BugVarsAsGoal.java 2009-03-03 07:42:18 UTC (rev 1457)
@@ -5,7 +5,7 @@
import org.junit.Before;
import org.junit.Test;
-/** based on bug found by Stephen Cranefield -- see jason list */
+/** based on bug found by Jorgen Villadsen */
public class BugVarsAsGoal {
TestAgent ag;
@@ -17,36 +17,15 @@
// defines the agent's AgentSpeak code
ag.parseAScode(
- "test_rule(A,a(A)). "+
- "ml0(L,L). "+
- "ml(V1,V2,R) :- ml0([V1,V2],R). "+
-
- "append([], L, L). "+
- "append([H|T], L1, [H|L2]) :- append(T, L1, L2). "+
-
- "+!test1 <- ?test_rule(T,A); A = a(V); T=45; jason.asunit.print(V). "+
- "+!test2 <- ?ml(A,B,L); A=1; B=2; jason.asunit.print(L). "+
- "+!test3 <- L=[X,Y]; ?append(L, [Z], L2); Z=a; X=f; Y=i; jason.asunit.print(L2). "
+ "+!g <- +p(ggg); !gg. " +
+ "+!gg : p(X) <- !!X. " +
+ "+!ggg[source(A)] <- jason.asunit.print(A). "
);
}
-
-
-
+
@Test
- public void testRule1() {
- ag.addGoal("test1");
- ag.assertPrint("45", 5);
+ public void testGoal() {
+ ag.addGoal("g");
+ ag.assertPrint("self", 10);
}
-
- @Test
- public void testRule2() {
- ag.addGoal("test2");
- ag.assertPrint("[1,2]", 5);
- }
-
- @Test
- public void testRule3() {
- ag.addGoal("test3");
- ag.assertPrint("[f,i,a]", 10);
- }
}
Modified: trunk/src/jason/asSyntax/LiteralImpl.java
===================================================================
--- trunk/src/jason/asSyntax/LiteralImpl.java 2009-03-02 15:20:39 UTC (rev 1456)
+++ trunk/src/jason/asSyntax/LiteralImpl.java 2009-03-03 07:42:18 UTC (rev 1457)
@@ -93,8 +93,8 @@
if (o instanceof LiteralImpl) {
final LiteralImpl l = (LiteralImpl) o;
return type == l.type && hashCode() == l.hashCode() && super.equals(l);
- } else if (o instanceof Atom) {
- return !negated() && super.equals(o);
+ } else if (o instanceof Atom && !negated()) {
+ return super.equals(o);
}
return false;
}
Modified: trunk/src/jason/asSyntax/Pred.java
===================================================================
--- trunk/src/jason/asSyntax/Pred.java 2009-03-02 15:20:39 UTC (rev 1456)
+++ trunk/src/jason/asSyntax/Pred.java 2009-03-03 07:42:18 UTC (rev 1457)
@@ -425,8 +425,8 @@
if (o instanceof Pred) {
final Pred p = (Pred) o;
return super.equals(o) && this.hasSubsetAnnot(p) && p.hasSubsetAnnot(this);
- } else if (o instanceof Atom) {
- return !hasAnnot() && super.equals(o);
+ } else if (o instanceof Atom && !hasAnnot() ) { // if o is some object that extends Atom (e.g. structure), goes to super equals
+ return super.equals(o); // consider super equals only when this has no annots
}
return false;
}
Modified: trunk/src/jason/asSyntax/Structure.java
===================================================================
--- trunk/src/jason/asSyntax/Structure.java 2009-03-02 15:20:39 UTC (rev 1456)
+++ trunk/src/jason/asSyntax/Structure.java 2009-03-03 07:42:18 UTC (rev 1457)
@@ -71,7 +71,7 @@
/**
* Create a structure with a defined number of terms.
*
- * It is used by list term and atom to not create the array list for terms.
+ * It is used by list term, plan body, ... to not create the array list for terms.
*/
public Structure(String functor, int termsSize) {
super(functor);
@@ -126,8 +126,9 @@
return true;
}
- if (t instanceof Atom) {
- return super.equals(t);
+ if (t instanceof Atom && this.isAtom()) {
+ // consider atom equals only when this is an atom
+ return super.equals(t);
}
return false;
}
Modified: trunk/src/jason/stdlib/foreach.java
===================================================================
--- trunk/src/jason/stdlib/foreach.java 2009-03-02 15:20:39 UTC (rev 1456)
+++ trunk/src/jason/stdlib/foreach.java 2009-03-03 07:42:18 UTC (rev 1457)
@@ -112,12 +112,15 @@
checkArguments(args);
// get all solutions for the loop
- // Note: you should get all solutions here, otherwise I concurrent modification will occur for the iterator
+ // Note: you should get all solutions here, otherwise a concurrent modification will occur for the iterator
LogicalFormula logExpr = (LogicalFormula)args[0];
iu = logExpr.logicalConsequence(ts.getAg(), un.clone());
List<Unifier> allsol = new ArrayList<Unifier>();
while (iu.hasNext())
allsol.add(iu.next());
+
+ if (allsol.isEmpty()) // none iteration
+ return true;
iu = allsol.iterator();
((Structure)foria.getBodyTerm()).addTerm(new ObjectTermImpl(iu));
} else if (args.length == 3) {
@@ -127,15 +130,18 @@
throw JasonException.createWrongArgumentNb(this);
}
- if (iu.hasNext()) {
- un.clear();
- un.compose(iu.next());
- PlanBody whattoadd = (PlanBody)args[1].clone();
+ un.clear();
+ un.compose(iu.next());
+
+ // add in the current intention:
+ // 1. the body argument of for and
+ // 2. a copy of the for internal action after the execution of the body
+ // (to perform the next iteration)
+ PlanBody whattoadd = (PlanBody)args[1].clone();
+ if (iu.hasNext())
whattoadd.add(new PlanBodyImpl(BodyType.internalAction, foria.getBodyTerm().clone()));
- whattoadd.setAsBodyTerm(false);
- foria.add(1,whattoadd);
- //System.out.println("new body="+foria.getBodyNext());
- }
+ whattoadd.setAsBodyTerm(false);
+ foria.add(1,whattoadd);
return true;
}
}
Modified: trunk/src/jason/stdlib/loop.java
===================================================================
--- trunk/src/jason/stdlib/loop.java 2009-03-02 15:20:39 UTC (rev 1456)
+++ trunk/src/jason/stdlib/loop.java 2009-03-03 07:42:18 UTC (rev 1457)
@@ -111,18 +111,20 @@
throw JasonException.createWrongArgumentNb(this);
}
- LogicalFormula logExpr = (LogicalFormula)args[0]; //.clone();
- //logExpr.apply(un); // need to apply since the internal action literal for while does not apply
+ LogicalFormula logExpr = (LogicalFormula)args[0];
+ // perform one iteration of the loop
Iterator<Unifier> iu = logExpr.logicalConsequence(ts.getAg(), un);
if (iu.hasNext()) {
-
un.compose(iu.next());
- PlanBody whattoadd = (PlanBody)args[1]; //.clone();
- whattoadd.add(new PlanBodyImpl(BodyType.internalAction, whileia.getBodyTerm().clone())); //(PlanBody)whileia.clone()); // add the while after
+ // add in the current intention:
+ // 1. the body argument and
+ // 2. a copy of the while internal action after the execution of the body
+ // (to test the loop again)
+ PlanBody whattoadd = (PlanBody)args[1];
+ whattoadd.add(new PlanBodyImpl(BodyType.internalAction, whileia.getBodyTerm().clone()));
whattoadd.setAsBodyTerm(false);
whileia.add(1,whattoadd);
- //System.out.println("new body="+whileia.getBodyNext());
}
return true;
}
Modified: trunk/src/jason/stdlib/term2string.java
===================================================================
--- trunk/src/jason/stdlib/term2string.java 2009-03-02 15:20:39 UTC (rev 1456)
+++ trunk/src/jason/stdlib/term2string.java 2009-03-03 07:42:18 UTC (rev 1457)
@@ -22,9 +22,9 @@
</ul>
<p>Examples:<ul>
- <li> <code>.substring(b,"b")</code>: true.
- <li> <code>.substring(b,X)</code>: unifies X to "b".
- <li> <code>.substring(X,"b")</code>: unified X to b.
+ <li> <code>.term2string(b,"b")</code>: true.
+ <li> <code>.term2string(b,X)</code>: unifies X with "b".
+ <li> <code>.term2string(X,"b")</code>: unified X with b.
</ul>
@see jason.stdlib.concat
Modified: trunk/src/test/TermTest.java
===================================================================
--- trunk/src/test/TermTest.java 2009-03-02 15:20:39 UTC (rev 1456)
+++ trunk/src/test/TermTest.java 2009-03-03 07:42:18 UTC (rev 1457)
@@ -77,6 +77,7 @@
assertEquals(l3, l4);
Term tpos = new Atom("pos");
+ assertFalse(l3.isAtom());
assertFalse(l3.equals(tpos));
assertFalse(tpos.equals(l3));
//System.out.println(new Term("pos")+"="+l3+" --> "+new Term("pos").equals(l3));
@@ -301,6 +302,7 @@
assertFalse(u.unifies(lp, a));
assertFalse(u.unifies(ln, a));
assertTrue(u.unifies(a, Literal.parseLiteral("s")));
+ assertTrue(Literal.parseLiteral("s").isAtom());
assertTrue(Literal.parseLiteral("s").equals(a));
assertTrue(u.unifies(Literal.parseLiteral("s"), a));
assertFalse(u.unifies(Literal.parseLiteral("~s"), a));
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-03-09 15:03:13
|
Revision: 1458
http://jason.svn.sourceforge.net/jason/?rev=1458&view=rev
Author: jomifred
Date: 2009-03-09 15:03:05 +0000 (Mon, 09 Mar 2009)
Log Message:
-----------
extends plan body term (enclosed by { }) to support also plans.
add_plan uses this new syntax to avoid using strings to represent the new plan
.add_plan({ +te : c <- a1; !g2 }); ....
Modified Paths:
--------------
trunk/applications/jasdl-owlapi/src/jasdl/asSyntax/SEPlan.java
trunk/src/jason/asSemantics/Unifier.java
trunk/src/jason/asSyntax/Plan.java
trunk/src/jason/asSyntax/PlanBodyImpl.java
trunk/src/jason/asSyntax/PlanLibrary.java
trunk/src/jason/asSyntax/Trigger.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/jason/stdlib/add_plan.java
trunk/src/test/ASParserTest.java
trunk/src/test/StdLibTest.java
trunk/src/test/TSTest.java
trunk/src/test/TermTest.java
Added Paths:
-----------
trunk/src/jason/stdlib/list_plans.java
Modified: trunk/applications/jasdl-owlapi/src/jasdl/asSyntax/SEPlan.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/asSyntax/SEPlan.java 2009-03-03 07:42:18 UTC (rev 1457)
+++ trunk/applications/jasdl-owlapi/src/jasdl/asSyntax/SEPlan.java 2009-03-09 15:03:05 UTC (rev 1458)
@@ -26,8 +26,8 @@
import jason.asSyntax.Literal;
import jason.asSyntax.LiteralImpl;
import jason.asSyntax.Plan;
-import jason.asSyntax.PlanBody;
import jason.asSyntax.Structure;
+import jason.asSyntax.Term;
import jason.asSyntax.Trigger;
/**
@@ -98,7 +98,7 @@
}
@Override
- public Object clone() {
+ public Term clone() {
return new SEPlan(agent, (Plan) super.clone());
}
Modified: trunk/src/jason/asSemantics/Unifier.java
===================================================================
--- trunk/src/jason/asSemantics/Unifier.java 2009-03-03 07:42:18 UTC (rev 1457)
+++ trunk/src/jason/asSemantics/Unifier.java 2009-03-09 15:03:05 UTC (rev 1458)
@@ -76,16 +76,6 @@
return vl;
}
- /*
- public Term get(Term t) {
- if (t.isVar()) {
- return function.get( deref((VarTerm) t));
- } else {
- return null;
- }
- }
- */
-
public boolean unifies(Trigger te1, Trigger te2) {
return te1.sameType(te2) && unifies(te1.getLiteral(), te2.getLiteral());
}
Modified: trunk/src/jason/asSyntax/Plan.java
===================================================================
--- trunk/src/jason/asSyntax/Plan.java 2009-03-03 07:42:18 UTC (rev 1457)
+++ trunk/src/jason/asSyntax/Plan.java 2009-03-09 15:03:05 UTC (rev 1458)
@@ -28,10 +28,6 @@
import java.io.Serializable;
import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -39,7 +35,8 @@
import org.w3c.dom.Element;
/** Represents an AgentSpack plan
-
+ (it extends structure to be used as a term)
+
@navassoc - label - Pred
@navassoc - event - Trigger
@navassoc - context - LogicalFormula
@@ -47,7 +44,7 @@
@navassoc - source - SourceInfo
*/
-public class Plan implements Cloneable, Serializable {
+public class Plan extends Structure implements Cloneable, Serializable {
private static final long serialVersionUID = 1L;
private static final Term TAtomic = ASSyntax.createAtom("atomic");
@@ -61,18 +58,18 @@
private LogicalFormula context;
private PlanBody body;
- protected SourceInfo srcInfo = null;
-
- private boolean isAtomic = false;
- private boolean isAllUnifs = false;
+ private boolean isAtomic = false;
+ private boolean isAllUnifs = false;
private boolean hasBreakpoint = false;
// used by clone
public Plan() {
+ super("plan", 0);
}
// used by parser
public Plan(Pred label, Trigger te, LogicalFormula ct, PlanBody bd) {
+ super("plan", 0);
tevent = te;
setLabel(label);
setContext(ct);
@@ -82,6 +79,24 @@
body = bd;
}
+ @Override
+ public int getArity() {
+ return 4;
+ }
+
+ private static final Term noLabelAtom = new Atom("nolabel");
+
+ @Override
+ public Term getTerm(int i) {
+ switch (i) {
+ case 0: return (label == null) ? noLabelAtom : label;
+ case 1: return tevent;
+ case 2: return (context == null) ? Literal.LTrue : context;
+ case 3: return body;
+ default: return null;
+ }
+ }
+
public void setLabel(Pred p) {
label = p;
if (p != null && p.hasAnnot()) {
@@ -172,32 +187,8 @@
}
return false;
}
-
- public List<VarTerm> getSingletonVars() {
- Map<VarTerm, Integer> all = new HashMap<VarTerm, Integer>();
- tevent.getLiteral().countVars(all);
- if (context != null)
- context.countVars(all);
- body.countVars(all);
-
- List<VarTerm> r = new ArrayList<VarTerm>();
- for (VarTerm k: all.keySet()) {
- if (all.get(k) == 1 && !k.isUnnamedVar())
- r.add(k);
- }
- return r;
- }
-
- @Override
- public int hashCode() {
- int code = 37;
- if (context != null) code += context.hashCode();
- if (tevent != null) code += tevent.hashCode();
- code += body.hashCode();
- return code;
- }
-
- public Object clone() {
+
+ public Term clone() {
Plan p = new Plan();
if (label != null) {
p.label = (Pred) label.clone();
@@ -237,15 +228,6 @@
return p;
}
-
- public SourceInfo getSrcInfo() {
- return srcInfo;
- }
-
- public void setSrcInfo(SourceInfo s) {
- srcInfo = s;
- }
-
public String toString() {
return toASString();
}
Modified: trunk/src/jason/asSyntax/PlanBodyImpl.java
===================================================================
--- trunk/src/jason/asSyntax/PlanBodyImpl.java 2009-03-03 07:42:18 UTC (rev 1457)
+++ trunk/src/jason/asSyntax/PlanBodyImpl.java 2009-03-09 15:03:05 UTC (rev 1458)
@@ -45,9 +45,10 @@
formType = t;
if (b != null) {
srcInfo = b.getSrcInfo();
- if (b.isAtom()) {
- b = ((Atom)b).forceFullLiteralImpl();
- }
+ // the atom issue is solved in TS
+ //if (b.isAtom()) {
+ // b = ((Atom)b).forceFullLiteralImpl();
+ //}
}
term = b;
}
Modified: trunk/src/jason/asSyntax/PlanLibrary.java
===================================================================
--- trunk/src/jason/asSyntax/PlanLibrary.java 2009-03-03 07:42:18 UTC (rev 1457)
+++ trunk/src/jason/asSyntax/PlanLibrary.java 2009-03-09 15:03:05 UTC (rev 1458)
@@ -67,12 +67,13 @@
/**
* Add a new plan written as a String. The source
* normally is "self" or the agent that sent this plan.
- * If the already has a plan equals to "stPlan", only a
+ * If the PL already has a plan equals to "stPlan", only a
* new source is added.
*
* The plan is added in the end of the PlanLibrary.
*
* @returns the plan just added
+ * @deprecated parse the plan before (ASSyntax methods) and call add(Plan, ...) methods
*/
public Plan add(StringTerm stPlan, Term tSource) throws ParseException, JasonException {
return add(stPlan, tSource, false);
@@ -81,7 +82,7 @@
/**
* Add a new plan written as a String. The source
* normally is "self" or the agent that sent this plan.
- * If the already has a plan equals to "stPlan", only a
+ * If the PL already has a plan equals to "stPlan", only a
* new source is added.
*
* If <i>before</i> is true, the plan will be added in the
@@ -89,6 +90,7 @@
* the end.
*
* @returns the plan just added
+ * @deprecated parse the plan before (ASSyntax methods) and call add(Plan, ...) methods
*/
public Plan add(StringTerm stPlan, Term tSource, boolean before) throws ParseException, JasonException {
String sPlan = stPlan.getString();
@@ -100,23 +102,38 @@
}
}
sPlan = sTemp.toString();
- Plan p = ASSyntax.parsePlan(sPlan); //Plan.parse(sPlan);
+ Plan p = ASSyntax.parsePlan(sPlan);
+ return add(p,tSource,before);
+ }
+
+
+ /**
+ * Add a new plan in PL. The source
+ * normally is "self" or the agent that sent this plan.
+ * If the PL already has a plan equals to the parameter p, only a
+ * new source is added.
+ *
+ * If <i>before</i> is true, the plan will be added in the
+ * begin of the PlanLibrary; otherwise, it is added in
+ * the end.
+ *
+ * @returns the plan just added
+ */
+ public Plan add(Plan p, Term source, boolean before) throws JasonException {
int i = plans.indexOf(p);
if (i < 0) {
// add label, if necessary
- if (p.getLabel() == null) {
+ if (p.getLabel() == null)
p.setLabel(getUniqueLabel());
- }
- p.getLabel().addSource(tSource);
+ p.getLabel().addSource(source);
add(p, before);
} else {
p = plans.get(i);
- p.getLabel().addSource(tSource);
+ p.getLabel().addSource(source);
}
return p;
}
-
public void add(Plan p) throws JasonException {
add(p,false);
}
@@ -147,7 +164,8 @@
p.setLabel(getUniqueLabel());
// add self source
- if (!p.getLabel().hasSource()) p.getLabel().addAnnot(BeliefBase.TSelf);
+ if (!p.getLabel().hasSource())
+ p.getLabel().addAnnot(BeliefBase.TSelf);
planLabels.put(p.getLabel().getFunctor(), p);
Modified: trunk/src/jason/asSyntax/Trigger.java
===================================================================
--- trunk/src/jason/asSyntax/Trigger.java 2009-03-03 07:42:18 UTC (rev 1457)
+++ trunk/src/jason/asSyntax/Trigger.java 2009-03-09 15:03:05 UTC (rev 1458)
@@ -35,19 +35,21 @@
import org.w3c.dom.Element;
/**
- * Represents an AgentSpeak trigger (like +!g, +p, ...).
- *
- * It is composed by:
- * an operator (+ or -);
- * a type (<empty>, !, or ?);
- * a literal
- *
- * @opt attributes
- * @navassoc - literal - Literal
- * @navassoc - operator - TEOperator
- * @navassoc - type - TEType
- */
-public class Trigger implements Cloneable {
+ Represents an AgentSpeak trigger (like +!g, +p, ...).
+
+ It is composed by:
+ an operator (+ or -);
+ a type (<empty>, !, or ?);
+ a literal
+
+ (it extends structure to be used as a term)
+
+ @opt attributes
+ @navassoc - literal - Literal
+ @navassoc - operator - TEOperator
+ @navassoc - type - TEType
+*/
+public class Trigger extends Structure implements Cloneable {
private static Logger logger = Logger.getLogger(Trigger.class.getName());
@@ -62,16 +64,17 @@
test { public String toString() { return "?"; } }
};
+
private TEOperator operator = TEOperator.add;
private TEType type = TEType.belief;
private Literal literal;
- private PredicateIndicator piCache = null;
-
public Trigger(TEOperator op, TEType t, Literal l) {
+ super("te", 0);
literal = l;
type = t;
setTrigOp(op);
+ setSrcInfo(l.getSrcInfo());
}
/** prefer to use ASSyntax.parseTrigger */
@@ -85,9 +88,45 @@
}
}
+ // override some structure methods
+ @Override
+ public int getArity() {
+ return 2;
+ }
+
+ private static final Term ab = new StringTermImpl("+");
+ private static final Term rb = new StringTermImpl("-");
+ private static final Term ag = new StringTermImpl("+!");
+ private static final Term rg = new StringTermImpl("-!");
+ private static final Term at = new StringTermImpl("+?");
+ private static final Term rt = new StringTermImpl("-?");
+
+ @Override
+ public Term getTerm(int i) {
+ switch (1) {
+ case 0:
+ switch (operator) {
+ case add:
+ switch (type) {
+ case belief: return ab;
+ case achieve: return ag;
+ case test: return at;
+ }
+ case del:
+ switch (type) {
+ case belief: return rb;
+ case achieve: return rg;
+ case test: return rt;
+ }
+ }
+ case 1: return literal;
+ default: return null;
+ }
+ }
+
public void setTrigOp(TEOperator op) {
operator = op;
- piCache = null;
+ predicateIndicatorCache = null;
}
public boolean sameType(Trigger e) {
@@ -103,11 +142,6 @@
return false;
}
- @Override
- public int hashCode() {
- return getPredicateIndicator().hashCode();
- }
-
public boolean isAchvGoal() {
return type == TEType.achieve;
}
@@ -121,21 +155,22 @@
}
public boolean isAddition() {
- return (operator == TEOperator.add);
+ return operator == TEOperator.add;
}
public Trigger clone() {
Trigger c = new Trigger(operator, type, literal.copy());
- c.piCache = this.piCache;
+ c.predicateIndicatorCache = this.predicateIndicatorCache;
return c;
}
/** return [+|-][!|?] super.getPredicateIndicator */
+ @Override
public PredicateIndicator getPredicateIndicator() {
- if (piCache == null) {
- piCache = new PredicateIndicator(operator.toString() + type + literal.getFunctor(), literal.getArity());
+ if (predicateIndicatorCache == null) {
+ predicateIndicatorCache = new PredicateIndicator(operator.toString() + type + literal.getFunctor(), literal.getArity());
}
- return piCache;
+ return predicateIndicatorCache;
}
public boolean apply(Unifier u) {
@@ -146,8 +181,9 @@
return literal;
}
- public void setLiteral(Literal literal) {
+ public void setLiteral(Literal literal) {
this.literal = literal;
+ predicateIndicatorCache = null;
}
public String toString() {
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2009-03-03 07:42:18 UTC (rev 1457)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2009-03-09 15:03:05 UTC (rev 1458)
@@ -357,14 +357,50 @@
}
}
-PlanBody plan_body_term(): { PlanBody B = null; }
+
+Term plan_term(): { Trigger T = null; Object C = null; PlanBody B = null, B1 = null; Plan P = null; boolean pb = true; Pred L = null; }
+ // pb = "only plan body"
{
"{"
- B = plan_body()
+ [ [<TK_LABEL_AT> L=pred() { pb = false; } ]
+ T = trigger() { if (T.getType() != TEType.belief) pb = false; }
+ [ ":" C = log_expr() { pb = false; } ]
+ [( "<-" { pb = false; }
+ | ";" { if (!pb) throw new ParseException(getSourceRef(T)+" Wrong place for ';'"); }
+ )
+ ]
+ ]
+ [ B = plan_body() ]
"}"
- { B.setAsBodyTerm(true);
- return B;
- }
+ {
+ if (T != null) {
+ // handle the case of "+a1", parsed as TE, need to be changed to plan's body
+ // handle the case of "+a1; +a2", parsed as "TE; Body"
+ if (pb) {
+ if (T.isAddition())
+ B1 = new PlanBodyImpl(BodyType.addBel, T.getLiteral());
+ else
+ B1 = new PlanBodyImpl(BodyType.delBel, T.getLiteral());
+ B1.setAsBodyTerm(true);
+ if (B != null)
+ B1.setBodyNext(B);
+ return B1;
+ }
+ if (C == null && B == null) {
+ // handle the case of a single trigger
+ return T;
+ } else {
+ // handle the case of a entire plan
+ Plan p = new Plan(L,T,(LogicalFormula)C, B);
+ p.setSrcInfo(T.getSrcInfo());
+ return p;
+ }
+ }
+
+ // the case of a simple plan body term
+ B.setAsBodyTerm(true);
+ return B;
+ }
}
@@ -438,7 +474,7 @@
}
/* Annotated Formulae */
-Pred pred() : { Token K; Pred p; List l; ListTerm lt; PlanBody b; }
+Pred pred() : { Token K; Pred p; List l; ListTerm lt; Term b; }
{
(
K=<ATOM>
@@ -454,7 +490,7 @@
"(" l = terms()
")" { p.setTerms(l); }
]
- ( b=plan_body_term() { p.addTerm(b); }
+ ( b=plan_term() { p.addTerm(b); }
)*
[
lt = list() { p.setAnnots(lt); }
@@ -478,7 +514,7 @@
Term term() : { Object o; }
{
( o=list()
- | o=plan_body_term()
+ | o=plan_term()
| o=log_expr() // log_expr includes literals/atoms/structures
)
{ return changeToAtom(o); }
@@ -506,7 +542,8 @@
{
( o=list()
| o=arithm_expr()
- | o=string()
+ | o=string()
+ | o=plan_term()
)
{ return changeToAtom(o); }
}
@@ -570,7 +607,7 @@
( op2 = arithm_expr()
| op2 = string()
| op2 = list()
- | op2 = plan_body_term()
+ | op2 = plan_term()
)
{ if ( ((Term)op1).isInternalAction() && operator != RelationalOp.literalBuilder)
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2009-03-03 07:42:18 UTC (rev 1457)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2009-03-09 15:03:05 UTC (rev 1458)
@@ -457,11 +457,112 @@
throw new Error("Missing return statement in function");
}
- final public PlanBody plan_body_term() throws ParseException {
- PlanBody B = null;
+ final public Term plan_term() throws ParseException {
+ Trigger T = null; Object C = null; PlanBody B = null, B1 = null; Plan P = null; boolean pb = true; Pred L = null;
jj_consume_token(27);
- B = plan_body();
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case TK_LABEL_AT:
+ case 34:
+ case 35:
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case TK_LABEL_AT:
+ jj_consume_token(TK_LABEL_AT);
+ L = pred();
+ pb = false;
+ break;
+ default:
+ jj_la1[18] = jj_gen;
+ ;
+ }
+ T = trigger();
+ if (T.getType() != TEType.belief) pb = false;
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 32:
+ jj_consume_token(32);
+ C = log_expr();
+ pb = false;
+ break;
+ default:
+ jj_la1[19] = jj_gen;
+ ;
+ }
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 33:
+ case 37:
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 33:
+ jj_consume_token(33);
+ pb = false;
+ break;
+ case 37:
+ jj_consume_token(37);
+ if (!pb) {if (true) throw new ParseException(getSourceRef(T)+" Wrong place for ';'");}
+ break;
+ default:
+ jj_la1[20] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ break;
+ default:
+ jj_la1[21] = jj_gen;
+ ;
+ }
+ break;
+ default:
+ jj_la1[22] = jj_gen;
+ ;
+ }
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ 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 31:
+ case 34:
+ case 35:
+ case 36:
+ case 38:
+ case 39:
+ B = plan_body();
+ break;
+ default:
+ jj_la1[23] = jj_gen;
+ ;
+ }
jj_consume_token(28);
+ if (T != null) {
+ // handle the case of "+a1", parsed as TE, need to be changed to plan's body
+ // handle the case of "+a1; +a2", parsed as "TE; Body"
+ if (pb) {
+ if (T.isAddition())
+ B1 = new PlanBodyImpl(BodyType.addBel, T.getLiteral());
+ else
+ B1 = new PlanBodyImpl(BodyType.delBel, T.getLiteral());
+ B1.setAsBodyTerm(true);
+ if (B != null)
+ B1.setBodyNext(B);
+ {if (true) return B1;}
+ }
+ if (C == null && B == null) {
+ // handle the case of a single trigger
+ {if (true) return T;}
+ } else {
+ // handle the case of a entire plan
+ Plan p = new Plan(L,T,(LogicalFormula)C, B);
+ p.setSrcInfo(T.getSrcInfo());
+ {if (true) return p;}
+ }
+ }
+
+ // the case of a simple plan body term
B.setAsBodyTerm(true);
{if (true) return B;}
throw new Error("Missing return statement in function");
@@ -501,18 +602,18 @@
formType = BodyType.delAddBel;
break;
default:
- jj_la1[18] = jj_gen;
+ jj_la1[24] = jj_gen;
;
}
break;
default:
- jj_la1[19] = jj_gen;
+ jj_la1[25] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
break;
default:
- jj_la1[20] = jj_gen;
+ jj_la1[26] = jj_gen;
;
}
B = log_expr();
@@ -549,7 +650,7 @@
type = Literal.LNeg;
break;
default:
- jj_la1[21] = jj_gen;
+ jj_la1[27] = jj_gen;
;
}
F = pred();
@@ -584,7 +685,7 @@
{if (true) return Literal.LFalse;}
break;
default:
- jj_la1[22] = jj_gen;
+ jj_la1[28] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -593,7 +694,7 @@
/* Annotated Formulae */
final public Pred pred() throws ParseException {
- Token K; Pred p; List l; ListTerm lt; PlanBody b;
+ Token K; Pred p; List l; ListTerm lt; Term b;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ATOM:
K = jj_consume_token(ATOM);
@@ -605,7 +706,7 @@
K = jj_consume_token(TK_END);
break;
default:
- jj_la1[23] = jj_gen;
+ jj_la1[29] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -619,7 +720,7 @@
p.setTerms(l);
break;
default:
- jj_la1[24] = jj_gen;
+ jj_la1[30] = jj_gen;
;
}
label_9:
@@ -629,10 +730,10 @@
;
break;
default:
- jj_la1[25] = jj_gen;
+ jj_la1[31] = jj_gen;
break label_9;
}
- b = plan_body_term();
+ b = plan_term();
p.addTerm(b);
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
@@ -641,7 +742,7 @@
p.setAnnots(lt);
break;
default:
- jj_la1[26] = jj_gen;
+ jj_la1[32] = jj_gen;
;
}
{if (true) return p;}
@@ -660,7 +761,7 @@
;
break;
default:
- jj_la1[27] = jj_gen;
+ jj_la1[33] = jj_gen;
break label_10;
}
jj_consume_token(41);
@@ -679,7 +780,7 @@
o = list();
break;
case 27:
- o = plan_body_term();
+ o = plan_term();
break;
case VAR:
case TK_TRUE:
@@ -697,7 +798,7 @@
o = log_expr();
break;
default:
- jj_la1[28] = jj_gen;
+ jj_la1[34] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -719,6 +820,7 @@
case STRING:
case ATOM:
case UNNAMEDVAR:
+ case 27:
case 35:
case 39:
case 42:
@@ -731,7 +833,7 @@
;
break;
default:
- jj_la1[29] = jj_gen;
+ jj_la1[35] = jj_gen;
break label_11;
}
jj_consume_token(41);
@@ -755,18 +857,18 @@
last = last.concat((ListTerm)f);
break;
default:
- jj_la1[30] = jj_gen;
+ jj_la1[36] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
break;
default:
- jj_la1[31] = jj_gen;
+ jj_la1[37] = jj_gen;
;
}
break;
default:
- jj_la1[32] = jj_gen;
+ jj_la1[38] = jj_gen;
;
}
jj_consume_token(44);
@@ -797,8 +899,11 @@
case STRING:
o = string();
break;
+ case 27:
+ o = plan_term();
+ break;
default:
- jj_la1[33] = jj_gen;
+ jj_la1[39] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -817,7 +922,7 @@
{if (true) return new LogExpr((LogicalFormula)t1,LogicalOp.or,(LogicalFormula)t2);}
break;
default:
- jj_la1[34] = jj_gen;
+ jj_la1[40] = jj_gen;
;
}
{if (true) return t1;}
@@ -834,7 +939,7 @@
{if (true) return new LogExpr((LogicalFormula)t1,LogicalOp.and,(LogicalFormula)t2);}
break;
default:
- jj_la1[35] = jj_gen;
+ jj_la1[41] = jj_gen;
;
}
{if (true) return t1;}
@@ -865,7 +970,7 @@
{if (true) return t;}
break;
default:
- jj_la1[36] = jj_gen;
+ jj_la1[42] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -901,7 +1006,7 @@
op1 = string();
break;
default:
- jj_la1[37] = jj_gen;
+ jj_la1[43] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -948,7 +1053,7 @@
operator = RelationalOp.literalBuilder;
break;
default:
- jj_la1[38] = jj_gen;
+ jj_la1[44] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -973,10 +1078,10 @@
op2 = list();
break;
case 27:
- op2 = plan_body_term();
+ op2 = plan_term();
break;
default:
- jj_la1[39] = jj_gen;
+ jj_la1[45] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -987,7 +1092,7 @@
{if (true) return new RelExpr((Term)op1, operator, (Term)op2);}
break;
default:
- jj_la1[40] = jj_gen;
+ jj_la1[46] = jj_gen;
;
}
{if (true) return op1;}
@@ -1012,7 +1117,7 @@
op = ArithmeticOp.minus;
break;
default:
- jj_la1[41] = jj_gen;
+ jj_la1[47] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1026,7 +1131,7 @@
{if (true) return new ArithExpr((NumberTerm)t1, op, (NumberTerm)t2);}
break;
default:
- jj_la1[42] = jj_gen;
+ jj_la1[48] = jj_gen;
;
}
{if (true) return t1;}
@@ -1060,7 +1165,7 @@
op = ArithmeticOp.mod;
break;
default:
- jj_la1[43] = jj_gen;
+ jj_la1[49] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1074,7 +1179,7 @@
{if (true) return new ArithExpr((NumberTerm)t1, op, (NumberTerm)t2);}
break;
default:
- jj_la1[44] = jj_gen;
+ jj_la1[50] = jj_gen;
;
}
{if (true) return t1;}
@@ -1099,7 +1204,7 @@
{if (true) return new ArithExpr((NumberTerm)t1, op, (NumberTerm)t2);}
break;
default:
- jj_la1[45] = jj_gen;
+ jj_la1[51] = jj_gen;
;
}
{if (true) return t1;}
@@ -1144,7 +1249,7 @@
{if (true) return t;}
break;
default:
- jj_la1[46] = jj_gen;
+ jj_la1[52] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
...
[truncated message content] |
|
From: <jom...@us...> - 2009-03-09 21:42:48
|
Revision: 1460
http://jason.svn.sourceforge.net/jason/?rev=1460&view=rev
Author: jomifred
Date: 2009-03-09 21:42:29 +0000 (Mon, 09 Mar 2009)
Log Message:
-----------
change .plan_label to use 'plan term'
Modified Paths:
--------------
trunk/demos/communication/bob.asl
trunk/src/asl/kqmlPlans.asl
trunk/src/jason/stdlib/add_plan.java
trunk/src/jason/stdlib/plan_label.java
Modified: trunk/demos/communication/bob.asl
===================================================================
--- trunk/demos/communication/bob.asl 2009-03-09 15:33:35 UTC (rev 1459)
+++ trunk/demos/communication/bob.asl 2009-03-09 21:42:29 UTC (rev 1460)
@@ -49,8 +49,8 @@
.println("Asking Maria to unachieve 'hello'");
.send(maria,unachieve, hello(bob));
- // send untell how to maria
- .send(maria,untellHow,hp).
+ // send untell how to maria
+ .send(maria,untellHow,hp).
+vl(X)[source(A)]
Modified: trunk/src/asl/kqmlPlans.asl
===================================================================
--- trunk/src/asl/kqmlPlans.asl 2009-03-09 15:33:35 UTC (rev 1459)
+++ trunk/src/asl/kqmlPlans.asl 2009-03-09 21:42:29 UTC (rev 1460)
@@ -112,5 +112,11 @@
// the triggering event
@kqmlReceivedAskHow
+!kqml_received(Sender, askHow, Content, MsgId)
- <- .relevant_plans(Content, ListAsString);
- .send(Sender, tellHow, ListAsString, MsgId).
+ <- .relevant_plans(Content, ListOfPlans);
+ .send(Sender, tellHow, ListOfPlans, MsgId).
+
+/* general communication error handler */
+
+@kqmlError
+-!kqml_received(Sender, Per, Content, MsgId)[error(EID), error_msg(EMsg)]
+ <- .print("Communication error -- ",EID, ": ", EMsg).
Modified: trunk/src/jason/stdlib/add_plan.java
===================================================================
--- trunk/src/jason/stdlib/add_plan.java 2009-03-09 15:33:35 UTC (rev 1459)
+++ trunk/src/jason/stdlib/add_plan.java 2009-03-09 21:42:29 UTC (rev 1460)
@@ -32,6 +32,7 @@
import jason.asSyntax.Plan;
import jason.asSyntax.StringTerm;
import jason.asSyntax.Term;
+import jason.asSyntax.VarTerm;
import jason.asSyntax.parser.ParseException;
import jason.bb.BeliefBase;
@@ -134,8 +135,10 @@
p = ASSyntax.parsePlan(sPlan);
} else if (t instanceof Plan) {
p = (Plan)t;
+ } else if (t instanceof VarTerm && ((VarTerm)t).hasValue() && ((VarTerm)t).getValue() instanceof Plan) {
+ p = (Plan)((VarTerm)t).getValue();
} else {
- throw JasonException.createWrongArgument(this, "The term '"+t+"' can not be used as a plan for .add_plan.");
+ throw JasonException.createWrongArgument(this, "The term '"+t+"' ("+t.getClass().getSimpleName()+") can not be used as a plan for .add_plan.");
}
return p;
Modified: trunk/src/jason/stdlib/plan_label.java
===================================================================
--- trunk/src/jason/stdlib/plan_label.java 2009-03-09 15:33:35 UTC (rev 1459)
+++ trunk/src/jason/stdlib/plan_label.java 2009-03-09 21:42:29 UTC (rev 1460)
@@ -28,18 +28,19 @@
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Plan;
-import jason.asSyntax.StringTermImpl;
import jason.asSyntax.Term;
/**
<p>Internal action: <b><code>.plan_label(<i>P</i>,<i>L</i>)</code></b>.
- <p>Description: unifies <i>P</i> with a string representing the plan
+ <p>Description: unifies <i>P</i> with a <i>plan term</i> representing the plan
labeled with the term <i>L</i> within the agent's plan library.
<p>Parameters:<ul>
- <li>- plan (string): the string representing the plan.<br/>
+ <li>- plan (plan term): the term representing the plan, it is
+ a plan enclosed by { and }
+ (e.g. <code>{+!g : vl(X) <- .print(X)}</code>).<br/>
<li>+ label (structure): the label of that plan.<br/>
@@ -47,8 +48,8 @@
<p>Example:<ul>
- <li> <code>.plan_label(P,p1)</code>: unifies P with the string
- representation of the plan labelled <code>p1</code>.</li>
+ <li> <code>.plan_label(P,p1)</code>: unifies P with the term
+ representation of the plan labeled <code>p1</code>.</li>
</ul>
@@ -78,8 +79,9 @@
if (p != null) {
p = (Plan)p.clone();
p.getLabel().delSources();
- String ps = p.toASString().replaceAll("\"", "\\\\\"");
- return un.unifies(new StringTermImpl(ps), args[0]);
+ //String ps = p.toASString().replaceAll("\"", "\\\\\"");
+ //return un.unifies(new StringTermImpl(ps), args[0]);
+ return un.unifies(p, args[0]);
} else {
return false;
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-03-10 13:04:40
|
Revision: 1462
http://jason.svn.sourceforge.net/jason/?rev=1462&view=rev
Author: jomifred
Date: 2009-03-10 13:04:16 +0000 (Tue, 10 Mar 2009)
Log Message:
-----------
update .rel_plans to use plan terms and trigger terms
Modified Paths:
--------------
trunk/demos/communication/bob.asl
trunk/release-notes.txt
trunk/src/asl/kqmlPlans.asl
trunk/src/jason/asSyntax/Literal.java
trunk/src/jason/asSyntax/Trigger.java
trunk/src/jason/stdlib/list_plans.java
trunk/src/jason/stdlib/relevant_plans.java
trunk/src/jason/stdlib/remove_plan.java
Modified: trunk/demos/communication/bob.asl
===================================================================
--- trunk/demos/communication/bob.asl 2009-03-09 22:42:38 UTC (rev 1461)
+++ trunk/demos/communication/bob.asl 2009-03-10 13:04:16 UTC (rev 1462)
@@ -37,6 +37,16 @@
.send(maria, askOne, fullname, FN);
.println("Full name is ",FN);
+ // Ask maria plans to goto
+ .send(maria, askHow, {+!goto(_,_)[source(_)]});
+ .wait(500); // wait answer
+ .print("Received plans:");
+ .list_plans( {+!goto(_,_)[source(_)]} );
+ .print;
+ // another implementation (that do not include the received plans automaticaly in the PL)
+ .send(maria, askHow, {+!goto(_,_)[source(_)]}, ListOfPlans);
+ .print("Received plans by askHow: ", ListOfPlans);
+
// Send to maria a plan to achieve the goal hello
.plan_label(Plan,hp); // get a plans based on a plan's label
.println("Sending tell how: ",Plan);
Modified: trunk/release-notes.txt
===================================================================
--- trunk/release-notes.txt 2009-03-09 22:42:38 UTC (rev 1461)
+++ trunk/release-notes.txt 2009-03-10 13:04:16 UTC (rev 1462)
@@ -31,6 +31,7 @@
not be used.
- Some concurrent execution of .wait and .drop_desire/intention
does not work (the intention isn't dropped)
+- send askHow with 4th argument blocks the intention
---------------------------
Modified: trunk/src/asl/kqmlPlans.asl
===================================================================
--- trunk/src/asl/kqmlPlans.asl 2009-03-09 22:42:38 UTC (rev 1461)
+++ trunk/src/asl/kqmlPlans.asl 2009-03-10 13:04:16 UTC (rev 1462)
@@ -112,7 +112,7 @@
// the triggering event
@kqmlReceivedAskHow
+!kqml_received(Sender, askHow, Content, MsgId)
- <- .relevant_plans(Content, ListOfPlans);
+ <- .relevant_plans(Content, ListOfPlans);
.send(Sender, tellHow, ListOfPlans, MsgId).
/* general communication error handler */
Modified: trunk/src/jason/asSyntax/Literal.java
===================================================================
--- trunk/src/jason/asSyntax/Literal.java 2009-03-09 22:42:38 UTC (rev 1461)
+++ trunk/src/jason/asSyntax/Literal.java 2009-03-10 13:04:16 UTC (rev 1462)
@@ -117,8 +117,10 @@
public List<Term> getTerms() { return Structure.emptyTermList; }
/** returns all terms of this literal as an array */
public Term[] getTermsArray() { return getTerms().toArray(Structure.emptyTermArray); }
+
+ private static final List<VarTerm> emptyListVar = new ArrayList<VarTerm>();
/** returns all singleton vars (that appears once) in this literal */
- public List<VarTerm> getSingletonVars() { return new ArrayList<VarTerm>(); }
+ public List<VarTerm> getSingletonVars() { return emptyListVar; }
/** replaces all terms by unnamed variables (_). */
public void makeTermsAnnon() {}
Modified: trunk/src/jason/asSyntax/Trigger.java
===================================================================
--- trunk/src/jason/asSyntax/Trigger.java 2009-03-09 22:42:38 UTC (rev 1461)
+++ trunk/src/jason/asSyntax/Trigger.java 2009-03-10 13:04:16 UTC (rev 1462)
@@ -25,6 +25,8 @@
package jason.asSyntax;
import jason.asSemantics.Unifier;
+import jason.asSyntax.PlanBody.BodyType;
+import jason.asSyntax.parser.ParseException;
import jason.asSyntax.parser.as2j;
import java.io.StringReader;
@@ -190,6 +192,34 @@
return operator.toString() + type + literal;
}
+ /** try to convert the term t into a trigger, in case t is a trigger term, a string that can be parsed to a trigger, a var with value trigger, .... */
+ public static Trigger tryToGetTrigger(Term t) throws ParseException {
+ if (t instanceof Trigger) {
+ return (Trigger)t;
+ }
+ if (t instanceof VarTerm) {
+ VarTerm v = (VarTerm)t;
+ if (v.hasValue() && v.getValue() instanceof Trigger) {
+ return (Trigger)v.getValue();
+ }
+ if (v.hasValue() && v.getValue() instanceof Plan) {
+ return ((Plan)v.getValue()).getTrigger();
+ }
+ }
+ if (t.isString()) {
+ return ASSyntax.parseTrigger(((StringTerm)t).getString());
+ }
+ if (t.isPlanBody()) {
+ PlanBody p = (PlanBody)t;
+ if (p.getPlanSize() == 1) {
+ if (p.getBodyType() == BodyType.addBel)
+ return new Trigger(TEOperator.add, TEType.belief, (Literal)p.getBodyTerm());
+ if (p.getBodyType() == BodyType.delBel)
+ return new Trigger(TEOperator.del, TEType.belief, (Literal)p.getBodyTerm());
+ }
+ }
+ return null;
+ }
/** get as XML */
public Element getAsDOM(Document document) {
Modified: trunk/src/jason/stdlib/list_plans.java
===================================================================
--- trunk/src/jason/stdlib/list_plans.java 2009-03-09 22:42:38 UTC (rev 1461)
+++ trunk/src/jason/stdlib/list_plans.java 2009-03-10 13:04:16 UTC (rev 1462)
@@ -5,14 +5,21 @@
import jason.asSemantics.Unifier;
import jason.asSyntax.Plan;
import jason.asSyntax.Term;
+import jason.asSyntax.Trigger;
/** list all plans in PL */
public class list_plans extends DefaultInternalAction {
@Override public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
+ Trigger te = null;
+ if (args.length == 1 && args[0] instanceof Trigger)
+ te = Trigger.tryToGetTrigger(args[0]);
+
for (Plan p: ts.getAg().getPL()) {
if (!p.getLabel().toString().startsWith("kqml")) { // do not list kqml plans
- ts.getLogger().info(p.toString());
+ if (te == null || new Unifier().unifies(p.getTrigger(), te)) {
+ ts.getLogger().info(p.toString());
+ }
}
}
return true;
Modified: trunk/src/jason/stdlib/relevant_plans.java
===================================================================
--- trunk/src/jason/stdlib/relevant_plans.java 2009-03-09 22:42:38 UTC (rev 1461)
+++ trunk/src/jason/stdlib/relevant_plans.java 2009-03-10 13:04:16 UTC (rev 1462)
@@ -28,12 +28,9 @@
import jason.asSemantics.Option;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
-import jason.asSyntax.ASSyntax;
import jason.asSyntax.ListTerm;
import jason.asSyntax.ListTermImpl;
import jason.asSyntax.Plan;
-import jason.asSyntax.StringTerm;
-import jason.asSyntax.StringTermImpl;
import jason.asSyntax.Term;
import jason.asSyntax.Trigger;
import jason.asSyntax.parser.ParseException;
@@ -48,10 +45,10 @@
<p>Parameters:<ul>
- <li>+ trigger (string): the string representing the triggering event.</li>
+ <li>+ trigger (trigger): the triggering event, enclosed by { and }.</li>
- <li>- plans (list): the list of strings with the code of the relevant
- plans.</li>
+ <li>- plans (list of plan terms): the list of plan terms corresponding to
+ the code of the relevant plans.</li>
<li><i>- labels</i> (list, optional): the list of labels of the plans.</li>
@@ -59,11 +56,11 @@
<p>Example:<ul>
- <li> <code>.relevant_plans("+!go(X,Y)",LP)</code>: unifies LP with a list of
+ <li> <code>.relevant_plans({+!go(X,Y)},LP)</code>: unifies LP with a list of
all plans in the agent's plan library that are relevant for the triggering
event <code>+!go(X,Y)</code>.</li>
- <li> <code>.relevant_plans("+!go(X,Y)",LP, LL)</code>: same as above but also
+ <li> <code>.relevant_plans({+!go(X,Y)},LP, LL)</code>: same as above but also
unifies LL with a list of labels of plans in LP.</li>
</ul>
@@ -78,24 +75,18 @@
@Override public int getMinArgs() { return 2; }
@Override public int getMaxArgs() { return 3; }
-
- @Override
- protected void checkArguments(Term[] args) throws JasonException {
- super.checkArguments(args);
- if (!args[0].isString())
- throw JasonException.createWrongArgument(this,"first argument must be a string");
- }
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
checkArguments(args);
- Trigger te;
+ Trigger te = null;
try {
- te = ASSyntax.parseTrigger(((StringTerm) args[0]).getString());
- } catch (ParseException e) {
+ te = Trigger.tryToGetTrigger(args[0]);
+ } catch (ParseException e) {}
+ if (te == null)
throw JasonException.createWrongArgument(this,"first argument '"+args[0]+"' must follow the syntax of a trigger.");
- }
+
ListTerm labels = new ListTermImpl();
ListTerm lt = new ListTermImpl();
ListTerm last = lt;
@@ -107,9 +98,11 @@
if (np.getLabel() != null) {
np.getLabel().delSources();
}
- StringTerm stplan = new StringTermImpl(np.toASString().replaceAll("\\\"", "\\\\\""));
- last = last.append(stplan);
- if (args.length == 3) labels.add(np.getLabel());
+ //StringTerm stplan = new StringTermImpl(np.toASString().replaceAll("\\\"", "\\\\\""));
+ //last = last.append(stplan);
+ last = last.append(np);
+ if (args.length == 3)
+ labels.add(np.getLabel());
}
}
Modified: trunk/src/jason/stdlib/remove_plan.java
===================================================================
--- trunk/src/jason/stdlib/remove_plan.java 2009-03-09 22:42:38 UTC (rev 1461)
+++ trunk/src/jason/stdlib/remove_plan.java 2009-03-10 13:04:16 UTC (rev 1462)
@@ -66,9 +66,10 @@
by labels <code>l1[source(bob)]</code>, <code>l2[source(bob)]</code>, and
<code>l3[source(bob)]</code>.</li>
+ <li> <code>.relevant_plans({ +!g }, _, L); .remove_plan(LL)</code>:
+ removes all plans with trigger event <code>+!g</code>.</li>
</ul>
-
@see jason.stdlib.add_plan
@see jason.stdlib.plan_label
@see jason.stdlib.relevant_plans
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-03-10 17:14:22
|
Revision: 1463
http://jason.svn.sourceforge.net/jason/?rev=1463&view=rev
Author: jomifred
Date: 2009-03-10 17:14:12 +0000 (Tue, 10 Mar 2009)
Log Message:
-----------
use trigger term for .at
Modified Paths:
--------------
trunk/examples/contract-net-protocol/c.asl
trunk/src/jason/asSyntax/Plan.java
trunk/src/jason/asSyntax/PlanLibrary.java
trunk/src/jason/asSyntax/Trigger.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/jason/stdlib/at.java
trunk/src/jason/stdlib/plan_label.java
trunk/src/jason/stdlib/relevant_plans.java
trunk/src/test/ASParserTest.java
trunk/src/test/StdLibTest.java
Modified: trunk/examples/contract-net-protocol/c.asl
===================================================================
--- trunk/examples/contract-net-protocol/c.asl 2009-03-10 13:04:16 UTC (rev 1462)
+++ trunk/examples/contract-net-protocol/c.asl 2009-03-10 17:14:12 UTC (rev 1463)
@@ -20,10 +20,9 @@
.findall(Name,introduction(participant,Name),LP);
.print("Sending CFP to ",LP);
.send(LP,tell,cfp(Id,Task));
- .concat("+!contract(",Id,")",Event);
// the deadline of the CNP is now + 4 seconds, so
// the event +!contract(Id) is generated at that time
- .at("now +4 seconds", Event).
+ .at("now +4 seconds", { +!contract(Id) }).
// receive proposal
Modified: trunk/src/jason/asSyntax/Plan.java
===================================================================
--- trunk/src/jason/asSyntax/Plan.java 2009-03-10 13:04:16 UTC (rev 1462)
+++ trunk/src/jason/asSyntax/Plan.java 2009-03-10 17:14:12 UTC (rev 1463)
@@ -62,6 +62,8 @@
private boolean isAllUnifs = false;
private boolean hasBreakpoint = false;
+ private boolean isTerm = false; // it is true when the plan body is used as a term instead of an element of a plan
+
// used by clone
public Plan() {
super("plan", 0);
@@ -71,12 +73,15 @@
public Plan(Pred label, Trigger te, LogicalFormula ct, PlanBody bd) {
super("plan", 0);
tevent = te;
+ tevent.setAsTriggerTerm(false);
setLabel(label);
setContext(ct);
- if (bd == null)
+ if (bd == null) {
body = new PlanBodyImpl();
- else
+ } else {
body = bd;
+ body.setAsBodyTerm(false);
+ }
}
@Override
@@ -122,6 +127,10 @@
context = null;
}
+ public void setAsPlanTerm(boolean b) {
+ isTerm = b;
+ }
+
/** prefer using ASSyntax.parsePlan */
public static Plan parse(String sPlan) {
as2j parser = new as2j(new StringReader(sPlan));
@@ -205,6 +214,8 @@
p.body = (PlanBody)body.clone();
p.setSrcInfo(srcInfo);
+
+ p.isTerm = isTerm;
return p;
}
@@ -224,6 +235,7 @@
p.body = body.clonePB();
p.setSrcInfo(srcInfo);
+ p.isTerm = isTerm;
return p;
}
@@ -234,10 +246,18 @@
/** returns this plan in a string complaint with AS syntax */
public String toASString() {
- return ((label == null) ? "" : "@" + label + " ") +
+ String b, e;
+ if (isTerm) {
+ b = "{ ";
+ e = " }";
+ } else {
+ b = "";
+ e = ".";
+ }
+ return b+((label == null) ? "" : "@" + label + " ") +
tevent + ((context == null) ? "" : " : " + context) +
(body.isEmptyBody() ? "" : " <- " + body) +
- ".";
+ e;
}
/** get as XML */
Modified: trunk/src/jason/asSyntax/PlanLibrary.java
===================================================================
--- trunk/src/jason/asSyntax/PlanLibrary.java 2009-03-10 13:04:16 UTC (rev 1462)
+++ trunk/src/jason/asSyntax/PlanLibrary.java 2009-03-10 17:14:12 UTC (rev 1463)
@@ -167,6 +167,8 @@
if (!p.getLabel().hasSource())
p.getLabel().addAnnot(BeliefBase.TSelf);
+ p.setAsPlanTerm(false); // it is not a term anymore
+
planLabels.put(p.getLabel().getFunctor(), p);
Trigger pte = p.getTrigger();
Modified: trunk/src/jason/asSyntax/Trigger.java
===================================================================
--- trunk/src/jason/asSyntax/Trigger.java 2009-03-10 13:04:16 UTC (rev 1462)
+++ trunk/src/jason/asSyntax/Trigger.java 2009-03-10 17:14:12 UTC (rev 1463)
@@ -71,6 +71,8 @@
private TEType type = TEType.belief;
private Literal literal;
+ private boolean isTerm = false; // it is true when the plan body is used as a term instead of an element of a plan
+
public Trigger(TEOperator op, TEType t, Literal l) {
super("te", 0);
literal = l;
@@ -163,6 +165,7 @@
public Trigger clone() {
Trigger c = new Trigger(operator, type, literal.copy());
c.predicateIndicatorCache = this.predicateIndicatorCache;
+ c.isTerm = isTerm;
return c;
}
@@ -187,9 +190,21 @@
this.literal = literal;
predicateIndicatorCache = null;
}
+
+ public void setAsTriggerTerm(boolean b) {
+ isTerm = b;
+ }
public String toString() {
- return operator.toString() + type + literal;
+ String b, e;
+ if (isTerm) {
+ b = "{ ";
+ e = " }";
+ } else {
+ b = "";
+ e = "";
+ }
+ return b + operator+ type + literal + e;
}
/** try to convert the term t into a trigger, in case t is a trigger term, a string that can be parsed to a trigger, a var with value trigger, .... */
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2009-03-10 13:04:16 UTC (rev 1462)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2009-03-10 17:14:12 UTC (rev 1463)
@@ -388,11 +388,13 @@
}
if (C == null && B == null) {
// handle the case of a single trigger
+ T.setAsTriggerTerm(true);
return T;
} else {
// handle the case of a entire plan
Plan p = new Plan(L,T,(LogicalFormula)C, B);
p.setSrcInfo(T.getSrcInfo());
+ p.setAsPlanTerm(true);
return p;
}
}
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2009-03-10 13:04:16 UTC (rev 1462)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2009-03-10 17:14:12 UTC (rev 1463)
@@ -553,11 +553,13 @@
}
if (C == null && B == null) {
// handle the case of a single trigger
+ T.setAsTriggerTerm(true);
{if (true) return T;}
} else {
// handle the case of a entire plan
Plan p = new Plan(L,T,(LogicalFormula)C, B);
p.setSrcInfo(T.getSrcInfo());
+ p.setAsPlanTerm(true);
{if (true) return p;}
}
}
@@ -1317,27 +1319,6 @@
finally { jj_save(0, xla); }
}
- final private boolean jj_3R_12() {
- 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_13()) jj_scanpos = xsp;
- while (true) {
- xsp = jj_scanpos;
- if (jj_3R_14()) { jj_scanpos = xsp; break; }
- }
- xsp = jj_scanpos;
- if (jj_3R_15()) jj_scanpos = xsp;
- return false;
- }
-
final private boolean jj_3R_15() {
if (jj_3R_17()) return true;
return false;
@@ -1351,13 +1332,13 @@
return false;
}
- final private boolean jj_3R_16() {
- if (jj_scan_token(27)) return true;
+ final private boolean jj_3R_14() {
+ if (jj_3R_16()) return true;
return false;
}
- final private boolean jj_3R_14() {
- if (jj_3R_16()) return true;
+ final private boolean jj_3R_16() {
+ if (jj_scan_token(27)) return true;
return false;
}
@@ -1371,6 +1352,27 @@
return false;
}
+ final private boolean jj_3R_12() {
+ 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_13()) jj_scanpos = xsp;
+ while (true) {
+ xsp = jj_scanpos;
+ if (jj_3R_14()) { jj_scanpos = xsp; break; }
+ }
+ xsp = jj_scanpos;
+ if (jj_3R_15()) jj_scanpos = xsp;
+ return false;
+ }
+
public as2jTokenManager token_source;
SimpleCharStream jj_input_stream;
public Token token, jj_nt;
Modified: trunk/src/jason/stdlib/at.java
===================================================================
--- trunk/src/jason/stdlib/at.java 2009-03-10 13:04:16 UTC (rev 1462)
+++ trunk/src/jason/stdlib/at.java 2009-03-10 17:14:12 UTC (rev 1463)
@@ -30,7 +30,6 @@
import jason.asSemantics.Intention;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
-import jason.asSyntax.ASSyntax;
import jason.asSyntax.StringTerm;
import jason.asSyntax.Term;
import jason.asSyntax.Trigger;
@@ -57,14 +56,15 @@
"d" or "day(s)".
The default <time_unit> is milliseconds.<br/><br/>
- <li>+ event (string): the event to be created. The string will
- be parsed as a triggering event (see the <b><i>Jason</i></b> syntax).
+ <li>+ event (trigger term): the event to be created. The event should
+ follow the Jason Syntax for event and be
+ enclosed by { and }.
</ul>
<p>Examples:<ul>
- <li> <code>.at("now +3 minutes", "+!g")</code>: generates the event <code>+!g</code> 3 minutes from now.
- <li> <code>.at("now +1 m", "+!g")</code>
- <li> <code>.at("now +2 h", "+!g")</code>
+ <li> <code>.at("now +3 minutes", {+!g})</code>: generates the event <code>+!g</code> 3 minutes from now.
+ <li> <code>.at("now +1 m", {+!g})</code>
+ <li> <code>.at("now +2 h", {+!g})</code>
</ul>
@see jason.stdlib.wait
@@ -83,7 +83,6 @@
StringTerm time = (StringTerm)args[0];
String stime = time.getString();
- StringTerm sevent = (StringTerm)args[1];
// parse time
long deadline = -1;
@@ -123,8 +122,8 @@
throw new JasonException("The time parameter ('"+time+"') of the internal action 'at' did not parse correctly!");
}
- Trigger te = ASSyntax.parseTrigger(sevent.getString());
-
+ Trigger te = Trigger.tryToGetTrigger(args[1]);
+
ts.getAg().getScheduler().schedule(new CheckDeadline(te, ts), deadline, TimeUnit.MILLISECONDS);
return true;
}
Modified: trunk/src/jason/stdlib/plan_label.java
===================================================================
--- trunk/src/jason/stdlib/plan_label.java 2009-03-10 13:04:16 UTC (rev 1462)
+++ trunk/src/jason/stdlib/plan_label.java 2009-03-10 17:14:12 UTC (rev 1463)
@@ -79,6 +79,7 @@
if (p != null) {
p = (Plan)p.clone();
p.getLabel().delSources();
+ p.setAsPlanTerm(true);
//String ps = p.toASString().replaceAll("\"", "\\\\\"");
//return un.unifies(new StringTermImpl(ps), args[0]);
return un.unifies(p, args[0]);
Modified: trunk/src/jason/stdlib/relevant_plans.java
===================================================================
--- trunk/src/jason/stdlib/relevant_plans.java 2009-03-10 13:04:16 UTC (rev 1462)
+++ trunk/src/jason/stdlib/relevant_plans.java 2009-03-10 17:14:12 UTC (rev 1463)
@@ -98,6 +98,7 @@
if (np.getLabel() != null) {
np.getLabel().delSources();
}
+ np.setAsPlanTerm(true);
//StringTerm stplan = new StringTermImpl(np.toASString().replaceAll("\\\"", "\\\\\""));
//last = last.append(stplan);
last = last.append(np);
Modified: trunk/src/test/ASParserTest.java
===================================================================
--- trunk/src/test/ASParserTest.java 2009-03-10 13:04:16 UTC (rev 1462)
+++ trunk/src/test/ASParserTest.java 2009-03-10 17:14:12 UTC (rev 1463)
@@ -192,6 +192,7 @@
Unifier un = new Unifier();
Term t = ASSyntax.parseTerm("{ +a(10) }");
assertTrue(t.isPlanBody());
+ assertEquals("{ +a(10) }", t.toString());
t = ASSyntax.parseTerm("{ -a; +b }");
assertEquals("{ -a; +b }", t.toString());
@@ -200,10 +201,10 @@
assertEquals(2, pb.getPlanSize());
t = ASSyntax.parseTerm("{ -a : b <- c1; c2 }");
- assertEquals("-a : b <- c1; c2.", t.toString());
+ assertEquals("{ -a : b <- c1; c2 }", t.toString());
t = ASSyntax.parseTerm("{ +!a(10) }");
- assertEquals("+!a(10)", t.toString());
+ assertEquals("{ +!a(10) }", t.toString());
assertTrue(t.isStructure());
Structure s = (Structure)t;
assertEquals(2, s.getArity());
@@ -219,14 +220,14 @@
assertEquals(PlanBody.BodyType.achieve, pb.getBodyType());
t = ASSyntax.parseTerm("{ +!a <- +b }");
- assertEquals("+!a <- +b.", t.toString());
+ assertEquals("{ +!a <- +b }", t.toString());
assertTrue(t.isStructure());
s = (Structure)t;
assertEquals(4, s.getArity());
assertEquals("plan", s.getFunctor());
t = ASSyntax.parseTerm("{ +a <- +c }");
- assertEquals("+a <- +c.", t.toString());
+ assertEquals("{ +a <- +c }", t.toString());
assertTrue(t.isStructure());
s = (Structure)t;
assertEquals(4, s.getArity());
Modified: trunk/src/test/StdLibTest.java
===================================================================
--- trunk/src/test/StdLibTest.java 2009-03-10 13:04:16 UTC (rev 1462)
+++ trunk/src/test/StdLibTest.java 2009-03-10 17:14:12 UTC (rev 1463)
@@ -176,7 +176,7 @@
// using IA addPlan
Iterator<Term> i = plans.iterator();
while (i.hasNext()) {
- StringTerm t = (StringTerm) i.next();
+ Term t = i.next();
new add_plan().execute(ts, new Unifier(), new Term[] { t, new Structure("fromGR") });
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-03-11 08:46:57
|
Revision: 1464
http://jason.svn.sourceforge.net/jason/?rev=1464&view=rev
Author: jomifred
Date: 2009-03-11 08:46:55 +0000 (Wed, 11 Mar 2009)
Log Message:
-----------
internal action .wait uses the new syntax for trigger as term
(more details in the API doc of the internal action and release-notes)
Modified Paths:
--------------
trunk/applications/jason-team/src/asl/dummy.asl
trunk/applications/jason-team/src/asl/exploration.asl
trunk/applications/jason-team/src/asl/gaucho.asl
trunk/applications/jason-team/src/asl/goto.asl
trunk/applications/jason-team/src/asl/herding.asl
trunk/release-notes.txt
trunk/src/jason/asSyntax/InternalActionLiteral.java
trunk/src/jason/asSyntax/PlanBodyImpl.java
trunk/src/jason/stdlib/add_plan.java
trunk/src/jason/stdlib/list.java
trunk/src/jason/stdlib/list_plans.java
trunk/src/jason/stdlib/package.html
trunk/src/jason/stdlib/wait.java
Modified: trunk/applications/jason-team/src/asl/dummy.asl
===================================================================
--- trunk/applications/jason-team/src/asl/dummy.asl 2009-03-10 17:14:12 UTC (rev 1463)
+++ trunk/applications/jason-team/src/asl/dummy.asl 2009-03-11 08:46:55 UTC (rev 1464)
@@ -57,7 +57,7 @@
+!decide_target
: not pos(_,_,_)
<- .print("waiting my location....");
- .wait("+pos(_,_,_)");
+ .wait({+pos(_,_,_)});
!decide_target.
+!decide_target
@@ -88,13 +88,13 @@
+!move
: not pos(_,_,_)
<- .print("waiting my location....");
- .wait("+pos(_,_,_)");
+ .wait({+pos(_,_,_)});
!move.
+!move
: not target(_,_)
<- .print("waiting my target....");
- .wait("+target(_,_)");
+ .wait({+target(_,_)});
!move.
+!move
Modified: trunk/applications/jason-team/src/asl/exploration.asl
===================================================================
--- trunk/applications/jason-team/src/asl/exploration.asl 2009-03-10 17:14:12 UTC (rev 1463)
+++ trunk/applications/jason-team/src/asl/exploration.asl 2009-03-11 08:46:55 UTC (rev 1464)
@@ -95,7 +95,7 @@
// wait others pos
while( .count(ally_pos(_,_,_), N) & N < 5 ) {
.print("ooo waiting others pos ");
- .wait("+ally_pos(_,_,_)", 500, _)
+ .wait({+ally_pos(_,_,_)}, 500, _)
};
// find distance to even agents
@@ -107,7 +107,7 @@
+!find_scouter([ag_d(_,AgName)|_],GId)
<- .print("ooo Ask ",AgName," to play scouter");
.send(AgName, achieve, play_role(scouter,GId));
- .wait("+play(AgName,scouter,GId)",2000).
+ .wait({+play(AgName,scouter,GId)},2000).
-!find_scouter([_|LSOdd],GId) // in case the wait fails, try next agent
<- .print("ooo find_scouter failure, try another agent.");
!find_scouter(LSOdd,GId).
@@ -127,8 +127,7 @@
-+target(TargetX, TargetY).
/* added by the pattern
- .wait("+at_target").
- //.wait("+pos(_,_,_)"); // wait next cycle
+ .wait({+at_target}).
!!goto_near_unvisited[scheme(Sch),mission(Mission)]
*/
@@ -138,7 +137,7 @@
-!goto_near_unvisited[scheme(Sch),mission(Mission)]
<- .current_intention(I);
.print("ooo Failure to goto_near_unvisited ",I);
- .wait("+pos(_,_,_)"); // wait next cycle
+ .wait({+pos(_,_,_)}); // wait next cycle
!!goto_near_unvisited[scheme(Sch),mission(Mission)].
*/
Modified: trunk/applications/jason-team/src/asl/gaucho.asl
===================================================================
--- trunk/applications/jason-team/src/asl/gaucho.asl 2009-03-10 17:14:12 UTC (rev 1463)
+++ trunk/applications/jason-team/src/asl/gaucho.asl 2009-03-11 08:46:55 UTC (rev 1464)
@@ -31,10 +31,10 @@
/* -- plans -- */
-+?pos(X, Y, S) <- .wait("+pos(X,Y,S)").
++?pos(X, Y, S) <- .wait({+pos(X,Y,S)}).
//+?group_area(Id,G,A) <- .wait("+group_area(Id,G,A)").
-+?gsize(W,H) <- .wait("+gsize(W,H)").
-+?group(team,G) <- .wait("+group(team,G)", 500, _); ?group(team,G).
++?gsize(W,H) <- .wait({+gsize(W,H)}).
++?group(team,G) <- .wait({+group(team,G)}, 500, _); ?group(team,G).
+?ally_pos(Name,X,Y) : .my_name(Name) <- ?pos(X,Y,_).
+corral(UpperLeftX,UpperLeftY,DownRightX,DownRightY)
@@ -54,7 +54,7 @@
<- .print("*** restart -- odd ***");
?random_pos(X,Y);
+target(X,Y);
- .wait("+at_target",1000,_);
+ .wait({+at_target},1000,_);
!create_exploration_gr.
+!restart
<- .print("*** restart -- even ***");
Modified: trunk/applications/jason-team/src/asl/goto.asl
===================================================================
--- trunk/applications/jason-team/src/asl/goto.asl 2009-03-10 17:14:12 UTC (rev 1463)
+++ trunk/applications/jason-team/src/asl/goto.asl 2009-03-11 08:46:55 UTC (rev 1464)
@@ -27,7 +27,7 @@
+!move
: not target(_,_)
<- .print("waiting my target....");
- .wait("+target(_,_)");
+ .wait({+target(_,_)});
!move.
+!move
Modified: trunk/applications/jason-team/src/asl/herding.asl
===================================================================
--- trunk/applications/jason-team/src/asl/herding.asl 2009-03-10 17:14:12 UTC (rev 1463)
+++ trunk/applications/jason-team/src/asl/herding.asl 2009-03-11 08:46:55 UTC (rev 1464)
@@ -126,8 +126,8 @@
}
}
};
- .wait("+pos(_,_,_)"); // wait an extra step before try to release agents again
- .wait("+pos(_,_,_)").
+ .wait({+pos(_,_,_)}); // wait an extra step before try to release agents again
+ .wait({+pos(_,_,_)}).
+!release_boys[scheme(Sch),mission(Mission),group(Gr)].
{ end }
@@ -212,8 +212,8 @@
: not cow(_,_,_)
<- .print("ooo I see no cow anymore");
// wait two cycles to decide to change the formation (due to fault perception we may not see the cows)
- .wait("+pos(_,_,_)");
- .wait("+pos(_,_,_)");
+ .wait({+pos(_,_,_)});
+ .wait({+pos(_,_,_)});
if (not cow(_,_,_)) {
.findall(P, play(P,herdboy,Gr), ListBoys);
!!create_exploration_gr;
Modified: trunk/release-notes.txt
===================================================================
--- trunk/release-notes.txt 2009-03-10 17:14:12 UTC (rev 1463)
+++ trunk/release-notes.txt 2009-03-11 08:46:55 UTC (rev 1464)
@@ -2,6 +2,34 @@
version 1.2.1
---------------------------
+New features
+- Plans and Triggers can be used as terms when enclosed by { and }
+
+ It is used in the following internal actions
+ .relevant_plans
+ e.g. .relevant_plans({ +!g(_) }, ListOfPlans)
+ instead of .relevant_plans( "+!g(_)" , ListOfPlans)
+ .add_plan
+ .at
+ .wait
+
+ It is also used in send tellHow
+ .send(bob, tellHow, { +te : c <- a1 }).
+
+ The advantage is that unification works
+ e.g. .at("now +1 m", {+stop(ID)})
+ and syntax errors are detected at compilation time
+
+ More complex meta-programming is also possible:
+ .... !myadd( { .print(a); .print(b) } ) ....
+ // pass the body of the plan as parameter to !myadd
+
+ +!myadd(Action) <- .add_plan( {+!g : c & b <- Action} ).
+ // add a plan with a fixed event/context and body as the parameter
+
+ The old style (with strings) continues to work.
+
+
Changes in the GUI
- When closing the window of MAS Console, the application is also
stopped.
Modified: trunk/src/jason/asSyntax/InternalActionLiteral.java
===================================================================
--- trunk/src/jason/asSyntax/InternalActionLiteral.java 2009-03-10 17:14:12 UTC (rev 1463)
+++ trunk/src/jason/asSyntax/InternalActionLiteral.java 2009-03-11 08:46:55 UTC (rev 1464)
@@ -30,7 +30,6 @@
import jason.stdlib.loop;
import java.util.Iterator;
-import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -86,22 +85,6 @@
return super.apply(u);
}
- @Override
- public void countVars(Map<VarTerm, Integer> c) {
- super.countVars(c);
- if (this.ia != null && this.ia instanceof jason.stdlib.wait) {
- // count the vars of first arg
- if (getTerm(0).isString()) {
- try {
- Trigger te = ASSyntax.parseTrigger( ((StringTerm)getTerm(0)).getString() );
- te.getLiteral().countVars(c);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
-
@SuppressWarnings("unchecked")
public Iterator<Unifier> logicalConsequence(Agent ag, Unifier un) {
if (ag.getTS().getUserAgArch().isRunning()) {
Modified: trunk/src/jason/asSyntax/PlanBodyImpl.java
===================================================================
--- trunk/src/jason/asSyntax/PlanBodyImpl.java 2009-03-10 17:14:12 UTC (rev 1463)
+++ trunk/src/jason/asSyntax/PlanBodyImpl.java 2009-03-11 08:46:55 UTC (rev 1464)
@@ -140,16 +140,22 @@
@Override
public boolean apply(Unifier u) {
- // do not apply in next!
- resetHashCodeCache();
+ // do not apply in next! (except in case this is a term)
+ boolean ok = false;
+
if (term != null && term.apply(u)) {
if (term.isPlanBody()) { // we cannot have "inner" body literals
formType = ((PlanBody)term).getBodyType();
term = ((PlanBody)term).getBodyTerm();
}
- return true;
+ ok = true;
}
- return false;
+ if (next != null && isTerm && next.apply(u))
+ ok = true;
+
+ if (ok)
+ resetHashCodeCache();
+ return ok;
}
@Override
Modified: trunk/src/jason/stdlib/add_plan.java
===================================================================
--- trunk/src/jason/stdlib/add_plan.java 2009-03-10 17:14:12 UTC (rev 1463)
+++ trunk/src/jason/stdlib/add_plan.java 2009-03-11 08:46:55 UTC (rev 1464)
@@ -140,7 +140,6 @@
} else {
throw JasonException.createWrongArgument(this, "The term '"+t+"' ("+t.getClass().getSimpleName()+") can not be used as a plan for .add_plan.");
}
-
return p;
}
}
Modified: trunk/src/jason/stdlib/list.java
===================================================================
--- trunk/src/jason/stdlib/list.java 2009-03-10 17:14:12 UTC (rev 1463)
+++ trunk/src/jason/stdlib/list.java 2009-03-11 08:46:55 UTC (rev 1464)
@@ -33,7 +33,6 @@
@see jason.stdlib.ground
*/
-
public class list extends DefaultInternalAction {
private static InternalAction singleton = null;
Modified: trunk/src/jason/stdlib/list_plans.java
===================================================================
--- trunk/src/jason/stdlib/list_plans.java 2009-03-10 17:14:12 UTC (rev 1463)
+++ trunk/src/jason/stdlib/list_plans.java 2009-03-11 08:46:55 UTC (rev 1464)
@@ -7,7 +7,21 @@
import jason.asSyntax.Term;
import jason.asSyntax.Trigger;
-/** list all plans in PL */
+/**
+<p>Internal action: <b><code>.list_plans</code></b>.
+
+<p>Description: prints out the plans in the plan library.
+
+<p>Parameter:<ul>
+<li>+ trigger (trigger term, [optional]): list only plan that unifies this parameter as trigger event.<br/>
+</ul>
+
+<p>Examples:<ul>
+<li> <code>.list_plans</code>
+<li> <code>.list_plans({ +g(_) })</code>
+</ul>
+
+*/
public class list_plans extends DefaultInternalAction {
@Override public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
Modified: trunk/src/jason/stdlib/package.html
===================================================================
--- trunk/src/jason/stdlib/package.html 2009-03-10 17:14:12 UTC (rev 1463)
+++ trunk/src/jason/stdlib/package.html 2009-03-11 08:46:55 UTC (rev 1464)
@@ -41,6 +41,7 @@
<li>{@link jason.stdlib.remove_plan remove_plan}: remove a plan.</li>
<li>{@link jason.stdlib.plan_label plan_label}: get the label of a plan.</li>
<li>{@link jason.stdlib.relevant_plans relevant_plans}: get a list of plans.</li>
+ <li>{@link jason.stdlib.list_plans list_plans}: print out the plans in the current plan library.</li>
</ul>
Modified: trunk/src/jason/stdlib/wait.java
===================================================================
--- trunk/src/jason/stdlib/wait.java 2009-03-10 17:14:12 UTC (rev 1463)
+++ trunk/src/jason/stdlib/wait.java 2009-03-11 08:46:55 UTC (rev 1464)
@@ -31,13 +31,11 @@
import jason.asSemantics.Intention;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
-import jason.asSyntax.ASSyntax;
import jason.asSyntax.InternalActionLiteral;
import jason.asSyntax.NumberTerm;
import jason.asSyntax.NumberTermImpl;
import jason.asSyntax.PlanBody;
import jason.asSyntax.PlanBodyImpl;
-import jason.asSyntax.StringTerm;
import jason.asSyntax.Term;
import jason.asSyntax.Trigger;
import jason.asSyntax.PlanBody.BodyType;
@@ -49,16 +47,12 @@
<p>Internal action: <b><code>.wait(<i>E</i>,<i>T</i>)</code></b>.
<p>Description: suspend the intention for the time specified by <i>T</i> (in
- milliseconds) or until some event <i>E</i> happens. The events are
- strings in AgentSpeak syntax, e.g. <code>"+bel(33)"</code>,
- <code>"+!go(X,Y)"</code>.
+ milliseconds) or until some event <i>E</i> happens. The events follow the
+ AgentSpeak syntax but are enclosed by { and }, e.g. <code>{+bel(33)}</code>,
+ <code>{+!go(X,Y)}</code>.
- Although the argument is a string, the variables
- in the string will be unified with the event, i.e., the unifier might have
- values for X and Y after the execution of <code>.wait("+!go(X,Y)")</code>.
-
<p>Parameters:<ul>
- <li><i>+ event</i> (string): the event to wait for.<br/>
+ <li><i>+ event</i> (trigger term): the event to wait for.<br/>
<li>+ timeout (number).<br/>
</ul>
@@ -66,18 +60,18 @@
<p>Examples:<ul>
<li> <code>.wait(1000)</code>: suspend the intention for 1 second.
- <li> <code>.wait("+b(1)")</code>: suspend the intention until the belief
+ <li> <code>.wait({+b(1)})</code>: suspend the intention until the belief
<code>b(1)</code> is added in the belief base.
- <li> <code>.wait("+!g", 2000)</code>: suspend the intention until the goal
+ <li> <code>.wait({+!g}, 2000)</code>: suspend the intention until the goal
<code>g</code> is triggered or 2 seconds have passed, whatever happens
first. In case the event does not happens in two seconds, the internal action
fails.
- <li> <code>.wait("+!g", 2000, EventTime)</code>: suspend the intention until the goal
+ <li> <code>.wait({+!g}, 2000, EventTime)</code>: suspend the intention until the goal
<code>g</code> is triggered or 2 seconds have passed, whatever happens
first.
- Hence this use of .wait has three arguments, in case the event does not happen in
+ As this use of .wait has three arguments, in case the event does not happen in
two seconds, the internal action does not fail (as in the previous example).
The third argument will be unified to the
elapsed time (in miliseconds) from the start of .wait until the event or timeout. </ul>
@@ -107,10 +101,10 @@
// time in milliseconds
NumberTerm time = (NumberTerm)args[0];
timeout = (long) time.solve();
- } else if (args[0].isString()) {
+ } else { // if (args[0].isString())
// wait for event
- te = ASSyntax.parseTrigger( ((StringTerm) args[0]).getString());
- te.getLiteral().apply(un);
+ te = Trigger.tryToGetTrigger(args[0]); //ASSyntax.parseTrigger( ((StringTerm) args[0]).getString());
+ //te.getLiteral().apply(un);
if (args.length >= 2)
timeout = (long) ((NumberTerm) args[1]).solve();
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-03-13 10:43:29
|
Revision: 1467
http://jason.svn.sourceforge.net/jason/?rev=1467&view=rev
Author: jomifred
Date: 2009-03-13 10:43:17 +0000 (Fri, 13 Mar 2009)
Log Message:
-----------
fix lack of import in kill_agent
Modified Paths:
--------------
trunk/doc/index.html
trunk/src/jason/stdlib/kill_agent.java
Modified: trunk/doc/index.html
===================================================================
--- trunk/doc/index.html 2009-03-13 10:34:17 UTC (rev 1466)
+++ trunk/doc/index.html 2009-03-13 10:43:17 UTC (rev 1467)
@@ -41,7 +41,9 @@
<li><a href="http://jason.sourceforge.net/JasonWebSite/Examples/Examples.html">Examples</a>
<li><a href="http://jason.sourceforge.net/JasonWebSite/Demos.html">Demos</a>
<li><a href="http://jason.sourceforge.net/JasonWebSite/Documents.html">Publications</a>
- <li><a href="http://jason.sourceforge.net/JasonWebSite/Related%20Projects.html">Related projects</a>
+ <li><a href="http://jason.sourceforge.net/JasonWebSite/Related%20Projects.html">Related
+ projects</a>
+ <li><a href="http://jason.wiki.sourceforge.net/">Wiki</a>
</ul>
</li>
<br/>
Modified: trunk/src/jason/stdlib/kill_agent.java
===================================================================
--- trunk/src/jason/stdlib/kill_agent.java 2009-03-13 10:34:17 UTC (rev 1466)
+++ trunk/src/jason/stdlib/kill_agent.java 2009-03-13 10:43:17 UTC (rev 1467)
@@ -27,8 +27,8 @@
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Term;
+import jason.asSyntax.StringTerm;
-
/**
<p>Internal action: <b><code>.kill_agent</code></b>.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-03-15 09:49:31
|
Revision: 1468
http://jason.svn.sourceforge.net/jason/?rev=1468&view=rev
Author: jomifred
Date: 2009-03-15 09:49:16 +0000 (Sun, 15 Mar 2009)
Log Message:
-----------
fix a bug in centralised env (when the agent was killed)
-- see email of Herv?\195?\131?\194?\169 Lange
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/tests/BugVarsAsGoal.java
trunk/doc/faq/faq.tex
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/asSyntax/Plan.java
trunk/src/jason/asSyntax/PlanBody.java
trunk/src/jason/asSyntax/PlanBodyImpl.java
trunk/src/jason/asSyntax/VarTerm.java
trunk/src/jason/infra/centralised/CentralisedEnvironment.java
trunk/src/jason/infra/centralised/RunCentralisedMAS.java
Modified: trunk/applications/as-unit-test/src/jason/tests/BugVarsAsGoal.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/BugVarsAsGoal.java 2009-03-13 10:43:17 UTC (rev 1467)
+++ trunk/applications/as-unit-test/src/jason/tests/BugVarsAsGoal.java 2009-03-15 09:49:16 UTC (rev 1468)
@@ -17,8 +17,8 @@
// defines the agent's AgentSpeak code
ag.parseAScode(
- "+!g <- +p(ggg); !gg. " +
- "+!gg : p(X) <- !!X. " +
+ "+!g <- +p(ggg); !gg; Y={!ggg}; Y. " +
+ "+!gg : p(X) <- +X; !!X. " +
"+!ggg[source(A)] <- jason.asunit.print(A). "
);
}
@@ -26,6 +26,7 @@
@Test
public void testGoal() {
ag.addGoal("g");
- ag.assertPrint("self", 10);
+ ag.assertPrint("self", 10);
+ ag.assertPrint("self", 10);
}
}
Modified: trunk/doc/faq/faq.tex
===================================================================
--- trunk/doc/faq/faq.tex 2009-03-13 10:43:17 UTC (rev 1467)
+++ trunk/doc/faq/faq.tex 2009-03-15 09:49:16 UTC (rev 1468)
@@ -954,7 +954,7 @@
The internal actions defined by the user can add new annotations to
indicate particular types of errors (see the API documentation of
- \htlink{JasonException}{http://jason.sourceforge.net/api/classjason_1_1JasonException.html}
+ \htlink{JasonException}{http://jason.sourceforge.net/api/jason/JasonException.html}
for more information about that).
\end{description}
@@ -1004,6 +1004,16 @@
\htlink{here}{http://jasonplugin.wikidot.com/} for more information,
including installation instructions.
+A command line option is also available. To compile a project:
+\begin{verbatim}
+<jason installation path>/bin/mas2j.sh <your project.mas2j>
+\end{verbatim}
+an Ant script is created in the \texttt{bin} directory. To run:
+\begin{verbatim}
+ant -f bin/build.xml
+\end{verbatim}
+
+
\subsection{How to create an Eclipse project for \jason?}
This might be useful if you are planning to contribute code for Jason
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2009-03-13 10:43:17 UTC (rev 1467)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2009-03-15 09:49:16 UTC (rev 1468)
@@ -427,7 +427,7 @@
}
Unifier u = im.unif;
PlanBody h = im.getCurrentStep();
- h.apply(u);
+ h.applyHead(u);
Literal body = null;
Term bTerm = h.getBodyTerm();
@@ -540,14 +540,13 @@
case delAddBel:
// -+a(1,X) ===> remove a(_,_), add a(1,X)
// change all vars to anon vars to remove it
- body = addSelfSource(body);
- Literal bc = (Literal)body.clone();
- bc.makeTermsAnnon();
+ body = addSelfSource(body.copy());
+ body.makeTermsAnnon();
// to delete, create events as external to avoid that
// remove/add create two events for the same intention
try {
- List<Literal>[] result = ag.brf(null, bc, conf.C.SI); // the intention is not the new focus
+ List<Literal>[] result = ag.brf(null, body, conf.C.SI); // the intention is not the new focus
if (result != null) { // really delete something
// generate events
updateEvents(result,Intention.EmptyInt);
Modified: trunk/src/jason/asSyntax/Plan.java
===================================================================
--- trunk/src/jason/asSyntax/Plan.java 2009-03-13 10:43:17 UTC (rev 1467)
+++ trunk/src/jason/asSyntax/Plan.java 2009-03-15 09:49:16 UTC (rev 1468)
@@ -102,16 +102,6 @@
}
}
- @Override
- public boolean apply(Unifier u) {
- boolean r = false;
- // if I am a term, the body also is (for apply)
- if (isTerm) body.setAsBodyTerm(true);
- r = super.apply(u);
- if (isTerm) body.setAsBodyTerm(false);
- return r;
- }
-
public void setLabel(Pred p) {
label = p;
if (p != null && p.hasAnnot()) {
Modified: trunk/src/jason/asSyntax/PlanBody.java
===================================================================
--- trunk/src/jason/asSyntax/PlanBody.java 2009-03-13 10:43:17 UTC (rev 1467)
+++ trunk/src/jason/asSyntax/PlanBody.java 2009-03-15 09:49:16 UTC (rev 1468)
@@ -1,5 +1,7 @@
package jason.asSyntax;
+import jason.asSemantics.Unifier;
+
/**
* Interface for elements of a plans's body.
*
@@ -27,6 +29,9 @@
public boolean isEmptyBody();
public int getPlanSize();
+ /** apply unifier only on first element of the body */
+ public boolean applyHead(Unifier u);
+
public void setBodyType(BodyType bt);
public void setBodyTerm(Term t);
public void setBodyNext(PlanBody bl);
Modified: trunk/src/jason/asSyntax/PlanBodyImpl.java
===================================================================
--- trunk/src/jason/asSyntax/PlanBodyImpl.java 2009-03-13 10:43:17 UTC (rev 1467)
+++ trunk/src/jason/asSyntax/PlanBodyImpl.java 2009-03-15 09:49:16 UTC (rev 1468)
@@ -144,18 +144,8 @@
if (i == 0) term = t;
if (i == 1) System.out.println("Should not setTerm(1) of body literal!");
}
-
- @Override
- public boolean apply(Unifier u) {
- // do not apply in next! (except in case this is a term)
- boolean ok = false;
-
- if (next != null && isTerm) {
- //next.setAsBodyTerm(true); // to force apply in next
- ok = next.apply(u);
- //next.setAsBodyTerm(false);
- }
-
+
+ public boolean applyHead(Unifier u) {
if (term != null && term.apply(u)) {
if (term.isPlanBody()) { // we cannot have "inner" body literals
PlanBody baknext = next;
@@ -163,14 +153,21 @@
next = ((PlanBody)term).getBodyNext();
term = ((PlanBody)term).getBodyTerm();
if (baknext != null) {
- //baknext.setAsBodyTerm(true); // to force apply in next
baknext.apply(u);
- //baknext.setAsBodyTerm(false);
getLastBody().add(baknext);
}
}
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean apply(Unifier u) {
+ boolean ok = next != null && next.apply(u);
+
+ if (applyHead(u))
ok = true;
- }
if (ok)
resetHashCodeCache();
Modified: trunk/src/jason/asSyntax/VarTerm.java
===================================================================
--- trunk/src/jason/asSyntax/VarTerm.java 2009-03-13 10:43:17 UTC (rev 1467)
+++ trunk/src/jason/asSyntax/VarTerm.java 2009-03-15 09:49:16 UTC (rev 1468)
@@ -955,6 +955,13 @@
return null;
}
+ public boolean applyHead(Unifier u) {
+ if (value != null && getValue() instanceof PlanBody)
+ return ((PlanBody) getValue()).applyHead(u);
+ else
+ return true;
+ }
+
public boolean isEmptyBody() {
if (value != null && getValue() instanceof PlanBody)
return ((PlanBody) getValue()).isEmptyBody();
Modified: trunk/src/jason/infra/centralised/CentralisedEnvironment.java
===================================================================
--- trunk/src/jason/infra/centralised/CentralisedEnvironment.java 2009-03-13 10:43:17 UTC (rev 1467)
+++ trunk/src/jason/infra/centralised/CentralisedEnvironment.java 2009-03-15 09:49:16 UTC (rev 1468)
@@ -89,12 +89,10 @@
public void actionExecuted(String agName, Structure actTerm, boolean success, Object infraData) {
ActionExec action = (ActionExec)infraData;
- if (success) {
- action.setResult(true);
- } else {
- action.setResult(false);
- }
- masRunner.getAg(agName).actionExecuted(action);
+ action.setResult(success);
+ CentralisedAgArch ag = masRunner.getAg(agName);
+ if (ag != null)
+ ag.actionExecuted(action);
}
Modified: trunk/src/jason/infra/centralised/RunCentralisedMAS.java
===================================================================
--- trunk/src/jason/infra/centralised/RunCentralisedMAS.java 2009-03-13 10:43:17 UTC (rev 1467)
+++ trunk/src/jason/infra/centralised/RunCentralisedMAS.java 2009-03-15 09:49:16 UTC (rev 1468)
@@ -83,7 +83,7 @@
private CentralisedEnvironment env = null;
private CentralisedExecutionControl control = null;
private boolean debug = false;
- private Map<String,CentralisedAgArch> ags = new ConcurrentHashMap<String,CentralisedAgArch>();
+ private Map<String,CentralisedAgArch> ags = new ConcurrentHashMap<String,CentralisedAgArch>();
public JButton btDebug;
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-03-16 14:35:44
|
Revision: 1469
http://jason.svn.sourceforge.net/jason/?rev=1469&view=rev
Author: jomifred
Date: 2009-03-16 14:35:31 +0000 (Mon, 16 Mar 2009)
Log Message:
-----------
fix a bug in parsing { -+a }
(the parser tries to parse it as a trigger)
Modified Paths:
--------------
trunk/README
trunk/applications/jason-team/src/asl/goto.asl
trunk/release-notes.txt
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/jason/infra/centralised/CentralisedEnvironment.java
trunk/src/test/ASParserTest.java
Modified: trunk/README
===================================================================
--- trunk/README 2009-03-15 09:49:16 UTC (rev 1468)
+++ trunk/README 2009-03-16 14:35:31 UTC (rev 1469)
@@ -5,7 +5,6 @@
Java 1.5 is required to run this application, it is available
at http://java.sun.com.
-For more information, please read the Jason tutorial that can
-be found in doc/Jason.pdf.
+For more information, please read doc/index.html.
Thank you for your interest in Jason!
Modified: trunk/applications/jason-team/src/asl/goto.asl
===================================================================
--- trunk/applications/jason-team/src/asl/goto.asl 2009-03-15 09:49:16 UTC (rev 1468)
+++ trunk/applications/jason-team/src/asl/goto.asl 2009-03-16 14:35:31 UTC (rev 1469)
@@ -21,7 +21,7 @@
+target(NX,NY)
<- .drop_desire(move);
jia.set_target(NX,NY);
- -at_target;
+ -at_target;
!!move.
+!move
Modified: trunk/release-notes.txt
===================================================================
--- trunk/release-notes.txt 2009-03-15 09:49:16 UTC (rev 1468)
+++ trunk/release-notes.txt 2009-03-16 14:35:31 UTC (rev 1469)
@@ -5,7 +5,7 @@
New features
- Plans and Triggers can be used as terms when enclosed by { and }
- It is used in the following internal actions
+ This feature is used in the following internal actions
.relevant_plans
e.g. .relevant_plans({ +!g(_) }, ListOfPlans)
instead of .relevant_plans( "+!g(_)" , ListOfPlans)
@@ -13,27 +13,29 @@
.at
.wait
- It is also used in send tellHow
+ It may be used in send tellHow
.send(bob, tellHow, { +te : c <- a1 }).
- The advantage is that unification works
+ The advantages are that unification works
e.g. .at("now +1 m", {+stop(ID)})
and syntax errors are detected at compilation time
+
+ The old style (with strings) continues to work.
More complex meta-programming is also possible:
.... !myadd( { .print(a); .print(b) } ) ....
// pass the body of the plan as parameter to !myadd
+!myadd(Action) <- .add_plan( {+!g : c & b <- Action} ).
- // add a plan with a fixed event/context and body as the parameter
-
- The old style (with strings) continues to work.
+ // add a plan with a fixed event/context and body
+ // given as a parameter
-
+
Changes in the GUI
- When closing the window of MAS Console, the application is also
stopped.
+
Changes in communication
- for messages sent to itself, the sender is 'self' now,
and not the agent's name as in previous releases
@@ -43,11 +45,12 @@
- .puts: used for printing messages to the console (based on Ruby
similar method). Developed by Felipe Meneguzzi.
- .all_names: get the name of all agentes in the system.
+- .list_plans: print out the plans of agent's plan library
Changes in internal actions
- .relevant_plans has a third argument that gets the labels
of the plans
-- .create_agent accepts strings for the name of the agents
+- .create_agent and .kill_agent accept strings for the agents' name
Bugs fixed
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2009-03-15 09:49:16 UTC (rev 1468)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2009-03-16 14:35:31 UTC (rev 1469)
@@ -240,8 +240,9 @@
boolean isEOF = false;
}
{
+ "{"
( LOOKAHEAD(4)
- "{" <TK_BEGIN> dir = pred() "}"
+ <TK_BEGIN> dir = pred() "}"
{ Agent innerAg = new Agent(); }
isEOF = agent(innerAg)
{ if (isEOF)
@@ -250,7 +251,7 @@
resultOfDirective = DirectiveProcessor.process(dir, outerAg, innerAg);
}
|
- "{" dir = pred() "}"
+ dir = pred() "}"
{ if (dir.toString().equals("end"))
return true;
else
@@ -361,8 +362,9 @@
Term plan_term(): { Trigger T = null; Object C = null; PlanBody B = null, B1 = null; Plan P = null; boolean pb = true; Pred L = null; }
// pb = "only plan body"
{
- "{"
- [ [<TK_LABEL_AT> L=pred() { pb = false; } ]
+ "{"
+ [ LOOKAHEAD(4)
+ [<TK_LABEL_AT> L=pred() { pb = false; } ]
T = trigger() { if (T.getType() != TEType.belief) pb = false; }
[ ":" C = log_expr() { pb = false; } ]
[( "<-" { pb = false; }
@@ -376,7 +378,7 @@
if (T != null) {
// handle the case of "+a1", parsed as TE, need to be changed to plan's body
// handle the case of "+a1; +a2", parsed as "TE; Body"
- if (pb) {
+ if (pb && L == null) {
if (T.isAddition())
B1 = new PlanBodyImpl(BodyType.addBel, T.getLiteral());
else
@@ -386,7 +388,7 @@
B1.setBodyNext(B);
return B1;
}
- if (C == null && B == null) {
+ if (C == null && B == null && L == null) {
// handle the case of a single trigger
T.setAsTriggerTerm(true);
return T;
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2009-03-15 09:49:16 UTC (rev 1468)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2009-03-16 14:35:31 UTC (rev 1469)
@@ -246,8 +246,8 @@
Agent resultOfDirective = null;
Agent bakAg = curAg;
boolean isEOF = false;
+ jj_consume_token(27);
if (jj_2_1(4)) {
- jj_consume_token(27);
jj_consume_token(TK_BEGIN);
dir = pred();
jj_consume_token(28);
@@ -259,8 +259,9 @@
resultOfDirective = DirectiveProcessor.process(dir, outerAg, innerAg);
} else {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 27:
- jj_consume_token(27);
+ case TK_BEGIN:
+ case TK_END:
+ case ATOM:
dir = pred();
jj_consume_token(28);
if (dir.toString().equals("end"))
@@ -460,10 +461,7 @@
final public Term plan_term() throws ParseException {
Trigger T = null; Object C = null; PlanBody B = null, B1 = null; Plan P = null; boolean pb = true; Pred L = null;
jj_consume_token(27);
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case TK_LABEL_AT:
- case 34:
- case 35:
+ if (jj_2_2(4)) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case TK_LABEL_AT:
jj_consume_token(TK_LABEL_AT);
@@ -508,9 +506,7 @@
jj_la1[21] = jj_gen;
;
}
- break;
- default:
- jj_la1[22] = jj_gen;
+ } else {
;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
@@ -534,14 +530,14 @@
B = plan_body();
break;
default:
- jj_la1[23] = jj_gen;
+ jj_la1[22] = jj_gen;
;
}
jj_consume_token(28);
if (T != null) {
// handle the case of "+a1", parsed as TE, need to be changed to plan's body
// handle the case of "+a1; +a2", parsed as "TE; Body"
- if (pb) {
+ if (pb && L == null) {
if (T.isAddition())
B1 = new PlanBodyImpl(BodyType.addBel, T.getLiteral());
else
@@ -551,7 +547,7 @@
B1.setBodyNext(B);
{if (true) return B1;}
}
- if (C == null && B == null) {
+ if (C == null && B == null && L == null) {
// handle the case of a single trigger
T.setAsTriggerTerm(true);
{if (true) return T;}
@@ -607,18 +603,18 @@
formType = BodyType.delAddBel;
break;
default:
- jj_la1[24] = jj_gen;
+ jj_la1[23] = jj_gen;
;
}
break;
default:
- jj_la1[25] = jj_gen;
+ jj_la1[24] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
break;
default:
- jj_la1[26] = jj_gen;
+ jj_la1[25] = jj_gen;
;
}
B = log_expr();
@@ -655,7 +651,7 @@
type = Literal.LNeg;
break;
default:
- jj_la1[27] = jj_gen;
+ jj_la1[26] = jj_gen;
;
}
F = pred();
@@ -690,7 +686,7 @@
{if (true) return Literal.LFalse;}
break;
default:
- jj_la1[28] = jj_gen;
+ jj_la1[27] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -711,7 +707,7 @@
K = jj_consume_token(TK_END);
break;
default:
- jj_la1[29] = jj_gen;
+ jj_la1[28] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -725,7 +721,7 @@
p.setTerms(l);
break;
default:
- jj_la1[30] = jj_gen;
+ jj_la1[29] = jj_gen;
;
}
label_9:
@@ -735,7 +731,7 @@
;
break;
default:
- jj_la1[31] = jj_gen;
+ jj_la1[30] = jj_gen;
break label_9;
}
b = plan_term();
@@ -747,7 +743,7 @@
p.setAnnots(lt);
break;
default:
- jj_la1[32] = jj_gen;
+ jj_la1[31] = jj_gen;
;
}
{if (true) return p;}
@@ -766,7 +762,7 @@
;
break;
default:
- jj_la1[33] = jj_gen;
+ jj_la1[32] = jj_gen;
break label_10;
}
jj_consume_token(41);
@@ -803,7 +799,7 @@
o = log_expr();
break;
default:
- jj_la1[34] = jj_gen;
+ jj_la1[33] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -838,7 +834,7 @@
;
break;
default:
- jj_la1[35] = jj_gen;
+ jj_la1[34] = jj_gen;
break label_11;
}
jj_consume_token(41);
@@ -862,18 +858,18 @@
last = last.concat((ListTerm)f);
break;
default:
- jj_la1[36] = jj_gen;
+ jj_la1[35] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
break;
default:
- jj_la1[37] = jj_gen;
+ jj_la1[36] = jj_gen;
;
}
break;
default:
- jj_la1[38] = jj_gen;
+ jj_la1[37] = jj_gen;
;
}
jj_consume_token(44);
@@ -908,7 +904,7 @@
o = plan_term();
break;
default:
- jj_la1[39] = jj_gen;
+ jj_la1[38] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -927,7 +923,7 @@
{if (true) return new LogExpr((LogicalFormula)t1,LogicalOp.or,(LogicalFormula)t2);}
break;
default:
- jj_la1[40] = jj_gen;
+ jj_la1[39] = jj_gen;
;
}
{if (true) return t1;}
@@ -944,7 +940,7 @@
{if (true) return new LogExpr((LogicalFormula)t1,LogicalOp.and,(LogicalFormula)t2);}
break;
default:
- jj_la1[41] = jj_gen;
+ jj_la1[40] = jj_gen;
;
}
{if (true) return t1;}
@@ -975,7 +971,7 @@
{if (true) return t;}
break;
default:
- jj_la1[42] = jj_gen;
+ jj_la1[41] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1011,7 +1007,7 @@
op1 = string();
break;
default:
- jj_la1[43] = jj_gen;
+ jj_la1[42] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1058,7 +1054,7 @@
operator = RelationalOp.literalBuilder;
break;
default:
- jj_la1[44] = jj_gen;
+ jj_la1[43] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1086,7 +1082,7 @@
op2 = plan_term();
break;
default:
- jj_la1[45] = jj_gen;
+ jj_la1[44] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1097,7 +1093,7 @@
{if (true) return new RelExpr((Term)op1, operator, (Term)op2);}
break;
default:
- jj_la1[46] = jj_gen;
+ jj_la1[45] = jj_gen;
;
}
{if (true) return op1;}
@@ -1122,7 +1118,7 @@
op = ArithmeticOp.minus;
break;
default:
- jj_la1[47] = jj_gen;
+ jj_la1[46] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1136,7 +1132,7 @@
{if (true) return new ArithExpr((NumberTerm)t1, op, (NumberTerm)t2);}
break;
default:
- jj_la1[48] = jj_gen;
+ jj_la1[47] = jj_gen;
;
}
{if (true) return t1;}
@@ -1170,7 +1166,7 @@
op = ArithmeticOp.mod;
break;
default:
- jj_la1[49] = jj_gen;
+ jj_la1[48] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1184,7 +1180,7 @@
{if (true) return new ArithExpr((NumberTerm)t1, op, (NumberTerm)t2);}
break;
default:
- jj_la1[50] = jj_gen;
+ jj_la1[49] = jj_gen;
;
}
{if (true) return t1;}
@@ -1209,7 +1205,7 @@
{if (true) return new ArithExpr((NumberTerm)t1, op, (NumberTerm)t2);}
break;
default:
- jj_la1[51] = jj_gen;
+ jj_la1[50] = jj_gen;
;
}
{if (true) return t1;}
@@ -1254,7 +1250,7 @@
{if (true) return t;}
break;
default:
- jj_la1[52] = jj_gen;
+ jj_la1[51] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1289,7 +1285,7 @@
v = new UnnamedVar(K.image);
break;
default:
- jj_la1[53] = jj_gen;
+ jj_la1[52] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1299,7 +1295,7 @@
v.setAnnots(lt);
break;
default:
- jj_la1[54] = jj_gen;
+ jj_la1[53] = jj_gen;
;
}
{if (true) return v;}
@@ -1322,34 +1318,360 @@
finally { jj_save(0, xla); }
}
- final private boolean jj_3R_14() {
- if (jj_3R_16()) return true;
+ final private boolean jj_2_2(int xla) {
+ jj_la = xla; jj_lastpos = jj_scanpos = token;
+ try { return !jj_3_2(); }
+ catch(LookaheadSuccess ls) { return true; }
+ finally { jj_save(1, xla); }
+ }
+
+ final private boolean jj_3R_21() {
+ if (jj_3R_36()) return true;
return false;
}
+ final private boolean jj_3R_46() {
+ if (jj_3R_59()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_13() {
+ Token xsp;
+ while (true) {
+ xsp = jj_scanpos;
+ if (jj_3R_21()) { jj_scanpos = xsp; break; }
+ }
+ while (true) {
+ xsp = jj_scanpos;
+ if (jj_3R_22()) { jj_scanpos = xsp; break; }
+ }
+ while (true) {
+ xsp = jj_scanpos;
+ if (jj_3R_23()) { jj_scanpos = xsp; break; }
+ }
+ while (true) {
+ xsp = jj_scanpos;
+ if (jj_3R_24()) { jj_scanpos = xsp; break; }
+ }
+ if (jj_scan_token(0)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_32() {
+ if (jj_scan_token(37)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_31() {
+ if (jj_scan_token(33)) return true;
+ return false;
+ }
+
final private boolean jj_3R_17() {
- if (jj_scan_token(42)) return true;
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_31()) {
+ jj_scanpos = xsp;
+ if (jj_3R_32()) return true;
+ }
return false;
}
- final private boolean jj_3_1() {
+ final private boolean jj_3R_16() {
+ if (jj_scan_token(32)) return true;
+ if (jj_3R_30()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_30() {
+ if (jj_3R_44()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_14() {
+ if (jj_scan_token(TK_LABEL_AT)) return true;
+ if (jj_3R_12()) return true;
+ return false;
+ }
+
+ final private boolean jj_3_2() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_14()) jj_scanpos = xsp;
+ if (jj_3R_15()) return true;
+ xsp = jj_scanpos;
+ if (jj_3R_16()) jj_scanpos = xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_17()) jj_scanpos = xsp;
+ return false;
+ }
+
+ final private boolean jj_3R_34() {
if (jj_scan_token(27)) return true;
- if (jj_scan_token(TK_BEGIN)) return true;
- if (jj_3R_12()) return true;
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3_2()) jj_scanpos = xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_46()) jj_scanpos = xsp;
if (jj_scan_token(28)) return true;
return false;
}
- final private boolean jj_3R_13() {
+ final private boolean jj_3R_68() {
+ if (jj_3R_34()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_67() {
+ if (jj_3R_72()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_66() {
+ if (jj_3R_71()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_65() {
+ if (jj_3R_35()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_60() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_65()) {
+ jj_scanpos = xsp;
+ if (jj_3R_66()) {
+ jj_scanpos = xsp;
+ if (jj_3R_67()) {
+ jj_scanpos = xsp;
+ if (jj_3R_68()) return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ final private boolean jj_3R_72() {
+ if (jj_scan_token(STRING)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_59() {
+ if (jj_3R_64()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_54() {
+ if (jj_3R_35()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_47() {
+ if (jj_3R_60()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_29() {
+ if (jj_3R_43()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_53() {
+ if (jj_scan_token(UNNAMEDVAR)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_28() {
+ if (jj_3R_42()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_35() {
+ if (jj_scan_token(42)) return true;
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_47()) jj_scanpos = xsp;
+ if (jj_scan_token(44)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_52() {
+ if (jj_scan_token(VAR)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_41() {
+ if (jj_scan_token(36)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_43() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_52()) {
+ jj_scanpos = xsp;
+ if (jj_3R_53()) return true;
+ }
+ xsp = jj_scanpos;
+ if (jj_3R_54()) jj_scanpos = xsp;
+ return false;
+ }
+
+ final private boolean jj_3R_40() {
+ if (jj_scan_token(31)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_27() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_40()) {
+ jj_scanpos = xsp;
+ if (jj_3R_41()) return true;
+ }
+ return false;
+ }
+
+ final private boolean jj_3R_58() {
+ if (jj_3R_30()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_57() {
+ if (jj_3R_34()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_26() {
+ if (jj_scan_token(35)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_56() {
+ if (jj_3R_35()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_25() {
+ if (jj_scan_token(34)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_45() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_56()) {
+ jj_scanpos = xsp;
+ if (jj_3R_57()) {
+ jj_scanpos = xsp;
+ if (jj_3R_58()) return true;
+ }
+ }
+ return false;
+ }
+
+ final private boolean jj_3R_15() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_25()) {
+ jj_scanpos = xsp;
+ if (jj_3R_26()) return true;
+ }
+ xsp = jj_scanpos;
+ if (jj_3R_27()) jj_scanpos = xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_28()) {
+ jj_scanpos = xsp;
+ if (jj_3R_29()) return true;
+ }
+ return false;
+ }
+
+ final private boolean jj_3R_88() {
+ if (jj_3R_42()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_33() {
+ if (jj_3R_45()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_87() {
+ if (jj_3R_88()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_86() {
+ if (jj_3R_43()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_85() {
if (jj_scan_token(39)) return true;
return false;
}
- final private boolean jj_3R_16() {
- if (jj_scan_token(27)) return true;
+ final private boolean jj_3R_20() {
+ if (jj_3R_35()) return true;
return false;
}
+ final private boolean jj_3R_84() {
+ if (jj_scan_token(35)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_19() {
+ if (jj_3R_34()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_48() {
+ if (jj_scan_token(TK_LABEL_AT)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_83() {
+ if (jj_scan_token(NUMBER)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_18() {
+ if (jj_scan_token(39)) return true;
+ if (jj_3R_33()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_39() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_48()) jj_scanpos = xsp;
+ if (jj_3R_15()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_82() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_83()) {
+ jj_scanpos = xsp;
+ if (jj_3R_84()) {
+ jj_scanpos = xsp;
+ if (jj_3R_85()) {
+ jj_scanpos = xsp;
+ if (jj_3R_86()) {
+ jj_scanpos = xsp;
+ if (jj_3R_87()) return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
final private boolean jj_3R_12() {
Token xsp;
xsp = jj_scanpos;
@@ -1361,21 +1683,202 @@
}
}
xsp = jj_scanpos;
- if (jj_3R_13()) jj_scanpos = xsp;
+ if (jj_3R_18()) jj_scanpos = xsp;
while (true) {
xsp = jj_scanpos;
- if (jj_3R_14()) { jj_scanpos = xsp; break; }
+ if (jj_3R_19()) { jj_scanpos = xsp; break; }
}
xsp = jj_scanpos;
- if (jj_3R_15()) jj_scanpos = xsp;
+ if (jj_3R_20()) jj_scanpos = xsp;
return false;
}
- final private boolean jj_3R_15() {
- if (jj_3R_17()) return true;
+ final private boolean jj_3R_38() {
+ if (jj_scan_token(31)) return true;
return false;
}
+ final private boolean jj_3R_81() {
+ if (jj_3R_82()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_51() {
+ if (jj_scan_token(TK_FALSE)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_50() {
+ if (jj_scan_token(TK_TRUE)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_37() {
+ if (jj_3R_42()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_80() {
+ if (jj_3R_81()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_61() {
+ if (jj_scan_token(TK_NEG)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_49() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_61()) jj_scanpos = xsp;
+ if (jj_3R_12()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_42() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_49()) {
+ jj_scanpos = xsp;
+ if (jj_3R_50()) {
+ jj_scanpos = xsp;
+ if (jj_3R_51()) return true;
+ }
+ }
+ return false;
+ }
+
+ final private boolean jj_3R_71() {
+ if (jj_3R_80()) return true;
+ return false;
+ }
+
+ final private boolean jj_3_1() {
+ if (jj_scan_token(TK_BEGIN)) return true;
+ if (jj_3R_12()) return true;
+ if (jj_scan_token(28)) return true;
+ if (jj_3R_13()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_36() {
+ if (jj_scan_token(27)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_79() {
+ if (jj_scan_token(35)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_78() {
+ if (jj_scan_token(34)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_77() {
+ if (jj_scan_token(36)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_76() {
+ if (jj_scan_token(38)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_70() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_75()) {
+ jj_scanpos = xsp;
+ if (jj_3R_76()) {
+ jj_scanpos = xsp;
+ if (jj_3R_77()) {
+ jj_scanpos = xsp;
+ if (jj_3R_78()) {
+ jj_scanpos = xsp;
+ if (jj_3R_79()) return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ final private boolean jj_3R_75() {
+ if (jj_scan_token(31)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_64() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_70()) jj_scanpos = xsp;
+ if (jj_3R_30()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_74() {
+ if (jj_3R_72()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_73() {
+ if (jj_3R_71()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_69() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_73()) {
+ jj_scanpos = xsp;
+ if (jj_3R_74()) return true;
+ }
+ return false;
+ }
+
+ final private boolean jj_3R_24() {
+ if (jj_3R_39()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_63() {
+ if (jj_3R_69()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_62() {
+ if (jj_scan_token(TK_NOT)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_23() {
+ if (jj_3R_38()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_55() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_62()) {
+ jj_scanpos = xsp;
+ if (jj_3R_63()) return true;
+ }
+ return false;
+ }
+
+ final private boolean jj_3R_22() {
+ if (jj_3R_37()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_44() {
+ if (jj_3R_55()) return true;
+ return false;
+ }
+
public as2jTokenManager token_source;
SimpleCharStream jj_input_stream;
public Token token, jj_nt;
@@ -1385,7 +1888,7 @@
public boolean lookingAhead = false;
private boolean jj_semLA;
private int jj_gen;
- final private int[] jj_la1 = new int[55];
+ final private int[] jj_la1 = new int[54];
static private int[] jj_la1_0;
static private int[] jj_la1_1;
static {
@@ -1393,12 +1896,12 @@
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,0x10000,0x0,0x0,0x0,0x10000,0x803acf80,0x0,0x80000000,0x80000000,0x800,0x10cb00,0x10c000,0x0,0x8000000,0x0,0x0,0x83acf80,0x0,0x200080,0x0,0x83acb80,0x83acb80,0x0,0x0,0x3acf80,0x3acb80,0x0,0x83acb80,0x0,0x0,0x0,0x3000,0x3000,0x0,0x32cb80,0x200080,0x0,};
+ jj_la1_0 = new int[] {0x8000000,0x10cb00,0x8000000,0x80000000,0x8000000,0x10000,0x10cb00,0x8000000,0x10c000,0x20000000,0x10000,0x0,0x0,0x0,0x80000000,0x80000000,0x30cb80,0x0,0x10000,0x0,0x0,0x0,0x803acf80,0x0,0x80000000,0x80000000,0x800,0x10cb00,0x10c000,0x0,0x8000000,0x0,0x0,0x83acf80,0x0,0x200080,0x0,0x83acb80,0x83acb80,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,0x0,0x1,0x22,0x22,0xc,0xdc,0x4,0x5c,0x5c,0x0,0x0,0x0,0x80,0x0,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,0x0,0x1,0x22,0x22,0xdc,0x4,0x5c,0x5c,0x0,0x0,0x0,0x80,0x0,0x400,0x200,0x488,0x200,0x400,0x800,0x488,0x488,0x800,0x2000,0x88,0x88,0x3fc000,0x488,0x3fc000,0xc,0xc,0xc00000,0xc00000,0x1000000,0x88,0x0,0x400,};...
[truncated message content] |
|
From: <jom...@us...> - 2009-03-16 22:06:52
|
Revision: 1470
http://jason.svn.sourceforge.net/jason/?rev=1470&view=rev
Author: jomifred
Date: 2009-03-16 22:06:38 +0000 (Mon, 16 Mar 2009)
Log Message:
-----------
improve performance by avoiding several clone of plans
. intended means does not clone the plan
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/tests/TestIF.java
trunk/examples/auction/auctioneer.asl
trunk/src/jason/asSemantics/IntendedMeans.java
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/asSyntax/InternalActionLiteral.java
trunk/src/jason/asSyntax/PlanBody.java
trunk/src/jason/asSyntax/PlanBodyImpl.java
trunk/src/jason/asSyntax/VarTerm.java
trunk/src/jason/stdlib/foreach.java
trunk/src/jason/stdlib/if_then_else.java
trunk/src/jason/stdlib/loop.java
Modified: trunk/applications/as-unit-test/src/jason/tests/TestIF.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestIF.java 2009-03-16 14:35:31 UTC (rev 1469)
+++ trunk/applications/as-unit-test/src/jason/tests/TestIF.java 2009-03-16 22:06:38 UTC (rev 1470)
@@ -42,7 +42,7 @@
ag.assertPrint("no", 5);
ag.assertAct("a2", 5);
}
-
+
@Test
public void testUnifiyInThenElse() {
ag.addGoal("test3");
Modified: trunk/examples/auction/auctioneer.asl
===================================================================
--- trunk/examples/auction/auctioneer.asl 2009-03-16 14:35:31 UTC (rev 1469)
+++ trunk/examples/auction/auctioneer.asl 2009-03-16 22:06:38 UTC (rev 1470)
@@ -16,7 +16,7 @@
+place_bid(N,V)[source(S)]
: auction(N) & winner(N,CurWin,CurVl) & V > CurVl
<- -winner(N,CurWin,CurVl);
- +winner(N,S,V);
+ +winner(N,S,V); .print("New winner is ",S, " with value ",V);
!check_end(N).
@pb2[atomic]
Modified: trunk/src/jason/asSemantics/IntendedMeans.java
===================================================================
--- trunk/src/jason/asSemantics/IntendedMeans.java 2009-03-16 14:35:31 UTC (rev 1469)
+++ trunk/src/jason/asSemantics/IntendedMeans.java 2009-03-16 22:06:38 UTC (rev 1470)
@@ -43,40 +43,48 @@
private static final long serialVersionUID = 1L;
- protected Unifier unif = null;
- protected Plan plan;
- private Trigger trigger; // the trigger which created this IM
+ protected Unifier unif = null;
+ protected PlanBody planBody;
+ protected Plan plan;
+ private Trigger trigger; // the trigger which created this IM
public IntendedMeans(Option opt, Trigger te) {
- plan = opt.getPlan().cloneOnlyBody();
- unif = opt.getUnifier(); //(Unifier)opt.getUnifier().clone();
+ plan = opt.getPlan();
+ planBody = plan.getBody();
+ unif = opt.getUnifier();
if (te == null) {
- trigger = plan.getTrigger();
+ trigger = plan.getTrigger().clone();
} else {
- trigger = (Trigger)te.clone();
- trigger.getLiteral().apply(unif);
+ trigger = te;
}
+ trigger.apply(unif);
}
- private IntendedMeans() {
- // used for clone
- }
+ // used by clone
+ private IntendedMeans() { }
/** removes the current action of the IM and returns the term of the body */
public Term removeCurrentStep() {
- PlanBody current = plan.getBody();
- if (current.isEmptyBody()) {
+ if (isFinished()) {
return null;
} else {
- return current.removeBody(0);
+ Term r = planBody.getBodyTerm();
+ planBody = planBody.getBodyNext();
+ return r;
}
}
public PlanBody getCurrentStep() {
- return plan.getBody();
+ return planBody;
}
+ // used by if/for/loop internal actions
+ public PlanBody insertAsNextStep(PlanBody pb2add) {
+ planBody = new PlanBodyImpl(planBody.getBodyType(), planBody.getBodyTerm());
+ planBody.setBodyNext(pb2add);
+ return planBody;
+ }
public Plan getPlan() {
return plan;
@@ -103,7 +111,7 @@
}
public boolean isFinished() {
- return plan.getBody().isEmptyBody();
+ return planBody == null || planBody.isEmptyBody();
}
public boolean isGoalAdd() {
@@ -112,23 +120,23 @@
public Object clone() {
IntendedMeans c = new IntendedMeans();
- c.unif = this.unif.clone();
- c.plan = (Plan)this.plan.clone();
- c.trigger = (Trigger)this.trigger.clone();
+ c.unif = this.unif.clone();
+ c.planBody = this.planBody.clonePB();
+ c.trigger = this.trigger.clone();
return c;
}
public String toString() {
- return plan + " / " + unif;
+ return planBody + " / " + unif;
}
public Term getAsTerm() {
Structure im = new Structure("im");
im.addTerm(new StringTermImpl(plan.getLabel().toString()));
- if (plan.getBody() instanceof PlanBodyImpl) {
+ if (planBody instanceof PlanBodyImpl) {
ListTerm lt = new ListTermImpl();
- for (PlanBody bd: (PlanBodyImpl)plan.getBody()) {
- PlanBody c = (PlanBody)bd.clone();
+ for (PlanBody bd: (PlanBodyImpl)planBody) {
+ PlanBody c = bd.clonePB();
c.apply(unif);
lt.add(new StringTermImpl(c.getBodyType().toString()+c.getBodyTerm()));
}
@@ -141,8 +149,8 @@
public Element getAsDOM(Document document) {
Element eim = (Element) document.createElement("intended-means");
eim.setAttribute("trigger", trigger.toString());
- if (plan != null) {
- eim.appendChild(plan.getAsDOM(document));
+ if (planBody != null) {
+ eim.appendChild(planBody.getAsDOM(document));
}
if (unif != null && unif.size() > 0) {
eim.appendChild(unif.getAsDOM(document));
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2009-03-16 14:35:31 UTC (rev 1469)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2009-03-16 22:06:38 UTC (rev 1470)
@@ -42,11 +42,14 @@
import jason.asSyntax.Term;
import jason.asSyntax.Trigger;
import jason.asSyntax.VarTerm;
+import jason.asSyntax.PlanBody.BodyType;
import jason.asSyntax.Trigger.TEOperator;
import jason.asSyntax.Trigger.TEType;
import jason.asSyntax.parser.ParseException;
import jason.bb.BeliefBase;
import jason.runtime.Settings;
+import jason.stdlib.foreach;
+import jason.stdlib.loop;
import java.util.Iterator;
import java.util.LinkedList;
@@ -427,10 +430,33 @@
}
Unifier u = im.unif;
PlanBody h = im.getCurrentStep();
- h.applyHead(u);
-
+
+ Term bTerm = h.getBodyTerm();
+ // de-var bTerm
+ while (bTerm instanceof VarTerm) { // TODO: test var in var
+ // h should be ground
+ Term bValue = u.get((VarTerm)bTerm);
+ if (bValue == null) { // the case of !A with A not ground
+ if (!generateGoalDeletion(conf.C.SI, null)) {
+ logger.log(Level.SEVERE, h.getSrcInfo()+": "+ "Variable '"+bTerm+"' must be ground.");
+ }
+ return;
+ }
+ if (bValue.isPlanBody()) {
+ if (h.getBodyType() != BodyType.action) { // the case of !A with A unified with +g
+ if (!generateGoalDeletion(conf.C.SI, null)) {
+ logger.log(Level.SEVERE, h.getSrcInfo()+": "+ "The operator '"+h.getBodyType()+"' is lost with the variable unified with a plan body. ");
+ }
+ return;
+ }
+ h = (PlanBody)bValue; // TODO: change the current plan for the apply of the plan of VAR // the case of A unified with {a;b;c}
+ bTerm = h.getBodyTerm();
+ } else {
+ bTerm = bValue;
+ }
+ }
+
Literal body = null;
- Term bTerm = h.getBodyTerm();
if (bTerm instanceof Literal)
body = (Literal)bTerm;
@@ -438,6 +464,7 @@
// Rule Action
case action:
+ body = body.copy(); body.apply(u);
confP.C.A = new ActionExec(body, conf.C.SI);
break;
@@ -446,7 +473,14 @@
List<Term> errorAnnots = null;
try {
InternalAction ia = ((InternalActionLiteral)bTerm).getIA(ag);
- Object oresult = ia.execute(this, u, body.getTermsArray());
+ // clone and apply args
+ Term[] terms = new Term[body.getArity()];
+ for (int i=0; i<terms.length; i++) {
+ terms[i] = body.getTerm(i).clone();
+ if ( !(ia instanceof loop) && !(ia instanceof foreach)) // loop e foreach must not apply
+ terms[i].apply(u);
+ }
+ Object oresult = ia.execute(this, u, terms);
if (oresult != null) {
ok = oresult instanceof Boolean && (Boolean)oresult;
if (!ok && oresult instanceof Iterator) { // ia result is an Iterator
@@ -494,16 +528,14 @@
// Rule Achieve
case achieve:
- body = addSelfSource(body.copy());
- body.makeVarsAnnon(u); // free variables in an event cannot conflict with those in the plan
+ body = prepareBodyForEvent(body, u);
conf.C.addAchvGoal(body, conf.C.SI);
confP.step = State.StartRC;
break;
// Rule Achieve as a New Focus (the !! operator)
case achieveNF:
- body = addSelfSource(body.copy());
- body.makeVarsAnnon(u); // free variables in an event cannot conflict with those in the plan
+ body = prepareBodyForEvent(body, u);
conf.C.addAchvGoal(body, Intention.EmptyInt);
updateIntention();
break;
@@ -516,9 +548,8 @@
} else {
boolean fail = true;
if (f instanceof Literal) { // generate event when using literal in the test (no events for log. expr. like ?(a & b))
- body = (Literal)f.clone();
+ body = prepareBodyForEvent(body, u);
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(u);
Trigger te = new Trigger(TEOperator.add, TEType.test, body);
if (ag.getPL().hasCandidatePlan(te)) {
Event evt = new Event(te, conf.C.SI);
@@ -540,13 +571,14 @@
case delAddBel:
// -+a(1,X) ===> remove a(_,_), add a(1,X)
// change all vars to anon vars to remove it
- body = addSelfSource(body.copy());
- body.makeTermsAnnon();
+ Literal b2 = prepareBodyForEvent(body, u);
+ b2.makeTermsAnnon(); // do not change body (but b2), to not interfere in addBel
// to delete, create events as external to avoid that
// remove/add create two events for the same intention
+ // (in future releases, creates a two branches for this operator)
try {
- List<Literal>[] result = ag.brf(null, body, conf.C.SI); // the intention is not the new focus
+ List<Literal>[] result = ag.brf(null, b2, conf.C.SI); // the intention is not the new focus
if (result != null) { // really delete something
// generate events
updateEvents(result,Intention.EmptyInt);
@@ -560,15 +592,12 @@
// Rule AddBel
case addBel:
- body = addSelfSource(body);
+ body = prepareBodyForEvent(body, u);
// calculate focus
Intention newfocus = Intention.EmptyInt;
if (setts.sameFocus())
newfocus = conf.C.SI;
-
- // rename free vars
- body.makeVarsAnnon(u);
// call BRF
try {
@@ -588,7 +617,7 @@
break;
case delBel:
- body = addSelfSource(body);
+ body = prepareBodyForEvent(body, u);
newfocus = Intention.EmptyInt;
if (setts.sameFocus())
@@ -614,17 +643,13 @@
}
// add the self source in the body in case no other source was given
- private Literal addSelfSource(Literal body) {
- // manage the case of var unified with atom
- if (body instanceof VarTerm) {
- Term v = ((VarTerm)body).getValue();
- if (v != null && v.isAtom())
- body = ((Atom)v);
- }
+ private Literal prepareBodyForEvent(Literal body, Unifier u) {
+ body = body.copy();
+ body.apply(u);
+ body.makeVarsAnnon(u); // free variables in an event cannot conflict with those in the plan
body = body.forceFullLiteralImpl();
if (!body.hasSource()) {
- // do not add source(self) in case the
- // programmer set the source
+ // do not add source(self) in case the programmer set the source
body.addAnnot(BeliefBase.TSelf);
}
return body;
Modified: trunk/src/jason/asSyntax/InternalActionLiteral.java
===================================================================
--- trunk/src/jason/asSyntax/InternalActionLiteral.java 2009-03-16 14:35:31 UTC (rev 1469)
+++ trunk/src/jason/asSyntax/InternalActionLiteral.java 2009-03-16 22:06:38 UTC (rev 1470)
@@ -26,8 +26,6 @@
import jason.asSemantics.Agent;
import jason.asSemantics.InternalAction;
import jason.asSemantics.Unifier;
-import jason.stdlib.foreach;
-import jason.stdlib.loop;
import java.util.Iterator;
import java.util.logging.Level;
@@ -76,15 +74,7 @@
public boolean isAtom() {
return false;
}
-
- @Override
- public boolean apply(Unifier u) {
- if (this.ia != null && (this.ia instanceof loop || this.ia instanceof foreach))
- return false;
- else
- return super.apply(u);
- }
-
+
@SuppressWarnings("unchecked")
public Iterator<Unifier> logicalConsequence(Agent ag, Unifier un) {
if (ag.getTS().getUserAgArch().isRunning()) {
Modified: trunk/src/jason/asSyntax/PlanBody.java
===================================================================
--- trunk/src/jason/asSyntax/PlanBody.java 2009-03-16 14:35:31 UTC (rev 1469)
+++ trunk/src/jason/asSyntax/PlanBody.java 2009-03-16 22:06:38 UTC (rev 1470)
@@ -1,6 +1,5 @@
package jason.asSyntax;
-import jason.asSemantics.Unifier;
/**
* Interface for elements of a plans's body.
@@ -29,9 +28,6 @@
public boolean isEmptyBody();
public int getPlanSize();
- /** apply unifier only on first element of the body */
- public boolean applyHead(Unifier u);
-
public void setBodyType(BodyType bt);
public void setBodyTerm(Term t);
public void setBodyNext(PlanBody bl);
Modified: trunk/src/jason/asSyntax/PlanBodyImpl.java
===================================================================
--- trunk/src/jason/asSyntax/PlanBodyImpl.java 2009-03-16 14:35:31 UTC (rev 1469)
+++ trunk/src/jason/asSyntax/PlanBodyImpl.java 2009-03-16 22:06:38 UTC (rev 1470)
@@ -145,7 +145,7 @@
if (i == 1) System.out.println("Should not setTerm(1) of body literal!");
}
- public boolean applyHead(Unifier u) {
+ private boolean applyHead(Unifier u) {
if (term != null && term.apply(u)) {
if (term.isPlanBody()) { // we cannot have "inner" body literals
PlanBody baknext = next;
Modified: trunk/src/jason/asSyntax/VarTerm.java
===================================================================
--- trunk/src/jason/asSyntax/VarTerm.java 2009-03-16 14:35:31 UTC (rev 1469)
+++ trunk/src/jason/asSyntax/VarTerm.java 2009-03-16 22:06:38 UTC (rev 1470)
@@ -955,13 +955,6 @@
return null;
}
- public boolean applyHead(Unifier u) {
- if (value != null && getValue() instanceof PlanBody)
- return ((PlanBody) getValue()).applyHead(u);
- else
- return true;
- }
-
public boolean isEmptyBody() {
if (value != null && getValue() instanceof PlanBody)
return ((PlanBody) getValue()).isEmptyBody();
Modified: trunk/src/jason/stdlib/foreach.java
===================================================================
--- trunk/src/jason/stdlib/foreach.java 2009-03-16 14:35:31 UTC (rev 1469)
+++ trunk/src/jason/stdlib/foreach.java 2009-03-16 22:06:38 UTC (rev 1470)
@@ -114,7 +114,7 @@
// get all solutions for the loop
// Note: you should get all solutions here, otherwise a concurrent modification will occur for the iterator
LogicalFormula logExpr = (LogicalFormula)args[0];
- iu = logExpr.logicalConsequence(ts.getAg(), un.clone());
+ iu = logExpr.logicalConsequence(ts.getAg(), un);
List<Unifier> allsol = new ArrayList<Unifier>();
while (iu.hasNext())
allsol.add(iu.next());
@@ -122,6 +122,9 @@
if (allsol.isEmpty()) // none iteration
return true;
iu = allsol.iterator();
+
+ foria = new PlanBodyImpl(BodyType.internalAction, foria.getBodyTerm().clone());
+ foria.add(im.getCurrentStep().getBodyNext());
((Structure)foria.getBodyTerm()).addTerm(new ObjectTermImpl(iu));
} else if (args.length == 3) {
// restore the solutions
@@ -132,16 +135,18 @@
un.clear();
un.compose(iu.next());
-
// add in the current intention:
// 1. the body argument of for and
- // 2. a copy of the for internal action after the execution of the body
+ // 2. the for internal action after the execution of the body
// (to perform the next iteration)
- PlanBody whattoadd = (PlanBody)args[1].clone();
- if (iu.hasNext())
- whattoadd.add(new PlanBodyImpl(BodyType.internalAction, foria.getBodyTerm().clone()));
+ PlanBody whattoadd = (PlanBody)args[1];
+ if (iu.hasNext()) {
+ whattoadd.add(foria);
+ } else {
+ whattoadd.add(foria.getBodyNext());
+ }
whattoadd.setAsBodyTerm(false);
- foria.add(1,whattoadd);
+ im.insertAsNextStep(whattoadd);
return true;
}
}
Modified: trunk/src/jason/stdlib/if_then_else.java
===================================================================
--- trunk/src/jason/stdlib/if_then_else.java 2009-03-16 14:35:31 UTC (rev 1469)
+++ trunk/src/jason/stdlib/if_then_else.java 2009-03-16 22:06:38 UTC (rev 1470)
@@ -102,9 +102,9 @@
if (whattoadd != null) {
IntendedMeans im = ts.getC().getSelectedIntention().peek();
- PlanBody ifia = im.getCurrentStep();
+ whattoadd.add(im.getCurrentStep().getBodyNext());
whattoadd.setAsBodyTerm(false);
- ifia.add(1,whattoadd);
+ im.insertAsNextStep(whattoadd);
}
return true;
}
Modified: trunk/src/jason/stdlib/loop.java
===================================================================
--- trunk/src/jason/stdlib/loop.java 2009-03-16 14:35:31 UTC (rev 1469)
+++ trunk/src/jason/stdlib/loop.java 2009-03-16 22:06:38 UTC (rev 1470)
@@ -101,8 +101,9 @@
// first execution of while
checkArguments(args);
// add backup unifier in the IA
+ whileia = new PlanBodyImpl(BodyType.internalAction, whileia.getBodyTerm().clone());
((Structure)whileia.getBodyTerm()).addTerm(new ObjectTermImpl(un.clone()));
- } else if (args.length == 3) {
+ } else if (args.length == 3) {
// restore the unifier of previous iterations
Unifier ubak = (Unifier)((ObjectTerm)args[2]).getObject();
un.clear();
@@ -119,12 +120,12 @@
// add in the current intention:
// 1. the body argument and
- // 2. a copy of the while internal action after the execution of the body
+ // 2. the while internal action after the execution of the body
// (to test the loop again)
PlanBody whattoadd = (PlanBody)args[1];
- whattoadd.add(new PlanBodyImpl(BodyType.internalAction, whileia.getBodyTerm().clone()));
+ whattoadd.add(whileia);
whattoadd.setAsBodyTerm(false);
- whileia.add(1,whattoadd);
+ im.insertAsNextStep(whattoadd);
}
return true;
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-03-17 17:00:37
|
Revision: 1471
http://jason.svn.sourceforge.net/jason/?rev=1471&view=rev
Author: jomifred
Date: 2009-03-17 17:00:23 +0000 (Tue, 17 Mar 2009)
Log Message:
-----------
improve tests for vars as plan body
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java
trunk/src/jason/JasonException.java
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/test/ASParserTest.java
Modified: trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java 2009-03-16 22:06:38 UTC (rev 1470)
+++ trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java 2009-03-17 17:00:23 UTC (rev 1471)
@@ -21,8 +21,16 @@
"+!test3 <- !g2(-1 + 2)."+
"+!test4 <- X = {a(1); b; c}; !g(X)."+
+ "+!test5 <- !g5(R); jason.asunit.print(R). "+
+ "+!g5(X) <- C; .print(errrrrror). "+
+ "-!g5(X)[error(I),error_msg(M)] <- jason.asunit.print(I,M); X = ok. "+
+
+ "+!test6 <- A = { a }; B = { A }; C = { B }; C; jason.asunit.print(end). "+
+
+ "+!test7(X) <- A = { jason.asunit.print(a,X); jason.asunit.print(b,X*2) }; A; jason.asunit.print(end,X/2). "+
+
"+!g({A; R}) <- A; !g(R). "+
- "+!g(A) <- A." +
+ "+!g(A) <- A." +
"+!g2(A) <- jason.asunit.print(A)."
);
}
@@ -31,7 +39,7 @@
public void testProgram1a() {
ag.addGoal("start");
ag.assertBel("g({a(1);b;c})", 5);
- ag.assertAct("a(1)", 4);
+ ag.assertAct("a(1)", 5);
ag.assertAct("b", 4);
ag.assertAct("c", 4);
}
@@ -56,4 +64,25 @@
ag.assertPrint("1", 5);
}
+ @Test
+ public void test5() {
+ ag.addGoal("test5");
+ ag.assertPrint("body_var_ungroundstringcode:1: Variable 'C' must be ground.",10);
+ ag.assertPrint("ok", 10);
+ }
+
+ @Test
+ public void test6() {
+ ag.addGoal("test6");
+ ag.assertAct("a", 5);
+ ag.assertPrint("end", 5);
+ }
+
+ @Test
+ public void test7() {
+ ag.addGoal("test7(100)");
+ ag.assertPrint("a100", 5);
+ ag.assertPrint("b200", 5);
+ ag.assertPrint("end50", 5);
+ }
}
Modified: trunk/src/jason/JasonException.java
===================================================================
--- trunk/src/jason/JasonException.java 2009-03-16 22:06:38 UTC (rev 1470)
+++ trunk/src/jason/JasonException.java 2009-03-17 17:00:23 UTC (rev 1471)
@@ -118,15 +118,5 @@
return ASSyntax.createList(
ASSyntax.createStructure("error", id),
ASSyntax.createStructure("error_msg", ASSyntax.createString(msg)));
- /*
- ListTerm failAnnots = new ListTermImpl();
- Structure e = new Structure("error", 1);
- e.addTerm(id);
- failAnnots.add(e);
- Structure m = new Structure("error_msg", 1);
- m.addTerm(new StringTermImpl(msg));
- failAnnots.add(m);
- return failAnnots;
- */
}
}
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2009-03-16 22:06:38 UTC (rev 1470)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2009-03-17 17:00:23 UTC (rev 1471)
@@ -430,26 +430,32 @@
}
Unifier u = im.unif;
PlanBody h = im.getCurrentStep();
-
+
Term bTerm = h.getBodyTerm();
// de-var bTerm
- while (bTerm instanceof VarTerm) { // TODO: test var in var
+ while (bTerm instanceof VarTerm) {
// h should be ground
Term bValue = u.get((VarTerm)bTerm);
if (bValue == null) { // the case of !A with A not ground
- if (!generateGoalDeletion(conf.C.SI, null)) {
- logger.log(Level.SEVERE, h.getSrcInfo()+": "+ "Variable '"+bTerm+"' must be ground.");
+ String msg = h.getSrcInfo()+": "+ "Variable '"+bTerm+"' must be ground.";
+ if (!generateGoalDeletion(conf.C.SI, JasonException.createBasicErrorAnnots("body_var_unground", msg))) {
+ logger.log(Level.SEVERE, msg);
}
return;
}
if (bValue.isPlanBody()) {
- if (h.getBodyType() != BodyType.action) { // the case of !A with A unified with +g
- if (!generateGoalDeletion(conf.C.SI, null)) {
- logger.log(Level.SEVERE, h.getSrcInfo()+": "+ "The operator '"+h.getBodyType()+"' is lost with the variable unified with a plan body. ");
+ if (h.getBodyType() != BodyType.action) { // the case of ...; A = { !g }; +g; ....
+ String msg = h.getSrcInfo()+": "+ "The operator '"+h.getBodyType()+"' is lost with the variable '"+bTerm+"' unified with a plan body '"+bValue+"'. ";
+ if (!generateGoalDeletion(conf.C.SI, JasonException.createBasicErrorAnnots("body_var_with_op", msg))) {
+ logger.log(Level.SEVERE, msg);
}
return;
}
- h = (PlanBody)bValue; // TODO: change the current plan for the apply of the plan of VAR // the case of A unified with {a;b;c}
+ h = (PlanBody)bValue;
+ if (h.getPlanSize() > 1) { // the case of A unified with {a;b;c}
+ h.add(im.getCurrentStep().getBodyNext());
+ im.insertAsNextStep(h.getBodyNext());
+ }
bTerm = h.getBodyTerm();
} else {
bTerm = bValue;
@@ -678,7 +684,6 @@
IntendedMeans topIM = i.pop();
Literal topLiteral = topIM.getTrigger().getLiteral();
if (logger.isLoggable(Level.FINE)) logger.fine("Returning from IM "+topIM.getPlan().getLabel()+", te="+topIM.getPlan().getTrigger());
-
// if finished a failure handling IM ...
if (im.getTrigger().isGoal() && !im.getTrigger().isAddition() && i.size() > 0) {
// needs to get rid of the IM until a goal that
@@ -691,8 +696,9 @@
// should became
// +!s: !z
im = i.peek();
- if (im.isFinished() || !im.unif.unifies(im.getCurrentStep().getBodyTerm(), topLiteral))
+ if (im.isFinished() || !im.unif.unifies(im.getCurrentStep().getBodyTerm(), topLiteral) || im.getCurrentStep().getBodyTerm() instanceof VarTerm) {
im = i.pop(); // +!c above
+ }
while (i.size() > 0 &&
!im.unif.unifies(im.getTrigger().getLiteral(), topLiteral) &&
!im.unif.unifies(im.getCurrentStep().getBodyTerm(), topLiteral)) {
@@ -703,30 +709,11 @@
im = i.peek(); // +!s or +?s
if (!im.isFinished()) {
// removes !b or ?s
- /* I am trying against comments below and use topIM.getTrigger!
- * since I don't remember why the trigger cann't be used
- * probably the reason is the old buggy makeVarAnnos
-
- Term g = im.removeCurrentStep();
- // make the TE of finished plan ground and unify that
- // with goal/test in the body (to "return" values).
- // (it must be the plan TE and not the IM.trigger because the
- // vars have name only in the plan TE, in the IM.trigger
- // they are anonymous)
- Literal tel = topIM.getPlan().getTrigger().getLiteral();
- // but import annots from IM.trigger
- tel.addAnnots(topIM.getTrigger().getLiteral().getAnnots());
- tel.topLiteral.makeVarsAnnon(topIM.unif);
- */
// unifies the final event with the body that called it
topLiteral.apply(topIM.unif);
im.unif.unifies(im.removeCurrentStep(), topLiteral);
}
}
-
- // the new top may have become
- // empty! need to keep checking.
- //applyClrInt(i);
}
}
@@ -924,7 +911,7 @@
// code
if (eventLiteral.getAnnots("code").isEmpty())
- eventLiteral.addAnnot(ASSyntax.createStructure("code", bodyterm));
+ eventLiteral.addAnnot(ASSyntax.createStructure("code", ASSyntax.createString(bodyterm.toString())));
// ASL source
if (eventLiteral.getAnnots("code_src").isEmpty())
Modified: trunk/src/test/ASParserTest.java
===================================================================
--- trunk/src/test/ASParserTest.java 2009-03-16 22:06:38 UTC (rev 1470)
+++ trunk/src/test/ASParserTest.java 2009-03-17 17:00:23 UTC (rev 1471)
@@ -20,6 +20,7 @@
import jason.asSyntax.Structure;
import jason.asSyntax.Term;
import jason.asSyntax.Trigger;
+import jason.asSyntax.PlanBody.BodyType;
import jason.asSyntax.parser.ParseException;
import jason.asSyntax.parser.as2j;
import jason.infra.centralised.CentralisedAgArch;
@@ -194,6 +195,11 @@
pb = (PlanBody)ASSyntax.parseTerm("{ }");
assertEquals(0, pb.getPlanSize());
+
+ pb = (PlanBody)ASSyntax.parseTerm("{ a; B}");
+ assertEquals(2, pb.getPlanSize());
+ assertEquals(BodyType.action, pb.getBodyType());
+ assertEquals(BodyType.action, pb.getBodyNext().getBodyType()); // B must be considered as action, see TS
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-03-17 22:19:19
|
Revision: 1472
http://jason.svn.sourceforge.net/jason/?rev=1472&view=rev
Author: jomifred
Date: 2009-03-17 22:19:02 +0000 (Tue, 17 Mar 2009)
Log Message:
-----------
use plan body term for internal action .current_intention
Modified Paths:
--------------
trunk/demos/failure/a.asl
trunk/doc/faq/faq.tex
trunk/src/jason/asSemantics/IntendedMeans.java
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/asSyntax/ASSyntax.java
trunk/src/jason/asSyntax/Literal.java
trunk/src/jason/asSyntax/Pred.java
trunk/src/jason/asSyntax/Structure.java
trunk/src/jason/stdlib/current_intention.java
Modified: trunk/demos/failure/a.asl
===================================================================
--- trunk/demos/failure/a.asl 2009-03-17 17:00:23 UTC (rev 1471)
+++ trunk/demos/failure/a.asl 2009-03-17 22:19:02 UTC (rev 1472)
@@ -12,10 +12,10 @@
.print("current intention is: ",I);
I = intention(Id,IntendedMeans);
.println;
- .println("* Intention ",Id, " IM stack:");
+ .println("* Intention #",Id, ", IM stack:");
!print_im(IntendedMeans).
+!print_im([]).
-+!print_im([im(_Planlabel,Body)|R])
++!print_im([im(_PlanLabel,Body)|R])
<- .println("* ",Body);
!print_im(R).
Modified: trunk/doc/faq/faq.tex
===================================================================
--- trunk/doc/faq/faq.tex 2009-03-17 17:00:23 UTC (rev 1471)
+++ trunk/doc/faq/faq.tex 2009-03-17 22:19:02 UTC (rev 1472)
@@ -887,19 +887,19 @@
\begin{verbatim}
intention(1,
[
- im("l__6[source(self)]",[".current_intention(I)", .....]),
- im("l__5[source(self)]",[".fail"]),
- im("l__4[source(self)]",["!g5(X)[source(self)]",".print(endg4)"]),
- im("l__3[source(self)]",["!g4(X)[source(self)]",".print(endg3)"]),
- im("l__2[source(self)]",["!g3(X)[source(self)]",".print(endg2)"]),
- im("l__1[source(self)]",["!g2(X)[source(self)]",".print(endg1)"]),
- im("l__0[source(self)]",["!g1(X)[source(self)]",".print("End, X=",X)"])
+ im(l__6[source(self)],{ .current_intention(I); ..... }),
+ im(l__5[source(self)],{ .fail"]),
+ im(l__4[source(self)],{ !g5(X)[source(self)]; .print(endg4) }),
+ im(l__3[source(self)],{ !g4(X)[source(self)]; .print(endg3) }),
+ im(l__2[source(self)],{ !g3(X)[source(self)]; .print(endg2) }),
+ im(l__1[source(self)],{ !g2(X)[source(self)]; .print(endg1) }),
+ im(l__0[source(self)],{ !g1(X)[source(self)]; .print("End, X=",X) })
]
)
\end{verbatim}
You can find more information in the documentation of the
- \htlink{current\_intention}{http://jason.sourceforge.net/api/classjason_1_1stdlib_1_1current__intention.html}
+ \htlink{current\_intention}{http://jason.sourceforge.net/api/jason/stdlib/current_intention.html}
pre-defined internal action.
Modified: trunk/src/jason/asSemantics/IntendedMeans.java
===================================================================
--- trunk/src/jason/asSemantics/IntendedMeans.java 2009-03-17 17:00:23 UTC (rev 1471)
+++ trunk/src/jason/asSemantics/IntendedMeans.java 2009-03-17 22:19:02 UTC (rev 1472)
@@ -24,13 +24,10 @@
package jason.asSemantics;
-import jason.asSyntax.ListTerm;
-import jason.asSyntax.ListTermImpl;
+import jason.asSyntax.ASSyntax;
import jason.asSyntax.Plan;
import jason.asSyntax.PlanBody;
import jason.asSyntax.PlanBodyImpl;
-import jason.asSyntax.StringTermImpl;
-import jason.asSyntax.Structure;
import jason.asSyntax.Term;
import jason.asSyntax.Trigger;
@@ -131,18 +128,15 @@
}
public Term getAsTerm() {
- Structure im = new Structure("im");
- im.addTerm(new StringTermImpl(plan.getLabel().toString()));
if (planBody instanceof PlanBodyImpl) {
- ListTerm lt = new ListTermImpl();
- for (PlanBody bd: (PlanBodyImpl)planBody) {
- PlanBody c = bd.clonePB();
- c.apply(unif);
- lt.add(new StringTermImpl(c.getBodyType().toString()+c.getBodyTerm()));
- }
- im.addTerm(lt);
+ //Plan p = new Plan((Pred)plan.getLabel().clone(), getTrigger().clone(), plan.getContext(), planBody.clonePB());
+ //p.makeVarsAnnon();
+ PlanBody bd = (PlanBody)((PlanBodyImpl)planBody.clone()).makeVarsAnnon();
+ bd.setAsBodyTerm(true);
+ return ASSyntax.createStructure("im", ASSyntax.createString(plan.getLabel()), bd);
+ } else {
+ return ASSyntax.createAtom("noimplementedforclass"+planBody.getClass().getSimpleName());
}
- return im;
}
/** get as XML */
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2009-03-17 17:00:23 UTC (rev 1471)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2009-03-17 22:19:02 UTC (rev 1472)
@@ -684,6 +684,7 @@
IntendedMeans topIM = i.pop();
Literal topLiteral = topIM.getTrigger().getLiteral();
if (logger.isLoggable(Level.FINE)) logger.fine("Returning from IM "+topIM.getPlan().getLabel()+", te="+topIM.getPlan().getTrigger());
+
// if finished a failure handling IM ...
if (im.getTrigger().isGoal() && !im.getTrigger().isAddition() && i.size() > 0) {
// needs to get rid of the IM until a goal that
@@ -911,7 +912,7 @@
// code
if (eventLiteral.getAnnots("code").isEmpty())
- eventLiteral.addAnnot(ASSyntax.createStructure("code", ASSyntax.createString(bodyterm.toString())));
+ eventLiteral.addAnnot(ASSyntax.createStructure("code", bodyterm.copy().makeVarsAnnon()));
// ASL source
if (eventLiteral.getAnnots("code_src").isEmpty())
Modified: trunk/src/jason/asSyntax/ASSyntax.java
===================================================================
--- trunk/src/jason/asSyntax/ASSyntax.java 2009-03-17 17:00:23 UTC (rev 1471)
+++ trunk/src/jason/asSyntax/ASSyntax.java 2009-03-17 22:19:02 UTC (rev 1472)
@@ -100,6 +100,10 @@
public static StringTerm createString(String s) {
return new StringTermImpl(s);
}
+ /** creates a new string term using .toString() of the parameter */
+ public static StringTerm createString(Object o) {
+ return new StringTermImpl(o.toString());
+ }
/** creates a new variable term */
public static VarTerm createVar(String functor) {
Modified: trunk/src/jason/asSyntax/Literal.java
===================================================================
--- trunk/src/jason/asSyntax/Literal.java 2009-03-17 17:00:23 UTC (rev 1471)
+++ trunk/src/jason/asSyntax/Literal.java 2009-03-17 22:19:02 UTC (rev 1472)
@@ -125,14 +125,14 @@
/** replaces all terms by unnamed variables (_). */
public void makeTermsAnnon() {}
/** replaces all variables by unnamed variables (_). */
- public void makeVarsAnnon() {}
+ public Literal makeVarsAnnon() { return this; }
/**
* replaces all variables of the term for unnamed variables (_).
*
* @param un is the unifier that contains the map of replacements
*/
- public void makeVarsAnnon(Unifier un) {}
+ public Literal makeVarsAnnon(Unifier un) { return this; }
/** returns all annotations of the literal */
public ListTerm getAnnots() { return null; }
Modified: trunk/src/jason/asSyntax/Pred.java
===================================================================
--- trunk/src/jason/asSyntax/Pred.java 2009-03-17 17:00:23 UTC (rev 1471)
+++ trunk/src/jason/asSyntax/Pred.java 2009-03-17 22:19:02 UTC (rev 1472)
@@ -392,7 +392,7 @@
@Override
- public void makeVarsAnnon(Unifier un) {
+ public Literal makeVarsAnnon(Unifier un) {
if (annots != null) {
Iterator<ListTerm> i = annots.listTermIterator();
while (i.hasNext()) {
@@ -415,7 +415,7 @@
}
}
}
- super.makeVarsAnnon(un);
+ return super.makeVarsAnnon(un);
}
@Override
Modified: trunk/src/jason/asSyntax/Structure.java
===================================================================
--- trunk/src/jason/asSyntax/Structure.java 2009-03-17 17:00:23 UTC (rev 1471)
+++ trunk/src/jason/asSyntax/Structure.java 2009-03-17 22:19:02 UTC (rev 1472)
@@ -271,12 +271,12 @@
}
@Override
- public void makeVarsAnnon() {
- makeVarsAnnon(new Unifier());
+ public Literal makeVarsAnnon() {
+ return makeVarsAnnon(new Unifier());
}
@Override
- public void makeVarsAnnon(Unifier un) {
+ public Literal makeVarsAnnon(Unifier un) {
final int size = getArity();
for (int i=0; i<size; i++) {
Term ti = getTerm(i);
@@ -299,6 +299,7 @@
}
}
resetHashCodeCache();
+ return this;
}
@Override
Modified: trunk/src/jason/stdlib/current_intention.java
===================================================================
--- trunk/src/jason/stdlib/current_intention.java 2009-03-17 17:00:23 UTC (rev 1471)
+++ trunk/src/jason/stdlib/current_intention.java 2009-03-17 22:19:02 UTC (rev 1472)
@@ -41,16 +41,16 @@
where each intended means has the form:<br><br>
- <code>im(<i>plan label</i>,<i>list of body literals</i>)</code><br><br>
+ <code>im(<i>plan label</i>,<i>plan body term</i>)</code><br><br>
For example:<br><br>
<blockquote>
<code>intention(1,<br>
[<br>
- im("l__6[source(self)]",[".current_intention(I)"]),<br>
- im("l__5[source(self)]",[".fail"]),<br>
- im("l__4[source(self)]",["!g5(X)",".print(endg4)"]),<br>
+ im(l__6[source(self)],{ .current_intention(I); .print(end) }),<br>
+ im(l__5[source(self)],{ .fail}),<br>
+ im(l__4[source(self)],{ !g5(X); .print(endg4) }),<br>
...<br>
])</code>
</blockquote>
@@ -65,7 +65,7 @@
<p>Example:<ul>
<li> <code>.current_intention(X)</code>: <code>X</code> unifies with the
- descriptions of the current intention (i.e. the intention that executed this
+ description of the current intention (i.e. the intention that executed this
internal action).</li>
</ul>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-03-18 14:40:29
|
Revision: 1473
http://jason.svn.sourceforge.net/jason/?rev=1473&view=rev
Author: jomifred
Date: 2009-03-18 14:40:06 +0000 (Wed, 18 Mar 2009)
Log Message:
-----------
add unifier in the current_intention
Modified Paths:
--------------
trunk/demos/failure/a.asl
trunk/doc/faq/faq.tex
trunk/release-notes.txt
trunk/src/jason/asSemantics/IntendedMeans.java
trunk/src/jason/asSemantics/Unifier.java
trunk/src/jason/asSyntax/Pred.java
trunk/src/jason/asSyntax/Structure.java
trunk/src/jason/asSyntax/UnnamedVar.java
trunk/src/jason/stdlib/concat.java
trunk/src/jason/stdlib/current_intention.java
trunk/src/jason/stdlib/plan_label.java
trunk/src/jason/stdlib/relevant_plans.java
trunk/src/test/ListTermTest.java
Modified: trunk/demos/failure/a.asl
===================================================================
--- trunk/demos/failure/a.asl 2009-03-17 22:19:02 UTC (rev 1472)
+++ trunk/demos/failure/a.asl 2009-03-18 14:40:06 UTC (rev 1473)
@@ -16,6 +16,6 @@
!print_im(IntendedMeans).
+!print_im([]).
-+!print_im([im(_PlanLabel,Body)|R])
- <- .println("* ",Body);
++!print_im([im(PlanLabel,Body,Unif)|R])
+ <- .println("* ",Body," * unifier: ",Unif);
!print_im(R).
Modified: trunk/doc/faq/faq.tex
===================================================================
--- trunk/doc/faq/faq.tex 2009-03-17 22:19:02 UTC (rev 1472)
+++ trunk/doc/faq/faq.tex 2009-03-18 14:40:06 UTC (rev 1473)
@@ -887,13 +887,13 @@
\begin{verbatim}
intention(1,
[
- im(l__6[source(self)],{ .current_intention(I); ..... }),
- im(l__5[source(self)],{ .fail"]),
- im(l__4[source(self)],{ !g5(X)[source(self)]; .print(endg4) }),
- im(l__3[source(self)],{ !g4(X)[source(self)]; .print(endg3) }),
- im(l__2[source(self)],{ !g3(X)[source(self)]; .print(endg2) }),
- im(l__1[source(self)],{ !g2(X)[source(self)]; .print(endg1) }),
- im(l__0[source(self)],{ !g1(X)[source(self)]; .print("End, X=",X) })
+ im(l__6[source(self)], { .current_intention(I); ... }, [map(I,...),...]),
+ im(l__5[source(self)], { .fail }, []),
+ im(l__4[source(self)], { !g5(X); .print(endg4) }, [map(X,failure)]),
+ im(l__3[source(self)], { !g4(X); .print(endg3) }, [map(X,failure)]),
+ im(l__2[source(self)], { !g3(X); .print(endg2) }, [map(X,failure)]),
+ im(l__1[source(self)], { !g2(X); .print(endg1) }, [map(X,failure)]),
+ im(l__0[source(self)], { !g1(X); .print("End, X=",X) }, [map(X,failure)])
]
)
\end{verbatim}
Modified: trunk/release-notes.txt
===================================================================
--- trunk/release-notes.txt 2009-03-17 22:19:02 UTC (rev 1472)
+++ trunk/release-notes.txt 2009-03-18 14:40:06 UTC (rev 1473)
@@ -15,6 +15,11 @@
It may be used in send tellHow
.send(bob, tellHow, { +te : c <- a1 }).
+
+ It is also used by internal actions that 'return' plans, like
+ . plan_label
+ . relevant_plans
+ . current_intention
The advantages are that unification works
e.g. .at("now +1 m", {+stop(ID)})
@@ -30,7 +35,10 @@
// add a plan with a fixed event/context and body
// given as a parameter
-
+- The performance is improved (+- 15%) by not cloning all the
+ plan in the creation of intended means
+
+
Changes in the GUI
- When closing the window of MAS Console, the application is also
stopped.
Modified: trunk/src/jason/asSemantics/IntendedMeans.java
===================================================================
--- trunk/src/jason/asSemantics/IntendedMeans.java 2009-03-17 22:19:02 UTC (rev 1472)
+++ trunk/src/jason/asSemantics/IntendedMeans.java 2009-03-18 14:40:06 UTC (rev 1473)
@@ -129,11 +129,10 @@
public Term getAsTerm() {
if (planBody instanceof PlanBodyImpl) {
- //Plan p = new Plan((Pred)plan.getLabel().clone(), getTrigger().clone(), plan.getContext(), planBody.clonePB());
- //p.makeVarsAnnon();
+ // TODO: use same replacements (Var -> Unnamed var) for the plan and for the unifier
PlanBody bd = (PlanBody)((PlanBodyImpl)planBody.clone()).makeVarsAnnon();
bd.setAsBodyTerm(true);
- return ASSyntax.createStructure("im", ASSyntax.createString(plan.getLabel()), bd);
+ return ASSyntax.createStructure("im", ASSyntax.createString(plan.getLabel()), bd, unif.getAsTerm());
} else {
return ASSyntax.createAtom("noimplementedforclass"+planBody.getClass().getSimpleName());
}
Modified: trunk/src/jason/asSemantics/Unifier.java
===================================================================
--- trunk/src/jason/asSemantics/Unifier.java 2009-03-17 22:19:02 UTC (rev 1472)
+++ trunk/src/jason/asSemantics/Unifier.java 2009-03-18 14:40:06 UTC (rev 1473)
@@ -23,10 +23,15 @@
package jason.asSemantics;
+import jason.asSyntax.ASSyntax;
+import jason.asSyntax.ListTerm;
+import jason.asSyntax.ListTermImpl;
import jason.asSyntax.Literal;
import jason.asSyntax.Pred;
+import jason.asSyntax.Structure;
import jason.asSyntax.Term;
import jason.asSyntax.Trigger;
+import jason.asSyntax.UnnamedVar;
import jason.asSyntax.VarTerm;
import java.util.HashMap;
@@ -279,6 +284,19 @@
public String toString() {
return function.toString();
}
+
+ public Term getAsTerm() {
+ ListTerm lf = new ListTermImpl();
+ ListTerm tail = lf;
+ for (VarTerm k: function.keySet()) {
+ Term vl = function.get(k).clone();
+ if (vl instanceof Literal)
+ ((Literal)vl).makeVarsAnnon();
+ Structure pair = ASSyntax.createStructure("map", new UnnamedVar("_"+UnnamedVar.getUniqueId()+k), vl); // the var must be changed to avoid cyclic references latter
+ tail = tail.append(pair);
+ }
+ return lf;
+ }
public int size() {
return function.size();
Modified: trunk/src/jason/asSyntax/Pred.java
===================================================================
--- trunk/src/jason/asSyntax/Pred.java 2009-03-17 22:19:02 UTC (rev 1472)
+++ trunk/src/jason/asSyntax/Pred.java 2009-03-18 14:40:06 UTC (rev 1473)
@@ -406,7 +406,7 @@
if (vt.isUnnamedVar()) {
uv = (UnnamedVar)vt;
} else {
- uv = new UnnamedVar();
+ uv = new UnnamedVar("_"+UnnamedVar.getUniqueId()+ta);
un.bind(vt, uv);
}
lt.setTerm(uv);
Modified: trunk/src/jason/asSyntax/Structure.java
===================================================================
--- trunk/src/jason/asSyntax/Structure.java 2009-03-17 22:19:02 UTC (rev 1472)
+++ trunk/src/jason/asSyntax/Structure.java 2009-03-18 14:40:06 UTC (rev 1473)
@@ -287,7 +287,7 @@
if (vt.isUnnamedVar()) {
uv = (UnnamedVar)vt;
} else {
- uv = new UnnamedVar();
+ uv = new UnnamedVar( "_"+UnnamedVar.getUniqueId()+ti);
un.bind(vt, uv);
}
setTerm(i,uv);
Modified: trunk/src/jason/asSyntax/UnnamedVar.java
===================================================================
--- trunk/src/jason/asSyntax/UnnamedVar.java 2009-03-17 22:19:02 UTC (rev 1472)
+++ trunk/src/jason/asSyntax/UnnamedVar.java 2009-03-18 14:40:06 UTC (rev 1473)
@@ -42,13 +42,17 @@
public UnnamedVar(String name) {
super( name.length() == 1 ? "_" + (varCont++) : name);
- myId = varCont++;
+ myId = varCont;
}
public UnnamedVar(int id) {
super("_" + id);
myId = id;
}
+
+ public static int getUniqueId() {
+ return varCont++;
+ }
public Term clone() {
if (hasValue()) {
Modified: trunk/src/jason/stdlib/concat.java
===================================================================
--- trunk/src/jason/stdlib/concat.java 2009-03-17 22:19:02 UTC (rev 1472)
+++ trunk/src/jason/stdlib/concat.java 2009-03-18 14:40:06 UTC (rev 1473)
@@ -53,6 +53,13 @@
<li> <code>.concat([a,b,c],[d,e],[f,g],X)</code>: <code>X</code> unifies with <code>[a,b,c,d,e,f,g]</code>.
</ul>
+ <p>Note: this internal action does not implement backtrack. You if need backtrack, you can add
+ and use the following rules in your code:
+ <pre>
+ concat([ ], L, L).
+ concat([H|T], L, [H|M]) :- concat(T, L, M).
+ </pre>
+
@see jason.stdlib.delete
@see jason.stdlib.length
@see jason.stdlib.member
@@ -94,7 +101,7 @@
return un.unifies(result, args[args.length-1]);
- } else {
+ } else if (args[0].isString()) {
// string concat
if (!args[args.length-1].isVar() && !args[args.length-1].isString()) {
throw JasonException.createWrongArgument(this,"Last argument '"+args[args.length-1]+"' is not a string nor a variable.");
@@ -112,6 +119,8 @@
sr.append(vl);
}
return un.unifies(new StringTermImpl(sr.toString()), args[args.length-1]);
+ } else {
+ throw JasonException.createWrongArgument(this,"First argument '"+args[0]+"' must be a list or string.");
}
}
}
Modified: trunk/src/jason/stdlib/current_intention.java
===================================================================
--- trunk/src/jason/stdlib/current_intention.java 2009-03-17 22:19:02 UTC (rev 1472)
+++ trunk/src/jason/stdlib/current_intention.java 2009-03-18 14:40:06 UTC (rev 1473)
@@ -41,16 +41,16 @@
where each intended means has the form:<br><br>
- <code>im(<i>plan label</i>,<i>plan body term</i>)</code><br><br>
+ <code>im(<i>plan label</i>,<i>plan body term</i>, <i>unification function (a list of maps)</i>)</code><br><br>
For example:<br><br>
<blockquote>
<code>intention(1,<br>
[<br>
- im(l__6[source(self)],{ .current_intention(I); .print(end) }),<br>
- im(l__5[source(self)],{ .fail}),<br>
- im(l__4[source(self)],{ !g5(X); .print(endg4) }),<br>
+ im(l__6[source(self)],{ .current_intention(I); .print(end) }, [map(I, ....)]),<br>
+ im(l__5[source(self)],{ .fail }, []),<br>
+ im(l__4[source(self)],{ !g5(X); .print(endg4) }, [map(X, test)]),<br>
...<br>
])</code>
</blockquote>
Modified: trunk/src/jason/stdlib/plan_label.java
===================================================================
--- trunk/src/jason/stdlib/plan_label.java 2009-03-17 22:19:02 UTC (rev 1472)
+++ trunk/src/jason/stdlib/plan_label.java 2009-03-18 14:40:06 UTC (rev 1473)
@@ -80,6 +80,7 @@
p = (Plan)p.clone();
p.getLabel().delSources();
p.setAsPlanTerm(true);
+ p.makeVarsAnnon();
//String ps = p.toASString().replaceAll("\"", "\\\\\"");
//return un.unifies(new StringTermImpl(ps), args[0]);
return un.unifies(p, args[0]);
Modified: trunk/src/jason/stdlib/relevant_plans.java
===================================================================
--- trunk/src/jason/stdlib/relevant_plans.java 2009-03-17 22:19:02 UTC (rev 1472)
+++ trunk/src/jason/stdlib/relevant_plans.java 2009-03-18 14:40:06 UTC (rev 1473)
@@ -95,10 +95,10 @@
for (Option opt: rp) {
// remove sources (this IA is used for communication)
Plan np = (Plan)opt.getPlan().clone();
- if (np.getLabel() != null) {
+ if (np.getLabel() != null)
np.getLabel().delSources();
- }
np.setAsPlanTerm(true);
+ np.makeVarsAnnon();
//StringTerm stplan = new StringTermImpl(np.toASString().replaceAll("\\\"", "\\\\\""));
//last = last.append(stplan);
last = last.append(np);
Modified: trunk/src/test/ListTermTest.java
===================================================================
--- trunk/src/test/ListTermTest.java 2009-03-17 22:19:02 UTC (rev 1472)
+++ trunk/src/test/ListTermTest.java 2009-03-18 14:40:06 UTC (rev 1473)
@@ -1,6 +1,7 @@
package test;
import jason.asSemantics.Unifier;
+import jason.asSyntax.ASSyntax;
import jason.asSyntax.Atom;
import jason.asSyntax.ListTerm;
import jason.asSyntax.ListTermImpl;
@@ -21,11 +22,11 @@
protected void setUp() throws Exception {
super.setUp();
- l1 = ListTermImpl.parseList("[a,b,c]");
- l2 = ListTermImpl.parseList("[a(1,2),b(r,t)|T]");
- l3 = ListTermImpl.parseList("[A|T]");
- l4 = ListTermImpl.parseList("[X,b,T]");
- l5 = ListTermImpl.parseList("[[b,c]]");
+ l1 = ASSyntax.parseList("[a,b,c]");
+ l2 = ASSyntax.parseList("[a(1,2),b(r,t)|T]");
+ l3 = ASSyntax.parseList("[A|T]");
+ l4 = ASSyntax.parseList("[X,b,T]");
+ l5 = ASSyntax.parseList("[[b,c]]");
//System.out.println("l1="+l1+"\nl2="+l2+"\nl3="+l3+"\nl4="+l4);
//System.out.println("l5="+l5);
}
@@ -37,11 +38,17 @@
assertEquals(l4.size(), 3);
assertEquals(l5.size(), 1);
- ListTerm l = new ListTermImpl();
+ ListTerm l = new ListTermImpl();
l.add(new Structure("a"));
l.add(new Structure("a"));
l.add(new Structure("a"));
assertEquals(l.size(), 3);
+
+ assertTrue(l1.isList());
+ assertTrue(l2.isList());
+ assertTrue(l3.isList());
+ assertTrue(l4.isList());
+ assertTrue(l5.isList());
}
public void testToString() {
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-03-19 18:36:11
|
Revision: 1474
http://jason.svn.sourceforge.net/jason/?rev=1474&view=rev
Author: jomifred
Date: 2009-03-19 18:36:05 +0000 (Thu, 19 Mar 2009)
Log Message:
-----------
rename SteppedEnvironment to TimeSteppedEnvironment
Modified Paths:
--------------
trunk/demos/sync-environment/EnvSync.java
trunk/demos/sync-environment/act-sync.mas2j
trunk/examples/game-of-life/LifeEnvironment.java
trunk/examples/gold-miners-II/env/MiningEnvironment.java
trunk/src/jason/environment/SteppedEnvironment.java
Added Paths:
-----------
trunk/src/jason/environment/TimeSteppedEnvironment.java
Modified: trunk/demos/sync-environment/EnvSync.java
===================================================================
--- trunk/demos/sync-environment/EnvSync.java 2009-03-18 14:40:06 UTC (rev 1473)
+++ trunk/demos/sync-environment/EnvSync.java 2009-03-19 18:36:05 UTC (rev 1474)
@@ -2,16 +2,14 @@
import jason.asSyntax.ASSyntax;
import jason.asSyntax.Literal;
-import jason.asSyntax.LiteralImpl;
-import jason.asSyntax.NumberTermImpl;
import jason.asSyntax.Structure;
-import jason.environment.SteppedEnvironment;
+import jason.environment.TimeSteppedEnvironment;
import java.util.logging.Logger;
import screen.Counters;
-public class EnvSync extends SteppedEnvironment {
+public class EnvSync extends TimeSteppedEnvironment {
private Logger logger = Logger.getLogger(EnvSync.class.getName());
Modified: trunk/demos/sync-environment/act-sync.mas2j
===================================================================
--- trunk/demos/sync-environment/act-sync.mas2j 2009-03-18 14:40:06 UTC (rev 1473)
+++ trunk/demos/sync-environment/act-sync.mas2j 2009-03-19 18:36:05 UTC (rev 1474)
@@ -2,7 +2,8 @@
Jason Project
-This project exemplifies the use of SteppedEnvironment. This environment has
+This project exemplifies the use of the class TimeSteppedEnvironment. The
+environment implemented by this class has
steps where each agent can perform only one action. When all agents have
asked for the execution of an action, the actions are really executed, the
perception updated and the next step starts.
Modified: trunk/examples/game-of-life/LifeEnvironment.java
===================================================================
--- trunk/examples/game-of-life/LifeEnvironment.java 2009-03-18 14:40:06 UTC (rev 1473)
+++ trunk/examples/game-of-life/LifeEnvironment.java 2009-03-19 18:36:05 UTC (rev 1474)
@@ -7,7 +7,7 @@
import java.util.logging.Logger;
-public class LifeEnvironment extends jason.environment.SteppedEnvironment {
+public class LifeEnvironment extends jason.environment.TimeSteppedEnvironment {
private Logger logger = Logger.getLogger("game-of-life.mas2j."+LifeEnvironment.class.getName());
Modified: trunk/examples/gold-miners-II/env/MiningEnvironment.java
===================================================================
--- trunk/examples/gold-miners-II/env/MiningEnvironment.java 2009-03-18 14:40:06 UTC (rev 1473)
+++ trunk/examples/gold-miners-II/env/MiningEnvironment.java 2009-03-19 18:36:05 UTC (rev 1474)
@@ -5,7 +5,7 @@
import jason.asSyntax.Literal;
import jason.asSyntax.Structure;
import jason.asSyntax.Term;
-import jason.environment.SteppedEnvironment;
+import jason.environment.TimeSteppedEnvironment;
import jason.environment.grid.Location;
import java.util.Random;
@@ -20,7 +20,7 @@
*
* @author Jomi
*/
-public class MiningEnvironment extends SteppedEnvironment {
+public class MiningEnvironment extends TimeSteppedEnvironment {
private Logger logger = Logger.getLogger("jasonTeamSimLocal.mas2j." + MiningEnvironment.class.getName());
Modified: trunk/src/jason/environment/SteppedEnvironment.java
===================================================================
--- trunk/src/jason/environment/SteppedEnvironment.java 2009-03-18 14:40:06 UTC (rev 1473)
+++ trunk/src/jason/environment/SteppedEnvironment.java 2009-03-19 18:36:05 UTC (rev 1474)
@@ -1,344 +1,7 @@
package jason.environment;
-import jason.asSyntax.Literal;
-import jason.asSyntax.Structure;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Queue;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-
/**
- * General environment class that "synchronise" all agents actions.
- * It waits one action for each agent and, when all actions is received,
- * executes them.
- *
- * @author Jomi
- *
+ * @deprecated this class was renamed to TimeSteppedEnvironment
*/
-public class SteppedEnvironment extends Environment {
-
- private Logger logger = Logger.getLogger(SteppedEnvironment.class.getName());
-
- /** Policy used when a second action is requested and the agent still has another action pending execution */
- public enum OverActionsPolicy {
- /** Queue the second action request for future execution */
- queue,
-
- /** Fail the second action */
- failSecond,
-
- /** Ignore the second action, it is considered as successfully executed */
- ignoreSecond
- };
-
- private int step = 0; // step counter
- private int nbAgs = -1; // number of agents acting on the environment
- private Map<String,ActRequest> requests; // actions to be executed
- private Queue<ActRequest> overRequests; // second action tentative in the step
- private TimeOutThread timeoutThread = null;
- private long stepTimeout = 0;
- private int sleep = 0; // pause time between cycles
-
-
- private OverActionsPolicy overActPol = OverActionsPolicy.ignoreSecond;
-
- public SteppedEnvironment() {
- super(2);
- }
-
- @Override
- public void init(String[] args) {
- super.init(args);
-
- if (args.length > 0) {
- try {
- stepTimeout = Integer.parseInt(args[0]);
- } catch (Exception e) {
- logger.warning("The argument "+args[0]+" is not a valid number for step timeout");
- }
- }
-
- // reset everything
- requests = new HashMap<String,ActRequest>();
- overRequests = new LinkedList<ActRequest>();
- step = 0;
- if (timeoutThread != null) timeoutThread.allAgFinished();
- stepStarted(step);
- }
-
- public void setSleep(int s) {
- sleep = s;
- }
-
-
- @Override
- public void stop() {
- super.stop();
- if (timeoutThread != null) timeoutThread.interrupt();
- }
-
-
- /**
- * Updates the number of agents using the environment, this default
- * implementation, considers all agents in the MAS as actors in the
- * environment.
- */
- protected void updateNumberOfAgents() {
- setNbAgs(getEnvironmentInfraTier().getRuntimeServices().getAgentsNames().size());
- }
-
- /** Returns the number of agents in the MAS (used to test the end of a cycle) */
- public int getNbAgs() {
- return nbAgs;
- }
-
- /** Set the number of agents */
- public void setNbAgs(int n) {
- nbAgs = n;
- }
-
- /** returns the current step counter */
- public int getStep() {
- return step;
- }
-
- /**
- * Sets the policy used for the second ask for an action while another action is not finished yet.
- * If set as queue, the second action is added in a queue for future execution
- * If set as failSecond, the second action fails.
- */
- public void setOverActionsPolicy(OverActionsPolicy p) {
- overActPol = p;
- }
-
- @Override
- public void scheduleAction(String agName, Structure action, Object infraData) {
- if (!isRunning()) return;
- ActRequest newRequest = new ActRequest(agName, action, requiredStepsForAction(agName, action), infraData);
-
- boolean startNew = false;
-
- synchronized (requests) { // lock access to requests
- if (nbAgs < 0 || timeoutThread == null) {
- // initialise dynamic information
- // (must be in sync part, so that more agents do not start the timeout thread)
- updateNumberOfAgents();
- if (stepTimeout > 0 && timeoutThread == null) {
- timeoutThread = new TimeOutThread(stepTimeout);
- timeoutThread.start();
- }
- }
-
- // if the agent already has an action scheduled, fail the first
- ActRequest inSchedule = requests.get(agName);
- if (inSchedule != null) {
- if (overActPol == OverActionsPolicy.queue) {
- overRequests.offer(newRequest);
- } else if (overActPol == OverActionsPolicy.failSecond) {
- getEnvironmentInfraTier().actionExecuted(agName, action, false, infraData);
- } else if (overActPol == OverActionsPolicy.ignoreSecond) {
- getEnvironmentInfraTier().actionExecuted(agName, action, true, infraData);
- }
- } else {
- // store the action request
- requests.put(agName, newRequest);
-
- // test if all agents have sent their actions
- if (testEndCycle(requests.keySet())) {
- startNew = true;
- }
- }
-
- if (startNew) {
- if (sleep > 0) {
- try {
- Thread.sleep(sleep);
- } catch (InterruptedException e) {}
- }
- }
- }
-
- if (startNew) {
- // starts the execution of the next step by another thread, so to not look the agent thread
- executor.execute(new Runnable() {
- public void run() {
- if (timeoutThread != null) timeoutThread.allAgFinished();
- startNewStep();
- }
- });
- }
- }
-
- public Structure getActionInSchedule(String agName) {
- ActRequest inSchedule = requests.get(agName);
- if (inSchedule != null) {
- return inSchedule.action;
- }
- return null;
- }
-
- /**
- * Returns true when a new cycle can start, it normally
- * holds when all agents are in the finishedAgs set.
- *
- * @param finishedAgs the set of agents' name that already finished the current cycle
- */
- protected boolean testEndCycle(Set<String> finishedAgs) {
- return finishedAgs.size() >= getNbAgs();
- }
-
- /** This method is called after the execution of the action and before to send 'continue' to the agents */
- protected void updateAgsPercept() {
- }
-
- private void startNewStep() {
- if (!isRunning()) return;
- synchronized (requests) {
-
- //logger.info("#"+requests.size());
- //logger.info("#"+overRequests.size());
-
- try {
-
- // execute all scheduled actions
- for (ActRequest a: requests.values()) {
- a.remainSteps--;
- if (a.remainSteps == 0) {
- // calls the user implementation of the action
- a.success = executeAction(a.agName, a.action);
- }
- }
-
- updateAgsPercept();
-
- // notify the agents about the result of the execution
- Iterator<ActRequest> i = requests.values().iterator();
- while (i.hasNext()) {
- ActRequest a = i.next();
- if (a.remainSteps == 0) {
- getEnvironmentInfraTier().actionExecuted(a.agName, a.action, a.success, a.infraData);
- i.remove();
- }
- }
-
- // clear all requests
- //requests.clear();
-
- // add actions waiting in over requests into the requests
- Iterator<ActRequest> io = overRequests.iterator();
- while (io.hasNext()) {
- ActRequest a = io.next();
- if (requests.get(a.agName) == null) {
- requests.put(a.agName, a);
- io.remove();
- }
- }
-
- // the over requests could complete the requests
- // so test end of step again
- if (testEndCycle(requests.keySet())) {
- startNewStep();
- }
- } catch (Exception ie) {
- if (isRunning() && !(ie instanceof InterruptedException)) {
- logger.log(Level.WARNING, "act error!",ie);
- }
- }
-
- }
- step++;
- stepStarted(step);
- }
-
- /** to be overridden by the user class */
- protected void stepStarted(int step) {
- }
-
- /** to be overridden by the user class */
- protected void stepFinished(int step, long time, boolean timeout) {
- }
-
- protected int requiredStepsForAction(String agName, Structure action) {
- return 1;
- }
-
- /** stops perception while executing the step's actions */
- @Override
- public List<Literal> getPercepts(String agName) {
- synchronized (requests) {
- return super.getPercepts(agName);
- }
- }
-
- class ActRequest {
- String agName;
- Structure action;
- Object infraData;
- boolean success;
- int remainSteps; // the number os steps this action have to wait to be executed
- public ActRequest(String ag, Structure act, int rs, Object data) {
- agName = ag;
- action = act;
- infraData = data;
- remainSteps = rs;
- }
- public boolean equals(Object obj) {
- return agName.equals(obj);
- }
- public int hashCode() {
- return agName.hashCode();
- }
- public String toString() {
- return "["+agName+","+action+"]";
- }
- }
-
- class TimeOutThread extends Thread {
- Lock lock = new ReentrantLock();
- Condition agActCond = lock.newCondition();
- long timeout = 0;
-
- public TimeOutThread(long to) {
- super("EnvironmentTimeOutThread");
- timeout = to;
- }
-
- public void allAgFinished() {
- lock.lock();
- agActCond.signal();
- lock.unlock();
- }
-
- public void run() {
- try {
- while (true) {
- lock.lock();
- long lastStepStart = System.currentTimeMillis();
- boolean byTimeOut = !agActCond.await(timeout, TimeUnit.MILLISECONDS);
- long now = System.currentTimeMillis();
- long time = (now-lastStepStart);
- stepFinished(step, time, byTimeOut);
- lock.unlock();
-
- if (byTimeOut) {
- startNewStep();
- }
- }
- } catch (InterruptedException e) {
- } catch (Exception e) {
- logger.log(Level.SEVERE, "Error in timeout thread!",e);
- }
- }
- }
+public class SteppedEnvironment extends TimeSteppedEnvironment {
}
Added: trunk/src/jason/environment/TimeSteppedEnvironment.java
===================================================================
--- trunk/src/jason/environment/TimeSteppedEnvironment.java (rev 0)
+++ trunk/src/jason/environment/TimeSteppedEnvironment.java 2009-03-19 18:36:05 UTC (rev 1474)
@@ -0,0 +1,344 @@
+package jason.environment;
+
+import jason.asSyntax.Literal;
+import jason.asSyntax.Structure;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+
+/**
+ * General environment class that "synchronise" all agents actions.
+ * It waits one action for each agent and, when all actions is received,
+ * executes them.
+ *
+ * @author Jomi
+ *
+ */
+public class TimeSteppedEnvironment extends Environment {
+
+ private Logger logger = Logger.getLogger(TimeSteppedEnvironment.class.getName());
+
+ /** Policy used when a second action is requested and the agent still has another action pending execution */
+ public enum OverActionsPolicy {
+ /** Queue the second action request for future execution */
+ queue,
+
+ /** Fail the second action */
+ failSecond,
+
+ /** Ignore the second action, it is considered as successfully executed */
+ ignoreSecond
+ };
+
+ private int step = 0; // step counter
+ private int nbAgs = -1; // number of agents acting on the environment
+ private Map<String,ActRequest> requests; // actions to be executed
+ private Queue<ActRequest> overRequests; // second action tentative in the step
+ private TimeOutThread timeoutThread = null;
+ private long stepTimeout = 0;
+ private int sleep = 0; // pause time between cycles
+
+
+ private OverActionsPolicy overActPol = OverActionsPolicy.ignoreSecond;
+
+ public TimeSteppedEnvironment() {
+ super(2);
+ }
+
+ @Override
+ public void init(String[] args) {
+ super.init(args);
+
+ if (args.length > 0) {
+ try {
+ stepTimeout = Integer.parseInt(args[0]);
+ } catch (Exception e) {
+ logger.warning("The argument "+args[0]+" is not a valid number for step timeout");
+ }
+ }
+
+ // reset everything
+ requests = new HashMap<String,ActRequest>();
+ overRequests = new LinkedList<ActRequest>();
+ step = 0;
+ if (timeoutThread != null) timeoutThread.allAgFinished();
+ stepStarted(step);
+ }
+
+ public void setSleep(int s) {
+ sleep = s;
+ }
+
+
+ @Override
+ public void stop() {
+ super.stop();
+ if (timeoutThread != null) timeoutThread.interrupt();
+ }
+
+
+ /**
+ * Updates the number of agents using the environment, this default
+ * implementation, considers all agents in the MAS as actors in the
+ * environment.
+ */
+ protected void updateNumberOfAgents() {
+ setNbAgs(getEnvironmentInfraTier().getRuntimeServices().getAgentsNames().size());
+ }
+
+ /** Returns the number of agents in the MAS (used to test the end of a cycle) */
+ public int getNbAgs() {
+ return nbAgs;
+ }
+
+ /** Set the number of agents */
+ public void setNbAgs(int n) {
+ nbAgs = n;
+ }
+
+ /** returns the current step counter */
+ public int getStep() {
+ return step;
+ }
+
+ /**
+ * Sets the policy used for the second ask for an action while another action is not finished yet.
+ * If set as queue, the second action is added in a queue for future execution
+ * If set as failSecond, the second action fails.
+ */
+ public void setOverActionsPolicy(OverActionsPolicy p) {
+ overActPol = p;
+ }
+
+ @Override
+ public void scheduleAction(String agName, Structure action, Object infraData) {
+ if (!isRunning()) return;
+ ActRequest newRequest = new ActRequest(agName, action, requiredStepsForAction(agName, action), infraData);
+
+ boolean startNew = false;
+
+ synchronized (requests) { // lock access to requests
+ if (nbAgs < 0 || timeoutThread == null) {
+ // initialise dynamic information
+ // (must be in sync part, so that more agents do not start the timeout thread)
+ updateNumberOfAgents();
+ if (stepTimeout > 0 && timeoutThread == null) {
+ timeoutThread = new TimeOutThread(stepTimeout);
+ timeoutThread.start();
+ }
+ }
+
+ // if the agent already has an action scheduled, fail the first
+ ActRequest inSchedule = requests.get(agName);
+ if (inSchedule != null) {
+ if (overActPol == OverActionsPolicy.queue) {
+ overRequests.offer(newRequest);
+ } else if (overActPol == OverActionsPolicy.failSecond) {
+ getEnvironmentInfraTier().actionExecuted(agName, action, false, infraData);
+ } else if (overActPol == OverActionsPolicy.ignoreSecond) {
+ getEnvironmentInfraTier().actionExecuted(agName, action, true, infraData);
+ }
+ } else {
+ // store the action request
+ requests.put(agName, newRequest);
+
+ // test if all agents have sent their actions
+ if (testEndCycle(requests.keySet())) {
+ startNew = true;
+ }
+ }
+
+ if (startNew) {
+ if (sleep > 0) {
+ try {
+ Thread.sleep(sleep);
+ } catch (InterruptedException e) {}
+ }
+ }
+ }
+
+ if (startNew) {
+ // starts the execution of the next step by another thread, so to not look the agent thread
+ executor.execute(new Runnable() {
+ public void run() {
+ if (timeoutThread != null) timeoutThread.allAgFinished();
+ startNewStep();
+ }
+ });
+ }
+ }
+
+ public Structure getActionInSchedule(String agName) {
+ ActRequest inSchedule = requests.get(agName);
+ if (inSchedule != null) {
+ return inSchedule.action;
+ }
+ return null;
+ }
+
+ /**
+ * Returns true when a new cycle can start, it normally
+ * holds when all agents are in the finishedAgs set.
+ *
+ * @param finishedAgs the set of agents' name that already finished the current cycle
+ */
+ protected boolean testEndCycle(Set<String> finishedAgs) {
+ return finishedAgs.size() >= getNbAgs();
+ }
+
+ /** This method is called after the execution of the action and before to send 'continue' to the agents */
+ protected void updateAgsPercept() {
+ }
+
+ private void startNewStep() {
+ if (!isRunning()) return;
+ synchronized (requests) {
+
+ //logger.info("#"+requests.size());
+ //logger.info("#"+overRequests.size());
+
+ try {
+
+ // execute all scheduled actions
+ for (ActRequest a: requests.values()) {
+ a.remainSteps--;
+ if (a.remainSteps == 0) {
+ // calls the user implementation of the action
+ a.success = executeAction(a.agName, a.action);
+ }
+ }
+
+ updateAgsPercept();
+
+ // notify the agents about the result of the execution
+ Iterator<ActRequest> i = requests.values().iterator();
+ while (i.hasNext()) {
+ ActRequest a = i.next();
+ if (a.remainSteps == 0) {
+ getEnvironmentInfraTier().actionExecuted(a.agName, a.action, a.success, a.infraData);
+ i.remove();
+ }
+ }
+
+ // clear all requests
+ //requests.clear();
+
+ // add actions waiting in over requests into the requests
+ Iterator<ActRequest> io = overRequests.iterator();
+ while (io.hasNext()) {
+ ActRequest a = io.next();
+ if (requests.get(a.agName) == null) {
+ requests.put(a.agName, a);
+ io.remove();
+ }
+ }
+
+ // the over requests could complete the requests
+ // so test end of step again
+ if (testEndCycle(requests.keySet())) {
+ startNewStep();
+ }
+ } catch (Exception ie) {
+ if (isRunning() && !(ie instanceof InterruptedException)) {
+ logger.log(Level.WARNING, "act error!",ie);
+ }
+ }
+
+ }
+ step++;
+ stepStarted(step);
+ }
+
+ /** to be overridden by the user class */
+ protected void stepStarted(int step) {
+ }
+
+ /** to be overridden by the user class */
+ protected void stepFinished(int step, long time, boolean timeout) {
+ }
+
+ protected int requiredStepsForAction(String agName, Structure action) {
+ return 1;
+ }
+
+ /** stops perception while executing the step's actions */
+ @Override
+ public List<Literal> getPercepts(String agName) {
+ synchronized (requests) {
+ return super.getPercepts(agName);
+ }
+ }
+
+ class ActRequest {
+ String agName;
+ Structure action;
+ Object infraData;
+ boolean success;
+ int remainSteps; // the number os steps this action have to wait to be executed
+ public ActRequest(String ag, Structure act, int rs, Object data) {
+ agName = ag;
+ action = act;
+ infraData = data;
+ remainSteps = rs;
+ }
+ public boolean equals(Object obj) {
+ return agName.equals(obj);
+ }
+ public int hashCode() {
+ return agName.hashCode();
+ }
+ public String toString() {
+ return "["+agName+","+action+"]";
+ }
+ }
+
+ class TimeOutThread extends Thread {
+ Lock lock = new ReentrantLock();
+ Condition agActCond = lock.newCondition();
+ long timeout = 0;
+
+ public TimeOutThread(long to) {
+ super("EnvironmentTimeOutThread");
+ timeout = to;
+ }
+
+ public void allAgFinished() {
+ lock.lock();
+ agActCond.signal();
+ lock.unlock();
+ }
+
+ public void run() {
+ try {
+ while (true) {
+ lock.lock();
+ long lastStepStart = System.currentTimeMillis();
+ boolean byTimeOut = !agActCond.await(timeout, TimeUnit.MILLISECONDS);
+ long now = System.currentTimeMillis();
+ long time = (now-lastStepStart);
+ stepFinished(step, time, byTimeOut);
+ lock.unlock();
+
+ if (byTimeOut) {
+ startNewStep();
+ }
+ }
+ } catch (InterruptedException e) {
+ } catch (Exception e) {
+ logger.log(Level.SEVERE, "Error in timeout thread!",e);
+ }
+ }
+ }
+}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2009-03-20 13:13:47
|
Revision: 1475
http://jason.svn.sourceforge.net/jason/?rev=1475&view=rev
Author: jomifred
Date: 2009-03-20 13:13:34 +0000 (Fri, 20 Mar 2009)
Log Message:
-----------
fix bug related to suspended atomic intention (bug 2695731)
Modified Paths:
--------------
trunk/applications/jason-moise/src/jmoise/MoiseBaseIA.java
trunk/applications/jason-moise/src/jmoise/OrgAgent.java
trunk/doc/faq/faq.tex
trunk/src/jason/asSemantics/Circumstance.java
trunk/src/jason/asSemantics/ConcurrentInternalAction.java
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/stdlib/send.java
trunk/src/jason/stdlib/suspend.java
trunk/src/jason/stdlib/wait.java
Removed Paths:
-------------
trunk/src/jason/stdlib/dropGoal.java
Modified: trunk/applications/jason-moise/src/jmoise/MoiseBaseIA.java
===================================================================
--- trunk/applications/jason-moise/src/jmoise/MoiseBaseIA.java 2009-03-19 18:36:05 UTC (rev 1474)
+++ trunk/applications/jason-moise/src/jmoise/MoiseBaseIA.java 2009-03-20 13:13:34 UTC (rev 1475)
@@ -40,7 +40,7 @@
if (suspendIntention()) {
Intention i = ts.getC().getSelectedIntention();
i.setSuspended(true);
- ts.getC().getPendingIntentions().put("om/"+m.getMsgId(), i);
+ ts.getC().addPendingIntention("om/"+m.getMsgId(), i);
}
return true;
}
Modified: trunk/applications/jason-moise/src/jmoise/OrgAgent.java
===================================================================
--- trunk/applications/jason-moise/src/jmoise/OrgAgent.java 2009-03-19 18:36:05 UTC (rev 1474)
+++ trunk/applications/jason-moise/src/jmoise/OrgAgent.java 2009-03-20 13:13:34 UTC (rev 1475)
@@ -143,7 +143,7 @@
// test if it is the result of some org action
if (m.getInReplyTo() != null) {
// find the intention
- Intention pi = C.getPendingIntentions().remove("om/"+m.getInReplyTo());
+ Intention pi = C.removePendingIntention("om/"+m.getInReplyTo());
if (pi != null) {
resumeIntention(pi, content, C);
}
Modified: trunk/doc/faq/faq.tex
===================================================================
--- trunk/doc/faq/faq.tex 2009-03-19 18:36:05 UTC (rev 1474)
+++ trunk/doc/faq/faq.tex 2009-03-20 13:13:34 UTC (rev 1475)
@@ -238,10 +238,10 @@
is executed, it will create a new agent called "bob" based on the
AgentSpeak code available at file "myAgent.asl".
-Analogously, the internal action \code{.killAgent(<agent name>)}
+Analogously, the internal action \code{.kill_agent(<agent name>)}
removes the agent identified by \code{<agent name>} from the current
-MAS. The createAgDemo project that comes with the Jason distribution
-files has examples of using these features.
+MAS. The \texttt{demos/create-agent} project that comes with the Jason
+distribution files has examples of using these features.
New agents can also be created in the user Java code, for example:
@@ -261,11 +261,13 @@
}
}
\end{verbatim}
-The RuntimeServices interface, used in the code above, provides useful
-services transparently from the underlying infrastructure
-(Centralised, Saci, ...). The interface's methods include agent
-creation, agent killing, and halting the system (see the API
-documentation for more information).
+The
+\htlink{RuntimeServices}{http://jason.sourceforge.net/api/jason/runtime/RuntimeServicesInfraTier.html}
+interface, used in the code above, provides useful services
+transparently from the underlying infrastructure (Centralised, Saci,
+...). The interface's methods include agent creation, agent killing,
+and halting the system (see the API documentation for more
+information).
Note that if you're using the \saci infrastructure, new
agents (possibly not \jason agents, see \ref{sec:whysaci}) can
Modified: trunk/src/jason/asSemantics/Circumstance.java
===================================================================
--- trunk/src/jason/asSemantics/Circumstance.java 2009-03-19 18:36:05 UTC (rev 1474)
+++ trunk/src/jason/asSemantics/Circumstance.java 2009-03-20 13:13:34 UTC (rev 1475)
@@ -23,6 +23,7 @@
package jason.asSemantics;
+import jason.JasonException;
import jason.asSyntax.Literal;
import jason.asSyntax.Trigger;
import jason.asSyntax.Trigger.TEOperator;
@@ -57,6 +58,7 @@
protected Option SO;
protected Intention SI;
private Intention AI; // Atomic Intention
+ private boolean atomicIntSuspended = false; // whether the current atomic intention is suspended in PA or PI
private Map<Integer, ActionExec> PA; // Pending actions, waiting action execution (key is the intention id)
private List<ActionExec> FA; // Feedback actions, those that are already executed
@@ -175,14 +177,12 @@
public void addIntention(Intention intention) {
I.offer(intention);
- if (intention.isAtomic()) {
+ if (intention.isAtomic())
setAtomicIntention(intention);
- }
// notify listeners
- for (CircumstanceListener el : listeners) {
+ for (CircumstanceListener el : listeners)
el.intentionAdded(intention);
- }
}
public boolean removeIntention(Intention i) {
@@ -217,6 +217,10 @@
public Intention removeAtomicIntention() {
if (AI != null) {
+ if (atomicIntSuspended) {
+ //throw new JasonException("Internal error: trying to remove the atomic intention, but it is suspended! it should be removed only when back to I!");
+ return null;
+ }
Intention tmp = AI;
removeIntention(AI);
return tmp;
@@ -228,6 +232,12 @@
return AI != null;
}
+ public boolean isAtomicIntentionSuspended() {
+ return AI != null && atomicIntSuspended;
+ }
+
+ /** pending intentions */
+
public Map<String, Intention> getPendingIntentions() {
return PI;
}
@@ -240,11 +250,29 @@
PI.clear();
}
+ public void addPendingIntention(String id, Intention i) {
+ if (i.isAtomic()) {
+ setAtomicIntention(i);
+ atomicIntSuspended = true;
+ }
+ PI.put(id, i);
+ }
+
+ public Intention removePendingIntention(String id) {
+ Intention i = PI.remove(id);
+ if (i != null && i.isAtomic()) {
+ atomicIntSuspended = false;
+ }
+ return i;
+ }
+
+ /** removes the intention i from PI and notify listeners that the intention was dropped */
public boolean dropPendingIntention(Intention i) {
- Iterator<Intention> it = PI.values().iterator();
- while (it.hasNext()) {
- if (it.next().equals(i)) {
- it.remove();
+ // use a loop instead of get because the intention (the value) is used in the search instead of the key
+ for (String key: PI.keySet()) {
+ Intention pii = PI.get(key);
+ if (pii.equals(i)) {
+ removePendingIntention(key);
// check in wait internal action
for (CircumstanceListener el : listeners) {
@@ -268,6 +296,8 @@
return AP;
}
+ /** feedback action */
+
public boolean hasFeedbackAction() {
return !FA.isEmpty();
}
@@ -281,13 +311,36 @@
synchronized (FA) {
FA.add(act);
}
+ if (act.getIntention().isAtomic()) {
+ atomicIntSuspended = false;
+ }
}
}
+
+ /** pending action */
+
public Map<Integer, ActionExec> getPendingActions() {
return PA;
}
+ public void addPendingAction(ActionExec a) {
+ Intention i = a.getIntention();
+ if (i.isAtomic()) {
+ setAtomicIntention(i);
+ atomicIntSuspended = true;
+ }
+ PA.put(i.getId(), a);
+ }
+
+ public ActionExec removePendingAction(int intentionId) {
+ ActionExec a = PA.remove(intentionId);
+ if (a != null && a.getIntention().isAtomic()) {
+ atomicIntSuspended = false;
+ }
+ return a;
+ }
+
public void clearPendingActions() {
PA.clear();
}
@@ -296,11 +349,21 @@
return PA != null && PA.size() > 0;
}
+ /** removes the intention i from PA and notify listeners that the intention was dropped */
public boolean dropPendingAction(Intention i) {
+ ActionExec act = removePendingAction(i.getId());
+ if (act != null) {
+ // check in wait internal action
+ for (CircumstanceListener el : listeners) {
+ el.intentionDropped(i);
+ }
+ return true;
+ }
+ /*
Iterator<ActionExec> it = PA.values().iterator();
while (it.hasNext()) {
if (it.next().getIntention().equals(i)) {
- it.remove();
+ removePendingAction(i.getId());
// check in wait internal action
for (CircumstanceListener el : listeners) {
@@ -309,6 +372,7 @@
return true;
}
}
+ */
return false;
}
Modified: trunk/src/jason/asSemantics/ConcurrentInternalAction.java
===================================================================
--- trunk/src/jason/asSemantics/ConcurrentInternalAction.java 2009-03-19 18:36:05 UTC (rev 1474)
+++ trunk/src/jason/asSemantics/ConcurrentInternalAction.java 2009-03-20 13:13:34 UTC (rev 1475)
@@ -79,7 +79,7 @@
final Circumstance C = ts.getC();
Intention i = C.getSelectedIntention();
i.setSuspended(true);
- C.getPendingIntentions().put(key, i);
+ C.addPendingIntention(key, i);
if (timeout > 0) {
// schedule a future test of the end of the action
@@ -118,7 +118,7 @@
ts.runAtBeginOfNextCycle(new Runnable() {
public void run() {
Circumstance C = ts.getC();
- Intention pi = C.getPendingIntentions().remove(intentionKey);
+ Intention pi = C.removePendingIntention(intentionKey);
if (pi != null) {
pi.setSuspended(false);
try {
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2009-03-19 18:36:05 UTC (rev 1474)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2009-03-20 13:13:34 UTC (rev 1475)
@@ -172,7 +172,7 @@
// check if an intention was suspended waiting this message
Intention intention = null;
if (m.getInReplyTo() != null) {
- intention = getC().getPendingIntentions().remove(m.getInReplyTo());
+ intention = getC().removePendingIntention(m.getInReplyTo());
}
// is it a pending intention?
if (intention != null) {
@@ -218,7 +218,7 @@
// Rule for atomic, if there is an atomic intention, do not select event
if (C.hasAtomicIntention()) {
- confP.step = State.SelInt;
+ confP.step = State.ProcAct; // need to go to ProcAct to see if an atomic intention received a feedback action
return;
}
@@ -375,7 +375,7 @@
// remove the intention from PA (PA has all pending action, including those in FA;
// but, if the intention is not in PA, it means that the intention was dropped
// and should not return to I)
- if (C.getPendingActions().remove(a.getIntention().getId()) != null) {
+ if (C.removePendingAction(confP.C.SI.getId()) != null) {
if (a.getResult()) {
// add the intention back in I
updateIntention();
@@ -398,11 +398,12 @@
if (confP.C.SI != null) {
return;
}
-
+
// Rule SelInt1
- if (conf.C.hasIntention()) {
+ if (!conf.C.isAtomicIntentionSuspended() && conf.C.hasIntention()) { // the isAtomicIntentionSuspended is necessary because the atomic intention may be suspended (the above removeAtomicInt returns null in that case)
+ // but no other intention could be selected
confP.C.SI = conf.ag.selectIntention(conf.C.getIntentions());
- if (confP.C.SI != null) { // the selectIntention function retuned null
+ if (confP.C.SI != null) { // the selectIntention function returned null
return;
}
}
@@ -924,11 +925,12 @@
}
public boolean canSleep() {
- return !conf.C.hasEvent() && !conf.C.hasIntention() &&
- !conf.C.hasFeedbackAction() &&
- conf.C.MB.isEmpty() &&
- taskForBeginOfCycle.isEmpty() &&
- agArch.canSleep();
+ return (C.isAtomicIntentionSuspended() && conf.C.MB.isEmpty())
+ || (!conf.C.hasEvent() && !conf.C.hasIntention() &&
+ !conf.C.hasFeedbackAction() &&
+ conf.C.MB.isEmpty() &&
+ //taskForBeginOfCycle.isEmpty() &&
+ agArch.canSleep());
}
/**
@@ -982,7 +984,7 @@
ActionExec action = C.getAction();
if (action != null) {
- C.getPendingActions().put(action.getIntention().getId(), action);
+ C.addPendingAction(action);
agArch.act(action, C.getFeedbackActions());
}
Deleted: trunk/src/jason/stdlib/dropGoal.java
===================================================================
--- trunk/src/jason/stdlib/dropGoal.java 2009-03-19 18:36:05 UTC (rev 1474)
+++ trunk/src/jason/stdlib/dropGoal.java 2009-03-20 13:13:34 UTC (rev 1475)
@@ -1,131 +0,0 @@
-//----------------------------------------------------------------------------
-// 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.ActionExec;
-import jason.asSemantics.Circumstance;
-import jason.asSemantics.DefaultInternalAction;
-import jason.asSemantics.Event;
-import jason.asSemantics.Intention;
-import jason.asSemantics.TransitionSystem;
-import jason.asSemantics.Unifier;
-import jason.asSyntax.Literal;
-import jason.asSyntax.Term;
-import jason.asSyntax.Trigger;
-import jason.asSyntax.Trigger.TEOperator;
-import jason.asSyntax.Trigger.TEType;
-
-/**
-
-@deprecated use fail_goal or succeed_goal accordingly.
- */
-public class dropGoal extends DefaultInternalAction {
-
- @Override
- public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
- try {
- ts.getLogger().info("Deprecated: use fail_goal or succeed_goal instead of .dropGoal.");
-
- drop(ts, (Literal)args[0], args[1].equals(Literal.LTrue), un);
- return true;
- } catch (ArrayIndexOutOfBoundsException e) {
- throw new JasonException("The internal action 'dropGoal' has not received two arguments.");
- } catch (Exception e) {
- e.printStackTrace();
- throw new JasonException("Error in internal action 'dropGoal': " + e);
- }
- }
-
- public void drop(TransitionSystem ts, Literal l, boolean success, Unifier un) throws JasonException{
- Trigger g = new Trigger(TEOperator.add, TEType.achieve, l);
- Circumstance C = ts.getC();
-
- for (Intention i: C.getIntentions()) {
- if (dropIntention(i, g, success, ts, un) > 1) {
- C.removeIntention(i);
- }
- }
-
- // dropping the current intention?
- dropIntention(C.getSelectedIntention(), g, success, ts, un);
-
- // dropping G in Events
- for (Event e: C.getEvents()) {
- Intention i = e.getIntention();
- if (dropIntention(i, g, success, ts, un) > 1) {
- C.removeEvent(e);
- }
- }
-
- // dropping from Pending Actions
- for (ActionExec a: C.getPendingActions().values()) {
- Intention i = a.getIntention();
- int r = dropIntention(i, g, success, ts, un);
- if (r > 0) { // i was changed
- C.dropPendingIntention(i); // remove i from PI
- if (r == 1) { // i must continue running
- C.addIntention(i); // and put the intention back in I
- }
- }
- }
-
- // dropping from Pending Intentions
- for (Intention i: C.getPendingIntentions().values()) {
- int r = dropIntention(i, g, success, ts, un);
- if (r > 0) { // i was changed
- C.dropPendingIntention(i); // remove i from PI
- if (r == 1) { // intention i must continue running
- C.addIntention(i); // and put the intention back in I
- }
- }
- }
- }
-
- private int dropIntention(Intention i, Trigger g, boolean success, TransitionSystem ts, Unifier un) throws JasonException {
- if (i != null && i.dropGoal(g, un)) {
- if (success) {
- // continue the intention
- i.peek().removeCurrentStep();
- ts.applyClrInt(i);
- return 1;
- } else {
- // generate failure event
- Event failEvent = null;
- if (!i.isFinished()) {
- failEvent = ts.findEventForFailure(i, i.peek().getTrigger());
- }
- if (failEvent != null) {
- ts.getC().addEvent(failEvent);
- ts.getLogger().warning("'.dropGoal' is generating a goal deletion event: " + failEvent.getTrigger());
- return 2;
- } else {
- ts.getLogger().warning("'.dropGoal' is removing an intention:\n" + i);
- return 3;
- }
- }
- }
- return 0;
- }
-}
Modified: trunk/src/jason/stdlib/send.java
===================================================================
--- trunk/src/jason/stdlib/send.java 2009-03-19 18:36:05 UTC (rev 1474)
+++ trunk/src/jason/stdlib/send.java 2009-03-20 13:13:34 UTC (rev 1475)
@@ -155,7 +155,7 @@
// async ask has a fourth argument and should suspend the intention
lastSendWasSynAsk = m.isAsk() && args.length > 3;
if (lastSendWasSynAsk) {
- ts.getC().getPendingIntentions().put(m.getMsgId(), ts.getC().getSelectedIntention());
+ ts.getC().addPendingIntention(m.getMsgId(), ts.getC().getSelectedIntention());
}
// (un)tell or unknown performative with 4 args is a reply to
@@ -201,7 +201,7 @@
ts.getAg().getScheduler().schedule( new Runnable() {
public void run() {
// if the intention is still in PI, brings it back to C.I
- Intention intention = ts.getC().getPendingIntentions().remove(m.getMsgId());
+ Intention intention = ts.getC().removePendingIntention(m.getMsgId());
if (intention != null) {
// unify "timeout" with the fourth parameter of .send
Structure send = (Structure)intention.peek().removeCurrentStep();
Modified: trunk/src/jason/stdlib/suspend.java
===================================================================
--- trunk/src/jason/stdlib/suspend.java 2009-03-19 18:36:05 UTC (rev 1474)
+++ trunk/src/jason/stdlib/suspend.java 2009-03-20 13:13:34 UTC (rev 1475)
@@ -95,7 +95,7 @@
Intention i = C.getSelectedIntention();
suspendIntention = true;
i.setSuspended(true);
- C.getPendingIntentions().put(SELF_SUSPENDED_INT, i);
+ C.addPendingIntention(SELF_SUSPENDED_INT, i);
return true;
}
Modified: trunk/src/jason/stdlib/wait.java
===================================================================
--- trunk/src/jason/stdlib/wait.java 2009-03-19 18:36:05 UTC (rev 1474)
+++ trunk/src/jason/stdlib/wait.java 2009-03-20 13:13:34 UTC (rev 1475)
@@ -143,7 +143,7 @@
sTE = "time"+(timeout);
}
sTE = si.getId()+"/"+sTE;
- c.getPendingIntentions().put(sTE, si);
+ c.addPendingIntention(sTE, si);
startTime = System.currentTimeMillis();
@@ -165,13 +165,13 @@
public void run() {
try {
// add SI again in C.I if it was not removed and this wait was not dropped
- if (c.getPendingIntentions().remove(sTE) == si && !c.getIntentions().contains(si) && !dropped) {
+ if (c.removePendingIntention(sTE) == si && !c.getIntentions().contains(si) && !dropped) {
if (stopByTimeout && te != null && elapsedTimeTerm == null) {
// fail the .wait by timeout
if (si.isSuspended()) { // if the intention was suspended by .suspend
PlanBody body = si.peek().getPlan().getBody();
body.add(1, new PlanBodyImpl(BodyType.internalAction, new InternalActionLiteral(".fail")));
- c.getPendingIntentions().put(suspend.SUSPENDED_INT+si.getId(), si);
+ c.addPendingIntention(suspend.SUSPENDED_INT+si.getId(), si);
} else {
ts.generateGoalDeletion(si, JasonException.createBasicErrorAnnots("wait_timeout", "timeout in .wait"));
}
@@ -183,7 +183,7 @@
un.unifies(elapsedTimeTerm, new NumberTermImpl(elapsedTime));
}
if (si.isSuspended()) { // if the intention was suspended by .suspend
- c.getPendingIntentions().put(suspend.SUSPENDED_INT+si.getId(), si);
+ c.addPendingIntention(suspend.SUSPENDED_INT+si.getId(), si);
} else {
c.addIntention(si);
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <bo...@us...> - 2009-03-22 01:57:07
|
Revision: 1476
http://jason.svn.sourceforge.net/jason/?rev=1476&view=rev
Author: bordini
Date: 2009-03-22 01:54:39 +0000 (Sun, 22 Mar 2009)
Log Message:
-----------
Added example blocks-world; IMPORTANT: cannot be released before bug with Patterns is fixed.
Created 3 new internal actions: .suffix, .prefix, and .sublist (still to consider if the results should be changed to match the logic programming implementation)
Changed StdLibTest.java to add unit tests for all 3 actions.
Release Notes also updated (example and internal actions).
Modified Paths:
--------------
trunk/release-notes.txt
trunk/src/test/StdLibTest.java
Added Paths:
-----------
trunk/examples/blocks-world/
trunk/examples/blocks-world/BlocksEnv/
trunk/examples/blocks-world/BlocksEnv/BlocksWorld.java
trunk/examples/blocks-world/BlocksEnv/WorldModel.java
trunk/examples/blocks-world/BlocksEnv/WorldView.java
trunk/examples/blocks-world/BlocksWorld.mas2j
trunk/examples/blocks-world/agent.asl
trunk/examples/blocks-world/agent_c.asl
trunk/examples/blocks-world/agent_g.asl
trunk/examples/blocks-world/agent_o.asl
trunk/examples/blocks-world/agent_p.asl
trunk/src/jason/stdlib/prefix.java
trunk/src/jason/stdlib/sublist.java
trunk/src/jason/stdlib/suffix.java
Added: trunk/examples/blocks-world/BlocksEnv/BlocksWorld.java
===================================================================
--- trunk/examples/blocks-world/BlocksEnv/BlocksWorld.java (rev 0)
+++ trunk/examples/blocks-world/BlocksEnv/BlocksWorld.java 2009-03-22 01:54:39 UTC (rev 1476)
@@ -0,0 +1,88 @@
+package BlocksEnv;
+
+import jason.asSyntax.Literal;
+import jason.asSyntax.Structure;
+
+import java.util.LinkedList;
+import java.util.Stack;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class BlocksWorld extends jason.environment.Environment {
+
+ private Logger logger = Logger.getLogger("BlocksWorld.mas2j" + BlocksWorld.class.getName());
+
+ WorldModel model;
+ WorldView view;
+
+ int sleep = 0;
+ boolean hasGUI = true;
+
+ @Override
+ public void init(String[] args) {
+ hasGUI = args[2].equals("yes");
+ sleep = Integer.parseInt(args[1]);
+ initWorld(Integer.parseInt(args[0]));
+ updateAllPercepts();
+ }
+
+ @Override
+ synchronized public boolean executeAction(String ag, Structure action) {
+ boolean result = false;
+ try {
+ if (sleep > 0) {
+ Thread.sleep(sleep);
+ }
+
+ //logger.info("Agent "+ag+" is doing: "+action);
+
+ if (action.getFunctor().equals("move")) {
+ // Location loc = new Location( (int)((NumberTerm)action.getTerm(0)).solve(),(int)((NumberTerm)action.getTerm(1)).solve());
+ LinkedList<String> adds=new LinkedList<String>(), dels=new LinkedList<String>();
+ result = model.move(action.getTerm(0).toString(),action.getTerm(1).toString(), adds, dels);
+ if (result) {
+ for(String d: dels)
+ removePercept("agent",Literal.parseLiteral(d));
+ for(String a: adds)
+ addPercept("agent",Literal.parseLiteral(a));
+ }
+ } else {
+ logger.info("executing: " + action + ", but it has not been implemented!");
+ }
+ return true;
+ } catch (InterruptedException e) {
+ } catch (Exception e) {
+ logger.log(Level.SEVERE, "error executing " + action + " for " + ag, e);
+ }
+ return false;
+ }
+
+ private void updateAllPercepts() {
+ clearPercepts("agent");
+ for (Stack<String> s : model.getStacks()) {
+ for (int i=1; i<s.size(); i++) {
+ addPercept("agent", Literal.parseLiteral("on("+s.get(i)+","+s.get(i-1)+")"));
+ }
+ }
+ }
+
+ public void initWorld(int w) {
+ try {
+ switch (w) {
+ case 1: model = WorldModel.world1(); break;
+ case 2: model = WorldModel.world2(); break;
+ case 3: model = WorldModel.world2(); break;
+ default:
+ logger.info("Invalid index!");
+ return;
+ }
+
+ if (hasGUI) {
+ view = new WorldView(model);
+ }
+ informAgsEnvironmentChanged();
+ } catch (Exception e) {
+ logger.warning("Error creating world "+e);
+ }
+ }
+}
Property changes on: trunk/examples/blocks-world/BlocksEnv/BlocksWorld.java
___________________________________________________________________
Added: svn:eol-style
+ native
Added: trunk/examples/blocks-world/BlocksEnv/WorldModel.java
===================================================================
--- trunk/examples/blocks-world/BlocksEnv/WorldModel.java (rev 0)
+++ trunk/examples/blocks-world/BlocksEnv/WorldModel.java 2009-03-22 01:54:39 UTC (rev 1476)
@@ -0,0 +1,154 @@
+package BlocksEnv;
+
+import jason.environment.grid.GridWorldModel;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Stack;
+import java.util.logging.Logger;
+
+public class WorldModel extends GridWorldModel {
+
+ public static final int BLOCK = 32;
+ public static final int TABLE = 64;
+ private Logger logger = Logger.getLogger("BlocksWorld.mas2j." + WorldModel.class.getName());
+
+
+ private String id = "WorldModel";
+ private List<Stack<String>> stackList = new LinkedList<Stack<String>>();
+ private String[][] names;
+
+ public static int GHeight = 0;
+ public static int GWidth = 0;
+
+ // singleton pattern
+ protected static WorldModel model = null;
+
+ private WorldModel(int w, int h, int nbAgs) {
+ super(w, h, nbAgs);
+ }
+
+ synchronized public static WorldModel create(int w, int h, int nbAgs) {
+ if (model == null) {
+ model = new WorldModel(w, h, nbAgs);
+ }
+ return model;
+ }
+
+ public static WorldModel get() {
+ return model;
+ }
+
+ public static void destroy() {
+ model = null;
+ }
+
+ public String getId() {
+ return id;
+ }
+ public void setId(String id) {
+ this.id = id;
+ }
+ public String toString() {
+ return id;
+ }
+
+ public String getName(int x, int y) {
+ return names[x][y];
+ }
+
+ public List<Stack<String>> getStacks() {
+ return stackList;
+ }
+
+ /** Actions **/
+
+ boolean move(String a, String b, List<String> adds, List<String> dels) throws Exception {
+ logger.info("Moving: "+a+" on top of "+b);
+ Stack<String> aS = null;
+ Stack<String> bS = null;
+ for (Stack<String> s : stackList) {
+ if (s.peek().equals(a))
+ aS = s;
+ if (s.peek().equals(b))
+ bS = s;
+ }
+ if (b.equals("table")) {
+ bS = new Stack<String>();
+ bS.add("table");
+ stackList.add(0,bS);
+ }
+ if (aS==null || bS==null) {
+ logger.info("Didn't find one of the blocks on top of a stack");
+ return false;
+ }
+ adds.add("on("+aS.peek()+","+bS.peek()+")");
+ bS.push(aS.pop());
+ dels.add("on("+bS.peek()+","+aS.peek()+")");
+ if (aS.peek().equals("table")) {
+ stackList.remove(aS);
+ }
+ modelToGrid();
+ view.update();
+
+ return true;
+ }
+
+
+ /** world with gold and obstacles */
+ static WorldModel world1() throws Exception {
+ GWidth =20;
+ GHeight=10;
+ WorldModel model = WorldModel.create(GWidth, GHeight, 0);
+ model.names = new String[GWidth][GHeight];
+
+ Stack<String> s1 = new Stack<String>();
+ s1.push("table"); s1.push("c"); s1.push("b"); s1.push("a");
+ model.stackList.add(s1);
+ Stack<String> s2 = new Stack<String>();
+ s2.push("table"); s2.push("e"); s2.push("d");
+ model.stackList.add(s2);
+ Stack<String> s3 = new Stack<String>();
+ s3.push("table"); s3.push("g"); s3.push("f");
+ model.stackList.add(s3);
+ model.modelToGrid();
+ return model;
+ }
+
+ static WorldModel world2() throws Exception {
+ GWidth =20;
+ GHeight=10;
+ WorldModel model = WorldModel.create(GWidth, GHeight, 0);
+ model.names = new String[GWidth][GHeight];
+ model.modelToGrid();
+ return model;
+ }
+
+ static WorldModel world3() throws Exception {
+ GWidth=50;
+ GHeight=10;
+ WorldModel model = WorldModel.create(GWidth, GHeight, 0);
+ model.names = new String[GWidth][GHeight];
+ model.modelToGrid();
+ return model;
+ }
+
+ void modelToGrid() {
+ for (int i=0; i<GWidth; i++) {
+ for (int j=0; j<GHeight-1; j++) {
+ model.data[i][j] = 0;
+ model.names[i][j] = "";
+ }
+ model.data[i][GHeight-1] = TABLE;
+ model.names[i][GHeight-1] = "table";
+ }
+ int i=0;
+ for (Stack<String> s : stackList) {
+ for (int j=1; j<s.size(); j++) {
+ model.data[i*2+1][GHeight-j-1] = BLOCK;
+ model.names[i*2+1][GHeight-j-1] = s.get(j);
+ }
+ i++;
+ }
+ }
+}
Property changes on: trunk/examples/blocks-world/BlocksEnv/WorldModel.java
___________________________________________________________________
Added: svn:eol-style
+ native
Added: trunk/examples/blocks-world/BlocksEnv/WorldView.java
===================================================================
--- trunk/examples/blocks-world/BlocksEnv/WorldView.java (rev 0)
+++ trunk/examples/blocks-world/BlocksEnv/WorldView.java 2009-03-22 01:54:39 UTC (rev 1476)
@@ -0,0 +1,51 @@
+package BlocksEnv;
+
+import jason.environment.grid.GridWorldView;
+
+import java.awt.Color;
+import java.awt.Graphics;
+
+
+public class WorldView extends GridWorldView {
+
+ public WorldView(WorldModel model) {
+ super(model, "Blocks World", 600);
+ setVisible(true);
+ repaint();
+ }
+
+ @Override
+ public void draw(Graphics g, int x, int y, int object) {
+ switch (object) {
+ case WorldModel.BLOCK: drawBlock(g, x, y); break;
+ case WorldModel.TABLE: drawTable(g, x, y); break;
+ }
+ }
+
+ public void drawBlock(Graphics g, int x, int y) {
+ g.setColor(Color.red);
+ g.fillRect(x * cellSizeW, y * cellSizeH, cellSizeW, cellSizeH);
+ g.setColor(Color.black);
+ g.drawRect(x * cellSizeW + 2, y * cellSizeH + 2, cellSizeW - 4, cellSizeH - 4);
+ drawString(g, x, y, defaultFont, ((WorldModel)getModel()).getName(x,y));
+ }
+
+ public void drawTable(Graphics g, int x, int y) {
+ g.setColor(Color.green);
+ g.fillRect(x * cellSizeW, y * cellSizeH, cellSizeW, cellSizeH);
+ }
+
+ @Override
+ public void drawAgent(Graphics g, int x, int y, Color c, int id) {
+ Color idColor = Color.black;
+ super.drawAgent(g, x, y, c, -1);
+ idColor = Color.white;
+ g.setColor(idColor);
+ drawString(g, x, y, defaultFont, String.valueOf(id+1));
+ }
+
+// public static void main(String[] args) throws Exception {
+// BlocksWorld env = new BlocksWorld();
+// env.init(new String[] {"1","0","yes"});
+// }
+}
Property changes on: trunk/examples/blocks-world/BlocksEnv/WorldView.java
___________________________________________________________________
Added: svn:eol-style
+ native
Added: trunk/examples/blocks-world/BlocksWorld.mas2j
===================================================================
--- trunk/examples/blocks-world/BlocksWorld.mas2j (rev 0)
+++ trunk/examples/blocks-world/BlocksWorld.mas2j 2009-03-22 01:54:39 UTC (rev 1476)
@@ -0,0 +1,15 @@
+/* Jason Blocks World Project */
+MAS blocksWorld {
+
+ infrastructure: Centralised
+
+ environment: BlocksEnv.BlocksWorld(1,0,yes) // change 0 to 500 or more to slowdown
+ // yes to use GUI
+
+// Choose one of the various solutions:
+ agents: agent;
+// agents: agent agent_o;
+// agents: agent agent_c;
+// agents: agent agent_p;
+// agents: agent agent_g;
+}
Property changes on: trunk/examples/blocks-world/BlocksWorld.mas2j
___________________________________________________________________
Added: svn:eol-style
+ native
Added: trunk/examples/blocks-world/agent.asl
===================================================================
--- trunk/examples/blocks-world/agent.asl (rev 0)
+++ trunk/examples/blocks-world/agent.asl 2009-03-22 01:54:39 UTC (rev 1476)
@@ -0,0 +1,34 @@
+// An agent for the Block World
+
+/* Initial beliefs and rules */
+clear(table).
+clear(X) :- not(on(Y,X)).
+tower([X]) :- on(X,table).
+tower([X,Y|T]) :- on(X,Y) & tower([Y|T]).
+
+/* Initial goals */
+// The final state to be achieved
+!state([[a,e,b],[f,d,c],[g]]).
+
+/* Plans */
+// Achieve one tower at a time
++!state([]).
++!state([H|T]) <- !tower(H); !state(T).
+
+// Achieve a state where a tower is built
++!tower(T) : tower(T). // already achieved, nothing else to do
++!tower([T]) <- !on(T,table). // easy to do a singleton tower
++!tower([X,Y|T]) <- !tower([Y|T]); !on(X,Y). // break my problem into smaller ones
+
+// Achieve a state of affairs where I believe a block is on top of another
++!on(X,Y) : on(X,Y). // already achieved
++!on(X,Y) <- !clear(X); !clear(Y); move(X,Y). // make sure blocks are clear, then move
+
+// Achieve a state of affairs where block X is clear (i.e.e, at the top of a tower)
++!clear(X) : clear(X). // already achieved
+// remove top block when the block I need to clear is underneath it
++!clear(X)
+ : tower([H|T]) & .member(X,T)
+ <- move(H,table);
+ !clear(X). // carry on trying, until achieved
+
Property changes on: trunk/examples/blocks-world/agent.asl
___________________________________________________________________
Added: svn:eol-style
+ native
Added: trunk/examples/blocks-world/agent_c.asl
===================================================================
--- trunk/examples/blocks-world/agent_c.asl (rev 0)
+++ trunk/examples/blocks-world/agent_c.asl 2009-03-22 01:54:39 UTC (rev 1476)
@@ -0,0 +1,30 @@
+// An agent for the Block World
+// Tries each stack of the goal world concurrently
+
+/* Initial beliefs and rules */
+clear(table).
+clear(X) :- not(on(Y,X)).
+tower([X]) :- on(X,table).
+tower([X,Y|T]) :- on(X,Y) & tower([Y|T]).
+
+/* Initial goals */
+// Try each stack concurrently
+!tower([g]).
+!tower([f,d,c]).
+!tower([a,e,b]).
+
+/* Plans */
+
++!tower(T) : tower(T).
++!tower([T]) <- !on(T,table).
++!tower([X,Y|T]) <- !tower([Y|T]); !on(X,Y).
+
++!on(X,Y) : on(X,Y).
+@po[atomic]
++!on(X,Y) <- !clear(X); !clear(Y); move(X,Y).
+
++!clear(X) : clear(X).
++!clear(X) : tower([H|T]) & .member(X,T)
+ <- move(H,table);
+ !clear(X).
+
Property changes on: trunk/examples/blocks-world/agent_c.asl
___________________________________________________________________
Added: svn:eol-style
+ native
Added: trunk/examples/blocks-world/agent_g.asl
===================================================================
--- trunk/examples/blocks-world/agent_g.asl (rev 0)
+++ trunk/examples/blocks-world/agent_g.asl 2009-03-22 01:54:39 UTC (rev 1476)
@@ -0,0 +1,25 @@
+// An agent for the Block World
+// This ones tries to be closer to the GOAL version
+
+/* Initial beliefs and rules */
+clear(table).
+clear(X) :- not(on(Y,X)).
+tower([X]) :- on(X,table).
+tower([X,Y|T]) :- on(X,Y) & tower([Y|T]).
+
+allowed(X,Y) :- clear(X) & clear(Y) & not on(X,Y).
+
+a_goal(S,G) :- .member(S1,S) & .suffix(G,S1).
+
+/* Initial goals */
+!state([[a,e,b],[f,d,c],[g]]).
+
+/* Plans */
++!state(S)
+ : a_goal(S,[X,Y|T]) & tower([Y|T]) & allowed(X,Y)
+ <- move(X,Y); !state(S).
++!state(S)
+ : a_goal(S,[X|T]) & not tower([X|T]) & allowed(X,table)
+ <- move(X,table); !state(S).
++!state(S).
+
Property changes on: trunk/examples/blocks-world/agent_g.asl
___________________________________________________________________
Added: svn:eol-style
+ native
Added: trunk/examples/blocks-world/agent_o.asl
===================================================================
--- trunk/examples/blocks-world/agent_o.asl (rev 0)
+++ trunk/examples/blocks-world/agent_o.asl 2009-03-22 01:54:39 UTC (rev 1476)
@@ -0,0 +1,39 @@
+// An agent for the Block World
+// It tries first to build the stacks that are closer to completion
+
+/* Initial beliefs and rules */
+clear(table).
+clear(X) :- not(on(Y,X)).
+tower([X]) :- on(X,table).
+tower([X,Y|T]) :- on(X,Y) & tower([Y|T]).
+
+highest_partial_tower(L,[]) :- calc(L,[]).
+highest_partial_tower(L,T) :- calc(L,L1) & .sort(L1,L2) & .reverse(L2,[s(_,T)|T3]).
+
+calc([],[]).
+calc([H|T],TR) :- ready(H,S) & S=.length(H) & calc(T,TR).
+calc([H|T],[s(S,H)|TR]) :- ready(H,S) & calc(T,TR).
+
+ready([],0).
+ready(L,S) :- tower(L) & S=.length(L).
+ready([H|T],S) :- ready(T,S).
+
+/* Initial goals */
+!state2([[a,e,b],[f,d,c],[g]]).
+
+/* Plans */
++!state2(S) : highest_partial_tower(S,[]).
++!state2(S) : highest_partial_tower(S,T) <- !tower(T); !state2(S).
+
++!tower(T) : tower(T).
++!tower([T]) <- !on(T,table).
++!tower([X,Y|T]) <- !tower([Y|T]); !on(X,Y).
+
++!on(X,Y) : on(X,Y).
++!on(X,Y) <- !clear(X); !clear(Y); move(X,Y).
+
++!clear(X) : clear(X).
++!clear(X) : tower([H|T]) & .member(X,T)
+ <- move(H,table);
+ !clear(X).
+
Property changes on: trunk/examples/blocks-world/agent_o.asl
___________________________________________________________________
Added: svn:eol-style
+ native
Added: trunk/examples/blocks-world/agent_p.asl
===================================================================
--- trunk/examples/blocks-world/agent_p.asl (rev 0)
+++ trunk/examples/blocks-world/agent_p.asl 2009-03-22 01:54:39 UTC (rev 1476)
@@ -0,0 +1,32 @@
+// An agent for the Block World
+
+/* Initial beliefs and rules */
+clear(table).
+clear(X) :- not(on(Y,X)).
+tower([X]) :- on(X,table).
+tower([X,Y|T]) :- on(X,Y) & tower([Y|T]).
+
+/* Initial goals */
+// The final state to be achieved
+!state([[a,e,b],[f,d,c],[g]]).
+
+/* Plans */
+// Achieve one tower at a time
++!state([]).
++!state([H|T]) <- !tower(H); !state(T).
+
+{begin dg(tower(T))} // plans for a declarative goal (dg)
++!tower([T]) <- !on(T,table).
++!tower([X,Y|T]) <- !tower([Y|T]); !on(X,Y).
+{end}
+
+{begin dg(on(X,Y))}
++!on(X,Y) <- !clear(X); !clear(Y); move(X,Y).
+{end}
+
+{begin bc(clear(X),dg(clear(X)))} // blindly committed (bc) to this goal
++!clear(X)
+ : tower([H|T]) & .member(X,T)
+ <- move(H,table).
+{end}
+
Property changes on: trunk/examples/blocks-world/agent_p.asl
___________________________________________________________________
Added: svn:eol-style
+ native
Modified: trunk/release-notes.txt
===================================================================
--- trunk/release-notes.txt 2009-03-20 13:13:34 UTC (rev 1475)
+++ trunk/release-notes.txt 2009-03-22 01:54:39 UTC (rev 1476)
@@ -54,13 +54,21 @@
similar method). Developed by Felipe Meneguzzi.
- .all_names: get the name of all agentes in the system.
- .list_plans: print out the plans of agent's plan library
+- .prefix, .suffix and .sublist: see comments in the API doc, as
+ their implementation is currently generates slightly different results
+ from their usual implementation in logic programming.
+
Changes in internal actions
- .relevant_plans has a third argument that gets the labels
of the plans
- .create_agent and .kill_agent accept strings for the agents' name
+New example
+- Blocks World
+
+
Bugs fixed
- arithmetic expressions are considered as Literal, causing
failures in unification
Added: trunk/src/jason/stdlib/prefix.java
===================================================================
--- trunk/src/jason/stdlib/prefix.java (rev 0)
+++ trunk/src/jason/stdlib/prefix.java 2009-03-22 01:54:39 UTC (rev 1476)
@@ -0,0 +1,116 @@
+package jason.stdlib;
+
+import jason.JasonException;
+import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
+import jason.asSemantics.TransitionSystem;
+import jason.asSemantics.Unifier;
+import jason.asSyntax.ListTerm;
+import jason.asSyntax.Term;
+
+import java.util.Iterator;
+import java.util.List;
+
+/**
+
+ <p>Internal action: <b><code>.prefix(<i>P</i>,<i>L</i>)</code></b>.
+
+ <p>Description: checks if some list <i>P</i> is a prefix of list <i>L</i>. If
+ <i>P</i> has free variables, this internal action backtracks all
+ possible values for <i>P</i>.
+
+ <p>Parameters:<ul>
+
+ <li>+/- prefix (list): the prefix to be checked.</li>
+ <li>+ list (list): the list where the prefix is from.</li>
+
+ </ul>
+
+ <p>Examples:<ul>
+
+ <li> <code>.prefix([a],[a,b,c])</code>: true.</li>
+ <li> <code>.prefix([b,c],[a,b,c])</code>: false.</li>
+ <li> <code>.prefix(X,[a,b,c])</code>: unifies X with any suffix of the list, i.e., [a,b,c], [a,b], and [a], in this order;
+ note that this is different from what its usual implementation in logic programming would result;
+ also, the empty list is not generated as a possibly prefix. </li>
+
+ </ul>
+
+ @see jason.stdlib.concat
+ @see jason.stdlib.length
+ @see jason.stdlib.sort
+ @see jason.stdlib.nth
+ @see jason.stdlib.max
+ @see jason.stdlib.min
+ @see jason.stdlib.reverse
+
+ @see jason.stdlib.difference
+ @see jason.stdlib.intersection
+ @see jason.stdlib.union
+
+*/
+public class prefix extends DefaultInternalAction {
+
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new prefix();
+ return singleton;
+ }
+
+ // Needs exactly 2 arguments
+ @Override public int getMinArgs() { return 2; }
+ @Override public int getMaxArgs() { return 2; }
+
+ // improve the check of the arguments to also check the type of the arguments
+ @Override protected void checkArguments(Term[] args) throws JasonException {
+ super.checkArguments(args); // check number of arguments
+ if (!args[0].isList() && !args[0].isVar())
+ throw JasonException.createWrongArgument(this,"first argument must be a list or a variable");
+ if (!args[1].isList())
+ throw JasonException.createWrongArgument(this,"second argument must be a list");
+ }
+
+ @Override
+ public Object execute(TransitionSystem ts, final Unifier un, Term[] args) throws Exception {
+
+ checkArguments(args);
+
+ // execute the internal action
+
+ final Term sublist = args[0];
+// final Iterator<Term> i = ((ListTerm)args[1]).iterator();
+ final ListTerm list = ((ListTerm)args[1]).cloneLT();
+
+ return new Iterator<Unifier>() {
+ Unifier c = null; // the current response (which is an unifier)
+
+ public boolean hasNext() {
+ if (c == null) // the first call of hasNext should find the first response
+ find();
+ return c != null;
+ }
+
+ public Unifier next() {
+ if (c == null) find();
+ Unifier b = c;
+ find(); // find next response
+ return b;
+ }
+
+ void find() {
+ while (!list.isEmpty()) {
+ c = un.clone();
+ if (c.unifiesNoUndo(sublist, list.clone())) {
+ ((List)list).remove(list.size()-1);
+ return; // found another sublist, c is the current response
+ }
+ ((List)list).remove(list.size()-1);
+ }
+ c = null; // no more sublists found
+ }
+
+ public void remove() {}
+ };
+ }
+}
Property changes on: trunk/src/jason/stdlib/prefix.java
___________________________________________________________________
Added: svn:eol-style
+ native
Added: trunk/src/jason/stdlib/sublist.java
===================================================================
--- trunk/src/jason/stdlib/sublist.java (rev 0)
+++ trunk/src/jason/stdlib/sublist.java 2009-03-22 01:54:39 UTC (rev 1476)
@@ -0,0 +1,126 @@
+package jason.stdlib;
+
+import jason.JasonException;
+import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
+import jason.asSemantics.TransitionSystem;
+import jason.asSemantics.Unifier;
+import jason.asSyntax.ListTerm;
+import jason.asSyntax.Term;
+
+import java.util.Iterator;
+import java.util.List;
+
+/**
+
+ <p>Internal action: <b><code>.sublist(<i>S</i>,<i>L</i>)</code></b>.
+
+ <p>Description: checks if some list <i>S</i> is a sublist of list <i>L</i>. If
+ <i>S</i> has free variables, this internal action backtracks all
+ possible values for <i>S</i>. This is based on .prefix and .suffix (try prefixes first then prefixes of each suffix).
+
+ <p>Parameters:<ul>
+
+ <li>+/- sublist (list): the sublist to be checked.</li>
+ <li>+ list (list): the list where the sublist is from.</li>
+
+ </ul>
+
+ <p>Examples:<ul>
+
+ <li> <code>.sublist([a],[a,b,c])</code>: true.</li>
+ <li> <code>.sublist([b],[a,b,c])</code>: true.</li>
+ <li> <code>.sublist([c],[a,b,c])</code>: true.</li>
+ <li> <code>.sublist([a,b],[a,b,c])</code>: true.</li>
+ <li> <code>.sublist([b,c],[a,b,c])</code>: true.</li>
+ <li> <code>.sublist([d],[a,b,c])</code>: false.</li>
+ <li> <code>.sublist([a,c],[a,b,c])</code>: false.</li>
+ <li> <code>.sublist(X,[a,b,c])</code>: unifies X with any suffix of the list, i.e., [a,b,c], [a,b], [a], [b,c], [b], [c] in this order;
+ note that this is not the order in which its usual implementation would return in logic programming;
+ also, the empty list is not generated as a possible sublist.</li>
+
+ </ul>
+
+ @see jason.stdlib.concat
+ @see jason.stdlib.length
+ @see jason.stdlib.sort
+ @see jason.stdlib.nth
+ @see jason.stdlib.max
+ @see jason.stdlib.min
+ @see jason.stdlib.reverse
+
+ @see jason.stdlib.difference
+ @see jason.stdlib.intersection
+ @see jason.stdlib.union
+
+*/
+public class sublist extends DefaultInternalAction {
+
+ private static InternalAction singleton = null;
+ public static InternalAction create() {
+ if (singleton == null)
+ singleton = new sublist();
+ return singleton;
+ }
+
+ // Needs exactly 2 arguments
+ @Override public int getMinArgs() { return 2; }
+ @Override public int getMaxArgs() { return 2; }
+
+ // improve the check of the arguments to also check the type of the arguments
+ @Override protected void checkArguments(Term[] args) throws JasonException {
+ super.checkArguments(args); // check number of arguments
+ if (!args[0].isList() && !args[0].isVar())
+ throw JasonException.createWrongArgument(this,"first argument must be a list or a variable");
+ if (!args[1].isList())
+ throw JasonException.createWrongArgument(this,"second argument must be a list");
+ }
+
+ @Override
+ public Object execute(TransitionSystem ts, final Unifier un, Term[] args) throws Exception {
+
+ checkArguments(args);
+
+ // execute the internal action
+
+ final Term sublist = args[0];
+// final Iterator<Term> i = ((ListTerm)args[1]).iterator();
+ final ListTerm listOutter = ((ListTerm)args[1]).cloneLT();
+
+ return new Iterator<Unifier>() {
+ Unifier c = null; // the current response (which is an unifier)
+ ListTerm list = listOutter.cloneLT(); // used in the inner loop
+
+ public boolean hasNext() {
+ if (c == null) // the first call of hasNext should find the first response
+ find();
+ return c != null;
+ }
+
+ public Unifier next() {
+ if (c == null) find();
+ Unifier b = c;
+ find(); // find next response
+ return b;
+ }
+
+ void find() {
+ while (!listOutter.isEmpty()) {
+ while (!list.isEmpty()) {
+ c = un.clone();
+ if (c.unifiesNoUndo(sublist, list.clone())) {
+ ((List)list).remove(list.size()-1);
+ return; // found another sublist, c is the current response
+ }
+ ((List)list).remove(list.size()-1);
+ }
+ ((List)listOutter).remove(0);
+ list = listOutter.cloneLT();
+ }
+ c = null; // no more sublists found
+ }
+
+ public void remove() {}
+ };
+ }
+}
Property changes on: trunk/src/jason/stdlib/sublist.java
___________________________________________________________________
Added: svn:eol-style
+ native
Added: trunk/src/jason/stdlib/suffix.java
===================================================================
--- trunk/src/jason/stdlib/suffix.java (rev 0)
+++ trunk/src/jason/stdlib/suffix.java 2009-03-22 01:54:39 UTC (rev 1476)
@@ -0,0 +1,115 @@
+package jason.stdlib;
+
+import jason.JasonException;
+import jason.asSemantics.DefaultInternalAction;
+import jason.asSemantics.InternalAction;
+import jason.asSemantics.TransitionSystem;
+import jason.asSemantics.Unifier;
+import jason.asSyntax.ListTerm;
+import jason.asSyntax.Term;
+
+import java.util.Iterator;
+import java.util.List;
+
+/**
+
+ <p>Internal action: <b><code>.suffix(<i>S</i>,<i>L</i>)</code></b>.
+
+ <p>Description: checks if some list <i>S</i> is a suffix of list <i>L</i>. If
+ <i>S</i> has free variables, this internal action backtracks all
+ possible values for <i>S</i>.
+
+ <p>Parameters:<ul>
+
+ <li>+/- suffix (list): the suffix to be checked.</li>
+ <li>+ list (list): the list where the suffix is from.</li>
+
+ </ul>
+
+ <p>Examples:<ul>
+
+ <li> <code>.suffix([c],[a,b,c])</code>: true.</li>
+ <li> <code>.suffix([a,b],[a,b,c])</code>: false.</li>
+ <li> <code>.suffix(X,[a,b,c])</code>: unifies X with any suffix of the list, i.e., [a,b,c], [b,c], and [c], in this order;
+ note that the empty list is not returned as a pos...
[truncated message content] |
|
From: <bo...@us...> - 2009-03-24 22:57:23
|
Revision: 1479
http://jason.svn.sourceforge.net/jason/?rev=1479&view=rev
Author: bordini
Date: 2009-03-24 22:57:14 +0000 (Tue, 24 Mar 2009)
Log Message:
-----------
Allowed empty list as suffix/prefix/sublist. Changed documentation to remove notes on empty list not being considered, and added these 3 internal actions in stdlib/package.html. Fixed StdLibTest.java to include [] as possible result in backtracking.
Modified Paths:
--------------
trunk/examples/blocks-world/agent_g.asl
trunk/src/jason/stdlib/package.html
trunk/src/jason/stdlib/prefix.java
trunk/src/jason/stdlib/sublist.java
trunk/src/jason/stdlib/suffix.java
trunk/src/test/StdLibTest.java
Modified: trunk/examples/blocks-world/agent_g.asl
===================================================================
--- trunk/examples/blocks-world/agent_g.asl 2009-03-24 11:47:30 UTC (rev 1478)
+++ trunk/examples/blocks-world/agent_g.asl 2009-03-24 22:57:14 UTC (rev 1479)
@@ -9,7 +9,7 @@
allowed(X,Y) :- clear(X) & clear(Y) & not on(X,Y).
-// an ad-hoc implementation of the GOAL a_goal construct for this problem
+// an ad-hoc implementation of the GOAL "a_goal" construct for this problem
a_goal(S,G) :- .member(S1,S) & .suffix(G,S1).
/* Initial goals */
Modified: trunk/src/jason/stdlib/package.html
===================================================================
--- trunk/src/jason/stdlib/package.html 2009-03-24 11:47:30 UTC (rev 1478)
+++ trunk/src/jason/stdlib/package.html 2009-03-24 22:57:14 UTC (rev 1479)
@@ -69,6 +69,9 @@
<li>{@link jason.stdlib.min min}: minimum value of a lists. </li>
<li>{@link jason.stdlib.sort sort}: sort lists. </li>
<li>{@link jason.stdlib.list list}: check whether an argument is a list.</li>
+ <li>{@link jason.stdlib.suffix suffix}: suffixes of a list. </li>
+ <li>{@link jason.stdlib.prefix prefix}: prefixes of a list. </li>
+ <li>{@link jason.stdlib.sublist sublist}: sublists of a list. </li>
<li>{@link jason.stdlib.difference difference}: difference of sets. </li>
<li>{@link jason.stdlib.intersection intersection}: intersection of sets. </li>
Modified: trunk/src/jason/stdlib/prefix.java
===================================================================
--- trunk/src/jason/stdlib/prefix.java 2009-03-24 11:47:30 UTC (rev 1478)
+++ trunk/src/jason/stdlib/prefix.java 2009-03-24 22:57:14 UTC (rev 1479)
@@ -7,9 +7,7 @@
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
import jason.asSyntax.Term;
-
import java.util.Iterator;
-import java.util.List;
/**
@@ -30,9 +28,9 @@
<li> <code>.prefix([a],[a,b,c])</code>: true.</li>
<li> <code>.prefix([b,c],[a,b,c])</code>: false.</li>
- <li> <code>.prefix(X,[a,b,c])</code>: unifies X with any suffix of the list, i.e., [a,b,c], [a,b], and [a], in this order;
- note that this is different from what its usual implementation in logic programming would result;
- also, the empty list is not generated as a possibly prefix. </li>
+ <li> <code>.prefix(X,[a,b,c])</code>: unifies X with any prefix of the list, i.e., [a,b,c], [a,b], [a], and [] in this order;
+ note that this is different from what its usual implementation in logic programming would result,
+ where the various prefixes are returned in increasing lengths instead.</li>
</ul>
@@ -43,6 +41,8 @@
@see jason.stdlib.max
@see jason.stdlib.min
@see jason.stdlib.reverse
+ @see jason.stdlib.suffix
+ @see jason.stdlib.sublist
@see jason.stdlib.difference
@see jason.stdlib.intersection
@@ -51,7 +51,11 @@
*/
public class prefix extends DefaultInternalAction {
- private static InternalAction singleton = null;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -4736810884249871078L;
+ private static InternalAction singleton = null;
public static InternalAction create() {
if (singleton == null)
singleton = new prefix();
@@ -84,6 +88,7 @@
return new Iterator<Unifier>() {
Unifier c = null; // the current response (which is an unifier)
+ boolean triedEmpty = false;
public boolean hasNext() {
if (c == null) // the first call of hasNext should find the first response
@@ -102,11 +107,18 @@
while (!list.isEmpty()) {
c = un.clone();
if (c.unifiesNoUndo(sublist, list.clone())) {
- ((List)list).remove(list.size()-1);
+ list.removeLast();
return; // found another sublist, c is the current response
}
- ((List)list).remove(list.size()-1);
+ list.removeLast();
}
+ if (!triedEmpty) {
+ triedEmpty = true;
+ c = un.clone();
+ if (c.unifiesNoUndo(sublist, list.clone())) {
+ return; // found another sublist, c is the current response
+ }
+ }
c = null; // no more sublists found
}
Modified: trunk/src/jason/stdlib/sublist.java
===================================================================
--- trunk/src/jason/stdlib/sublist.java 2009-03-24 11:47:30 UTC (rev 1478)
+++ trunk/src/jason/stdlib/sublist.java 2009-03-24 22:57:14 UTC (rev 1479)
@@ -7,9 +7,7 @@
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
import jason.asSyntax.Term;
-
import java.util.Iterator;
-import java.util.List;
/**
@@ -35,9 +33,8 @@
<li> <code>.sublist([b,c],[a,b,c])</code>: true.</li>
<li> <code>.sublist([d],[a,b,c])</code>: false.</li>
<li> <code>.sublist([a,c],[a,b,c])</code>: false.</li>
- <li> <code>.sublist(X,[a,b,c])</code>: unifies X with any suffix of the list, i.e., [a,b,c], [a,b], [a], [b,c], [b], [c] in this order;
- note that this is not the order in which its usual implementation would return in logic programming;
- also, the empty list is not generated as a possible sublist.</li>
+ <li> <code>.sublist(X,[a,b,c])</code>: unifies X with any sublist of the list, i.e., [a,b,c], [a,b], [a], [b,c], [b], [c], and [] in this order;
+ note that this is not the order in which its usual implementation would return in logic programming (see note on .prefix).</li>
</ul>
@@ -48,6 +45,8 @@
@see jason.stdlib.max
@see jason.stdlib.min
@see jason.stdlib.reverse
+ @see jason.stdlib.prefix
+ @see jason.stdlib.suffix
@see jason.stdlib.difference
@see jason.stdlib.intersection
@@ -56,7 +55,11 @@
*/
public class sublist extends DefaultInternalAction {
- private static InternalAction singleton = null;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -1725808189703510112L;
+ private static InternalAction singleton = null;
public static InternalAction create() {
if (singleton == null)
singleton = new sublist();
@@ -90,6 +93,7 @@
return new Iterator<Unifier>() {
Unifier c = null; // the current response (which is an unifier)
ListTerm list = listOutter.cloneLT(); // used in the inner loop
+ boolean triedEmpty = false;
public boolean hasNext() {
if (c == null) // the first call of hasNext should find the first response
@@ -109,14 +113,21 @@
while (!list.isEmpty()) {
c = un.clone();
if (c.unifiesNoUndo(sublist, list.clone())) {
- ((List)list).remove(list.size()-1);
+ list.remove(list.size()-1);
return; // found another sublist, c is the current response
}
- ((List)list).remove(list.size()-1);
+ list.remove(list.size()-1);
}
- ((List)listOutter).remove(0);
+ listOutter.remove(0);
list = listOutter.cloneLT();
}
+ if (!triedEmpty) {
+ triedEmpty = true;
+ c = un.clone();
+ if (c.unifiesNoUndo(sublist, list.clone())) {
+ return; // found another sublist, c is the current response
+ }
+ }
c = null; // no more sublists found
}
Modified: trunk/src/jason/stdlib/suffix.java
===================================================================
--- trunk/src/jason/stdlib/suffix.java 2009-03-24 11:47:30 UTC (rev 1478)
+++ trunk/src/jason/stdlib/suffix.java 2009-03-24 22:57:14 UTC (rev 1479)
@@ -7,9 +7,7 @@
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
import jason.asSyntax.Term;
-
import java.util.Iterator;
-import java.util.List;
/**
@@ -30,8 +28,7 @@
<li> <code>.suffix([c],[a,b,c])</code>: true.</li>
<li> <code>.suffix([a,b],[a,b,c])</code>: false.</li>
- <li> <code>.suffix(X,[a,b,c])</code>: unifies X with any suffix of the list, i.e., [a,b,c], [b,c], and [c], in this order;
- note that the empty list is not returned as a possible suffix.</li>
+ <li> <code>.suffix(X,[a,b,c])</code>: unifies X with any suffix of the list, i.e., [a,b,c], [b,c], [c], and [] in this order.</li>
</ul>
@@ -42,6 +39,8 @@
@see jason.stdlib.max
@see jason.stdlib.min
@see jason.stdlib.reverse
+ @see jason.stdlib.prefix
+ @see jason.stdlib.sublist
@see jason.stdlib.difference
@see jason.stdlib.intersection
@@ -50,7 +49,11 @@
*/
public class suffix extends DefaultInternalAction {
- private static InternalAction singleton = null;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 2463927564326061873L;
+ private static InternalAction singleton = null;
public static InternalAction create() {
if (singleton == null)
singleton = new suffix();
@@ -83,7 +86,7 @@
return new Iterator<Unifier>() {
Unifier c = null; // the current response (which is an unifier)
-
+ boolean triedEmpty = false;
public boolean hasNext() {
if (c == null) // the first call of hasNext should find the first response
find();
@@ -101,11 +104,18 @@
while (!list.isEmpty()) {
c = un.clone();
if (c.unifiesNoUndo(sublist, list.clone())) {
- ((List)list).remove(0);
+ list.remove(0);
return; // found another sublist, c is the current response
}
- ((List)list).remove(0);
+ list.remove(0);
}
+ if (!triedEmpty) {
+ triedEmpty = true;
+ c = un.clone();
+ if (c.unifiesNoUndo(sublist, list.clone())) {
+ return; // found another sublist, c is the current response
+ }
+ }
c = null; // no more sublists found
}
Modified: trunk/src/test/StdLibTest.java
===================================================================
--- trunk/src/test/StdLibTest.java 2009-03-24 11:47:30 UTC (rev 1478)
+++ trunk/src/test/StdLibTest.java 2009-03-24 22:57:14 UTC (rev 1479)
@@ -379,11 +379,12 @@
Term tx = ASSyntax.parseTerm("X");
u = new Unifier();
i = (Iterator<Unifier>)new jason.stdlib.prefix().execute(null, u, new Term[] { tx, l1 });
- assertTrue(iteratorSize(i) == 3);
+ assertTrue(iteratorSize(i) == 4);
i = (Iterator<Unifier>)new jason.stdlib.prefix().execute(null, u, new Term[] { tx, l1 });
assertEquals(i.next().get("X").toString(),"[a,b,c]");
assertEquals(i.next().get("X").toString(),"[a,b]");
assertEquals(i.next().get("X").toString(),"[a]");
+ assertEquals(i.next().get("X").toString(),"[]");
assertFalse(i.hasNext());
}
@@ -429,11 +430,12 @@
Term tx = ASSyntax.parseTerm("X");
u = new Unifier();
i = (Iterator<Unifier>)new jason.stdlib.suffix().execute(null, u, new Term[] { tx, l1 });
- assertTrue(iteratorSize(i) == 3);
+ assertTrue(iteratorSize(i) == 4);
i = (Iterator<Unifier>)new jason.stdlib.suffix().execute(null, u, new Term[] { tx, l1 });
assertEquals(i.next().get("X").toString(),"[a,b,c]");
assertEquals(i.next().get("X").toString(),"[b,c]");
assertEquals(i.next().get("X").toString(),"[c]");
+ assertEquals(i.next().get("X").toString(),"[]");
assertFalse(i.hasNext());
}
@@ -530,7 +532,7 @@
Term tx = ASSyntax.parseTerm("X");
u = new Unifier();
i = (Iterator<Unifier>)new jason.stdlib.sublist().execute(null, u, new Term[] { tx, l1 });
- assertTrue(iteratorSize(i) == 6);
+ assertTrue(iteratorSize(i) == 7);
i = (Iterator<Unifier>)new jason.stdlib.sublist().execute(null, u, new Term[] { tx, l1 });
assertEquals(i.next().get("X").toString(),"[a,b,c]");
assertEquals(i.next().get("X").toString(),"[a,b]");
@@ -538,6 +540,7 @@
assertEquals(i.next().get("X").toString(),"[b,c]");
assertEquals(i.next().get("X").toString(),"[b]");
assertEquals(i.next().get("X").toString(),"[c]");
+ assertEquals(i.next().get("X").toString(),"[]");
assertFalse(i.hasNext());
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|