You can subscribe to this list here.
| 2008 |
Jan
|
Feb
|
Mar
(35) |
Apr
(96) |
May
(39) |
Jun
(25) |
Jul
(7) |
Aug
(7) |
Sep
(44) |
Oct
(17) |
Nov
(14) |
Dec
(9) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2009 |
Jan
(5) |
Feb
(28) |
Mar
(26) |
Apr
(14) |
May
(3) |
Jun
(3) |
Jul
(13) |
Aug
(41) |
Sep
(12) |
Oct
|
Nov
(2) |
Dec
(17) |
| 2010 |
Jan
(9) |
Feb
(5) |
Mar
(11) |
Apr
(3) |
May
(4) |
Jun
(2) |
Jul
(3) |
Aug
(8) |
Sep
(2) |
Oct
(11) |
Nov
(3) |
Dec
(1) |
| 2011 |
Jan
|
Feb
(1) |
Mar
(8) |
Apr
(4) |
May
(4) |
Jun
(5) |
Jul
(3) |
Aug
(2) |
Sep
(7) |
Oct
(4) |
Nov
(4) |
Dec
(2) |
| 2012 |
Jan
|
Feb
|
Mar
(4) |
Apr
(11) |
May
(8) |
Jun
(2) |
Jul
(7) |
Aug
(6) |
Sep
(2) |
Oct
(2) |
Nov
|
Dec
(3) |
| 2013 |
Jan
|
Feb
(1) |
Mar
(7) |
Apr
(3) |
May
(1) |
Jun
(4) |
Jul
(8) |
Aug
(4) |
Sep
(4) |
Oct
(6) |
Nov
(8) |
Dec
(6) |
| 2014 |
Jan
|
Feb
|
Mar
(2) |
Apr
(4) |
May
(6) |
Jun
(10) |
Jul
|
Aug
(7) |
Sep
(15) |
Oct
(4) |
Nov
(1) |
Dec
(1) |
| 2015 |
Jan
|
Feb
(1) |
Mar
(10) |
Apr
(4) |
May
(6) |
Jun
(1) |
Jul
|
Aug
(2) |
Sep
(2) |
Oct
(5) |
Nov
(6) |
Dec
(12) |
| 2016 |
Jan
(1) |
Feb
(4) |
Mar
(7) |
Apr
(30) |
May
(5) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
|
From: <jom...@us...> - 2008-03-30 20:41:49
|
Revision: 1181
http://jason.svn.sourceforge.net/jason/?rev=1181&view=rev
Author: jomifred
Date: 2008-03-30 13:41:40 -0700 (Sun, 30 Mar 2008)
Log Message:
-----------
undo terms as plan's body
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/tests/TestAll.java
trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/test/ASParserTest.java
trunk/src/test/PlanTest.java
Modified: trunk/applications/as-unit-test/src/jason/tests/TestAll.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestAll.java 2008-03-30 14:24:59 UTC (rev 1180)
+++ trunk/applications/as-unit-test/src/jason/tests/TestAll.java 2008-03-30 20:41:40 UTC (rev 1181)
@@ -9,7 +9,7 @@
BugVarsInInitBels.class,
TestAddLogExprInBB.class,
TestKQML.class,
- TestVarInContext.class,
- TestPlanbodyAsTerm.class
+ TestVarInContext.class /*,
+ TestPlanbodyAsTerm.class*/
})
public class TestAll { }
Modified: trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java 2008-03-30 14:24:59 UTC (rev 1180)
+++ trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java 2008-03-30 20:41:40 UTC (rev 1181)
@@ -18,6 +18,7 @@
ag.parseAScode(
"+!start <- +g(a(1); b; c); ?g(X); !g(X). "+
"+!test2 <- !g(!g2(1)). "+
+ "+!test3 <- !g2(-1 + 2). "+
"+!g(A; R) <- A; !g(R). "+
"+!g(A) <- A." +
"+!g2(A) <- jason.asunit.print(A)."
@@ -39,4 +40,10 @@
ag.assertPrint("1", 5);
}
+ @Test
+ public void testProgram3() {
+ ag.addGoal("test3");
+ ag.assertPrint("1", 5);
+ }
+
}
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-30 14:24:59 UTC (rev 1180)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-30 20:41:40 UTC (rev 1181)
@@ -449,15 +449,15 @@
Term term() : { Object o;}
{
( o=list()
- | o=plan_body() // plan_body includes literals/atoms/structures
+ | o=log_expr() //plan_body() // plan_body includes literals/atoms/structures
)
{ // if the result is a BodyLiteral action with size = 1, it is indeed a literal and not a body literal
- if (o instanceof BodyLiteral) {
+ /*if (o instanceof BodyLiteral) {
BodyLiteral bl = (BodyLiteral)o;
if (bl.getBodyType() == BodyType.action && bl.getPlanSize() == 1) {
o = bl.getBodyTerm();
}
- }
+ }*/
return changeToAtom(o);
}
}
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2008-03-30 14:24:59 UTC (rev 1180)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2008-03-30 20:41:40 UTC (rev 1181)
@@ -653,13 +653,9 @@
case STRING:
case ATOM:
case UNNAMEDVAR:
- case 31:
- case 34:
case 35:
- case 36:
- case 38:
case 39:
- o = plan_body();
+ o = log_expr();
break;
default:
jj_la1[27] = jj_gen;
@@ -667,12 +663,12 @@
throw new ParseException();
}
// if the result is a BodyLiteral action with size = 1, it is indeed a literal and not a body literal
- if (o instanceof BodyLiteral) {
+ /*if (o instanceof BodyLiteral) {
BodyLiteral bl = (BodyLiteral)o;
if (bl.getBodyType() == BodyType.action && bl.getPlanSize() == 1) {
o = bl.getBodyTerm();
}
- }
+ }*/
{if (true) return changeToAtom(o);}
throw new Error("Missing return statement in function");
}
@@ -1240,10 +1236,10 @@
jj_la1_1();
}
private static void jj_la1_0() {
- jj_la1_0 = new int[] {0x8000000,0x10cb00,0x8000000,0x80000000,0x8000000,0x10000,0x10cb00,0x8000000,0x8000000,0x20000000,0x10000,0x0,0x0,0x0,0x80000000,0x80000000,0x30cb80,0x800,0x10cb00,0x0,0x0,0x80000000,0x80000000,0x10c000,0x0,0x0,0x0,0x803acf80,0x0,0x200080,0x0,0x3acb80,0x3acb80,0x0,0x0,0x3acf80,0x3acb80,0x0,0x3acb80,0x0,0x0,0x0,0x3000,0x3000,0x0,0x32cb80,0x200080,0x0,};
+ jj_la1_0 = new int[] {0x8000000,0x10cb00,0x8000000,0x80000000,0x8000000,0x10000,0x10cb00,0x8000000,0x8000000,0x20000000,0x10000,0x0,0x0,0x0,0x80000000,0x80000000,0x30cb80,0x800,0x10cb00,0x0,0x0,0x80000000,0x80000000,0x10c000,0x0,0x0,0x0,0x3acf80,0x0,0x200080,0x0,0x3acb80,0x3acb80,0x0,0x0,0x3acf80,0x3acb80,0x0,0x3acb80,0x0,0x0,0x0,0x3000,0x3000,0x0,0x32cb80,0x200080,0x0,};
}
private static void jj_la1_1() {
- jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0xc,0x0,0x0,0x0,0x0,0x0,0x1,0x2,0xc,0x10,0x10,0x0,0x0,0x0,0x20,0x4,0x5c,0x5c,0x0,0x80,0x400,0x200,0x4dc,0x200,0x400,0x800,0x488,0x488,0x800,0x2000,0x88,0x88,0x3fc000,0x488,0x3fc000,0xc,0xc,0xc00000,0xc00000,0x1000000,0x88,0x0,0x400,};
+ jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0xc,0x0,0x0,0x0,0x0,0x0,0x1,0x2,0xc,0x10,0x10,0x0,0x0,0x0,0x20,0x4,0x5c,0x5c,0x0,0x80,0x400,0x200,0x488,0x200,0x400,0x800,0x488,0x488,0x800,0x2000,0x88,0x88,0x3fc000,0x488,0x3fc000,0xc,0xc,0xc00000,0xc00000,0x1000000,0x88,0x0,0x400,};
}
final private JJCalls[] jj_2_rtns = new JJCalls[1];
private boolean jj_rescan = false;
Modified: trunk/src/test/ASParserTest.java
===================================================================
--- trunk/src/test/ASParserTest.java 2008-03-30 14:24:59 UTC (rev 1180)
+++ trunk/src/test/ASParserTest.java 2008-03-30 20:41:40 UTC (rev 1181)
@@ -5,7 +5,6 @@
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.BodyLiteral;
-import jason.asSyntax.Literal;
import jason.asSyntax.LogExpr;
import jason.asSyntax.LogicalFormula;
import jason.asSyntax.NumberTerm;
@@ -165,6 +164,8 @@
}
public void testParsingPlanBody() {
+ // TODO: think about this
+ /*
Literal l = Literal.parseLiteral("p(a1;a2, a3, !g, ?b;.print(oi), 10)");
assertEquals(5,l.getArity());
assertTrue(l.getTerm(0) instanceof BodyLiteral);
@@ -174,7 +175,7 @@
assertTrue(l.getTerm(2).isPlanBody());
assertTrue(l.getTerm(3).isPlanBody());
assertFalse(l.getTerm(4).isPlanBody());
-
+ */
}
public void testParsingAllSources() {
Modified: trunk/src/test/PlanTest.java
===================================================================
--- trunk/src/test/PlanTest.java 2008-03-30 14:24:59 UTC (rev 1180)
+++ trunk/src/test/PlanTest.java 2008-03-30 20:41:40 UTC (rev 1181)
@@ -55,7 +55,7 @@
assertEquals(0, pls.size());
}
- public void testParser() {
+ public void testParser1() {
Plan p = Plan.parse("+te : a & b <- a1; a2; .print(a); !g1; !!g2; ?test1; 10 > 3; +b1; -b2; -+b3.");
p = (Plan)p.clone();
Iterator<BodyLiteral> i = ((BodyLiteralImpl)p.getBody()).iterator();
@@ -72,7 +72,7 @@
assertEquals( BodyLiteral.BodyType.delAddBel, ((BodyLiteral)i.next()).getBodyType());
assertFalse(i.hasNext());
}
-
+
public void testDelete() {
Plan p = Plan.parse("+te : a & b <- !a1; ?a2; .print(a); !g1.");
assertEquals(4, p.getBody().getPlanSize());
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-30 14:25:07
|
Revision: 1180
http://jason.svn.sourceforge.net/jason/?rev=1180&view=rev
Author: jomifred
Date: 2008-03-30 07:24:59 -0700 (Sun, 30 Mar 2008)
Log Message:
-----------
variables can be unified with BodyLiteral
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/asunit/TestArch.java
trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java
trunk/demos/directives/myp/LoggerDirective.java
trunk/demos/failure/a.asl
trunk/src/jason/asSemantics/ActionExec.java
trunk/src/jason/asSemantics/IntendedMeans.java
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/asSyntax/BodyLiteral.java
trunk/src/jason/asSyntax/Plan.java
trunk/src/jason/asSyntax/Term.java
trunk/src/jason/asSyntax/VarTerm.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/jason/asSyntax/patterns/goal/DG.java
trunk/src/jason/asSyntax/patterns/goal/EBDG.java
trunk/src/jason/stdlib/wait.java
trunk/src/test/ASParserTest.java
trunk/src/test/PlanTest.java
trunk/src/xml/agInspection.xsl
trunk/src/xml/asl2html.xsl
Added Paths:
-----------
trunk/src/jason/asSyntax/BodyLiteralImpl.java
Modified: trunk/applications/as-unit-test/src/jason/asunit/TestArch.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/asunit/TestArch.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/applications/as-unit-test/src/jason/asunit/TestArch.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -5,8 +5,6 @@
import jason.asSemantics.ActionExec;
import jason.asSyntax.Literal;
import jason.asSyntax.Structure;
-import jason.asSyntax.Term;
-import jason.asSyntax.VarTerm;
import jason.environment.Environment;
import jason.infra.centralised.CentralisedAgArch;
import jason.infra.centralised.CentralisedEnvironment;
@@ -85,12 +83,7 @@
@Override
public void act(ActionExec action, List<ActionExec> feedback) {
- Term t = action.getActionTerm();
- if (t instanceof VarTerm) {
- t = ((VarTerm)t).getValue();
- }
- actions.add(action.getActionTerm());
- System.out.println("*"+action.getActionTerm().getClass().getName()+" "+t.getClass().getName());
+ actions.add(action.getActionTerm());
if (getEnvInfraTier() != null) {
super.act(action, feedback); //env.scheduleAction(getAgName(), action.getActionTerm(), action);
} else {
Modified: trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -16,19 +16,27 @@
// defines the agent's AgentSpeak code
ag.parseAScode(
- "+!start <- +g(a; b; c); ?g(X); !g(X). "+
+ "+!start <- +g(a(1); b; c); ?g(X); !g(X). "+
+ "+!test2 <- !g(!g2(1)). "+
"+!g(A; R) <- A; !g(R). "+
- "+!g(A) <- .print(A); A; .print(end)."
+ "+!g(A) <- A." +
+ "+!g2(A) <- jason.asunit.print(A)."
);
}
@Test
- public void testProgram() {
+ public void testProgram1() {
ag.addGoal("start");
- ag.assertBel("g(a;b;c)", 5);
- ag.assertAct("a", 4);
+ ag.assertBel("g(a(1);b;c)", 5);
+ ag.assertAct("a(1)", 4);
ag.assertAct("b", 4);
ag.assertAct("c", 4);
}
+ @Test
+ public void testProgram2() {
+ ag.addGoal("test2");
+ ag.assertPrint("1", 5);
+ }
+
}
Modified: trunk/demos/directives/myp/LoggerDirective.java
===================================================================
--- trunk/demos/directives/myp/LoggerDirective.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/demos/directives/myp/LoggerDirective.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -3,6 +3,7 @@
import jason.asSemantics.Agent;
import jason.asSyntax.BodyLiteral;
+import jason.asSyntax.BodyLiteralImpl;
import jason.asSyntax.Literal;
import jason.asSyntax.Plan;
import jason.asSyntax.Pred;
@@ -27,11 +28,11 @@
// add .print(te) in the begin and end of the plan
for (Plan p: innerContent.getPL()) {
Literal print1 = Literal.parseLiteral(".print(\"Entering \","+p.getTrigger().getLiteral()+")");
- BodyLiteral b1 = new BodyLiteral(BodyType.internalAction, print1);
+ BodyLiteral b1 = new BodyLiteralImpl(BodyType.internalAction, print1);
p.getBody().add(0,b1);
Literal print2 = Literal.parseLiteral(".print(\"Leaving \","+p.getTrigger().getLiteral()+")");
- BodyLiteral b2 = new BodyLiteral(BodyType.internalAction, print2);
+ BodyLiteral b2 = new BodyLiteralImpl(BodyType.internalAction, print2);
p.getBody().add(b2);
newAg.getPL().add(p);
Modified: trunk/demos/failure/a.asl
===================================================================
--- trunk/demos/failure/a.asl 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/demos/failure/a.asl 2008-03-30 14:24:59 UTC (rev 1180)
@@ -8,5 +8,13 @@
+!g5(_) : true <- .fail.
-!g3(failure) : true
<- .current_intention(I);
- .print("In failure handling plan, current intention is: ",I).
+ .print("In failure handling plan, current intention is: ",I);
+ I = intention(Id,IntendedMeans);
+ .println;
+ .println("* Intention ",Id, " IM stack:");
+ !print_im(IntendedMeans).
++!print_im([]).
++!print_im([im(_Planlabel,Body)|R])
+ <- .println("* ",Body);
+ !print_im(R).
Modified: trunk/src/jason/asSemantics/ActionExec.java
===================================================================
--- trunk/src/jason/asSemantics/ActionExec.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSemantics/ActionExec.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -61,8 +61,9 @@
}
public Structure getActionTerm() {
- return action;
+ return action;
}
+
public Intention getIntention() {
return intention;
}
Modified: trunk/src/jason/asSemantics/IntendedMeans.java
===================================================================
--- trunk/src/jason/asSemantics/IntendedMeans.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSemantics/IntendedMeans.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -25,6 +25,7 @@
package jason.asSemantics;
import jason.asSyntax.BodyLiteral;
+import jason.asSyntax.BodyLiteralImpl;
import jason.asSyntax.ListTerm;
import jason.asSyntax.ListTermImpl;
import jason.asSyntax.Literal;
@@ -73,10 +74,10 @@
/** removes the current action of the IM and returns the term of the body */
public Term removeCurrentStep() {
BodyLiteral current = plan.getBody();
- if (current.isEmpty()) {
+ if (current.isEmptyBody()) {
return null;
} else {
- return current.remove(0);
+ return current.removeBody(0);
}
}
@@ -106,7 +107,7 @@
}
public boolean isFinished() {
- return plan.getBody().isEmpty();
+ return plan.getBody().isEmptyBody();
}
public boolean isGoalAdd() {
@@ -128,13 +129,15 @@
public Term getAsTerm() {
Structure im = new Structure("im");
im.addTerm(new StringTermImpl(plan.getLabel().toString()));
- ListTerm lt = new ListTermImpl();
- for (Term bd: plan.getBody()) {
- Term c = (Term)bd.clone();
- c.apply(unif);
- lt.add(new StringTermImpl(c.toString()));
+ if (plan.getBody() instanceof BodyLiteralImpl) {
+ ListTerm lt = new ListTermImpl();
+ for (BodyLiteral bd: (BodyLiteralImpl)plan.getBody()) {
+ BodyLiteral c = (BodyLiteral)bd.clone();
+ c.apply(unif);
+ lt.add(new StringTermImpl(c.getBodyType().toString()+c.getBodyTerm()));
+ }
+ im.addTerm(lt);
}
- im.addTerm(lt);
return im;
}
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -402,16 +402,15 @@
return;
}
Unifier u = im.unif;
- BodyLiteral h = im.getCurrentStep();
- Term bTerm = h.getTerm();
+ BodyLiteral h = im.getCurrentStep();
+ h.apply(u);
- bTerm.apply(u);
-
- Literal body = null;
+ Literal body = null;
+ Term bTerm = h.getBodyTerm();
if (bTerm instanceof Literal)
body = (Literal)bTerm;
- switch (h.getType()) {
+ switch (h.getBodyType()) {
// Rule Action
case action:
Modified: trunk/src/jason/asSyntax/BodyLiteral.java
===================================================================
--- trunk/src/jason/asSyntax/BodyLiteral.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSyntax/BodyLiteral.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -1,12 +1,7 @@
package jason.asSyntax;
-import java.util.Iterator;
+public interface BodyLiteral extends Term {
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class BodyLiteral extends Structure implements Iterable<BodyLiteral> {
-
public enum BodyType {
none { public String toString() { return ""; }},
action { public String toString() { return ""; }},
@@ -20,198 +15,19 @@
constraint { public String toString() { return ""; }}
}
- public static final String BODY_PLAN_FUNCTOR = ";";
+ public BodyType getBodyType();
+ public Term getBodyTerm();
+ public BodyLiteral getBodyNext();
- private Term term = null;
- private BodyLiteral next = null;
- private BodyType formType = BodyType.none;
-
- /** constructor for empty plan body */
- public BodyLiteral() {
- super(BODY_PLAN_FUNCTOR, 0);
- }
-
- public BodyLiteral(BodyType t, Term b) {
- super(BODY_PLAN_FUNCTOR, 0);
- term = b;
- formType = t;
- setSrc(b);
- }
+ public boolean isEmptyBody();
+ public int getPlanSize();
- public void setNext(BodyLiteral next) {
- this.next = next;
- }
- public BodyLiteral getNext() {
- return next;
- }
-
- public boolean isEmpty() {
- return term == null;
- }
+ public void setBodyType(BodyType bt);
+ public void setBodyTerm(Term t);
+ public void setBodyNext(BodyLiteral bl);
- public BodyType getType() {
- return formType;
- }
- public Term getTerm() {
- return term;
- }
-
- public Literal getLiteralFormula() {
- if (term instanceof Literal)
- return (Literal)term;
- else
- return null;
- }
-
- public Iterator<BodyLiteral> iterator() {
- return new Iterator<BodyLiteral>() {
- BodyLiteral current = BodyLiteral.this;
- public boolean hasNext() {
- return current != null && current.term != null && current.next != null;
- }
- public BodyLiteral next() {
- BodyLiteral r = current;
- if (current != null)
- current = current.next;
- return r;
- }
- public void remove() { }
- };
- }
-
- // Override some structure methods to work with unification/equals
- @Override
- public int getArity() {
- if (term == null)
- return 0;
- else if (next == null)
- return 1;
- else
- return 2;
- }
-
- @Override
- public Term getTerm(int i) {
- if (i == 0) return term;
- if (i == 1) {
- if (next != null && next.term.isVar() && next.next == null)
- // if next is the last VAR, return that var
- return next.term;
- else
- return next;
- }
- return null;
- }
-
- @Override
- public void setTerm(int i, Term t) {
- if (i == 0) term = t;
- if (i == 1) System.out.println("Should not set next of body literal!");
- }
-
- @Override
- public boolean isPlanBody() {
- return true;
- }
-
- @Override
- public boolean equals(Object o) {
- if (o == null) return false;
- if (o == this) return true;
- if (o instanceof BodyLiteral) {
- BodyLiteral b = (BodyLiteral)o;
- return formType == b.formType && super.equals(o);
- }
- return false;
- }
-
- @Override
- public int calcHashCode() {
- return formType.hashCode() + super.calcHashCode();
- }
-
- public boolean add(BodyLiteral bl) {
- if (term == null)
- swap(bl);
- else if (next == null)
- next = bl;
- else
- next.add(bl);
- return true;
- }
-
- public boolean add(int index, BodyLiteral bl) {
- if (index == 0) {
- swap(bl);
- this.next = bl;
- } else {
- next.add(index - 1, bl);
- }
- return true;
- }
-
- public Term remove(int index) {
- if (index == 0) {
- if (next == null) {
- term = null; // becomes an empty
- } else {
- Term oldvalue = term;
- swap(next); // get values of text
- next = next.next;
- return oldvalue;
- }
- return this;
- } else {
- return next.remove(index - 1);
- }
- }
-
- public int size() {
- if (term == null)
- return 0;
- else if (next == null)
- return 1;
- else
- return next.size() + 1;
- }
-
- private void swap(BodyLiteral bl) {
- BodyType bt = this.formType;
- this.formType = bl.formType;
- bl.formType = bt;
-
- Term l = this.term;
- this.term = bl.term;
- bl.term = l;
- }
-
- public Object clone() {
- if (term == null) // empty
- return new BodyLiteral();
-
- BodyLiteral c = new BodyLiteral(formType, (Term)term.clone());
- if (next != null)
- c.setNext((BodyLiteral)getNext().clone());
- return c;
- }
-
- public String toString() {
- if (term == null)
- return "";
- else if (next == null)
- return formType.toString() + term;
- else
- return formType.toString() + term + "; " + next;
- }
-
- /** get as XML */
- public Element getAsDOM(Document document) {
- Element u = (Element) document.createElement("body-literal");
- if (formType.toString().length() > 0) {
- u.setAttribute("type", formType.toString());
- }
- u.appendChild( ((Structure)term).getAsDOM(document));
- return u;
- }
+ public boolean add(BodyLiteral bl);
+ public boolean add(int index, BodyLiteral bl);
+ public Term removeBody(int index);
}
\ No newline at end of file
Added: trunk/src/jason/asSyntax/BodyLiteralImpl.java
===================================================================
--- trunk/src/jason/asSyntax/BodyLiteralImpl.java (rev 0)
+++ trunk/src/jason/asSyntax/BodyLiteralImpl.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -0,0 +1,236 @@
+package jason.asSyntax;
+
+import jason.asSemantics.Unifier;
+
+import java.util.Iterator;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * Represents a plan body item (achieve, test, action, ...) and its successors.
+ *
+ * A plan body like <code>a1; ?t; !g</code> is represented by the following structure
+ * <code>(a1, (?t, (!g)))</code>.
+ *
+ * @author Jomi
+ */
+public class BodyLiteralImpl extends Structure implements BodyLiteral, Iterable<BodyLiteral> {
+
+ public static final String BODY_PLAN_FUNCTOR = ";";
+
+ private Term term = null;
+ private BodyLiteral next = null;
+ private BodyType formType = BodyType.none;
+
+ /** constructor for empty plan body */
+ public BodyLiteralImpl() {
+ super(BODY_PLAN_FUNCTOR, 0);
+ }
+
+ public BodyLiteralImpl(BodyType t, Term b) {
+ super(BODY_PLAN_FUNCTOR, 0);
+ term = b;
+ formType = t;
+ setSrc(b);
+ }
+
+ public void setBodyNext(BodyLiteral next) {
+ this.next = next;
+ }
+ public BodyLiteral getBodyNext() {
+ return next;
+ }
+
+ public boolean isEmptyBody() {
+ return term == null;
+ }
+
+ public BodyType getBodyType() {
+ return formType;
+ }
+ public void setBodyType(BodyType bt) {
+ formType = bt;
+ }
+
+ public Term getBodyTerm() {
+ return term;
+ }
+ public void setBodyTerm(Term t) {
+ term = t;
+ }
+
+ @Override
+ public boolean isPlanBody() {
+ return true;
+ }
+
+ public Iterator<BodyLiteral> iterator() {
+ return new Iterator<BodyLiteral>() {
+ BodyLiteral current = BodyLiteralImpl.this;
+ public boolean hasNext() {
+ return current != null && current.getBodyTerm() != null;
+ }
+ public BodyLiteral next() {
+ BodyLiteral r = current;
+ if (current != null)
+ current = current.getBodyNext();
+ return r;
+ }
+ public void remove() { }
+ };
+ }
+
+ // Override some structure methods to work with unification/equals
+ @Override
+ public int getArity() {
+ if (term == null)
+ return 0;
+ else if (next == null)
+ return 1;
+ else
+ return 2;
+ }
+
+ @Override
+ public Term getTerm(int i) {
+ if (i == 0)
+ return term;
+ if (i == 1) {
+ if (next != null && next.getBodyTerm().isVar() && next.getBodyNext() == null)
+ // if next is the last VAR, return that var
+ return next.getBodyTerm();
+ else
+ return next;
+ }
+ return null;
+ }
+
+ @Override
+ public void setTerm(int i, Term t) {
+ if (i == 0) term = t;
+ if (i == 1) System.out.println("Should not set next of body literal!");
+ }
+
+ @Override
+ public boolean apply(Unifier u) {
+ // do not apply in next!
+ resetHashCodeCache();
+ if (term != null && term.apply(u)) {
+ if (term.isPlanBody()) { // we can not have "inner" body literals
+ formType = ((BodyLiteral)term).getBodyType();
+ term = ((BodyLiteral)term).getBodyTerm();
+ }
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null) return false;
+ if (o == this) return true;
+
+ if (o instanceof BodyLiteral) {
+ BodyLiteral b = (BodyLiteral)o;
+ return formType == b.getBodyType() && super.equals(o);
+ }
+ return false;
+ }
+
+ @Override
+ public int calcHashCode() {
+ return formType.hashCode() + super.calcHashCode();
+ }
+
+ public boolean add(BodyLiteral bl) {
+ if (term == null)
+ swap(bl);
+ else if (next == null)
+ next = bl;
+ else
+ next.add(bl);
+ return true;
+ }
+
+ public boolean add(int index, BodyLiteral bl) {
+ if (index == 0) {
+ swap(bl);
+ this.next = bl;
+ } else {
+ next.add(index - 1, bl);
+ }
+ return true;
+ }
+
+ public Term removeBody(int index) {
+ if (index == 0) {
+ if (next == null) {
+ term = null; // becomes an empty
+ } else {
+ Term oldvalue = term;
+ swap(next); // get values of text
+ next = next.getBodyNext();
+ return oldvalue;
+ }
+ return this;
+ } else {
+ return next.removeBody(index - 1);
+ }
+ }
+
+ public int getPlanSize() {
+ if (term == null)
+ return 0;
+ else if (next == null)
+ return 1;
+ else
+ return next.getPlanSize() + 1;
+ }
+
+ private void swap(BodyLiteral bl) {
+ BodyType bt = this.formType;
+ this.formType = bl.getBodyType();
+ bl.setBodyType(bt);
+
+ Term l = this.term;
+ this.term = bl.getBodyTerm();
+ bl.setBodyTerm(l);
+ }
+
+ public Object clone() {
+ if (term == null) // empty
+ return new BodyLiteralImpl();
+
+ BodyLiteralImpl c = new BodyLiteralImpl(formType, (Term)term.clone());
+ if (next != null)
+ c.setBodyNext((BodyLiteral)getBodyNext().clone());
+ return c;
+ }
+
+ public String toString() {
+ if (term == null)
+ return "";
+ else if (next == null)
+ return formType.toString() + term;
+ else
+ return formType.toString() + term + "; " + next;
+ }
+
+ /** get as XML */
+ public Element getAsDOM(Document document) {
+ Element eb = (Element) document.createElement("body");
+ BodyLiteral bl = this;
+ while (bl != null && !bl.isEmptyBody()) {
+ Element u = (Element) document.createElement("body-literal");
+ if (bl.getBodyType().toString().length() > 0) {
+ u.setAttribute("type", bl.getBodyType().toString());
+ }
+ u.appendChild( ((Structure)bl.getBodyTerm()).getAsDOM(document));
+ eb.appendChild(u);
+
+ bl = bl.getBodyNext();
+ }
+ return eb;
+ }
+}
Modified: trunk/src/jason/asSyntax/Plan.java
===================================================================
--- trunk/src/jason/asSyntax/Plan.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSyntax/Plan.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -68,7 +68,7 @@
setLabel(label);
setContext(ct);
if (bd == null)
- body = new BodyLiteral();
+ body = new BodyLiteralImpl();
else
body = bd;
}
@@ -234,7 +234,7 @@
public String toASString() {
return ((label == null) ? "" : "@" + label + " ") +
tevent + ((context == null) ? "" : " : " + context) +
- (body.isEmpty() ? "" : " <- " + body) +
+ (body.isEmptyBody() ? "" : " <- " + body) +
".";
}
@@ -254,18 +254,8 @@
u.appendChild(ec);
}
- if (body.size() > 0) {
- Element eb = (Element) document.createElement("body");
- for (BodyLiteral bl: body) {
- eb.appendChild(bl.getAsDOM(document));
- }
- /*
- Iterator<ListTerm> i = body.listTermIterator();
- while (i.hasNext()) {
- eb.appendChild(i.next().getAsDOM(document));
- }
- */
- u.appendChild(eb);
+ if (!body.isEmptyBody()) {
+ u.appendChild(body.getAsDOM(document));
}
return u;
Modified: trunk/src/jason/asSyntax/Term.java
===================================================================
--- trunk/src/jason/asSyntax/Term.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSyntax/Term.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -12,33 +12,20 @@
public interface Term extends Cloneable, Comparable<Term>, Serializable, ToDOM {
public boolean isVar();
-
public boolean isLiteral();
-
public boolean isRule();
-
public boolean isList();
-
public boolean isString();
-
public boolean isInternalAction();
-
public boolean isArithExpr();
-
public boolean isNumeric();
-
public boolean isPred();
-
public boolean isGround();
-
public boolean isStructure();
-
public boolean isAtom();
-
public boolean isPlanBody();
public boolean hasVar(VarTerm t);
-
public void countVars(Map<VarTerm, Integer> c);
public Object clone();
@@ -56,4 +43,6 @@
public int getSrcLine();
public String getSrc();
+ public String getErrorMsg(); // info for error messages
+
}
Modified: trunk/src/jason/asSyntax/VarTerm.java
===================================================================
--- trunk/src/jason/asSyntax/VarTerm.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSyntax/VarTerm.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -46,7 +46,7 @@
*
* @author jomi
*/
-public class VarTerm extends Literal implements NumberTerm, ListTerm, StringTerm, ObjectTerm {
+public class VarTerm extends Literal implements NumberTerm, ListTerm, StringTerm, ObjectTerm, BodyLiteral {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(VarTerm.class.getName());
@@ -312,6 +312,11 @@
public boolean isString() {
return value != null && getValue().isString();
}
+
+ @Override
+ public boolean isPlanBody() {
+ return value != null && getValue().isPlanBody();
+ }
@Override
public boolean isNumeric() {
@@ -863,6 +868,82 @@
return null;
}
+ // -----------------------
+ // BodyLiteral interface implementation
+ // -----------------------
+
+ public BodyType getBodyType() {
+ if (value != null && getValue() instanceof BodyLiteral)
+ return ((BodyLiteral) getValue()).getBodyType();
+ else
+ return BodyType.none;
+ }
+
+ public Term getBodyTerm() {
+ if (value != null && getValue() instanceof BodyLiteral)
+ return ((BodyLiteral) getValue()).getBodyTerm();
+ else
+ return null;
+ }
+
+ public BodyLiteral getBodyNext() {
+ if (value != null && getValue() instanceof BodyLiteral)
+ return ((BodyLiteral) getValue()).getBodyNext();
+ else
+ return null;
+ }
+
+ public boolean isEmptyBody() {
+ if (value != null && getValue() instanceof BodyLiteral)
+ return ((BodyLiteral) getValue()).isEmptyBody();
+ else
+ return true;
+ }
+
+ public int getPlanSize() {
+ if (value != null && getValue() instanceof BodyLiteral)
+ return ((BodyLiteral) getValue()).getPlanSize();
+ else
+ return 0;
+ }
+
+ public void setBodyType(BodyType bt) {
+ if (value != null && getValue() instanceof BodyLiteral)
+ ((BodyLiteral) getValue()).setBodyType(bt);
+ }
+
+ public void setBodyTerm(Term t) {
+ if (value != null && getValue() instanceof BodyLiteral)
+ ((BodyLiteral) getValue()).setBodyTerm(t);
+ }
+
+ public void setBodyNext(BodyLiteral bl) {
+ if (value != null && getValue() instanceof BodyLiteral)
+ ((BodyLiteral) getValue()).setBodyNext(bl);
+ }
+
+ public boolean add(BodyLiteral bl) {
+ if (value != null && getValue() instanceof BodyLiteral)
+ return ((BodyLiteral) getValue()).add(bl);
+ else
+ return false;
+ }
+
+ public boolean add(int index, BodyLiteral bl) {
+ if (value != null && getValue() instanceof BodyLiteral)
+ return ((BodyLiteral) getValue()).add(index, bl);
+ else
+ return false;
+ }
+
+ public Term removeBody(int index) {
+ if (value != null && getValue() instanceof BodyLiteral)
+ return ((BodyLiteral) getValue()).removeBody(index);
+ else
+ return null;
+ }
+
+
/** get as XML */
public Element getAsDOM(Document document) {
if (hasValue()) {
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-30 14:24:59 UTC (rev 1180)
@@ -307,8 +307,8 @@
if (!(B instanceof BodyLiteral))
throw new ParseException(getSourceRef(B)+" Unknown body formula:"+B);
bl = (BodyLiteral)B;
- if (bl.getTerm().equals(Literal.LTrue))
- bl = (BodyLiteral)bl.getNext();
+ if (bl.getBodyTerm().equals(Literal.LTrue))
+ bl = (BodyLiteral)bl.getBodyNext();
}
Plan p = new Plan(L,T,(LogicalFormula)C, bl);
p.setSrcLines(start,end);
@@ -370,7 +370,7 @@
R = plan_body() { if (!(R instanceof BodyLiteral)) throw new ParseException(getSourceRef(R)+" "+R+" is not a body literal!"); }
]
{ if (F instanceof BodyLiteral && R instanceof BodyLiteral) {
- ((BodyLiteral)F).setNext( (BodyLiteral)R );
+ ((BodyLiteral)F).setBodyNext( (BodyLiteral)R );
}
return F;
}
@@ -394,13 +394,13 @@
{ if (B instanceof Literal) {
if ( ((Literal)B).isInternalAction() )
formType = BodyType.internalAction;
- return new BodyLiteral(formType, (Literal)B);
+ return new BodyLiteralImpl(formType, (Literal)B);
} else if (formType == BodyType.action && B instanceof RelExpr) {
- return new BodyLiteral(BodyType.constraint, (RelExpr)B); // constraint
+ return new BodyLiteralImpl(BodyType.constraint, (RelExpr)B); // constraint
} else {
if (formType == BodyType.test) {
if (B instanceof LogicalFormula)
- return new BodyLiteral(BodyType.test, (Term)B); // used in ?(a & b)
+ return new BodyLiteralImpl(BodyType.test, (Term)B); // used in ?(a & b)
else
throw new ParseException(getSourceRef(B)+" The argument for ? is not a logical formula.");
} else {
@@ -454,8 +454,8 @@
{ // if the result is a BodyLiteral action with size = 1, it is indeed a literal and not a body literal
if (o instanceof BodyLiteral) {
BodyLiteral bl = (BodyLiteral)o;
- if (bl.getType() == BodyType.action && bl.size() == 1) {
- o = bl.getTerm();
+ if (bl.getBodyType() == BodyType.action && bl.getPlanSize() == 1) {
+ o = bl.getBodyTerm();
}
}
return changeToAtom(o);
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -361,8 +361,8 @@
if (!(B instanceof BodyLiteral))
{if (true) throw new ParseException(getSourceRef(B)+" Unknown body formula:"+B);}
bl = (BodyLiteral)B;
- if (bl.getTerm().equals(Literal.LTrue))
- bl = (BodyLiteral)bl.getNext();
+ if (bl.getBodyTerm().equals(Literal.LTrue))
+ bl = (BodyLiteral)bl.getBodyNext();
}
Plan p = new Plan(L,T,(LogicalFormula)C, bl);
p.setSrcLines(start,end);
@@ -494,7 +494,7 @@
;
}
if (F instanceof BodyLiteral && R instanceof BodyLiteral) {
- ((BodyLiteral)F).setNext( (BodyLiteral)R );
+ ((BodyLiteral)F).setBodyNext( (BodyLiteral)R );
}
{if (true) return F;}
throw new Error("Missing return statement in function");
@@ -552,13 +552,13 @@
if (B instanceof Literal) {
if ( ((Literal)B).isInternalAction() )
formType = BodyType.internalAction;
- {if (true) return new BodyLiteral(formType, (Literal)B);}
+ {if (true) return new BodyLiteralImpl(formType, (Literal)B);}
} else if (formType == BodyType.action && B instanceof RelExpr) {
- {if (true) return new BodyLiteral(BodyType.constraint, (RelExpr)B);} // constraint
+ {if (true) return new BodyLiteralImpl(BodyType.constraint, (RelExpr)B);} // constraint
} else {
if (formType == BodyType.test) {
if (B instanceof LogicalFormula)
- {if (true) return new BodyLiteral(BodyType.test, (Term)B);} // used in ?(a & b)
+ {if (true) return new BodyLiteralImpl(BodyType.test, (Term)B);} // used in ?(a & b)
else
{if (true) throw new ParseException(getSourceRef(B)+" The argument for ? is not a logical formula.");}
} else {
@@ -669,8 +669,8 @@
// if the result is a BodyLiteral action with size = 1, it is indeed a literal and not a body literal
if (o instanceof BodyLiteral) {
BodyLiteral bl = (BodyLiteral)o;
- if (bl.getType() == BodyType.action && bl.size() == 1) {
- o = bl.getTerm();
+ if (bl.getBodyType() == BodyType.action && bl.getPlanSize() == 1) {
+ o = bl.getBodyTerm();
}
}
{if (true) return changeToAtom(o);}
Modified: trunk/src/jason/asSyntax/patterns/goal/DG.java
===================================================================
--- trunk/src/jason/asSyntax/patterns/goal/DG.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSyntax/patterns/goal/DG.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -2,6 +2,7 @@
import jason.asSemantics.Agent;
import jason.asSyntax.BodyLiteral;
+import jason.asSyntax.BodyLiteralImpl;
import jason.asSyntax.Literal;
import jason.asSyntax.Plan;
import jason.asSyntax.Pred;
@@ -31,7 +32,7 @@
// add ?g in the end of all inner plans
for (Plan p: innerContent.getPL()) {
- BodyLiteral b = new BodyLiteral(BodyType.test, (Literal)goal.clone());
+ BodyLiteral b = new BodyLiteralImpl(BodyType.test, (Literal)goal.clone());
p.getBody().add(b);
newAg.getPL().add(p);
}
Modified: trunk/src/jason/asSyntax/patterns/goal/EBDG.java
===================================================================
--- trunk/src/jason/asSyntax/patterns/goal/EBDG.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/asSyntax/patterns/goal/EBDG.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -2,6 +2,7 @@
import jason.asSemantics.Agent;
import jason.asSyntax.BodyLiteral;
+import jason.asSyntax.BodyLiteralImpl;
import jason.asSyntax.Literal;
import jason.asSyntax.LogExpr;
import jason.asSyntax.LogicalFormula;
@@ -52,10 +53,10 @@
// change body
// add +p__f(i,g)
- BodyLiteral b1 = new BodyLiteral(BodyType.addBel, pi);
+ BodyLiteral b1 = new BodyLiteralImpl(BodyType.addBel, pi);
p.getBody().add(0, b1);
// add ?g
- BodyLiteral b2 = new BodyLiteral(BodyType.test, (Literal)goal.clone());
+ BodyLiteral b2 = new BodyLiteralImpl(BodyType.test, (Literal)goal.clone());
p.getBody().add(b2);
newAg.getPL().add(p);
}
Modified: trunk/src/jason/stdlib/wait.java
===================================================================
--- trunk/src/jason/stdlib/wait.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/jason/stdlib/wait.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -31,7 +31,7 @@
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Atom;
-import jason.asSyntax.BodyLiteral;
+import jason.asSyntax.BodyLiteralImpl;
import jason.asSyntax.NumberTerm;
import jason.asSyntax.StringTerm;
import jason.asSyntax.Term;
@@ -176,7 +176,7 @@
si.peek().removeCurrentStep();
if (stopByTimeout && te != null) {
// fail the .wait
- si.peek().getPlan().getBody().add(0, new BodyLiteral(BodyType.internalAction, new Atom(".fail")));
+ si.peek().getPlan().getBody().add(0, new BodyLiteralImpl(BodyType.internalAction, new Atom(".fail")));
}
if (si.isSuspended()) { // if the intention was suspended by .suspend
String k = suspend.SUSPENDED_INT+si.getId();
Modified: trunk/src/test/ASParserTest.java
===================================================================
--- trunk/src/test/ASParserTest.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/test/ASParserTest.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -40,8 +40,8 @@
assertTrue(ag.parseAS("src/asl/kqmlPlans.asl"));
assertTrue(ag.parseAS("examples/auction/ag1.asl"));
Plan p = ag.getPL().get("l__0");
- assertEquals(p.getBody().size(), 1);
- assertEquals(((BodyLiteral)p.getBody()).getType(), BodyLiteral.BodyType.internalAction);
+ assertEquals(p.getBody().getPlanSize(), 1);
+ assertEquals(((BodyLiteral)p.getBody()).getBodyType(), BodyLiteral.BodyType.internalAction);
assertTrue(ag.parseAS("examples/auction/ag2.asl"));
assertTrue(ag.parseAS("examples/auction/ag3.asl"));
}
Modified: trunk/src/test/PlanTest.java
===================================================================
--- trunk/src/test/PlanTest.java 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/test/PlanTest.java 2008-03-30 14:24:59 UTC (rev 1180)
@@ -3,6 +3,8 @@
import jason.JasonException;
import jason.asSemantics.Unifier;
import jason.asSyntax.BodyLiteral;
+import jason.asSyntax.BodyLiteralImpl;
+import jason.asSyntax.Literal;
import jason.asSyntax.Plan;
import jason.asSyntax.PlanLibrary;
import jason.asSyntax.Trigger;
@@ -56,44 +58,58 @@
public void testParser() {
Plan p = Plan.parse("+te : a & b <- a1; a2; .print(a); !g1; !!g2; ?test1; 10 > 3; +b1; -b2; -+b3.");
p = (Plan)p.clone();
- Iterator<BodyLiteral> i = p.getBody().iterator();
- assertEquals( BodyLiteral.BodyType.action, ((BodyLiteral)i.next()).getType());
- assertEquals( BodyLiteral.BodyType.action, ((BodyLiteral)i.next()).getType());
- assertEquals( BodyLiteral.BodyType.internalAction, ((BodyLiteral)i.next()).getType());
- assertEquals( BodyLiteral.BodyType.achieve, ((BodyLiteral)i.next()).getType());
- assertEquals( BodyLiteral.BodyType.achieveNF, ((BodyLiteral)i.next()).getType());
- assertEquals( BodyLiteral.BodyType.test, ((BodyLiteral)i.next()).getType());
- assertEquals( BodyLiteral.BodyType.constraint, ((BodyLiteral)i.next()).getType());
- assertEquals( BodyLiteral.BodyType.addBel, ((BodyLiteral)i.next()).getType());
- assertEquals( BodyLiteral.BodyType.delBel, ((BodyLiteral)i.next()).getType());
- assertEquals( BodyLiteral.BodyType.delAddBel, ((BodyLiteral)i.next()).getType());
+ Iterator<BodyLiteral> i = ((BodyLiteralImpl)p.getBody()).iterator();
+ assertEquals( BodyLiteral.BodyType.action, ((BodyLiteral)i.next()).getBodyType());
+ assertEquals( BodyLiteral.BodyType.action, ((BodyLiteral)i.next()).getBodyType());
+ assertEquals( BodyLiteral.BodyType.internalAction, ((BodyLiteral)i.next()).getBodyType());
+ assertEquals( BodyLiteral.BodyType.achieve, ((BodyLiteral)i.next()).getBodyType());
+ assertEquals( BodyLiteral.BodyType.achieveNF, ((BodyLiteral)i.next()).getBodyType());
+ assertEquals( BodyLiteral.BodyType.test, ((BodyLiteral)i.next()).getBodyType());
+ assertEquals( BodyLiteral.BodyType.constraint, ((BodyLiteral)i.next()).getBodyType());
+ assertEquals( BodyLiteral.BodyType.addBel, ((BodyLiteral)i.next()).getBodyType());
+ assertEquals( BodyLiteral.BodyType.delBel, ((BodyLiteral)i.next()).getBodyType());
+ assertTrue(i.hasNext());
+ assertEquals( BodyLiteral.BodyType.delAddBel, ((BodyLiteral)i.next()).getBodyType());
assertFalse(i.hasNext());
}
public void testDelete() {
Plan p = Plan.parse("+te : a & b <- !a1; ?a2; .print(a); !g1.");
- assertEquals(4, p.getBody().size());
- p.getBody().remove(0);
- assertEquals(3, p.getBody().size());
- assertEquals(BodyLiteral.BodyType.test, p.getBody().getType());
- p.getBody().remove(0); // 2
- p.getBody().remove(0); // 1
- assertEquals(1, p.getBody().size());
- p.getBody().remove(0); // 1
- assertTrue(p.getBody().isEmpty());
+ assertEquals(4, p.getBody().getPlanSize());
+ p.getBody().removeBody(0);
+ assertEquals(3, p.getBody().getPlanSize());
+ assertEquals(BodyLiteral.BodyType.test, p.getBody().getBodyType());
+ p.getBody().removeBody(0); // 2
+ p.getBody().removeBody(0); // 1
+ assertEquals(1, p.getBody().getPlanSize());
+ p.getBody().removeBody(0); // 1
+ assertTrue(p.getBody().isEmptyBody());
}
+ public void testEqualsBodyLiteral() {
+ BodyLiteral bl = new BodyLiteralImpl(BodyType.achieve, new Literal("g1"));
+ VarTerm v = new VarTerm("X");
+ Unifier u = new Unifier();
+ // X = !g1
+ assertTrue(u.unifies(v, bl));
+ v.apply(u);
+ assertEquals(BodyType.achieve, v.getBodyType());
+ assertEquals(bl.getBodyTerm(),v.getBodyTerm());
+ Plan p = Plan.parse("+te : a & b <- !g1.");
+ assertEquals(p.getBody(),v);
+ }
+
public void testUnifyBody() {
Plan p1 = Plan.parse("+te : a & b <- !a1; ?a2; .print(a); !g1.");
- BodyLiteral bl = new BodyLiteral(BodyType.action, new VarTerm("A1"));
- bl.add(new BodyLiteral(BodyType.action, new VarTerm("A2")));
- bl.add(new BodyLiteral(BodyType.action, new VarTerm("A3")));
- assertEquals(p1.getBody().getArity(), bl.getArity());
+ BodyLiteral bl = new BodyLiteralImpl(BodyType.action, new VarTerm("A1"));
+ bl.add(new BodyLiteralImpl(BodyType.action, new VarTerm("A2")));
+ bl.add(new BodyLiteralImpl(BodyType.action, new VarTerm("A3")));
+ //assertEquals(p1.getBody().getArity(), bl.getArity());
Unifier u = new Unifier();
assertTrue(u.unifies(p1.getBody(), bl));
assertEquals("a1", u.get("A1").toString());
assertEquals("a2", u.get("A2").toString());
- assertEquals(".print(a); !g1", u.get("A3").toString());
+ assertEquals(".print(a); !g1", u.get("A3").toString());
}
}
Modified: trunk/src/xml/agInspection.xsl
===================================================================
--- trunk/src/xml/agInspection.xsl 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/xml/agInspection.xsl 2008-03-30 14:24:59 UTC (rev 1180)
@@ -440,13 +440,15 @@
<tr>
<td width="20" />
<td width="20" style="vertical-align: top"><b><-</b></td>
- <td><xsl:apply-templates select="body" /></td>
+ <td>
+ <xsl:apply-templates select="body">
+ <xsl:with-param name="in-plan" select="'true'" />
+ </xsl:apply-templates>
+ </td>
</tr>
</table>
</xsl:if>
- <xsl:if test="count(body/body-literal) = 0">
- <xsl:text>.</xsl:text>
- </xsl:if>
+ <xsl:text>.</xsl:text>
</xsl:template>
@@ -467,6 +469,7 @@
</xsl:template>
<xsl:template match="body">
+ <xsl:param name="in-plan" select="'false'" />
<xsl:for-each select="body-literal">
<xsl:choose>
<xsl:when test="literal/@ia = 'true'">
@@ -489,7 +492,6 @@
</xsl:otherwise>
</xsl:choose>
<xsl:if test="not(position()=last())">; </xsl:if>
- <xsl:if test="position()=last()">.</xsl:if>
</xsl:for-each>
</xsl:template>
Modified: trunk/src/xml/asl2html.xsl
===================================================================
--- trunk/src/xml/asl2html.xsl 2008-03-29 23:55:50 UTC (rev 1179)
+++ trunk/src/xml/asl2html.xsl 2008-03-30 14:24:59 UTC (rev 1180)
@@ -65,6 +65,7 @@
</xsl:template>
<xsl:template match="body">
+ <xsl:param name="in-plan" select="'false'" />
<xsl:for-each select="body-literal">
<xsl:choose>
<xsl:when test="literal/@ia = 'true'">
@@ -86,8 +87,12 @@
<xsl:value-of select="@type"/><xsl:apply-templates />
</xsl:otherwise>
</xsl:choose>
- <xsl:if test="not(position()=last())">; <br/></xsl:if>
- <xsl:if test="position()=last()">.</xsl:if>
+ <xsl:if test="not(position()=last())">
+ <xsl:text>; </xsl:text>
+ <xsl:if test="$in-plan='true'">
+ <br/>
+ </xsl:if>
+ </xsl:if>
</xsl:for-each>
</xsl:template>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-29 23:55:57
|
Revision: 1179
http://jason.svn.sourceforge.net/jason/?rev=1179&view=rev
Author: jomifred
Date: 2008-03-29 16:55:50 -0700 (Sat, 29 Mar 2008)
Log Message:
-----------
first implementation of body plan as term
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java
trunk/applications/as-unit-test/src/jason/asunit/TestArch.java
trunk/applications/as-unit-test/src/jason/tests/TestAll.java
trunk/src/jason/asSyntax/BodyLiteral.java
trunk/src/jason/asSyntax/DefaultTerm.java
trunk/src/jason/asSyntax/InternalActionLiteral.java
trunk/src/jason/asSyntax/ListTermImpl.java
trunk/src/jason/asSyntax/Plan.java
trunk/src/jason/asSyntax/Term.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/jason/jeditplugin/JasonID.java
trunk/src/test/ASParserTest.java
trunk/src/test/PlanTest.java
Added Paths:
-----------
trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java
Modified: trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -166,7 +166,6 @@
public void assertAct(final Structure act, final int maxCycles) {
Condition c = new Condition() {
public boolean test(TestArch arch) {
- //System.out.println(arch.getCycle() + " " + arch.getActions()+ getTS().getC().getFeedbackActions());
return arch.getActions().contains(act);
}
};
Modified: trunk/applications/as-unit-test/src/jason/asunit/TestArch.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/asunit/TestArch.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/applications/as-unit-test/src/jason/asunit/TestArch.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -5,6 +5,8 @@
import jason.asSemantics.ActionExec;
import jason.asSyntax.Literal;
import jason.asSyntax.Structure;
+import jason.asSyntax.Term;
+import jason.asSyntax.VarTerm;
import jason.environment.Environment;
import jason.infra.centralised.CentralisedAgArch;
import jason.infra.centralised.CentralisedEnvironment;
@@ -83,9 +85,18 @@
@Override
public void act(ActionExec action, List<ActionExec> feedback) {
+ Term t = action.getActionTerm();
+ if (t instanceof VarTerm) {
+ t = ((VarTerm)t).getValue();
+ }
actions.add(action.getActionTerm());
- if (getEnvInfraTier() != null)
+ System.out.println("*"+action.getActionTerm().getClass().getName()+" "+t.getClass().getName());
+ if (getEnvInfraTier() != null) {
super.act(action, feedback); //env.scheduleAction(getAgName(), action.getActionTerm(), action);
+ } else {
+ action.setResult(true);
+ feedback.add(action);
+ }
}
public void print(String s) {
Modified: trunk/applications/as-unit-test/src/jason/tests/TestAll.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestAll.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/applications/as-unit-test/src/jason/tests/TestAll.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -9,6 +9,7 @@
BugVarsInInitBels.class,
TestAddLogExprInBB.class,
TestKQML.class,
- TestVarInContext.class
+ TestVarInContext.class,
+ TestPlanbodyAsTerm.class
})
public class TestAll { }
Added: trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java (rev 0)
+++ trunk/applications/as-unit-test/src/jason/tests/TestPlanbodyAsTerm.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -0,0 +1,34 @@
+package jason.tests;
+
+import jason.asunit.TestAgent;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestPlanbodyAsTerm {
+
+ TestAgent ag;
+
+ // initialisation of the agent test
+ @Before
+ public void setupAg() {
+ ag = new TestAgent();
+
+ // defines the agent's AgentSpeak code
+ ag.parseAScode(
+ "+!start <- +g(a; b; c); ?g(X); !g(X). "+
+ "+!g(A; R) <- A; !g(R). "+
+ "+!g(A) <- .print(A); A; .print(end)."
+ );
+ }
+
+ @Test
+ public void testProgram() {
+ ag.addGoal("start");
+ ag.assertBel("g(a;b;c)", 5);
+ ag.assertAct("a", 4);
+ ag.assertAct("b", 4);
+ ag.assertAct("c", 4);
+ }
+
+}
Modified: trunk/src/jason/asSyntax/BodyLiteral.java
===================================================================
--- trunk/src/jason/asSyntax/BodyLiteral.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/asSyntax/BodyLiteral.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -1,40 +1,14 @@
-//----------------------------------------------------------------------------
-// Copyright (C) 2003 Rafael H. Bordini, Jomi F. Hubner, et al.
-//
-// This library is free software; you can redistribute it and/or
-// modify it under the terms of the GNU Lesser General Public
-// License as published by the Free Software Foundation; either
-// version 2.1 of the License, or (at your option) any later version.
-//
-// This library is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-// Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public
-// License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-//
-// To contact the authors:
-// http://www.dur.ac.uk/r.bordini
-// http://www.inf.furb.br/~jomi
-//
-//----------------------------------------------------------------------------
-
package jason.asSyntax;
+import java.util.Iterator;
+
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-/**
- * Represents a plan body item (achieve, test, action, ...) and its successors,
- * it is thus like a list term.
- *
- * @author Jomi
- */
-public class BodyLiteral extends ListTermImpl implements Cloneable {
+public class BodyLiteral extends Structure implements Iterable<BodyLiteral> {
public enum BodyType {
+ none { public String toString() { return ""; }},
action { public String toString() { return ""; }},
internalAction { public String toString() { return ""; }},
achieve { public String toString() { return "!"; }},
@@ -46,28 +20,100 @@
constraint { public String toString() { return ""; }}
}
- private BodyType formType;
+ public static final String BODY_PLAN_FUNCTOR = ";";
+
+ private Term term = null;
+ private BodyLiteral next = null;
+ private BodyType formType = BodyType.none;
+ /** constructor for empty plan body */
public BodyLiteral() {
+ super(BODY_PLAN_FUNCTOR, 0);
}
public BodyLiteral(BodyType t, Term b) {
- setTerm(b);
+ super(BODY_PLAN_FUNCTOR, 0);
+ term = b;
+ formType = t;
setSrc(b);
- formType = t;
}
+ public void setNext(BodyLiteral next) {
+ this.next = next;
+ }
+ public BodyLiteral getNext() {
+ return next;
+ }
+
+ public boolean isEmpty() {
+ return term == null;
+ }
+
public BodyType getType() {
return formType;
}
-
+
+ public Term getTerm() {
+ return term;
+ }
+
public Literal getLiteralFormula() {
- Term t = getTerm();
- if (t instanceof Literal)
- return (Literal)t;
+ if (term instanceof Literal)
+ return (Literal)term;
else
return null;
}
+
+ public Iterator<BodyLiteral> iterator() {
+ return new Iterator<BodyLiteral>() {
+ BodyLiteral current = BodyLiteral.this;
+ public boolean hasNext() {
+ return current != null && current.term != null && current.next != null;
+ }
+ public BodyLiteral next() {
+ BodyLiteral r = current;
+ if (current != null)
+ current = current.next;
+ return r;
+ }
+ public void remove() { }
+ };
+ }
+
+ // Override some structure methods to work with unification/equals
+ @Override
+ public int getArity() {
+ if (term == null)
+ return 0;
+ else if (next == null)
+ return 1;
+ else
+ return 2;
+ }
+
+ @Override
+ public Term getTerm(int i) {
+ if (i == 0) return term;
+ if (i == 1) {
+ if (next != null && next.term.isVar() && next.next == null)
+ // if next is the last VAR, return that var
+ return next.term;
+ else
+ return next;
+ }
+ return null;
+ }
+
+ @Override
+ public void setTerm(int i, Term t) {
+ if (i == 0) term = t;
+ if (i == 1) System.out.println("Should not set next of body literal!");
+ }
+
+ @Override
+ public boolean isPlanBody() {
+ return true;
+ }
@Override
public boolean equals(Object o) {
@@ -81,36 +127,82 @@
}
@Override
- public int hashCode() {
- return formType.hashCode() + super.hashCode();
+ public int calcHashCode() {
+ return formType.hashCode() + super.calcHashCode();
}
- public Object clone() {
- BodyLiteral c;
- Term t = getTerm();
- if (t == null) { // empty body
- c = new BodyLiteral();
- } else {
- c = new BodyLiteral(formType, (Term)t.clone());
- c.setNext((Term)getNext().clone());
+ public boolean add(BodyLiteral bl) {
+ if (term == null)
+ swap(bl);
+ else if (next == null)
+ next = bl;
+ else
+ next.add(bl);
+ return true;
+ }
+
+ public boolean add(int index, BodyLiteral bl) {
+ if (index == 0) {
+ swap(bl);
+ this.next = bl;
+ } else {
+ next.add(index - 1, bl);
}
- return c;
+ return true;
}
- @Override
- protected void setValuesFrom(ListTerm lt) {
- super.setValuesFrom(lt);
- formType = ((BodyLiteral)lt).formType;
+ public Term remove(int index) {
+ if (index == 0) {
+ if (next == null) {
+ term = null; // becomes an empty
+ } else {
+ Term oldvalue = term;
+ swap(next); // get values of text
+ next = next.next;
+ return oldvalue;
+ }
+ return this;
+ } else {
+ return next.remove(index - 1);
+ }
}
+
+ public int size() {
+ if (term == null)
+ return 0;
+ else if (next == null)
+ return 1;
+ else
+ return next.size() + 1;
+ }
+
+ private void swap(BodyLiteral bl) {
+ BodyType bt = this.formType;
+ this.formType = bl.formType;
+ bl.formType = bt;
+
+ Term l = this.term;
+ this.term = bl.term;
+ bl.term = l;
+ }
+
+ public Object clone() {
+ if (term == null) // empty
+ return new BodyLiteral();
+
+ BodyLiteral c = new BodyLiteral(formType, (Term)term.clone());
+ if (next != null)
+ c.setNext((BodyLiteral)getNext().clone());
+ return c;
+ }
-
public String toString() {
- if (isEmpty())
+ if (term == null)
return "";
- else if (getNext().isEmpty())
- return formType.toString() + getTerm() + ".";
+ else if (next == null)
+ return formType.toString() + term;
else
- return formType.toString() + getTerm() + "; " + getNext();
+ return formType.toString() + term + "; " + next;
}
/** get as XML */
@@ -119,7 +211,7 @@
if (formType.toString().length() > 0) {
u.setAttribute("type", formType.toString());
}
- u.appendChild( ((Structure)getTerm()).getAsDOM(document));
+ u.appendChild( ((Structure)term).getAsDOM(document));
return u;
}
-}
+}
\ No newline at end of file
Modified: trunk/src/jason/asSyntax/DefaultTerm.java
===================================================================
--- trunk/src/jason/asSyntax/DefaultTerm.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/asSyntax/DefaultTerm.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -63,6 +63,7 @@
public boolean isPred() { return false; }
public boolean isStructure() { return false; }
public boolean isAtom() { return false; }
+ public boolean isPlanBody() { return false; }
public boolean isGround() { return true; }
public boolean hasVar(VarTerm t) { return false; }
Modified: trunk/src/jason/asSyntax/InternalActionLiteral.java
===================================================================
--- trunk/src/jason/asSyntax/InternalActionLiteral.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/asSyntax/InternalActionLiteral.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -117,7 +117,7 @@
public Object clone() {
InternalActionLiteral c = new InternalActionLiteral(this);
c.predicateIndicatorCache = this.predicateIndicatorCache;
- c.hashCodeCache = this.hashCodeCache;
+ c.hashCodeCache = this.hashCodeCache;
return c;
}
Modified: trunk/src/jason/asSyntax/ListTermImpl.java
===================================================================
--- trunk/src/jason/asSyntax/ListTermImpl.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/asSyntax/ListTermImpl.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -280,8 +280,7 @@
*/
public ListTerm concat(ListTerm lt) {
if (isEmpty()) {
- term = lt.getTerm();
- next = (Term)lt.getNext();
+ setValuesFrom(lt);
} else if (((ListTerm)next).isEmpty() ) {
next = (Term)lt;
} else {
@@ -420,7 +419,7 @@
public void add(int index, Term o) {
if (index == 0) {
- ListTermImpl n = new ListTermImpl(term,next);
+ ListTerm n = new ListTermImpl(term,next);
this.term = o;
this.next = n;
} else if (index > 0 && getNext() != null) {
Modified: trunk/src/jason/asSyntax/Plan.java
===================================================================
--- trunk/src/jason/asSyntax/Plan.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/asSyntax/Plan.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -30,7 +30,6 @@
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
@@ -235,7 +234,8 @@
public String toASString() {
return ((label == null) ? "" : "@" + label + " ") +
tevent + ((context == null) ? "" : " : " + context) +
- " <- " + body;
+ (body.isEmpty() ? "" : " <- " + body) +
+ ".";
}
/** get as XML */
@@ -256,10 +256,15 @@
if (body.size() > 0) {
Element eb = (Element) document.createElement("body");
+ for (BodyLiteral bl: body) {
+ eb.appendChild(bl.getAsDOM(document));
+ }
+ /*
Iterator<ListTerm> i = body.listTermIterator();
while (i.hasNext()) {
eb.appendChild(i.next().getAsDOM(document));
}
+ */
u.appendChild(eb);
}
Modified: trunk/src/jason/asSyntax/Term.java
===================================================================
--- trunk/src/jason/asSyntax/Term.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/asSyntax/Term.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -35,6 +35,8 @@
public boolean isAtom();
+ public boolean isPlanBody();
+
public boolean hasVar(VarTerm t);
public void countVars(Map<VarTerm, Integer> c);
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-29 23:55:50 UTC (rev 1179)
@@ -171,7 +171,7 @@
Literal g;
Plan p;
curAg = a;
- if (a != null) asSource = a.getASLSrc();
+ if (a != null && a.getASLSrc() != null) asSource = a.getASLSrc();
boolean endDir = false;
}
{
@@ -229,6 +229,7 @@
{
Pred dir = null;
Agent resultOfDirective = null;
+ Agent bakAg = curAg;
boolean isEOF = false;
}
{
@@ -253,6 +254,7 @@
// import bels, plans and initial goals from agent resultOfDirective
outerAg.importComponents(resultOfDirective);
}
+ curAg = bakAg;
return false;
}
}
@@ -286,13 +288,14 @@
/* Plan */
Plan plan() : { Token k; Pred L = null;
- Trigger T; Object C = null;
- BodyLiteral B = null;
+ Trigger T;
+ Object C = null; BodyLiteral bl = null;
+ Object B = null;
int start = -1, end;}
{
[ k = <TK_LABEL_AT> L=pred() { start = k.beginLine; } ]
T=trigger()
- [ k = ":" C=log_expr() { if (start == -1) start = k.beginLine; } ]
+ [ k = ":" C = log_expr() { if (start == -1) start = k.beginLine; } ]
[ k = "<-" B = plan_body() { if (start == -1) start = k.beginLine; } ]
k = "." { if (start == -1) start = k.beginLine; }
{ end = k.beginLine;
@@ -300,7 +303,14 @@
try { ial = checkInternalActionsInContext((LogicalFormula)C, curAg); } catch (Exception e) {}
if (ial != null)
throw new ParseException(getSourceRef(ial)+" The internal action '"+ial+"' can not be used in plan's context!");
- Plan p = new Plan(L,T,(LogicalFormula)C,B);
+ if (B != null) {
+ if (!(B instanceof BodyLiteral))
+ throw new ParseException(getSourceRef(B)+" Unknown body formula:"+B);
+ bl = (BodyLiteral)B;
+ if (bl.getTerm().equals(Literal.LTrue))
+ bl = (BodyLiteral)bl.getNext();
+ }
+ Plan p = new Plan(L,T,(LogicalFormula)C, bl);
p.setSrcLines(start,end);
p.setSrc(asSource);
return p;
@@ -352,23 +362,22 @@
/* Plan body */
-BodyLiteral plan_body() : { BodyLiteral F; BodyLiteral R = null; }
+Object plan_body() : { Object F; Object R = null; }
{
F = body_formula()
- [ ";" R = plan_body() ]
- { if (F.getTerm().equals(Literal.LTrue))
- return R;
- if (R == null)
- F.setNext(new BodyLiteral());
- else
- F.setNext(R);
+ [ ";" { if (!(F instanceof BodyLiteral)) throw new ParseException(getSourceRef(F)+" "+F+" is not a body literal!"); }
+ R = plan_body() { if (!(R instanceof BodyLiteral)) throw new ParseException(getSourceRef(R)+" "+R+" is not a body literal!"); }
+ ]
+ { if (F instanceof BodyLiteral && R instanceof BodyLiteral) {
+ ((BodyLiteral)F).setNext( (BodyLiteral)R );
+ }
return F;
}
}
-BodyLiteral body_formula() :
+Object body_formula() :
{ BodyType formType = BodyType.action; Object B; }
{
[ "!" { formType = BodyType.achieve; }
@@ -395,7 +404,7 @@
else
throw new ParseException(getSourceRef(B)+" The argument for ? is not a logical formula.");
} else {
- throw new ParseException(getSourceRef(B)+" Unknown body formula.");
+ return B;
}
}
}
@@ -440,9 +449,17 @@
Term term() : { Object o;}
{
( o=list()
- | o=log_expr() // log expr includes literals/atoms/structures
+ | o=plan_body() // plan_body includes literals/atoms/structures
)
- { return changeToAtom(o); }
+ { // if the result is a BodyLiteral action with size = 1, it is indeed a literal and not a body literal
+ if (o instanceof BodyLiteral) {
+ BodyLiteral bl = (BodyLiteral)o;
+ if (bl.getType() == BodyType.action && bl.size() == 1) {
+ o = bl.getTerm();
+ }
+ }
+ return changeToAtom(o);
+ }
}
@@ -462,7 +479,7 @@
"]" { return lt; }
}
-// term_in_list is the same as term, but log_expr must be enclosed by "("....")" to avoid problem with |
+// term_in_list is the same as term, but log_expr/plan_body must be enclosed by "("....")" to avoid problem with |
Term term_in_list() : { Object o; }
{
( o=list()
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -89,7 +89,7 @@
Literal g;
Plan p;
curAg = a;
- if (a != null) asSource = a.getASLSrc();
+ if (a != null && a.getASLSrc() != null) asSource = a.getASLSrc();
boolean endDir = false;
label_1:
while (true) {
@@ -237,6 +237,7 @@
final public boolean directive(Agent outerAg) throws ParseException, jason.JasonException {
Pred dir = null;
Agent resultOfDirective = null;
+ Agent bakAg = curAg;
boolean isEOF = false;
if (jj_2_1(4)) {
jj_consume_token(27);
@@ -270,6 +271,7 @@
// import bels, plans and initial goals from agent resultOfDirective
outerAg.importComponents(resultOfDirective);
}
+ curAg = bakAg;
{if (true) return false;}
throw new Error("Missing return statement in function");
}
@@ -313,8 +315,9 @@
/* Plan */
final public Plan plan() throws ParseException {
Token k; Pred L = null;
- Trigger T; Object C = null;
- BodyLiteral B = null;
+ Trigger T;
+ Object C = null; BodyLiteral bl = null;
+ Object B = null;
int start = -1, end;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case TK_LABEL_AT:
@@ -354,7 +357,14 @@
try { ial = checkInternalActionsInContext((LogicalFormula)C, curAg); } catch (Exception e) {}
if (ial != null)
{if (true) throw new ParseException(getSourceRef(ial)+" The internal action '"+ial+"' can not be used in plan's context!");}
- Plan p = new Plan(L,T,(LogicalFormula)C,B);
+ if (B != null) {
+ if (!(B instanceof BodyLiteral))
+ {if (true) throw new ParseException(getSourceRef(B)+" Unknown body formula:"+B);}
+ bl = (BodyLiteral)B;
+ if (bl.getTerm().equals(Literal.LTrue))
+ bl = (BodyLiteral)bl.getNext();
+ }
+ Plan p = new Plan(L,T,(LogicalFormula)C, bl);
p.setSrcLines(start,end);
p.setSrc(asSource);
{if (true) return p;}
@@ -469,29 +479,28 @@
}
/* Plan body */
- final public BodyLiteral plan_body() throws ParseException {
- BodyLiteral F; BodyLiteral R = null;
+ final public Object plan_body() throws ParseException {
+ Object F; Object R = null;
F = body_formula();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 37:
jj_consume_token(37);
+ if (!(F instanceof BodyLiteral)) {if (true) throw new ParseException(getSourceRef(F)+" "+F+" is not a body literal!");}
R = plan_body();
+ if (!(R instanceof BodyLiteral)) {if (true) throw new ParseException(getSourceRef(R)+" "+R+" is not a body literal!");}
break;
default:
jj_la1[19] = jj_gen;
;
}
- if (F.getTerm().equals(Literal.LTrue))
- {if (true) return R;}
- if (R == null)
- F.setNext(new BodyLiteral());
- else
- F.setNext(R);
+ if (F instanceof BodyLiteral && R instanceof BodyLiteral) {
+ ((BodyLiteral)F).setNext( (BodyLiteral)R );
+ }
{if (true) return F;}
throw new Error("Missing return statement in function");
}
- final public BodyLiteral body_formula() throws ParseException {
+ final public Object body_formula() throws ParseException {
BodyType formType = BodyType.action; Object B;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 31:
@@ -553,7 +562,7 @@
else
{if (true) throw new ParseException(getSourceRef(B)+" The argument for ? is not a logical formula.");}
} else {
- {if (true) throw new ParseException(getSourceRef(B)+" Unknown body formula.");}
+ {if (true) return B;}
}
}
throw new Error("Missing return statement in function");
@@ -644,15 +653,26 @@
case STRING:
case ATOM:
case UNNAMEDVAR:
+ case 31:
+ case 34:
case 35:
+ case 36:
+ case 38:
case 39:
- o = log_expr();
+ o = plan_body();
break;
default:
jj_la1[27] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
+ // if the result is a BodyLiteral action with size = 1, it is indeed a literal and not a body literal
+ if (o instanceof BodyLiteral) {
+ BodyLiteral bl = (BodyLiteral)o;
+ if (bl.getType() == BodyType.action && bl.size() == 1) {
+ o = bl.getTerm();
+ }
+ }
{if (true) return changeToAtom(o);}
throw new Error("Missing return statement in function");
}
@@ -726,7 +746,7 @@
throw new Error("Missing return statement in function");
}
-// term_in_list is the same as term, but log_expr must be enclosed by "("....")" to avoid problem with |
+// term_in_list is the same as term, but log_expr/plan_body must be enclosed by "("....")" to avoid problem with |
final public Term term_in_list() throws ParseException {
Object o;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
@@ -1163,11 +1183,6 @@
finally { jj_save(0, xla); }
}
- final private boolean jj_3R_12() {
- if (jj_scan_token(39)) return true;
- return false;
- }
-
final private boolean jj_3_1() {
if (jj_scan_token(27)) return true;
if (jj_scan_token(TK_BEGIN)) return true;
@@ -1176,6 +1191,16 @@
return false;
}
+ final private boolean jj_3R_14() {
+ if (jj_scan_token(42)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_12() {
+ if (jj_scan_token(39)) return true;
+ return false;
+ }
+
final private boolean jj_3R_11() {
Token xsp;
xsp = jj_scanpos;
@@ -1193,11 +1218,6 @@
return false;
}
- final private boolean jj_3R_14() {
- if (jj_scan_token(42)) return true;
- return false;
- }
-
final private boolean jj_3R_13() {
if (jj_3R_14()) return true;
return false;
@@ -1220,10 +1240,10 @@
jj_la1_1();
}
private static void jj_la1_0() {
- jj_la1_0 = new int[] {0x8000000,0x10cb00,0x8000000,0x80000000,0x8000000,0x10000,0x10cb00,0x8000000,0x8000000,0x20000000,0x10000,0x0,0x0,0x0,0x80000000,0x80000000,0x30cb80,0x800,0x10cb00,0x0,0x0,0x80000000,0x80000000,0x10c000,0x0,0x0,0x0,0x3acf80,0x0,0x200080,0x0,0x3acb80,0x3acb80,0x0,0x0,0x3acf80,0x3acb80,0x0,0x3acb80,0x0,0x0,0x0,0x3000,0x3000,0x0,0x32cb80,0x200080,0x0,};
+ jj_la1_0 = new int[] {0x8000000,0x10cb00,0x8000000,0x80000000,0x8000000,0x10000,0x10cb00,0x8000000,0x8000000,0x20000000,0x10000,0x0,0x0,0x0,0x80000000,0x80000000,0x30cb80,0x800,0x10cb00,0x0,0x0,0x80000000,0x80000000,0x10c000,0x0,0x0,0x0,0x803acf80,0x0,0x200080,0x0,0x3acb80,0x3acb80,0x0,0x0,0x3acf80,0x3acb80,0x0,0x3acb80,0x0,0x0,0x0,0x3000,0x3000,0x0,0x32cb80,0x200080,0x0,};
}
private static void jj_la1_1() {
- jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0xc,0x0,0x0,0x0,0x0,0x0,0x1,0x2,0xc,0x10,0x10,0x0,0x0,0x0,0x20,0x4,0x5c,0x5c,0x0,0x80,0x400,0x200,0x488,0x200,0x400,0x800,0x488,0x488,0x800,0x2000,0x88,0x88,0x3fc000,0x488,0x3fc000,0xc,0xc,0xc00000,0xc00000,0x1000000,0x88,0x0,0x400,};
+ jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0xc,0x0,0x0,0x0,0x0,0x0,0x1,0x2,0xc,0x10,0x10,0x0,0x0,0x0,0x20,0x4,0x5c,0x5c,0x0,0x80,0x400,0x200,0x4dc,0x200,0x400,0x800,0x488,0x488,0x800,0x2000,0x88,0x88,0x3fc000,0x488,0x3fc000,0xc,0xc,0xc00000,0xc00000,0x1000000,0x88,0x0,0x400,};
}
final private JJCalls[] jj_2_rtns = new JJCalls[1];
private boolean jj_rescan = false;
Modified: trunk/src/jason/jeditplugin/JasonID.java
===================================================================
--- trunk/src/jason/jeditplugin/JasonID.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/jason/jeditplugin/JasonID.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -31,6 +31,8 @@
import jason.mas2j.parser.TokenMgrError;
import jason.runtime.OutputStreamAdapter;
import jason.util.asl2html;
+import jason.util.asl2tex;
+import jason.util.asl2xml;
import java.awt.BorderLayout;
import java.awt.Dimension;
@@ -77,7 +79,6 @@
import errorlist.DefaultErrorSource;
import errorlist.ErrorSource;
-import jason.util.*;
public class JasonID extends JPanel implements EBComponent, RunProjectListener {
@@ -379,7 +380,7 @@
return null;
}
- private boolean parseProjectAS(MAS2JProject project) {
+ protected boolean parseProjectAS(MAS2JProject project) {
// compile
File asFile = null;
try {
@@ -456,16 +457,14 @@
max++;
try {
Thread.sleep(200);
- } catch (Exception e) {
- }
+ } catch (Exception e) { }
}
}
MAS2JProject project = parseProject(b);
- if (project == null || !parseProjectAS(project)) {
+ if (project == null) // || !parseProjectAS(project)) {
return;
- }
-
+
// launch the MAS
animation.start();
btStop.setEnabled(true);
@@ -636,9 +635,8 @@
return;
}
MAS2JProject project = parseProject(b);
- if (project == null || !parseProjectAS(project)) {
+ if (project == null) // || !parseProjectAS(project)) {
return;
- }
CentralisedMASLauncherAnt script = new CentralisedMASLauncherAnt("jar");
script.setProject(project);
if (script.writeScripts(false)) {
@@ -653,9 +651,8 @@
return;
}
MAS2JProject project = parseProject(b);
- if (project == null || !parseProjectAS(project)) {
+ if (project == null) // || !parseProjectAS(project)) {
return;
- }
CentralisedMASLauncherAnt script = new CentralisedMASLauncherAnt("jnlp");
script.setProject(project);
if (script.writeScripts(false)) {
Modified: trunk/src/test/ASParserTest.java
===================================================================
--- trunk/src/test/ASParserTest.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/test/ASParserTest.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -5,6 +5,7 @@
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.BodyLiteral;
+import jason.asSyntax.Literal;
import jason.asSyntax.LogExpr;
import jason.asSyntax.LogicalFormula;
import jason.asSyntax.NumberTerm;
@@ -163,6 +164,19 @@
}
+ public void testParsingPlanBody() {
+ Literal l = Literal.parseLiteral("p(a1;a2, a3, !g, ?b;.print(oi), 10)");
+ assertEquals(5,l.getArity());
+ assertTrue(l.getTerm(0) instanceof BodyLiteral);
+ assertTrue(l.getTerm(0).isPlanBody());
+
+ assertFalse(l.getTerm(1).isPlanBody());
+ assertTrue(l.getTerm(2).isPlanBody());
+ assertTrue(l.getTerm(3).isPlanBody());
+ assertFalse(l.getTerm(4).isPlanBody());
+
+ }
+
public void testParsingAllSources() {
parseDir(new File("./examples"));
parseDir(new File("./demos"));
@@ -192,7 +206,8 @@
parser.mas();
}
} catch (Exception e) {
- fail("Error parsing "+f);
+ e.printStackTrace();
+ fail("Error parsing "+f+": "+e);
}
}
}
Modified: trunk/src/test/PlanTest.java
===================================================================
--- trunk/src/test/PlanTest.java 2008-03-28 18:07:59 UTC (rev 1178)
+++ trunk/src/test/PlanTest.java 2008-03-29 23:55:50 UTC (rev 1179)
@@ -1,11 +1,13 @@
package test;
import jason.JasonException;
+import jason.asSemantics.Unifier;
import jason.asSyntax.BodyLiteral;
-import jason.asSyntax.ListTerm;
import jason.asSyntax.Plan;
import jason.asSyntax.PlanLibrary;
import jason.asSyntax.Trigger;
+import jason.asSyntax.VarTerm;
+import jason.asSyntax.BodyLiteral.BodyType;
import jason.asSyntax.parser.ParseException;
import java.util.Iterator;
@@ -54,7 +56,7 @@
public void testParser() {
Plan p = Plan.parse("+te : a & b <- a1; a2; .print(a); !g1; !!g2; ?test1; 10 > 3; +b1; -b2; -+b3.");
p = (Plan)p.clone();
- Iterator<ListTerm> i = p.getBody().listTermIterator();
+ Iterator<BodyLiteral> i = p.getBody().iterator();
assertEquals( BodyLiteral.BodyType.action, ((BodyLiteral)i.next()).getType());
assertEquals( BodyLiteral.BodyType.action, ((BodyLiteral)i.next()).getType());
assertEquals( BodyLiteral.BodyType.internalAction, ((BodyLiteral)i.next()).getType());
@@ -80,4 +82,18 @@
p.getBody().remove(0); // 1
assertTrue(p.getBody().isEmpty());
}
+
+ public void testUnifyBody() {
+ Plan p1 = Plan.parse("+te : a & b <- !a1; ?a2; .print(a); !g1.");
+ BodyLiteral bl = new BodyLiteral(BodyType.action, new VarTerm("A1"));
+ bl.add(new BodyLiteral(BodyType.action, new VarTerm("A2")));
+ bl.add(new BodyLiteral(BodyType.action, new VarTerm("A3")));
+ assertEquals(p1.getBody().getArity(), bl.getArity());
+ Unifier u = new Unifier();
+ assertTrue(u.unifies(p1.getBody(), bl));
+ assertEquals("a1", u.get("A1").toString());
+ assertEquals("a2", u.get("A2").toString());
+ assertEquals(".print(a); !g1", u.get("A3").toString());
+ }
+
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-28 18:08:02
|
Revision: 1178
http://jason.svn.sourceforge.net/jason/?rev=1178&view=rev
Author: jomifred
Date: 2008-03-28 11:07:59 -0700 (Fri, 28 Mar 2008)
Log Message:
-----------
body literal extends list term
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/tests/BugVarsInInitBels.java
trunk/applications/jason-moise/example/auction/ag3.asl
trunk/applications/jason-moise/src/jmoise/OrgAgent.java
trunk/src/jason/asSemantics/IntendedMeans.java
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/asSyntax/ArithExpr.java
trunk/src/jason/asSyntax/BinaryStructure.java
trunk/src/jason/asSyntax/BodyLiteral.java
trunk/src/jason/asSyntax/ListTermImpl.java
trunk/src/jason/asSyntax/Plan.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/jason/stdlib/send.java
trunk/src/test/ASParserTest.java
trunk/src/test/PlanTest.java
trunk/src/test/StdLibTest.java
Modified: trunk/applications/as-unit-test/src/jason/tests/BugVarsInInitBels.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/BugVarsInInitBels.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/applications/as-unit-test/src/jason/tests/BugVarsInInitBels.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -17,7 +17,7 @@
// defines the agent's AgentSpeak code
ag.parseAScode(
- "test_rule(A,A). "+
+ "test_rule(A,A). "+ // do not replace A by _ (the test is just the name A for the var)
"!test. "+
"+!test <- A = test_wrong_value; "+
" ?test_rule(T,right_value); "+
Modified: trunk/applications/jason-moise/example/auction/ag3.asl
===================================================================
--- trunk/applications/jason-moise/example/auction/ag3.asl 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/applications/jason-moise/example/auction/ag3.asl 2008-03-28 18:07:59 UTC (rev 1178)
@@ -46,7 +46,7 @@
.send(A,tell,alliance).
// remember the winners
-+goal_state(Sch, winner(W), satisfied)
++goal_state(Sch, winner(W), achieved)
: goal_state(Sch, auction(N), _)
<- +winner(N,W).
-
+
Modified: trunk/applications/jason-moise/src/jmoise/OrgAgent.java
===================================================================
--- trunk/applications/jason-moise/src/jmoise/OrgAgent.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/applications/jason-moise/src/jmoise/OrgAgent.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -309,7 +309,8 @@
if (!u.get(S).equals(gState) || !gap.equals(gilInBB.getTerm(1))) {
if (!getTS().getAg().delBel(gilInBB))
logger.warning("Belief "+gilInBB+" should be deleted, but was not!");
- else if (logger.isLoggable(Level.FINE)) logger.fine("Remove goal belief: " + gil);
+ else
+ if (logger.isLoggable(Level.FINE)) logger.fine("Remove goal belief: " + gil);
}
}
Modified: trunk/src/jason/asSemantics/IntendedMeans.java
===================================================================
--- trunk/src/jason/asSemantics/IntendedMeans.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSemantics/IntendedMeans.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -70,16 +70,18 @@
// used for clone
}
- /** removes the current action of the IM */
- public BodyLiteral removeCurrentStep() {
- if (!plan.getBody().isEmpty())
- return plan.getBody().remove(0);
- else
+ /** removes the current action of the IM and returns the term of the body */
+ public Term removeCurrentStep() {
+ BodyLiteral current = plan.getBody();
+ if (current.isEmpty()) {
return null;
+ } else {
+ return current.remove(0);
+ }
}
public BodyLiteral getCurrentStep() {
- return plan.getBody().get(0);
+ return plan.getBody();
}
@@ -127,9 +129,9 @@
Structure im = new Structure("im");
im.addTerm(new StringTermImpl(plan.getLabel().toString()));
ListTerm lt = new ListTermImpl();
- for (BodyLiteral bd: plan.getBody()) {
- BodyLiteral c = (BodyLiteral)bd.clone();
- c.getLogicalFormula().apply(unif);
+ for (Term bd: plan.getBody()) {
+ Term c = (Term)bd.clone();
+ c.apply(unif);
lt.add(new StringTermImpl(c.toString()));
}
im.addTerm(lt);
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -35,6 +35,7 @@
import jason.asSyntax.LogicalFormula;
import jason.asSyntax.Plan;
import jason.asSyntax.PlanLibrary;
+import jason.asSyntax.Structure;
import jason.asSyntax.Term;
import jason.asSyntax.Trigger;
import jason.asSyntax.Trigger.TEOperator;
@@ -158,15 +159,15 @@
// .send(ag1,askOne, value, X)
// if the answer was tell 3, unifies X=3
// if the answer was untell 3, unifies X=false
- BodyLiteral send = intention.peek().removeCurrentStep();
+ Structure send = (Structure)intention.peek().removeCurrentStep();
if (m.isUnTell()) {
- if (send.getLiteralFormula().getTerm(1).toString().equals("askOne")) {
+ if (send.getTerm(1).toString().equals("askOne")) {
content = Literal.LFalse;
} else { // the .send is askAll
content = new ListTermImpl(); // the answer is an empty list
}
}
- if (intention.peek().getUnif().unifies(send.getLiteralFormula().getTerm(3), content)) {
+ if (intention.peek().getUnif().unifies(send.getTerm(3), content)) {
getC().addIntention(intention);
} else {
conf.C.SI = intention;
@@ -402,12 +403,13 @@
}
Unifier u = im.unif;
BodyLiteral h = im.getCurrentStep();
-
- h.getLogicalFormula().apply(u);
+ Term bTerm = h.getTerm();
+ bTerm.apply(u);
+
Literal body = null;
- if (h.getLogicalFormula() instanceof Literal)
- body = h.getLiteralFormula();
+ if (bTerm instanceof Literal)
+ body = (Literal)bTerm;
switch (h.getType()) {
@@ -446,7 +448,7 @@
break;
case constraint:
- Iterator<Unifier> iu = h.getLogicalFormula().logicalConsequence(ag, u);
+ Iterator<Unifier> iu = ((LogicalFormula)bTerm).logicalConsequence(ag, u);
if (iu.hasNext()) {
im.unif = iu.next();
updateIntention();
@@ -475,7 +477,7 @@
// Rule Test
case test:
- LogicalFormula f = h.getLogicalFormula();
+ LogicalFormula f = (LogicalFormula)bTerm;
if (conf.ag.believes(f, u)) {
updateIntention();
} else {
@@ -633,12 +635,12 @@
im = i.peek(); // +!s or +?s
if (!im.isFinished()) {
// removes !b or ?s
- BodyLiteral g = im.removeCurrentStep();
+ Term g = im.removeCurrentStep();
// make the TE of finished plan ground and unify that
// with goal in the body
Literal tel = topIM.getPlan().getTrigger().getLiteral();
tel.apply(topIM.unif);
- im.unif.unifies(tel, g.getLiteralFormula());
+ im.unif.unifies(tel, g);
}
}
@@ -699,70 +701,7 @@
}
return ap;
}
-
- /*
- class ApplPlanTimeOut extends Thread {
- List<Option> ap = null;
- List<Option> rp = null;
- boolean finish = false;
-
- List<Option> get(List<Option> rp) {
- this.rp = rp;
- start();
- waitEvaluation();
- return ap;
- }
-
- synchronized void waitEvaluation() {
- try {
- if (!finish) {
- wait(3000); // wait 5 seconds for the evaluation!
- if (!finish) {
- logger.warning("*** Evaluation of appl plan do not finish in 3 seconds!"+C+"\bBB="+getAg().getBB());
- }
- }
- finish = true;
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- synchronized void finishEvaluation() {
- finish = true;
- notify();
- }
-
- public void run() {
- for (Option opt: rp) {
- LogicalFormula context = opt.plan.getContext();
- if (context == null) { // context is true
- if (ap == null) ap = new LinkedList<Option>();
- ap.add(opt);
- } else {
- boolean allUnifs = opt.getPlan().isAllUnifs();
- Iterator<Unifier> r = context.logicalConsequence(ag, opt.unif);
- if (r != null) {
- while (r.hasNext()) {
- opt.unif = r.next();
-
- if (ap == null) ap = new LinkedList<Option>();
- ap.add(opt);
-
- if (!allUnifs) break; // returns only the first unification
- if (r.hasNext()) {
- // create a new option for the next loop step
- opt = new Option((Plan)opt.plan.clone(), null);
- }
- }
- }
- }
- }
- finishEvaluation();
- }
- }
- */
-
public void updateEvents(List<Literal>[] result, Intention focus) {
if (result == null) return;
// create the events
Modified: trunk/src/jason/asSyntax/ArithExpr.java
===================================================================
--- trunk/src/jason/asSyntax/ArithExpr.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSyntax/ArithExpr.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -133,7 +133,7 @@
super(oper.toString(),1);
addTerm(t1);
op = oper;
- if (t1 instanceof SourceInfo) setSrc((SourceInfo)t1);
+ setSrc(t1);
}
private ArithExpr(ArithExpr ae) { // for clone
Modified: trunk/src/jason/asSyntax/BinaryStructure.java
===================================================================
--- trunk/src/jason/asSyntax/BinaryStructure.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSyntax/BinaryStructure.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -45,7 +45,7 @@
public BinaryStructure(String id, Term arg) {
super(id,1);
addTerm( arg );
- if (arg instanceof SourceInfo) setSrc((SourceInfo)arg);
+ setSrc(arg);
}
public boolean isUnary() {
Modified: trunk/src/jason/asSyntax/BodyLiteral.java
===================================================================
--- trunk/src/jason/asSyntax/BodyLiteral.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSyntax/BodyLiteral.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -26,8 +26,13 @@
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-/** Represents an item of a plan body (achieve, test, action, ...) */
-public class BodyLiteral extends SourceInfo implements Cloneable {
+/**
+ * Represents a plan body item (achieve, test, action, ...) and its successors,
+ * it is thus like a list term.
+ *
+ * @author Jomi
+ */
+public class BodyLiteral extends ListTermImpl implements Cloneable {
public enum BodyType {
action { public String toString() { return ""; }},
@@ -41,24 +46,15 @@
constraint { public String toString() { return ""; }}
}
- private LogicalFormula formula;
private BodyType formType;
- /** used of actions, internal actions, test goals, achieve goals, adds, removes */
- public BodyLiteral(BodyType t, Literal l) {
- formula = (Literal) l.clone();
- formType = t;
- if (l.isInternalAction())
- formType = BodyType.internalAction;
- setSrc(l);
+ public BodyLiteral() {
}
-
- /** used for test goals and constraints (the argument is a logical formula) */
- public BodyLiteral(BodyType t, LogicalFormula lf) {
- formula = (LogicalFormula) lf.clone();
+
+ public BodyLiteral(BodyType t, Term b) {
+ setTerm(b);
+ setSrc(b);
formType = t;
- if (lf instanceof SourceInfo)
- setSrc((SourceInfo)lf);
}
public BodyType getType() {
@@ -66,40 +62,55 @@
}
public Literal getLiteralFormula() {
- if (formula instanceof Literal)
- return (Literal)formula;
+ Term t = getTerm();
+ if (t instanceof Literal)
+ return (Literal)t;
else
return null;
}
- public LogicalFormula getLogicalFormula() {
- return formula;
- }
-
@Override
public boolean equals(Object o) {
- if (o != null && o instanceof BodyLiteral) {
- BodyLiteral b = (BodyLiteral) o;
- return formType == b.formType && formula.equals(b.formula);
+ if (o == null) return false;
+ if (o == this) return true;
+ if (o instanceof BodyLiteral) {
+ BodyLiteral b = (BodyLiteral)o;
+ return formType == b.formType && super.equals(o);
}
return false;
}
@Override
public int hashCode() {
- return formType.hashCode() + formula.hashCode();
+ return formType.hashCode() + super.hashCode();
}
public Object clone() {
- if (formType == BodyType.test || formType == BodyType.constraint) {
- return new BodyLiteral(formType, formula);
+ BodyLiteral c;
+ Term t = getTerm();
+ if (t == null) { // empty body
+ c = new BodyLiteral();
} else {
- return new BodyLiteral(formType, (Literal)formula);
+ c = new BodyLiteral(formType, (Term)t.clone());
+ c.setNext((Term)getNext().clone());
}
+ return c;
}
+ @Override
+ protected void setValuesFrom(ListTerm lt) {
+ super.setValuesFrom(lt);
+ formType = ((BodyLiteral)lt).formType;
+ }
+
+
public String toString() {
- return formType + formula.toString();
+ if (isEmpty())
+ return "";
+ else if (getNext().isEmpty())
+ return formType.toString() + getTerm() + ".";
+ else
+ return formType.toString() + getTerm() + "; " + getNext();
}
/** get as XML */
@@ -108,7 +119,7 @@
if (formType.toString().length() > 0) {
u.setAttribute("type", formType.toString());
}
- u.appendChild(formula.getAsDOM(document));
+ u.appendChild( ((Structure)getTerm()).getAsDOM(document));
return u;
}
}
Modified: trunk/src/jason/asSyntax/ListTermImpl.java
===================================================================
--- trunk/src/jason/asSyntax/ListTermImpl.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSyntax/ListTermImpl.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -127,10 +127,10 @@
}
public ListTerm getNext() {
- try {
+ if (next instanceof ListTerm)
return (ListTerm)next;
- } catch (Exception e){}
- return null;
+ else
+ return null;
}
@@ -544,12 +544,16 @@
};
}
+ protected void setValuesFrom(ListTerm lt) {
+ this.term = lt.getTerm();
+ this.next = lt.getNext();
+ }
+
public Term remove(int index) {
if (index == 0) {
Term bt = this.term;
if (getNext() != null) {
- this.term = getNext().getTerm();
- this.next = (Term)getNext().getNext();
+ setValuesFrom(getNext());
} else {
clear();
}
@@ -563,8 +567,7 @@
public boolean remove(Object o) {
if (term != null && term.equals(o)) {
if (getNext() != null) {
- this.term = getNext().getTerm();
- this.next = (Term)getNext().getNext();
+ setValuesFrom(getNext());
} else {
clear();
}
Modified: trunk/src/jason/asSyntax/Plan.java
===================================================================
--- trunk/src/jason/asSyntax/Plan.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSyntax/Plan.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -29,10 +29,8 @@
import java.io.Serializable;
import java.io.StringReader;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
-import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
@@ -54,8 +52,9 @@
private Pred label = null;
private Trigger tevent = null;
private LogicalFormula context;
- private List<BodyLiteral> body;
+ private BodyLiteral body;
+
private boolean isAtomic = false;
private boolean isAllUnifs = false;
private boolean hasBreakpoint = false;
@@ -65,12 +64,12 @@
}
// used by parser
- public Plan(Pred label, Trigger te, LogicalFormula ct, List<BodyLiteral> bd) {
+ public Plan(Pred label, Trigger te, LogicalFormula ct, BodyLiteral bd) {
tevent = te;
setLabel(label);
setContext(ct);
if (bd == null)
- body = Collections.emptyList();
+ body = new BodyLiteral();
else
body = bd;
}
@@ -123,7 +122,7 @@
return context;
}
- public List<BodyLiteral> getBody() {
+ public BodyLiteral getBody() {
return body;
}
@@ -170,9 +169,7 @@
tevent.getLiteral().countVars(all);
if (context != null)
context.countVars(all);
- if (body != null)
- for (BodyLiteral bl: body)
- bl.getLogicalFormula().countVars(all);
+ body.countVars(all);
List<VarTerm> r = new ArrayList<VarTerm>();
for (VarTerm k: all.keySet()) {
@@ -187,7 +184,7 @@
int code = 37;
if (context != null) code += context.hashCode();
if (tevent != null) code += tevent.hashCode();
- if (body != null) code += body.hashCode();
+ code += body.hashCode();
return code;
}
@@ -205,10 +202,7 @@
if (context != null)
p.context = (LogicalFormula)context.clone();
- p.body = new LinkedList<BodyLiteral>(); // the plan will be "consumed" by remove(0), so linkedlist
- for (BodyLiteral l : body) {
- p.body.add((BodyLiteral) l.clone());
- }
+ p.body = (BodyLiteral)body.clone();
p.setSrc(this);
@@ -226,39 +220,22 @@
p.tevent = (Trigger)tevent.clone();
p.context = context;
+ p.body = (BodyLiteral)body.clone();
- p.body = new LinkedList<BodyLiteral>(); // the plan will be "consumed" by remove(0), so linkedlist
- for (BodyLiteral l : body) {
- p.body.add((BodyLiteral) l.clone());
- }
-
p.setSrc(this);
return p;
}
- private String listToString(List<BodyLiteral> l, String separator) {
- StringBuffer s = new StringBuffer();
- Iterator<BodyLiteral> i = l.iterator();
- while (i.hasNext()) {
- s.append(i.next().toString());
- if (i.hasNext()) {
- s.append(separator);
- }
- }
- return s.toString();
- }
-
public String toString() {
return toASString();
}
/** returns this plan in a string complaint with AS syntax */
public String toASString() {
- return (((label == null) ? "" : "@" + label + " ") +
- tevent + ((context == null) ? "" : " : " + context) +
- ((body.size() == 0) ? "" : " <- " + listToString(body, "; ")) +
- ".");
+ return ((label == null) ? "" : "@" + label + " ") +
+ tevent + ((context == null) ? "" : " : " + context) +
+ " <- " + body;
}
/** get as XML */
@@ -279,8 +256,9 @@
if (body.size() > 0) {
Element eb = (Element) document.createElement("body");
- for (BodyLiteral bl : body) {
- eb.appendChild(bl.getAsDOM(document));
+ Iterator<ListTerm> i = body.listTermIterator();
+ while (i.hasNext()) {
+ eb.appendChild(i.next().getAsDOM(document));
}
u.appendChild(eb);
}
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-28 18:07:59 UTC (rev 1178)
@@ -287,13 +287,13 @@
/* Plan */
Plan plan() : { Token k; Pred L = null;
Trigger T; Object C = null;
- ArrayList B = new ArrayList();
+ BodyLiteral B = null;
int start = -1, end;}
{
[ k = <TK_LABEL_AT> L=pred() { start = k.beginLine; } ]
T=trigger()
[ k = ":" C=log_expr() { if (start == -1) start = k.beginLine; } ]
- [ k = "<-" plan_body(B) { if (start == -1) start = k.beginLine; } ]
+ [ k = "<-" B = plan_body() { if (start == -1) start = k.beginLine; } ]
k = "." { if (start == -1) start = k.beginLine; }
{ end = k.beginLine;
InternalActionLiteral ial = null;
@@ -303,8 +303,9 @@
Plan p = new Plan(L,T,(LogicalFormula)C,B);
p.setSrcLines(start,end);
p.setSrc(asSource);
- return p;}
+ return p;
}
+}
/* Trigger */
Trigger trigger() :
@@ -351,14 +352,19 @@
/* Plan body */
-void plan_body(List bd) : { BodyLiteral F; }
+BodyLiteral plan_body() : { BodyLiteral F; BodyLiteral R = null; }
{
- F=body_formula() { if (! F.getLogicalFormula().equals(Literal.LTrue)) {
- bd.add(F);
- }
+ F = body_formula()
+
+ [ ";" R = plan_body() ]
+ { if (F.getTerm().equals(Literal.LTrue))
+ return R;
+ if (R == null)
+ F.setNext(new BodyLiteral());
+ else
+ F.setNext(R);
+ return F;
}
-
- [ ";" plan_body(bd) ]
}
@@ -377,13 +383,15 @@
B = log_expr()
{ if (B instanceof Literal) {
+ if ( ((Literal)B).isInternalAction() )
+ formType = BodyType.internalAction;
return new BodyLiteral(formType, (Literal)B);
} else if (formType == BodyType.action && B instanceof RelExpr) {
return new BodyLiteral(BodyType.constraint, (RelExpr)B); // constraint
} else {
if (formType == BodyType.test) {
if (B instanceof LogicalFormula)
- return new BodyLiteral(BodyType.test, (LogicalFormula)B); // used in ?(a & b)
+ return new BodyLiteral(BodyType.test, (Term)B); // used in ?(a & b)
else
throw new ParseException(getSourceRef(B)+" The argument for ? is not a logical formula.");
} else {
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -314,7 +314,7 @@
final public Plan plan() throws ParseException {
Token k; Pred L = null;
Trigger T; Object C = null;
- ArrayList B = new ArrayList();
+ BodyLiteral B = null;
int start = -1, end;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case TK_LABEL_AT:
@@ -340,7 +340,7 @@
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 33:
k = jj_consume_token(33);
- plan_body(B);
+ B = plan_body();
if (start == -1) start = k.beginLine;
break;
default:
@@ -469,21 +469,26 @@
}
/* Plan body */
- final public void plan_body(List bd) throws ParseException {
- BodyLiteral F;
+ final public BodyLiteral plan_body() throws ParseException {
+ BodyLiteral F; BodyLiteral R = null;
F = body_formula();
- if (! F.getLogicalFormula().equals(Literal.LTrue)) {
- bd.add(F);
- }
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 37:
jj_consume_token(37);
- plan_body(bd);
+ R = plan_body();
break;
default:
jj_la1[19] = jj_gen;
;
}
+ if (F.getTerm().equals(Literal.LTrue))
+ {if (true) return R;}
+ if (R == null)
+ F.setNext(new BodyLiteral());
+ else
+ F.setNext(R);
+ {if (true) return F;}
+ throw new Error("Missing return statement in function");
}
final public BodyLiteral body_formula() throws ParseException {
@@ -536,13 +541,15 @@
}
B = log_expr();
if (B instanceof Literal) {
+ if ( ((Literal)B).isInternalAction() )
+ formType = BodyType.internalAction;
{if (true) return new BodyLiteral(formType, (Literal)B);}
} else if (formType == BodyType.action && B instanceof RelExpr) {
{if (true) return new BodyLiteral(BodyType.constraint, (RelExpr)B);} // constraint
} else {
if (formType == BodyType.test) {
if (B instanceof LogicalFormula)
- {if (true) return new BodyLiteral(BodyType.test, (LogicalFormula)B);} // used in ?(a & b)
+ {if (true) return new BodyLiteral(BodyType.test, (Term)B);} // used in ?(a & b)
else
{if (true) throw new ParseException(getSourceRef(B)+" The argument for ? is not a logical formula.");}
} else {
@@ -1156,6 +1163,11 @@
finally { jj_save(0, xla); }
}
+ final private boolean jj_3R_12() {
+ if (jj_scan_token(39)) return true;
+ return false;
+ }
+
final private boolean jj_3_1() {
if (jj_scan_token(27)) return true;
if (jj_scan_token(TK_BEGIN)) return true;
@@ -1191,11 +1203,6 @@
return false;
}
- final private boolean jj_3R_12() {
- if (jj_scan_token(39)) return true;
- return false;
- }
-
public as2jTokenManager token_source;
SimpleCharStream jj_input_stream;
public Token token, jj_nt;
Modified: trunk/src/jason/stdlib/send.java
===================================================================
--- trunk/src/jason/stdlib/send.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/jason/stdlib/send.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -31,7 +31,6 @@
import jason.asSemantics.Message;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
-import jason.asSyntax.BodyLiteral;
import jason.asSyntax.ListTerm;
import jason.asSyntax.NumberTerm;
import jason.asSyntax.Pred;
@@ -238,8 +237,8 @@
Intention intention = c.getPendingIntentions().remove(idInPending);
if (intention != null) {
// unify "timeout" with the fourth parameter of .send
- BodyLiteral send = intention.peek().removeCurrentStep();
- intention.peek().getUnif().unifies(send.getLiteralFormula().getTerm(3), timeoutTerm);
+ Structure send = (Structure)intention.peek().removeCurrentStep();
+ intention.peek().getUnif().unifies(send.getTerm(3), timeoutTerm);
// add the intention back in C.I
c.addIntention(intention);
}
Modified: trunk/src/test/ASParserTest.java
===================================================================
--- trunk/src/test/ASParserTest.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/test/ASParserTest.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -40,7 +40,7 @@
assertTrue(ag.parseAS("examples/auction/ag1.asl"));
Plan p = ag.getPL().get("l__0");
assertEquals(p.getBody().size(), 1);
- assertEquals(p.getBody().get(0).getType(), BodyLiteral.BodyType.internalAction);
+ assertEquals(((BodyLiteral)p.getBody()).getType(), BodyLiteral.BodyType.internalAction);
assertTrue(ag.parseAS("examples/auction/ag2.asl"));
assertTrue(ag.parseAS("examples/auction/ag3.asl"));
}
Modified: trunk/src/test/PlanTest.java
===================================================================
--- trunk/src/test/PlanTest.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/test/PlanTest.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -1,11 +1,14 @@
package test;
import jason.JasonException;
+import jason.asSyntax.BodyLiteral;
+import jason.asSyntax.ListTerm;
import jason.asSyntax.Plan;
import jason.asSyntax.PlanLibrary;
import jason.asSyntax.Trigger;
import jason.asSyntax.parser.ParseException;
+import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
@@ -47,4 +50,34 @@
pls = pl.getAllRelevant(Trigger.parseTrigger("+bla"));
assertEquals(0, pls.size());
}
+
+ public void testParser() {
+ Plan p = Plan.parse("+te : a & b <- a1; a2; .print(a); !g1; !!g2; ?test1; 10 > 3; +b1; -b2; -+b3.");
+ p = (Plan)p.clone();
+ Iterator<ListTerm> i = p.getBody().listTermIterator();
+ assertEquals( BodyLiteral.BodyType.action, ((BodyLiteral)i.next()).getType());
+ assertEquals( BodyLiteral.BodyType.action, ((BodyLiteral)i.next()).getType());
+ assertEquals( BodyLiteral.BodyType.internalAction, ((BodyLiteral)i.next()).getType());
+ assertEquals( BodyLiteral.BodyType.achieve, ((BodyLiteral)i.next()).getType());
+ assertEquals( BodyLiteral.BodyType.achieveNF, ((BodyLiteral)i.next()).getType());
+ assertEquals( BodyLiteral.BodyType.test, ((BodyLiteral)i.next()).getType());
+ assertEquals( BodyLiteral.BodyType.constraint, ((BodyLiteral)i.next()).getType());
+ assertEquals( BodyLiteral.BodyType.addBel, ((BodyLiteral)i.next()).getType());
+ assertEquals( BodyLiteral.BodyType.delBel, ((BodyLiteral)i.next()).getType());
+ assertEquals( BodyLiteral.BodyType.delAddBel, ((BodyLiteral)i.next()).getType());
+ assertFalse(i.hasNext());
+ }
+
+ public void testDelete() {
+ Plan p = Plan.parse("+te : a & b <- !a1; ?a2; .print(a); !g1.");
+ assertEquals(4, p.getBody().size());
+ p.getBody().remove(0);
+ assertEquals(3, p.getBody().size());
+ assertEquals(BodyLiteral.BodyType.test, p.getBody().getType());
+ p.getBody().remove(0); // 2
+ p.getBody().remove(0); // 1
+ assertEquals(1, p.getBody().size());
+ p.getBody().remove(0); // 1
+ assertTrue(p.getBody().isEmpty());
+ }
}
Modified: trunk/src/test/StdLibTest.java
===================================================================
--- trunk/src/test/StdLibTest.java 2008-03-27 21:33:48 UTC (rev 1177)
+++ trunk/src/test/StdLibTest.java 2008-03-28 18:07:59 UTC (rev 1178)
@@ -132,7 +132,7 @@
StringTerm pt1 = new StringTermImpl("@t1 +a : g(10) <- .print(\"ok 10\").");
Plan pa = ag.getPL().add(pt1, null);
assertTrue(pa != null);
- assertEquals(pa.toASString(),"@t1[source(self)] +a : g(10) <- .print(\"ok 10\").");
+ assertEquals("@t1[source(self)] +a : g(10) <- .print(\"ok 10\").", pa.toASString());
ag.getPL().add(new StringTermImpl("@t2 +a : g(20) <- .print(\"ok 20\")."), new Structure("nosource"));
((Plan) ag.getPL().getPlans().get(1)).getLabel().addSource(new Structure("ag1"));
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-27 21:33:50
|
Revision: 1177
http://jason.svn.sourceforge.net/jason/?rev=1177&view=rev
Author: jomifred
Date: 2008-03-27 14:33:48 -0700 (Thu, 27 Mar 2008)
Log Message:
-----------
the grammar rule for body_literal was simplified
Modified Paths:
--------------
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/test/ASParserTest.java
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-27 20:38:44 UTC (rev 1176)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-27 21:33:48 UTC (rev 1177)
@@ -351,7 +351,7 @@
/* Plan body */
-void plan_body(ArrayList bd) : { BodyLiteral F; }
+void plan_body(List bd) : { BodyLiteral F; }
{
F=body_formula() { if (! F.getLogicalFormula().equals(Literal.LTrue)) {
bd.add(F);
@@ -362,16 +362,10 @@
}
-BodyLiteral body_formula() : { Literal A; Token k;
- BodyType formType = BodyType.action;
- Object L;
- Object rel; VarTerm v;
- }
+BodyLiteral body_formula() :
+ { BodyType formType = BodyType.action; Object B; }
{
-
- ( LOOKAHEAD(4)
- // goals and belief updates
- ( "!" { formType = BodyType.achieve; }
+ [ "!" { formType = BodyType.achieve; }
| "!!" { formType = BodyType.achieveNF; }
| "?" { formType = BodyType.test; }
| "+" { formType = BodyType.addBel; }
@@ -379,37 +373,29 @@
["+" { formType = BodyType.delAddBel; }
]
)
- )
- ( A = literal() { return new BodyLiteral(formType,A); }
- | v = var() { return new BodyLiteral(formType,v); } // used in communication "+C"
- | "(" L = log_expr() ")"
- { if (formType == BodyType.test) {
- if (L instanceof LogicalFormula)
- return new BodyLiteral(BodyType.test, (LogicalFormula)L); // used in ?(a & b)
- else
- throw new ParseException(getSourceRef(L)+" The argument in ?(<logical formula>) is not a logical formula.");
- } else {
- throw new ParseException(getSourceRef(L)+" Constructions like (<logical formula>) are possible only for test goal: ?(<logical formula>).");
- }
- }
- )
- |
- // actions or expressions
- rel = rel_expr()
- { if (rel instanceof Literal) {
- return new BodyLiteral(formType, (Literal)rel); // action
- } else if (rel instanceof RelExpr) {
- return new BodyLiteral(BodyType.constraint, (RelExpr)rel); // constraint
+ ]
+
+ B = log_expr()
+ { if (B instanceof Literal) {
+ return new BodyLiteral(formType, (Literal)B);
+ } else if (formType == BodyType.action && B instanceof RelExpr) {
+ return new BodyLiteral(BodyType.constraint, (RelExpr)B); // constraint
} else {
- throw new ParseException(getSourceRef(rel)+" A body formula should be an action or a constraint (RelExpr).");
+ if (formType == BodyType.test) {
+ if (B instanceof LogicalFormula)
+ return new BodyLiteral(BodyType.test, (LogicalFormula)B); // used in ?(a & b)
+ else
+ throw new ParseException(getSourceRef(B)+" The argument for ? is not a logical formula.");
+ } else {
+ throw new ParseException(getSourceRef(B)+" Unknown body formula.");
+ }
}
}
- )
}
/* Annotated Formulae */
-Pred pred() : { Token K; Pred p; Term t; List l; ListTerm lt;}
+Pred pred() : { Token K; Pred p; List l; ListTerm lt;}
{
(
K=<ATOM>
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2008-03-27 20:38:44 UTC (rev 1176)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2008-03-27 21:33:48 UTC (rev 1177)
@@ -469,8 +469,8 @@
}
/* Plan body */
- final public void plan_body(ArrayList bd) throws ParseException {
- BodyLiteral F;
+ final public void plan_body(List bd) throws ParseException {
+ BodyLiteral F;
F = body_formula();
if (! F.getLogicalFormula().equals(Literal.LTrue)) {
bd.add(F);
@@ -487,11 +487,13 @@
}
final public BodyLiteral body_formula() throws ParseException {
- Literal A; Token k;
- BodyType formType = BodyType.action;
- Object L;
- Object rel; VarTerm v;
- if (jj_2_2(4)) {
+ BodyType formType = BodyType.action; Object B;
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 31:
+ case 34:
+ case 35:
+ case 36:
+ case 38:
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 31:
jj_consume_token(31);
@@ -527,75 +529,32 @@
jj_consume_token(-1);
throw new ParseException();
}
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case TK_TRUE:
- case TK_FALSE:
- case TK_NEG:
- case TK_BEGIN:
- case TK_END:
- case ATOM:
- A = literal();
- {if (true) return new BodyLiteral(formType,A);}
- break;
- case VAR:
- case UNNAMEDVAR:
- v = var();
- {if (true) return new BodyLiteral(formType,v);}
- break;
- case 39:
- jj_consume_token(39);
- L = log_expr();
- jj_consume_token(40);
- if (formType == BodyType.test) {
- if (L instanceof LogicalFormula)
- {if (true) return new BodyLiteral(BodyType.test, (LogicalFormula)L);} // used in ?(a & b)
- else
- {if (true) throw new ParseException(getSourceRef(L)+" The argument in ?(<logical formula>) is not a logical formula.");}
+ break;
+ default:
+ jj_la1[22] = jj_gen;
+ ;
+ }
+ B = log_expr();
+ if (B instanceof Literal) {
+ {if (true) return new BodyLiteral(formType, (Literal)B);}
+ } else if (formType == BodyType.action && B instanceof RelExpr) {
+ {if (true) return new BodyLiteral(BodyType.constraint, (RelExpr)B);} // constraint
} else {
- {if (true) throw new ParseException(getSourceRef(L)+" Constructions like (<logical formula>) are possible only for test goal: ?(<logical formula>).");}
+ if (formType == BodyType.test) {
+ if (B instanceof LogicalFormula)
+ {if (true) return new BodyLiteral(BodyType.test, (LogicalFormula)B);} // used in ?(a & b)
+ else
+ {if (true) throw new ParseException(getSourceRef(B)+" The argument for ? is not a logical formula.");}
+ } else {
+ {if (true) throw new ParseException(getSourceRef(B)+" Unknown body formula.");}
+ }
}
- break;
- default:
- jj_la1[22] = jj_gen;
- jj_consume_token(-1);
- throw new ParseException();
- }
- } else {
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case VAR:
- case TK_TRUE:
- case TK_FALSE:
- case TK_NEG:
- case TK_BEGIN:
- case TK_END:
- case NUMBER:
- case STRING:
- case ATOM:
- case UNNAMEDVAR:
- case 35:
- case 39:
- // actions or expressions
- rel = rel_expr();
- if (rel instanceof Literal) {
- {if (true) return new BodyLiteral(formType, (Literal)rel);} // action
- } else if (rel instanceof RelExpr) {
- {if (true) return new BodyLiteral(BodyType.constraint, (RelExpr)rel);} // constraint
- } else {
- {if (true) throw new ParseException(getSourceRef(rel)+" A body formula should be an action or a constraint (RelExpr).");}
- }
- break;
- default:
- jj_la1[23] = jj_gen;
- jj_consume_token(-1);
- throw new ParseException();
- }
- }
throw new Error("Missing return statement in function");
}
/* Annotated Formulae */
final public Pred pred() throws ParseException {
- Token K; Pred p; Term t; List l; ListTerm lt;
+ Token K; Pred p; List l; ListTerm lt;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ATOM:
K = jj_consume_token(ATOM);
@@ -607,7 +566,7 @@
K = jj_consume_token(TK_END);
break;
default:
- jj_la1[24] = jj_gen;
+ jj_la1[23] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -622,7 +581,7 @@
p.setTerms(l);
break;
default:
- jj_la1[25] = jj_gen;
+ jj_la1[24] = jj_gen;
;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
@@ -631,7 +590,7 @@
p.setAnnots(lt);
break;
default:
- jj_la1[26] = jj_gen;
+ jj_la1[25] = jj_gen;
;
}
{if (true) return p;}
@@ -650,7 +609,7 @@
;
break;
default:
- jj_la1[27] = jj_gen;
+ jj_la1[26] = jj_gen;
break label_9;
}
jj_consume_token(41);
@@ -683,7 +642,7 @@
o = log_expr();
break;
default:
- jj_la1[28] = jj_gen;
+ jj_la1[27] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -717,7 +676,7 @@
;
break;
default:
- jj_la1[29] = jj_gen;
+ jj_la1[28] = jj_gen;
break label_10;
}
jj_consume_token(41);
@@ -741,18 +700,18 @@
last = last.concat((ListTerm)f);
break;
default:
- jj_la1[30] = jj_gen;
+ jj_la1[29] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
break;
default:
- jj_la1[31] = jj_gen;
+ jj_la1[30] = jj_gen;
;
}
break;
default:
- jj_la1[32] = jj_gen;
+ jj_la1[31] = jj_gen;
;
}
jj_consume_token(44);
@@ -784,7 +743,7 @@
o = string();
break;
default:
- jj_la1[33] = jj_gen;
+ jj_la1[32] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -803,7 +762,7 @@
{if (true) return new LogExpr((LogicalFormula)t1,LogicalOp.or,(LogicalFormula)t2);}
break;
default:
- jj_la1[34] = jj_gen;
+ jj_la1[33] = jj_gen;
;
}
{if (true) return t1;}
@@ -820,7 +779,7 @@
{if (true) return new LogExpr((LogicalFormula)t1,LogicalOp.and,(LogicalFormula)t2);}
break;
default:
- jj_la1[35] = jj_gen;
+ jj_la1[34] = jj_gen;
;
}
{if (true) return t1;}
@@ -851,7 +810,7 @@
{if (true) return t;}
break;
default:
- jj_la1[36] = jj_gen;
+ jj_la1[35] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -887,7 +846,7 @@
op1 = string();
break;
default:
- jj_la1[37] = jj_gen;
+ jj_la1[36] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -934,7 +893,7 @@
operator = RelationalOp.literalBuilder;
break;
default:
- jj_la1[38] = jj_gen;
+ jj_la1[37] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -959,7 +918,7 @@
op2 = list();
break;
default:
- jj_la1[39] = jj_gen;
+ jj_la1[38] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -970,7 +929,7 @@
{if (true) return new RelExpr((Term)op1, operator, (Term)op2);}
break;
default:
- jj_la1[40] = jj_gen;
+ jj_la1[39] = jj_gen;
;
}
{if (true) return op1;}
@@ -995,7 +954,7 @@
op = ArithmeticOp.minus;
break;
default:
- jj_la1[41] = jj_gen;
+ jj_la1[40] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1009,7 +968,7 @@
{if (true) return new ArithExpr((NumberTerm)t1, op, (NumberTerm)t2);}
break;
default:
- jj_la1[42] = jj_gen;
+ jj_la1[41] = jj_gen;
;
}
{if (true) return t1;}
@@ -1043,7 +1002,7 @@
op = ArithmeticOp.mod;
break;
default:
- jj_la1[43] = jj_gen;
+ jj_la1[42] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1057,7 +1016,7 @@
{if (true) return new ArithExpr((NumberTerm)t1, op, (NumberTerm)t2);}
break;
default:
- jj_la1[44] = jj_gen;
+ jj_la1[43] = jj_gen;
;
}
{if (true) return t1;}
@@ -1082,7 +1041,7 @@
{if (true) return new ArithExpr((NumberTerm)t1, op, (NumberTerm)t2);}
break;
default:
- jj_la1[45] = jj_gen;
+ jj_la1[44] = jj_gen;
;
}
{if (true) return t1;}
@@ -1128,7 +1087,7 @@
{if (true) return t;}
break;
default:
- jj_la1[46] = jj_gen;
+ jj_la1[45] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1163,7 +1122,7 @@
v = new UnnamedVar(K.image);
break;
default:
- jj_la1[47] = jj_gen;
+ jj_la1[46] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1173,7 +1132,7 @@
v.setAnnots(lt);
break;
default:
- jj_la1[48] = jj_gen;
+ jj_la1[47] = jj_gen;
;
}
{if (true) return v;}
@@ -1197,377 +1156,6 @@
finally { jj_save(0, xla); }
}
- 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_12() {
- if (jj_scan_token(31)) return true;
- return false;
- }
-
- final private boolean jj_3_2() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_12()) {
- jj_scanpos = xsp;
- if (jj_3R_13()) {
- jj_scanpos = xsp;
- if (jj_3R_14()) {
- jj_scanpos = xsp;
- if (jj_3R_15()) {
- jj_scanpos = xsp;
- if (jj_3R_16()) return true;
- }
- }
- }
- }
- xsp = jj_scanpos;
- if (jj_3R_17()) {
- jj_scanpos = xsp;
- if (jj_3R_18()) {
- jj_scanpos = xsp;
- if (jj_3R_19()) return true;
- }
- }
- return false;
- }
-
- final private boolean jj_3R_68() {
- if (jj_scan_token(35)) return true;
- return false;
- }
-
- final private boolean jj_3R_67() {
- if (jj_scan_token(34)) return true;
- return false;
- }
-
- final private boolean jj_3R_64() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_67()) {
- jj_scanpos = xsp;
- if (jj_3R_68()) return true;
- }
- return false;
- }
-
- final private boolean jj_3R_53() {
- if (jj_3R_63()) return true;
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_64()) jj_scanpos = xsp;
- return false;
- }
-
- final private boolean jj_3R_29() {
- if (jj_scan_token(TK_FALSE)) return true;
- return false;
- }
-
- final private boolean jj_3R_62() {
- if (jj_scan_token(53)) return true;
- return false;
- }
-
- final private boolean jj_3R_28() {
- if (jj_scan_token(TK_TRUE)) return true;
- return false;
- }
-
- final private boolean jj_3R_61() {
- if (jj_scan_token(52)) return true;
- return false;
- }
-
- final private boolean jj_3R_60() {
- if (jj_scan_token(51)) return true;
- return false;
- }
-
- final private boolean jj_3R_59() {
- if (jj_scan_token(50)) return true;
- return false;
- }
-
- final private boolean jj_3R_58() {
- if (jj_scan_token(49)) return true;
- return false;
- }
-
- final private boolean jj_3R_57() {
- if (jj_scan_token(48)) return true;
- return false;
- }
-
- final private boolean jj_3R_56() {
- if (jj_scan_token(47)) return true;
- return false;
- }
-
- final private boolean jj_3R_55() {
- if (jj_scan_token(46)) return true;
- return false;
- }
-
- final private boolean jj_3R_50() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_55()) {
- jj_scanpos = xsp;
- if (jj_3R_56()) {
- jj_scanpos = xsp;
- if (jj_3R_57()) {
- jj_scanpos = xsp;
- if (jj_3R_58()) {
- jj_scanpos = xsp;
- if (jj_3R_59()) {
- jj_scanpos = xsp;
- if (jj_3R_60()) {
- jj_scanpos = xsp;
- if (jj_3R_61()) {
- jj_scanpos = xsp;
- if (jj_3R_62()) return true;
- }
- }
- }
- }
- }
- }
- }
- return false;
- }
-
- final private boolean jj_3R_35() {
- if (jj_scan_token(TK_NEG)) return true;
- return false;
- }
-
- final private boolean jj_3R_49() {
- if (jj_3R_54()) return true;
- return false;
- }
-
- final private boolean jj_3R_48() {
- if (jj_3R_53()) return true;
- return false;
- }
-
- final private boolean jj_3R_27() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_35()) jj_scanpos = xsp;
- if (jj_3R_11()) return true;
- return false;
- }
-
- final private boolean jj_3R_23() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_27()) {
- jj_scanpos = xsp;
- if (jj_3R_28()) {
- jj_scanpos = xsp;
- if (jj_3R_29()) return true;
- }
- }
- return false;
- }
-
- final private boolean jj_3R_43() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_48()) {
- jj_scanpos = xsp;
- if (jj_3R_49()) return true;
- }
- xsp = jj_scanpos;
- if (jj_3R_50()) jj_scanpos = xsp;
- return false;
- }
-
- final private boolean jj_3R_40() {
- if (jj_3R_43()) return true;
- return false;
- }
-
- final private boolean jj_3R_39() {
- if (jj_scan_token(TK_NOT)) return true;
- if (jj_3R_36()) return true;
- return false;
- }
-
- final private boolean jj_3R_36() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_39()) {
- jj_scanpos = xsp;
- if (jj_3R_40()) return true;
- }
- return false;
- }
-
- final private boolean jj_3R_37() {
- if (jj_scan_token(45)) return true;
- return false;
- }
-
- final private boolean jj_3R_33() {
- if (jj_3R_36()) return true;
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_37()) jj_scanpos = xsp;
- return false;
- }
-
- final private boolean jj_3R_34() {
- if (jj_scan_token(43)) return true;
- return false;
- }
-
- final private boolean jj_3R_25() {
- if (jj_3R_33()) return true;
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_34()) jj_scanpos = xsp;
- return false;
- }
-
- final private boolean jj_3R_47() {
- if (jj_3R_54()) return true;
- return false;
- }
-
- final private boolean jj_3R_46() {
- if (jj_3R_53()) return true;
- return false;
- }
-
- final private boolean jj_3R_45() {
- if (jj_3R_26()) return true;
- return false;
- }
-
- final private boolean jj_3R_42() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_45()) {
- jj_scanpos = xsp;
- if (jj_3R_46()) {
- jj_scanpos = xsp;
- if (jj_3R_47()) return true;
- }
- }
- return false;
- }
-
- final private boolean jj_3R_54() {
- if (jj_scan_token(STRING)) return true;
- return false;
- }
-
- final private boolean jj_3R_32() {
- if (jj_3R_26()) return true;
- return false;
- }
-
- final private boolean jj_3R_38() {
- if (jj_3R_42()) return true;
- return false;
- }
-
- final private boolean jj_3R_26() {
- if (jj_scan_token(42)) return true;
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_38()) jj_scanpos = xsp;
- if (jj_scan_token(44)) return true;
- return false;
- }
-
- final private boolean jj_3R_31() {
- if (jj_scan_token(UNNAMEDVAR)) return true;
- return false;
- }
-
- final private boolean jj_3R_30() {
- if (jj_scan_token(VAR)) return true;
- return false;
- }
-
- final private boolean jj_3R_24() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_30()) {
- jj_scanpos = xsp;
- if (jj_3R_31()) return true;
- }
- xsp = jj_scanpos;
- if (jj_3R_32()) jj_scanpos = xsp;
- return false;
- }
-
- final private boolean jj_3R_52() {
- if (jj_3R_25()) return true;
- return false;
- }
-
- final private boolean jj_3R_51() {
- if (jj_3R_26()) return true;
- return false;
- }
-
- final private boolean jj_3R_44() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_51()) {
- jj_scanpos = xsp;
- if (jj_3R_52()) return true;
- }
- return false;
- }
-
- final private boolean jj_3R_80() {
- if (jj_3R_23()) return true;
- return false;
- }
-
- final private boolean jj_3R_41() {
- if (jj_3R_44()) return true;
- return false;
- }
-
- final private boolean jj_3R_21() {
- if (jj_3R_26()) return true;
- return false;
- }
-
- final private boolean jj_3R_79() {
- if (jj_3R_80()) return true;
- return false;
- }
-
- final private boolean jj_3R_78() {
- if (jj_3R_24()) return true;
- return false;
- }
-
- final private boolean jj_3R_77() {
- if (jj_scan_token(39)) return true;
- if (jj_3R_25()) return true;
- return false;
- }
-
- final private boolean jj_3R_20() {
- if (jj_scan_token(39)) return true;
- if (jj_3R_41()) return true;
- return false;
- }
-
final private boolean jj_3_1() {
if (jj_scan_token(27)) return true;
if (jj_scan_token(TK_BEGIN)) return true;
@@ -1576,36 +1164,6 @@
return false;
}
- final private boolean jj_3R_76() {
- if (jj_scan_token(35)) return true;
- if (jj_3R_69()) return true;
- return false;
- }
-
- final private boolean jj_3R_75() {
- if (jj_scan_token(NUMBER)) return true;
- return false;
- }
-
- final private boolean jj_3R_69() {
- 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_11() {
Token xsp;
xsp = jj_scanpos;
@@ -1617,114 +1175,27 @@
}
}
xsp = jj_scanpos;
- if (jj_3R_20()) jj_scanpos = xsp;
+ if (jj_3R_12()) jj_scanpos = xsp;
xsp = jj_scanpos;
- if (jj_3R_21()) jj_scanpos = xsp;
+ if (jj_3R_13()) jj_scanpos = xsp;
return false;
}
- final private boolean jj_3R_70() {
- if (jj_scan_token(56)) return true;
+ final private boolean jj_3R_14() {
+ if (jj_scan_token(42)) return true;
return false;
}
- final private boolean jj_3R_65() {
- if (jj_3R_69()) return true;
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_70()) jj_scanpos = xsp;
+ final private boolean jj_3R_13() {
+ if (jj_3R_14()) return true;
return false;
}
- final private boolean jj_3R_74() {
- if (jj_scan_token(TK_INTMOD)) return true;
- return false;
- }
-
- final private boolean jj_3R_19() {
+ final private boolean jj_3R_12() {
if (jj_scan_token(39)) return true;
- if (jj_3R_25()) return true;
- if (jj_scan_token(40)) return true;
return false;
}
- final private boolean jj_3R_73() {
- if (jj_scan_token(TK_INTDIV)) return true;
- return false;
- }
-
- final private boolean jj_3R_18() {
- if (jj_3R_24()) return true;
- return false;
- }
-
- final private boolean jj_3R_72() {
- if (jj_scan_token(55)) return true;
- return false;
- }
-
- final private boolean jj_3R_17() {
- if (jj_3R_23()) return true;
- return false;
- }
-
- final private boolean jj_3R_22() {
- if (jj_scan_token(34)) return true;
- return false;
- }
-
- final private boolean jj_3R_71() {
- if (jj_scan_token(54)) return true;
- return false;
- }
-
- final private boolean jj_3R_66() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_71()) {
- jj_scanpos = xsp;
- if (jj_3R_72()) {
- jj_scanpos = xsp;
- if (jj_3R_73()) {
- jj_scanpos = xsp;
- if (jj_3R_74()) return true;
- }
- }
- }
- return false;
- }
-
- final private boolean jj_3R_63() {
- if (jj_3R_65()) return true;
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_66()) jj_scanpos = xsp;
- return false;
- }
-
- final private boolean jj_3R_16() {
- if (jj_scan_token(35)) return true;
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_22()) jj_scanpos = xsp;
- return false;
- }
-
- final private boolean jj_3R_15() {
- if (jj_scan_token(34)) return true;
- return false;
- }
-
- final private boolean jj_3R_14() {
- if (jj_scan_token(36)) return true;
- return false;
- }
-
- final private boolean jj_3R_13() {
- if (jj_scan_token(38)) return true;
- return false;
- }
-
public as2jTokenManager token_source;
SimpleCharStream jj_input_stream;
public Token token, jj_nt;
@@ -1734,7 +1205,7 @@
public boolean lookingAhead = false;
private boolean jj_semLA;
private int jj_gen;
- final private int[] jj_la1 = new int[49];
+ final private int[] jj_la1 = new int[48];
static private int[] jj_la1_0;
static private int[] jj_la1_1;
static {
@@ -1742,12 +1213,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,0x800,0x10cb00,0x0,0x0,0x80000000,0x30cb80,0x3acb80,0x10c000,0x0,0x0,0x0,0x3acf80,0x0,0x200080,0x0,0x3acb80,0x3acb80,0x0,0x0,0x3acf80,0x3acb80,0x0,0x3acb80,0x0,0x0,0x0,0x3000,0x3000,0x0,0x32cb80,0x200080,0x0,};
+ jj_la1_0 = new int[] {0x8000000,0x10cb00,0x8000000,0x80000000,0x8000000,0x10000,0x10cb00,0x8000000,0x8000000,0x20000000,0x10000,0x0,0x0,0x0,0x80000000,0x80000000,0x30cb80,0x800,0x10cb00,0x0,0x0,0x80000000,0x80000000,0x10c000,0x0,0x0,0x0,0x3acf80,0x0,0x200080,0x0,0x3acb80,0x3acb80,0x0,0x0,0x3acf80,0x3acb80,0x0,0x3acb80,0x0,0x0,0x0,0x3000,0x3000,0x0,0x32cb80,0x200080,0x0,};
}
private static void jj_la1_1() {
- jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0xc,0x0,0x0,0x0,0x0,0x0,0x1,0x2,0xc,0x10,0x10,0x0,0x0,0x0,0x20,0x4,0x5c,0x80,0x88,0x0,0x80,0x400,0x200,0x488,0x200,0x400,0x800,0x488,0x488,0x800,0x2000,0x88,0x88,0x3fc000,0x488,0x3fc000,0xc,0xc,0xc00000,0xc00000,0x1000000,0x88,0x0,0x400,};
+ jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0xc,0x0,0x0,0x0,0x0,0x0,0x1,0x2,0xc,0x10,0x10,0x0,0x0,0x0,0x20,0x4,0x5c,0x5c,0x0,0x80,0x400,0x200,0x488,0x200,0x400,0x800,0x488,0x488,0x800,0x2000,0x88,0x88,0x3fc000,0x488,0x3fc000,0xc,0xc,0xc00000,0xc00000,0x1000000,0x88,0x0,0x400,};
}
- final private JJCalls[] jj_2_rtns = new JJCalls[2];
+ final private JJCalls[] jj_2_rtns = new JJCalls[1];
private boolean jj_rescan = false;
private int jj_gc = 0;
@@ -1760,7 +1231,7 @@
token = new Token();
jj_ntk = -1;
jj_gen = 0;
- for (int i = 0; i < 49; i++) jj_la1[i] = -1;
+ for (int i = 0; i < 48; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
@@ -1773,7 +1244,7 @@
token = new Token();
jj_ntk = -1;
jj_gen = 0;
- for (int i = 0; i < 49; i++) jj_la1[i] = -1;
+ for (int i = 0; i < 48; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
@@ -1783,7 +1254,7 @@
token = new Token();
jj_ntk = -1;
jj_gen = 0;
- for (int i = 0; i < 49; i++) jj_la1[i] = -1;
+ for (int i = 0; i < 48; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
@@ -1793,7 +1264,7 @@
token = new Token();
jj_ntk = -1;
jj_gen = 0;
- for (int i = 0; i < 49; i++) jj_la1[i] = -1;
+ for (int i = 0; i < 48; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
@@ -1802,7 +1273,7 @@
token = new Token();
jj_ntk = -1;
jj_gen = 0;
- for (int i = 0; i < 49; i++) jj_la1[i] = -1;
+ for (int i = 0; i < 48; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
@@ -1811,7 +1282,7 @@
token = new Token();
jj_ntk = -1;
jj_gen = 0;
- for (int i = 0; i < 49; i++) jj_la1[i] = -1;
+ for (int i = 0; i < 48; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
@@ -1930,7 +1401,7 @@
la1tokens[jj_kind] = true;
jj_kind = -1;
}
- for (int i = 0; i < 49; i++) {
+ for (int i = 0; i < 48; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
@@ -1967,7 +1438,7 @@
final private void jj_rescan_token() {
jj_rescan = true;
- for (int i = 0; i < 2; i++) {
+ for (int i = 0; i < 1; i++) {
try {
JJCalls p = jj_2_rtns[i];
do {
@@ -1975,7 +1446,6 @@
jj_la = p.arg; jj_lastpos = jj_scanpos = p.first;
switch (i) {
case 0: jj_3_1(); break;
- case 1: jj_3_2(); break;
}
}
p = p.next;
Modified: trunk/src/test/ASParserTest.java
===================================================================
--- trunk/src/test/ASParserTest.java 2008-03-27 20:38:44 UTC (rev 1176)
+++ trunk/src/test/ASParserTest.java 2008-03-27 21:33:48 UTC (rev 1177)
@@ -181,22 +181,18 @@
File[] files = dir.listFiles();
if (files != null) {
for (File f: files) {
- if (f.isDirectory()) {
- parseDir(f);
- } else if (f.getName().endsWith(MAS2JProject.AS_EXT)) {
- try {
+ try {
+ if (f.isDirectory()) {
+ parseDir(f);
+ } else if (f.getName().endsWith(MAS2JProject.AS_EXT)) {
as2j parser = new as2j(new FileInputStream(f));
parser.agent((Agent)null);
- } catch (Exception e) {
- fail("Error parsing "+f);
- }
- } else if (f.getName().endsWith(MAS2JProject.EXT)) {
- try {
+ } else if (f.getName().endsWith(MAS2JProject.EXT)) {
mas2j parser = new mas2j(new FileInputStream(f));
parser.mas();
- } catch (Exception e) {
- fail("Error parsing "+f);
}
+ } catch (Exception e) {
+ fail("Error parsing "+f);
}
}
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-27 20:38:51
|
Revision: 1176
http://jason.svn.sourceforge.net/jason/?rev=1176&view=rev
Author: jomifred
Date: 2008-03-27 13:38:44 -0700 (Thu, 27 Mar 2008)
Log Message:
-----------
include a JUnit test to parse all .asl/.mas2j files inside demos and examples
Modified Paths:
--------------
trunk/src/jason/asSyntax/directives/FunctionRegister.java
trunk/src/jason/asSyntax/directives/Include.java
trunk/src/test/ASParserTest.java
Modified: trunk/src/jason/asSyntax/directives/FunctionRegister.java
===================================================================
--- trunk/src/jason/asSyntax/directives/FunctionRegister.java 2008-03-26 09:15:42 UTC (rev 1175)
+++ trunk/src/jason/asSyntax/directives/FunctionRegister.java 2008-03-27 20:38:44 UTC (rev 1176)
@@ -81,6 +81,8 @@
@SuppressWarnings("unchecked")
public Agent process(Pred directive, Agent outerContent, Agent innerContent) {
+ if (outerContent == null)
+ return null;
try {
String id = ((StringTerm)directive.getTerm(0)).getString();
if (directive.getArity() == 1) {
Modified: trunk/src/jason/asSyntax/directives/Include.java
===================================================================
--- trunk/src/jason/asSyntax/directives/Include.java 2008-03-26 09:15:42 UTC (rev 1175)
+++ trunk/src/jason/asSyntax/directives/Include.java 2008-03-27 20:38:44 UTC (rev 1176)
@@ -25,9 +25,11 @@
private List<String> aslSourcePath = null;
public Agent process(Pred directive, Agent outerContent, Agent innerContent) {
+ if (outerContent == null)
+ return null;
String file = ((StringTerm)directive.getTerm(0)).getString();
try {
- String outerPrefix = outerContent.getASLSrc(); // the source file that has the include directive
+ String outerPrefix = outerContent.getASLSrc(); // the source file that has the include directive
InputStream in;
if (outerContent != null && outerPrefix != null) {
// check if the outer is URL
@@ -69,7 +71,7 @@
logger.fine("as2j: AgentSpeak program '"+file+"' parsed successfully!");
return ag;
} catch (FileNotFoundException e) {
- logger.log(Level.SEVERE,"The included file '"+file+"' was not found! (it is being included in the agent "+outerContent.getASLSrc()+")");
+ logger.log(Level.SEVERE,"The included file '"+file+"' was not found! (it is being included in the agent '"+outerContent.getASLSrc()+"')");
} catch (Exception e) {
logger.log(Level.SEVERE,"as2j: error parsing \"" + file + "\"", e);
}
Modified: trunk/src/test/ASParserTest.java
===================================================================
--- trunk/src/test/ASParserTest.java 2008-03-26 09:15:42 UTC (rev 1175)
+++ trunk/src/test/ASParserTest.java 2008-03-27 20:38:44 UTC (rev 1176)
@@ -12,7 +12,11 @@
import jason.asSyntax.RelExpr;
import jason.asSyntax.parser.as2j;
import jason.infra.centralised.CentralisedAgArch;
+import jason.mas2j.MAS2JProject;
+import jason.mas2j.parser.mas2j;
+import java.io.File;
+import java.io.FileInputStream;
import java.io.StringReader;
import java.util.Iterator;
@@ -158,4 +162,43 @@
assertTrue(a.getPL().getPlans().size() == 5);
}
+
+ public void testParsingAllSources() {
+ parseDir(new File("./examples"));
+ parseDir(new File("./demos"));
+ parseDir(new File("./applications/jason-moise"));
+ parseDir(new File("./applications/jason-team"));
+ parseDir(new File("./doc/mini-tutorial"));
+ parseDir(new File("../Jason-applications/examples-site-jBook"));
+ parseDir(new File("../Jason-applications/Tests"));
+ }
+
+ public void parseDir(File dir) {
+ if (!dir.exists())
+ return;
+ if (dir.getName().endsWith(".svn"))
+ return;
+ File[] files = dir.listFiles();
+ if (files != null) {
+ for (File f: files) {
+ if (f.isDirectory()) {
+ parseDir(f);
+ } else if (f.getName().endsWith(MAS2JProject.AS_EXT)) {
+ try {
+ as2j parser = new as2j(new FileInputStream(f));
+ parser.agent((Agent)null);
+ } catch (Exception e) {
+ fail("Error parsing "+f);
+ }
+ } else if (f.getName().endsWith(MAS2JProject.EXT)) {
+ try {
+ mas2j parser = new mas2j(new FileInputStream(f));
+ parser.mas();
+ } catch (Exception e) {
+ fail("Error parsing "+f);
+ }
+ }
+ }
+ }
+ }
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-26 09:15:46
|
Revision: 1175
http://jason.svn.sourceforge.net/jason/?rev=1175&view=rev
Author: jomifred
Date: 2008-03-26 02:15:42 -0700 (Wed, 26 Mar 2008)
Log Message:
-----------
add a TestAll class in AS-Unit to run all tests
Modified Paths:
--------------
trunk/applications/as-unit-test/build.xml
trunk/demos/directives/b.asl
trunk/demos/sync-environment/dcount.asl
Added Paths:
-----------
trunk/applications/as-unit-test/src/jason/tests/TestAll.java
Modified: trunk/applications/as-unit-test/build.xml
===================================================================
--- trunk/applications/as-unit-test/build.xml 2008-03-24 21:15:02 UTC (rev 1174)
+++ trunk/applications/as-unit-test/build.xml 2008-03-26 09:15:42 UTC (rev 1175)
@@ -49,7 +49,7 @@
<formatter type="plain" usefile="false" />
<batchtest>
<fileset dir="${basedir}/src" includes="example/**/Test*.java" />
- <fileset dir="${basedir}/src" includes="jason/tests/**/Test*.java" />
+ <fileset dir="${basedir}/src" includes="jason/tests/TestAll.java" />
</batchtest>
</junit>
<fail message="test failed" if="test.failure" />
@@ -72,63 +72,6 @@
</javadoc>
</target>
- <target name="dist" depends="jar" description="Build distribution.">
-
- <echo message="Generating Jason ASUnit ${version}.${release}" />
-
- <propertyfile file="${dist.properties}">
- <entry key="version" value="${version}" />
- <entry key="release" value="${release}" />
- <!-- entry default="0" key="build" operation="+" type="int" /-->
- <entry key="build.date" type="date" value="now" />
- </propertyfile>
- <property file="${dist.properties}" />
-
- <fixcrlf eol="crlf" includes="**/*.txt,**/*.bat" srcdir="${basedir}" />
-
- <delete failonerror="no" includeEmptyDirs="true">
- <fileset dir="${distDir}" />
- </delete>
- <delete dir="${distDir}/.." />
-
- <mkdir dir="${distDir}" />
-
- <copy todir="${distDir}">
- <fileset dir="${basedir}" includes="*.*" />
- <fileset dir="${basedir}" includes="LICENSE" />
- <fileset dir="${basedir}" includes="README" />
-
- <fileset dir="${basedir}" includes="bin/*" excludes="bin/jedit.tgz" />
- <fileset dir="${basedir}" includes="bin/jedit/**/*" />
- <fileset dir="${basedir}" includes="doc/**/*" />
- <fileset dir="${basedir}" includes="examples/**/*" />
- <fileset dir="${basedir}" includes="demos/**/*" />
- <fileset dir="${basedir}" includes="lib/**/*" />
- <fileset dir="${basedir}" includes="src/**/*" />
- </copy>
-
- <delete failonerror="no" includeEmptyDirs="true">
- <fileset dir="${distDir}" includes=".settings" />
- <fileset dir="${distDir}" includes=".project" />
- <fileset dir="${distDir}" includes=".classpath" />
- </delete>
- <delete dir="${distDir}/bin/classes" />
- <delete dir="${distDir}/doc/faq" />
- <delete dir="${distDir}/doc/mini-tutorial/src" />
-
- <tar compression="gzip" tarfile="${distFile}.tgz">
- <tarfileset dir="${distDir}/.." mode="755">
- <include name="Jason-${version}.${release}/**/*.sh" />
- <include name="Jason-${version}.${release}/**/asl2*" />
- </tarfileset>
- <tarfileset dir="${distDir}/..">
- <include name="Jason-${version}.${release}/**/*" />
- <exclude name="Jason-${version}.${release}/**/*.sh" />
- <exclude name="Jason-${version}.${release}/**/asl2*" />
- </tarfileset>
- </tar>
- </target>
-
<target name="clean">
<delete dir="${build.dir}" />
</target>
Added: trunk/applications/as-unit-test/src/jason/tests/TestAll.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestAll.java (rev 0)
+++ trunk/applications/as-unit-test/src/jason/tests/TestAll.java 2008-03-26 09:15:42 UTC (rev 1175)
@@ -0,0 +1,14 @@
+package jason.tests;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+import org.junit.runners.Suite.SuiteClasses;
+
+@RunWith(Suite.class)
+@SuiteClasses({
+ BugVarsInInitBels.class,
+ TestAddLogExprInBB.class,
+ TestKQML.class,
+ TestVarInContext.class
+ })
+public class TestAll { }
Modified: trunk/demos/directives/b.asl
===================================================================
--- trunk/demos/directives/b.asl 2008-03-24 21:15:02 UTC (rev 1174)
+++ trunk/demos/directives/b.asl 2008-03-26 09:15:42 UTC (rev 1175)
@@ -2,13 +2,13 @@
+!start : true <- myp.list_plans; !d(1); !d(2).
{ begin ld }
-+!d(X) <- act.
-+!d(X) <- act.
++!d(X) <- act(X).
++!d(X) <- act(X).
{ end }
/*
The above plans will be changed by the directive to:
- +!d(X) <- .print("Entering ",d(X)); .print(d1); .print("Leaving ",d(X)).
- +!d(X) <- .print("Entering ",d(X)); .print(d2); .print("Leaving ",d(X)).
+ +!d(X) <- .print("Entering ",d(X)); act(X); .print("Leaving ",d(X)).
+ +!d(X) <- .print("Entering ",d(X)); act(X); .print("Leaving ",d(X)).
*/
Modified: trunk/demos/sync-environment/dcount.asl
===================================================================
--- trunk/demos/sync-environment/dcount.asl 2008-03-24 21:15:02 UTC (rev 1174)
+++ trunk/demos/sync-environment/dcount.asl 2008-03-26 09:15:42 UTC (rev 1175)
@@ -1,9 +1,10 @@
// this agent has TWO intentions to act
+vl(0).
+
!i1.
!i2.
-vl(0).
/* Plans */
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <tom...@us...> - 2008-03-24 21:15:13
|
Revision: 1174
http://jason.svn.sourceforge.net/jason/?rev=1174&view=rev
Author: tomklapiscak
Date: 2008-03-24 14:15:02 -0700 (Mon, 24 Mar 2008)
Log Message:
-----------
Non-JASDL annotations (addition only) and unground belief removals (at brf stage) handled correctly by JASDL. Removal of SE-Literals (and associated annotation handling) still needs work.
Modified Paths:
--------------
trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java
trunk/applications/jasdl-owlapi/src/jasdl/bb/JasdlBeliefBase.java
trunk/applications/jasdl-owlapi/src/jasdl/bridge/ToSELiteralConverter.java
Modified: trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java 2008-03-24 20:37:34 UTC (rev 1173)
+++ trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java 2008-03-24 21:15:02 UTC (rev 1174)
@@ -32,6 +32,7 @@
import jason.architecture.AgArch;
import jason.asSemantics.Intention;
import jason.asSemantics.TransitionSystem;
+import jason.asSemantics.Unifier;
import jason.asSyntax.Atom;
import jason.asSyntax.Literal;
import jason.bb.BeliefBase;
@@ -193,7 +194,7 @@
// just accept beliefToDel. Assumption: Deletions never lead to inconsistencies?!
- if(beliefToDel != null){
+ if(beliefToDel != null){
removeList.add(beliefToDel);
}
@@ -250,18 +251,29 @@
toReturn[0].add(added);
}
}
+
for(Literal removed : removeList){
- if(getBB().remove(removed)){
- if(toReturn == null){
+ // we need to ground unground removals
+ Unifier u = null;
+ try {
+ u = i.peek().getUnif(); // get from current intention
+ } catch (Exception e) {
+ u = new Unifier();
+ }
+ if (believes(removed, u)) {
+ removed.apply(u); // TODO: should unground removals not result in removal of all unifications?
+ if(getBB().remove(removed)){
if(toReturn == null){
- toReturn = new List[2];
- toReturn[0] = new Vector<Literal>();
- toReturn[1] = new Vector<Literal>();
+ if(toReturn == null){
+ toReturn = new List[2];
+ toReturn[0] = new Vector<Literal>();
+ toReturn[1] = new Vector<Literal>();
+ }
+ toReturn[1].add(removed);
}
- toReturn[1].add(removed);
+
}
-
- }
+ }
}
return toReturn;
Modified: trunk/applications/jasdl-owlapi/src/jasdl/bb/JasdlBeliefBase.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/bb/JasdlBeliefBase.java 2008-03-24 20:37:34 UTC (rev 1173)
+++ trunk/applications/jasdl-owlapi/src/jasdl/bb/JasdlBeliefBase.java 2008-03-24 21:15:02 UTC (rev 1174)
@@ -1,13 +1,12 @@
package jasdl.bb;
import jasdl.asSemantics.JasdlAgent;
-import jasdl.bb.revision.BeliefBaseContractor;
-import jasdl.bb.revision.JasdlReasonerFactory;
import jasdl.bridge.seliteral.SELiteral;
import jasdl.bridge.seliteral.SELiteralAllDifferentAssertion;
import jasdl.util.JasdlException;
import jasdl.util.NotEnrichedException;
import jason.asSyntax.Literal;
+import jason.asSyntax.Term;
import jason.bb.DefaultBeliefBase;
import java.util.HashSet;
@@ -34,31 +33,28 @@
public boolean add(Literal l) {
getLogger().fine("Adding "+l);
try{
- SELiteral sl = agent.getSELiteralFactory().create(l); // all non-JASDL annotations added.. TODO: This needs sorting
+
+ SELiteral sl = agent.getSELiteralFactory().create(l);
OWLIndividualAxiom axiom = sl.createAxiom();
OWLOntology ontology = sl.getOntology();
- // add axiom annotations to axiom containing serialised list terms.
- // Could be (clumsily) made to sit in toAxiomConverter? - this is probably the only place we add axioms to an ontology anyway
- OWLAnnotation annot = agent.getOntologyManager().getOWLDataFactory().getOWLLabelAnnotation(sl.getSemanticallyNaiveAnnotations().toString()); //TODO: more efficient way of serialising list terms?
- OWLAxiomAnnotationAxiom annotAxiom = agent.getOntologyManager().getOWLDataFactory().getOWLAxiomAnnotationAxiom(axiom, annot);
-
- // need to merge existing annotations into a single one containing a whole list.
-
-
- boolean containsAxiom = ontology.containsAxiom(axiom);
- boolean containsAnnot = ontology.containsAxiom(annotAxiom);
- agent.getLogger().fine("Contains Axiom "+axiom+"?: " +containsAxiom);
- agent.getLogger().fine("Contains Annotation "+annotAxiom+"?: " +containsAnnot);
- if(!containsAxiom || !containsAnnot){
- if(!containsAxiom){
- agent.getOntologyManager().applyChange(new AddAxiom(ontology, axiom));
- }
- if(!containsAnnot){
+ boolean containsAxiom = ontology.containsAxiom(axiom);
+ if(!containsAxiom){
+ agent.getOntologyManager().applyChange(new AddAxiom(ontology, axiom));
+ }
+
+ boolean containsAllAnnots = true;
+ for(Term _annot : sl.getSemanticallyNaiveAnnotations()){
+ OWLAnnotation annot = agent.getOntologyManager().getOWLDataFactory().getOWLLabelAnnotation(_annot.toString());
+ OWLAxiomAnnotationAxiom annotAxiom = agent.getOntologyManager().getOWLDataFactory().getOWLAxiomAnnotationAxiom(axiom, annot);
+ if(!ontology.containsAxiom(annotAxiom)){
+ containsAllAnnots = false;
agent.getOntologyManager().applyChange(new AddAxiom(ontology, annotAxiom));
}
- agent.getReasoner().refresh();
-
+ }
+
+ if(!containsAxiom || !containsAllAnnots){
+ agent.getReasoner().refresh();
if(!agent.isBeliefRevisionEnabled()){ // if brf disabled, resort to legacy consistency maintenance mechanism
if(!agent.getReasoner().isConsistent()){
RemoveAxiom rem = new RemoveAxiom(ontology, axiom);
@@ -90,7 +86,7 @@
public boolean remove(Literal l) {
getLogger().fine("Removing "+l);
try{
- // TODO: use contraction
+ // TODO: use contraction for belief base removal
//BeliefBaseContractor contractor = new BeliefBaseContractor(agent.getOntologyManager(), new JasdlReasonerFactory(), agent.getLogger());
//contractor.contract(axiom, kernelsetFilter, incisionFunction)
@@ -103,7 +99,7 @@
agent.getReasoner().refresh();
return true;
}catch(NotEnrichedException e){
- return super.add(l); // semantically-naive, use standard Jason mechanisms
+ return super.remove(l); // semantically-naive, use standard Jason mechanisms
}catch(Exception e){
getLogger().warning("Exception caught removing SELiteral "+l+" from belief base: ");
e.printStackTrace();
Modified: trunk/applications/jasdl-owlapi/src/jasdl/bridge/ToSELiteralConverter.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/bridge/ToSELiteralConverter.java 2008-03-24 20:37:34 UTC (rev 1173)
+++ trunk/applications/jasdl-owlapi/src/jasdl/bridge/ToSELiteralConverter.java 2008-03-24 21:15:02 UTC (rev 1174)
@@ -64,12 +64,8 @@
// get annotations
Set<OWLAxiomAnnotationAxiom> annotAxioms = axiom.getAnnotationAxioms(ontology);
for(OWLAxiomAnnotationAxiom annotAxiom : annotAxioms){ // remember, possibly semantically-naive payload!
- Structure annot = ListTermImpl.parse(annotAxiom.getAnnotation().getAnnotationValueAsConstant().getLiteral());
- if(annot.isList()){
- result.addAll((ListTerm)annot);
- }else{
- result.add(annot);
- }
+ Term annot = Literal.parse(annotAxiom.getAnnotation().getAnnotationValueAsConstant().getLiteral());
+ result.add(annot);
}
return result;
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-24 20:37:38
|
Revision: 1173
http://jason.svn.sourceforge.net/jason/?rev=1173&view=rev
Author: jomifred
Date: 2008-03-24 13:37:34 -0700 (Mon, 24 Mar 2008)
Log Message:
-----------
add a new test in ASUnit to check the KQML performatives
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java
trunk/applications/as-unit-test/src/jason/asunit/TestArch.java
trunk/applications/as-unit-test/src/jason/tests/TestVarInContext.java
trunk/src/jason/asSemantics/Unifier.java
trunk/src/jason/asSyntax/Literal.java
trunk/src/jason/asSyntax/PlanLibrary.java
trunk/src/jason/asSyntax/VarTerm.java
trunk/src/jason/infra/centralised/CentralisedAgArch.java
trunk/src/jason/infra/centralised/CentralisedEnvironment.java
trunk/src/jason/infra/centralised/RunCentralisedMAS.java
trunk/src/test/RuleTest.java
trunk/src/test/VarTermTest.java
Added Paths:
-----------
trunk/applications/as-unit-test/src/jason/tests/TestKQML.java
Modified: trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -14,6 +14,7 @@
import jason.asSyntax.Trigger;
import jason.asSyntax.parser.ParseException;
import jason.bb.BeliefBase;
+import jason.infra.centralised.RunCentralisedMAS;
import jason.runtime.Settings;
import java.io.StringReader;
@@ -21,9 +22,23 @@
public class TestAgent extends Agent {
+ // creates the masRunner
+ static {
+ new RunCentralisedMAS();
+ }
+
+
public TestAgent() {
+ this(null);
+ }
+
+ public TestAgent(String agName) {
try {
- TestArch arch = new TestArch();
+ TestArch arch = null;
+ if (agName == null)
+ arch = new TestArch();
+ else
+ arch = new TestArch(agName);
arch.getUserAgArch().setTS(initAg(arch.getUserAgArch(), null, null, new Settings()));
} catch (JasonException e) {
logger.log(Level.SEVERE, "Error creating TestArch", e);
@@ -32,10 +47,16 @@
public boolean parseAScode(String aslCode) {
try {
+ getPL().clear(); // to force KQML plans to be after string plans
setASLSrc("stringcode");
parseAS(new StringReader(aslCode));
addInitialBelsInBB();
addInitialGoalsInTS();
+
+ // kqml Plans at the end of the ag PS
+ setASLSrc("kqmlPlans.asl");
+ parseAS(JasonException.class.getResource("/asl/kqmlPlans.asl"));
+ setASLSrc("stringcode");
return true;
} catch (Exception e) {
logger.log(Level.SEVERE, "Error parsing\n"+aslCode+": "+e.getMessage());
@@ -105,14 +126,14 @@
fail("Parsing '"+formula+"' as a formula failed!");
}
}
- public void assertBel(final LogicalFormula bel, final int maxCycles) {
+ public void assertBel(final LogicalFormula belief, final int maxCycles) {
Condition c = new Condition() {
public boolean test(TestArch arch) {
- return believes(bel, new Unifier());
+ return believes(belief, new Unifier());
}
};
if (!assertMaxCyclesAndAnotherCondition(c, maxCycles))
- fail("failed assertBel("+bel+")");
+ fail("failed assertBel("+belief+")");
}
@@ -167,8 +188,7 @@
public void assertPrint(final String out, final int maxCycles) {
Condition c = new Condition() {
public boolean test(TestArch arch) {
- boolean result = arch.getOutput().indexOf(out) >= 0;
- return result;
+ return arch.getOutput().indexOf(out) >= 0;
}
};
if (assertMaxCyclesAndAnotherCondition(c, maxCycles))
Modified: trunk/applications/as-unit-test/src/jason/asunit/TestArch.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/asunit/TestArch.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/applications/as-unit-test/src/jason/asunit/TestArch.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -24,14 +24,16 @@
StringBuilder output = new StringBuilder();
- private static RunCentralisedMAS runner = new RunCentralisedMAS();
-
public TestArch() {
- setAgName("ASUnitTest" + (nameCount++));
+ this("ASUnitTest" + (nameCount++));
+ }
+
+ public TestArch(String agName) {
+ setAgName(agName);
AgArch a = new AgArch();
a.setArchInfraTier(this);
setUserAgArch(a);
- runner.addAg(this);
+ RunCentralisedMAS.getRunner().addAg(this);
}
public int getCycle() {
@@ -62,7 +64,7 @@
public void setEnv(Environment env) {
try {
- CentralisedEnvironment infraEnv = new CentralisedEnvironment(null, runner);
+ CentralisedEnvironment infraEnv = new CentralisedEnvironment(null, RunCentralisedMAS.getRunner());
infraEnv.setUserEnvironment(env);
env.setEnvironmentInfraTier(infraEnv);
setEnvInfraTier(infraEnv);
Added: trunk/applications/as-unit-test/src/jason/tests/TestKQML.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestKQML.java (rev 0)
+++ trunk/applications/as-unit-test/src/jason/tests/TestKQML.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -0,0 +1,115 @@
+package jason.tests;
+
+import jason.asunit.TestAgent;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestKQML {
+
+ TestAgent bob, maria;
+
+ // initialisation of the agents
+ @Before
+ public void setupAgs() {
+ bob = new TestAgent("bob");
+ maria = new TestAgent("maria");
+
+ // defines the agent's AgentSpeak code
+ bob.parseAScode(
+ "+!simple_send <- .send(maria, tell, vl(10)); "+
+ " .send(maria, achieve, goto(10,2)). " +
+
+ "+!send_ask1 <- .send(maria, askOne, vl(_), vl(X)); " +
+ " .send(maria, askOne, vl(_)); " +
+ " act1(X). "+
+ "+!send_ask2 <- .send(maria, askOne, t2(_), A); "+
+ " jason.asunit.print(A). " +
+ "+!send_ask3 <- .send(maria, askOne, t1(_), A); "+
+ " jason.asunit.print(t1,\" \",A). "+
+ "+!send_ask4 <- .send(maria, askOne, fullname, A); "+
+ " jason.asunit.print(A). "+
+
+ "+!send_askAll1 <- .send(maria, askAll, vl(_), L); "+
+ " jason.asunit.print(L). "+
+ "+!send_askAll2 <- .send(maria, askAll, t1(_), L); "+
+ " jason.asunit.print(L). "+
+
+ "+!send_tellHow <- .plan_label(Plan,hp);"+
+ " .send(maria,tellHow,Plan); "+
+ " .send(maria,achieve, hello(bob)). "+
+ "+!send_untellHow <- .send(maria,untellHow,hp). "+
+
+ "@hp +!hello(Who) <- jason.asunit.print(\"Hello \",Who)."
+ );
+
+ maria.parseAScode(
+ "vl(1). vl(2). " +
+ "+!goto(X,Y)[source(Ag)] <- act(X,Y,Ag). "+
+ "+?t2(X) : vl(Y) <- X = 10 + Y."+
+ "+!kqml_received(Sender, askOne, fullname, ReplyWith) <- .send(Sender,tell,\"Maria dos Santos\", ReplyWith). "
+ );
+
+ }
+
+ @Test
+ public void testSend() {
+ bob.addGoal("simple_send");
+ bob.assertIdle(5); // bob sent the messages
+ maria.assertBel("vl(10)", 5); // maria received tell
+ maria.assertAct("act(10,2,bob)", 5); // maria received achieved
+ }
+
+ @Test
+ public void testAsk() {
+ bob.addGoal("send_ask1");
+ bob.addGoal("send_ask2");
+ bob.assertIdle(10); // let bob to send the messages
+ maria.assertIdle(10); // let maria to process the messages
+ bob.assertAct("act1(1)", 5);
+ maria.assertIdle(5);
+ bob.assertBel("vl(1)[source(maria)]", 5); // answer of maria for second askOne (assynchronous)
+
+ bob.assertPrint("t2(11)", 5); // answer for ask2
+ }
+
+ @Test
+ public void testAsk3() {
+ bob.addGoal("send_ask3");
+ bob.assertIdle(10); // let bob to send the messages
+ maria.assertIdle(10); // let maria to process the messages
+ bob.assertPrint("t1 false", 5); // answer for ask3
+
+ bob.addGoal("send_ask4");
+ bob.assertIdle(10);
+ maria.assertIdle(10);
+ bob.assertPrint("Maria dos Santos", 5); // answer for ask3
+ }
+
+ @Test
+ public void testAskAll() {
+ bob.addGoal("simple_send");
+ bob.addGoal("send_askAll1");
+ bob.assertIdle(10);
+ maria.assertIdle(10);
+ bob.assertPrint("[vl(10),vl(1),vl(2)]", 5);
+
+ bob.addGoal("send_askAll2");
+ bob.assertIdle(10);
+ maria.assertIdle(10);
+ bob.assertPrint("[]", 5);
+ }
+
+ @Test
+ public void testTellHow() {
+ bob.addGoal("send_tellHow");
+ bob.assertIdle(10);
+ maria.assertPrint("Hello bob", 10);
+
+ bob.addGoal("send_untellHow");
+ bob.assertIdle(10);
+ maria.assertIdle(10);
+ Assert.assertTrue(maria.getPL().get("hp") == null);
+ }
+}
Modified: trunk/applications/as-unit-test/src/jason/tests/TestVarInContext.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestVarInContext.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/applications/as-unit-test/src/jason/tests/TestVarInContext.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -31,6 +31,8 @@
public void testContext() {
ag.addGoal("test1");
ag.assertPrint("b2", 5);
+ ag.addGoal("test1"); // test twice to see if nothing was changed
+ ag.assertPrint("b2", 5);
ag.addGoal("test2");
ag.assertPrint("error", 5);
Modified: trunk/src/jason/asSemantics/Unifier.java
===================================================================
--- trunk/src/jason/asSemantics/Unifier.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/jason/asSemantics/Unifier.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -136,8 +136,11 @@
boolean ok = unifyTerms(t1g, t2g);
// if np1 is a var that was unified, clear its annots, as in
- // X[An] = p(1)[a]
- // X is mapped to p(1) and not p(1)[a]
+ // X[An] = p(1)[a,b]
+ // X is mapped to p(1) and not p(1)[a,b]
+ // (if the user wants the "remaining" annots, s/he should write
+ // X[An|R] = p(1)[a,b]
+ // X = p(1), An = a, R=[b]
if (ok && np1 != null) { // they are predicates
if (np1.isVar() && np1.hasAnnot()) {
Term np1vl = function.get((VarTerm) np1);
@@ -306,10 +309,10 @@
if (currentVl != null && currentVl instanceof VarsCluster) {
VarsCluster cluster = (VarsCluster) currentVl;
for (VarTerm cvt : cluster)
- function.put(cvt, value); //(Term) value.clone());
+ function.put(cvt, value); //(Term) value.clone()); // the clone is done in apply
} else {
// no value in cluster
- function.put((VarTerm) vt.clone(), value); //(Term) value.clone());
+ function.put((VarTerm) vt.clone(), value); //(Term) value.clone()); // the clone is done in apply
}
return true;
}
Modified: trunk/src/jason/asSyntax/Literal.java
===================================================================
--- trunk/src/jason/asSyntax/Literal.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/jason/asSyntax/Literal.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -125,11 +125,8 @@
*
* Returns an iterator for all unifiers that are logCons.
*/
- @SuppressWarnings("unchecked")
public Iterator<Unifier> logicalConsequence(final Agent ag, final Unifier un) {
- final Literal lclone = (Literal)this.clone();
- lclone.apply(un);
- final Iterator<Literal> il = ag.getBB().getRelevant(lclone);
+ final Iterator<Literal> il = ag.getBB().getRelevant(this);
if (il == null) // no relevant bels
return LogExpr.EMPTY_UNIF_LIST.iterator();
@@ -137,7 +134,7 @@
Unifier current = null;
Iterator<Unifier> ruleIt = null; // current rule solutions iterator
Rule rule; // current rule
- Literal lcloneAnnon = null; // a copy of lclone with makeVarsAnnon
+ Literal cloneAnnon = null; // a copy of the literal with makeVarsAnnon
AgArch arch = ag.getTS().getUserAgArch();
boolean needsUpdate = true;
@@ -169,7 +166,7 @@
rhead.apply(ruleUn);
Unifier unC = (Unifier) un.clone();
- if (unC.unifiesNoUndo(lclone, rhead)) {
+ if (unC.unifiesNoUndo(Literal.this, rhead)) {
current = unC;
return;
}
@@ -185,12 +182,13 @@
// make its vars anonymous,
// it is used to define what will be the unifier used
// inside the rule.
- if (lcloneAnnon == null) {
- lcloneAnnon = (Literal)lclone.clone();
- lcloneAnnon.makeVarsAnnon();
+ if (cloneAnnon == null) {
+ cloneAnnon = (Literal)Literal.this.clone();
+ cloneAnnon.apply(un);
+ cloneAnnon.makeVarsAnnon();
}
Unifier ruleUn = new Unifier();
- if (ruleUn.unifiesNoUndo(lcloneAnnon, rule)) { // the rule head unifies with the literal
+ if (ruleUn.unifiesNoUndo(cloneAnnon, rule)) { // the rule head unifies with the literal
ruleIt = rule.getBody().logicalConsequence(ag,ruleUn);
get();
if (current != null) { // if it get a value
@@ -198,35 +196,8 @@
}
}
} else {
- /* -- the problem below was solved by translating test_rule(A,A) to test_rule(A,A):-true.
- if (!b.isGround()) {
- // All the code below is necessary for situations like
- // test_rule(A,A).
- // !test(test_wrong_value).
- // +!test(A) : test_rule(Test,test_right_value) <- .println("Test = ",Test).
- // where a local variable has the same name as a variable in the belief.
- //
- // So, the solution is
- // 1. create a new empy unifier to unify lclone with b
- // ; lclone is test_rule(Test,test_right_value)
- // ; b is test_rule(A,A)
- // ; u is {A=test_right_value, Test=test_right_value}
- // ; note the value of A in this unifier
- // 2. create another clone b of lclone to apply this
- // unifier u ; c after apply is test_rule(test_right_value,test_right_value)
- // 3. create the result unifier as a clone of the current (un)
- // 4. using the new unifier, unify lclone and
- // b to get only the value of Test and not the A
- // in the result unifier
- Unifier u = new Unifier();
- if (u.unifies(lclone, b)) {
- b = (Literal)lclone.clone();
- b.apply(u);
- }
- }
- */
Unifier u = (Unifier) un.clone();
- if (u.unifiesNoUndo(lclone, b)) {
+ if (u.unifiesNoUndo(Literal.this, b)) {
current = u;
return;
}
Modified: trunk/src/jason/asSyntax/PlanLibrary.java
===================================================================
--- trunk/src/jason/asSyntax/PlanLibrary.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/jason/asSyntax/PlanLibrary.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -183,7 +183,14 @@
return plans.iterator();
}
-
+ /** remove all plans */
+ public void clear() {
+ planLabels.clear();
+ plans.clear();
+ varPlans.clear();
+ relPlans.clear();
+ }
+
/**
* Remove a plan represented by the label <i>pLabel</i>.
* In case the plan has many sources, only the plan's source is removed.
Modified: trunk/src/jason/asSyntax/VarTerm.java
===================================================================
--- trunk/src/jason/asSyntax/VarTerm.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/jason/asSyntax/VarTerm.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -109,7 +109,7 @@
return false;
}
- vl = (Term)vl.clone();
+ vl = (Term)vl.clone(); // should clone here, since there is no cloning in unify
// The below does not conform the rules in manual
//if (vl.isPred() && this.hasAnnot()) { // if this var has annots, add them in the value's annots (Experimental)
// ((Pred)vl).addAnnots(this.getAnnots());
Modified: trunk/src/jason/infra/centralised/CentralisedAgArch.java
===================================================================
--- trunk/src/jason/infra/centralised/CentralisedAgArch.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/jason/infra/centralised/CentralisedAgArch.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -60,7 +60,7 @@
protected CentralisedEnvironment infraEnv = null;
private CentralisedExecutionControl infraControl = null;
- private RunCentralisedMAS masRunner = null;
+ private RunCentralisedMAS masRunner = RunCentralisedMAS.getRunner();
/** The user implementation of the architecture */
protected AgArch userAgArch;
Modified: trunk/src/jason/infra/centralised/CentralisedEnvironment.java
===================================================================
--- trunk/src/jason/infra/centralised/CentralisedEnvironment.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/jason/infra/centralised/CentralisedEnvironment.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -44,7 +44,7 @@
/** the user customisation class for the environment */
private Environment userEnv;
- private RunCentralisedMAS masRunner = null;
+ private RunCentralisedMAS masRunner = RunCentralisedMAS.getRunner();
private boolean running = true;
private static Logger logger = Logger.getLogger(CentralisedEnvironment.class.getName());
Modified: trunk/src/jason/infra/centralised/RunCentralisedMAS.java
===================================================================
--- trunk/src/jason/infra/centralised/RunCentralisedMAS.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/jason/infra/centralised/RunCentralisedMAS.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -86,6 +86,10 @@
public JButton btDebug;
+ public RunCentralisedMAS() {
+ runner = this;
+ }
+
public static void main(String[] args) {
runner = new RunCentralisedMAS();
runner.init(args);
Modified: trunk/src/test/RuleTest.java
===================================================================
--- trunk/src/test/RuleTest.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/test/RuleTest.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -107,8 +107,7 @@
// min([C|T],V,M) :- C < V & min(T,C,M).
// min([_|T],V,M) :- min(T,V,M).
//ag.getBB().add(Literal.parseLiteral("min([],M,M)"));
- ag.getBB().add(new Rule(Literal.parseLiteral("min([],M,M)"),
- LogExpr.parseExpr(".println(fim,M)")));
+ ag.getBB().add(new Rule(Literal.parseLiteral("min([],M,M)"), Literal.LTrue));
ag.getBB().add(new Rule(Literal.parseLiteral("min([op(C)|T], op(V), M)"),
LogExpr.parseExpr("C < V & min(T,op(C),M)")));
ag.getBB().add(new Rule(Literal.parseLiteral("min([op(C)|T], op(V), M)"),
Modified: trunk/src/test/VarTermTest.java
===================================================================
--- trunk/src/test/VarTermTest.java 2008-03-23 13:10:17 UTC (rev 1172)
+++ trunk/src/test/VarTermTest.java 2008-03-24 20:37:34 UTC (rev 1173)
@@ -6,6 +6,7 @@
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ArithExpr;
+import jason.asSyntax.Atom;
import jason.asSyntax.DefaultTerm;
import jason.asSyntax.ListTerm;
import jason.asSyntax.ListTermImpl;
@@ -268,6 +269,11 @@
// X[a,b] = Y[a] - not ok
u = new Unifier();
assertFalse(u.unifies(v2, v1));
+
+ assertTrue(u.unifies(v1, v2));
+ assertTrue(u.unifies(new Atom("vvv"), v1));
+ v1.apply(u);
+ assertEquals("vvv", v1.toString());
}
public void testVarWithAnnots3() {
@@ -276,7 +282,7 @@
VarTerm v2 = VarTerm.parseVar("Y[a,c|R]");
Unifier u = new Unifier();
assertTrue(u.unifies(v1, v2));
- assertEquals(u.get("R").toString(),"[b,d]");
+ assertEquals("[b,d]",u.get("R").toString());
}
public void testVarWithAnnots4() {
@@ -292,6 +298,19 @@
assertFalse(u.unifies(v2, Literal.parseLiteral("open[source(a)]")));
}
+ public void testVarWithAnnots5() {
+ // X[A|R] = p(1)[a,b,c] - ok and
+ // X = p(1), A = a, R=[b,c]
+ VarTerm v = VarTerm.parseVar("X[A|R]");
+ Unifier u = new Unifier();
+ assertTrue(u.unifies(v, Literal.parseLiteral("p(1)[a,b,c]")));
+ assertEquals("[b,c]", u.get("R").toString());
+ assertEquals("a", u.get("A").toString());
+ assertEquals("p(1)", u.get(v).toString());
+ v.apply(u);
+ assertEquals("p(1)", v.toString());
+ }
+
/*
public void testVarWithAnnots5() {
// P -> open[source(a)]
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-23 13:10:21
|
Revision: 1172
http://jason.svn.sourceforge.net/jason/?rev=1172&view=rev
Author: jomifred
Date: 2008-03-23 06:10:17 -0700 (Sun, 23 Mar 2008)
Log Message:
-----------
1. allows free vars in context (e.g. : P[a] | P[b]).
-- see tests/TestVarInContext.java for more examples
2. minor changes in jason-team
Modified Paths:
--------------
trunk/applications/jason-team/src/asl/dummy.asl
trunk/applications/jason-team/src/java/arch/ACArchitecture.java
trunk/applications/jason-team/src/java/arch/ACProxy.java
trunk/applications/jason-team/src/java/arch/WriteStatusThread.java
trunk/src/jason/asSyntax/LogExpr.java
trunk/src/jason/asSyntax/VarTerm.java
trunk/src/test/VarTermTest.java
Added Paths:
-----------
trunk/applications/as-unit-test/build.xml
trunk/applications/as-unit-test/lib/
trunk/applications/as-unit-test/lib/junit.jar
trunk/applications/as-unit-test/src/jason/tests/TestVarInContext.java
Added: trunk/applications/as-unit-test/build.xml
===================================================================
--- trunk/applications/as-unit-test/build.xml (rev 0)
+++ trunk/applications/as-unit-test/build.xml 2008-03-23 13:10:17 UTC (rev 1172)
@@ -0,0 +1,136 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<project basedir="." default="test" name="Jason AS Unit">
+
+ <property environment="env" />
+
+ <property name="jasondir" value="../.." />
+
+ <property name="asunitjar" value="lib/asunit.jar" />
+
+ <property name="build.dir" value="${basedir}/bin" />
+
+ <property name="dist.properties" value="${basedir}/bin/dist.properties" />
+ <property name="version" value="0" />
+ <property name="release" value="0.1" />
+ <property name="distDir" value="${env.HOME}/tmp/x/ASUnit-${version}.${release}" />
+ <property name="distFile" value="${env.HOME}/ASUnit-${version}.${release}" />
+
+ <path id="project.classpath">
+ <pathelement location="${basedir}/lib/junit.jar" />
+ <pathelement location="${jasondir}/lib/jason.jar" />
+ </path>
+
+ <target name="init" >
+ <mkdir dir="${build.dir}" />
+ <mkdir dir="${basedir}/lib" />
+ </target>
+
+ <target name="compile" depends="init">
+ <javac srcdir="src" destdir="${build.dir}" debug="true" deprecation="true" optimize="true" nowarn="true" source="1.5" target="1.5">
+ <classpath refid="project.classpath" />
+ </javac>
+ </target>
+
+
+ <target name="jar" depends="compile">
+ <jar jarfile="${asunitjar}" >
+ <fileset dir="${build.dir}">
+ <include name="jason/asunit/**/*.class" />
+ </fileset>
+ </jar>
+ </target>
+
+ <target name="test" depends="jar">
+ <ant dir="../.." target="jar" />
+ <junit printsummary="yes" failureProperty="test.failure">
+ <classpath refid="project.classpath" />
+ <classpath path="${build.dir}" />
+ <formatter type="plain" usefile="false" />
+ <batchtest>
+ <fileset dir="${basedir}/src" includes="example/**/Test*.java" />
+ <fileset dir="${basedir}/src" includes="jason/tests/**/Test*.java" />
+ </batchtest>
+ </junit>
+ <fail message="test failed" if="test.failure" />
+ <delete failonerror="no" verbose="false">
+ <fileset dir="${basedir}" includes="bookstore.*" />
+ </delete>
+ </target>
+
+ <target name="apidoc" depends="compile">
+ <javadoc
+ destdir="${basedir}/doc/api"
+ packagenames="jason.asunit.*"
+ sourcepath="${basedir}/src"
+ excludepackagenames="jason.asSyntax.parser,jason.mas2j.parser"
+ use="true"
+ version="true"
+ author="true"
+ windowtitle="Jason - AgentSpeak Unit Test">
+ <classpath refid="project.classpath" />
+ </javadoc>
+ </target>
+
+ <target name="dist" depends="jar" description="Build distribution.">
+
+ <echo message="Generating Jason ASUnit ${version}.${release}" />
+
+ <propertyfile file="${dist.properties}">
+ <entry key="version" value="${version}" />
+ <entry key="release" value="${release}" />
+ <!-- entry default="0" key="build" operation="+" type="int" /-->
+ <entry key="build.date" type="date" value="now" />
+ </propertyfile>
+ <property file="${dist.properties}" />
+
+ <fixcrlf eol="crlf" includes="**/*.txt,**/*.bat" srcdir="${basedir}" />
+
+ <delete failonerror="no" includeEmptyDirs="true">
+ <fileset dir="${distDir}" />
+ </delete>
+ <delete dir="${distDir}/.." />
+
+ <mkdir dir="${distDir}" />
+
+ <copy todir="${distDir}">
+ <fileset dir="${basedir}" includes="*.*" />
+ <fileset dir="${basedir}" includes="LICENSE" />
+ <fileset dir="${basedir}" includes="README" />
+
+ <fileset dir="${basedir}" includes="bin/*" excludes="bin/jedit.tgz" />
+ <fileset dir="${basedir}" includes="bin/jedit/**/*" />
+ <fileset dir="${basedir}" includes="doc/**/*" />
+ <fileset dir="${basedir}" includes="examples/**/*" />
+ <fileset dir="${basedir}" includes="demos/**/*" />
+ <fileset dir="${basedir}" includes="lib/**/*" />
+ <fileset dir="${basedir}" includes="src/**/*" />
+ </copy>
+
+ <delete failonerror="no" includeEmptyDirs="true">
+ <fileset dir="${distDir}" includes=".settings" />
+ <fileset dir="${distDir}" includes=".project" />
+ <fileset dir="${distDir}" includes=".classpath" />
+ </delete>
+ <delete dir="${distDir}/bin/classes" />
+ <delete dir="${distDir}/doc/faq" />
+ <delete dir="${distDir}/doc/mini-tutorial/src" />
+
+ <tar compression="gzip" tarfile="${distFile}.tgz">
+ <tarfileset dir="${distDir}/.." mode="755">
+ <include name="Jason-${version}.${release}/**/*.sh" />
+ <include name="Jason-${version}.${release}/**/asl2*" />
+ </tarfileset>
+ <tarfileset dir="${distDir}/..">
+ <include name="Jason-${version}.${release}/**/*" />
+ <exclude name="Jason-${version}.${release}/**/*.sh" />
+ <exclude name="Jason-${version}.${release}/**/asl2*" />
+ </tarfileset>
+ </tar>
+ </target>
+
+ <target name="clean">
+ <delete dir="${build.dir}" />
+ </target>
+
+</project>
Added: trunk/applications/as-unit-test/lib/junit.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/as-unit-test/lib/junit.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/as-unit-test/src/jason/tests/TestVarInContext.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/tests/TestVarInContext.java (rev 0)
+++ trunk/applications/as-unit-test/src/jason/tests/TestVarInContext.java 2008-03-23 13:10:17 UTC (rev 1172)
@@ -0,0 +1,42 @@
+package jason.tests;
+
+import jason.asunit.TestAgent;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class TestVarInContext {
+
+ TestAgent ag;
+
+ // initialisation of the agent test
+ @Before
+ public void setupAg() {
+ ag = new TestAgent();
+ ag.setDebugMode(true);
+
+ // defines the agent's AgentSpeak code
+ ag.parseAScode(
+ "b1[b]. b2[c]. b3[d]. b4[a,d]. "+
+ "+!test1 : P[e] | P[c] <- jason.asunit.print(P). " +
+
+ "+!test2 : P[e] & P[c] <- jason.asunit.print(P). " +
+ "-!test2 <- jason.asunit.print(\"error\"). " +
+
+ "+!test3 : P[a] & P[d] <- jason.asunit.print(P). "
+ );
+ }
+
+ @Test
+ public void testContext() {
+ ag.addGoal("test1");
+ ag.assertPrint("b2", 5);
+
+ ag.addGoal("test2");
+ ag.assertPrint("error", 5);
+
+ ag.addGoal("test3");
+ ag.assertPrint("b4", 5);
+ }
+
+}
Modified: trunk/applications/jason-team/src/asl/dummy.asl
===================================================================
--- trunk/applications/jason-team/src/asl/dummy.asl 2008-03-22 12:30:49 UTC (rev 1171)
+++ trunk/applications/jason-team/src/asl/dummy.asl 2008-03-23 13:10:17 UTC (rev 1172)
@@ -75,7 +75,8 @@
+restart
<- .print("*** restart ***");
- .drop_all_desires;
+ .drop_all_desires;
+ .abolish(target(_,_));
!move.
/* -- tests -- */
Modified: trunk/applications/jason-team/src/java/arch/ACArchitecture.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-22 12:30:49 UTC (rev 1171)
+++ trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-23 13:10:17 UTC (rev 1172)
@@ -142,24 +142,24 @@
}
void newCycle() {
- List<ActionExec> feedback = getTS().getC().getFeedbackActions();
+ logger.info("last action sent is "+lastActionInCurrentCycle+". The following was not sent: "+toExecute);
+ setLastAct(lastActionInCurrentCycle);
+ lastActionInCurrentCycle = null;
// set all actions as successfully executed
+ List<ActionExec> feedback = getTS().getC().getFeedbackActions();
while (!toExecute.isEmpty()) {
ActionExec action = toExecute.poll();
action.setResult(true);
feedback.add(action);
}
-
- logger.info("last action sent is "+lastActionInCurrentCycle);
- setLastAct(lastActionInCurrentCycle);
- lastActionInCurrentCycle = null;
}
synchronized void go() {
notifyAll();
}
synchronized void waitSleep() throws InterruptedException {
+ // TODO: do something by timeout?
wait();
}
Modified: trunk/applications/jason-team/src/java/arch/ACProxy.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/ACProxy.java 2008-03-22 12:30:49 UTC (rev 1171)
+++ trunk/applications/jason-team/src/java/arch/ACProxy.java 2008-03-23 13:10:17 UTC (rev 1172)
@@ -136,6 +136,8 @@
}
}
+ int maxx = 0; // max value of some cell'x
+
public void processRequestAction(Element perception, long currenttime, long deadline) {
try {
@@ -158,8 +160,7 @@
lpos.addTerm(new NumberTermImpl(step));
percepts.add(lpos);
- int maxx = 0; // max value of some cell'x
- int enemyId = 1;
+ int enemyId = 1;
// add in perception what is around
NodeList nl = perception.getElementsByTagName("cell");
for (int i=0; i < nl.getLength(); i++) {
Modified: trunk/applications/jason-team/src/java/arch/WriteStatusThread.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/WriteStatusThread.java 2008-03-22 12:30:49 UTC (rev 1171)
+++ trunk/applications/jason-team/src/java/arch/WriteStatusThread.java 2008-03-23 13:10:17 UTC (rev 1172)
@@ -3,7 +3,6 @@
import jason.environment.grid.Location;
import java.io.PrintWriter;
-import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
Modified: trunk/src/jason/asSyntax/LogExpr.java
===================================================================
--- trunk/src/jason/asSyntax/LogExpr.java 2008-03-22 12:30:49 UTC (rev 1171)
+++ trunk/src/jason/asSyntax/LogExpr.java 2008-03-23 13:10:17 UTC (rev 1172)
@@ -132,12 +132,12 @@
private void get() {
needsUpdate = false;
current = null;
- if (ileft.hasNext())
+ if (ileft != null && ileft.hasNext())
current = ileft.next();
else {
if (iright == null)
iright = getRHS().logicalConsequence(ag,un);
- if (iright.hasNext())
+ if (iright != null && iright.hasNext())
current = iright.next();
}
}
Modified: trunk/src/jason/asSyntax/VarTerm.java
===================================================================
--- trunk/src/jason/asSyntax/VarTerm.java 2008-03-22 12:30:49 UTC (rev 1171)
+++ trunk/src/jason/asSyntax/VarTerm.java 2008-03-23 13:10:17 UTC (rev 1172)
@@ -46,7 +46,7 @@
*
* @author jomi
*/
-public class VarTerm extends InternalActionLiteral implements NumberTerm, ListTerm, StringTerm, ObjectTerm {
+public class VarTerm extends Literal implements NumberTerm, ListTerm, StringTerm, ObjectTerm {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(VarTerm.class.getName());
@@ -110,9 +110,10 @@
}
vl = (Term)vl.clone();
- if (vl.isPred() && this.hasAnnot()) { // if this var has annots, add them in the value's annots (Experimental)
- ((Pred)vl).addAnnots(this.getAnnots());
- }
+ // The below does not conform the rules in manual
+ //if (vl.isPred() && this.hasAnnot()) { // if this var has annots, add them in the value's annots (Experimental)
+ // ((Pred)vl).addAnnots(this.getAnnots());
+ //}
value = vl;
resetHashCodeCache();
@@ -224,6 +225,9 @@
c.apply(un);
if (c.hasValue() && c.getValue() instanceof LogicalFormula) {
return ((LogicalFormula)c.getValue()).logicalConsequence(ag, un);
+ } else {
+ // the variable is still a Var, find all bels that unify.
+ return super.logicalConsequence(ag, un);
}
}
}
Modified: trunk/src/test/VarTermTest.java
===================================================================
--- trunk/src/test/VarTermTest.java 2008-03-22 12:30:49 UTC (rev 1171)
+++ trunk/src/test/VarTermTest.java 2008-03-23 13:10:17 UTC (rev 1172)
@@ -1,5 +1,9 @@
package test;
+import jason.RevisionFailedException;
+import jason.architecture.AgArch;
+import jason.asSemantics.Agent;
+import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ArithExpr;
import jason.asSyntax.DefaultTerm;
@@ -16,6 +20,7 @@
import jason.asSyntax.parser.SimpleCharStream;
import jason.asSyntax.parser.Token;
import jason.asSyntax.parser.as2jTokenManager;
+import jason.infra.centralised.CentralisedAgArch;
import java.io.StringReader;
import java.util.Iterator;
@@ -287,6 +292,7 @@
assertFalse(u.unifies(v2, Literal.parseLiteral("open[source(a)]")));
}
+ /*
public void testVarWithAnnots5() {
// P -> open[source(a)]
// P[source(self)]
@@ -297,7 +303,37 @@
v1.apply(u);
assertEquals(v1.getAnnots().size(), 2);
}
+ */
+
+
+ public void testVarWithAnnotsInLogCons() throws RevisionFailedException {
+ Agent ag = new Agent();
+ AgArch arch = new AgArch();
+ arch.setArchInfraTier(new CentralisedAgArch());
+ ag.setTS(new TransitionSystem(ag, null, null, arch));
+ ag.addBel(Literal.parseLiteral("b1[b]"));
+ ag.addBel(Literal.parseLiteral("b2[d]"));
+
+ Unifier u = new Unifier();
+ VarTerm v1 = VarTerm.parseVar("P[d]");
+ assertEquals(2, iteratorSize(ag.getBB().getRelevant(v1)));
+ Iterator<Unifier> i = v1.logicalConsequence(ag, u);
+ assertTrue(i.hasNext());
+ u = i.next(); // u = {P[d]=b2}
+ v1.apply(u);
+ assertEquals("b2",v1.toString());
+ }
+
+ @SuppressWarnings("unchecked")
+ private int iteratorSize(Iterator i) {
+ int c = 0;
+ while (i.hasNext()) {
+ i.next();
+ c++;
+ }
+ return c;
+ }
public static void main(String[] a) {
new VarTermTest().testVarWithAnnots3();
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-22 12:30:55
|
Revision: 1171
http://jason.svn.sourceforge.net/jason/?rev=1171&view=rev
Author: jomifred
Date: 2008-03-22 05:30:49 -0700 (Sat, 22 Mar 2008)
Log Message:
-----------
improvement in monitoring of agents' activities
Modified Paths:
--------------
trunk/applications/jason-team/AC-Local-JasonTeam.mas2j
trunk/applications/jason-team/readme.txt
trunk/applications/jason-team/src/asl/dummy.asl
trunk/applications/jason-team/src/java/arch/ACArchitecture.java
trunk/applications/jason-team/src/java/arch/CowboyArch.java
trunk/applications/jason-team/src/java/jia/Search.java
trunk/build.xml
trunk/src/jason/JasonException.java
trunk/src/jason/RevisionFailedException.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
Added Paths:
-----------
trunk/applications/jason-team/src/java/arch/WriteStatusThread.java
Modified: trunk/applications/jason-team/AC-Local-JasonTeam.mas2j
===================================================================
--- trunk/applications/jason-team/AC-Local-JasonTeam.mas2j 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/applications/jason-team/AC-Local-JasonTeam.mas2j 2008-03-22 12:30:49 UTC (rev 1171)
@@ -11,7 +11,7 @@
agents:
dummy1 dummy.asl
- [verbose=1, gui=no, write_model=yes, ac_sim_back_dir="./massim-server/backup",
+ [verbose=1, gui=yes, write_status=yes, ac_sim_back_dir="./massim-server/backup",
host="localhost", port=12300, username=participant1, password="1"]
agentArchClass arch.ACArchitecture
agentClass agent.SelectEvent
Modified: trunk/applications/jason-team/readme.txt
===================================================================
--- trunk/applications/jason-team/readme.txt 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/applications/jason-team/readme.txt 2008-03-22 12:30:49 UTC (rev 1171)
@@ -38,7 +38,7 @@
6. you can get the agents location with the command
- tail -f world-state-dummy1.txt
+ tail -f world-status.txt
7. the get the graphical view of some agent, add gui=yes in
the agent's option (.mas2j file)
Modified: trunk/applications/jason-team/src/asl/dummy.asl
===================================================================
--- trunk/applications/jason-team/src/asl/dummy.asl 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/applications/jason-team/src/asl/dummy.asl 2008-03-22 12:30:49 UTC (rev 1171)
@@ -84,6 +84,6 @@
+steps(MaxSteps) <- .println("steps = ",MaxSteps).
+corral(X1,Y1,X2,Y2) <- .println("corral = ",X1,",",Y1," -- ",X2,",",Y2).
-+cell(X,Y,Type) <- .println("cell = ",X,",",Y," = ",Type).
+//+cell(X,Y,Type) <- .println("cell = ",X,",",Y," = ",Type).
+pratio(R) <- .println("pratio = ",R).
+pos(X,Y,S) <- .println("pos = ",X,",",Y,"/",S).
Modified: trunk/applications/jason-team/src/java/arch/ACArchitecture.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-22 12:30:49 UTC (rev 1171)
@@ -127,9 +127,9 @@
class WaitSleep extends Thread {
ActionExec lastAction;
+ String lastActionInCurrentCycle;
Queue<ActionExec> toExecute = new ConcurrentLinkedQueue<ActionExec>();
- String x;
WaitSleep() {
super("WaitSpeepToSendAction");
@@ -151,8 +151,9 @@
feedback.add(action);
}
- logger.info("last action sent is "+x);
- x = null;
+ logger.info("last action sent is "+lastActionInCurrentCycle);
+ setLastAct(lastActionInCurrentCycle);
+ lastActionInCurrentCycle = null;
}
synchronized void go() {
@@ -169,8 +170,8 @@
lastAction = null;
waitSleep();
if (lastAction != null) {
- x = lastAction.getActionTerm().getTerm(0).toString();
- proxy.sendAction(x);
+ lastActionInCurrentCycle = lastAction.getActionTerm().getTerm(0).toString();
+ proxy.sendAction(lastActionInCurrentCycle);
toExecute.offer(lastAction);
}
} catch (InterruptedException e) {
Modified: trunk/applications/jason-team/src/java/arch/CowboyArch.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/CowboyArch.java 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/applications/jason-team/src/java/arch/CowboyArch.java 2008-03-22 12:30:49 UTC (rev 1171)
@@ -13,12 +13,7 @@
import jason.mas2j.ClassParameters;
import jason.runtime.Settings;
-import java.io.PrintWriter;
-import java.util.HashMap;
import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -46,7 +41,7 @@
int cycle = 0;
- WriteModelThread writeModelThread = null;
+ WriteStatusThread writeStatusThread = null;
protected Logger logger = Logger.getLogger(CowboyArch.class.getName());
@@ -60,10 +55,11 @@
public void initAg(String agClass, ClassParameters bbPars, String asSrc, Settings stts) throws JasonException {
super.initAg(agClass, bbPars, asSrc, stts);
gui = "yes".equals(stts.getUserParameter("gui"));
- if ("yes".equals(stts.getUserParameter("write_model"))) {
- writeModelThread = new WriteModelThread();
- writeModelThread.start();
+ if ("yes".equals(stts.getUserParameter("write_status"))) {
+ writeStatusThread = WriteStatusThread.create(this);
}
+ WriteStatusThread.registerAgent(getAgName(), this);
+
// create the viewer for contest simulator
massimBackDir = stts.getUserParameter("ac_sim_back_dir");
if (massimBackDir != null && massimBackDir.startsWith("\""))
@@ -74,7 +70,7 @@
public void stopAg() {
if (view != null) view.dispose();
if (acView != null) acView.finish();
- if (writeModelThread != null) writeModelThread.interrupt();
+ if (writeStatusThread != null) writeStatusThread.interrupt();
super.stopAg();
}
@@ -120,8 +116,8 @@
acView.setPriority(Thread.MIN_PRIORITY);
acView.start();
}
- if (writeModelThread != null)
- writeModelThread.reset();
+ if (writeStatusThread != null)
+ writeStatusThread.reset();
}
/** The perception of the corral location is removed from the percepts list
@@ -168,10 +164,29 @@
lo5 = new Location(-1,-1),
lo6 = new Location(-1,-1);
+
+ Location oldLoc;
+ /** the location in previous cycle */
+ public Location getLastLocation() {
+ return oldLoc;
+ }
+ protected String lastAct;
+ protected void setLastAct(String act) {
+ lastAct = act;
+ }
+ public String getLastAction() {
+ return lastAct;
+ }
+
+ public int getCycle() {
+ return cycle;
+ }
+
+
/** update the model with the agent location and share this information with team mates */
void locationPerceived(int x, int y) {
- Location oldLoc = model.getAgPos(getMyId());
+ oldLoc = model.getAgPos(getMyId());
if (oldLoc != null) {
model.clearAgView(oldLoc); // clear golds and enemies
}
@@ -239,7 +254,7 @@
void setCycle(int s) {
cycle = s;
if (view != null) view.setCycle(cycle);
- if (writeModelThread != null) writeModelThread.go();
+ if (writeStatusThread != null) writeStatusThread.go();
}
void setScore(int s) {
@@ -315,75 +330,4 @@
return (Integer.parseInt(agName.substring(agName.length()-1))) - 1;
}
-
-
- class WriteModelThread extends Thread {
-
- Map<Integer,List<Location>> locations;
-
- public void reset() {
- // init locations
- locations = new HashMap<Integer, List<Location>>();
- for (int i=0; i<WorldModel.agsByTeam; i++) {
- locations.put(i, new LinkedList<Location>());
- }
- }
-
- public void run() {
- reset();
-
- String fileName = "world-state-"+getAgName()+".txt";
- PrintWriter out = null;
- try {
- out = new PrintWriter(fileName);
- while (true) {
- try {
- waitSomeTime();
- if (model != null && playing) {
- //out.println("\n\n** Agent "+getAgName()+" in cycle "+cycle+"\n");
- //for (int i=0; i<model.getNbOfAgs(); i++) {
- // out.println("miner"+(i+1)+" is carrying "+model.getGoldsWithAg(i)+" gold(s), at "+model.getAgPos(i));
- //}
- //out.println(model.toString());
- StringBuilder s = new StringBuilder(String.format("Step %5d : ", cycle));
- for (int i=0; i<WorldModel.agsByTeam; i++) {
- Location agp = model.getAgPos(i);
- if (agp != null) {
- // count how long the agent is in the same location
- int c = 0;
- Iterator<Location> il = locations.get(i).iterator();
- while (il.hasNext() && il.next().equals(agp) && c <= 11) {
- c++;
- }
- String sc = "*";
- if (c < 10) sc = ""+c;
-
- locations.get(i).add(0,agp);
- s.append(String.format("%5d,%2d/%s", agp.x, agp.y, sc));
- }
- }
- logger.info(s.toString());
- out.println(s.toString());
- out.flush();
- }
- } catch (InterruptedException e) { // no problem, quit the thread
- return;
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- out.close();
- }
- }
-
- synchronized private void waitSomeTime() throws InterruptedException {
- wait(4000);
- }
- synchronized private void go() {
- notifyAll();
- }
- }
}
Added: trunk/applications/jason-team/src/java/arch/WriteStatusThread.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/WriteStatusThread.java (rev 0)
+++ trunk/applications/jason-team/src/java/arch/WriteStatusThread.java 2008-03-22 12:30:49 UTC (rev 1171)
@@ -0,0 +1,123 @@
+package arch;
+
+import jason.environment.grid.Location;
+
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Logger;
+
+import env.WorldModel;
+
+public class WriteStatusThread extends Thread {
+
+ protected Logger logger = Logger.getLogger(WriteStatusThread.class.getName());
+
+ // singleton
+ static WriteStatusThread instance = null;
+ private WriteStatusThread() {}
+
+ public static WriteStatusThread create(CowboyArch owner) {
+ if (instance == null) {
+ instance = new WriteStatusThread();
+ instance.owner = owner;
+ instance.start();
+ }
+ return instance;
+ }
+ public static boolean isCreated() {
+ return instance != null;
+ }
+
+ private CowboyArch owner = null;
+
+ private static CowboyArch[] agents = new CowboyArch[WorldModel.agsByTeam];
+
+ public static void registerAgent(String name, CowboyArch arch) {
+ agents[arch.getMyId()] = arch;
+ }
+
+ Map<Integer,List<Location>> locations;
+
+ public void reset() {
+ // init locations
+ locations = new HashMap<Integer, List<Location>>();
+ for (int i=0; i<WorldModel.agsByTeam; i++) {
+ locations.put(i, new LinkedList<Location>());
+ }
+ }
+
+ public void run() {
+ reset();
+
+ String fileName = "world-status.txt";
+ PrintWriter out = null;
+ try {
+ out = new PrintWriter(fileName);
+ while (true) {
+ try {
+ waitNextCycle();
+ //out.println("\n\n** Agent "+getAgName()+" in cycle "+cycle+"\n");
+ //for (int i=0; i<model.getNbOfAgs(); i++) {
+ // out.println("miner"+(i+1)+" is carrying "+model.getGoldsWithAg(i)+" gold(s), at "+model.getAgPos(i));
+ //}
+ //out.println(model.toString());
+ StringBuilder s = new StringBuilder(String.format("Step %5d : ", owner.getCycle()-1));
+ for (int agId=0; agId<WorldModel.agsByTeam; agId++) {
+ Location agp = agents[agId].getLastLocation();
+ if (agp != null) {
+ // count how long the agent is in the same location
+ int c = 0;
+ Iterator<Location> il = locations.get(agId).iterator();
+ while (il.hasNext() && il.next().equals(agp) && c <= 11) {
+ c++;
+ }
+ String sc = "*";
+ if (c < 10) sc = ""+c;
+
+ locations.get(agId).add(0,agp);
+ String lastAct = shortActionFormat(agents[agId].getLastAction());
+ s.append(String.format("%5d,%2d/%s %s", agp.x, agp.y, sc, lastAct));
+ }
+ }
+ logger.info(s.toString());
+ out.println(s.toString());
+ out.flush();
+ } catch (InterruptedException e) { // no problem, quit the thread
+ return;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ out.close();
+ }
+ }
+
+ public String shortActionFormat(String act) {
+ if (act.equals(WorldModel.Move.east.toString())) return "e ";
+ if (act.equals(WorldModel.Move.northeast.toString())) return "ne";
+ if (act.equals(WorldModel.Move.southeast.toString())) return "se";
+ if (act.equals(WorldModel.Move.west.toString())) return "w ";
+ if (act.equals(WorldModel.Move.northwest.toString())) return "nw";
+ if (act.equals(WorldModel.Move.southwest.toString())) return "sw";
+ if (act.equals(WorldModel.Move.north.toString())) return "n ";
+ if (act.equals(WorldModel.Move.south.toString())) return "s ";
+ return act;
+ }
+
+ synchronized private void waitNextCycle() throws InterruptedException {
+ wait(10000);
+ }
+
+ synchronized void go() {
+ notifyAll();
+ }
+
+}
Modified: trunk/applications/jason-team/src/java/jia/Search.java
===================================================================
--- trunk/applications/jason-team/src/java/jia/Search.java 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/applications/jason-team/src/java/jia/Search.java 2008-03-22 12:30:49 UTC (rev 1171)
@@ -177,7 +177,7 @@
if (ia.model.isFreeOfObstacle(newl) && !ia.model.hasObject(WorldModel.CORRAL, newl)) {
if (ia.considerAgentsAsObstacles) {
- if (ia.model.isFree(newl) || ia.from.distance(newl) > 1) {
+ if ((ia.model.isFree(WorldModel.AGENT,newl) && ia.model.isFree(WorldModel.COW,newl)) || ia.from.distance(newl) > 3) {
s.add(new GridState(newl,op,ia));
}
} else {
Modified: trunk/build.xml
===================================================================
--- trunk/build.xml 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/build.xml 2008-03-22 12:30:49 UTC (rev 1171)
@@ -304,7 +304,7 @@
<target name="clean">
<delete failonerror="no" includeEmptyDirs="true" verbose="true">
<fileset defaultexcludes="no" dir="${basedir}" includes="**/*~" />
- <fileset dir="${basedir}" includes="**/*.class" />
+ <fileset dir="${basedir}" includes="**/*.class" excludes="applications/**/*"/>
<fileset dir="${basedir}" includes="**/core" />
<fileset dir="${basedir}/doc/api" includes="**/*" />
<fileset dir="${basedir}" includes="**/.nbattrs" />
Modified: trunk/src/jason/JasonException.java
===================================================================
--- trunk/src/jason/JasonException.java 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/src/jason/JasonException.java 2008-03-22 12:30:49 UTC (rev 1171)
@@ -19,14 +19,6 @@
// http://www.dur.ac.uk/r.bordini
// http://www.inf.furb.br/~jomi
//
-// CVS information:
-// $Date$
-// $Revision$
-// $Log$
-// Revision 1.3 2005/08/12 22:26:08 jomifred
-// add cvs keywords
-//
-//
//----------------------------------------------------------------------------
Modified: trunk/src/jason/RevisionFailedException.java
===================================================================
--- trunk/src/jason/RevisionFailedException.java 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/src/jason/RevisionFailedException.java 2008-03-22 12:30:49 UTC (rev 1171)
@@ -19,14 +19,6 @@
// http://www.dur.ac.uk/r.bordini
// http://www.inf.furb.br/~jomi
//
-// CVS information:
-// $Date: 2007-02-19 16:53:54 +0100 (Mon, 19 Feb 2007) $
-// $Revision: 751 $
-// $Log$
-// Revision 1.3 2005/08/12 22:26:08 jomifred
-// add cvs keywords
-//
-//
//----------------------------------------------------------------------------
package jason;
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-22 12:30:49 UTC (rev 1171)
@@ -57,6 +57,7 @@
private static Config config = Config.get();
public void setAg(Agent ag) { curAg = ag; }
+
private String getSourceRef(Object o) {
if (o instanceof SourceInfo) {
SourceInfo s = (SourceInfo)o;
@@ -65,6 +66,7 @@
return "";
}
}
+
private InternalActionLiteral checkInternalActionsInContext(LogicalFormula f, Agent ag) throws Exception {
if (f != null) {
if (f instanceof InternalActionLiteral) {
@@ -82,6 +84,7 @@
}
return null;
}
+
private ArithFunction getArithFunction(Structure l) {
ArithFunction af = null;
if (curAg != null)
@@ -91,7 +94,19 @@
// try global function
af = FunctionRegister.getFunction(l.getFunctor(), l.getArity());
return af;
- }
+ }
+
+ private Term changeToAtom(Object o) {
+ Term u = (Term)o;
+ if (u.isAtom()) {
+ Atom a = new Atom( ((Structure)u).getFunctor());
+ a.setSrc(u);
+ return a;
+ } else {
+ return u;
+ }
+ }
+
}
PARSER_END(as2j)
@@ -428,30 +443,21 @@
}
-Term term() : { Term u; Object o; Atom a; }
+Term term() : { Object o;}
{
- ( u=list()
- | o=arithm_expr() { u = (Term)o; // arithm expr includes literals/atoms/structures
- if (u.isAtom()) {
- a = new Atom( ((Structure)u).getFunctor());
- a.setSrc(u);
- return a;
- }
- return u;
- }
- | u=string()
+ ( o=list()
+ | o=log_expr() // log expr includes literals/atoms/structures
)
- { return u; }
+ { return changeToAtom(o); }
}
-ListTermImpl list() : { ListTermImpl lt = new ListTermImpl(); ListTerm last;
- Token K; Term f; }
+ListTermImpl list() : { ListTermImpl lt = new ListTermImpl(); ListTerm last; Token K; Term f; }
{
"["
[
- f=term() { last = lt.append(f); lt.setSrcLine(f.getSrcLine()); lt.setSrc(f.getSrc());}
- ( "," f=term() { last = last.append(f); }
+ f=term_in_list() { last = lt.append(f); lt.setSrcLine(f.getSrcLine()); lt.setSrc(f.getSrc());}
+ ( "," f=term_in_list() { last = last.append(f); }
)*
[ "|" ( K=<VAR> { last.setNext(new VarTerm(K.image)); }
| K=<UNNAMEDVAR> { last.setNext(new UnnamedVar(K.image)); }
@@ -462,23 +468,31 @@
"]" { return lt; }
}
+// term_in_list is the same as term, but log_expr must be enclosed by "("....")" to avoid problem with |
+Term term_in_list() : { Object o; }
+{
+ ( o=list()
+ | o=arithm_expr()
+ | o=string()
+ )
+ { return changeToAtom(o); }
+}
+
/* logical expression */
-Object log_expr() :
- { Object t1, t2; }
+Object log_expr() : { Object t1, t2; }
{
t1 = log_expr_trm()
-[ "|" t2 = log_expr() { return new LogExpr((LogicalFormula)t1,LogicalOp.or,(LogicalFormula)t2); } ]
- { return t1; }
+ [ "|" t2 = log_expr() { return new LogExpr((LogicalFormula)t1,LogicalOp.or,(LogicalFormula)t2); } ]
+ { return t1; }
}
-Object log_expr_trm() :
- { Object t1, t2; }
+Object log_expr_trm() : { Object t1, t2; }
{
t1 = log_expr_factor()
-[ "&" t2 = log_expr_trm() { return new LogExpr((LogicalFormula)t1,LogicalOp.and,(LogicalFormula)t2); } ]
- { return t1; }
+[ "&" t2 = log_expr_trm() { return new LogExpr((LogicalFormula)t1,LogicalOp.and,(LogicalFormula)t2); } ]
+ { return t1; }
}
Object log_expr_factor():
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2008-03-21 15:35:38 UTC (rev 1170)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2008-03-22 12:30:49 UTC (rev 1171)
@@ -27,6 +27,7 @@
private static Config config = Config.get();
public void setAg(Agent ag) { curAg = ag; }
+
private String getSourceRef(Object o) {
if (o instanceof SourceInfo) {
SourceInfo s = (SourceInfo)o;
@@ -35,6 +36,7 @@
return "";
}
}
+
private InternalActionLiteral checkInternalActionsInContext(LogicalFormula f, Agent ag) throws Exception {
if (f != null) {
if (f instanceof InternalActionLiteral) {
@@ -52,6 +54,7 @@
}
return null;
}
+
private ArithFunction getArithFunction(Structure l) {
ArithFunction af = null;
if (curAg != null)
@@ -63,6 +66,17 @@
return af;
}
+ private Term changeToAtom(Object o) {
+ Term u = (Term)o;
+ if (u.isAtom()) {
+ Atom a = new Atom( ((Structure)u).getFunctor());
+ a.setSrc(u);
+ return a;
+ } else {
+ return u;
+ }
+ }
+
/* AgentSpeak Grammar */
/* agent ::= bels goals plans
@@ -648,46 +662,37 @@
}
final public Term term() throws ParseException {
- Term u; Object o; Atom a;
+ Object o;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 42:
- u = list();
+ o = list();
break;
case VAR:
case TK_TRUE:
case TK_FALSE:
+ case TK_NOT:
case TK_NEG:
case TK_BEGIN:
case TK_END:
case NUMBER:
+ case STRING:
case ATOM:
case UNNAMEDVAR:
case 35:
case 39:
- o = arithm_expr();
- u = (Term)o; // arithm expr includes literals/atoms/structures
- if (u.isAtom()) {
- a = new Atom( ((Structure)u).getFunctor());
- a.setSrc(u);
- {if (true) return a;}
- }
- {if (true) return u;}
+ o = log_expr();
break;
- case STRING:
- u = string();
- break;
default:
jj_la1[28] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
- {if (true) return u;}
+ {if (true) return changeToAtom(o);}
throw new Error("Missing return statement in function");
}
final public ListTermImpl list() throws ParseException {
- ListTermImpl lt = new ListTermImpl(); ListTerm last;
- Token K; Term f;
+ ListTermImpl lt = new ListTermImpl(); ListTerm last; Token K; Term f;
jj_consume_token(42);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case VAR:
@@ -703,7 +708,7 @@
case 35:
case 39:
case 42:
- f = term();
+ f = term_in_list();
last = lt.append(f); lt.setSrcLine(f.getSrcLine()); lt.setSrc(f.getSrc());
label_10:
while (true) {
@@ -716,7 +721,7 @@
break label_10;
}
jj_consume_token(41);
- f = term();
+ f = term_in_list();
last = last.append(f);
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
@@ -755,38 +760,70 @@
throw new Error("Missing return statement in function");
}
+// term_in_list is the same as term, but log_expr must be enclosed by "("....")" to avoid problem with |
+ final public Term term_in_list() throws ParseException {
+ Object o;
+ switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
+ case 42:
+ o = list();
+ break;
+ case VAR:
+ case TK_TRUE:
+ case TK_FALSE:
+ case TK_NEG:
+ case TK_BEGIN:
+ case TK_END:
+ case NUMBER:
+ case ATOM:
+ case UNNAMEDVAR:
+ case 35:
+ case 39:
+ o = arithm_expr();
+ break;
+ case STRING:
+ o = string();
+ break;
+ default:
+ jj_la1[33] = jj_gen;
+ jj_consume_token(-1);
+ throw new ParseException();
+ }
+ {if (true) return changeToAtom(o);}
+ throw new Error("Missing return statement in function");
+ }
+
/* logical expression */
final public Object log_expr() throws ParseException {
- Object t1, t2;
+ Object t1, t2;
t1 = log_expr_trm();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 43:
jj_consume_token(43);
t2 = log_expr();
- {if (true) return new LogExpr((LogicalFormula)t1,LogicalOp.or,(LogicalFormula)t2);}
+ {if (true) return new LogExpr((LogicalFormula)t1,LogicalOp.or,(LogicalFormula)t2);}
break;
default:
- jj_la1[33] = jj_gen;
+ jj_la1[34] = jj_gen;
;
}
- {if (true) return t1;}
+ {if (true) return t1;}
throw new Error("Missing return statement in function");
}
final public Object log_expr_trm() throws ParseException {
- Object t1, t2;
+ Object t1, t2;
t1 = log_expr_factor();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 45:
jj_consume_token(45);
t2 = log_expr_trm();
- {if (true) return new LogExpr((LogicalFormula)t1,LogicalOp.and,(LogicalFormula)t2);}
+ {if (true) return new LogExpr((LogicalFormula)t1,LogicalOp.and,(LogicalFormula)t2);}
break;
default:
- jj_la1[34] = jj_gen;
+ jj_la1[35] = jj_gen;
;
}
- {if (true) return t1;}
+ {if (true) return t1;}
throw new Error("Missing return statement in function");
}
@@ -814,7 +851,7 @@
{if (true) return t;}
break;
default:
- jj_la1[35] = jj_gen;
+ jj_la1[36] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -850,7 +887,7 @@
op1 = string();
break;
default:
- jj_la1[36] = jj_gen;
+ jj_la1[37] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -897,7 +934,7 @@
operator = RelationalOp.literalBuilder;
break;
default:
- jj_la1[37] = jj_gen;
+ jj_la1[38] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -922,7 +959,7 @@
op2 = list();
break;
default:
- jj_la1[38] = jj_gen;
+ jj_la1[39] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -933,7 +970,7 @@
{if (true) return new RelExpr((Term)op1, operator, (Term)op2);}
break;
default:
- jj_la1[39] = jj_gen;
+ jj_la1[40] = jj_gen;
;
}
{if (true) return op1;}
@@ -958,7 +995,7 @@
op = ArithmeticOp.minus;
break;
default:
- jj_la1[40] = jj_gen;
+ jj_la1[41] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -972,7 +1009,7 @@
{if (true) return new ArithExpr((NumberTerm)t1, op, (NumberTerm)t2);}
break;
default:
- jj_la1[41] = jj_gen;
+ jj_la1[42] = jj_gen;
;
}
{if (true) return t1;}
@@ -1006,7 +1043,7 @@
op = ArithmeticOp.mod;
break;
default:
- jj_la1[42] = jj_gen;
+ jj_la1[43] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1020,7 +1057,7 @@
{if (true) return new ArithExpr((NumberTerm)t1, op, (NumberTerm)t2);}
break;
default:
- jj_la1[43] = jj_gen;
+ jj_la1[44] = jj_gen;
;
}
{if (true) return t1;}
@@ -1045,7 +1082,7 @@
{if (true) return new ArithExpr((NumberTerm)t1, op, (NumberTerm)t2);}
break;
default:
- jj_la1[44] = jj_gen;
+ jj_la1[45] = jj_gen;
;
}
{if (true) return t1;}
@@ -1091,7 +1128,7 @@
{if (true) return t;}
break;
default:
- jj_la1[45] = jj_gen;
+ jj_la1[46] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1126,7 +1163,7 @@
v = new UnnamedVar(K.image);
break;
default:
- jj_la1[46] = jj_gen;
+ jj_la1[47] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
@@ -1136,7 +1173,7 @@
v.setAnnots(lt);
break;
default:
- jj_la1[47] = jj_gen;
+ jj_la1[48] = jj_gen;
;
}
{if (true) return v;}
@@ -1167,95 +1204,6 @@
finally { jj_save(1, xla); }
}
- final private boolean jj_3R_71() {
- if (jj_scan_token(TK_INTMOD)) return true;
- return false;
- }
-
- final private boolean jj_3R_70() {
- if (jj_scan_token(TK_INTDIV)) return true;
- return false;
- }
-
- final private boolean jj_3R_19() {
- if (jj_scan_token(39)) return true;
- if (jj_3R_25()) return true;
- if (jj_scan_token(40)) return true;
- return false;
- }
-
- final private boolean jj_3R_69() {
- if (jj_scan_token(55)) return true;
- return false;
- }
-
- final private boolean jj_3R_18() {
- if (jj_3R_24()) return true;
- return false;
- }
-
- final private boolean jj_3R_68() {
- if (jj_scan_token(54)) return true;
- return false;
- }
-
- final private boolean jj_3R_17() {
- if (jj_3R_23()) return true;
- return false;
- }
-
- final private boolean jj_3R_22() {
- if (jj_scan_token(34)) return true;
- return false;
- }
-
- final private boolean jj_3R_63() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_68()) {
- jj_scanpos = xsp;
- if (jj_3R_69()) {
- jj_scanpos = xsp;
- if (jj_3R_70()) {
- jj_scanpos = xsp;
- if (jj_3R_71()) return true;
- }
- }
- }
- return false;
- }
-
- final private boolean jj_3R_60() {
- if (jj_3R_62()) return true;
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_63()) jj_scanpos = xsp;
- return false;
- }
-
- final private boolean jj_3R_16() {
- if (jj_scan_token(35)) return true;
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_22()) jj_scanpos = xsp;
- return false;
- }
-
- final private boolean jj_3R_15() {
- if (jj_scan_token(34)) return true;
- return false;
- }
-
- final private boolean jj_3R_14() {
- if (jj_scan_token(36)) return true;
- return false;
- }
-
- final private boolean jj_3R_13() {
- if (jj_scan_token(38)) return true;
- return false;
- }
-
final private boolean jj_3R_12() {
if (jj_scan_token(31)) return true;
return false;
@@ -1288,46 +1236,41 @@
return false;
}
- final private boolean jj_3R_65() {
+ final private boolean jj_3R_68() {
if (jj_scan_token(35)) return true;
return false;
}
- final private boolean jj_3R_64() {
+ final private boolean jj_3R_67() {
if (jj_scan_token(34)) return true;
return false;
}
- final private boolean jj_3R_61() {
+ final private boolean jj_3R_64() {
Token xsp;
xsp = jj_scanpos;
- if (jj_3R_64()) {
+ if (jj_3R_67()) {
jj_scanpos = xsp;
- if (jj_3R_65()) return true;
+ if (jj_3R_68()) return true;
}
return false;
}
- final private boolean jj_3R_50() {
- if (jj_3R_60()) return true;
+ final private boolean jj_3R_53() {
+ if (jj_3R_63()) return true;
Token xsp;
xsp = jj_scanpos;
- if (jj_3R_61()) jj_scanpos = xsp;
+ if (jj_3R_64()) jj_scanpos = xsp;
return false;
}
- final private boolean jj_3R_59() {
- if (jj_scan_token(53)) return true;
- return false;
- }
-
final private boolean jj_3R_29() {
if (jj_scan_token(TK_FALSE)) return true;
return false;
}
- final private boolean jj_3R_58() {
- if (jj_scan_token(52)) return true;
+ final private boolean jj_3R_62() {
+ if (jj_scan_token(53)) return true;
return false;
}
@@ -1336,45 +1279,44 @@
return false;
}
- final private boolean jj_3R_57() {
+ final private boolean jj_3R_61() {
+ if (jj_scan_token(52)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_60() {
if (jj_scan_token(51)) return true;
return false;
}
- final private boolean jj_3R_56() {
+ final private boolean jj_3R_59() {
if (jj_scan_token(50)) return true;
return false;
}
- final private boolean jj_3R_55() {
+ final private boolean jj_3R_58() {
if (jj_scan_token(49)) return true;
return false;
}
- final private boolean jj_3R_54() {
+ final private boolean jj_3R_57() {
if (jj_scan_token(48)) return true;
return false;
}
- final private boolean jj_3R_53() {
+ final private boolean jj_3R_56() {
if (jj_scan_token(47)) return true;
return false;
}
- final private boolean jj_3R_52() {
+ final private boolean jj_3R_55() {
if (jj_scan_token(46)) return true;
return false;
}
- final private boolean jj_3R_49() {
+ final private boolean jj_3R_50() {
Token xsp;
xsp = jj_scanpos;
- if (jj_3R_52()) {
- jj_scanpos = xsp;
- if (jj_3R_53()) {
- jj_scanpos = xsp;
- if (jj_3R_54()) {
- jj_scanpos = xsp;
if (jj_3R_55()) {
jj_scanpos = xsp;
if (jj_3R_56()) {
@@ -1383,7 +1325,13 @@
jj_scanpos = xsp;
if (jj_3R_58()) {
jj_scanpos = xsp;
- if (jj_3R_59()) return true;
+ if (jj_3R_59()) {
+ jj_scanpos = xsp;
+ if (jj_3R_60()) {
+ jj_scanpos = xsp;
+ if (jj_3R_61()) {
+ jj_scanpos = xsp;
+ if (jj_3R_62()) return true;
}
}
}
@@ -1399,13 +1347,13 @@
return false;
}
- final private boolean jj_3R_48() {
- if (jj_3R_51()) return true;
+ final private boolean jj_3R_49() {
+ if (jj_3R_54()) return true;
return false;
}
- final private boolean jj_3R_47() {
- if (jj_3R_50()) return true;
+ final private boolean jj_3R_48() {
+ if (jj_3R_53()) return true;
return false;
}
@@ -1433,12 +1381,12 @@
final private boolean jj_3R_43() {
Token xsp;
xsp = jj_scanpos;
- if (jj_3R_47()) {
+ if (jj_3R_48()) {
jj_scanpos = xsp;
- if (jj_3R_48()) return true;
+ if (jj_3R_49()) return true;
}
xsp = jj_scanpos;
- if (jj_3R_49()) jj_scanpos = xsp;
+ if (jj_3R_50()) jj_scanpos = xsp;
return false;
}
@@ -1489,35 +1437,58 @@
return false;
}
- final private boolean jj_3R_38() {
- if (jj_3R_42()) return true;
+ final private boolean jj_3R_47() {
+ if (jj_3R_54()) return true;
return false;
}
- final private boolean jj_3R_51() {
- if (jj_scan_token(STRING)) return true;
+ final private boolean jj_3R_46() {
+ if (jj_3R_53()) return true;
return false;
}
- final private boolean jj_3R_26() {
- if (jj_scan_token(42)) return true;
+ final private boolean jj_3R_45() {
+ if (jj_3R_26()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_42() {
Token xsp;
xsp = jj_scanpos;
- if (jj_3R_38()) jj_scanpos = xsp;
- if (jj_scan_token(44)) return true;
+ if (jj_3R_45()) {
+ jj_scanpos = xsp;
+ if (jj_3R_46()) {
+ jj_scanpos = xsp;
+ if (jj_3R_47()) return true;
+ }
+ }
return false;
}
+ final private boolean jj_3R_54() {
+ if (jj_scan_token(STRING)) return true;
+ return false;
+ }
+
final private boolean jj_3R_32() {
if (jj_3R_26()) return true;
return false;
}
- final private boolean jj_3R_46() {
- if (jj_3R_51()) return true;
+ final private boolean jj_3R_38() {
+ if (jj_3R_42()) return true;
return false;
}
+ final private boolean jj_3R_26() {
+ if (jj_scan_token(42)) return true;
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_38()) jj_scanpos = xsp;
+ if (jj_scan_token(44)) return true;
+ return false;
+ }
+
final private boolean jj_3R_31() {
if (jj_scan_token(UNNAMEDVAR)) return true;
return false;
@@ -1540,36 +1511,33 @@
return false;
}
- final private boolean jj_3R_45() {
- if (jj_3R_50()) return true;
+ final private boolean jj_3R_52() {
+ if (jj_3R_25()) return true;
return false;
}
- final private boolean jj_3R_44() {
+ final private boolean jj_3R_51() {
if (jj_3R_26()) return true;
return false;
}
- final private boolean jj_3R_42() {
+ final private boolean jj_3R_44() {
Token xsp;
xsp = jj_scanpos;
- if (jj_3R_44()) {
+ if (jj_3R_51()) {
jj_scanpos = xsp;
- if (jj_3R_45()) {
- jj_scanpos = xsp;
- if (jj_3R_46()) return true;
+ if (jj_3R_52()) return true;
}
- }
return false;
}
- final private boolean jj_3R_77() {
+ final private boolean jj_3R_80() {
if (jj_3R_23()) return true;
return false;
}
final private boolean jj_3R_41() {
- if (jj_3R_42()) return true;
+ if (jj_3R_44()) return true;
return false;
}
@@ -1578,17 +1546,17 @@
return false;
}
- final private boolean jj_3R_76() {
- if (jj_3R_77()) return true;
+ final private boolean jj_3R_79() {
+ if (jj_3R_80()) return true;
return false;
}
- final private boolean jj_3R_75() {
+ final private boolean jj_3R_78() {
if (jj_3R_24()) return true;
return false;
}
- final private boolean jj_3R_74() {
+ final private boolean jj_3R_77() {
if (jj_scan_token(39)) return true;
if (jj_3R_25()) return true;
return false;
@@ -1608,29 +1576,29 @@
return false;
}
- final private boolean jj_3R_73() {
+ final private boolean jj_3R_76() {
if (jj_scan_token(35)) return true;
- if (jj_3R_66()) return true;
+ if (jj_3R_69()) return true;
return false;
}
- final private boolean jj_3R_72() {
+ final private boolean jj_3R_75() {
if (jj_scan_token(NUMBER)) return true;
return false;
}
- final private boolean jj_3R_66() {
+ final private boolean jj_3R_69() {
Token xsp;
xsp = jj_scanpos;
- if (jj_3R_72()) {
+ if (jj_3R_75()) {
jj_scanpos = xsp;
- if (jj_3R_73()) {
+ if (jj_3R_76()) {
jj_scanpos = xsp;
- if (jj_3R_74()) {
+ if (jj_3R_77()) {
jj_scanpos = xsp;
- if (jj_3R_75()) {
+ if (jj_3R_78()) {
jj_scanpos = xsp;
- if (jj_3R_76()) return true;
+ if (jj_3R_79()) return true;
}
}
}
@@ -1655,19 +1623,108 @@
return false;
}
- final private boolean jj_3R_67() {
+ final private boolean jj_3R_70() {
if (jj_scan_token(56)) return true;
return false;
}
- final private boolean jj_3R_62() {
- if (jj_3R_66()) return true;
+ final private boolean jj_3R_65() {
+ if (jj_3R_69()) return true;
Token xsp;
xsp = jj_scanpos;
- if (jj_3R_67()) jj_scanpos = xsp;
+ if (jj_3R_70()) jj_scanpos = xsp;
return false;
}
+ final private boolean jj_3R_74() {
+ if (jj_scan_token(TK_INTMOD)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_19() {
+ if (jj_scan_token(39)) return true;
+ if (jj_3R_25()) return true;
+ if (jj_scan_token(40)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_73() {
+ if (jj_scan_token(TK_INTDIV)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_18() {
+ if (jj_3R_24()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_72() {
+ if (jj_scan_token(55)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_17() {
+ if (jj_3R_23()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_22() {
+ if (jj_scan_token(34)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_71() {
+ if (jj_scan_token(54)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_66() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_71()) {
+ jj_scanpos = xsp;
+ if (jj_3R_72()) {
+ jj_scanpos = xsp;
+ if (jj_3R_73()) {
+ jj_scanpos = xsp;
+ if (jj_3R_74()) return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ final private boolean jj_3R_63() {
+ if (jj_3R_65()) return true;
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_66()) jj_scanpos = xsp;
+ return false;
+ }
+
+ final private boolean jj_3R_16() {
+ if (jj_scan_token(35)) return true;
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_22()) jj_scanpos = xsp;
+ return false;
+ }
+
+ final private boolean jj_3R_15() {
+ if (jj_scan_token(34)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_14() {
+ if (jj_scan_token(36)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_13() {
+ if (jj_scan_token(38)) return true;
+ return false;
+ }
+
public as2jTokenManager token_source;
SimpleCharStream jj_input_stream;
public Token token, jj_nt;
@@ -1677,7 +1734,7 @@
public boolean lookingAhead = false;
private boolean jj_semLA;
private int jj_gen;
- final private int[] jj_la1 = new int[48];
+ final private int[] jj_la1 = new int[49];
static private int[] jj_la1_0;
static private int[] jj_la1_1;
static {
@@ -1685,10 +1742,10 @@
jj_la1_1();
}
private static void jj_la1_0() {
- jj_la1_0 = new int[] {0x8000000,0x10cb00,0x8000000,0x80000000,0x8000000,0x10000,0x10cb00,0x8000000,0x8000000,0x20000000,0x10000,0x0,0x0,0x0,0x80000000,0x80000000,0x30cb80,0x800,0x10cb00,0x0,0x0,0x80000000,0x30cb80,0x3acb80,0x10c000,0x0,0x0,0x0,0x3acb80,0x0,0x200080,0x0,0x3acb80,0x0,0x0,0x3acf80,0x3acb80,0x0,0x3acb80,0x0,0x0,0x0,0x3000,0x3000,0x0,0x32cb80,0x200080,0x0,};
+ jj_la1_0 = new int[] {0x8000000,0x10cb00,0x8000000,0x80000000,0x8000000,0x10000,0x10cb00,0x8000000,0x8000000,0x20000000,0x10000,0x0,0x0,0x0,0x80000000,0x80000000,0x30cb80,0x800,0x10cb00,0x0,0x0,0x80000000,0x30cb80,0x3acb80,0x10c000,0x0,0x0,0x0,0x3acf80,0x0,0x200080,0x0,0x3acb80,0x3acb80,0x0,0x0,0x3acf80,0x3acb80,0x0,0x3acb80,0x0,0x0,0x0,0x3000,0x3000,0x0,0x32cb80,0x200080,0x0,};
}
private static void jj_la1_1() {
- jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0xc,0x0,0x0,0x0,0x0,0x0,0x1,0x2,0xc,0x10,0x10,0x0,0x0,0x0,0x20,0x4,0x5c,0x80,0x88,0x0,0x80,0x400,0x200,0x488,0x200,0x400,0x800,0x488,0x800,0x2000,0x88,0x88,0x3fc000,0x488,0x3fc000,0xc,0xc,0xc00000,0xc00000,0x1000000,0x88,0x0,0x400,};
+ jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0xc,0x0,0x0,0x0,0x0,0x0,0x1,0x2,0xc,0x10,0x10,0x0,0x0,0x0,0x20,0x4,0x5c,0x80,0x88,0x0,0x80,0x400,0x200,0x488,0x200,0x400,0x800,0x488,0x488,0x800,0x2000,0x88,0x88,0x3fc000,0x488,0x3fc000,0xc,0xc,0xc00000,0xc00000,0x1000000,0x88,0x0,0x400,};
}
final private JJCalls[] jj_2_rtns = new JJCalls[2];
private boolean jj_rescan = false;
@@ -1703,7 +1760,7 @@
token = new Token();
jj_ntk = -1;
jj_gen = 0;
- for (int i = 0; i < 48; i++) jj_la1[i] = -1;
+ for (int i = 0; i < 49; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
@@ -1716,7 +1773,7 @@
token = new Token();
jj_ntk = -1;
jj_gen = 0;
- for (int i = 0; i < 48; i++) jj_la1[i] = -1;
+ for (int i = 0; i < 49; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
@@ -1726,7 +1783,7 @@
token = new Token();
jj_ntk = -1;
jj_gen = 0;
- for (int i = 0; i < 48; i++) jj_la1[i] = -1;
+ for (int i = 0; i < 49; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
@@ -1736,7 +1793,7 @@
token = new Token();
jj_ntk = -1;
jj_gen = 0;
- for (int i = 0; i < 48; i++) jj_la1[i] = -1;
+ for (int i = 0; i < 49; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
@@ -1745,7 +1802,7 @@
token = new Token();
jj_ntk = -1;
jj_gen = 0;
- for (int i = 0; i < 48; i++) jj_la1[i] = -1;
+ for (int i = 0; i < 49; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
@@ -1754,7 +1811,7 @@
token = new Token();
jj_ntk = -1;
jj_gen = 0;
- for (int i = 0; i < 48; i++) jj_la1[i] = -1;
+ for (int i = 0; i < 49; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
@@ -1873,7 +1930,7 @@
la1tokens[jj_kind] = true;
jj_kind = -1;
}
- for (int i = 0; i < 48; i++) {
+ for (int i = 0; i < 49; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-21 15:35:45
|
Revision: 1170
http://jason.svn.sourceforge.net/jason/?rev=1170&view=rev
Author: jomifred
Date: 2008-03-21 08:35:38 -0700 (Fri, 21 Mar 2008)
Log Message:
-----------
use Atom class only as term
Modified Paths:
--------------
trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java
trunk/applications/jason-moise/src/jmoise/OrgAgent.java
trunk/applications/jason-team/src/java/arch/ACArchitecture.java
trunk/applications/jason-team/src/java/arch/CowboyArch.java
trunk/demos/function/a.asl
trunk/examples/gold-miners-II/arch/MinerArch.java
trunk/src/jason/asSemantics/Agent.java
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/asSyntax/ArithFunctionTerm.java
trunk/src/jason/asSyntax/InternalActionLiteral.java
trunk/src/jason/asSyntax/SourceInfo.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
trunk/src/jason/environment/Environment.java
trunk/src/jason/functions/RuleToFunction.java
trunk/src/test/TermTest.java
Modified: trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java
===================================================================
--- trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/applications/as-unit-test/src/jason/asunit/TestAgent.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -2,11 +2,11 @@
import static org.junit.Assert.fail;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.asSemantics.Agent;
import jason.asSemantics.Event;
import jason.asSemantics.Intention;
import jason.asSemantics.Unifier;
-import jason.asSyntax.Atom;
import jason.asSyntax.Literal;
import jason.asSyntax.LogExpr;
import jason.asSyntax.LogicalFormula;
@@ -76,19 +76,21 @@
super.addBel(Literal.tryParsingLiteral(bel));
} catch (ParseException e) {
fail("Parsing '"+bel+"' as a belief!");
+ } catch (RevisionFailedException e) {
+ fail("BRF error for adding '"+bel+"!");
}
}
public void delBel(String bel) {
try {
Literal l = Literal.tryParsingLiteral(bel);
if (!l.hasSource()) {
- if (l instanceof Atom)
- l = new Literal(l.getFunctor());
l.addAnnot(BeliefBase.TSelf);
}
super.delBel(l);
} catch (ParseException e) {
fail("Parsing '"+bel+"' as a belief!");
+ } catch (RevisionFailedException e) {
+ fail("BRF error for deleting '"+bel+"!");
}
}
Modified: trunk/applications/jason-moise/src/jmoise/OrgAgent.java
===================================================================
--- trunk/applications/jason-moise/src/jmoise/OrgAgent.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/applications/jason-moise/src/jmoise/OrgAgent.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -143,8 +143,6 @@
private Literal addAsBel(String b) throws RevisionFailedException {
Literal l = Literal.parseLiteral(b);
- if (l.isAtom())
- l = new Literal(l.getFunctor());
l.addAnnot(managerSource);
getTS().getAg().addBel(l);
return l;
@@ -189,8 +187,6 @@
alreadyGeneratedEvents.add(gi);
Literal l = Literal.parseLiteral(gi.getAsProlog());
- if (l.isAtom())
- l = new Literal(l.getFunctor());
Literal giID = new Literal("scheme");
giID.addTerm(new Atom(gi.getScheme().getId()));
l.addAnnot(giID);
Modified: trunk/applications/jason-team/src/java/arch/ACArchitecture.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -1,9 +1,9 @@
package arch;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.asSemantics.ActionExec;
import jason.asSyntax.Literal;
-import jason.functions.log;
import jason.mas2j.ClassParameters;
import jason.runtime.Settings;
@@ -90,7 +90,7 @@
}
@Override
- void simulationEndPerceived(String result) {
+ void simulationEndPerceived(String result) throws RevisionFailedException {
percepts = new ArrayList<Literal>();
super.simulationEndPerceived(result);
}
Modified: trunk/applications/jason-team/src/java/arch/CowboyArch.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/CowboyArch.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/applications/jason-team/src/java/arch/CowboyArch.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -1,6 +1,7 @@
package arch;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.asSemantics.Message;
import jason.asSyntax.Atom;
import jason.asSyntax.Literal;
@@ -103,7 +104,7 @@
/** The perception of the grid size is removed from the percepts list
and "directly" added as a belief */
- void gsizePerceived(int w, int h, String opponent) {
+ void gsizePerceived(int w, int h, String opponent) throws RevisionFailedException {
model = new LocalWorldModel(w, h);
getTS().getAg().addBel(Literal.parseLiteral("gsize("+w+","+h+")"));
playing = true;
@@ -125,7 +126,7 @@
/** The perception of the corral location is removed from the percepts list
and "directly" added as a belief */
- void corralPerceived(Location upperLeft, Location downRight) {
+ void corralPerceived(Location upperLeft, Location downRight) throws RevisionFailedException {
model.setCorral(upperLeft, downRight);
if (acView != null) acView.getModel().setCorral(upperLeft, downRight);
getTS().getAg().addBel(Literal.parseLiteral("corral("+upperLeft.x+","+upperLeft.y+","+downRight.x+","+downRight.y+")"));
@@ -133,13 +134,13 @@
/** The number of steps of the simulation is removed from the percepts list
and "directly" added as a belief */
- void stepsPerceived(int s) {
+ void stepsPerceived(int s) throws RevisionFailedException {
getTS().getAg().addBel(Literal.parseLiteral("steps("+s+")"));
model.setMaxSteps(s);
}
/** The perception ratio is discovered */
- void perceptionRatioPerceived(int s) {
+ void perceptionRatioPerceived(int s) throws RevisionFailedException {
if (s != model.getPerceptionRatio()) {
model.setPerceptionRatio(s);
getTS().getAg().addBel(Literal.parseLiteral("pratio("+s+")"));
@@ -199,8 +200,8 @@
logger.info("** Arch adding restart for "+getAgName());
getTS().getC().create();
- getTS().getAg().getBB().abolish(new Atom("restart").getPredicateIndicator());
- getTS().getAg().addBel(new Atom("restart"));
+ getTS().getAg().getBB().abolish(new Literal("restart").getPredicateIndicator());
+ getTS().getAg().addBel(new Literal("restart"));
lo2 = new Location(-1,-1); // to not restart again in the next cycle
} catch (Exception e) {
logger.info("Error in restart!"+ e);
@@ -230,7 +231,7 @@
model.add(WorldModel.ENEMY, x, y);
}
- void simulationEndPerceived(String result) {
+ void simulationEndPerceived(String result) throws RevisionFailedException {
getTS().getAg().addBel(Literal.parseLiteral("end_of_simulation("+result+")"));
playing = false;
}
Modified: trunk/demos/function/a.asl
===================================================================
--- trunk/demos/function/a.asl 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/demos/function/a.asl 2008-03-21 15:35:38 UTC (rev 1170)
@@ -32,7 +32,7 @@
/* Initial goals */
-!show_predef_funtion.
+//!show_predef_funtion.
!show_userdef_funtion.
/* Plans */
Modified: trunk/examples/gold-miners-II/arch/MinerArch.java
===================================================================
--- trunk/examples/gold-miners-II/arch/MinerArch.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/examples/gold-miners-II/arch/MinerArch.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -152,9 +152,9 @@
//logger.info("** Arch adding restart for "+getAgName()+", TS="+getTS().getCurrentTask()+", "+getTS().getC());
getTS().getC().create();
- getTS().getAg().getBB().abolish(new Atom("restart").getPredicateIndicator());
+ getTS().getAg().getBB().abolish(new Literal("restart").getPredicateIndicator());
getTS().getAg().getBB().abolish(new PredicateIndicator("gold",2)); // tira os ouros
- getTS().getAg().addBel(new Atom("restart"));
+ getTS().getAg().addBel(new Literal("restart"));
lo2 = new Location(-1,-1); // to not restart again in the next cycle
//getTS().stopCycle();
Modified: trunk/src/jason/asSemantics/Agent.java
===================================================================
--- trunk/src/jason/asSemantics/Agent.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/asSemantics/Agent.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -26,7 +26,6 @@
import jason.JasonException;
import jason.RevisionFailedException;
import jason.architecture.AgArch;
-import jason.asSyntax.Atom;
import jason.asSyntax.Literal;
import jason.asSyntax.LogicalFormula;
import jason.asSyntax.Plan;
@@ -598,8 +597,6 @@
*/
public boolean addBel(Literal bel) throws RevisionFailedException {
if (!bel.hasSource()) {
- if (bel instanceof Atom)
- bel = new Literal(bel.getFunctor());
bel.addAnnot(BeliefBase.TSelf);
}
List<Literal>[] result = brf(bel, null, Intention.EmptyInt);
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -508,8 +508,6 @@
if (!body.hasAnnot()) {
// do not add source(self) in case the
// programmer set some annotation
- if (body instanceof Atom)
- body = new Literal(body.getFunctor());
body.addAnnot(BeliefBase.TSelf);
}
Literal bc = (Literal)body.clone();
@@ -535,8 +533,6 @@
if (!body.hasSource()) {
// do not add source(self) in case the
// programmer set the source
- if (body instanceof Atom)
- body = new Literal(body.getFunctor());
body.addAnnot(BeliefBase.TSelf);
}
@@ -569,8 +565,6 @@
if (!body.hasAnnot()) {
// do not add source(self) in case the
// programmer set some annotation
- if (body instanceof Atom)
- body = new Literal(body.getFunctor());
body.addAnnot(BeliefBase.TSelf);
}
Modified: trunk/src/jason/asSyntax/ArithFunctionTerm.java
===================================================================
--- trunk/src/jason/asSyntax/ArithFunctionTerm.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/asSyntax/ArithFunctionTerm.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -35,7 +35,7 @@
public ArithFunctionTerm(ArithFunction function) {
super(function.getName(), 2);
- this.function = function;
+ this.function = function;
}
public ArithFunctionTerm(ArithFunctionTerm af) {
@@ -55,6 +55,11 @@
}
@Override
+ public boolean isAtom() {
+ return false;
+ }
+
+ @Override
public boolean isStructure() {
return false;
}
Modified: trunk/src/jason/asSyntax/InternalActionLiteral.java
===================================================================
--- trunk/src/jason/asSyntax/InternalActionLiteral.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/asSyntax/InternalActionLiteral.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -68,6 +68,11 @@
}
@Override
+ public boolean isAtom() {
+ return false;
+ }
+
+ @Override
public boolean canBeAddedInBB() {
return false;
}
Modified: trunk/src/jason/asSyntax/SourceInfo.java
===================================================================
--- trunk/src/jason/asSyntax/SourceInfo.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/asSyntax/SourceInfo.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -21,6 +21,10 @@
beginSrcLine = o.beginSrcLine;
endSrcLine = o.endSrcLine;
}
+ public void setSrc(Object o) {
+ if (o instanceof SourceInfo)
+ setSrc((SourceInfo)o);
+ }
public void setSrc(String asSource) {
source = asSource;
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-21 15:35:38 UTC (rev 1170)
@@ -310,10 +310,7 @@
( F=literal()
| F=var()
- ) { if (F instanceof Atom)
- F = new Literal(F.getFunctor()); // trigger literal must be a literal and not an atom
- return new Trigger(teOp,teType,F);
- }
+ ) { return new Trigger(teOp,teType,F); }
}
/* Literal */
@@ -329,11 +326,6 @@
throw new ParseException(getSourceRef(F)+" The internal action class for '"+F+"' was not found!");
}
}
- if (F.isAtom() && type == Literal.LPos) {
- Atom a = new Atom(F.getFunctor());
- a.setSrc(F);
- return a;
- }
return new Literal(type,F);
}
)
@@ -436,10 +428,17 @@
}
-Term term() : { Term u; Object o; }
+Term term() : { Term u; Object o; Atom a; }
{
( u=list()
- | o=arithm_expr() { return (Term)o; } // arithm expr includes literals
+ | o=arithm_expr() { u = (Term)o; // arithm expr includes literals/atoms/structures
+ if (u.isAtom()) {
+ a = new Atom( ((Structure)u).getFunctor());
+ a.setSrc(u);
+ return a;
+ }
+ return u;
+ }
| u=string()
)
{ return u; }
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -406,8 +406,6 @@
jj_consume_token(-1);
throw new ParseException();
}
- if (F instanceof Atom)
- F = new Literal(F.getFunctor()); // trigger literal must be a literal and not an atom
{if (true) return new Trigger(teOp,teType,F);}
throw new Error("Missing return statement in function");
}
@@ -438,11 +436,6 @@
{if (true) throw new ParseException(getSourceRef(F)+" The internal action class for '"+F+"' was not found!");}
}
}
- if (F.isAtom() && type == Literal.LPos) {
- Atom a = new Atom(F.getFunctor());
- a.setSrc(F);
- {if (true) return a;}
- }
{if (true) return new Literal(type,F);}
break;
case TK_TRUE:
@@ -655,7 +648,7 @@
}
final public Term term() throws ParseException {
- Term u; Object o;
+ Term u; Object o; Atom a;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 42:
u = list();
@@ -672,7 +665,13 @@
case 35:
case 39:
o = arithm_expr();
- {if (true) return (Term)o;}
+ u = (Term)o; // arithm expr includes literals/atoms/structures
+ if (u.isAtom()) {
+ a = new Atom( ((Structure)u).getFunctor());
+ a.setSrc(u);
+ {if (true) return a;}
+ }
+ {if (true) return u;}
break;
case STRING:
u = string();
@@ -1173,21 +1172,15 @@
return false;
}
- final private boolean jj_3R_16() {
- if (jj_scan_token(35)) return true;
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_22()) jj_scanpos = xsp;
- return false;
- }
-
final private boolean jj_3R_70() {
if (jj_scan_token(TK_INTDIV)) return true;
return false;
}
- final private boolean jj_3R_15() {
- if (jj_scan_token(34)) return true;
+ final private boolean jj_3R_19() {
+ if (jj_scan_token(39)) return true;
+ if (jj_3R_25()) return true;
+ if (jj_scan_token(40)) return true;
return false;
}
@@ -1196,8 +1189,8 @@
return false;
}
- final private boolean jj_3R_14() {
- if (jj_scan_token(36)) return true;
+ final private boolean jj_3R_18() {
+ if (jj_3R_24()) return true;
return false;
}
@@ -1206,13 +1199,13 @@
return false;
}
- final private boolean jj_3R_13() {
- if (jj_scan_token(38)) return true;
+ final private boolean jj_3R_17() {
+ if (jj_3R_23()) return true;
return false;
}
- final private boolean jj_3R_12() {
- if (jj_scan_token(31)) return true;
+ final private boolean jj_3R_22() {
+ if (jj_scan_token(34)) return true;
return false;
}
@@ -1240,6 +1233,34 @@
return false;
}
+ final private boolean jj_3R_16() {
+ if (jj_scan_token(35)) return true;
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_22()) jj_scanpos = xsp;
+ return false;
+ }
+
+ final private boolean jj_3R_15() {
+ if (jj_scan_token(34)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_14() {
+ if (jj_scan_token(36)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_13() {
+ if (jj_scan_token(38)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_12() {
+ if (jj_scan_token(31)) return true;
+ return false;
+ }
+
final private boolean jj_3_2() {
Token xsp;
xsp = jj_scanpos;
@@ -1295,23 +1316,23 @@
return false;
}
- final private boolean jj_3R_29() {
- if (jj_scan_token(TK_FALSE)) return true;
+ final private boolean jj_3R_59() {
+ if (jj_scan_token(53)) return true;
return false;
}
- final private boolean jj_3R_28() {
- if (jj_scan_token(TK_TRUE)) return true;
+ final private boolean jj_3R_29() {
+ if (jj_scan_token(TK_FALSE)) return true;
return false;
}
- final private boolean jj_3R_59() {
- if (jj_scan_token(53)) return true;
+ final private boolean jj_3R_58() {
+ if (jj_scan_token(52)) return true;
return false;
}
- final private boolean jj_3R_58() {
- if (jj_scan_token(52)) return true;
+ final private boolean jj_3R_28() {
+ if (jj_scan_token(TK_TRUE)) return true;
return false;
}
@@ -1345,11 +1366,6 @@
return false;
}
- final private boolean jj_3R_35() {
- if (jj_scan_token(TK_NEG)) return true;
- return false;
- }
-
final private boolean jj_3R_49() {
Token xsp;
xsp = jj_scanpos;
@@ -1378,11 +1394,21 @@
return false;
}
+ final private boolean jj_3R_35() {
+ if (jj_scan_token(TK_NEG)) return true;
+ return false;
+ }
+
final private boolean jj_3R_48() {
if (jj_3R_51()) return true;
return false;
}
+ final private boolean jj_3R_47() {
+ if (jj_3R_50()) return true;
+ return false;
+ }
+
final private boolean jj_3R_27() {
Token xsp;
xsp = jj_scanpos;
@@ -1391,11 +1417,6 @@
return false;
}
- final private boolean jj_3R_47() {
- if (jj_3R_50()) return true;
- return false;
- }
-
final private boolean jj_3R_23() {
Token xsp;
xsp = jj_scanpos;
@@ -1497,26 +1518,38 @@
return false;
}
- final private boolean jj_3R_45() {
- if (jj_3R_50()) return true;
+ final private boolean jj_3R_31() {
+ if (jj_scan_token(UNNAMEDVAR)) return true;
return false;
}
- final private boolean jj_3R_31() {
- if (jj_scan_token(UNNAMEDVAR)) return true;
+ final private boolean jj_3R_30() {
+ if (jj_scan_token(VAR)) return true;
return false;
}
- final private boolean jj_3R_44() {
- if (jj_3R_26()) return true;
+ final private boolean jj_3R_24() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_30()) {
+ jj_scanpos = xsp;
+ if (jj_3R_31()) return true;
+ }
+ xsp = jj_scanpos;
+ if (jj_3R_32()) jj_scanpos = xsp;
return false;
}
- final private boolean jj_3R_30() {
- if (jj_scan_token(VAR)) return true;
+ final private boolean jj_3R_45() {
+ if (jj_3R_50()) return true;
return false;
}
+ final private boolean jj_3R_44() {
+ if (jj_3R_26()) return true;
+ return false;
+ }
+
final private boolean jj_3R_42() {
Token xsp;
xsp = jj_scanpos;
@@ -1530,15 +1563,8 @@
return false;
}
- final private boolean jj_3R_24() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_30()) {
- jj_scanpos = xsp;
- if (jj_3R_31()) return true;
- }
- xsp = jj_scanpos;
- if (jj_3R_32()) jj_scanpos = xsp;
+ final private boolean jj_3R_77() {
+ if (jj_3R_23()) return true;
return false;
}
@@ -1552,17 +1578,6 @@
return false;
}
- final private boolean jj_3R_77() {
- if (jj_3R_23()) return true;
- return false;
- }
-
- final private boolean jj_3R_20() {
- if (jj_scan_token(39)) return true;
- if (jj_3R_41()) return true;
- return false;
- }
-
final private boolean jj_3R_76() {
if (jj_3R_77()) return true;
return false;
@@ -1579,6 +1594,12 @@
return false;
}
+ final private boolean jj_3R_20() {
+ if (jj_scan_token(39)) return true;
+ if (jj_3R_41()) return true;
+ return false;
+ }
+
final private boolean jj_3_1() {
if (jj_scan_token(27)) return true;
if (jj_scan_token(TK_BEGIN)) return true;
@@ -1598,23 +1619,6 @@
return false;
}
- final private boolean jj_3R_11() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_scan_token(20)) {
- jj_scanpos = xsp;
- if (jj_scan_token(14)) {
- jj_scanpos = xsp;
- if (jj_scan_token(15)) return true;
- }
- }
- xsp = jj_scanpos;
- if (jj_3R_20()) jj_scanpos = xsp;
- xsp = jj_scanpos;
- if (jj_3R_21()) jj_scanpos = xsp;
- return false;
- }
-
final private boolean jj_3R_66() {
Token xsp;
xsp = jj_scanpos;
@@ -1634,6 +1638,23 @@
return false;
}
+ final private boolean jj_3R_11() {
+ Token xsp;
+ xsp = jj_scanpos;
+ if (jj_scan_token(20)) {
+ jj_scanpos = xsp;
+ if (jj_scan_token(14)) {
+ jj_scanpos = xsp;
+ if (jj_scan_token(15)) return true;
+ }
+ }
+ xsp = jj_scanpos;
+ if (jj_3R_20()) jj_scanpos = xsp;
+ xsp = jj_scanpos;
+ if (jj_3R_21()) jj_scanpos = xsp;
+ return false;
+ }
+
final private boolean jj_3R_67() {
if (jj_scan_token(56)) return true;
return false;
@@ -1647,28 +1668,6 @@
return false;
}
- final private boolean jj_3R_19() {
- if (jj_scan_token(39)) return true;
- if (jj_3R_25()) return true;
- if (jj_scan_token(40)) return true;
- return false;
- }
-
- final private boolean jj_3R_18() {
- if (jj_3R_24()) return true;
- return false;
- }
-
- final private boolean jj_3R_17() {
- if (jj_3R_23()) return true;
- return false;
- }
-
- final private boolean jj_3R_22() {
- if (jj_scan_token(34)) return true;
- return false;
- }
-
public as2jTokenManager token_source;
SimpleCharStream jj_input_stream;
public Token token, jj_nt;
Modified: trunk/src/jason/environment/Environment.java
===================================================================
--- trunk/src/jason/environment/Environment.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/environment/Environment.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -25,7 +25,6 @@
package jason.environment;
import jason.asSemantics.Unifier;
-import jason.asSyntax.Atom;
import jason.asSyntax.Literal;
import jason.asSyntax.Structure;
@@ -172,7 +171,6 @@
public void addPercept(Literal per) {
if (per != null) {
if (! percepts.contains(per)) {
- if (per instanceof Atom) per = new Literal(per.getFunctor());
percepts.add(per);
uptodateAgs.clear();
}
@@ -240,7 +238,6 @@
}
if (! agl.contains(per)) {
uptodateAgs.remove(agName);
- if (per instanceof Atom) per = new Literal(per.getFunctor());
agl.add(per);
}
}
Modified: trunk/src/jason/functions/RuleToFunction.java
===================================================================
--- trunk/src/jason/functions/RuleToFunction.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/jason/functions/RuleToFunction.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -39,6 +39,11 @@
}
@Override
+ public String getName() {
+ return super.getName()+"_{"+literal+"}";
+ }
+
+ @Override
public boolean checkArity(int a) {
return a == arity;
}
Modified: trunk/src/test/TermTest.java
===================================================================
--- trunk/src/test/TermTest.java 2008-03-20 23:22:41 UTC (rev 1169)
+++ trunk/src/test/TermTest.java 2008-03-21 15:35:38 UTC (rev 1170)
@@ -725,4 +725,17 @@
assertEquals(0, p.getSingletonVars().size());
}
+
+ public void testAtomParsing() {
+ Literal l = Literal.parseLiteral("b");
+ assertFalse(l instanceof Atom);
+
+ l = Literal.parseLiteral("b(10,a,c(10,x))[ant1,source(c)]");
+ assertTrue(l.getTerm(1) instanceof Atom);
+ assertFalse(l.getTerm(2) instanceof Atom);
+ assertTrue(l.getAnnots().get(0) instanceof Atom);
+
+ l = Literal.parseLiteral("b(a.r)"); // internal actions should not be atoms
+ assertFalse(l.getTerm(0) instanceof Atom);
+ }
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <tom...@us...> - 2008-03-20 23:22:48
|
Revision: 1169
http://jason.svn.sourceforge.net/jason/?rev=1169&view=rev
Author: tomklapiscak
Date: 2008-03-20 16:22:41 -0700 (Thu, 20 Mar 2008)
Log Message:
-----------
Description Logic based belief-revision implemented. Given a modification to the ontology that would result in an inconsistency, consistency is be maintained by either contracting the least trusted of the contradictory assertions, or preventing the addition of the incoming belief.
JASDL's implementation of the "incision" function (used establish which justifications to contract) makes use of agent trust ratings (which can now be specified in the mas2j file) established using the source annotation.
JASDL's implementation of the "KernelsetFilter" ensures that only assertions about individuals (i.e. those that can be represented as SE-Literals) can be contracted.
The BeliefBaseRevisor is designed as a general library for belief base revision of OWL-DL ontologies using the OWL-API and will soon be placed in a seperate library.
Since this feature is highly experimental, it can disabled in the mas2j file. In which case, JASDL's legacy consistency maintenence mechanism is adopted (earlier assertions always precede over later ones).
Failed and ineffectual belief additions now handled correctly by JASDL.
travel_agent example updated.
Agent mind-inspector support re-implemented.
Modified Paths:
--------------
trunk/applications/jasdl-owlapi/examples/travel_agent/config.mas2j
trunk/applications/jasdl-owlapi/examples/travel_agent/customer.asl
trunk/applications/jasdl-owlapi/examples/travel_agent/travel_agent.asl
trunk/applications/jasdl-owlapi/lib/pellet/pellet.jar
trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java
trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlConfigurator.java
trunk/applications/jasdl-owlapi/src/jasdl/bb/JasdlBeliefBase.java
trunk/applications/jasdl-owlapi/src/jasdl/bridge/ToSELiteralConverter.java
trunk/applications/jasdl-owlapi/src/jasdl/bridge/seliteral/SELiteral.java
Added Paths:
-----------
trunk/applications/jasdl-owlapi/lib/pellet/jena/
trunk/applications/jasdl-owlapi/lib/pellet/jena/antlr-2.7.5.jar
trunk/applications/jasdl-owlapi/lib/pellet/jena/arq-extra.jar
trunk/applications/jasdl-owlapi/lib/pellet/jena/arq.jar
trunk/applications/jasdl-owlapi/lib/pellet/jena/commons-logging-1.1.jar
trunk/applications/jasdl-owlapi/lib/pellet/jena/concurrent.jar
trunk/applications/jasdl-owlapi/lib/pellet/jena/icu4j_3_4.jar
trunk/applications/jasdl-owlapi/lib/pellet/jena/iri.jar
trunk/applications/jasdl-owlapi/lib/pellet/jena/jena.jar
trunk/applications/jasdl-owlapi/lib/pellet/jena/jenatest.jar
trunk/applications/jasdl-owlapi/lib/pellet/jena/json.jar
trunk/applications/jasdl-owlapi/lib/pellet/jena/junit.jar
trunk/applications/jasdl-owlapi/lib/pellet/jena/log4j-1.2.12.jar
trunk/applications/jasdl-owlapi/lib/pellet/jena/lucene-core-2.0.0.jar
trunk/applications/jasdl-owlapi/lib/pellet/jena/stax-api-1.0.jar
trunk/applications/jasdl-owlapi/lib/pellet/jena/wstx-asl-3.0.0.jar
trunk/applications/jasdl-owlapi/lib/pellet/jena/xercesImpl.jar
trunk/applications/jasdl-owlapi/lib/pellet/jena/xml-apis.jar
trunk/applications/jasdl-owlapi/lib/pellet/jetty/
trunk/applications/jasdl-owlapi/lib/pellet/jetty/jetty.jar
trunk/applications/jasdl-owlapi/lib/pellet/junit/
trunk/applications/jasdl-owlapi/lib/pellet/junit/junit.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/antlr-runtime-3.0.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/commons-lang-2.2.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-api.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-apibinding.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-change.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-debugging.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-dig1_1.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-functionalparser.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-functionalrenderer.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-impl.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-krssparser.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-mansyntaxparser.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-mansyntaxrenderer.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-metrics.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-oboparser.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-owlxmlparser.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-owlxmlrenderer.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-rdfapi.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-rdfxmlparser.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-rdfxmlrenderer.jar
trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-util.jar
trunk/applications/jasdl-owlapi/lib/pellet/pcj.jar
trunk/applications/jasdl-owlapi/lib/pellet/servlet.jar
trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/
trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/BeliefBaseContractor.java
trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/BeliefBaseRevisor.java
trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/IncisionFunction.java
trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/IsolatedOntologyOperation.java
trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/JasdlIncisionFunction.java
trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/JasdlReasonerFactory.java
trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/KernelsetFilter.java
trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/TBoxAxiomKernelsetFilter.java
Modified: trunk/applications/jasdl-owlapi/examples/travel_agent/config.mas2j
===================================================================
--- trunk/applications/jasdl-owlapi/examples/travel_agent/config.mas2j 2008-03-20 18:15:42 UTC (rev 1168)
+++ trunk/applications/jasdl-owlapi/examples/travel_agent/config.mas2j 2008-03-20 23:22:41 UTC (rev 1169)
@@ -31,12 +31,19 @@
travel_agent
travel_agent.asl
[
- jasdl_default_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy", // applied to incoming ontologies and those given no automapping
+ jasdl_useBeliefRevision = "true", // use experimental DL-based belief revision mechanism
+
+ jasdl_default_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy", // applied to incoming ontologies and those given no automapping
jasdl_ontologies="travel",
jasdl_travel_uri="http://www.dur.ac.uk/t.g.klapiscak/onts/travel.owl",
/*jasdl_travel_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy",*/ // defaults can be overriden per-ontology here
- jasdl_travel_mapping_manual="small_beach=beach" // these manual mappings will override any automatic mappings made by strategies
+ jasdl_travel_mapping_manual="small_beach=beach", // these manual mappings will override any automatic mappings made by strategies,
+
+ // static trust ratings, mainly for testing purposes - likely to change
+ jasdl_knownAgents = "tom,ben",
+ jasdl_tom_trustRating="0.9",
+ jasdl_ben_trustRating="0.4"
]
agentArchClass jasdl.architecture.JasdlAgArch
agentClass jasdl.asSemantics.JasdlAgent
@@ -47,12 +54,14 @@
customer.asl
[
/* jasdl_default_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy", */ // defaults to this
+ jasdl_useBeliefRevision = "true",
jasdl_ontologies="holidays,places",
/*jasdl_holidays_uri="file:///home/tom/Desktop/Project/workspace/jason/applications/jasdl-owlapi/examples/travel_agent/ontologies/travel.owl", */
jasdl_holidays_uri="http://www.dur.ac.uk/t.g.klapiscak/onts/travel.owl",
jasdl_holidays_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy",
jasdl_holidays_mapping_manual="small_beach=beach, luxuriousHotel=LuxuryHotel", // for demonstration of arbitrary primitive mappings being handled correctly
+
jasdl_places_uri="http://www.dur.ac.uk/t.g.klapiscak/onts/places.owl",
jasdl_places_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy"
Modified: trunk/applications/jasdl-owlapi/examples/travel_agent/customer.asl
===================================================================
--- trunk/applications/jasdl-owlapi/examples/travel_agent/customer.asl 2008-03-20 18:15:42 UTC (rev 1168)
+++ trunk/applications/jasdl-owlapi/examples/travel_agent/customer.asl 2008-03-20 23:22:41 UTC (rev 1169)
@@ -59,3 +59,7 @@
.print(XS, " are mutually distinct individuals, according to ", Source).
++testing
+ <-
+ .print("Semantically-naive inter-agent communication working").
+
Modified: trunk/applications/jasdl-owlapi/examples/travel_agent/travel_agent.asl
===================================================================
--- trunk/applications/jasdl-owlapi/examples/travel_agent/travel_agent.asl 2008-03-20 18:15:42 UTC (rev 1168)
+++ trunk/applications/jasdl-owlapi/examples/travel_agent/travel_agent.asl 2008-03-20 23:22:41 UTC (rev 1169)
@@ -33,6 +33,7 @@
.print("Example: Updating Belief Base 1");
+hotel(hilton)[o(travel)]; // hilton is a hotel
+hasRating(hilton, threeStarRating)[o(travel)]; // hilton has three-star rating
+ +town(london)[o(travel)];
+city(london)[o(travel)]; // london is a city
+hasAccommodation(london, hilton)[o(travel)]; // hilton is in london
+country(england)[o(travel)]; // england is a country
@@ -49,8 +50,28 @@
+!example_UBB_2
<-
.print("Example: Updating Belief Base 2");
- /* 1 */ +hasRating(hilton, twoStarRating)[o(travel)];
- /* 2 */ +ruralArea(london)[o(travel)];
+
+ +city(somewhere)[o(travel), source(ben)];
+ +town(somewhere)[o(travel), source(ben)];
+
+ // Despite the classes urbanArea and ruralArea being disjoint, the belief addition below will succeed,
+ // since tom's word is trusted over ben's (see config.mas2j)
+ // as a result, both (incompatible) assertions made above by ben will be contracted
+ // and the one below will be added. Notice ABox consistency is maintained..
+ +ruralArea(somewhere)[o(travel), source(tom)];
+ ?ruralArea(somewhere)[o(travel)];
+
+ .print("DL-based belief revision is enabled"); // without, the above test-goal will fail, since legacy mechanism simply removes incoming inconsistent beliefs
+
+ // since the classes destination and and contact are disjoint (and ruralArea is a subclass of destination),
+ // and since we trust ben less than tom, the belief addition below will fail (and tom's assertion above will persist),
+ // thus failing the whole plan.
+ +contact(somewhere)[o(travel), source(ben)].
+
+-!example_UBB_2
+ <-
+ // Notice this does not hold, since belief revision rejected the less trusted assertion made by ben.
+ ?~contact(somewhere)[o(travel)];
.print("Completed: Updating Belief Base 2").
@@ -83,6 +104,7 @@
+!example_KSAA
<-
.print("Example: Knowledge Sharing Among Agents");
+ .send(customer, tell, testing);
.send(customer, tell, luxuryHotel(hilton)[o(travel)]);
// since all_different assertions are treated as SE-literals, we can now send them between agents
.send(customer, tell, all_different([hilton, fourSeasons])[o(travel)]).
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/antlr-2.7.5.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/antlr-2.7.5.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/arq-extra.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/arq-extra.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/arq.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/arq.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/commons-logging-1.1.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/commons-logging-1.1.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/concurrent.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/concurrent.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/icu4j_3_4.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/icu4j_3_4.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/iri.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/iri.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/jena.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/jena.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/jenatest.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/jenatest.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/json.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/json.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/junit.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/junit.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/log4j-1.2.12.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/log4j-1.2.12.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/lucene-core-2.0.0.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/lucene-core-2.0.0.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/stax-api-1.0.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/stax-api-1.0.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/wstx-asl-3.0.0.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/wstx-asl-3.0.0.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/xercesImpl.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/xercesImpl.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jena/xml-apis.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jena/xml-apis.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/jetty/jetty.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/jetty/jetty.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/junit/junit.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/junit/junit.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/antlr-runtime-3.0.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/antlr-runtime-3.0.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/commons-lang-2.2.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/commons-lang-2.2.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-api.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-api.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-apibinding.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-apibinding.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-change.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-change.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-debugging.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-debugging.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-dig1_1.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-dig1_1.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-functionalparser.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-functionalparser.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-functionalrenderer.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-functionalrenderer.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-impl.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-impl.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-krssparser.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-krssparser.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-mansyntaxparser.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-mansyntaxparser.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-mansyntaxrenderer.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-mansyntaxrenderer.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-metrics.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-metrics.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-oboparser.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-oboparser.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-owlxmlparser.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-owlxmlparser.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-owlxmlrenderer.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-owlxmlrenderer.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-rdfapi.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-rdfapi.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-rdfxmlparser.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-rdfxmlparser.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-rdfxmlrenderer.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-rdfxmlrenderer.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-util.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/owlapi/owlapi-util.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: trunk/applications/jasdl-owlapi/lib/pellet/pcj.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/pcj.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Modified: trunk/applications/jasdl-owlapi/lib/pellet/pellet.jar
===================================================================
(Binary files differ)
Added: trunk/applications/jasdl-owlapi/lib/pellet/servlet.jar
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jasdl-owlapi/lib/pellet/servlet.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Modified: trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java 2008-03-20 18:15:42 UTC (rev 1168)
+++ trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java 2008-03-20 23:22:41 UTC (rev 1169)
@@ -5,6 +5,10 @@
import jasdl.asSemantics.parsing.URIEntityChecker;
import jasdl.asSyntax.JasdlPlanLibrary;
import jasdl.bb.JasdlBeliefBase;
+import jasdl.bb.revision.BeliefBaseRevisor;
+import jasdl.bb.revision.JasdlIncisionFunction;
+import jasdl.bb.revision.JasdlReasonerFactory;
+import jasdl.bb.revision.TBoxAxiomKernelsetFilter;
import jasdl.bridge.AllDifferentPlaceholder;
import jasdl.bridge.ToAxiomConverter;
import jasdl.bridge.ToSELiteralConverter;
@@ -16,15 +20,20 @@
import jasdl.bridge.alias.MappingStrategy;
import jasdl.bridge.label.LabelManager;
import jasdl.bridge.label.OntologyURIManager;
+import jasdl.bridge.seliteral.SELiteral;
import jasdl.bridge.seliteral.SELiteralFactory;
import jasdl.util.DuplicateMappingException;
import jasdl.util.InvalidSELiteralException;
import jasdl.util.JasdlException;
+import jasdl.util.NotEnrichedException;
import jasdl.util.UnknownMappingException;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.architecture.AgArch;
+import jason.asSemantics.Intention;
import jason.asSemantics.TransitionSystem;
import jason.asSyntax.Atom;
+import jason.asSyntax.Literal;
import jason.bb.BeliefBase;
import jason.runtime.Settings;
@@ -32,6 +41,7 @@
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collections;
+import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.Vector;
@@ -42,10 +52,15 @@
import org.mindswap.pellet.PelletOptions;
import org.mindswap.pellet.owlapi.Reasoner;
import org.semanticweb.owl.apibinding.OWLManager;
+import org.semanticweb.owl.model.AddAxiom;
+import org.semanticweb.owl.model.OWLAnnotation;
+import org.semanticweb.owl.model.OWLAxiom;
+import org.semanticweb.owl.model.OWLAxiomAnnotationAxiom;
import org.semanticweb.owl.model.OWLClass;
import org.semanticweb.owl.model.OWLDescription;
import org.semanticweb.owl.model.OWLEntity;
import org.semanticweb.owl.model.OWLEquivalentClassesAxiom;
+import org.semanticweb.owl.model.OWLIndividualAxiom;
import org.semanticweb.owl.model.OWLOntology;
import org.semanticweb.owl.model.OWLOntologyChangeException;
import org.semanticweb.owl.model.OWLOntologyCreationException;
@@ -54,7 +69,7 @@
import uk.ac.manchester.cs.owl.mansyntaxrenderer.ManchesterOWLSyntaxOWLObjectRendererImpl;
-public class JasdlAgent extends JmcaAgent {
+public class JasdlAgent extends JmcaAgent{
public static List<MappingStrategy> DEFAULT_MAPPING_STRATEGIES = Arrays.asList( new MappingStrategy[] { new DecapitaliseMappingStrategy()} );
private OWLOntologyManager ontologyManager;
@@ -76,13 +91,12 @@
public static String ANON_LABEL_PREFIX = "anon_label_";
public static String ANON_ALIAS_PREFIX = "anon_alias_";
- /**
- * Since Jason doesn't initialise an agent name in time
- */
- private String agentName;
-
private DefinitionManager definitionManager;
+ private HashMap<Atom, Float> trustMap;
+
+ private boolean beliefRevisionEnabled = true;
+
public JasdlAgent(){
@@ -101,6 +115,8 @@
toAxiomConverter = new ToAxiomConverter(this);
toSELiteralConverter = new ToSELiteralConverter(this);
+ trustMap = new HashMap<Atom, Float>();
+
manchesterObjectRenderer = new ManchesterOWLSyntaxOWLObjectRendererImpl();
manchesterObjectRenderer.setShortFormProvider(new ShortFormProvider(){
public void dispose() {
@@ -124,6 +140,8 @@
+
+
@Override
public TransitionSystem initAg(AgArch arch, BeliefBase bb, String src, Settings stts) throws JasonException {
if(!(bb instanceof JasdlBeliefBase)){
@@ -149,8 +167,110 @@
return ts;
}
+ public List<Literal> getABoxState() throws JasdlException{
+ List<Literal> bels = new Vector<Literal>();
+ for(OWLOntology ontology : ontologyManager.getOntologies()){
+ for(OWLIndividualAxiom axiom : ontology.getIndividualAxioms()){
+ Literal l = toSELiteralConverter.convert(axiom).getLiteral();
+ bels.add(l);
+ }
+ }
+ return bels;
+ }
+
+
+
+ public List<Literal>[] brf(Literal beliefToAdd, Literal beliefToDel, Intention i) throws RevisionFailedException {
+
+ if(!isBeliefRevisionEnabled()){ // if experimental feature is disabled
+ return super.brf(beliefToAdd, beliefToDel, i);
+ }
+
+ List<Literal> addList = new Vector<Literal>();
+ List<Literal> removeList = new Vector<Literal>();
+
+
+ // just accept beliefToDel. Assumption: Deletions never lead to inconsistencies?!
+ if(beliefToDel != null){
+ removeList.add(beliefToDel);
+ }
+
+ if(beliefToAdd != null){
+ try{
+
+
+ SELiteral sl = getSELiteralFactory().create(beliefToAdd);
+ OWLAxiom axiomToAdd = sl.createAxiom();
+
+ BeliefBaseRevisor bbrev = new BeliefBaseRevisor(axiomToAdd, getOntologyManager(), new JasdlReasonerFactory(), getLogger());
+ List<OWLAxiom>[] result = bbrev.revise(new TBoxAxiomKernelsetFilter(), new JasdlIncisionFunction(this, sl));
+
+ /*
+ for(OWLAxiom added : result[0]){
+ addList.add( getToSELiteralConverter().convert((OWLIndividualAxiom)added).getLiteral()); // safe type cast - Jasdl's incision function ensures only individual axioms are contracted
+ }
+ */
+ // Simplication possible: only at most one addition (toAdd). Additionally, annotations required!
+ if(result[0].contains(axiomToAdd)){
+ addList.add(beliefToAdd);
+
+ // there will only be axioms to remove if we accepted beliefToAdd
+ for(OWLAxiom removed : result[1]){
+ removeList.add( getToSELiteralConverter().convert((OWLIndividualAxiom)removed).getLiteral()); // safe type cast - Jasdl's incision function ensures only individual axioms are contracted
+ }
+ }else{
+ // throw revision failed exception, since we didn't successfully add this belief
+ throw new RevisionFailedException("Revision failed on "+beliefToAdd);
+ }
+
+
+ }catch(RevisionFailedException e){
+ throw e; // propagate upwards
+ }catch(NotEnrichedException e){
+ // can't perform DL-based belief revision on SN-Literals
+ addList.add(beliefToAdd);
+ }catch(Exception e){
+ getLogger().warning("Error performing belief revision. Reason:");
+ e.printStackTrace();
+ }
+ }
+ List<Literal>[] toReturn = null;
+
+
+ // affect BB
+ for(Literal added : addList){
+ if(getBB().add(added)){
+ if(toReturn == null){
+ toReturn = new List[2];
+ toReturn[0] = new Vector<Literal>();
+ toReturn[1] = new Vector<Literal>();
+ }
+ toReturn[0].add(added);
+ }
+ }
+ for(Literal removed : removeList){
+ if(getBB().remove(removed)){
+ if(toReturn == null){
+ if(toReturn == null){
+ toReturn = new List[2];
+ toReturn[0] = new Vector<Literal>();
+ toReturn[1] = new Vector<Literal>();
+ }
+ toReturn[1].add(removed);
+ }
+
+ }
+ }
+
+ return toReturn;
+ }
+
+
+
+
+
/**
* Convenience method to (polymorphically) create an entity from resource URI (if known).
* TODO: where should this sit?
@@ -476,4 +596,28 @@
return manchesterURIDescriptionParser;
}
+ public void setTrustRating(Atom name, float trust){
+ trustMap.remove(name);
+ trustMap.put(name, trust);
+ }
+
+ public Float getTrustRating(Atom name){
+ return trustMap.get(name);
+ }
+
+
+
+
+
+ public boolean isBeliefRevisionEnabled() {
+ return beliefRevisionEnabled;
+ }
+
+ public void setBeliefRevisionEnabled(boolean beliefRevisionEnabled) {
+ this.beliefRevisionEnabled = beliefRevisionEnabled;
+ }
+
+
+
+
}
Modified: trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlConfigurator.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlConfigurator.java 2008-03-20 18:15:42 UTC (rev 1168)
+++ trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlConfigurator.java 2008-03-20 23:22:41 UTC (rev 1169)
@@ -26,6 +26,9 @@
private static String MAS2J_MAPPING_STRATEGIES = "_mapping_strategies";
private static String MAS2J_MAPPING_MANUAL = "_mapping_manual";
private static String MAS2J_AGENT_NAME = "_agent_name";
+ private static String MAS2J_TRUSTRATING = "_trustRating";
+ private static String MAS2J_KNOWNAGENTS = "_knownAgents";
+ private static String MAS2J_USEBELIEFREVISION = "_useBeliefRevision";
/**
* List of reserved ontology labels. Currently:
@@ -49,9 +52,15 @@
// load default mapping strategies
agent.setDefaultMappingStrategies(getMappingStrategies(stts, new Atom("default"))); //implication "default" is a reserved ontology label
+ // set whether to use belief revision or not
+ String useBeliefRevision = prepareUserParameter(stts, MAS2J_PREFIX + MAS2J_USEBELIEFREVISION);
+ agent.setBeliefRevisionEnabled(Boolean.parseBoolean(useBeliefRevision));
+
loadOntologies(stts);
- applyManualMappings(stts);
+ applyManualMappings(stts);
+ loadTrustRatings(stts);
+
}catch(JasdlException e){
throw new JasdlException("JASDL agent encountered error during configuration. Reason: "+e);
@@ -105,6 +114,26 @@
}
}
+ private void loadTrustRatings(Settings stts) throws JasdlException{
+ // agent trusts itself completely!
+ agent.setTrustRating(new Atom("self"), 1f);
+
+ // load trust ratings
+ String[] knownAgents = splitUserParameter(stts, MAS2J_PREFIX + MAS2J_KNOWNAGENTS);
+ for(String knownAgent : knownAgents){
+ if(knownAgent.length() > 0){
+ String _trustRating = prepareUserParameter(stts, MAS2J_PREFIX + "_" + knownAgent + MAS2J_TRUSTRATING);
+ Float trustRating;
+ try{
+ trustRating = Float.parseFloat(_trustRating);
+ }catch(NumberFormatException e){
+ throw new JasdlException("Invalid trust rating for "+knownAgent+". Reason: "+e);
+ }
+ agent.setTrustRating(new Atom(knownAgent), trustRating);
+ }
+ }
+ }
+
Modified: trunk/applications/jasdl-owlapi/src/jasdl/bb/JasdlBeliefBase.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/bb/JasdlBeliefBase.java 2008-03-20 18:15:42 UTC (rev 1168)
+++ trunk/applications/jasdl-owlapi/src/jasdl/bb/JasdlBeliefBase.java 2008-03-20 23:22:41 UTC (rev 1169)
@@ -1,18 +1,25 @@
package jasdl.bb;
import jasdl.asSemantics.JasdlAgent;
+import jasdl.bb.revision.BeliefBaseContractor;
+import jasdl.bb.revision.JasdlReasonerFactory;
import jasdl.bridge.seliteral.SELiteral;
import jasdl.bridge.seliteral.SELiteralAllDifferentAssertion;
+import jasdl.util.JasdlException;
import jasdl.util.NotEnrichedException;
import jason.asSyntax.Literal;
import jason.bb.DefaultBeliefBase;
import java.util.HashSet;
import java.util.Iterator;
+import java.util.List;
import java.util.Set;
+import java.util.Vector;
import java.util.logging.Logger;
import org.semanticweb.owl.model.AddAxiom;
+import org.semanticweb.owl.model.OWLAnnotation;
+import org.semanticweb.owl.model.OWLAxiomAnnotationAxiom;
import org.semanticweb.owl.model.OWLDifferentIndividualsAxiom;
import org.semanticweb.owl.model.OWLIndividual;
import org.semanticweb.owl.model.OWLIndividualAxiom;
@@ -27,23 +34,44 @@
public boolean add(Literal l) {
getLogger().fine("Adding "+l);
try{
- SELiteral sl = agent.getSELiteralFactory().create(l);
- getLogger().fine("... "+sl);
+ SELiteral sl = agent.getSELiteralFactory().create(l); // all non-JASDL annotations added.. TODO: This needs sorting
+ OWLIndividualAxiom axiom = sl.createAxiom();
OWLOntology ontology = sl.getOntology();
- OWLIndividualAxiom axiom = sl.createAxiom();
- getLogger().fine("..... as axiom: "+axiom);
- AddAxiom add = new AddAxiom(ontology, axiom);
- agent.getOntologyManager().applyChange(add);
- agent.getReasoner().refresh();
+ // add axiom annotations to axiom containing serialised list terms.
+ // Could be (clumsily) made to sit in toAxiomConverter? - this is probably the only place we add axioms to an ontology anyway
+ OWLAnnotation annot = agent.getOntologyManager().getOWLDataFactory().getOWLLabelAnnotation(sl.getSemanticallyNaiveAnnotations().toString()); //TODO: more efficient way of serialising list terms?
+ OWLAxiomAnnotationAxiom annotAxiom = agent.getOntologyManager().getOWLDataFactory().getOWLAxiomAnnotationAxiom(axiom, annot);
- if(!agent.getReasoner().isConsistent()){
- RemoveAxiom rem = new RemoveAxiom(ontology, axiom);
- agent.getOntologyManager().applyChange(rem);
+ // need to merge existing annotations into a single one containing a whole list.
+
+
+ boolean containsAxiom = ontology.containsAxiom(axiom);
+ boolean containsAnnot = ontology.containsAxiom(annotAxiom);
+ agent.getLogger().fine("Contains Axiom "+axiom+"?: " +containsAxiom);
+ agent.getLogger().fine("Contains Annotation "+annotAxiom+"?: " +containsAnnot);
+
+ if(!containsAxiom || !containsAnnot){
+ if(!containsAxiom){
+ agent.getOntologyManager().applyChange(new AddAxiom(ontology, axiom));
+ }
+ if(!containsAnnot){
+ agent.getOntologyManager().applyChange(new AddAxiom(ontology, annotAxiom));
+ }
agent.getReasoner().refresh();
+
+ if(!agent.isBeliefRevisionEnabled()){ // if brf disabled, resort to legacy consistency maintenance mechanism
+ if(!agent.getReasoner().isConsistent()){
+ RemoveAxiom rem = new RemoveAxiom(ontology, axiom);
+ agent.getOntologyManager().applyChange(rem);
+ agent.getReasoner().refresh();
+ return false;
+ }
+ }
+
+ return true;
+ }else{
return false;
- }
-
- return true;
+ }
}catch(NotEnrichedException e){
getLogger().fine("... semantically-naive");
return super.add(l); // semantically-naive, use standard Jason mechanisms
@@ -53,13 +81,19 @@
return false;
}
}
+
-
-
+ /**
+ * Removal is equivalent to contraction!
+ */
@Override
public boolean remove(Literal l) {
getLogger().fine("Removing "+l);
try{
+ // TODO: use contraction
+ //BeliefBaseContractor contractor = new BeliefBaseContractor(agent.getOntologyManager(), new JasdlReasonerFactory(), agent.getLogger());
+ //contractor.contract(axiom, kernelsetFilter, incisionFunction)
+
SELiteral sl = agent.getSELiteralFactory().create(l);
OWLOntology ontology = sl.getOntology();
OWLIndividualAxiom axiom = sl.createAxiom();
@@ -80,7 +114,13 @@
@Override
public Literal contains(Literal l) {
try {
- agent.getSELiteralFactory().create(l); // just to check for enrichement
+ // TODO: use OWLOntology#contains
+ SELiteral sl = agent.getSELiteralFactory().create(l); // <- currently just to establish if semantically-enriched
+ //OWLIndividualAxiom axiom = sl.createAxiom();
+ //OWLAnnotation annot = agent.getOntologyManager().getOWLDataFactory().getOWLLabelAnnotation(sl.getSemanticallyNaiveAnnotations().toString()); //TODO: more efficient way of serialising list terms?
+ //OWLAxiomAnnotationAxiom annotAxiom = agent.getOntologyManager().getOWLDataFactory().getOWLAxiomAnnotationAxiom(axiom, annot);
+
+
Iterator<Literal> it = getRelevant(l);
if(it.hasNext()){
return it.next();
@@ -119,6 +159,9 @@
}
relevant.add(found.getLiteral());
+
+
+
}
getLogger().fine("... found: "+relevant);
}catch(NotEnrichedException e){
@@ -129,6 +172,30 @@
}
return relevant.iterator();
}
+
+
+ /**
+ * TODO: Currently only returns asserted ABox axioms. Include option to also show inferences?
+ */
+ @Override
+ public Iterator<Literal> iterator() {
+ List<Literal> bels = new Vector<Literal>();
+
+ // add all SN-Literals
+ Iterator it = super.iterator();
+ while(it.hasNext()){
+ bels.add((Literal)it.next());
+ }
+
+ // add all SE-Literals (asserted)
+ try{
+ bels.addAll(agent.getABoxState());
+ }catch(JasdlException e){
+ getLogger().warning("Exception caught while retrieving ABox state: "+e);
+ }
+
+ return bels.iterator();
+ }
Added: trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/BeliefBaseContractor.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/BeliefBaseContractor.java (rev 0)
+++ trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/BeliefBaseContractor.java 2008-03-20 23:22:41 UTC (rev 1169)
@@ -0,0 +1,88 @@
+package jasdl.bb.revision;
+
+import java.util.List;
+import java.util.Set;
+import java.util.Vector;
+import java.util.logging.Logger;
+
+import org.semanticweb.owl.inference.OWLReasonerException;
+import org.semanticweb.owl.model.OWLAxiom;
+import org.semanticweb.owl.model.OWLDescription;
+import org.semanticweb.owl.model.OWLOntologyChange;
+import org.semanticweb.owl.model.OWLOntologyChangeException;
+import org.semanticweb.owl.model.OWLOntologyCreationException;
+import org.semanticweb.owl.model.OWLOntologyManager;
+import org.semanticweb.owl.model.RemoveAxiom;
+import org.semanticweb.owl.model.UnknownOWLOntologyException;
+
+import com.clarkparsia.explanation.BlackBoxExplanation;
+import com.clarkparsia.explanation.HSTExplanationGenerator;
+import com.clarkparsia.explanation.ReasonerFactory;
+import com.clarkparsia.explanation.SatisfiabilityConverter;
+
+public class BeliefBaseContractor extends IsolatedOntologyOperation{
+
+ private Logger logger;
+
+ public BeliefBaseContractor(OWLOntologyManager originalManager, ReasonerFactory reasonerFactory, Logger logger) throws OWLOntologyCreationException, OWLOntologyChangeException, UnknownOWLOntologyException, OWLReasonerException {
+ super(originalManager, reasonerFactory);
+ this.logger = logger;
+ }
+
+ public List<OWLAxiom> contract(Set<OWLAxiom> contractionSet, KernelsetFilter kernelsetFilter, IncisionFunction incisionFunction) throws OWLOntologyChangeException, OWLReasonerException{
+ List<OWLAxiom> toRemove = new Vector<OWLAxiom>(); // to be removed OUTSIDE isolated ontology elsewhere
+ for(OWLAxiom toContract : contractionSet){
+ toRemove.addAll(contract(toContract, kernelsetFilter, incisionFunction));
+ }
+ return toRemove;
+ }
+
+ public List<OWLAxiom> contract(OWLAxiom axiom, KernelsetFilter kernelsetFilter, IncisionFunction incisionFunction) throws OWLOntologyChangeException, OWLReasonerException{
+ List<OWLAxiom> toRemove = new Vector<OWLAxiom>();
+
+ logger.fine("Contracting "+axiom+"...");
+ toRemove.add(axiom);
+ // note: either axiom is a which is contradictory by definition, or another which is entailed by definition
+ isolatedOntologyManager.applyChange(new RemoveAxiom(isolatedOntology, axiom));
+
+ //if(!axiom.equals(a)){ // otherwise we wouldn't need to contract a, can simply remove (it can't have any support by definition)
+
+ // require contraction
+ // gather justifications
+ // apply incision function (same one???)
+ // recursively contract
+
+
+ SatisfiabilityConverter satcon = new SatisfiabilityConverter(isolatedOntologyManager.getOWLDataFactory());
+ OWLDescription description = satcon.convert(axiom);
+ BlackBoxExplanation bbgen = new BlackBoxExplanation(isolatedOntologyManager);
+ HSTExplanationGenerator hstgen = new HSTExplanationGenerator(bbgen);
+ hstgen.setOntology(isolatedOntology);
+ hstgen.setReasoner(isolatedReasoner);
+ hstgen.setReasonerFactory(reasonerFactory);
+ Set<Set<OWLAxiom>> justifications = kernelsetFilter.apply(hstgen.getExplanations(description));
+
+ //Set<Set<OWLAxiom>> justifications = hstgen.getExplanations(description);
+ if(!justifications.isEmpty()){
+ logger.fine("Description of "+axiom+": "+description);
+ logger.fine("Justifications for "+axiom+": "+justifications);
+
+
+ Set<OWLAxiom> toContract = incisionFunction.apply(justifications);
+ toRemove.addAll(toContract);
+ List<OWLOntologyChange> isolatedRemovals = new Vector<OWLOntologyChange>();
+ for(OWLAxiom remove : toContract){
+ isolatedRemovals.add(new RemoveAxiom(isolatedOntology, remove));
+ }
+ logger.fine("Removing: "+toContract);
+ isolatedOntologyManager.applyChanges(isolatedRemovals);
+
+ toRemove.addAll(contract(toContract, kernelsetFilter, incisionFunction));
+ }
+ //}
+
+ return toRemove;
+
+
+ }
+}
Added: trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/BeliefBaseRevisor.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/BeliefBaseRevisor.java (rev 0)
+++ trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/BeliefBaseRevisor.java 2008-03-20 23:22:41 UTC (rev 1169)
@@ -0,0 +1,92 @@
+package jasdl.bb.revision;
+
+import java.net.URI;
+import java.util.List;
+import java.util.Set;
+import java.util.Vector;
+import java.util.logging.Logger;
+
+import org.semanticweb.owl.inference.OWLReasoner;
+import org.semanticweb.owl.inference.OWLReasonerException;
+import org.semanticweb.owl.model.AddAxiom;
+import org.semanticweb.owl.model.OWLAxiom;
+import org.semanticweb.owl.model.OWLDescription;
+import org.semanticweb.owl.model.OWLOntology;
+import org.semanticweb.owl.model.OWLOntologyChange;
+import org.semanticweb.owl.model.OWLOntologyChangeException;
+import org.semanticweb.owl.model.OWLOntologyCreationException;
+import org.semanticweb.owl.model.OWLOntologyManager;
+import org.semanticweb.owl.model.UnknownOWLOntologyException;
+
+import com.clarkparsia.explanation.BlackBoxExplanation;
+import com.clarkparsia.explanation.HSTExplanationGenerator;
+import com.clarkparsia.explanation.ReasonerFactory;
+import com.clarkparsia.explanation.SatisfiabilityConverter;
+
+public class BeliefBaseRevisor extends IsolatedOntologyOperation {
+
+ private Logger logger;
+ private OWLAxiom toAdd;
+
+ public BeliefBaseRevisor(OWLAxiom toAdd, OWLOntologyManager originalManager, ReasonerFactory reasonerFactory, Logger logger) throws UnknownOWLOntologyException, OWLOntologyCreationException, OWLOntologyChangeException, OWLReasonerException{
+ super(originalManager, reasonerFactory);
+ this.logger = logger;
+ // unfortunately, this needs to be done here (not in .revise)
+ // since JASDL (specifically) needs to annotate this axiom
+ this.toAdd = toAdd;
+ isolatedOntologyManager.applyChange(new AddAxiom(isolatedOntology, toAdd));
+ }
+
+ public List<OWLAxiom>[] revise(KernelsetFilter kernelsetFilter, IncisionFunction incisionFunction){
+ List<OWLAxiom> addList = new Vector<OWLAxiom>();
+ List<OWLAxiom> delList = new Vector<OWLAxiom>();
+ try {
+ isolatedReasoner.classify();
+
+ if(isolatedReasoner.isConsistent(isolatedOntology)){
+ addList.add(toAdd);
+ }else{
+ Set<Set<OWLAxiom>> kernelset = applyKernelOperator(toAdd, isolatedOntologyManager, isolatedOntology, isolatedReasoner, reasonerFactory);
+ kernelset = kernelsetFilter.apply(kernelset);
+ log("Explanation of inconsistency: "+kernelset);
+ BeliefBaseContractor contractor = new BeliefBaseContractor(isolatedOntologyManager, reasonerFactory, logger);
+ List<OWLAxiom> contracted = contractor.contract(incisionFunction.apply(kernelset), kernelsetFilter, incisionFunction);
+
+
+ if(!contracted.contains(toAdd)){
+ addList.add(toAdd); // remember, toAdd is not in original ontology so need to remove if it has been contracted
+ }
+ delList.addAll(contracted);
+ }
+
+
+ } catch (Exception e) {
+ logger.warning("Revision failed. Reason: ");
+ e.printStackTrace();
+ }
+
+ return new List[] {addList, delList};
+ }
+
+
+ private Set<Set<OWLAxiom>> applyKernelOperator(OWLAxiom a, OWLOntologyManager ontologyManager, OWLOntology ontology, OWLReasoner reasoner, ReasonerFactory reasonerFactory){
+ SatisfiabilityConverter satcon = new SatisfiabilityConverter(ontologyManager.getOWLDataFactory());
+ OWLDescription description = ontologyManager.getOWLDataFactory().getOWLObjectComplementOf(satcon.convert(a));
+ BlackBoxExplanation bbgen = new BlackBoxExplanation(ontologyManager);
+ HSTExplanationGenerator hstgen = new HSTExplanationGenerator(bbgen);
+ hstgen.setOntology(ontology);
+ hstgen.setReasoner(reasoner);
+ hstgen.setReasonerFactory(reasonerFactory);
+ return hstgen.getExplanations(description);
+ }
+
+
+ private void log(String msg){
+ if(logger != null){
+ logger.fine(msg);
+ }
+ }
+
+
+
+}
Added: trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/IncisionFunction.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/IncisionFunction.java (rev 0)
+++ trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/IncisionFunction.java 2008-03-20 23:22:41 UTC (rev 1169)
@@ -0,0 +1,18 @@
+package jasdl.bb.revision;
+
+import java.util.Set;
+
+import org.semanticweb.owl.model.OWLAxiom;
+
+public interface IncisionFunction {
+
+
+
+ /**
+ * Given a kernel set, establish a set of beliefs that undermine all kernels
+ * Abstract since application dependent (see parsia:brf)
+ * @param kernelset
+ * @return
+ */
+ public Set<OWLAxiom> apply(Set<Set<OWLAxiom>> input);
+}
Added: trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/IsolatedOntologyOperation.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/IsolatedOntologyOperation.java (rev 0)
+++ trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/IsolatedOntologyOperation.java 2008-03-20 23:22:41 UTC (rev 1169)
@@ -0,0 +1,59 @@
+package jasdl.bb.revision;
+
+import java.net.URI;
+import java.util.List;
+import java.util.Vector;
+
+import org.semanticweb.owl.apibinding.OWLManager;
+import org.semanticweb.owl.inference.OWLReasoner;
+import org.semanticweb.owl.inference.OWLReasonerException;
+import org.semanticweb.owl.model.AddAxiom;
+import org.semanticweb.owl.model.OWLAxiom;
+import org.semanticweb.owl.model.OWLOntology;
+import org.semanticweb.owl.model.OWLOntologyChange;
+import org.semanticweb.owl.model.OWLOntologyChangeException;
+import org.semanticweb.owl.model.OWLOntologyCreationException;
+import org.semanticweb.owl.model.OWLOntologyManager;
+import org.semanticweb.owl.model.UnknownOWLOntologyException;
+
+import com.clarkparsia.explanation.ReasonerFactory;
+// brf should clone ontology so other reasoning can carry on elsewhere
+public class IsolatedOntologyOperation {
+
+ protected OWLOntologyManager isolatedOntologyManager;
+ protected OWLOntology isolatedOntology;
+ protected ReasonerFactory reasonerFactory;
+ protected OWLReasoner isolatedReasoner;
+
+
+ public IsolatedOntologyOperation(OWLOntologyManager originalManager, ReasonerFactory reasonerFactory) throws OWLOntologyCreationException, OWLOntologyChangeException, UnknownOWLOntologyException, OWLReasonerException{
+ this.isolatedOntologyManager = OWLManager.createOWLOntologyManager();
+ this.isolatedOntology = createDebuggingOntology(originalManager, isolatedOntologyManager);
+ this.reasonerFactory = new JasdlReasonerFactory();
+ this.isolatedReasoner = reasonerFactory.createReasoner(isolatedOntologyManager);
+ this.isolatedReasoner.loadOntologies(isolatedOntologyManager.getImportsClosure(isolatedOntology));
+ }
+
+ private OWLOntology createDebuggingOntology(OWLOntologyManager from, OWLOntologyManager to) throws OWLOntologyCreationException, OWLOntologyChangeException{
+ OWLOntology debuggingOntology = to.createOntology(URI.create("http://beliefbase/isolated.owl"));
+ for(OWLOntology ontology : from.getOntologies()){
+ List<OWLOntologyChange> changes = new Vector<OWLOntologyChange>();
+ for(OWLAxiom axiom : ontology.getAxioms()){
+ AddAxiom change = new AddAxiom(debuggingOntology, axiom);
+ changes.add(change);
+ }
+ to.applyChanges(changes);
+ }
+ return debuggingOntology;
+ }
+
+ public OWLOntology getIsolatedOntology() {
+ return isolatedOntology;
+ }
+
+ public OWLOntologyManager getIsolatedOntologyManager() {
+ return isolatedOntologyManager;
+ }
+
+
+}
Added: trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/JasdlIncisionFunction.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/JasdlIncisionFunction.java (rev 0)
+++ trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/JasdlIncisionFunction.java 2008-03-20 23:22:41 UTC (rev 1169)
@@ -0,0 +1,95 @@
+package jasdl.bb.revision;
+
+import jasdl.asSemantics.JasdlAgent;
+import jasdl.bridge.seliteral.SELiteral;
+import jasdl.util.JasdlException;
+import jason.asSyntax.Atom;
+import jason.asSyntax.ListTerm;
+import jason.asSyntax.Term;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.semanticweb.owl.model.OWLAxiom;
+import org.semanticweb.owl.model.OWLIndividualAxiom;
+
+public class JasdlIncisionFunction implements IncisionFunction{
+
+
+ private JasdlAgent agent;
+ private SELiteral toAddLiteral;
+
+ /**
+ * The SELiteral to be added is required for a particularly inelegant hack that allows us
+ * to retrieve the annotations of the NOT YET ADDED axiom.
+ *
+ * @param agent required for getting trust ratings
+ * @param toAdd
+ * @param toAddAnnotations
+ */
+ public JasdlIncisionFunction(JasdlAgent agent, SELiteral toAddLiteral){
+ this.agent = agent;
+ this.toAddLiteral = toAddLiteral;
+ }
+
+ /**
+ * Chooses from each akernel axiom with lowest trust associated with it.
+ * Currently calculated using ASSERTED source annotations only.
+ * No source annotation is taken as trust = 0;
+ */
+ public Set<OWLAxiom> apply(Set<Set<OWLAxiom>> kernelset) {
+ try{
+ Set<OWLAxiom> chosen = new HashSet<OWLAxiom>();
+ for(Set<OWLAxiom> akernel : kernelset){
+ if(!akernel.isEmpty()){
+ OWLAxiom leastTrusted = null; // guaranteed to take a value
+ float minTrustRating = 1f;
+ for(OWLAxiom axiom : akernel){
+ float trustRating = getTrustRating(axiom);
+ agent.getLogger().finest("Trust rating of "+axiom+"="+trustRating);
+ if(trustRating <= minTrustRating){
+ minTrustRating = trustRating;
+ leastTrusted = axiom;
+ }
+ }
+ chosen.add(leastTrusted);
+ }
+ }
+ return chosen;
+ }catch(Exception e){
+ e.printStackTrace(); // TODO: introduce a seperate exception hierarchy once this package has been seperated from JASDL
+ return null;
+ }
+ }
+
+ /**
+ * Currently returns the trust rating of the most trusted source. Future work will look at better ways of calculating this.
+ * @param axiom
+ * @return
+ * @throws JasdlException
+ */
+ private float getTrustRating(OWLAxiom axiom) throws JasdlException{
+ ListTerm sources;
+ if(axiom.equals(toAddLiteral.createAxiom())){ // hack to get the annotations of the NOT YET ADDED toAdd axiom
+ sources = toAddLiteral.getLiteral().getSources();
+ }else{
+ SELiteral sl = agent.getToSELiteralConverter().convert((OWLIndividualAxiom)axiom); // kernel filter ensures axiom is an OWLIndividualAxiom
+ sources = sl.getLiteral().getSources();
+ }
+ agent.getLogger().finest("Sources of "+axiom+"="+sources);
+ float maxTrustRating = 0f; // if no sources available, trust is 0
+ for(Term source : sources){
+ if(!source.isAtom()){
+ throw new JasdlException("Invalid source annotation "+source);
+ }
+ Atom name = (Atom)source;
+ float trustRating = agent.getTrustRating(name);
+ if(trustRating > maxTrustRating){
+ maxTrustRating = trustRating;
+ }
+ }
+ return maxTrustRating;
+ }
+
+
+}
Added: trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/JasdlReasonerFactory.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/JasdlReasonerFactory.java (rev 0)
+++ trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/JasdlReasonerFactory.java 2008-03-20 23:22:41 UTC (rev 1169)
@@ -0,0 +1,28 @@
+package jasdl.bb.revision;
+
+import org.mindswap.pellet.owlapi.Reasoner;
+import org.semanticweb.owl.inference.OWLReasoner;
+import org.semanticweb.owl.model.OWLOntologyManager;
+
+import com.clarkparsia.explanation.ReasonerFactory;
+
+public class JasdlReasonerFactory implements ReasonerFactory{
+
+ public JasdlReasonerFactory() {
+ super();
+ }
+
+ public boolean requiresExplicitClassification() {
+ return false;
+ }
+
+ public OWLReasoner createReasoner(OWLOntologyManager manager) {
+ return new Reasoner(manager);
+ }
+
+ public String getReasonerName() {
+ return "reasoner";
+ }
+
+
+}
Added: trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/KernelsetFilter.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/KernelsetFilter.java (rev 0)
+++ trunk/applications/jasdl-owlapi/src/jasdl/bb/revision/KernelsetFilter.java 2008-0...
[truncated message content] |
|
From: <jom...@us...> - 2008-03-20 18:15:48
|
Revision: 1168
http://jason.svn.sourceforge.net/jason/?rev=1168&view=rev
Author: jomifred
Date: 2008-03-20 11:15:42 -0700 (Thu, 20 Mar 2008)
Log Message:
-----------
BRF (belief revision function) may throws an exception
Modified Paths:
--------------
trunk/applications/jason-moise/src/jmoise/OrgAgent.java
trunk/examples/gold-miners-II/arch/MinerArch.java
trunk/examples/sniffer/comm/SnifferCentralised.java
trunk/src/jason/asSemantics/Agent.java
trunk/src/jason/asSemantics/TransitionSystem.java
trunk/src/jason/bb/TextPersistentBB.java
trunk/src/test/BeliefBaseTest.java
trunk/src/test/StdLibTest.java
Added Paths:
-----------
trunk/src/jason/RevisionFailedException.java
Modified: trunk/applications/jason-moise/src/jmoise/OrgAgent.java
===================================================================
--- trunk/applications/jason-moise/src/jmoise/OrgAgent.java 2008-03-20 08:56:41 UTC (rev 1167)
+++ trunk/applications/jason-moise/src/jmoise/OrgAgent.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -1,6 +1,7 @@
package jmoise;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSemantics.Agent;
import jason.asSemantics.Event;
@@ -129,15 +130,18 @@
logger.log(Level.SEVERE, "Error!", e);
}
} // while
-
- if (updateGoalBels)
- updateGoalBels();
- if (updateGoalEvt)
- generateOrgGoalEvents();
+ try {
+ if (updateGoalBels)
+ updateGoalBels();
+ if (updateGoalEvt)
+ generateOrgGoalEvents();
+ } catch (Exception e) {
+ logger.log(Level.SEVERE, "Error!", e);
+ }
}
- private Literal addAsBel(String b) {
+ private Literal addAsBel(String b) throws RevisionFailedException {
Literal l = Literal.parseLiteral(b);
if (l.isAtom())
l = new Literal(l.getFunctor());
@@ -146,7 +150,7 @@
return l;
}
- void generateObligationPermissionEvents(Pred m) {
+ void generateObligationPermissionEvents(Pred m) throws RevisionFailedException {
// computes this agent obligations in the scheme
String schId = m.getTerm(0).toString();
String grId = m.getTerm(1).toString();
@@ -217,7 +221,7 @@
private static final PredicateIndicator commitmentLiteral = new PredicateIndicator("commitment", 3);
/** removes all bels related to a Scheme */
- void removeBeliefs(String schId) {
+ void removeBeliefs(String schId) throws RevisionFailedException {
Agent ag = getTS().getAg();
ag.abolish(buildLiteralToCleanBB(schId, obligationLiteral, false), null);
ag.abolish(buildLiteralToCleanBB(schId, permissionLiteral, false), null);
@@ -246,7 +250,7 @@
}
/** add/remove bel regarding the goals' state */
- void updateGoalBels() {
+ void updateGoalBels() throws RevisionFailedException {
// for all missions
// for all goals
// if not in BB, add
@@ -258,7 +262,7 @@
}
}
- void updateGoalBels(Pred arg) {
+ void updateGoalBels(Pred arg) throws RevisionFailedException {
String schId = arg.getTerm(0).toString();
String goalId = arg.getTerm(1).toString();
for (SchemeInstance sch : getMyOEAgent().getAllMySchemes()) {
@@ -277,7 +281,7 @@
private static final Atom aImpossible = new Atom("impossible");
private static final Atom aAchieved = new Atom("achieved");
- void updateGoalBels(GoalInstance gi) {
+ void updateGoalBels(GoalInstance gi) throws RevisionFailedException {
Pred gap = Pred.parsePred(gi.getAsProlog());
if (gi.getScheme().getRoot() == gi) {
Modified: trunk/examples/gold-miners-II/arch/MinerArch.java
===================================================================
--- trunk/examples/gold-miners-II/arch/MinerArch.java 2008-03-20 08:56:41 UTC (rev 1167)
+++ trunk/examples/gold-miners-II/arch/MinerArch.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -1,6 +1,7 @@
package arch;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSemantics.Message;
import jason.asSyntax.Atom;
@@ -73,7 +74,7 @@
/** The perception of the grid size is removed from the percepts list
and "directly" added as a belief */
- void gsizePerceived(int w, int h) {
+ void gsizePerceived(int w, int h) throws RevisionFailedException {
if (view != null) {
view.dispose();
}
@@ -87,14 +88,14 @@
/** The perception of the depot location is removed from the percepts list
and "directly" added as a belief */
- void depotPerceived(int x, int y) {
+ void depotPerceived(int x, int y) throws RevisionFailedException {
model.setDepot(x, y);
getTS().getAg().addBel(Literal.parseLiteral("depot("+simId+","+x+","+y+")"));
}
/** The number of steps of the simulation is removed from the percepts list
- and "directly" added as a belief */
- void stepsPerceived(int s) {
+ and "directly" added as a belief */
+ void stepsPerceived(int s) throws RevisionFailedException {
getTS().getAg().addBel(Literal.parseLiteral("steps("+simId+","+s+")"));
model.setMaxSteps(s);
}
@@ -186,7 +187,7 @@
model.add(WorldModel.ENEMY, x, y);
}
- void simulationEndPerceived(String result) {
+ void simulationEndPerceived(String result) throws RevisionFailedException {
getTS().getAg().addBel(Literal.parseLiteral("end_of_simulation("+simId+","+result+")"));
playing = false;
}
Modified: trunk/examples/sniffer/comm/SnifferCentralised.java
===================================================================
--- trunk/examples/sniffer/comm/SnifferCentralised.java 2008-03-20 08:56:41 UTC (rev 1167)
+++ trunk/examples/sniffer/comm/SnifferCentralised.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -1,6 +1,7 @@
package comm;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSemantics.Message;
import jason.asSyntax.Atom;
@@ -61,6 +62,10 @@
e.addTerm(new Atom(m.getSender()));
e.addTerm(new Atom(m.getReceiver()));
e.addTerm(new StringTermImpl(m.getPropCont().toString()));
- getTS().getAg().addBel(e);
+ try {
+ getTS().getAg().addBel(e);
+ } catch (RevisionFailedException e1) {
+ e1.printStackTrace();
+ }
}
}
Added: trunk/src/jason/RevisionFailedException.java
===================================================================
--- trunk/src/jason/RevisionFailedException.java (rev 0)
+++ trunk/src/jason/RevisionFailedException.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -0,0 +1,47 @@
+//----------------------------------------------------------------------------
+// Copyright (C) 2003 Rafael H. Bordini, Jomi F. Hubner, et al.
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// To contact the authors:
+// http://www.dur.ac.uk/r.bordini
+// http://www.inf.furb.br/~jomi
+//
+// CVS information:
+// $Date: 2007-02-19 16:53:54 +0100 (Mon, 19 Feb 2007) $
+// $Revision: 751 $
+// $Log$
+// Revision 1.3 2005/08/12 22:26:08 jomifred
+// add cvs keywords
+//
+//
+//----------------------------------------------------------------------------
+
+package jason;
+
+public class RevisionFailedException extends JasonException {
+
+ public RevisionFailedException() {
+ }
+
+ public RevisionFailedException(String msg) {
+ super(msg);
+ }
+
+ public RevisionFailedException(String msg, Exception cause) {
+ super(msg);
+ initCause(cause);
+ }
+}
Modified: trunk/src/jason/asSemantics/Agent.java
===================================================================
--- trunk/src/jason/asSemantics/Agent.java 2008-03-20 08:56:41 UTC (rev 1167)
+++ trunk/src/jason/asSemantics/Agent.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -24,6 +24,7 @@
package jason.asSemantics;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSyntax.Atom;
import jason.asSyntax.Literal;
@@ -312,7 +313,7 @@
}
/** add the initial beliefs in BB and produce the corresponding events */
- public void addInitialBelsInBB() {
+ public void addInitialBelsInBB() throws RevisionFailedException {
// Once beliefs are stored in a Stack in the BB, insert them in inverse order
for (int i=initialBels.size()-1; i >=0; i--) {
Literal b = initialBels.get(i);
@@ -544,7 +545,7 @@
* nothing change, returns null.
*/
@SuppressWarnings("unchecked")
- public List<Literal>[] brf(Literal beliefToAdd, Literal beliefToDel, Intention i) {
+ public List<Literal>[] brf(Literal beliefToAdd, Literal beliefToDel, Intention i) throws RevisionFailedException {
// This class does not implement belief revision! It
// is supposed that a subclass will do it.
// It simply add/del the belief.
@@ -595,7 +596,7 @@
* events. If <i>bel</i> has no source, add
* <code>source(self)</code>. (the belief is not cloned!)
*/
- public boolean addBel(Literal bel) {
+ public boolean addBel(Literal bel) throws RevisionFailedException {
if (!bel.hasSource()) {
if (bel instanceof Atom)
bel = new Literal(bel.getFunctor());
@@ -614,7 +615,7 @@
* If the agent believes in <i>bel</i>, removes it (calling brf)
* and generate the event.
*/
- public boolean delBel(Literal bel) {
+ public boolean delBel(Literal bel) throws RevisionFailedException {
List<Literal>[] result = brf(null, bel, Intention.EmptyInt);
if (result != null && ts != null) {
ts.updateEvents(result, Intention.EmptyInt);
@@ -627,7 +628,7 @@
/** Removes all occurrences of <i>bel</i> in BB.
If <i>un</i> is null, an empty Unifier is used.
*/
- public void abolish(Literal bel, Unifier un) {
+ public void abolish(Literal bel, Unifier un) throws RevisionFailedException {
List<Literal> toDel = new ArrayList<Literal>();
Iterator<Literal> il = getBB().getRelevant(bel);
Modified: trunk/src/jason/asSemantics/TransitionSystem.java
===================================================================
--- trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-20 08:56:41 UTC (rev 1167)
+++ trunk/src/jason/asSemantics/TransitionSystem.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -24,6 +24,7 @@
package jason.asSemantics;
import jason.JasonException;
+import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSyntax.Atom;
import jason.asSyntax.BodyLiteral;
@@ -516,10 +517,15 @@
// to delete, create events as external to avoid that
// remove/add create two events for the same intention
- List<Literal>[] result = ag.brf(null, bc, conf.C.SI); // the intention is not the new focus
- if (result != null) { // really delete something
- // generate events
- updateEvents(result,Intention.EmptyInt);
+ try {
+ List<Literal>[] result = ag.brf(null, bc, conf.C.SI); // the intention is not the new focus
+ if (result != null) { // really delete something
+ // generate events
+ updateEvents(result,Intention.EmptyInt);
+ }
+ } catch (RevisionFailedException re) {
+ generateGoalDeletion();
+ break;
}
// add the belief, so no break;
@@ -543,15 +549,19 @@
body.makeVarsAnnon();
// call BRF
- result = ag.brf(body,null,conf.C.SI); // the intention is not the new focus
- if (result != null) { // really add something
- // generate events
- updateEvents(result,newfocus);
- if (!setts.sameFocus()) {
- updateIntention();
- }
- } else {
- updateIntention();
+ try {
+ List<Literal>[] result = ag.brf(body,null,conf.C.SI); // the intention is not the new focus
+ if (result != null) { // really add something
+ // generate events
+ updateEvents(result,newfocus);
+ if (!setts.sameFocus()) {
+ updateIntention();
+ }
+ } else {
+ updateIntention();
+ }
+ } catch (RevisionFailedException re) {
+ generateGoalDeletion();
}
break;
@@ -569,16 +579,20 @@
newfocus = conf.C.SI;
// call BRF
- result = ag.brf(null,body, conf.C.SI); // the intention is not the new focus
- if (result != null) { // really change something
- // generate events
- updateEvents(result,newfocus);
- if (!setts.sameFocus()) {
- updateIntention();
- }
- } else {
- updateIntention();
- }
+ try {
+ List<Literal>[] result = ag.brf(null,body, conf.C.SI); // the intention is not the new focus
+ if (result != null) { // really change something
+ // generate events
+ updateEvents(result,newfocus);
+ if (!setts.sameFocus()) {
+ updateIntention();
+ }
+ } else {
+ updateIntention();
+ }
+ } catch (RevisionFailedException re) {
+ generateGoalDeletion();
+ }
break;
}
}
@@ -790,7 +804,7 @@
}
}
-
+ /** generate a failure event for the current intention */
private void generateGoalDeletion() throws JasonException {
IntendedMeans im = conf.C.SI.peek();
if (im.isGoalAdd()) {
Modified: trunk/src/jason/bb/TextPersistentBB.java
===================================================================
--- trunk/src/jason/bb/TextPersistentBB.java 2008-03-20 08:56:41 UTC (rev 1167)
+++ trunk/src/jason/bb/TextPersistentBB.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -1,5 +1,6 @@
package jason.bb;
+import jason.RevisionFailedException;
import jason.asSemantics.Agent;
import jason.asSyntax.Literal;
@@ -21,11 +22,15 @@
File file = null;
public void init(Agent ag, String[] args) {
- file = new File(ag.getTS().getUserAgArch().getAgName() + ".bb");
- logger.fine("reading from file " + file);
- if (file.exists()) {
- ag.parseAS(file.getAbsolutePath());
- ag.addInitialBelsInBB();
+ try {
+ file = new File(ag.getTS().getUserAgArch().getAgName() + ".bb");
+ logger.fine("reading from file " + file);
+ if (file.exists()) {
+ ag.parseAS(file.getAbsolutePath());
+ ag.addInitialBelsInBB();
+ }
+ } catch (RevisionFailedException e) {
+ logger.log(Level.SEVERE,"Error in init.",e);
}
}
Modified: trunk/src/test/BeliefBaseTest.java
===================================================================
--- trunk/src/test/BeliefBaseTest.java 2008-03-20 08:56:41 UTC (rev 1167)
+++ trunk/src/test/BeliefBaseTest.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -1,5 +1,6 @@
package test;
+import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSemantics.Agent;
import jason.asSemantics.Intention;
@@ -519,7 +520,7 @@
@SuppressWarnings("unchecked")
- public void testBelBRF() {
+ public void testBelBRF() throws RevisionFailedException {
Agent ag = new Agent();
AgArch arch = new AgArch();
arch.setArchInfraTier(new CentralisedAgArch());
Modified: trunk/src/test/StdLibTest.java
===================================================================
--- trunk/src/test/StdLibTest.java 2008-03-20 08:56:41 UTC (rev 1167)
+++ trunk/src/test/StdLibTest.java 2008-03-20 18:15:42 UTC (rev 1168)
@@ -1,5 +1,6 @@
package test;
+import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSemantics.Agent;
import jason.asSemantics.Circumstance;
@@ -95,7 +96,7 @@
"[ok(10)[source(rafa)],[ok(20)[source(rafa)],ok(30)[source(rafa)],[ok(40)[source(rafa)],ok(50)[source(rafa)],ok(60)[source(rafa)]]]]");
}
- public void testFindAll() {
+ public void testFindAll() throws RevisionFailedException {
Agent ag = new Agent();
ag.setLogger(null);
AgArch arch = new AgArch();
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-20 08:56:49
|
Revision: 1167
http://jason.svn.sourceforge.net/jason/?rev=1167&view=rev
Author: jomifred
Date: 2008-03-20 01:56:41 -0700 (Thu, 20 Mar 2008)
Log Message:
-----------
fix bug related to plan's TE being an Atom
Modified Paths:
--------------
trunk/src/jason/asSyntax/Atom.java
trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
trunk/src/jason/asSyntax/parser/as2j.java
Modified: trunk/src/jason/asSyntax/Atom.java
===================================================================
--- trunk/src/jason/asSyntax/Atom.java 2008-03-19 17:50:11 UTC (rev 1166)
+++ trunk/src/jason/asSyntax/Atom.java 2008-03-20 08:56:41 UTC (rev 1167)
@@ -142,6 +142,12 @@
return super.addAnnot(t);
}
+ @Override
+ public void addAnnots(List<Term> l) {
+ logger.log(Level.SEVERE, "You should not add annots '"+l+"' in atom "+this+"\n",new Exception());
+ super.addAnnots(l);
+ }
+
@Override public void makeTermsAnnon() { }
@Override public void makeVarsAnnon() { }
Modified: trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc
===================================================================
--- trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-19 17:50:11 UTC (rev 1166)
+++ trunk/src/jason/asSyntax/parser/AS2JavaParser.jcc 2008-03-20 08:56:41 UTC (rev 1167)
@@ -310,7 +310,10 @@
( F=literal()
| F=var()
- ) { return new Trigger(teOp,teType,F); }
+ ) { if (F instanceof Atom)
+ F = new Literal(F.getFunctor()); // trigger literal must be a literal and not an atom
+ return new Trigger(teOp,teType,F);
+ }
}
/* Literal */
Modified: trunk/src/jason/asSyntax/parser/as2j.java
===================================================================
--- trunk/src/jason/asSyntax/parser/as2j.java 2008-03-19 17:50:11 UTC (rev 1166)
+++ trunk/src/jason/asSyntax/parser/as2j.java 2008-03-20 08:56:41 UTC (rev 1167)
@@ -406,6 +406,8 @@
jj_consume_token(-1);
throw new ParseException();
}
+ if (F instanceof Atom)
+ F = new Literal(F.getFunctor()); // trigger literal must be a literal and not an atom
{if (true) return new Trigger(teOp,teType,F);}
throw new Error("Missing return statement in function");
}
@@ -1166,28 +1168,6 @@
finally { jj_save(1, xla); }
}
- final private boolean jj_3R_19() {
- if (jj_scan_token(39)) return true;
- if (jj_3R_25()) return true;
- if (jj_scan_token(40)) return true;
- return false;
- }
-
- final private boolean jj_3R_18() {
- if (jj_3R_24()) return true;
- return false;
- }
-
- final private boolean jj_3R_17() {
- if (jj_3R_23()) return true;
- return false;
- }
-
- final private boolean jj_3R_22() {
- if (jj_scan_token(34)) return true;
- return false;
- }
-
final private boolean jj_3R_71() {
if (jj_scan_token(TK_INTMOD)) return true;
return false;
@@ -1667,6 +1647,28 @@
return false;
}
+ final private boolean jj_3R_19() {
+ if (jj_scan_token(39)) return true;
+ if (jj_3R_25()) return true;
+ if (jj_scan_token(40)) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_18() {
+ if (jj_3R_24()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_17() {
+ if (jj_3R_23()) return true;
+ return false;
+ }
+
+ final private boolean jj_3R_22() {
+ if (jj_scan_token(34)) return true;
+ return false;
+ }
+
public as2jTokenManager token_source;
SimpleCharStream jj_input_stream;
public Token token, jj_nt;
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-19 17:50:14
|
Revision: 1166
http://jason.svn.sourceforge.net/jason/?rev=1166&view=rev
Author: jomifred
Date: 2008-03-19 10:50:11 -0700 (Wed, 19 Mar 2008)
Log Message:
-----------
jason-team: write a "summary" of the world state (ag's location) in a file
Modified Paths:
--------------
trunk/applications/jason-team/AC-Local-JasonTeam.mas2j
trunk/applications/jason-team/readme.txt
trunk/applications/jason-team/src/asl/dummy.asl
trunk/applications/jason-team/src/java/arch/ACArchitecture.java
trunk/applications/jason-team/src/java/arch/CowboyArch.java
Modified: trunk/applications/jason-team/AC-Local-JasonTeam.mas2j
===================================================================
--- trunk/applications/jason-team/AC-Local-JasonTeam.mas2j 2008-03-18 22:36:40 UTC (rev 1165)
+++ trunk/applications/jason-team/AC-Local-JasonTeam.mas2j 2008-03-19 17:50:11 UTC (rev 1166)
@@ -11,7 +11,7 @@
agents:
dummy1 dummy.asl
- [verbose=1, gui=no, write_model=no, ac_sim_back_dir="./massim-server/backup",
+ [verbose=1, gui=no, write_model=yes, ac_sim_back_dir="./massim-server/backup",
host="localhost", port=12300, username=participant1, password="1"]
agentArchClass arch.ACArchitecture
agentClass agent.SelectEvent
Modified: trunk/applications/jason-team/readme.txt
===================================================================
--- trunk/applications/jason-team/readme.txt 2008-03-18 22:36:40 UTC (rev 1165)
+++ trunk/applications/jason-team/readme.txt 2008-03-19 17:50:11 UTC (rev 1166)
@@ -36,7 +36,15 @@
5. start the simulation
go to shell running startServer.sh and press ENTER
+6. you can get the agents location with the command
+
+ tail -f world-state-dummy1.txt
+7. the get the graphical view of some agent, add gui=yes in
+ the agent's option (.mas2j file)
+
+
+
---- OLD ----
Our team can run in three configurations (Jason 1.0.2 is required):
Modified: trunk/applications/jason-team/src/asl/dummy.asl
===================================================================
--- trunk/applications/jason-team/src/asl/dummy.asl 2008-03-18 22:36:40 UTC (rev 1165)
+++ trunk/applications/jason-team/src/asl/dummy.asl 2008-03-19 17:50:11 UTC (rev 1166)
@@ -37,6 +37,11 @@
-- (it is a kind of persistent goal)
*/
+// if the target is changed, "restart" move
++target(_,_)
+ <- .drop_desire(move);
+ !!move.
+
// I still do not know my location
+!move
: not pos(_,_,_)
@@ -50,8 +55,9 @@
(not target(_,_) | // I have no target OR
target(X,Y) | // I am at target OR
(target(BX,BY) & jia.direction(X, Y, BX, BY, skip))) // is impossible to go to target
- <- !define_new_target;
- !move.
+ <- ?random_pos(NX,NY);
+ jia.set_target(NX,NY);
+ -+target(NX,NY).
// does one step towards target
+!move
@@ -63,20 +69,15 @@
// in case of failure, move
-!move
- <- .current_intention(I); .println("failure in move:",I);
+ <- .current_intention(I); .println("failure in move, intention: ",I);
!move.
-/* -- add a belief target random move -- */
-
-+!define_new_target
- <- ?random_pos(NX,NY);
- jia.set_target(NX,NY);
- -+target(NX,NY).
++restart
+ <- .print("*** restart ***");
+ .drop_all_desires;
+ !move.
-
-+restart <- .print("*** Restart! "); .drop_all_desires; !define_new_target; !move.
-
/* -- tests -- */
+gsize(Weight,Height) <- .println("gsize = ",Weight,",",Height).
@@ -85,4 +86,4 @@
+cell(X,Y,Type) <- .println("cell = ",X,",",Y," = ",Type).
+pratio(R) <- .println("pratio = ",R).
-+pos(X,Y,S) <- .println("pos = ",X,",",Y,"/",S).
\ No newline at end of file
++pos(X,Y,S) <- .println("pos = ",X,",",Y,"/",S).
Modified: trunk/applications/jason-team/src/java/arch/ACArchitecture.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-18 22:36:40 UTC (rev 1165)
+++ trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-19 17:50:11 UTC (rev 1166)
@@ -3,6 +3,7 @@
import jason.JasonException;
import jason.asSemantics.ActionExec;
import jason.asSyntax.Literal;
+import jason.functions.log;
import jason.mas2j.ClassParameters;
import jason.runtime.Settings;
@@ -128,6 +129,8 @@
ActionExec lastAction;
Queue<ActionExec> toExecute = new ConcurrentLinkedQueue<ActionExec>();
+ String x;
+
WaitSleep() {
super("WaitSpeepToSendAction");
}
@@ -146,7 +149,10 @@
ActionExec action = toExecute.poll();
action.setResult(true);
feedback.add(action);
- }
+ }
+
+ logger.info("last action sent is "+x);
+ x = null;
}
synchronized void go() {
@@ -163,7 +169,8 @@
lastAction = null;
waitSleep();
if (lastAction != null) {
- proxy.sendAction(lastAction.getActionTerm().getTerm(0).toString());
+ x = lastAction.getActionTerm().getTerm(0).toString();
+ proxy.sendAction(x);
toExecute.offer(lastAction);
}
} catch (InterruptedException e) {
Modified: trunk/applications/jason-team/src/java/arch/CowboyArch.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/CowboyArch.java 2008-03-18 22:36:40 UTC (rev 1165)
+++ trunk/applications/jason-team/src/java/arch/CowboyArch.java 2008-03-19 17:50:11 UTC (rev 1166)
@@ -13,7 +13,11 @@
import jason.runtime.Settings;
import java.io.PrintWriter;
+import java.util.HashMap;
import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -115,6 +119,8 @@
acView.setPriority(Thread.MIN_PRIORITY);
acView.start();
}
+ if (writeModelThread != null)
+ writeModelThread.reset();
}
/** The perception of the corral location is removed from the percepts list
@@ -232,7 +238,7 @@
void setCycle(int s) {
cycle = s;
if (view != null) view.setCycle(cycle);
- //if (writeModelT != null) writeModelT.writeModel();
+ if (writeModelThread != null) writeModelThread.go();
}
void setScore(int s) {
@@ -311,32 +317,72 @@
class WriteModelThread extends Thread {
+
+ Map<Integer,List<Location>> locations;
+
+ public void reset() {
+ // init locations
+ locations = new HashMap<Integer, List<Location>>();
+ for (int i=0; i<WorldModel.agsByTeam; i++) {
+ locations.put(i, new LinkedList<Location>());
+ }
+ }
+
public void run() {
+ reset();
+
String fileName = "world-state-"+getAgName()+".txt";
PrintWriter out = null;
try {
out = new PrintWriter(fileName);
while (true) {
- waitSomeTime();
- if (model != null && playing) {
- out.println("\n\n** Agent "+getAgName()+" in cycle "+cycle+"\n");
- //for (int i=0; i<model.getNbOfAgs(); i++) {
- // TODO: out.println("miner"+(i+1)+" is carrying "+model.getGoldsWithAg(i)+" gold(s), at "+model.getAgPos(i));
- //}
- out.println(model.toString());
- out.flush();
- }
+ try {
+ waitSomeTime();
+ if (model != null && playing) {
+ //out.println("\n\n** Agent "+getAgName()+" in cycle "+cycle+"\n");
+ //for (int i=0; i<model.getNbOfAgs(); i++) {
+ // out.println("miner"+(i+1)+" is carrying "+model.getGoldsWithAg(i)+" gold(s), at "+model.getAgPos(i));
+ //}
+ //out.println(model.toString());
+ StringBuilder s = new StringBuilder(String.format("Step %5d : ", cycle));
+ for (int i=0; i<WorldModel.agsByTeam; i++) {
+ Location agp = model.getAgPos(i);
+ if (agp != null) {
+ // count how long the agent is in the same location
+ int c = 0;
+ Iterator<Location> il = locations.get(i).iterator();
+ while (il.hasNext() && il.next().equals(agp) && c <= 11) {
+ c++;
+ }
+ String sc = "*";
+ if (c < 10) sc = ""+c;
+
+ locations.get(i).add(0,agp);
+ s.append(String.format("%5d,%2d/%s", agp.x, agp.y, sc));
+ }
+ }
+ logger.info(s.toString());
+ out.println(s.toString());
+ out.flush();
+ }
+ } catch (InterruptedException e) { // no problem, quit the thread
+ return;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
- } catch (InterruptedException e) { // no problem, quit the thread
- } catch (Exception e) {
- e.printStackTrace();
+ } catch (Exception e) {
+ e.printStackTrace();
} finally {
out.close();
}
}
synchronized private void waitSomeTime() throws InterruptedException {
- wait(2000);
+ wait(4000);
}
+ synchronized private void go() {
+ notifyAll();
+ }
}
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-18 22:36:43
|
Revision: 1165
http://jason.svn.sourceforge.net/jason/?rev=1165&view=rev
Author: jomifred
Date: 2008-03-18 15:36:40 -0700 (Tue, 18 Mar 2008)
Log Message:
-----------
improve jason-team
. send action to simulator when the agent is going to sleep (nothing else thus to decide)
. dummy has a "persistent goal" of moving
Modified Paths:
--------------
trunk/applications/jason-team/AC-Local-JasonTeam.mas2j
trunk/applications/jason-team/src/asl/dummy.asl
trunk/applications/jason-team/src/java/arch/ACArchitecture.java
trunk/applications/jason-team/src/java/arch/ACProxy.java
trunk/applications/jason-team/src/java/arch/CowboyArch.java
trunk/src/jason/asSyntax/Literal.java
Added Paths:
-----------
trunk/examples/gold-miners-II/miners.mas2j
Removed Paths:
-------------
trunk/examples/gold-miners-II/JasonTeam.mas2j
Modified: trunk/applications/jason-team/AC-Local-JasonTeam.mas2j
===================================================================
--- trunk/applications/jason-team/AC-Local-JasonTeam.mas2j 2008-03-18 21:40:34 UTC (rev 1164)
+++ trunk/applications/jason-team/AC-Local-JasonTeam.mas2j 2008-03-18 22:36:40 UTC (rev 1165)
@@ -15,32 +15,32 @@
host="localhost", port=12300, username=participant1, password="1"]
agentArchClass arch.ACArchitecture
agentClass agent.SelectEvent
- beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)");
+ beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)","corral(_,_,_,_)","pratio(_)");
dummy2 dummy.asl
[verbose=1,host="localhost", port=12300, username=participant2, password="2"]
agentArchClass arch.ACArchitecture
agentClass agent.SelectEvent
- beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)");
+ beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)","corral(_,_,_,_)","pratio(_)");
dummy3 dummy.asl
[verbose=1,host="localhost", port=12300, username=participant3, password="3"]
agentArchClass arch.ACArchitecture
agentClass agent.SelectEvent
- beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)");
+ beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)","corral(_,_,_,_)","pratio(_)");
dummy4 dummy.asl
[verbose=1,host="localhost", port=12300, username=participant4, password="4"]
agentArchClass arch.ACArchitecture
agentClass agent.SelectEvent
- beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)");
+ beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)","corral(_,_,_,_)","pratio(_)");
dummy5 dummy.asl
[verbose=1,host="localhost", port=12300, username=participant5, password="5"]
agentArchClass arch.ACArchitecture
agentClass agent.SelectEvent
- beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)");
+ beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)","corral(_,_,_,_)","pratio(_)");
dummy6 dummy.asl
[verbose=1,host="localhost", port=12300, username=participant6, password="6"]
agentArchClass arch.ACArchitecture
agentClass agent.SelectEvent
- beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)");
+ beliefBaseClass agent.UniqueBelsBB("gsize(_,_)","steps(_)","cell(_,_,key)","corral(_,_,_,_)","pratio(_)");
aslSourcePath: "src/asl";
}
Modified: trunk/applications/jason-team/src/asl/dummy.asl
===================================================================
--- trunk/applications/jason-team/src/asl/dummy.asl 2008-03-18 21:40:34 UTC (rev 1164)
+++ trunk/applications/jason-team/src/asl/dummy.asl 2008-03-18 22:36:40 UTC (rev 1165)
@@ -19,9 +19,6 @@
*/
-// the following plans (+pos....) react to the starting step
-// (since each new step causes a new +pos perception)
-
/* -- useful rules */
// find a free random location
@@ -29,35 +26,56 @@
pos(AgX,AgY,_) &
jia.random(RX,40) & X = (RX-20)+AgX & X > 0 &
jia.random(RY,40,5) & Y = (RY-20)+AgY &
- not jia.obstacle(X,Y) &
- jia.set_target(X,Y).
+ not jia.obstacle(X,Y).
+/* -- initial goal */
-/* -- go to the back pos -- */
+!move.
-// at the back_pos
-+pos(X,Y,_)
- : back_pos(X,Y) | // I am at back pos, find another
- (back_pos(BX,BY) & jia.direction(X, Y, BX, BY, skip)) // impossible to go to back_pos, find another
- <- !define_new_pos.
-+pos(X,Y,_)
- : back_pos(BX,BY) & jia.direction(X, Y, BX, BY, D) // one step towards back_pos
- <- do(D).
-
-/* -- random move -- */
-+pos(_,_,_)
- <- !define_new_pos.
+
+/* -- plans to move to a destination represented in the belief target(X,Y)
+ -- (it is a kind of persistent goal)
+*/
+
+// I still do not know my location
++!move
+ : not pos(_,_,_)
+ <- .print("waiting my location....");
+ .wait("+pos(_,_,_)");
+ !move.
+
+// find a new destination
++!move
+ : pos(X,Y,_) &
+ (not target(_,_) | // I have no target OR
+ target(X,Y) | // I am at target OR
+ (target(BX,BY) & jia.direction(X, Y, BX, BY, skip))) // is impossible to go to target
+ <- !define_new_target;
+ !move.
+
+// does one step towards target
++!move
+ : pos(X,Y,_) &
+ target(BX,BY) &
+ jia.direction(X, Y, BX, BY, D) // jia.direction finds one action D (using A*) towards the target
+ <- do(D); // this action will "block" the intention until it is sent to the simulator (in the end of the cycle)
+ !!move. // continue moving
+
+// in case of failure, move
+-!move
+ <- .current_intention(I); .println("failure in move:",I);
+ !move.
+
+
+/* -- add a belief target random move -- */
-+!define_new_pos
- <- ?pos(X,Y,_);
- ?random_pos(NX,NY);
- //.print("New point ",NX,",",NY);
- -+back_pos(NX,NY);
- jia.direction(X, Y, NX, NY, D);
- do(D).
++!define_new_target
+ <- ?random_pos(NX,NY);
+ jia.set_target(NX,NY);
+ -+target(NX,NY).
-+restart <- .drop_all_desires; !define_new_pos.
++restart <- .print("*** Restart! "); .drop_all_desires; !define_new_target; !move.
/* -- tests -- */
@@ -67,3 +85,4 @@
+cell(X,Y,Type) <- .println("cell = ",X,",",Y," = ",Type).
+pratio(R) <- .println("pratio = ",R).
++pos(X,Y,S) <- .println("pos = ",X,",",Y,"/",S).
\ No newline at end of file
Modified: trunk/applications/jason-team/src/java/arch/ACArchitecture.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-18 21:40:34 UTC (rev 1164)
+++ trunk/applications/jason-team/src/java/arch/ACArchitecture.java 2008-03-18 22:36:40 UTC (rev 1165)
@@ -3,7 +3,6 @@
import jason.JasonException;
import jason.asSemantics.ActionExec;
import jason.asSyntax.Literal;
-import jason.asSyntax.Structure;
import jason.mas2j.ClassParameters;
import jason.runtime.Settings;
@@ -11,6 +10,7 @@
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.logging.Level;
import java.util.logging.Logger;
/**
@@ -27,6 +27,7 @@
private ACProxy proxy;
private List<Literal> percepts = new ArrayList<Literal>();
+ private WaitSleep waitSleepThread;
@Override
public void initAg(String agClass, ClassParameters bbPars, String asSrc, Settings stts) throws JasonException {
@@ -44,6 +45,9 @@
username,
password);
new Thread(proxy,"AgentProxy"+username).start();
+
+ waitSleepThread = new WaitSleep();
+ waitSleepThread.start();
}
@@ -51,47 +55,45 @@
public void stopAg() {
super.stopAg();
proxy.finish();
+ waitSleepThread.interrupt();
}
@Override
public List<Literal> perceive() {
- return new ArrayList<Literal>(percepts);
+ return new ArrayList<Literal>(percepts); // it must be a copy!
}
- Queue<ActionExec> toExecute = new ConcurrentLinkedQueue<ActionExec>();
-
+ @Override
+ /** when the agent can sleep, i.e. has nothing else to decide, sent its last action to the simulator */
+ public void sleep() {
+ waitSleepThread.go();
+ super.sleep();
+ }
+
public void startNextStep(int step, List<Literal> p) {
percepts = p;
-
- // set all actions as successfully executed
- List<ActionExec> feedback = getTS().getC().getFeedbackActions();
- while (!toExecute.isEmpty()) {
- ActionExec action = toExecute.poll();
- action.setResult(true);
- feedback.add(action);
- }
-
+ waitSleepThread.newCycle();
getTS().getUserAgArch().getArchInfraTier().wake();
setCycle(step);
}
+ /** all actions block its intention and succeed in the end of the cycle,
+ * only the last action of the cycle will be sent to simulator */
@Override
- public void act(final ActionExec act, List<ActionExec> feedback) {
- final Structure acTerm = act.getActionTerm();
- if (acTerm.getFunctor().equals("do")){
- // (to not block the TS)
- // TODO: use a thread pool
- new Thread() {
- public void run() {
- proxy.sendAction(acTerm.getTerm(0).toString());
- toExecute.offer(act);
- }
- }.start();
+ public void act(ActionExec act, List<ActionExec> feedback) {
+ if (act.getActionTerm().getFunctor().equals("do")) {
+ waitSleepThread.addAction(act);
} else {
- logger.info("ignoring action "+acTerm+", it is not a 'do'.");
+ logger.info("ignoring action "+act+", it is not a 'do'.");
}
}
-
+
+ @Override
+ void simulationEndPerceived(String result) {
+ percepts = new ArrayList<Literal>();
+ super.simulationEndPerceived(result);
+ }
+
// TODO: create a new agent and plug it on the connection
/** this method is called when the agent crashes and other approaches to fix it (fix1 and fix2) does not worked */
@@ -120,5 +122,58 @@
return false;
}
*/
+
+ class WaitSleep extends Thread {
+
+ ActionExec lastAction;
+ Queue<ActionExec> toExecute = new ConcurrentLinkedQueue<ActionExec>();
+ WaitSleep() {
+ super("WaitSpeepToSendAction");
+ }
+
+ synchronized void addAction(ActionExec action) {
+ if (lastAction != null)
+ toExecute.offer(lastAction);
+ lastAction = action;
+ }
+
+ void newCycle() {
+ List<ActionExec> feedback = getTS().getC().getFeedbackActions();
+
+ // set all actions as successfully executed
+ while (!toExecute.isEmpty()) {
+ ActionExec action = toExecute.poll();
+ action.setResult(true);
+ feedback.add(action);
+ }
+ }
+
+ synchronized void go() {
+ notifyAll();
+ }
+ synchronized void waitSleep() throws InterruptedException {
+ wait();
+ }
+
+ @Override
+ synchronized public void run() {
+ while (true) {
+ try {
+ lastAction = null;
+ waitSleep();
+ if (lastAction != null) {
+ proxy.sendAction(lastAction.getActionTerm().getTerm(0).toString());
+ toExecute.offer(lastAction);
+ }
+ } catch (InterruptedException e) {
+ return; // condition to stop the thread
+ } catch (Exception e) {
+ logger.log(Level.SEVERE, "Error sending "+lastAction+" to simulator.",e);
+ toExecute.clear();
+ }
+ }
+ }
+ }
+
}
Modified: trunk/applications/jason-team/src/java/arch/ACProxy.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/ACProxy.java 2008-03-18 21:40:34 UTC (rev 1164)
+++ trunk/applications/jason-team/src/java/arch/ACProxy.java 2008-03-18 22:36:40 UTC (rev 1165)
@@ -5,7 +5,6 @@
import jason.asSyntax.Structure;
import jason.environment.grid.Location;
-import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
@@ -160,6 +159,7 @@
percepts.add(lpos);
int maxx = 0; // max value of some cell'x
+ int enemyId = 1;
// add in perception what is around
NodeList nl = perception.getElementsByTagName("cell");
for (int i=0; i < nl.getLength(); i++) {
@@ -172,7 +172,6 @@
if (cellx > maxx)
maxx = cellx;
- int enemyId = 1;
NodeList cnl = cell.getChildNodes();
for (int j=0; j < cnl.getLength(); j++) {
if (cnl.item(j).getNodeType() == Element.ELEMENT_NODE && cellx != 0 && celly != 0) {
@@ -186,8 +185,8 @@
} else if (type.getAttribute("type").equals("enemy")) {
Structure le = new Literal("enemy");
le.addTerm(new NumberTermImpl( (enemyId++) )); // we need an id to work with UniqueBB
- arq.enemyPerceived(absx, absy);
percepts.add(CowboyArch.createCellPerception(cellx, celly, le));
+ arq.enemyPerceived(absx, absy);
}
} else if (type.getNodeName().equals("cow")) {
@@ -212,8 +211,8 @@
//if (logger.isLoggable(Level.FINE))
logger.info("Request action for "+lpos+" / "+rid + " percepts: "+percepts);
+ arq.perceptionRatioPerceived(maxx);
arq.startNextStep(step, percepts);
- arq.perceptionRatioPerceived(maxx);
} catch (Exception e) {
logger.log(Level.SEVERE, "error processing request",e);
@@ -257,7 +256,10 @@
int d = new Random().nextInt(10000);
try {
while (running) {
- sleep(20000+d);
+ if (isConnected())
+ sleep(20000+d);
+ else
+ sleep(2000);
count++;
ok = false;
sentTime = System.currentTimeMillis();
Modified: trunk/applications/jason-team/src/java/arch/CowboyArch.java
===================================================================
--- trunk/applications/jason-team/src/java/arch/CowboyArch.java 2008-03-18 21:40:34 UTC (rev 1164)
+++ trunk/applications/jason-team/src/java/arch/CowboyArch.java 2008-03-18 22:36:40 UTC (rev 1165)
@@ -41,6 +41,8 @@
int cycle = 0;
+ WriteModelThread writeModelThread = null;
+
protected Logger logger = Logger.getLogger(CowboyArch.class.getName());
public static Atom aOBSTACLE = new Atom("obstacle");
@@ -54,7 +56,8 @@
super.initAg(agClass, bbPars, asSrc, stts);
gui = "yes".equals(stts.getUserParameter("gui"));
if ("yes".equals(stts.getUserParameter("write_model"))) {
- new WriteModelThread().start();
+ writeModelThread = new WriteModelThread();
+ writeModelThread.start();
}
// create the viewer for contest simulator
massimBackDir = stts.getUserParameter("ac_sim_back_dir");
@@ -66,6 +69,7 @@
public void stopAg() {
if (view != null) view.dispose();
if (acView != null) acView.finish();
+ if (writeModelThread != null) writeModelThread.interrupt();
super.stopAg();
}
@@ -192,8 +196,6 @@
getTS().getAg().getBB().abolish(new Atom("restart").getPredicateIndicator());
getTS().getAg().addBel(new Atom("restart"));
lo2 = new Location(-1,-1); // to not restart again in the next cycle
-
- //getTS().stopCycle();
} catch (Exception e) {
logger.info("Error in restart!"+ e);
}
@@ -218,11 +220,6 @@
model.add(WorldModel.COW, x, y);
}
- // not used, the allies send messages with their location
- //void allyPerceived(int x, int y) {
- // model.add(WorldModel.AGENT, x, y);
- //}
-
void enemyPerceived(int x, int y) {
model.add(WorldModel.ENEMY, x, y);
}
@@ -316,9 +313,10 @@
class WriteModelThread extends Thread {
public void run() {
String fileName = "world-state-"+getAgName()+".txt";
+ PrintWriter out = null;
try {
- PrintWriter out = new PrintWriter(fileName);
- while (isRunning()) {
+ out = new PrintWriter(fileName);
+ while (true) {
waitSomeTime();
if (model != null && playing) {
out.println("\n\n** Agent "+getAgName()+" in cycle "+cycle+"\n");
@@ -329,9 +327,11 @@
out.flush();
}
}
- out.close();
+ } catch (InterruptedException e) { // no problem, quit the thread
} catch (Exception e) {
e.printStackTrace();
+ } finally {
+ out.close();
}
}
Deleted: trunk/examples/gold-miners-II/JasonTeam.mas2j
===================================================================
--- trunk/examples/gold-miners-II/JasonTeam.mas2j 2008-03-18 21:40:34 UTC (rev 1164)
+++ trunk/examples/gold-miners-II/JasonTeam.mas2j 2008-03-18 22:36:40 UTC (rev 1165)
@@ -1,41 +0,0 @@
-/*
- * Jason Team for the
- * Multi-Agent Programming Contest 2007
- * (http://cig.in.tu-clausthal.de/AgentContest2007)
- *
- * Configuration for local simulator
- *
- * By Jomi & Rafael
- */
-
-MAS miners {
- infrastructure: Centralised
-
- environment: env.MiningEnvironment(11, 0, yes, "dummy", "miner", 1000)
- // parameters: 1. environment configuration id (from 1 to 13)
- // 11 is Fence in 2007 Contest
- // 12 is Semiramis in 2007 Contest
- // 13 is Overkill in 2007 Contest
- // 2. sleep time (in ms) after each action
- // 3. whether display the gui
- // 4. name of the agents of red team
- // 5. name of the agents of blue team
- // 6. window size
-
- agents:
- // red team
- dummy agentArchClass arch.LocalMinerArch #6;
-
- // blue team
- leader
- beliefBaseClass agent.DiscardBelsBB("my_status","picked","committed_to","cell");
-
- miner
- agentClass agent.SelectEvent
- beliefBaseClass agent.UniqueBelsBB("gsize(_,_,_)","depot(_,_,_)","steps(_,_)","committed_to(_,_,key)")
- agentArchClass arch.LocalMinerArch
- #6;
-
- aslSourcePath: "asl";
-}
-
Copied: trunk/examples/gold-miners-II/miners.mas2j (from rev 1161, trunk/examples/gold-miners-II/JasonTeam.mas2j)
===================================================================
--- trunk/examples/gold-miners-II/miners.mas2j (rev 0)
+++ trunk/examples/gold-miners-II/miners.mas2j 2008-03-18 22:36:40 UTC (rev 1165)
@@ -0,0 +1,41 @@
+/*
+ * Jason Team for the
+ * Multi-Agent Programming Contest 2007
+ * (http://cig.in.tu-clausthal.de/AgentContest2007)
+ *
+ * Configuration for local simulator
+ *
+ * By Jomi & Rafael
+ */
+
+MAS miners {
+ infrastructure: Centralised
+
+ environment: env.MiningEnvironment(11, 0, yes, "dummy", "miner", 1000)
+ // parameters: 1. environment configuration id (from 1 to 13)
+ // 11 is Fence in 2007 Contest
+ // 12 is Semiramis in 2007 Contest
+ // 13 is Overkill in 2007 Contest
+ // 2. sleep time (in ms) after each action
+ // 3. whether display the gui
+ // 4. name of the agents of red team
+ // 5. name of the agents of blue team
+ // 6. window size
+
+ agents:
+ // red team
+ dummy agentArchClass arch.LocalMinerArch #6;
+
+ // blue team
+ leader
+ beliefBaseClass agent.DiscardBelsBB("my_status","picked","committed_to","cell");
+
+ miner
+ agentClass agent.SelectEvent
+ beliefBaseClass agent.UniqueBelsBB("gsize(_,_,_)","depot(_,_,_)","steps(_,_)","committed_to(_,_,key)")
+ agentArchClass arch.LocalMinerArch
+ #6;
+
+ aslSourcePath: "asl";
+}
+
Modified: trunk/src/jason/asSyntax/Literal.java
===================================================================
--- trunk/src/jason/asSyntax/Literal.java 2008-03-18 21:40:34 UTC (rev 1164)
+++ trunk/src/jason/asSyntax/Literal.java 2008-03-18 22:36:40 UTC (rev 1165)
@@ -85,10 +85,7 @@
public static Literal parseLiteral(String sLiteral) {
as2j parser = new as2j(new StringReader(sLiteral));
try {
- Literal l = parser.literal();
- if (l instanceof Atom) // force the result as literal
- l = new Literal(l.getFunctor());
- return l;
+ return parser.literal();
} catch (Exception e) {
logger.log(Level.SEVERE,"Error parsing literal " + sLiteral,e);
return null;
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <gf...@us...> - 2008-03-18 21:40:36
|
Revision: 1164
http://jason.svn.sourceforge.net/jason/?rev=1164&view=rev
Author: gfronza
Date: 2008-03-18 14:40:34 -0700 (Tue, 18 Mar 2008)
Log Message:
-----------
Removed file/folder
Removed Paths:
-------------
trunk/applications/jason-eclipse-plugin/.classpath
Deleted: trunk/applications/jason-eclipse-plugin/.classpath
===================================================================
--- trunk/applications/jason-eclipse-plugin/.classpath 2008-03-18 20:29:50 UTC (rev 1163)
+++ trunk/applications/jason-eclipse-plugin/.classpath 2008-03-18 21:40:34 UTC (rev 1164)
@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry excluding="**/.svn/|.svn/" kind="src" path="src"/>
- <classpathentry exported="true" kind="lib" path="lib/dom4j-mini.jar"/>
- <classpathentry exported="true" kind="lib" path="lib/jason.jar"/>
- <classpathentry exported="true" kind="lib" path="lib/regexp-1.2-mini.jar"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <gf...@us...> - 2008-03-18 20:30:20
|
Revision: 1163
http://jason.svn.sourceforge.net/jason/?rev=1163&view=rev
Author: gfronza
Date: 2008-03-18 13:29:50 -0700 (Tue, 18 Mar 2008)
Log Message:
-----------
Fixed problem in the Mas2j editor. Now is possible to open external projects (outside workspace) with the plugin.
New feature was added, now is possible import to workspace external projects created in jEdit.
Modified Paths:
--------------
trunk/applications/jason-eclipse-plugin/.classpath
trunk/applications/jason-eclipse-plugin/META-INF/MANIFEST.MF
trunk/applications/jason-eclipse-plugin/plugin.xml
trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/core/MAS2JHandler.java
trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/core/PluginTemplates.java
trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/editors/ASLEditor.java
trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/editors/MAS2JEditor.java
trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewAgentWizard.java
trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewEnvironmentWizard.java
trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewEnvironmentWizardPage.java
trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewInternalActionWizardPage.java
trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewJasonProjectWizard.java
Added Paths:
-----------
trunk/applications/jason-eclipse-plugin/icons/list.gif
trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/core/ProjectCreation.java
trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/importWizards/
trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/importWizards/JasonProjectImportWizard.java
trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/importWizards/JasonProjectImportWizardPage.java
Modified: trunk/applications/jason-eclipse-plugin/.classpath
===================================================================
--- trunk/applications/jason-eclipse-plugin/.classpath 2008-03-18 20:12:54 UTC (rev 1162)
+++ trunk/applications/jason-eclipse-plugin/.classpath 2008-03-18 20:29:50 UTC (rev 1163)
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
- <classpathentry kind="src" path="src"/>
+ <classpathentry excluding="**/.svn/|.svn/" kind="src" path="src"/>
<classpathentry exported="true" kind="lib" path="lib/dom4j-mini.jar"/>
<classpathentry exported="true" kind="lib" path="lib/jason.jar"/>
<classpathentry exported="true" kind="lib" path="lib/regexp-1.2-mini.jar"/>
Modified: trunk/applications/jason-eclipse-plugin/META-INF/MANIFEST.MF
===================================================================
--- trunk/applications/jason-eclipse-plugin/META-INF/MANIFEST.MF 2008-03-18 20:12:54 UTC (rev 1162)
+++ trunk/applications/jason-eclipse-plugin/META-INF/MANIFEST.MF 2008-03-18 20:29:50 UTC (rev 1163)
@@ -2,7 +2,7 @@
Bundle-ManifestVersion: 2
Bundle-Name: JasonIDE Plug-in
Bundle-SymbolicName: net.sourceforge.jasonide;singleton:=true
-Bundle-Version: 1.0.0
+Bundle-Version: 1.0.1
Bundle-Activator: net.sourceforge.jasonide.Activator
Bundle-Localization: plugin
Require-Bundle: org.eclipse.ui,
@@ -15,7 +15,8 @@
org.eclipse.jdt.ui,
org.eclipse.jdt.core,
org.eclipse.debug.core,
- org.eclipse.jdt.launching
+ org.eclipse.jdt.launching,
+ org.eclipse.debug.ui
Eclipse-LazyStart: true
Bundle-Vendor: net.sourceforge.jason
Bundle-ClassPath: lib/dom4j-mini.jar,
Added: trunk/applications/jason-eclipse-plugin/icons/list.gif
===================================================================
(Binary files differ)
Property changes on: trunk/applications/jason-eclipse-plugin/icons/list.gif
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Modified: trunk/applications/jason-eclipse-plugin/plugin.xml
===================================================================
--- trunk/applications/jason-eclipse-plugin/plugin.xml 2008-03-18 20:12:54 UTC (rev 1162)
+++ trunk/applications/jason-eclipse-plugin/plugin.xml 2008-03-18 20:29:50 UTC (rev 1163)
@@ -131,5 +131,21 @@
menubarPath="additions"/>
</objectContribution>
</extension>
+ <extension
+ point="org.eclipse.ui.importWizards">
+ <category
+ id="net.sourceforge.jasonide.importWizards"
+ name="Jason"/>
+ <wizard
+ category="net.sourceforge.jasonide.importWizards"
+ class="net.sourceforge.jasonide.importWizards.JasonProjectImportWizard"
+ icon="icons/jason.jpg"
+ id="net.sourceforge.jasonide.importWizards.JasonProjectImportWizard"
+ name="Import Jason Project">
+ <description>
+ Import a file from the local file system into the workspace.
+ </description>
+ </wizard>
+ </extension>
</plugin>
Modified: trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/core/MAS2JHandler.java
===================================================================
--- trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/core/MAS2JHandler.java 2008-03-18 20:12:54 UTC (rev 1162)
+++ trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/core/MAS2JHandler.java 2008-03-18 20:29:50 UTC (rev 1163)
@@ -10,6 +10,7 @@
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
+import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
@@ -109,8 +110,38 @@
/**
* Gets the contents of the mas2j file.
*/
- public static String getMas2JFileName(IProject project) throws FileNotFoundException {
- String pathToMas2JFile = project.getLocation().toString() + File.separator + project.getName() + MAS2J_EXT;
+ public static String getMas2JFilePath(String projectDir) throws FileNotFoundException {
+ String pathToMas2JFile = null;
+ File d = new File(projectDir);
+ // list only dirs and *.mas2j
+ File[] files = d.listFiles(
+ new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ File f = new File(dir, name);
+ if (f.isDirectory()) {
+ return true;
+ }
+ else if (name.toLowerCase().endsWith("mas2j")){
+ return true;
+ }
+ return false;
+ }
+ }
+ );
+ for (int i = 0; i < files.length; i++) {
+ File f = files[i];
+ if (f.isDirectory()) {
+ pathToMas2JFile = getMas2JFilePath(f.getAbsolutePath());
+ if (pathToMas2JFile != null) {
+ break;
+ }
+ }
+ else {
+ return f.getAbsolutePath();
+ }
+ }
+
+
return pathToMas2JFile;
}
@@ -156,7 +187,7 @@
*/
public static String persistMas2JFile(IProject project, String contents) throws JasonPluginException {
try {
- String fileName = getMas2JFileName(project);
+ String fileName = getMas2JFilePath(project.getLocation().toString());
writeTextInFile(fileName, contents);
return fileName;
Modified: trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/core/PluginTemplates.java
===================================================================
--- trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/core/PluginTemplates.java 2008-03-18 20:12:54 UTC (rev 1162)
+++ trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/core/PluginTemplates.java 2008-03-18 20:29:50 UTC (rev 1163)
@@ -28,7 +28,7 @@
public static final String JASON_BUILDER_LAUNCHER = "JasonBuilder.launch";
- public static String getProjectPropertiesContents() {
+ public static String getProjectClasspathContents() {
return
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<classpath>\n" +
Added: trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/core/ProjectCreation.java
===================================================================
--- trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/core/ProjectCreation.java (rev 0)
+++ trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/core/ProjectCreation.java 2008-03-18 20:29:50 UTC (rev 1163)
@@ -0,0 +1,417 @@
+package net.sourceforge.jasonide.core;
+
+import jason.jeditplugin.Config;
+import jason.mas2j.AgentParameters;
+import jason.mas2j.ClassParameters;
+import jason.mas2j.MAS2JProject;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.Enumeration;
+import java.util.Formatter;
+import java.util.Hashtable;
+import java.util.Scanner;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import java.util.zip.ZipInputStream;
+
+import org.eclipse.core.resources.ICommand;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IProjectDescription;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.debug.core.DebugPlugin;
+import org.eclipse.debug.core.ILaunchConfiguration;
+import org.eclipse.debug.core.ILaunchConfigurationType;
+import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
+import org.eclipse.debug.core.ILaunchManager;
+import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.swt.widgets.Shell;
+
+public class ProjectCreation {
+
+ private Shell shell;
+
+ public ProjectCreation(Shell shell) {
+ this.shell = shell;
+ }
+
+ public Shell getShell() {
+ return this.shell;
+ }
+
+ /**
+ * Creates the empty directories for the new Jason project.
+ */
+ public void createProjectDirs(String projectRootDir) {
+ new File(projectRootDir + File.separator + "src").mkdir();
+ new File(projectRootDir + File.separator + "src" + File.separator + "java").mkdir();
+ new File(projectRootDir + File.separator + "src" + File.separator + "asl").mkdir();
+ new File(projectRootDir + File.separator + "bin").mkdir();
+ new File(projectRootDir + File.separator + "bin" + File.separator + "classes").mkdir();
+ }
+
+ /**
+ * Creates the .classpath file for Jason Project.
+ */
+ public void createClassPathFile(String projectRootDir) {
+ String classPathContent = PluginTemplates.getProjectClasspathContents();
+
+ String jasonJarInProject = Config.get().getJasonJar();
+ classPathContent = new Formatter().format(classPathContent, new Object[] {jasonJarInProject}).toString();
+
+ try {
+ FileWriter fw = new FileWriter(new File(projectRootDir + File.separator + ".classpath"));
+ fw.write(classPathContent);
+ fw.flush();
+ fw.close();
+ } catch (IOException e) {
+ MessageDialog.openError(getShell(), "Error", e.getMessage());
+ }
+ }
+
+ /**
+ * Configures de .project file.
+ * @param project
+ * @param monitor
+ */
+ public void configureProjectEnvironment(IProject project, IProgressMonitor monitor) {
+ try {
+ IProjectDescription pd = project.getDescription();
+
+ ICommand c1 = pd.newCommand();
+ c1.setBuilderName("org.eclipse.jdt.core.javabuilder");
+
+ ICommand c2 = pd.newCommand();
+ c2.setBuilderName("org.eclipse.pde.ManifestBuilder");
+
+ pd.setBuildSpec(new ICommand[] {c1, c2});
+ pd.setNatureIds(new String[] {"org.eclipse.jdt.core.javanature"});
+
+ project.setDescription(pd, monitor);
+ } catch (CoreException e) {
+ MessageDialog.openError(getShell(), "Error", e.getMessage());
+ }
+ }
+
+ /**
+ * Creates the build.properties of the new Jason Project.
+ */
+ public void createBuildPropertiesFile(String projectRootDir) {
+ try {
+ FileWriter fw = new FileWriter(new File(projectRootDir + File.separator + "build.properties"));
+ fw.write(PluginTemplates.getBuildPropertiesContents());
+ fw.flush();
+ fw.close();
+ } catch (IOException e) {
+ MessageDialog.openError(getShell(), "Error", e.getMessage());
+ }
+ }
+
+ /**
+ * Creates the .settings directory for Jason Project.
+ */
+ public void createSettingsDir(String projectRootDir) {
+ String corePrefsContent = PluginTemplates.getProjectCorePrefsContents();
+ String uiPrefsContent = PluginTemplates.getProjectUiPrefsContents();
+
+ try {
+ // make .settings folder
+ new File(projectRootDir + File.separator + ".settings").mkdir();
+
+ // core prefs
+ FileWriter fw = new FileWriter(new File(projectRootDir + File.separator + ".settings" + File.separator + PluginTemplates.CORE_PREFS));
+ fw.write(corePrefsContent);
+ fw.flush();
+ fw.close();
+
+ // ui prefs
+ fw = new FileWriter(new File(projectRootDir + File.separator + ".settings" + File.separator + PluginTemplates.UI_PREFS));
+ fw.write(uiPrefsContent);
+ fw.flush();
+ fw.close();
+ } catch (IOException e) {
+ MessageDialog.openError(getShell(), "Error", e.getMessage());
+ }
+ }
+
+ /**
+ * Creates the Java based Environment.
+ * @param projectRootDir
+ * @param envClassName
+ * @param projectName
+ */
+ public void createEnvironmentClass(String dirRoot, String envClassName, String projectName) {
+ try {
+ // replace "." because it's special symbol in regular expressions.
+ envClassName = envClassName.replace(".", "&");
+
+ String[] items = envClassName.split("&");
+ String className = null;
+ String actualPackage = dirRoot + File.separator + "src" + File.separator + "java";
+ String packages = "";
+
+ if (items.length > 0) {
+ className = items[items.length-1];
+
+ for (int i = 0; i < items.length-1; i++) {
+ File f = new File(actualPackage + File.separator + items[i]);
+ f.mkdir();
+ actualPackage = actualPackage + File.separator + items[i];
+
+ if (packages.length() != 0) {
+ packages = packages.concat(".");
+ }
+ packages = packages.concat(items[i]);
+ }
+ }
+ else {
+ className = "src" + File.separator + "java" + File.separator + envClassName;
+ }
+
+ // is Java code then must be placed in the source Java folder of the project.
+ actualPackage += File.separator;
+
+ File f = new File(actualPackage + File.separator + className + ".java");
+ f.createNewFile();
+
+ String jasonHome = JasonPluginConstants.JASON_HOME;
+ String envTempl = jasonHome +
+ File.separator +
+ PluginTemplates.TEMPLATE_DIR +
+ File.separator +
+ PluginTemplates.ENVIRONMENT;
+
+ StringBuffer buffer = new StringBuffer();
+ Scanner s = new Scanner(new File(envTempl));
+ while (s.hasNextLine()) {
+ buffer.append(s.nextLine().concat("\r\n"));
+ }
+
+ String templateContent = buffer.toString();
+
+ // contains package(s)
+ if (packages.length() != 0) {
+ templateContent = "package ".concat(packages).concat(";\r\n\r\n").concat(templateContent);
+ }
+
+ templateContent = templateContent.replace("<PROJECT_NAME>", projectName);
+ templateContent = templateContent.replace("<ENV_NAME>", className);
+
+ FileWriter fw = new FileWriter(f);
+ fw.write(templateContent);
+ fw.flush();
+ fw.close();
+ } catch (IOException e) {
+ MessageDialog.openError(getShell(), "Error", e.getMessage());
+ }
+ }
+
+ /**
+ * Creates a sample agent named sample.asl.
+ * @param projectRootDir
+ */
+ public void createSampleAgentFile(String projectRootDir, String projectName) {
+ try {
+ File f = new File(projectRootDir + File.separator + JasonPluginConstants.AGENT_DEFAULT_REPOS + File.separator + "sample.asl");
+ f.createNewFile();
+
+ String jasonHome = JasonPluginConstants.JASON_HOME;
+ String envTempl = jasonHome +
+ File.separator +
+ PluginTemplates.TEMPLATE_DIR +
+ File.separator +
+ PluginTemplates.AGENT;
+
+ StringBuffer buffer = new StringBuffer();
+ Scanner s = new Scanner(new File(envTempl));
+ while (s.hasNextLine()) {
+ buffer.append(s.nextLine().concat("\r\n"));
+ }
+
+ String templateContent = buffer.toString();
+
+ templateContent = templateContent.replace("<AG_NAME>", "sample");
+ templateContent = templateContent.replace("<PROJECT_NAME>", projectName);
+
+ FileWriter fw = new FileWriter(f);
+ fw.write(templateContent);
+ fw.flush();
+ fw.close();
+ } catch (IOException e) {
+ MessageDialog.openError(getShell(), "Error", e.getMessage());
+ }
+ }
+
+ /**
+ * Creates the Mas2J file. This file represents a Jason project.
+ * @param projectRootDir
+ * @param projectName
+ * @param infrastructure
+ */
+ public void createMas2JFile(String projectRootDir, String projectName, String infrastructure, String envClassName) {
+ MAS2JProject mas2jProject = new MAS2JProject();
+ mas2jProject.setSocName(projectName.toLowerCase());
+ mas2jProject.setInfrastructure(new ClassParameters(infrastructure));
+ mas2jProject.addSourcePath(JasonPluginConstants.AGENT_DEFAULT_REPOS_MAS2J);
+
+ AgentParameters ag = new AgentParameters();
+ ag.name = JasonPluginConstants.SAMPLE_AGENT_NAME;
+ //ag.setupDefault();
+ mas2jProject.addAgent(ag);
+ mas2jProject.setupDefault();
+
+ if (envClassName.length() > 0) {
+ mas2jProject.setEnvClass(new ClassParameters(envClassName));
+ }
+
+ try {
+ File f = new File(projectRootDir + File.separator + projectName + MAS2JHandler.MAS2J_EXT);
+ f.createNewFile();
+
+ FileWriter fw = new FileWriter(f);
+ fw.write(MAS2JHandler.mas2jProjectToString(mas2jProject));
+ fw.flush();
+ fw.close();
+ } catch (IOException e) {
+ MessageDialog.openError(getShell(), "Error", e.getMessage());
+ }
+ }
+
+ /**
+ * Creates the Launcher for the MAS Project.
+ * @param projectRootDir
+ * @param projectName
+ * @param newProject
+ * @param debug
+ */
+ public void createProjectLaunchConfiguration(String projectRootDir, String projectName, String mas2jFile, IProject newProject, boolean debug) {
+ try {
+ if (mas2jFile == null) {
+ mas2jFile = projectName + MAS2JHandler.MAS2J_EXT;
+ }
+
+ String mas2jFileName = "\"" + projectRootDir + File.separator + mas2jFile + "\"";
+ String launcherConfigName;
+ String secondParameter;
+ String supportsMode;
+ if (debug) {
+ launcherConfigName = "Debug MAS - " + projectName;
+ secondParameter = "debug";
+ supportsMode = ILaunchManager.DEBUG_MODE;
+ }
+ else {
+ launcherConfigName = "Run MAS - " + projectName;
+ secondParameter = "run";
+ supportsMode = ILaunchManager.RUN_MODE;
+ }
+
+ ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
+ ILaunchConfigurationType type = manager.getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION);
+ ILaunchConfiguration[] configurations = manager.getLaunchConfigurations(type);
+ for (int i = 0; i < configurations.length; i++) {
+ ILaunchConfiguration configuration = configurations[i];
+ if (configuration.getName().equals(launcherConfigName)) {
+ configuration.delete();
+ break;
+ }
+ }
+
+ ILaunchConfigurationWorkingCopy workingCopy = type.newInstance(null, launcherConfigName);
+ workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, projectName);
+ workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, "jason.mas2j.parser.mas2j");
+ workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, mas2jFileName + " " + secondParameter);
+ workingCopy.supportsMode(supportsMode);
+
+ /*ILaunchConfiguration config = */
+ workingCopy.doSave();
+ } catch (CoreException e) {
+ MessageDialog.openError(getShell(), "Error", e.getMessage());
+ }
+ }
+
+ /**
+ * @return Mas2J filename.
+ */
+ public String importResources(String archiveFileName, String projectRootDir) throws IOException, FileNotFoundException {
+ Hashtable htSizes = new Hashtable();
+
+ // extracts just sizes only.
+ ZipFile zf=new ZipFile(archiveFileName);
+ Enumeration e=zf.entries();
+ while (e.hasMoreElements()) {
+ ZipEntry ze=(ZipEntry)e.nextElement();
+ htSizes.put(ze.getName(),new Integer((int)ze.getSize()));
+ }
+ zf.close();
+
+ String mas2jFileName = null;
+
+ FileInputStream fis = new FileInputStream(archiveFileName);
+ BufferedInputStream bis=new BufferedInputStream(fis);
+ ZipInputStream zis=new ZipInputStream(bis);
+ ZipEntry ze=null;
+ while ((ze=zis.getNextEntry())!=null) {
+ if (ze.getName().endsWith(MAS2JHandler.MAS2J_EXT)) {
+ String[] mas2jFileNameParts = ze.getName().split("/");
+ mas2jFileName = mas2jFileNameParts[mas2jFileNameParts.length-1];
+ }
+
+ if ((!projectRootDir.endsWith("/")) || (!ze.getName().startsWith("/"))) {
+ projectRootDir = projectRootDir.concat("/");
+ }
+
+ File newFile = new File(projectRootDir.concat(ze.getName()));
+
+ if (ze.isDirectory()) {
+ //make dir
+ newFile.mkdir();
+ }
+ else { // is a file
+ int size=(int)ze.getSize();
+ // -1 means unknown size.
+ if (size==-1) {
+ size=((Integer)htSizes.get(ze.getName())).intValue();
+ }
+ byte[] b=new byte[(int)size];
+ int rb=0;
+ int chunk=0;
+ while (((int)size - rb) > 0) {
+ chunk = zis.read(b,rb,(int)size - rb);
+ if (chunk==-1) {
+ break;
+ }
+ rb+=chunk;
+ }
+
+ // write contents in a file
+ new FileOutputStream(newFile).write(b);
+ }
+ }
+
+ return mas2jFileName;
+ }
+
+ /**
+ * @return Mas2J filename.
+ */
+ public String getMas2jFileNameInArchiveFile(String archiveFileName) throws IOException, FileNotFoundException {
+ FileInputStream fis = new FileInputStream(archiveFileName);
+ BufferedInputStream bis=new BufferedInputStream(fis);
+ ZipInputStream zis=new ZipInputStream(bis);
+ ZipEntry ze=null;
+ while ((ze=zis.getNextEntry())!=null) {
+ if (ze.getName().endsWith(MAS2JHandler.MAS2J_EXT)) {
+ String[] mas2jFileNameParts = ze.getName().split("/");
+ return mas2jFileNameParts[mas2jFileNameParts.length-1];
+ }
+ }
+ return "";
+ }
+}
Modified: trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/editors/ASLEditor.java
===================================================================
--- trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/editors/ASLEditor.java 2008-03-18 20:12:54 UTC (rev 1162)
+++ trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/editors/ASLEditor.java 2008-03-18 20:29:50 UTC (rev 1163)
@@ -1,17 +1,12 @@
package net.sourceforge.jasonide.editors;
import jason.JasonException;
-import jason.mas2j.MAS2JProject;
-import jason.mas2j.parser.ParseException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
-import java.util.Iterator;
-import java.util.List;
import net.sourceforge.jasonide.Activator;
-import net.sourceforge.jasonide.core.MAS2JHandler;
import net.sourceforge.jasonide.core.PluginMarkerUtils;
import net.sourceforge.jasonide.editors.cbg.ColoringEditor;
@@ -52,38 +47,16 @@
// delete old markers
PluginMarkerUtils.deleteOldMarkers(ifile);
- String projectLocation = iproject.getLocation().toString();
- try {
- String mas2jFileName = MAS2JHandler.getMas2JFileName(iproject);
- MAS2JProject project = MAS2JHandler.parseForRun(mas2jFileName, projectLocation);
-
- List srcPaths = project.getSourcePaths();
-
- // check if agent source file exists in actual sourcepath
- for (Iterator iter = srcPaths.iterator(); iter.hasNext();) {
- String element = (String) iter.next();
- String asFileName = element + File.separator + ifile.getName();
-
- File file = new File(asFileName);
- if (file.exists()) {
- jason.asSyntax.parser.as2j parser = new jason.asSyntax.parser.as2j(new FileReader(file));
- if (parser != null) {
- parser.agent(null);
- }
- break;
- }
+ try {
+ // absolute project location + filePath relative in project (without project name)
+ String asfileName = iproject.getLocation().toString() + getFilePathWithoutProjectName(ifile);
+ jason.asSyntax.parser.as2j parser = new jason.asSyntax.parser.as2j(new FileReader(new File(asfileName)));
+ if (parser != null) {
+ parser.agent(null);
}
} catch (FileNotFoundException e) {
showError(e.getMessage(), e);
- } catch (ParseException e) {
- String msg = e.getMessage();
-
- int lineError = PluginMarkerUtils.getLineNumberFromMsg(msg);
- PluginMarkerUtils.createMarker(ifile, e.getMessage().replace("\r", "").replace("\n", ""),
- lineError,
- PluginMarkerUtils.getCharStart(document.get(), lineError, msg),
- PluginMarkerUtils.getCharEnd(document.get(), lineError, msg));
} catch (JasonException e) {
String msg = "Problems:" + "\n\n" + e.getMessage();
showError(msg, e);
@@ -108,6 +81,22 @@
}
}
+ /**
+ * Extract only the path of the file, excluding the project name.
+ * @param iFile
+ * @return String
+ */
+ private String getFilePathWithoutProjectName(IFile iFile) {
+ String[] parts = iFile.getFullPath().toString().split("/");
+ StringBuilder sb = new StringBuilder();
+ // first is empty and the second is the project name
+ for(int i = 2; i < parts.length; i++) {
+ sb.append("/");
+ sb.append(parts[i]);
+ }
+ return sb.toString();
+ }
+
private void showError(String msg, Throwable e) {
ErrorDialog.openError(
getSite().getShell(),
Modified: trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/editors/MAS2JEditor.java
===================================================================
--- trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/editors/MAS2JEditor.java 2008-03-18 20:12:54 UTC (rev 1162)
+++ trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/editors/MAS2JEditor.java 2008-03-18 20:29:50 UTC (rev 1163)
@@ -165,10 +165,10 @@
PluginMarkerUtils.deleteOldMarkers(ifile);
IProject project = ifile.getProject();
-
String mas2jFilePath = null;
try {
- mas2jFilePath = MAS2JHandler.getMas2JFileName(project);
+ // absolute project location + filePath relative in project (without project name)
+ mas2jFilePath = project.getLocation().toString() + getFilePathWithoutProjectName(ifile);
// compile Mas2J
MAS2JProject mas2Project = MAS2JHandler.parse(mas2jFilePath);
@@ -192,6 +192,22 @@
}
/**
+ * Extract only the path of the file, excluding the project name.
+ * @param iFile
+ * @return String
+ */
+ private String getFilePathWithoutProjectName(IFile iFile) {
+ String[] parts = iFile.getFullPath().toString().split("/");
+ StringBuilder sb = new StringBuilder();
+ // first is empty and the second is the project name
+ for(int i = 2; i < parts.length; i++) {
+ sb.append("/");
+ sb.append(parts[i]);
+ }
+ return sb.toString();
+ }
+
+ /**
* Extracts informations from Mas2JProject object.
* @param masProject
*/
Added: trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/importWizards/JasonProjectImportWizard.java
===================================================================
--- trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/importWizards/JasonProjectImportWizard.java (rev 0)
+++ trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/importWizards/JasonProjectImportWizard.java 2008-03-18 20:29:50 UTC (rev 1163)
@@ -0,0 +1,121 @@
+/*******************************************************************************
+ * Copyright (c) 2006 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.jasonide.importWizards;
+
+import java.lang.reflect.InvocationTargetException;
+
+import net.sourceforge.jasonide.core.ProjectCreation;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.operation.IRunnableWithProgress;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.ui.IImportWizard;
+import org.eclipse.ui.IWorkbench;
+
+public class JasonProjectImportWizard extends Wizard implements IImportWizard {
+
+ private JasonProjectImportWizardPage page;
+ private ProjectCreation projectCreation;
+
+ public JasonProjectImportWizard() {
+ super();
+ projectCreation = new ProjectCreation(getShell());
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.wizard.Wizard#performFinish()
+ */
+ public boolean performFinish() {
+ final String archiveFileName = page.getExternalProjectArchiveFilePath();
+ final String projectName = page.getProjectName();
+
+ IRunnableWithProgress op = new IRunnableWithProgress() {
+ public void run(IProgressMonitor monitor) throws InvocationTargetException {
+ try {
+ doFinish(archiveFileName, projectName, monitor);
+ } catch (Exception e) {
+ throw new InvocationTargetException(e);
+ } finally {
+ monitor.done();
+ }
+ }
+ };
+ try {
+ getContainer().run(true, false, op);
+ } catch (InterruptedException e) {
+ return false;
+ } catch (InvocationTargetException e) {
+ Throwable realException = e.getTargetException();
+ MessageDialog.openError(getShell(), "Error", realException.getMessage());
+ return false;
+ }
+ return true;
+ }
+
+ private void doFinish(String archiveFileName, String projectName, IProgressMonitor monitor) throws Exception {
+ monitor.beginTask("Creating the project " + projectName, 2);
+
+ // create a new Eclipse Jason Project
+ IProject newProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
+ newProject.create(monitor);
+ String projectRootDir = newProject.getLocation().toString();
+
+ // create the project directories for sources.
+ projectCreation.createProjectDirs(projectRootDir);
+
+ // create the settings directory and core/ui prefs.
+ projectCreation.createSettingsDir(projectRootDir);
+
+ // create .classpath file
+ projectCreation.createClassPathFile(projectRootDir);
+
+ // open project and refesh local.
+ newProject.open(monitor);
+
+ // create the build.properties of the project.
+ projectCreation.createBuildPropertiesFile(projectRootDir);
+
+ // configure the .project file.
+ projectCreation.configureProjectEnvironment(newProject, monitor);
+
+ // import the resources from archive file.
+ String mas2jFile = projectCreation.importResources(archiveFileName, projectRootDir);
+
+ // create the project launchers (Run e Debug).
+ projectCreation.createProjectLaunchConfiguration(projectRootDir, projectName, mas2jFile, newProject, false);
+ projectCreation.createProjectLaunchConfiguration(projectRootDir, projectName, mas2jFile, newProject, true);
+
+ // refresh the project after all these changes.
+ newProject.getWorkspace().getRoot().refreshLocal(IWorkspaceRoot.DEPTH_INFINITE, monitor);
+ monitor.beginTask("Project created in current workspace", 2);
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection)
+ */
+ public void init(IWorkbench workbench, IStructuredSelection selection) {
+ setWindowTitle("Jason Project Import Wizard");
+ setNeedsProgressMonitor(true);
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.wizard.IWizard#addPages()
+ */
+ public void addPages() {
+ page = new JasonProjectImportWizardPage("Import Jason Project");
+ addPage(page);
+ }
+}
Added: trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/importWizards/JasonProjectImportWizardPage.java
===================================================================
--- trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/importWizards/JasonProjectImportWizardPage.java (rev 0)
+++ trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/importWizards/JasonProjectImportWizardPage.java 2008-03-18 20:29:50 UTC (rev 1163)
@@ -0,0 +1,98 @@
+/*******************************************************************************
+ * Copyright (c) 2006 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.jasonide.importWizards;
+
+import net.sourceforge.jasonide.core.MAS2JHandler;
+import net.sourceforge.jasonide.core.ProjectCreation;
+
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+
+public class JasonProjectImportWizardPage extends WizardPage {
+
+ private Text externalProjectText;
+ private Text projectNameText;
+
+ public JasonProjectImportWizardPage(String pageName) {
+ super(pageName);
+ setTitle(pageName);
+ setDescription("Import a external Jason project into the workspace");
+ }
+
+ public void createControl(Composite parent) {
+ Composite container = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ container.setLayout(layout);
+ layout.numColumns = 3;
+ layout.verticalSpacing = 9;
+
+ Label label = new Label(container, SWT.NULL);
+ label.setText("&Archive file:");
+
+ externalProjectText = new Text(container, SWT.BORDER | SWT.SINGLE);
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ externalProjectText.setLayoutData(gd);
+
+ Button button = new Button(container, SWT.PUSH);
+ button.setText("Browse...");
+ button.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ handleBrowseExternalProject();
+ }
+ });
+
+ label = new Label(container, SWT.NULL);
+ label.setText("&Project name:");
+
+ projectNameText = new Text(container, SWT.BORDER | SWT.SINGLE);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ projectNameText.setLayoutData(gd);
+
+ setControl(container);
+ }
+
+ private void handleBrowseExternalProject() {
+ FileDialog dialog = new FileDialog(getShell(), SWT.OPEN);
+ dialog.setFilterExtensions(new String[] {"*.zip", "*.tar", "*.jar"});
+
+ String result = dialog.open();
+ if (result != null) {
+ externalProjectText.setText(result);
+
+ try {
+ String name = new ProjectCreation(getShell()).getMas2jFileNameInArchiveFile(result);
+ if (name.endsWith(MAS2JHandler.MAS2J_EXT)) {
+ name = name.replace(MAS2JHandler.MAS2J_EXT, "");
+ }
+ projectNameText.setText(name);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ public String getExternalProjectArchiveFilePath() {
+ return externalProjectText.getText();
+ }
+
+ public String getProjectName() {
+ return projectNameText.getText();
+ }
+}
Modified: trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewAgentWizard.java
===================================================================
--- trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewAgentWizard.java 2008-03-18 20:12:54 UTC (rev 1162)
+++ trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewAgentWizard.java 2008-03-18 20:29:50 UTC (rev 1163)
@@ -161,15 +161,20 @@
try {
// mas2j editor is open? yes: then modify contents of editor, no: then modify contents of file.
if (document == null) {
- // parse the mas2j file project.
- MAS2JProject project2 = MAS2JHandler.parse(MAS2JHandler.getMas2JFileName(file.getProject()));
- AgentParameters ag = new AgentParameters();
- ag.name = file.getName().replace(MAS2JHandler.AS_EXT, ""); // removes the file extension.
- project2.addAgent(ag);
-
- String mas2jContents = MAS2JHandler.mas2jProjectToString(project2);
- MAS2JHandler.persistMas2JFile(file.getProject(), mas2jContents);
+ // get the mas2j file path, if null then mas2j is not located in project directory.
+ String mas2jFilePath = MAS2JHandler.getMas2JFilePath(file.getProject().getLocation().toString());
+ if (mas2jFilePath != null) {
+ // parse the mas2j file project.
+ MAS2JProject project2 = MAS2JHandler.parse(mas2jFilePath);
+
+ AgentParameters ag = new AgentParameters();
+ ag.name = file.getName().replace(MAS2JHandler.AS_EXT, ""); // removes the file extension.
+ project2.addAgent(ag);
+
+ String mas2jContents = MAS2JHandler.mas2jProjectToString(project2);
+ MAS2JHandler.persistMas2JFile(file.getProject(), mas2jContents);
+ }
}
else {
String tempFileName = MAS2JHandler.persistTempMas2JFile(file.getProject(), document.get());
Modified: trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewEnvironmentWizard.java
===================================================================
--- trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewEnvironmentWizard.java 2008-03-18 20:12:54 UTC (rev 1162)
+++ trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewEnvironmentWizard.java 2008-03-18 20:29:50 UTC (rev 1163)
@@ -183,12 +183,17 @@
try {
// mas2j editor is open? yes: then modify contents of editor, no: then modify contents of file.
if (document == null) {
- // parse the mas2j file project.
- MAS2JProject project2 = MAS2JHandler.parse(MAS2JHandler.getMas2JFileName(file.getProject()));
- project2.setEnvClass(new ClassParameters(className));
- String mas2jContents = MAS2JHandler.mas2jProjectToString(project2);
- MAS2JHandler.persistMas2JFile(file.getProject(), mas2jContents);
+ // get the mas2j file path, if null then mas2j is not located in project directory.
+ String mas2jFilePath = MAS2JHandler.getMas2JFilePath(file.getProject().getLocation().toString());
+ if (mas2jFilePath != null) {
+ // parse the mas2j file project.
+ MAS2JProject project2 = MAS2JHandler.parse(mas2jFilePath);
+ project2.setEnvClass(new ClassParameters(className));
+
+ String mas2jContents = MAS2JHandler.mas2jProjectToString(project2);
+ MAS2JHandler.persistMas2JFile(file.getProject(), mas2jContents);
+ }
}
else {
String tempFileName = MAS2JHandler.persistTempMas2JFile(file.getProject(), document.get());
Modified: trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewEnvironmentWizardPage.java
===================================================================
--- trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewEnvironmentWizardPage.java 2008-03-18 20:12:54 UTC (rev 1162)
+++ trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewEnvironmentWizardPage.java 2008-03-18 20:29:50 UTC (rev 1163)
@@ -17,7 +17,6 @@
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.internal.core.PackageFragment;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.dialogs.IDialogPage;
import org.eclipse.jface.viewers.ISelection;
@@ -97,7 +96,7 @@
else if (firstElement instanceof IPackageFragment) {
IPackageFragment pfr = (IPackageFragment)firstElement;
- String[] names = ((PackageFragment)pfr).names; // TODO: fix that
+ String[] names = ((org.eclipse.jdt.internal.core.PackageFragment)pfr).names; // TODO: fix that
if (names.length > 0) {
packageName = names[0];
for (int i = 1; i < names.length; i++) {
@@ -132,7 +131,7 @@
else if (parent instanceof IPackageFragment) {
if (packageName == null) {
//System.out.println("eh pacote: " + parent.getPath().segments()[parent.getPath().segments().length-1]);
- String[] names = ((PackageFragment)parent).names; // TODO: fix that
+ String[] names = ((org.eclipse.jdt.internal.core.PackageFragment)parent).names; // TODO: fix that
if (names.length > 0) {
packageName = names[0];
for (int i = 1; i < names.length; i++) {
@@ -351,6 +350,7 @@
* the container field.
*/
private void handleBrowseSourceFolder() {
+
ContainerSelectionDialog dialog = new ContainerSelectionDialog(
getShell(), ResourcesPlugin.getWorkspace().getRoot(), false,
"Select new file container");
@@ -371,7 +371,7 @@
if (dialog.open() == SelectionDialog.OK) {
Object[] result = dialog.getResult();
if (result.length == 1) {
- String[] names = ((PackageFragment)result[0]).names; // TODO: fix that
+ String[] names = ((org.eclipse.jdt.internal.core.PackageFragment)result[0]).names; // TODO: fix that
if (names.length > 0) {
packageName = names[0];
for (int i = 1; i < names.length; i++) {
Modified: trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewInternalActionWizardPage.java
===================================================================
--- trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewInternalActionWizardPage.java 2008-03-18 20:12:54 UTC (rev 1162)
+++ trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewInternalActionWizardPage.java 2008-03-18 20:29:50 UTC (rev 1163)
@@ -20,7 +20,6 @@
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.internal.core.PackageFragment;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.dialogs.IDialogPage;
import org.eclipse.jface.viewers.ISelection;
@@ -101,7 +100,7 @@
else if (firstElement instanceof IPackageFragment) {
IPackageFragment pfr = (IPackageFragment)firstElement;
- String[] names = ((PackageFragment)pfr).names; // TODO: fix that
+ String[] names = ((org.eclipse.jdt.internal.core.PackageFragment)pfr).names; // TODO: fix that
if (names.length > 0) {
packageName = names[0];
for (int i = 1; i < names.length; i++) {
@@ -136,7 +135,7 @@
else if (parent instanceof IPackageFragment) {
if (packageName == null) {
//System.out.println("eh pacote: " + parent.getPath().segments()[parent.getPath().segments().length-1]);
- String[] names = ((PackageFragment)parent).names; // TODO: fix that
+ String[] names = ((org.eclipse.jdt.internal.core.PackageFragment)parent).names; // TODO: fix that
if (names.length > 0) {
packageName = names[0];
for (int i = 1; i < names.length; i++) {
@@ -364,7 +363,7 @@
if (dialog.open() == SelectionDialog.OK) {
Object[] result = dialog.getResult();
if (result.length == 1) {
- String[] names = ((PackageFragment)result[0]).names; // TODO: fix that
+ String[] names = ((org.eclipse.jdt.internal.core.PackageFragment)result[0]).names; // TODO: fix that
if (names.length > 0) {
packageName = names[0];
for (int i = 1; i < names.length; i++) {
Modified: trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewJasonProjectWizard.java
===================================================================
--- trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewJasonProjectWizard.java 2008-03-18 20:12:54 UTC (rev 1162)
+++ trunk/applications/jason-eclipse-plugin/src/net/sourceforge/jasonide/wizards/NewJasonProjectWizard.java 2008-03-18 20:29:50 UTC (rev 1163)
@@ -1,33 +1,13 @@
package net.sourceforge.jasonide.wizards;
-import jason.jeditplugin.Config;
-import jason.mas2j.AgentParameters;
-import jason.mas2j.ClassParameters;
-import jason.mas2j.MAS2JProject;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
-import java.util.Formatter;
-import java.util.Scanner;
-import net.sourceforge.jasonide.core.JasonPluginConstants;
-import net.sourceforge.jasonide.core.PluginTemplates;
-import net.sourceforge.jasonide.core.MAS2JHandler;
+import net.sourceforge.jasonide.core.ProjectCreation;
-import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.debug.core.DebugPlugin;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.debug.core.ILaunchConfigurationType;
-import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
-import org.eclipse.debug.core.ILaunchManager;
-import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
@@ -50,6 +30,7 @@
private NewJasonProjectWizardPage page;
private ISelection selection;
+ private ProjectCreation projectCreation;
/**
* Constructor for NewJasonProjectWizard.
@@ -57,7 +38,8 @@
public NewJasonProjectWizard() {
super();
setNeedsProgressMonitor(true);
- setWindowTitle("Jason Project");
+ setWindowTitle("Jason Project");
+ projectCreation = new ProjectCreation(getShell());
}
/**
@@ -107,7 +89,6 @@
* file if missing or just replace its contents, and open
* the editor on the newly created file.
*/
-
private void doFinish(IProject newProject, String envClassName, String infraStructure, IProgressMonitor monitor) throws CoreException {
monitor.beginTask("Creating the project " + newProject.getName(), 2);
@@ -118,35 +99,35 @@
String projectName = newProject.getName();
// create the project directories for sources.
- createProjectDirs(projectRootDir);
+ projectCreation.createProjectDirs(projectRootDir);
// create the settings directory and core/ui prefs.
- createSettingsDir(projectRootDir);
+ projectCreation.createSettingsDir(projectRootDir);
// create .classpath file
- createClassPathFile(projectRootDir);
+ projectCreation.createClassPathFile(projectRootDir);
// contains environment?
if (envClassName.length() > 0) {
- createEnvironmentClass(projectRootDir, envClassName, projectName);
+ projectCreation.createEnvironmentClass(projectRootDir, envClassName, projectName);
}
// create initial files.
- createSampleAgentFile(projectRootDir, projectName);
- createMas2JFile(projectRootDir, projectName, infraStructure, envClassName);
+ projectCreation.createSampleAgentFile(projectRootDir, projectName);
+ projectCreation.createMas2JFile(projectRootDir, projectName, infraStructure, envClassName);
// open project and refesh local.
newProject.open(monitor);
// create the build.properties of the project.
- createBuildPropertiesFile(projectRootDir);
+ projectCreation.createBuildPropertiesFile(projectRootDir);
// configure the .project file.
- configureProjectEnvironment(newProject, monitor);
+ projectCreation.configureProjectEnvironment(newProject, monitor);
// create the project launchers (Run e Debug).
- createProjectLaunchConfiguration(projectRootDir, projectName, newProject, false);
- createProjectLaunchConfiguration(projectRootDir, projectName, newProject, true);
+ projectCreation.createProjectLaunchConfiguration(projectRootDir, projectName, null, newProject, false);
+ projectCreation.createProjectLaunchConfiguration(projectRootDir, projectName, null, newProject, true);
// refresh the project after all these changes.
newProject.getWorkspace().getRoot().refreshLocal(IWorkspaceRoot.DEPTH_INFINITE, monitor);
@@ -155,294 +136,8 @@
MessageDialog.openError(getShell(), "Error", e.getMessage());
}
}
-
- /**
- * Creates the empty directories for the new Jason project.
- */
- private void createProjectDirs(String projectRootDir) {
- new File(projectRootDir + File.separator + "src").mkdir();
- new File(projectRootDir + File.separator + "src" + File.separator + "java").mkdir();
- new File(projectRootDir + File.separator + "src" + File.separator + "asl").mkdir();
- new File(projectRootDir + File.separator + "bin").mkdir();
- new File(projectRootDir + File.separator + "bin" + File.separator + "classes").mkdir();
- }
/**
- * Creates the .classpath file for Jason Project.
- */
- private void createClassPathFile(String projectRootDir) {
- String classPathContent = PluginTemplates.getProjectPropertiesContents();
-
- String jasonJarInProject = Config.get().getJasonJar();
- classPathContent = new Formatter().format(classPathContent, new Object[] {jasonJarInProject}).toString();
-
- try {
- FileWriter fw = new FileWriter(new File(projectRootDir + File.separator + ".classpath"));
- fw.write(classPathContent);
- fw.flush();
- fw.close();
- } catch (IOException e) {
- MessageDialog.openError(getShell(), "Error", e.getMessage());
- }
- }
-
- /**
- * Configures de .project file.
- * @param project
- * @param monitor
- */
- private void configureProjectEnvironment(IProject project, IProgressMonitor monitor) {
- try {
- IProjectDescription pd = project.getDescription();
-
- ICommand c1 = pd.newCommand();
- c1.setBuilderName("org.eclipse.jdt.core.javabuilder");
-
- ICommand c2 = pd.newCommand();
- c2.setBuilderName("org.eclipse.pde.ManifestBuilder");
-
- pd.setBuildSpec(new ICommand[] {c1, c2});
- pd.setNatureIds(new String[] {"org.eclipse.jdt.core.javanature"});
-
- project.setDescription(pd, monitor);
- } catch (CoreException e) {
- MessageDialog.openError(getShell(), "Error", e.getMessage());
- }
- }
-
- /**
- * Creates the build.properties of the new Jason Project.
- */
- private void createBuildPropertiesFile(String projectRootDir) {
- try {
- FileWriter fw = new FileWriter(new File(projectRootDir + File.separator + "build.properties"));
- fw.write(PluginTemplates.getBuildPropertiesContents());
- fw.flush();
- fw.close();
- } catch (IOException e) {
- MessageDialog.openError(getShell(), "Error", e.getMessage());
- }
- }
-
- /**
- * Creates the .settings directory for Jason Project.
- */
- private void createSettingsDir(String projectRootDir) {
- String corePrefsContent = PluginTemplates.getProjectCorePrefsContents();
- String uiPrefsContent = PluginTemplates.getProjectUiPrefsContents();
-
- try {
- // make .settings folder
- new File(projectRootDir + File.separator + ".settings").mkdir();
-
- // core prefs
- FileWriter fw = new FileWriter(new File(projectRootDir + File.separator + ".settings" + File.separator + PluginTemplates.CORE_PREFS));
- fw.write(corePrefsContent);
- fw.flush();
- fw.close();
-
- // ui prefs
- fw = new FileWriter(new File(projectRootDir + File.separator + ".settings" + File.separator + PluginTemplates.UI_PREFS));
- fw.write(uiPrefsContent);
- fw.flush();
- fw.close();
- } catch (IOException e) {
- MessageDialog.openError(getShell(), "Error", e.getMessage());
- }
- }
-
- /**
- * Creates the Java based Environment.
- * @param projectRootDir
- * @param envClassName
- * @param projectName
- */
- private void createEnvironmentClass(String dirRoot, String envClassName, String projectName) {
- try {
- // replace "." because it's special symbol in regular expressions.
- envClassName = envClassName.replace(".", "&");
-
- String[] items = envClassName.split("&");
- String className = null;
- String actualPackage = dirRoot + File.separator + "src" + File.separator + "java";
- String packages = "";
-
- if (items.length > 0) {
- className = items[items.length-1];
-
- for (int i = 0; i < items.length-1; i++) {
- File f = new File(actualPackage + File.separator + items[i]);
- f.mkdir();
- actualPackage = actualPackage + File.separator + items[i];
-
- if (packages.length() != 0) {
- packages = packages.concat(".");
- }
- packages = packages.concat(items[i]);
- }
- }
- else {
- className = "src" + File.separator + "java" + File.separator + envClassName;
- }
-
- // is Java code then must be placed in the source Java folder of the project.
- actualPackage += File.separator;
-
- File f = new File(actualPackage + File.separator + className + ".java");
- f.createNewFile();
-
- String jasonHome = JasonPluginConstants.JASON_HOME;
- String envTempl = jasonHome +
- File.separator +
- PluginTemplates.TEMPLATE_DIR +
- File.separator +
- PluginTemplates.ENVIRONMENT;
-
- StringBuffer buffer = new StringBuffer();
- Scanner s = new Scanner(new File(envTempl));
- while (s.hasNextLine()) {
- buffer.append(s.nextLine().concat("\r\n"));
- }
-
- String templateContent = buffer.toString();
-
- // contains package(s)
- if (packages.length() != 0) {
- templateContent = "package ".concat(packages).concat(";\r\n\r\n").concat(templateContent);
- }
-
- templateContent = templateContent.replace("<PROJECT_NAME>", projectName);
- templateContent = templateContent.replace("<ENV_NAME>", className);
-
- FileWriter fw = new FileWriter(f);
- fw.write(templateContent);
- fw.flush();
- fw.close();
- } catch (IOException e) {
- MessageDialog.openError(getShell(), "Error", e.getMessage());
- }
- }
-
- /**
- * Creates a sample agent named sample.asl.
- * @param projectRootDir
- */
- private void createSampleAgentFile(String projectRootDir, String projectName) {
- try {
- File f = new File(projectRootDir + File.separator + JasonPluginConstants.AGENT_DEFAULT_REPOS + File.separator + "sample.asl");
- f.createNewFile();
-
- String jasonHome = JasonPluginConstants.JASON_HOME;
- String envTempl = jasonHome +
- File.separator +
- PluginTemplates.TEMPLATE_DIR +
- File.separator +
- PluginTemplates.AGENT;
-
- StringBuffer buffer = new StringBuffer();
- Scanner s = new Scanner(new File(envTempl));
- while (s.hasNextLine()) {
- buffer.append(s.nextLine().concat("\r\n"));
- }
-
- String templateContent = buffer.toString();
-
- templateContent = templateContent.replace("<AG_NAME>", "sample");
- templateContent = templateContent.replace("<PROJECT_NAME>", projectName);
-
- FileWriter fw = new FileWriter(f);
- fw.write(templateContent);
- fw.flush();
- fw.close();
- } catch (IOException e) {
- MessageDialog.openError(getShell(), "Error", e.getMessage());
- }
- }
-
- /**
- * Creates the Mas2J file. This file represents a Jason project.
- * @param projectRootDir
- * @param projectName
- * @param infrastructure
- */
- private void createMas2JFile(String projectRootDir, String projectName, String infrastructure, String envClassName) {
- MAS2JProject mas2jProject = new MAS2JProject();
- mas2jProject.setSocName(projectName.toLowerCase());
- mas2jProject.setInfrastructure(new ClassParameters(infrastructure));
- mas2jProject.addSourcePath(JasonPluginConstants.AGENT_DEFAULT_REPOS_MAS2J);
-
- AgentParameters ag = new AgentParameters();
- ag.name = JasonPluginConstants.SAMPLE_AGENT_NAME;
- //ag.setupDefault();
- mas2jProject.addAgent(ag);
- mas2jProject.setupDefault();
-
- if (envClassName.length() > 0) {
- mas2jProject.setEnvClass(new ClassParameters(envClassName));
- }
-
- try {
- File f = new File(projectRootDir + File.separator + projectName + MAS2JHandler.MAS2J_EXT);
- f.createNewFile();
-
- FileWriter fw = new FileWriter(f);
- fw.write(MAS2JHandler.mas2jProjectToString(mas2jProject));
- fw.flush();
- fw.close();
- } catch (IOException e) {
- MessageDialog.openError(getShell(), "Error", e.getMessage());
- }
- }
-
- /**
- * Creates the Launcher for the MAS Project.
- * @param projectRootDir
- * @param projectName
- * @param newProject
- * @param debug
- */
- private void createProjectLaunchConfiguration(String projectRootDir, String projectName, IProject newProject, boolean debug) {
- try {
- String mas2jFileName = projectRootDir + File.separator + projectName + MAS2JHandler.MAS2J_EXT;
- String launcherConfigName;
- String secondParameter;
- String supportsMode;
- if (debug) {
- launcherConfigName = "Debug MAS - " + projectName;
- secondParameter = "debug";
- supportsMode = ILaunchManager.DEBUG_MODE;
- }
- else {
- launcherConfigName = "Run MAS - " + projectName;
- secondParameter = "run";
- supportsMode = ILaunchManager.RUN_MODE;
- }
-
- ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
- ILaunchConfigurationType type = manager.getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION);
- ILaunchConfiguration[] configurations = manager.getLaunchConfigurations(type);
- for (int i = 0; i < configurations.length; i++) {
- ILaunchConfiguration configuration = configurations[i];
- if (configuration.getName().equals(launcherConfigName)) {
- configuration.delete();
- break;
- }
- }
-
- ILaunchConfigurationWorkingCopy workingCopy = type.newInstance(null, launcherConfigName);
- workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, projectName);
- workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, "jason.mas2j.parser.mas2j");
- workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, mas2jFileName + " " + secondParameter);
- workingCopy.supportsMode(supportsMode);
-
- /*ILaunchConfiguration config = */
- workingCopy.doSave();
- } catch (CoreException e) {
- MessageDialog.openError(getShell(), "Error", e.getMessage());
- }
- }
-
- /**
* We will accept the selection in the workbench to see if
* we can initialize from it.
* @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <tom...@us...> - 2008-03-18 20:13:12
|
Revision: 1162
http://jason.svn.sourceforge.net/jason/?rev=1162&view=rev
Author: tomklapiscak
Date: 2008-03-18 13:12:54 -0700 (Tue, 18 Mar 2008)
Log Message:
-----------
travel_agent's c-build.xml fixed, travel_agent now performs all necessary ant tasks in the right order and ensures latest jason.jar is used. travel_agent should now run out of the box.
README updated.
Modified Paths:
--------------
trunk/applications/jasdl-owlapi/README
trunk/applications/jasdl-owlapi/examples/travel_agent/bin/c-build.xml
Modified: trunk/applications/jasdl-owlapi/README
===================================================================
--- trunk/applications/jasdl-owlapi/README 2008-03-18 03:01:18 UTC (rev 1161)
+++ trunk/applications/jasdl-owlapi/README 2008-03-18 20:12:54 UTC (rev 1162)
@@ -1,5 +1,23 @@
-JASDL: "Jason AgentSpeak-DescriptionLogic"
+JASDL: "Jason AgentSpeak-Description Logic"
Copyright (C) 2008 Thomas Klapiscak (t.g...@du...)
JASDL is distributed under the LGPL license (see COPYING and COPYING.LESSER)
-Thank you for your interest in JASDL!
+
+*** Running JASDL ***
+
+Firstly, please check you are using the latest revision of the entire Jason trunk from the SVN before use.
+
+To run a JASDL agent, its class-path must include all jars under the sub-directories:
+ * trunk/applications/jasdl-owlapi/lib
+ * trunk/applications/jmca/lib
+ * All standard Jason libraries, please ensure that these are built from the latest revision of the Jason trunk.
+
+The (unmodified) travel_agent example (trunk/applications/jasdl-owlapi/examples/travel_agent/config.mas2j)
+must be run in-situ within the Jason trunk. All necessary ant tasks will be performed by its custom build script.
+
+*** Configuring JASDL ***
+
+Please refer to /trunk/jason/applications/jasdl-owlapi/examples/travel_agent/config.mas2j for an example of how to configure JASDL agents.
+
+
+Thank you for your interest in JASDL!
\ No newline at end of file
Modified: trunk/applications/jasdl-owlapi/examples/travel_agent/bin/c-build.xml
===================================================================
--- trunk/applications/jasdl-owlapi/examples/travel_agent/bin/c-build.xml 2008-03-18 03:01:18 UTC (rev 1161)
+++ trunk/applications/jasdl-owlapi/examples/travel_agent/bin/c-build.xml 2008-03-18 20:12:54 UTC (rev 1162)
@@ -1,12 +1,16 @@
<?xml version="1.0" encoding="ISO-8859-1" ?>
<project name ="custombuild" basedir="..">
+ <property name="jasonJar" value="../../../../lib/jason.jar"/>
+
<import file="build.xml"/>
- <target name="user-init">
+
+ <target name="user-init">
+ <ant dir="../../../../" inheritAll="false" target="plugin"/>
+ <ant dir="../../../jmca" inheritAll="false"/>
<ant dir="../.." inheritAll="false"/>
- <ant dir="../../../jmca" inheritAll="false"/>
</target>
+
<target name="user-end">
- <echo message="JASDL end"/>
</target>
</project>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <tom...@us...> - 2008-03-18 03:01:29
|
Revision: 1161
http://jason.svn.sourceforge.net/jason/?rev=1161&view=rev
Author: tomklapiscak
Date: 2008-03-17 20:01:18 -0700 (Mon, 17 Mar 2008)
Log Message:
-----------
travel_agent example improved and tidied up.
JASDL no longer relies on jasdl_agent_name setting - agent name is (more appropriately) taken from agent architecture.
Modified Paths:
--------------
trunk/applications/jasdl-owlapi/examples/travel_agent/config.mas2j
trunk/applications/jasdl-owlapi/examples/travel_agent/customer.asl
trunk/applications/jasdl-owlapi/examples/travel_agent/travel_agent.asl
trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java
trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlConfigurator.java
Modified: trunk/applications/jasdl-owlapi/examples/travel_agent/config.mas2j
===================================================================
--- trunk/applications/jasdl-owlapi/examples/travel_agent/config.mas2j 2008-03-18 02:05:59 UTC (rev 1160)
+++ trunk/applications/jasdl-owlapi/examples/travel_agent/config.mas2j 2008-03-18 03:01:18 UTC (rev 1161)
@@ -21,9 +21,7 @@
/* Jason Project */
-/* Note: Uses c-build.xml for two reasons:
- * 1) to prevent need for large classpath specification in this file
- * 2) to automatically run ant jar task for jasdl and jmca so up-to-date versions are used
+/* Note: Uses c-build.xml to automatically run ant jar task for jasdl and jmca so up-to-date versions are used
*/
MAS dalt08 {
@@ -32,23 +30,13 @@
agents:
travel_agent
travel_agent.asl
- [
- jasdl_agent_name = "travelagent",
- // implication, "default" is a reserved ontology name
- // also, "self"
+ [
jasdl_default_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy", // applied to incoming ontologies and those given no automapping
- //TODO: what about when automapping causes a conflict?! anonymous aliasing?
-
+
jasdl_ontologies="travel",
jasdl_travel_uri="http://www.dur.ac.uk/t.g.klapiscak/onts/travel.owl",
- //jasdl_travel_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy",
- jasdl_travel_mapping_manual="small_beach=beach",
-
- jasdl_places_uri="http://www.dur.ac.uk/t.g.klapiscak/onts/places.owl",
- jasdl_places_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy"
-
- //,jasdl_aktors_uri="http://www.aktors.org/ontology/portal.owl",
- //jasdl_aktors_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy"
+ /*jasdl_travel_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy",*/ // defaults can be overriden per-ontology here
+ jasdl_travel_mapping_manual="small_beach=beach" // these manual mappings will override any automatic mappings made by strategies
]
agentArchClass jasdl.architecture.JasdlAgArch
agentClass jasdl.asSemantics.JasdlAgent
@@ -57,30 +45,23 @@
customer
customer.asl
- [
- jasdl_agent_name = "customer",
+ [
+ /* jasdl_default_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy", */ // defaults to this
jasdl_ontologies="holidays,places",
- //jasdl_holidays_uri="file:///home/tom/Desktop/Project/workspace/jason/applications/jasdl-owlapi/examples/travel_agent/ontologies/travel.owl",
+ /*jasdl_holidays_uri="file:///home/tom/Desktop/Project/workspace/jason/applications/jasdl-owlapi/examples/travel_agent/ontologies/travel.owl", */
jasdl_holidays_uri="http://www.dur.ac.uk/t.g.klapiscak/onts/travel.owl",
jasdl_holidays_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy",
- jasdl_holidays_mapping_manual="small_beach=beach, luxuriousHotel=LuxuryHotel", // arbitrary primitive mappings handled correctly
+ jasdl_holidays_mapping_manual="small_beach=beach, luxuriousHotel=LuxuryHotel", // for demonstration of arbitrary primitive mappings being handled correctly
jasdl_places_uri="http://www.dur.ac.uk/t.g.klapiscak/onts/places.owl",
jasdl_places_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy"
-
- /* Example per-agent proxy settings used for ontology instantiation */
- //jasdl_http_proxy="127.0.0.1:3128"
- //jasdl_https_proxy="127.0.0.1:8080"
- //jasdl_ftp_proxy="127.0.0.1:8080"
- //jasdl_socks_proxy="127.0.0.1:1080"
]
agentArchClass jasdl.architecture.JasdlAgArch
agentClass jasdl.asSemantics.JasdlAgent
beliefBaseClass jasdl.bb.JasdlBeliefBase
#1;
-
classpath: "../../lib/**/*.jar";"../../../jmca/lib/jmca.jar";
}
Modified: trunk/applications/jasdl-owlapi/examples/travel_agent/customer.asl
===================================================================
--- trunk/applications/jasdl-owlapi/examples/travel_agent/customer.asl 2008-03-18 02:05:59 UTC (rev 1160)
+++ trunk/applications/jasdl-owlapi/examples/travel_agent/customer.asl 2008-03-18 03:01:18 UTC (rev 1161)
@@ -18,41 +18,44 @@
*
*/
-//+luxuriousHotel(L)[o(holidays), source(Source)]
+luxuriousHotel(L)[o(holidays), source(Source)]
- <-
+ <-
+ .print("The ", L, " luxurious hotel is available");
- ?hotel(L)[o(holidays)];
- .print("The ", L, " luxurious hotel is available");
- jasdl.ia.define_class(query, "holidays:city and holidays:hasAccommodation value self:", L);
- .send(Source, askOne, query(City)[o(self)], query(City)[o(self)]);
+ // construct a class containing all cities in which L is located
+ jasdl.ia.define_class(cityOfL, "holidays:city and holidays:hasAccommodation value self:", L);
+ .send(Source, askOne, cityOfL(City)[o(self)], cityOfL(City)[o(self)]); // use to "query" to sender of this luxuriousHotel (travel_agent)
.print(L, " is located in the city ", City);
// check given hotel is located in a destination that has some museums
jasdl.ia.define_class(hotelNearMuseums, "holidays:isLocatedAt some (holidays:hasActivity some holidays:museums)");
- .send(Source, askOne, hotelNearMuseums(HotelNearMuseums)[o(self)], hotelNearMuseums(HotelNearMuseums)[o(self)]);
+ .send(Source, askOne, hotelNearMuseums(HotelNearMuseums)[o(self)], hotelNearMuseums(HotelNearMuseums)[o(self)]); // use to "query" to sender of this luxuriousHotel (travel_agent)
.print(HotelNearMuseums, " is a hotel located in a city with some museums");
+ // Shows a class definition in part composed of other run-time class definitions
jasdl.ia.define_class(luxuriousHotelNearMuseums, "self:hotelNearMuseums AND holidays:luxuriousHotel");
- .send(Source, askOne, luxuriousHotelNearMuseums(LuxuriousHotelNearMuseums)[o(self)], luxuriousHotelNearMuseums(LuxuriousHotelNearMuseums)[o(self)]);
+ .send(Source, askOne, luxuriousHotelNearMuseums(LuxuriousHotelNearMuseums)[o(self)], luxuriousHotelNearMuseums(LuxuriousHotelNearMuseums)[o(self)]); // use to "query" to sender of this luxuriousHotel (travel_agent)
.print(LuxuriousHotelNearMuseums, " is a luxurious hotel located in a city with some museums");
// bundle([h_1...h_n]) demonstrates how JASDL deals with nested se-content
// in particular, this query bundles together an arbitrary number of queries into a single message
- .send(Source, askOne, bundle( [ luxuriousHotel(H1)[o(holidays)], hotel(H2)[o(holidays)], activity(H3)[o(holidays)], hotelNearMuseums(H4)[o(self)] ] ), Response);
+ .send(Source, askOne, bundle( [ luxuriousHotel(H1)[o(holidays)], hotel(H2)[o(holidays)], activity(H3)[o(holidays)], hotelNearMuseums(H4)[o(self)] ] ), Response); // use to "query" to sender of this luxuriousHotel (travel_agent)
.print("Bundled query response: ", Response);
+ // ontology refered to by "places" is not known by travel_agent, but will be instantiated at run-time so it can usefully deal with this message
+ .send(Source, tell, building(travel_lodge)[o(places)]);
+ .send(Source, askOne, building(travel_lodge)[o(places)], _, 1000); // ensure information has been recieved by sender (travel_agent)
+
+ // demonstrates use of class definitions that mix entities from different ontologies
+ jasdl.ia.define_class(buildingAndHotel, "places:building and holidays:hotel");
+ .send(Source, askOne, buildingAndHotel(BuildingAndHotel)[o(self)], buildingAndHotel(BuildingAndHotel)[o(self)]);
+ .print(BuildingAndHotel, " is a building and a hotel");
+
.send(Source, tell, example_KSAA_complete).
-
+// Shows how we can receive all_different assertions that can now be sent (since they are no longer asserted using internal actions)
+all_different(XS)[o(holidays), source(Source)]
<-
- .print(XS, " are mutually distinct individuals, according to ", Source);
- .send(Source, tell, building(travel_lodge)[o(places)]);
- .wait(1000); // wait to ensure travel_agent has had a chance to add this information to its belief base
+ .print(XS, " are mutually distinct individuals, according to ", Source).
- jasdl.ia.define_class(q3, "(places:place and places:building) and holidays:hotel");
- .send(Source, askOne, q3(Hotel)[o(self)], q3(Hotel)[o(self)]);
- .print(Hotel, " is a building and a hotel").
-
Modified: trunk/applications/jasdl-owlapi/examples/travel_agent/travel_agent.asl
===================================================================
--- trunk/applications/jasdl-owlapi/examples/travel_agent/travel_agent.asl 2008-03-18 02:05:59 UTC (rev 1160)
+++ trunk/applications/jasdl-owlapi/examples/travel_agent/travel_agent.asl 2008-03-18 03:01:18 UTC (rev 1161)
@@ -39,16 +39,12 @@
+urbanArea(windsor)[o(travel)]; // windsor is an urban area
+isPartOf(windsor, london)[o(travel)]; // windsor is a part of london
+isPartOf(london, england)[o(travel)]; // london is a part of england
- +hasPricePerNight(hilton, 22.0)[o(travel)]; // hilton costs £22 a night
-
+ +hasPricePerNight(hilton, 22.0)[o(travel)]; // hilton costs £22 a night
+museums(scienceMuseum)[o(travel)];
+hasActivity(london, scienceMuseum)[o(travel)];
+hotel(travel_lodge)[o(travel)];
-
.print("Completed: Updating Belief Base 1").
-
-
@example_ubb_2[atomic]
+!example_UBB_2
<-
@@ -88,8 +84,10 @@
<-
.print("Example: Knowledge Sharing Among Agents");
.send(customer, tell, luxuryHotel(hilton)[o(travel)]);
- .send(customer, tell, all_different([hilton, fourSeasons])[o(travel)]). // since all_different assertions are treated as SE-literals, we can now send them between agents
-
+ // since all_different assertions are treated as SE-literals, we can now send them between agents
+ .send(customer, tell, all_different([hilton, fourSeasons])[o(travel)]).
+
+
// for dealing with bundled queries - see customer.asl
@bundle_1[atomic]
+?bundle([]).
@@ -144,9 +142,11 @@
+urbanArea(x)[o(travel), source(tom)];
+ruralArea(y)[o(travel), source(ben)];
- ?all_different([x,y])[o(travel), source(tom), source(ben)]; // because knowledge from tom and ben contributed to the inference that x and y are distinct
+ // because knowledge from tom and ben contributed to the inference that x and y are distinct
+ ?all_different([x,y])[o(travel), source(tom), source(ben)];
- ?familyDestination(butlins)[o(travel), something]; // notice "something" annotation is gathered here since it all_different assertion contributes to this inference
+ // notice "something" annotation is gathered (added in !example_all_different) here since it all_different assertion contributes to this inference
+ ?familyDestination(butlins)[o(travel), something];
.print("Complete: annotation gathering").
Modified: trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java 2008-03-18 02:05:59 UTC (rev 1160)
+++ trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java 2008-03-18 03:01:18 UTC (rev 1161)
@@ -5,6 +5,7 @@
import jasdl.asSemantics.parsing.URIEntityChecker;
import jasdl.asSyntax.JasdlPlanLibrary;
import jasdl.bb.JasdlBeliefBase;
+import jasdl.bridge.AllDifferentPlaceholder;
import jasdl.bridge.ToAxiomConverter;
import jasdl.bridge.ToSELiteralConverter;
import jasdl.bridge.alias.Alias;
@@ -132,7 +133,20 @@
// load .mas2j JASDL configuration
JasdlConfigurator config = new JasdlConfigurator(this);
config.configure(stts);
- return super.initAg(arch, bb, src, stts);
+
+ TransitionSystem ts = super.initAg(arch, bb, src, stts);
+
+ // *** The following must be performed after super.initAg since we require an agent name to be set ***
+
+ // create a personal ontology for (axioms that reference) run-time defined class
+ createOntology(getPersonalOntologyLabel(), getPersonalOntologyURI(), true);
+
+ // create a "placeholder" ontology so we can safely map thing and nothing without actually loading the ontology
+ createOntology(AliasFactory.OWL_THING.getLabel(), URI.create("http://www.w3.org/2002/07/owl"), false);
+ getAliasManager().put( AliasFactory.OWL_THING, getOntologyManager().getOWLDataFactory().getOWLThing());
+ getAliasManager().put( AliasFactory.OWL_NOTHING, getOntologyManager().getOWLDataFactory().getOWLNothing());
+
+ return ts;
}
@@ -237,12 +251,10 @@
OWLOntology ontology = ontologyManager.loadOntologyFromPhysicalURI(uri);
Set<OWLOntology> imports = ontologyManager.getImportsClosure(ontology);
reasoner.loadOntologies(imports);
- reasoner.classify();
- labelManager.put(label, ontology, false); // (successfully) loaded ontologies never personal
- physicalURIManager.put(ontology, uri);
- logicalURIManager.put(ontology, ontology.getURI());
+ reasoner.classify();
+ initOntology(ontology, label, uri, ontology.getURI(), false); // (successfully) loaded ontologies never personal
+ applyMappingStrategies(ontology, strategies);
getLogger().fine("Loaded ontology from "+uri+" and assigned label "+label);
- applyMappingStrategies(ontology, strategies);
return ontology;
}catch(OWLOntologyCreationException e){
getLogger().warning("Placeholder personal ontology substituted for unreachable "+uri);
@@ -252,6 +264,8 @@
}
}
+
+
/**
* Creates and fully maps a blank ontology. Used for example for "owl" ontology, containing
* axioms referencing "owl:thing" and "owl:nothing", and for personal ontologies containing
@@ -263,10 +277,8 @@
public OWLOntology createOntology(Atom label, URI uri, boolean isPersonal) throws JasdlException{
try{
OWLOntology ontology = getOntologyManager().createOntology( uri );
- getLabelManager().put(label, ontology, isPersonal);
- getPhysicalURIManager().put(ontology, uri);
- getLogicalURIManager().put(ontology, uri);
getReasoner().loadOntology(ontology);
+ initOntology(ontology, label, uri, uri, isPersonal);
return ontology;
} catch (OWLOntologyCreationException e) {
throw new JasdlException("Error instantiating OWL ontology. Reason: "+e);
@@ -274,6 +286,23 @@
}
/**
+ * Common ontology initialisation functionality, sets up various mappings.
+ * @param ontology
+ * @param label
+ * @param physicalURI
+ * @param logicalURI
+ * @param isPersonal
+ * @throws JasdlException
+ */
+ private void initOntology(OWLOntology ontology, Atom label, URI physicalURI, URI logicalURI, boolean isPersonal) throws JasdlException{
+ labelManager.put(label, ontology, isPersonal);
+ physicalURIManager.put(ontology, physicalURI);
+ logicalURIManager.put(ontology, logicalURI);
+ // create the AllDifferent placeholder entity for this ontology
+ getAliasManager().put( AliasFactory.INSTANCE.all_different(label), new AllDifferentPlaceholder(label)); // must be new instance to avoid duplicate mapping exceptions
+ }
+
+ /**
* When a duplicate mapping is encountered, an anonymous alias is created for the offending resource
* @param ontology
* @param strategies
@@ -364,14 +393,8 @@
* @return
*/
public String getAgentName(){
- return agentName;
+ return getTS().getUserAgArch().getAgName();
}
-
- public void setAgentName(String agentName){
- this.agentName = agentName;
- }
-
-
public List<MappingStrategy> getDefaultMappingStrategies() {
Modified: trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlConfigurator.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlConfigurator.java 2008-03-18 02:05:59 UTC (rev 1160)
+++ trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlConfigurator.java 2008-03-18 03:01:18 UTC (rev 1161)
@@ -27,6 +27,14 @@
private static String MAS2J_MAPPING_MANUAL = "_mapping_manual";
private static String MAS2J_AGENT_NAME = "_agent_name";
+ /**
+ * List of reserved ontology labels. Currently:
+ * <ul>
+ * <li> "default" - allows jasdl_default_mapping_strategies to be conveniently used to define the default mapping strategies performed
+ * by this agent on unknown incoming ontologies and predefined ontologies lacking mapping strategy definition</li>
+ * <li> "self" - refers to the "personal" ontology used by this agent to store axioms referencing run-time defined classes and individuals </li>
+ * </ul>
+ */
public static List<Atom> reservedOntologyLabels = Arrays.asList( new Atom[] {new Atom("default"), new Atom("self")});
@@ -38,15 +46,11 @@
public void configure(Settings stts) throws JasdlException{
try{
- // load agent name
- agent.setAgentName(prepareUserParameter( stts, MAS2J_PREFIX + MAS2J_AGENT_NAME ));
-
// load default mapping strategies
agent.setDefaultMappingStrategies(getMappingStrategies(stts, new Atom("default"))); //implication "default" is a reserved ontology label
loadOntologies(stts);
- applyManualMappings(stts);
- applyMiscMappings();
+ applyManualMappings(stts);
}catch(JasdlException e){
@@ -134,34 +138,12 @@
return strategies;
}
- /**
- * Maps thing and nothing. Must use "owl" label to refer to these, e.g. thing(x)[o(owl)]
- *
- * @throws JasdlException
- */
- private void applyMiscMappings() throws JasdlException{
-
- // create a "placeholder" ontology so we can safely map thing and nothing without actually loading the ontology
- agent.createOntology(AliasFactory.OWL_THING.getLabel(), URI.create("http://www.w3.org/2002/07/owl"), false);
-
- // create a personal ontology for (axioms that reference) run-time defined class
- agent.createOntology(agent.getPersonalOntologyLabel(), agent.getPersonalOntologyURI(), true);
-
- agent.getAliasManager().put( AliasFactory.OWL_THING, agent.getOntologyManager().getOWLDataFactory().getOWLThing());
- agent.getAliasManager().put( AliasFactory.OWL_NOTHING, agent.getOntologyManager().getOWLDataFactory().getOWLNothing());
-
- for(Atom label : agent.getLabelManager().getLefts()){
- agent.getAliasManager().put( AliasFactory.INSTANCE.all_different(label), new AllDifferentPlaceholder(label)); // must be new instance to avoid duplicate mapping exceptions
- }
- }
-
-
/**
* Convenience method to strip quotes and trim a .mas2j setting
* @param stts .mas2j settings
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <tom...@us...> - 2008-03-18 02:06:03
|
Revision: 1160
http://jason.svn.sourceforge.net/jason/?rev=1160&view=rev
Author: tomklapiscak
Date: 2008-03-17 19:05:59 -0700 (Mon, 17 Mar 2008)
Log Message:
-----------
Class definitions can now be composed of other run-time defined classes. This was achieved by:
* Adding equivalent named classes for anonymous defined classes (thus inherently allowing parsing to work).
* Mapping such named classes to their original anonymous descriptions.
* Recursively "normalising" outgoing expressions by replacing all references to run-time defined classes with the rendering of their corresponding anonymous description.
travel_agent example updated.
Modified Paths:
--------------
trunk/applications/jasdl-owlapi/examples/travel_agent/customer.asl
trunk/applications/jasdl-owlapi/src/jasdl/architecture/OutgoingPropContProcessingStrategy.java
trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java
trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlConfigurator.java
trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/parsing/NSPrefixEntityChecker.java
trunk/applications/jasdl-owlapi/src/jasdl/bridge/label/LabelManager.java
trunk/applications/jasdl-owlapi/src/jasdl/bridge/seliteral/SELiteral.java
Added Paths:
-----------
trunk/applications/jasdl-owlapi/src/jasdl/bridge/alias/DefinitionManager.java
Modified: trunk/applications/jasdl-owlapi/examples/travel_agent/customer.asl
===================================================================
--- trunk/applications/jasdl-owlapi/examples/travel_agent/customer.asl 2008-03-17 23:30:54 UTC (rev 1159)
+++ trunk/applications/jasdl-owlapi/examples/travel_agent/customer.asl 2008-03-18 02:05:59 UTC (rev 1160)
@@ -29,13 +29,17 @@
.print(L, " is located in the city ", City);
// check given hotel is located in a destination that has some museums
- jasdl.ia.define_class(q2, "{self:",L,"} and holidays:isLocatedAt some (holidays:hasActivity some holidays:museums)");
- .send(Source, askOne, q2(Hotel)[o(self)], q2(Hotel)[o(self)]);
- .print(Hotel, " is located in a city with some museums");
+ jasdl.ia.define_class(hotelNearMuseums, "holidays:isLocatedAt some (holidays:hasActivity some holidays:museums)");
+ .send(Source, askOne, hotelNearMuseums(HotelNearMuseums)[o(self)], hotelNearMuseums(HotelNearMuseums)[o(self)]);
+ .print(HotelNearMuseums, " is a hotel located in a city with some museums");
+ jasdl.ia.define_class(luxuriousHotelNearMuseums, "self:hotelNearMuseums AND holidays:luxuriousHotel");
+ .send(Source, askOne, luxuriousHotelNearMuseums(LuxuriousHotelNearMuseums)[o(self)], luxuriousHotelNearMuseums(LuxuriousHotelNearMuseums)[o(self)]);
+ .print(LuxuriousHotelNearMuseums, " is a luxurious hotel located in a city with some museums");
+
// bundle([h_1...h_n]) demonstrates how JASDL deals with nested se-content
// in particular, this query bundles together an arbitrary number of queries into a single message
- .send(Source, askOne, bundle( [ luxuriousHotel(H1)[o(holidays)], hotel(H2)[o(holidays)], activity(H3)[o(holidays)], q2(H4)[o(self)] ] ), Response);
+ .send(Source, askOne, bundle( [ luxuriousHotel(H1)[o(holidays)], hotel(H2)[o(holidays)], activity(H3)[o(holidays)], hotelNearMuseums(H4)[o(self)] ] ), Response);
.print("Bundled query response: ", Response);
.send(Source, tell, example_KSAA_complete).
Modified: trunk/applications/jasdl-owlapi/src/jasdl/architecture/OutgoingPropContProcessingStrategy.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/architecture/OutgoingPropContProcessingStrategy.java 2008-03-17 23:30:54 UTC (rev 1159)
+++ trunk/applications/jasdl-owlapi/src/jasdl/architecture/OutgoingPropContProcessingStrategy.java 2008-03-18 02:05:59 UTC (rev 1160)
@@ -22,7 +22,6 @@
import static jasdl.architecture.JasdlAgArch.ANON_ANNOTATION_FUNCTOR;
import static jasdl.architecture.JasdlAgArch.NAMED_ANNOTATION_FUNCTOR;
import jasdl.asSemantics.JasdlAgent;
-import jasdl.bridge.alias.Alias;
import jasdl.bridge.seliteral.SELiteral;
import jasdl.bridge.seliteral.SELiteralAllDifferentAssertion;
import jasdl.util.JasdlException;
@@ -40,8 +39,8 @@
import java.util.HashSet;
import java.util.Set;
-import org.semanticweb.owl.model.OWLNamedObject;
-import org.semanticweb.owl.model.OWLObject;
+import org.semanticweb.owl.model.OWLDescription;
+import org.semanticweb.owl.model.OWLEntity;
import org.semanticweb.owl.model.OWLOntology;
public class OutgoingPropContProcessingStrategy implements PropContProcessingStrategy {
@@ -65,22 +64,12 @@
// qualify o
sl.qualifyOntologyAnnotation();
- OWLObject obj = sl.toOWLObject();
- String expression = agent.getManchesterObjectRenderer().render(obj);
- StringTerm expressionTerm = new StringTermImpl(expression);
- Alias alias = sl.toAlias();
+ OWLEntity entity = (OWLEntity)sl.toOWLObject();
+ String expression = normaliseExpression(agent.getManchesterObjectRenderer().render(entity), agent);
+ StringTerm expressionTerm = new StringTermImpl(expression);
- if(obj instanceof OWLNamedObject){
+ if(entity.isOWLClass() && agent.getDefinitionManager().isKnownLeft(entity.asOWLClass())){ // we have an anonymous run-time defined class
- // unambiguously refer to named entity
- if(!(sl instanceof SELiteralAllDifferentAssertion)){// not required if all_different
- Structure named = new Structure(NAMED_ANNOTATION_FUNCTOR);
- named.addTerm(expressionTerm);
- sl.getLiteral().addAnnot(named);
- }
-
- }else{ // we have an anonymous run-time defined class
-
// construct anon annotation
Structure anon = new Structure(ANON_ANNOTATION_FUNCTOR);
anon.addTerm(expressionTerm);
@@ -105,7 +94,17 @@
}
anon.addTerm(list);
- sl.getLiteral().addAnnot(anon);
+ sl.getLiteral().addAnnot(anon);
+
+ }else{
+
+ // unambiguously refer to named entity
+ if(!(sl instanceof SELiteralAllDifferentAssertion)){// not required if all_different
+ Structure named = new Structure(NAMED_ANNOTATION_FUNCTOR);
+ named.addTerm(expressionTerm);
+ sl.getLiteral().addAnnot(named);
+ }
+
}
result = sl.getLiteral();
}catch(NotEnrichedException e){
@@ -114,5 +113,44 @@
return result;
}
+ /**
+ * Returns an expression in which all references to run-time defined classes have been (recursuvely) replaced
+ * with the rendering of their anonymous descriptions, thus ensuring this rendering only refers to predefined classes.
+ * @param expression expression to normalise
+ * @param agent
+ * @return normalised form of expression
+ * @throws JasdlException
+ */
+ private String normaliseExpression(String expression, JasdlAgent agent) throws JasdlException{
+ String[] tokens = expression.toString().split("[ |\n]");
+ String newExpression = "";
+ for(String token : tokens){
+ try {
+ URI entityURI = new URI(token);
+ OWLEntity entity = agent.toEntity(entityURI);
+ if(entity.isOWLClass()){
+ try{
+ OWLDescription desc = agent.getDefinitionManager().getRight(entity.asOWLClass());
+ String rendering = agent.getManchesterObjectRenderer().render(desc);
+ newExpression += "("+normaliseExpression(rendering, agent)+")";
+ }catch(UnknownMappingException e1){
+ // this is a predefined class
+ newExpression += token;
+ }
+ }else{
+ // this is a predefined non-class entity (property, individual, etc)
+ newExpression += token;
+ }
+ }catch(URISyntaxException e){
+ // this is (probably) a keyword
+ newExpression += " " + token + " ";
+ }catch(UnknownMappingException e2){
+ // this is (probably) a keyword
+ newExpression += " " + token + " ";
+ }
+
+ }
+ return newExpression;
+ }
}
Modified: trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java 2008-03-17 23:30:54 UTC (rev 1159)
+++ trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java 2008-03-18 02:05:59 UTC (rev 1160)
@@ -11,6 +11,7 @@
import jasdl.bridge.alias.AliasFactory;
import jasdl.bridge.alias.AliasManager;
import jasdl.bridge.alias.DecapitaliseMappingStrategy;
+import jasdl.bridge.alias.DefinitionManager;
import jasdl.bridge.alias.MappingStrategy;
import jasdl.bridge.label.LabelManager;
import jasdl.bridge.label.OntologyURIManager;
@@ -29,6 +30,7 @@
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.Vector;
@@ -39,9 +41,12 @@
import org.mindswap.pellet.PelletOptions;
import org.mindswap.pellet.owlapi.Reasoner;
import org.semanticweb.owl.apibinding.OWLManager;
+import org.semanticweb.owl.model.OWLClass;
import org.semanticweb.owl.model.OWLDescription;
import org.semanticweb.owl.model.OWLEntity;
+import org.semanticweb.owl.model.OWLEquivalentClassesAxiom;
import org.semanticweb.owl.model.OWLOntology;
+import org.semanticweb.owl.model.OWLOntologyChangeException;
import org.semanticweb.owl.model.OWLOntologyCreationException;
import org.semanticweb.owl.model.OWLOntologyManager;
import org.semanticweb.owl.util.ShortFormProvider;
@@ -74,6 +79,8 @@
* Since Jason doesn't initialise an agent name in time
*/
private String agentName;
+
+ private DefinitionManager definitionManager;
@@ -87,6 +94,7 @@
ontologyManager = OWLManager.createOWLOntologyManager();
physicalURIManager = new OntologyURIManager();
logicalURIManager = new OntologyURIManager();
+ definitionManager = new DefinitionManager();
seLiteralFactory = new SELiteralFactory(this);
toAxiomConverter = new ToAxiomConverter(this);
@@ -230,15 +238,17 @@
Set<OWLOntology> imports = ontologyManager.getImportsClosure(ontology);
reasoner.loadOntologies(imports);
reasoner.classify();
- labelManager.put(label, ontology);
+ labelManager.put(label, ontology, false); // (successfully) loaded ontologies never personal
physicalURIManager.put(ontology, uri);
logicalURIManager.put(ontology, ontology.getURI());
getLogger().fine("Loaded ontology from "+uri+" and assigned label "+label);
applyMappingStrategies(ontology, strategies);
return ontology;
}catch(OWLOntologyCreationException e){
- getLogger().warning("Placeholder ontology substituted for unreachable "+uri);
- return createOntology(label, uri); // can't load it, just create a blank (for unqualification of ontology annotations for example)
+ getLogger().warning("Placeholder personal ontology substituted for unreachable "+uri);
+ // can't load it, just create a blank (for unqualification of ontology annotations for example)
+ // personal by definition
+ return createOntology(label, uri, true);
}
}
@@ -250,10 +260,10 @@
* @param uri
* @throws JasdlException
*/
- public OWLOntology createOntology(Atom label, URI uri) throws JasdlException{
+ public OWLOntology createOntology(Atom label, URI uri, boolean isPersonal) throws JasdlException{
try{
OWLOntology ontology = getOntologyManager().createOntology( uri );
- getLabelManager().put(label, ontology);
+ getLabelManager().put(label, ontology, isPersonal);
getPhysicalURIManager().put(ontology, uri);
getLogicalURIManager().put(ontology, uri);
getReasoner().loadOntology(ontology);
@@ -325,8 +335,26 @@
desc = parser.parse(expression);
}catch(Exception e){
throw new JasdlException("Could not parse expression "+expression+". Reason: "+e);
- }
- getAliasManager().put(alias, desc);
+ }
+
+ // We need this class to be named for parsing.
+ // Create an equivalent class and add this instead with alias as fragment.
+ // Clashes shouldn't be an issue here (thanks to distinct personal ontologies).
+ OWLOntology ontology = getLabelManager().getRight(label);
+ String _uri = getLogicalURIManager().getRight(ontology).toString();
+ _uri+="#"+functor;
+ URI uri = URI.create(_uri);
+ OWLClass naming = ontologyManager.getOWLDataFactory().getOWLClass(uri);
+ OWLEquivalentClassesAxiom axiom = ontologyManager.getOWLDataFactory().getOWLEquivalentClassesAxiom(naming, desc);
+ try {
+ ontologyManager.addAxioms(ontology, Collections.singleton(axiom));
+ } catch (OWLOntologyChangeException e) {
+ throw new JasdlException("Error adding "+uri+" naming of "+desc+" to "+label);
+ }
+ reasoner.refresh();
+ getLogger().fine("Adding named class "+uri+" for "+desc+" in "+label);
+ getAliasManager().put(alias, naming); // consequence, we can no longer easily distinguish run-time defined classes from pre-defined - need to maintain a map
+ getDefinitionManager().put(naming, desc);
getLogger().fine("Defined new class with alias "+alias);
return desc;
}
@@ -391,6 +419,12 @@
return logicalURIManager;
}
+ public DefinitionManager getDefinitionManager() {
+ return definitionManager;
+ }
+
+
+
public Reasoner getReasoner() {
return reasoner;
}
Modified: trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlConfigurator.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlConfigurator.java 2008-03-17 23:30:54 UTC (rev 1159)
+++ trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlConfigurator.java 2008-03-18 02:05:59 UTC (rev 1160)
@@ -142,10 +142,10 @@
private void applyMiscMappings() throws JasdlException{
// create a "placeholder" ontology so we can safely map thing and nothing without actually loading the ontology
- agent.createOntology(AliasFactory.OWL_THING.getLabel(), URI.create("http://www.w3.org/2002/07/owl"));
+ agent.createOntology(AliasFactory.OWL_THING.getLabel(), URI.create("http://www.w3.org/2002/07/owl"), false);
// create a personal ontology for (axioms that reference) run-time defined class
- agent.createOntology(agent.getPersonalOntologyLabel(), agent.getPersonalOntologyURI());
+ agent.createOntology(agent.getPersonalOntologyLabel(), agent.getPersonalOntologyURI(), true);
agent.getAliasManager().put( AliasFactory.OWL_THING, agent.getOntologyManager().getOWLDataFactory().getOWLThing());
agent.getAliasManager().put( AliasFactory.OWL_NOTHING, agent.getOntologyManager().getOWLDataFactory().getOWLNothing());
Modified: trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/parsing/NSPrefixEntityChecker.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/parsing/NSPrefixEntityChecker.java 2008-03-17 23:30:54 UTC (rev 1159)
+++ trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/parsing/NSPrefixEntityChecker.java 2008-03-18 02:05:59 UTC (rev 1160)
@@ -94,6 +94,9 @@
Atom label = new Atom(tokens[0]);
Alias alias = AliasFactory.INSTANCE.create(functor, label);
return (OWLEntity)agent.getAliasManager().getRight(alias); // guaranteed to be an entity? Not for anonymous classes!
+ }catch(ClassCastException e){
+ // we are dealing with an anonymous class description
+ return null;
} catch (Exception e) {
return null;
}
Added: trunk/applications/jasdl-owlapi/src/jasdl/bridge/alias/DefinitionManager.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/bridge/alias/DefinitionManager.java (rev 0)
+++ trunk/applications/jasdl-owlapi/src/jasdl/bridge/alias/DefinitionManager.java 2008-03-18 02:05:59 UTC (rev 1160)
@@ -0,0 +1,15 @@
+package jasdl.bridge.alias;
+
+import jasdl.bridge.MappingManager;
+
+import org.semanticweb.owl.model.OWLClass;
+import org.semanticweb.owl.model.OWLDescription;
+
+/**
+ * Maintains mappings between run-time defined classes and their anonymous descriptions.
+ * Required for recursive rendering of run-time defined classes in terms of predefined.
+ * @author Tom Klapiscak
+ *
+ */
+public class DefinitionManager extends MappingManager<OWLClass, OWLDescription> {
+}
Modified: trunk/applications/jasdl-owlapi/src/jasdl/bridge/label/LabelManager.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/bridge/label/LabelManager.java 2008-03-17 23:30:54 UTC (rev 1159)
+++ trunk/applications/jasdl-owlapi/src/jasdl/bridge/label/LabelManager.java 2008-03-18 02:05:59 UTC (rev 1160)
@@ -1,8 +1,12 @@
package jasdl.bridge.label;
import jasdl.bridge.MappingManager;
+import jasdl.util.DuplicateMappingException;
import jason.asSyntax.Atom;
+import java.util.HashSet;
+import java.util.Set;
+
import org.semanticweb.owl.model.OWLOntology;
/**
@@ -12,4 +16,31 @@
*
*/
public class LabelManager extends MappingManager<Atom, OWLOntology>{
+
+ /**
+ * Members of this set are defined as "personal" ontology instances used for storing axioms
+ * about run-time defined classes and individuals. This information is needed, for example, when preparing
+ * outgoing message content (named or anon?).
+ */
+ private Set<OWLOntology> personals;
+
+
+
+
+ public LabelManager() {
+ super();
+ personals = new HashSet<OWLOntology>();
+ }
+
+ public boolean isPersonal(OWLOntology y){
+ return personals.contains(y);
+ }
+
+
+ public void put(Atom x, OWLOntology y, boolean isPersonal) throws DuplicateMappingException {
+ if(isPersonal) personals.add(y);
+ super.put(x, y);
+ }
+
+
}
Modified: trunk/applications/jasdl-owlapi/src/jasdl/bridge/seliteral/SELiteral.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/bridge/seliteral/SELiteral.java 2008-03-17 23:30:54 UTC (rev 1159)
+++ trunk/applications/jasdl-owlapi/src/jasdl/bridge/seliteral/SELiteral.java 2008-03-18 02:05:59 UTC (rev 1160)
@@ -79,7 +79,7 @@
if(o.getTerm(0).isStructure()){ // Checking for atomicity directly does not seem to work
return agent.getLabelManager().getRight((Atom)o.getTerm(0));
}else if(o.getTerm(0).isString()){
- return agent.getOntology(o.getTerm(0).toString());
+ return agent.getOntology(o.getTerm(0).toString()); // may instantiate a new ontology
}else{
throw new InvalidSELiteralException("Invalid ontology annotation format on "+o);
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-17 23:30:57
|
Revision: 1159
http://jason.svn.sourceforge.net/jason/?rev=1159&view=rev
Author: jomifred
Date: 2008-03-17 16:30:54 -0700 (Mon, 17 Mar 2008)
Log Message:
-----------
in build.xml created to run the user project, calls user-init before init (and not before
run)
Modified Paths:
--------------
trunk/src/jason/asSyntax/Atom.java
trunk/src/jason/infra/centralised/CentralisedMASLauncherAnt.java
trunk/src/templates/build-template.xml
trunk/src/test/TermTest.java
Modified: trunk/src/jason/asSyntax/Atom.java
===================================================================
--- trunk/src/jason/asSyntax/Atom.java 2008-03-17 21:13:29 UTC (rev 1158)
+++ trunk/src/jason/asSyntax/Atom.java 2008-03-17 23:30:54 UTC (rev 1159)
@@ -131,8 +131,7 @@
if (o == this) return true;
if (o instanceof Structure) {
Structure s = (Structure)o;
- if (!getFunctor().equals(s.getFunctor())) return false;
- return s.isAtom();
+ return s.isAtom() && getFunctor().equals(s.getFunctor());
}
return false;
}
Modified: trunk/src/jason/infra/centralised/CentralisedMASLauncherAnt.java
===================================================================
--- trunk/src/jason/infra/centralised/CentralisedMASLauncherAnt.java 2008-03-17 21:13:29 UTC (rev 1158)
+++ trunk/src/jason/infra/centralised/CentralisedMASLauncherAnt.java 2008-03-17 23:30:54 UTC (rev 1159)
@@ -187,14 +187,15 @@
if (apos < 0) {
lib += " <pathelement location=\""+cp+"\"/>\n";
} else {
+ cp = cp.replaceAll("\\\\", "/");
String dir = "${basedir}";
String files = cp;
- int spos = cp.lastIndexOf(File.separator);
+ int spos = cp.lastIndexOf("/");
if (spos >= 0 && spos < apos) {
dir = cp.substring(0,spos);
files = cp.substring(spos+1);
} else {
- spos = cp.lastIndexOf(File.separator+"**");
+ spos = cp.lastIndexOf("/**");
if (spos >= 0 && spos < apos) {
dir = cp.substring(0,spos);
files = cp.substring(spos+1);
Modified: trunk/src/templates/build-template.xml
===================================================================
--- trunk/src/templates/build-template.xml 2008-03-17 21:13:29 UTC (rev 1158)
+++ trunk/src/templates/build-template.xml 2008-03-17 23:30:54 UTC (rev 1159)
@@ -33,6 +33,7 @@
<target name="init">
<mkdir dir="${build.dir}" />
+ <antcall target="user-init" />
</target>
<target name="compile" depends="init">
@@ -82,7 +83,6 @@
<target name="run" depends="compile" >
<echo message="Running project ${ant.project.name}" />
- <antcall target="user-init" />
<java classname="<PROJECT-RUNNER-CLASS>"
failonerror="true" fork="yes" dir="${basedir}" >
<classpath refid="project.classpath"/>
Modified: trunk/src/test/TermTest.java
===================================================================
--- trunk/src/test/TermTest.java 2008-03-17 21:13:29 UTC (rev 1158)
+++ trunk/src/test/TermTest.java 2008-03-17 23:30:54 UTC (rev 1159)
@@ -43,6 +43,7 @@
assertFalse(t1.equals(t2));
t2.addTerm(new Atom("a"));
+ assertEquals(new Atom("a"),new Atom("a"));
assertTrue(t1.equals(t2));
assertTrue(t2.equals(t1));
assertEquals(t1.hashCode(),t2.hashCode());
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jom...@us...> - 2008-03-17 21:13:32
|
Revision: 1158
http://jason.svn.sourceforge.net/jason/?rev=1158&view=rev
Author: jomifred
Date: 2008-03-17 14:13:29 -0700 (Mon, 17 Mar 2008)
Log Message:
-----------
implement make makeVarsAnnots for annotations
Modified Paths:
--------------
trunk/examples/gold-miners-II/asl/miner.asl
trunk/src/jason/asSyntax/Atom.java
trunk/src/jason/asSyntax/ListTermImpl.java
trunk/src/jason/asSyntax/Literal.java
trunk/src/jason/asSyntax/Pred.java
trunk/src/jason/asSyntax/Structure.java
trunk/src/test/TermTest.java
Modified: trunk/examples/gold-miners-II/asl/miner.asl
===================================================================
--- trunk/examples/gold-miners-II/asl/miner.asl 2008-03-17 19:13:28 UTC (rev 1157)
+++ trunk/examples/gold-miners-II/asl/miner.asl 2008-03-17 21:13:29 UTC (rev 1158)
@@ -59,7 +59,7 @@
!change_to_fetch(NewG).
+!choose_goal // there is no worth gold
- : carrying.gold > 0
+ : carrying_gold(NG) & NG > 0
<- !change_to_goto_depot.
+!choose_goal // not carrying gold, be free and search gold
Modified: trunk/src/jason/asSyntax/Atom.java
===================================================================
--- trunk/src/jason/asSyntax/Atom.java 2008-03-17 19:13:28 UTC (rev 1157)
+++ trunk/src/jason/asSyntax/Atom.java 2008-03-17 21:13:29 UTC (rev 1158)
@@ -33,9 +33,9 @@
import java.util.logging.Logger;
/**
- * Represents an atom (a structure with no arguments), it is an
+ * Represents an atom (a structure with no arguments, e.g. "tell", "a"), it is an
* immutable object. It extends Literal, so can be used in place of a
- * Literal, but does not allow operations on terms.
+ * Literal, but does not allow operations on terms/atoms and can not be negated.
*/
public final class Atom extends Literal {
@@ -113,17 +113,27 @@
// an Atom as parameter
return new ArrayList<Term>(2);
}
-
+
@Override
public Term[] getTermsArray() {
- return new Term[0];
+ return emptyTermArray;
}
+ @Override
+ public void setNegated(boolean b) {
+ logger.log(Level.SEVERE, "You should not negate the atom "+this+"\n",new Exception());
+ super.setNegated(b);
+ }
+
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
- if (o instanceof Structure) return getFunctor().equals(((Structure)o).getFunctor());
+ if (o instanceof Structure) {
+ Structure s = (Structure)o;
+ if (!getFunctor().equals(s.getFunctor())) return false;
+ return s.isAtom();
+ }
return false;
}
Modified: trunk/src/jason/asSyntax/ListTermImpl.java
===================================================================
--- trunk/src/jason/asSyntax/ListTermImpl.java 2008-03-17 19:13:28 UTC (rev 1157)
+++ trunk/src/jason/asSyntax/ListTermImpl.java 2008-03-17 21:13:29 UTC (rev 1158)
@@ -182,6 +182,11 @@
}
}
+ @Override
+ public boolean isAtom() {
+ return false;
+ }
+
@Override
public boolean isList() {
return true;
Modified: trunk/src/jason/asSyntax/Literal.java
===================================================================
--- trunk/src/jason/asSyntax/Literal.java 2008-03-17 19:13:28 UTC (rev 1157)
+++ trunk/src/jason/asSyntax/Literal.java 2008-03-17 21:13:29 UTC (rev 1158)
@@ -85,7 +85,10 @@
public static Literal parseLiteral(String sLiteral) {
as2j parser = new as2j(new StringReader(sLiteral));
try {
- return parser.literal();
+ Literal l = parser.literal();
+ if (l instanceof Atom) // force the result as literal
+ l = new Literal(l.getFunctor());
+ return l;
} catch (Exception e) {
logger.log(Level.SEVERE,"Error parsing literal " + sLiteral,e);
return null;
@@ -356,9 +359,9 @@
@SuppressWarnings("serial")
- static class TrueLiteral extends Literal {
+ static final class TrueLiteral extends Literal {
public TrueLiteral() {
- super("true",1);
+ super("true",0);
}
@Override
@@ -373,9 +376,9 @@
}
@SuppressWarnings("serial")
- static class FalseLiteral extends Literal {
+ static final class FalseLiteral extends Literal {
public FalseLiteral() {
- super("false",1);
+ super("false",0);
}
@Override
Modified: trunk/src/jason/asSyntax/Pred.java
===================================================================
--- trunk/src/jason/asSyntax/Pred.java 2008-03-17 19:13:28 UTC (rev 1157)
+++ trunk/src/jason/asSyntax/Pred.java 2008-03-17 21:13:29 UTC (rev 1158)
@@ -404,7 +404,36 @@
return false;
}
+
+ /**
+ * Replaces all variables of the term for unnamed variables (_).
+ *
+ * @param changes is the map of replacements
+ */
@Override
+ protected void makeVarsAnnon(Map<VarTerm,UnnamedVar> changes) {
+ if (annots != null) {
+ Iterator<ListTerm> i = annots.listTermIterator();
+ while (i.hasNext()) {
+ ListTerm lt = i.next();
+ Term ta = lt.getTerm();
+ if (ta.isVar()) {
+ // replace ta to an unnamed var
+ UnnamedVar uv = changes.get(ta);
+ if (uv == null) {
+ uv = new UnnamedVar();
+ changes.put((VarTerm)ta, uv);
+ }
+ lt.setTerm(uv);
+ } else if (ta.isStructure()) {
+ ((Structure)ta).makeVarsAnnon(changes);
+ }
+ }
+ }
+ super.makeVarsAnnon(changes);
+ }
+
+ @Override
public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
Modified: trunk/src/jason/asSyntax/Structure.java
===================================================================
--- trunk/src/jason/asSyntax/Structure.java 2008-03-17 19:13:28 UTC (rev 1157)
+++ trunk/src/jason/asSyntax/Structure.java 2008-03-17 21:13:29 UTC (rev 1158)
@@ -48,6 +48,8 @@
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(Structure.class.getName());
+ protected static final Term[] emptyTermArray = new Term[0]; // just to have a type for toArray in the getTermsArray method
+
private final String functor; // immutable field
private List<Term> terms;
@@ -237,11 +239,7 @@
/** returns the i-th term (first term is 0) */
public Term getTerm(int i) {
- if (terms.size() > i) {
- return terms.get(i);
- } else {
- return null;
- }
+ return terms.get(i);
}
public int getArity() {
@@ -264,8 +262,6 @@
return getArity() > 0; // should use getArity to work for list/atom
}
- private static final Term[] emptyTermArray = new Term[0]; // just to have a type for toArray in the getTermsArray method
-
public Term[] getTermsArray() {
return terms.toArray(emptyTermArray);
}
@@ -277,7 +273,7 @@
@Override
public boolean isAtom() {
- return !hasTerm() && !isList();
+ return !hasTerm();
}
public boolean isGround() {
@@ -300,7 +296,7 @@
*
* @param changes is the map of replacements
*/
- private void makeVarsAnnon(Map<VarTerm,UnnamedVar> changes) {
+ protected void makeVarsAnnon(Map<VarTerm,UnnamedVar> changes) {
final int size = getArity();
for (int i=0; i<size; i++) {
Term ti = getTerm(i);
Modified: trunk/src/test/TermTest.java
===================================================================
--- trunk/src/test/TermTest.java 2008-03-17 19:13:28 UTC (rev 1157)
+++ trunk/src/test/TermTest.java 2008-03-17 21:13:29 UTC (rev 1158)
@@ -7,11 +7,11 @@
import jason.asSyntax.ListTermImpl;
import jason.asSyntax.Literal;
import jason.asSyntax.NumberTermImpl;
+import jason.asSyntax.Plan;
import jason.asSyntax.Pred;
import jason.asSyntax.Structure;
import jason.asSyntax.Term;
import jason.asSyntax.Trigger;
-import jason.asSyntax.Plan;
import jason.asSyntax.VarTerm;
import jason.asSyntax.Trigger.TEOperator;
import jason.asSyntax.Trigger.TEType;
@@ -19,6 +19,8 @@
import jason.bb.BeliefBase;
import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
import junit.framework.TestCase;
@@ -72,8 +74,7 @@
Term tpos = new Atom("pos");
assertFalse(l3.equals(tpos));
- assertTrue(tpos.equals(l3));
- assertTrue(new Atom("pos").equals(l3));
+ assertFalse(tpos.equals(l3));
//System.out.println(new Term("pos")+"="+l3+" --> "+new Term("pos").equals(l3));
assertFalse(new Pred("pos").equals(l3));
@@ -581,6 +582,15 @@
assertEquals(l1.toString(), "calc(32,33,33)");
}
+ public void testMakeVarAnnon3() {
+ Literal l1 = Literal.parseLiteral("calc(AgY,X)[vl(X),source(AgY),bla(Y),X]");
+ l1.makeVarsAnnon();
+ Map<VarTerm, Integer> v = new HashMap<VarTerm, Integer>();
+ l1.countVars(v);
+ assertEquals(3, v.size());
+ assertEquals("vl("+l1.getTerm(1)+")",l1.getAnnots("vl").get(0).toString());
+ }
+
public void testAddAnnots() {
Literal p1 = Literal.parseLiteral("p1");
Literal p2 = Literal.parseLiteral("p2[a1,a2]");
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <tom...@us...> - 2008-03-17 19:13:39
|
Revision: 1157
http://jason.svn.sourceforge.net/jason/?rev=1157&view=rev
Author: tomklapiscak
Date: 2008-03-17 12:13:28 -0700 (Mon, 17 Mar 2008)
Log Message:
-----------
New and improved semantically-enriched knowledge sharing protocol implemented and working.
Improvements to mapping system.
Architectural improvements (SELiteral class now follows "decorator" design pattern).
Various bug-fixes.
travel_agent example updated
Modified Paths:
--------------
trunk/applications/jasdl-owlapi/examples/travel_agent/config.mas2j
trunk/applications/jasdl-owlapi/examples/travel_agent/customer.asl
trunk/applications/jasdl-owlapi/examples/travel_agent/travel_agent.asl
trunk/applications/jasdl-owlapi/src/jasdl/architecture/IncomingPropContProcessingStrategy.java
trunk/applications/jasdl-owlapi/src/jasdl/architecture/JasdlAgArch.java
trunk/applications/jasdl-owlapi/src/jasdl/architecture/OutgoingPropContProcessingStrategy.java
trunk/applications/jasdl-owlapi/src/jasdl/architecture/PropContProcessingStrategy.java
trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java
trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlConfigurator.java
trunk/applications/jasdl-owlapi/src/jasdl/asSyntax/JasdlPlanLibrary.java
trunk/applications/jasdl-owlapi/src/jasdl/bb/JasdlBeliefBase.java
trunk/applications/jasdl-owlapi/src/jasdl/bridge/MappingManager.java
trunk/applications/jasdl-owlapi/src/jasdl/bridge/ToAxiomConverter.java
trunk/applications/jasdl-owlapi/src/jasdl/bridge/alias/AliasFactory.java
trunk/applications/jasdl-owlapi/src/jasdl/bridge/seliteral/SELiteral.java
trunk/applications/jasdl-owlapi/src/jasdl/bridge/seliteral/SELiteralAllDifferentAssertion.java
trunk/applications/jasdl-owlapi/src/jasdl/bridge/seliteral/SELiteralClassAssertion.java
trunk/applications/jasdl-owlapi/src/jasdl/bridge/seliteral/SELiteralDataPropertyAssertion.java
trunk/applications/jasdl-owlapi/src/jasdl/bridge/seliteral/SELiteralFactory.java
trunk/applications/jasdl-owlapi/src/jasdl/bridge/seliteral/SELiteralObjectPropertyAssertion.java
trunk/applications/jasdl-owlapi/src/jasdl/bridge/seliteral/SELiteralPropertyAssertion.java
trunk/applications/jasdl-owlapi/src/jasdl/ia/define_class.java
Added Paths:
-----------
trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/parsing/
trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/parsing/NSPrefixEntityChecker.java
trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/parsing/URIEntityChecker.java
Modified: trunk/applications/jasdl-owlapi/examples/travel_agent/config.mas2j
===================================================================
--- trunk/applications/jasdl-owlapi/examples/travel_agent/config.mas2j 2008-03-17 08:41:44 UTC (rev 1156)
+++ trunk/applications/jasdl-owlapi/examples/travel_agent/config.mas2j 2008-03-17 19:13:28 UTC (rev 1157)
@@ -32,10 +32,16 @@
agents:
travel_agent
travel_agent.asl
- [
- jasdl_ontologies="travel,places",
+ [
+ jasdl_agent_name = "travelagent",
+ // implication, "default" is a reserved ontology name
+ // also, "self"
+ jasdl_default_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy", // applied to incoming ontologies and those given no automapping
+ //TODO: what about when automapping causes a conflict?! anonymous aliasing?
+
+ jasdl_ontologies="travel",
jasdl_travel_uri="http://www.dur.ac.uk/t.g.klapiscak/onts/travel.owl",
- jasdl_travel_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy",
+ //jasdl_travel_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy",
jasdl_travel_mapping_manual="small_beach=beach",
jasdl_places_uri="http://www.dur.ac.uk/t.g.klapiscak/onts/places.owl",
@@ -51,13 +57,18 @@
customer
customer.asl
- [
- jasdl_ontologies="holidays",
+ [
+ jasdl_agent_name = "customer",
+
+ jasdl_ontologies="holidays,places",
//jasdl_holidays_uri="file:///home/tom/Desktop/Project/workspace/jason/applications/jasdl-owlapi/examples/travel_agent/ontologies/travel.owl",
jasdl_holidays_uri="http://www.dur.ac.uk/t.g.klapiscak/onts/travel.owl",
jasdl_holidays_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy",
- jasdl_holidays_mapping_manual="small_beach=beach, luxuriousHotel=LuxuryHotel" // arbitrary primitive mappings handled correctly
+ jasdl_holidays_mapping_manual="small_beach=beach, luxuriousHotel=LuxuryHotel", // arbitrary primitive mappings handled correctly
+ jasdl_places_uri="http://www.dur.ac.uk/t.g.klapiscak/onts/places.owl",
+ jasdl_places_mapping_strategies="jasdl.bridge.alias.DecapitaliseMappingStrategy"
+
/* Example per-agent proxy settings used for ontology instantiation */
//jasdl_http_proxy="127.0.0.1:3128"
//jasdl_https_proxy="127.0.0.1:8080"
Modified: trunk/applications/jasdl-owlapi/examples/travel_agent/customer.asl
===================================================================
--- trunk/applications/jasdl-owlapi/examples/travel_agent/customer.asl 2008-03-17 08:41:44 UTC (rev 1156)
+++ trunk/applications/jasdl-owlapi/examples/travel_agent/customer.asl 2008-03-17 19:13:28 UTC (rev 1157)
@@ -18,27 +18,37 @@
*
*/
+//+luxuriousHotel(L)[o(holidays), source(Source)]
+luxuriousHotel(L)[o(holidays), source(Source)]
<-
- /* 1 */ .print("The ", L, " luxurious hotel is available");
- /* 2 */ jasdl.ia.define_class(query, "city and hasAccommodation value ", L);
- /* 3 */ .send(Source, askOne, query(City)[o(holidays)], query(City)[o(holidays)]);
- /* 4 */ .print(L, " is located in the city ", City);
+ ?hotel(L)[o(holidays)];
+ .print("The ", L, " luxurious hotel is available");
+ jasdl.ia.define_class(query, "holidays:city and holidays:hasAccommodation value self:", L);
+ .send(Source, askOne, query(City)[o(self)], query(City)[o(self)]);
+ .print(L, " is located in the city ", City);
+
// check given hotel is located in a destination that has some museums
- jasdl.ia.define_class(q2, "{",L,"} and isLocatedAt some (hasActivity some museums)");
- .send(Source, askOne, q2(Hotel)[o(holidays)], q2(Hotel)[o(holidays)]);
+ jasdl.ia.define_class(q2, "{self:",L,"} and holidays:isLocatedAt some (holidays:hasActivity some holidays:museums)");
+ .send(Source, askOne, q2(Hotel)[o(self)], q2(Hotel)[o(self)]);
.print(Hotel, " is located in a city with some museums");
// bundle([h_1...h_n]) demonstrates how JASDL deals with nested se-content
// in particular, this query bundles together an arbitrary number of queries into a single message
- .send(Source, askOne, bundle( [ luxuriousHotel(H1)[o(holidays)], hotel(H2)[o(holidays)], activity(H3)[o(holidays)] ] ), Response);
+ .send(Source, askOne, bundle( [ luxuriousHotel(H1)[o(holidays)], hotel(H2)[o(holidays)], activity(H3)[o(holidays)], q2(H4)[o(self)] ] ), Response);
.print("Bundled query response: ", Response);
.send(Source, tell, example_KSAA_complete).
+
+all_different(XS)[o(holidays), source(Source)]
<-
- .print(XS, " are mutually distinct individuals, according to ", Source).
+ .print(XS, " are mutually distinct individuals, according to ", Source);
+ .send(Source, tell, building(travel_lodge)[o(places)]);
+ .wait(1000); // wait to ensure travel_agent has had a chance to add this information to its belief base
+ jasdl.ia.define_class(q3, "(places:place and places:building) and holidays:hotel");
+ .send(Source, askOne, q3(Hotel)[o(self)], q3(Hotel)[o(self)]);
+ .print(Hotel, " is a building and a hotel").
+
Modified: trunk/applications/jasdl-owlapi/examples/travel_agent/travel_agent.asl
===================================================================
--- trunk/applications/jasdl-owlapi/examples/travel_agent/travel_agent.asl 2008-03-17 08:41:44 UTC (rev 1156)
+++ trunk/applications/jasdl-owlapi/examples/travel_agent/travel_agent.asl 2008-03-17 19:13:28 UTC (rev 1157)
@@ -44,16 +44,7 @@
+museums(scienceMuseum)[o(travel)];
+hasActivity(london, scienceMuseum)[o(travel)];
+hotel(travel_lodge)[o(travel)];
-
- +building(hilton)[o(places)];
-
- ?place(Place)[o(places)];
- .print(Place);
-
- jasdl.ia.define_class(q2, "(places:place and places:building) and travel:hotel");
- ?q2(X)[o(self)];
- .print(X);
-
+
.print("Completed: Updating Belief Base 1").
Modified: trunk/applications/jasdl-owlapi/src/jasdl/architecture/IncomingPropContProcessingStrategy.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/architecture/IncomingPropContProcessingStrategy.java 2008-03-17 08:41:44 UTC (rev 1156)
+++ trunk/applications/jasdl-owlapi/src/jasdl/architecture/IncomingPropContProcessingStrategy.java 2008-03-17 19:13:28 UTC (rev 1157)
@@ -19,29 +19,152 @@
*/
package jasdl.architecture;
+import static jasdl.architecture.JasdlAgArch.ANON_ANNOTATION_FUNCTOR;
import static jasdl.architecture.JasdlAgArch.NAMED_ANNOTATION_FUNCTOR;
-import static jasdl.architecture.JasdlAgArch.ANON_ANNOTATION_FUNCTOR;
+import static jasdl.util.Common.strip;
import jasdl.asSemantics.JasdlAgent;
+import jasdl.bridge.alias.Alias;
+import jasdl.bridge.alias.AliasFactory;
import jasdl.bridge.seliteral.SELiteral;
+import jasdl.util.DuplicateMappingException;
import jasdl.util.JasdlException;
import jasdl.util.NotEnrichedException;
+import jason.asSyntax.Atom;
+import jason.asSyntax.ListTerm;
import jason.asSyntax.Literal;
+import jason.asSyntax.StringTerm;
+import jason.asSyntax.Structure;
+import jason.asSyntax.Term;
+import java.net.URI;
+import java.net.URISyntaxException;
+
public class IncomingPropContProcessingStrategy implements PropContProcessingStrategy{
- public Literal process(Literal l, JasdlAgent agent) throws JasdlException{
+ public Literal process(Literal l, JasdlAgent agent, String src) throws JasdlException{
try{
- SELiteral sl = new SELiteral(l, agent); // note, l might not (yet) be a valid se-literal (mappings may be performed below) so factory cannot be used
- // replace physical URI with ontology label if known, else instantiate and assign anonymous label
+ Literal result;
+ agent.getLogger().fine("Processing incoming "+l);
+
+ SELiteral sl = new SELiteral(l, agent);
sl.unqualifyOntologyAnnotation();
+ result = processAllDifferent(sl);
+ if(result!=null) return result;
+ result = processNamed(sl, agent);
+ if(result!=null) return result;
- return sl; // not able to modify literal functors directly
+ result = processAnon(sl, agent);
+ if(result!=null) return result;
+
}catch(NotEnrichedException e){
// do nothing
- return l;
}
+ return l;
+
}
+ private Literal processAllDifferent(SELiteral sl){
+ if(sl.getLiteral().getFunctor().equals(AliasFactory.OWL_ALL_DIFFERENT_FUNCTOR.toString())){
+ return sl.getLiteral();
+ }else{
+ return null;
+ }
+ }
+
+ private Literal processNamed(SELiteral sl, JasdlAgent agent) throws JasdlException{
+ ListTerm nameds = sl.getLiteral().getAnnots(NAMED_ANNOTATION_FUNCTOR);
+ if(nameds.size() == 1){
+ // get named annotation
+ Term _named = nameds.get(0);
+ if(!(_named instanceof Structure)){
+ throw new JasdlException("Invalid "+NAMED_ANNOTATION_FUNCTOR+" annotation: "+_named);
+ }
+ Structure named = (Structure)_named;
+ if(named.getArity() != 1){
+ throw new JasdlException("Invalid "+NAMED_ANNOTATION_FUNCTOR+" annotation arity: "+_named);
+ }
+
+ // get expression
+ Term expressionTerm = named.getTerm(0);
+ if(!(expressionTerm instanceof StringTerm)){
+ throw new JasdlException("Invalid "+NAMED_ANNOTATION_FUNCTOR+" annotation term: "+expressionTerm);
+ }
+ String expression = strip(expressionTerm.toString(), "\""); // quotes stripped
+
+
+ URI uri;
+ try {
+ uri = new URI(expression);
+ } catch (URISyntaxException e) {
+ throw new JasdlException("Invalid entity URI in "+expression);
+ }
+ Alias local = agent.getAliasManager().getLeft(agent.toEntity(uri)); // will already be present by definition
+
+ // create new (SE) Literal
+ sl.mutateFunctor(local.getFunctor().toString());
+
+
+ sl.getLiteral().delAnnot(named); // drop named, no longer needed
+ return sl.getLiteral(); // not able to modify literal functors directly
+ }else{
+ return null;
+ }
+ }
+
+ private Literal processAnon(SELiteral sl, JasdlAgent agent) throws JasdlException{
+ ListTerm anons = sl.getLiteral().getAnnots(ANON_ANNOTATION_FUNCTOR);
+ if(anons.size() == 1){
+ // Get Anon annotation
+ Term _anon = anons.get(0);
+ if(!(_anon instanceof Structure)){
+ throw new JasdlException("Invalid "+ANON_ANNOTATION_FUNCTOR+" annotation: "+_anon);
+ }
+ Structure anon = (Structure)_anon;
+ if(anon.getArity() != 2){
+ throw new JasdlException("Invalid "+ANON_ANNOTATION_FUNCTOR+" annotation arity: "+_anon);
+ }
+
+ // Get expression
+ Term expressionTerm = anon.getTerm(0);
+ if(!(expressionTerm instanceof StringTerm)){
+ throw new JasdlException("Invalid "+ANON_ANNOTATION_FUNCTOR+" annotation expression term: "+expressionTerm);
+ }
+ String expression = strip(expressionTerm.toString(), "\""); // quotes stripped
+
+ // Parse prequisite ontology URIs
+ Term prereqsTerm = anon.getTerm(1);
+ if(!(prereqsTerm instanceof ListTerm)){
+ throw new JasdlException("Invalid "+ANON_ANNOTATION_FUNCTOR+" annotation prereqs term: "+expressionTerm);
+ }
+ ListTerm prereqs = (ListTerm)prereqsTerm;
+ for(Term _prereqTerm : prereqs){
+ if(!(_prereqTerm instanceof StringTerm)){
+ throw new JasdlException("Invalid "+ANON_ANNOTATION_FUNCTOR+" prereq: "+_prereqTerm);
+ }
+ StringTerm prereqTerm = (StringTerm)_prereqTerm;
+ String prereq = strip(prereqTerm.toString(), "\""); // quotes stripped
+ agent.getOntology(prereq);
+ }
+
+ // do we already know this expression?
+ Atom functor = new Atom(sl.getLiteral().getFunctor());
+ try{
+ agent.defineClass(functor, sl.getOntologyLabel(), expression, agent.getManchesterURIDescriptionParser()); // Instantiate defined expression
+ }catch(DuplicateMappingException e){
+ // do nothing
+ }
+
+ // drop anon annotation, no longer needed
+ sl.getLiteral().delAnnot(anon);
+
+ return sl.getLiteral();
+ }else{
+ return null;
+ }
+
+ }
+
+
}
Modified: trunk/applications/jasdl-owlapi/src/jasdl/architecture/JasdlAgArch.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/architecture/JasdlAgArch.java 2008-03-17 08:41:44 UTC (rev 1156)
+++ trunk/applications/jasdl-owlapi/src/jasdl/architecture/JasdlAgArch.java 2008-03-17 19:13:28 UTC (rev 1157)
@@ -30,8 +30,8 @@
import jason.asSyntax.Term;
import jason.asSyntax.VarTerm;
-import java.util.PriorityQueue;
import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Logger;
public class JasdlAgArch extends AgArch {
@@ -48,7 +48,7 @@
super.checkMail();
// temporary set to hold processed message clones
- Queue<Message> tempMail = new PriorityQueue<Message>();
+ Queue<Message> tempMail = new ConcurrentLinkedQueue<Message>();
Queue<Message> mail = getTS().getC().getMailBox();
// mustn't affect original message object, otherwise effects are global (i.e. at infrastructure level)
@@ -67,21 +67,21 @@
mail.addAll(tempMail);
if(!mail.isEmpty()){
- getLogger().info("Pending messages: "+mail);
+ getLogger().fine("Pending messages: "+mail);
}
}
@Override
public void sendMsg(Message msg) throws Exception {
processMessage(msg, outgoingStrategy);
- getLogger().info("Sending message: "+msg);
+ getLogger().fine("Sending message: "+msg);
super.sendMsg(msg);
}
@Override
public void broadcast(Message msg) throws Exception {
processMessage(msg, outgoingStrategy);
- getLogger().finest("Broadcasting message: "+msg);
+ getLogger().fine("Broadcasting message: "+msg);
super.broadcast(msg);
}
@@ -98,28 +98,30 @@
Object propcont = msg.getPropCont();
if(propcont == null){
return;
- }
+ }
if(propcont instanceof Structure){ // only Structures require processing
- propcont = processStructure((Structure)propcont, strategy);
+ msg.setPropCont(processStructure((Structure)propcont, strategy, msg.getSender()));
}
- msg.setPropCont(propcont);
+
}
- private Structure processStructure(Structure struct, PropContProcessingStrategy strategy) throws JasdlException{
+ private Structure processStructure(Structure struct, PropContProcessingStrategy strategy, String src) throws JasdlException{
- // Process outer SE-enriched content
- if(struct instanceof Literal){ // processing strategies only apply to Literals
- Literal l = (Literal)struct;
- try{
- struct = strategy.process(l, getAgent());
- }catch(JasdlException e){
- e.printStackTrace();
- }
- }
+
// recurse down terms and lists (for "bundled" SE-enriched content)
if(struct.getArity()>0){ // if we have any terms to process!
+ // Process outer SE-enriched content
+ if(struct instanceof Literal){ // processing strategies only apply to Literals
+ Literal l = (Literal)struct;
+ try{
+ struct = strategy.process(l, getAgent(), src);
+ }catch(JasdlException e){
+ e.printStackTrace();
+ }
+ }
+
//int i=0;
//for(Term _term : struct.getTerms()){ - mustn't use in case struct is a list
if(struct.isVar()){
@@ -129,7 +131,7 @@
ListTermImpl newList = new ListTermImpl(); // a "clone"
for(Term e : ((ListTerm)struct).getAsList()){
if(e instanceof Structure){
- Structure alteredTerm = (Structure)processStructure((Structure)e, strategy);
+ Structure alteredTerm = (Structure)processStructure((Structure)e, strategy, src);
newList.append(alteredTerm);
}
}
@@ -139,7 +141,7 @@
Term _term = struct.getTerm(i);
if(_term instanceof Structure){
Structure term = (Structure)_term;
- Structure alteredTerm = (Structure)processStructure(term, strategy);
+ Structure alteredTerm = (Structure)processStructure(term, strategy, src);
struct.setTerm(i, alteredTerm); // modifies original struct
}
}
Modified: trunk/applications/jasdl-owlapi/src/jasdl/architecture/OutgoingPropContProcessingStrategy.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/architecture/OutgoingPropContProcessingStrategy.java 2008-03-17 08:41:44 UTC (rev 1156)
+++ trunk/applications/jasdl-owlapi/src/jasdl/architecture/OutgoingPropContProcessingStrategy.java 2008-03-17 19:13:28 UTC (rev 1157)
@@ -24,8 +24,10 @@
import jasdl.asSemantics.JasdlAgent;
import jasdl.bridge.alias.Alias;
import jasdl.bridge.seliteral.SELiteral;
+import jasdl.bridge.seliteral.SELiteralAllDifferentAssertion;
import jasdl.util.JasdlException;
import jasdl.util.NotEnrichedException;
+import jasdl.util.UnknownMappingException;
import jason.asSyntax.ListTerm;
import jason.asSyntax.ListTermImpl;
import jason.asSyntax.Literal;
@@ -38,6 +40,8 @@
import java.util.HashSet;
import java.util.Set;
+import org.semanticweb.owl.model.OWLNamedObject;
+import org.semanticweb.owl.model.OWLObject;
import org.semanticweb.owl.model.OWLOntology;
public class OutgoingPropContProcessingStrategy implements PropContProcessingStrategy {
@@ -51,22 +55,39 @@
* @param l
* @throws JasdlException
*/
- public Literal process(Literal l, JasdlAgent agent) throws JasdlException {
+ public Literal process(Literal l, JasdlAgent agent, String src) throws JasdlException {
+ agent.getLogger().fine("Processing outgoing "+l);
+
+ Literal result = l;
try{
- SELiteral sl = new SELiteral(l, agent);
+ SELiteral sl = agent.getSELiteralFactory().create(l);
+
+ // qualify o
+ sl.qualifyOntologyAnnotation();
- StringTerm expression = new StringTermImpl( agent.getManchesterObjectRenderer().render(sl.toOWLObject()));
+ OWLObject obj = sl.toOWLObject();
+ String expression = agent.getManchesterObjectRenderer().render(obj);
+ StringTerm expressionTerm = new StringTermImpl(expression);
+ Alias alias = sl.toAlias();
-
- Alias alias = sl.toAlias();
- if(alias.getLabel().equals(agent.getPersonalOntologyLabel())){ // do we have an anonymous run-time defined class?
+ if(obj instanceof OWLNamedObject){
+ // unambiguously refer to named entity
+ if(!(sl instanceof SELiteralAllDifferentAssertion)){// not required if all_different
+ Structure named = new Structure(NAMED_ANNOTATION_FUNCTOR);
+ named.addTerm(expressionTerm);
+ sl.getLiteral().addAnnot(named);
+ }
+
+ }else{ // we have an anonymous run-time defined class
+
+ // construct anon annotation
Structure anon = new Structure(ANON_ANNOTATION_FUNCTOR);
- anon.addTerm(expression);
+ anon.addTerm(expressionTerm);
// add set of prerequisite ontologies
Set<OWLOntology> prereqs = new HashSet<OWLOntology>();
- String[] tokens = expression.toString().split(" ");
+ String[] tokens = expression.toString().split("[ |\n]");
for(String token : tokens){
try {
URI entityURI = new URI(token);
@@ -74,36 +95,24 @@
prereqs.add(agent.getLogicalURIManager().getLeft(ontologyURI));
} catch (URISyntaxException e) {
// do nothing, probably a keyword
+ } catch(UnknownMappingException e){
+ // do nothing, probably a keyword
}
}
ListTerm list = new ListTermImpl();
for(OWLOntology prereq : prereqs){
- list.add(agent.getLabelManager().getLeft(prereq));
+ list.add( new StringTermImpl(agent.getPhysicalURIManager().getRight(prereq).toString()) );
}
anon.addTerm(list);
- l.addAnnot(anon);
-
- // drop o, not needed
- sl.dropOntologyAnnotation();
-
- }else{
- // qualify o
- sl.qualifyOntologyAnnotation();
-
- // unambiguously refer to named entity
- Structure named = new Structure(NAMED_ANNOTATION_FUNCTOR);
- named.addTerm(expression);
- sl.addAnnot(named);
- }
-
-
-
- return sl;
+ sl.getLiteral().addAnnot(anon);
+ }
+ result = sl.getLiteral();
}catch(NotEnrichedException e){
// do nothing
- return l;
}
+ return result;
}
+
}
Modified: trunk/applications/jasdl-owlapi/src/jasdl/architecture/PropContProcessingStrategy.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/architecture/PropContProcessingStrategy.java 2008-03-17 08:41:44 UTC (rev 1156)
+++ trunk/applications/jasdl-owlapi/src/jasdl/architecture/PropContProcessingStrategy.java 2008-03-17 19:13:28 UTC (rev 1157)
@@ -24,5 +24,5 @@
import jason.asSyntax.Literal;
public interface PropContProcessingStrategy {
- public Literal process(Literal propcont, JasdlAgent agent) throws JasdlException;
+ public Literal process(Literal propcont, JasdlAgent agent, String src) throws JasdlException;
}
Modified: trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java 2008-03-17 08:41:44 UTC (rev 1156)
+++ trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlAgent.java 2008-03-17 19:13:28 UTC (rev 1157)
@@ -1,5 +1,8 @@
package jasdl.asSemantics;
+import static jasdl.util.Common.strip;
+import jasdl.asSemantics.parsing.NSPrefixEntityChecker;
+import jasdl.asSemantics.parsing.URIEntityChecker;
import jasdl.asSyntax.JasdlPlanLibrary;
import jasdl.bb.JasdlBeliefBase;
import jasdl.bridge.ToAxiomConverter;
@@ -7,9 +10,13 @@
import jasdl.bridge.alias.Alias;
import jasdl.bridge.alias.AliasFactory;
import jasdl.bridge.alias.AliasManager;
+import jasdl.bridge.alias.DecapitaliseMappingStrategy;
+import jasdl.bridge.alias.MappingStrategy;
import jasdl.bridge.label.LabelManager;
import jasdl.bridge.label.OntologyURIManager;
import jasdl.bridge.seliteral.SELiteralFactory;
+import jasdl.util.DuplicateMappingException;
+import jasdl.util.InvalidSELiteralException;
import jasdl.util.JasdlException;
import jasdl.util.UnknownMappingException;
import jason.JasonException;
@@ -21,7 +28,10 @@
import java.net.URI;
import java.net.URISyntaxException;
+import java.util.Arrays;
+import java.util.List;
import java.util.Set;
+import java.util.Vector;
import jmca.asSemantics.JmcaAgent;
@@ -29,25 +39,18 @@
import org.mindswap.pellet.PelletOptions;
import org.mindswap.pellet.owlapi.Reasoner;
import org.semanticweb.owl.apibinding.OWLManager;
-import org.semanticweb.owl.expression.OWLEntityChecker;
-import org.semanticweb.owl.model.OWLClass;
-import org.semanticweb.owl.model.OWLDataProperty;
-import org.semanticweb.owl.model.OWLDataType;
import org.semanticweb.owl.model.OWLDescription;
import org.semanticweb.owl.model.OWLEntity;
-import org.semanticweb.owl.model.OWLIndividual;
-import org.semanticweb.owl.model.OWLObject;
-import org.semanticweb.owl.model.OWLObjectProperty;
import org.semanticweb.owl.model.OWLOntology;
import org.semanticweb.owl.model.OWLOntologyCreationException;
import org.semanticweb.owl.model.OWLOntologyManager;
-import org.semanticweb.owl.model.OWLRuntimeException;
import org.semanticweb.owl.util.ShortFormProvider;
-import uk.ac.manchester.cs.owl.OWLClassImpl;
import uk.ac.manchester.cs.owl.mansyntaxrenderer.ManchesterOWLSyntaxOWLObjectRendererImpl;
public class JasdlAgent extends JmcaAgent {
+ public static List<MappingStrategy> DEFAULT_MAPPING_STRATEGIES = Arrays.asList( new MappingStrategy[] { new DecapitaliseMappingStrategy()} );
+
private OWLOntologyManager ontologyManager;
private Reasoner reasoner;
private AliasManager aliasManager;
@@ -58,12 +61,26 @@
private OntologyURIManager logicalURIManager;
private OntologyURIManager physicalURIManager;
private ManchesterOWLSyntaxOWLObjectRendererImpl manchesterObjectRenderer;
- private ManchesterOWLSyntaxDescriptionParser manchesterDescriptionParser;
+ private ManchesterOWLSyntaxDescriptionParser manchesterNsPrefixDescriptionParser;
+ private ManchesterOWLSyntaxDescriptionParser manchesterURIDescriptionParser;
+
+ private List<MappingStrategy> defaultMappingStrategies;
+
+ public static String ANON_LABEL_PREFIX = "anon_label_";
+ public static String ANON_ALIAS_PREFIX = "anon_alias_";
+
+ /**
+ * Since Jason doesn't initialise an agent name in time
+ */
+ private String agentName;
+
public JasdlAgent(){
super();
+ defaultMappingStrategies = DEFAULT_MAPPING_STRATEGIES;
+
// instantiate managers
aliasManager = new AliasManager();
labelManager = new LabelManager();
@@ -84,9 +101,9 @@
}
}); // we want fully qualified entity references
- manchesterDescriptionParser = new ManchesterOWLSyntaxDescriptionParser(ontologyManager.getOWLDataFactory(), new NSPrefixEntityChecker(this));
-
-
+ manchesterNsPrefixDescriptionParser = new ManchesterOWLSyntaxDescriptionParser(ontologyManager.getOWLDataFactory(), new NSPrefixEntityChecker(this));
+ manchesterURIDescriptionParser = new ManchesterOWLSyntaxDescriptionParser(ontologyManager.getOWLDataFactory(), new URIEntityChecker(this));
+
// instantiate (Pellet) reasoner
PelletOptions.USE_TRACING = true;
reasoner = new Reasoner(ontologyManager);
@@ -102,25 +119,112 @@
public TransitionSystem initAg(AgArch arch, BeliefBase bb, String src, Settings stts) throws JasonException {
if(!(bb instanceof JasdlBeliefBase)){
throw new JasdlException("JASDL must be used in combination with the jasdl.bb.OwlBeliefBase class");
- }
-
- ((JasdlBeliefBase)bb).setAgent(this);
-
-
+ }
+ ((JasdlBeliefBase)bb).setAgent(this);
// load .mas2j JASDL configuration
JasdlConfigurator config = new JasdlConfigurator(this);
- config.configure(stts);
+ config.configure(stts);
return super.initAg(arch, bb, src, stts);
}
+
+
+
+ /**
+ * Convenience method to (polymorphically) create an entity from resource URI (if known).
+ * TODO: where should this sit?
+ * @param uri URI of resource to create entity from
+ * @return entity identified by URI
+ * @throws UnknownReferenceException if OWLObject not known
+ */
+ public OWLEntity toEntity(URI uri) throws JasdlException{
+ URI ontURI;
+ try {
+ ontURI = new URI(uri.getScheme(), uri.getSchemeSpecificPart(), null);
+ } catch (URISyntaxException e) {
+ throw new JasdlException("Invalid entity URI "+uri);
+ }
+ OWLOntology ontology = getLogicalURIManager().getLeft(ontURI);
+ // clumsy approach, but I can't find any way of achieving this polymorphically (i.e. retrieve an OWLEntity from a URI) using OWL-API
+ OWLEntity entity;
+ if(ontology.containsClassReference(uri)){
+ entity = getOntologyManager().getOWLDataFactory().getOWLClass(uri);
+ }else if (ontology.containsObjectPropertyReference(uri)){
+ entity = getOntologyManager().getOWLDataFactory().getOWLObjectProperty(uri);
+ }else if (ontology.containsDataPropertyReference(uri)){
+ entity = getOntologyManager().getOWLDataFactory().getOWLDataProperty(uri);
+ }else if (ontology.containsIndividualReference(uri)){
+ entity = getOntologyManager().getOWLDataFactory().getOWLIndividual(uri);
+ }else{
+ throw new UnknownMappingException("Unknown ontology resource URI: "+uri);
+ }
+ return entity;
+ }
+ /**
+ * Convenience method to parse a string into a URI and return the associated ontology.
+ * Ontology is instantiated and assigned a unique anonymous label if unknown.
+ * @param uri
+ * @return
+ * @throws JasdlException
+ */
+ public OWLOntology getOntology(String _uri) throws JasdlException{
+ URI uri;
+ try {
+ uri = new URI( strip(_uri, "\"")); // quotes stripped
+ } catch (URISyntaxException e) {
+ throw new InvalidSELiteralException("Invalid physical ontology URI "+_uri+". Reason: "+e);
+ }
+ return getOntology(uri);
+ }
+
+ /**
+ * Convenience method to return the ontology associated with a URI.
+ * Ontology is instantiated and assigned a unique anonymous label if unknown.
+ * @param uri
+ * @return
+ * @throws JasdlException
+ */
+ public OWLOntology getOntology(URI uri) throws JasdlException{
+ OWLOntology ontology;
+ try{
+ ontology = getPhysicalURIManager().getLeft(uri);
+ }catch(UnknownMappingException e){
+ // instantiate novel ontology
+ // create a guaranteed unique anonymous label
+ String label;
+ Atom labelAtom;
+ int i = 0;
+ while(true){
+ label = ANON_LABEL_PREFIX+i;
+ labelAtom = new Atom(label);
+ if(!getLabelManager().isKnownLeft(labelAtom)){
+ break;
+ }
+ i++;
+ }
+ ontology = loadOntology(labelAtom, uri);
+ }
+ return ontology;
+ }
+ /**
+ * Calls loadOntology with default mapping strategies.
+ * For incoming ontologies and those with unspecified mapping strategies.
+ * @param label
+ * @param uri
+ * @return
+ * @throws JasdlException
+ */
+ public OWLOntology loadOntology(Atom label, URI uri) throws JasdlException{
+ return loadOntology(label, uri, defaultMappingStrategies);
+ }
/**
- * Convenience method to instantiate an ontology, load it into reasoner and map it to a label
+ * Convenience method to instantiate an ontology, load it into reasoner and map it to a label.
* @param uri
* @throws JasdlException
*/
- public void loadOntology(Atom label, URI uri) throws JasdlException{
+ public OWLOntology loadOntology(Atom label, URI uri, List<MappingStrategy> strategies) throws JasdlException{
try{
OWLOntology ontology = ontologyManager.loadOntologyFromPhysicalURI(uri);
Set<OWLOntology> imports = ontologyManager.getImportsClosure(ontology);
@@ -129,249 +233,190 @@
labelManager.put(label, ontology);
physicalURIManager.put(ontology, uri);
logicalURIManager.put(ontology, ontology.getURI());
+ getLogger().fine("Loaded ontology from "+uri+" and assigned label "+label);
+ applyMappingStrategies(ontology, strategies);
+ return ontology;
}catch(OWLOntologyCreationException e){
- throw new JasdlException("Error loading ontology "+uri+". Reason: "+e);
- }
+ getLogger().warning("Placeholder ontology substituted for unreachable "+uri);
+ return createOntology(label, uri); // can't load it, just create a blank (for unqualification of ontology annotations for example)
+ }
}
-
- public void createOntology(Atom label, URI uri) throws JasdlException{
+ /**
+ * Creates and fully maps a blank ontology. Used for example for "owl" ontology, containing
+ * axioms referencing "owl:thing" and "owl:nothing", and for personal ontologies containing
+ * axioms referencing run-time defined anonymous classes.
+ * @param label
+ * @param uri
+ * @throws JasdlException
+ */
+ public OWLOntology createOntology(Atom label, URI uri) throws JasdlException{
try{
OWLOntology ontology = getOntologyManager().createOntology( uri );
getLabelManager().put(label, ontology);
getPhysicalURIManager().put(ontology, uri);
getLogicalURIManager().put(ontology, uri);
- getReasoner().loadOntology(ontology);
+ getReasoner().loadOntology(ontology);
+ return ontology;
} catch (OWLOntologyCreationException e) {
throw new JasdlException("Error instantiating OWL ontology. Reason: "+e);
}
}
- public Atom getPersonalOntologyLabel(){
- return new Atom("self");
+ /**
+ * When a duplicate mapping is encountered, an anonymous alias is created for the offending resource
+ * @param ontology
+ * @param strategies
+ * @throws JasdlException
+ */
+ private void applyMappingStrategies(OWLOntology ontology, List<MappingStrategy> strategies) throws JasdlException{
+ // we need to construct a reasoner specifically for this to isolate entities from just one ontology
+ Reasoner reasoner = new Reasoner(getOntologyManager());
+ Set<OWLOntology> imports = getOntologyManager().getImportsClosure(ontology);
+ reasoner.loadOntologies(imports);
+
+ List<OWLEntity> entities = new Vector<OWLEntity>();
+ entities.addAll(reasoner.getClasses());
+ entities.addAll(reasoner.getProperties());
+ entities.addAll(reasoner.getIndividuals());
+
+ Atom label = getLabelManager().getLeft(ontology);
+
+ for(OWLEntity entity : entities){
+ try{
+ String _functor = entity.getURI().getFragment();
+ for(MappingStrategy strategy : strategies){
+ _functor = strategy.apply(_functor);
+ }
+ Atom functor = new Atom(_functor);
+ getAliasManager().put(AliasFactory.INSTANCE.create(functor, label), entity);
+ }catch(DuplicateMappingException e){
+ // generate an anonymous alias for this entity
+ String functor;
+ Alias anonAlias;
+ int i = 0;
+ while(true){
+ functor = ANON_ALIAS_PREFIX + i;
+ anonAlias = AliasFactory.INSTANCE.create(new Atom(functor), label);
+ if(!getAliasManager().isKnownLeft(anonAlias)){
+ break;
+ }
+ i++;
+ }
+ getAliasManager().put(anonAlias, entity);
+ }
+ }
}
-
- public URI getPersonalOntologyURI() {
- return URI.create("http://www.dur.ac.uk/t.g.klapiscak/"+getPersonalOntologyLabel()+".owl");
- }
+ public OWLDescription defineClass(Atom functor, String expression, ManchesterOWLSyntaxDescriptionParser parser) throws JasdlException{
+ return defineClass(functor, getPersonalOntologyLabel(), expression, parser);
+ }
- public OWLDescription defineClass(Atom functor, String expression) throws JasdlException{
+ public OWLDescription defineClass(Atom functor, Atom label, String expression, ManchesterOWLSyntaxDescriptionParser parser) throws JasdlException{
+ Alias alias = AliasFactory.INSTANCE.create(functor, label);
+ if(getAliasManager().isKnownLeft(alias)){
+ throw new DuplicateMappingException("New class definition with alias "+alias+" overlaps with an existing ontological entity");
+ }
OWLDescription desc;
try{
- desc = getManchesterDescriptionParser().parse(expression);
- }catch(Exception e){
- e.printStackTrace();
+ desc = parser.parse(expression);
+ }catch(Exception e){
throw new JasdlException("Could not parse expression "+expression+". Reason: "+e);
- }
-
- Alias alias = AliasFactory.INSTANCE.create(functor, getPersonalOntologyLabel());
- getAliasManager().put(alias, desc);
-
+ }
+ getAliasManager().put(alias, desc);
+ getLogger().fine("Defined new class with alias "+alias);
return desc;
}
+
+ /**
+ * *Must* be unique within society!
+ * @return
+ */
+ public String getAgentName(){
+ return agentName;
+ }
+
+ public void setAgentName(String agentName){
+ this.agentName = agentName;
+ }
+
+
+
+ public List<MappingStrategy> getDefaultMappingStrategies() {
+ return defaultMappingStrategies;
+ }
+
+ public void setDefaultMappingStrategies(List<MappingStrategy> defaultMappingStrategies) {
+ this.defaultMappingStrategies = defaultMappingStrategies;
+ }
+
+
+
+ public Atom getPersonalOntologyLabel(){
+ return new Atom("self");
+ }
+
+ public URI getPersonalOntologyURI() {
+ return getPersonalOntologyURI(new Atom(getAgentName()));
+ }
+
+ public URI getPersonalOntologyURI(Atom label) {
+ return URI.create("http://www.dur.ac.uk/t.g.klapiscak/"+label+".owl");
+ }
+
+
public AliasManager getAliasManager() {
return aliasManager;
}
-
-
public LabelManager getLabelManager() {
return labelManager;
}
-
-
public OWLOntologyManager getOntologyManager() {
return ontologyManager;
}
-
-
-
-
public OntologyURIManager getPhysicalURIManager() {
return physicalURIManager;
- }
+ }
-
-
-
public OntologyURIManager getLogicalURIManager() {
return logicalURIManager;
}
-
-
-
+
public Reasoner getReasoner() {
return reasoner;
}
-
-
-
-
-
-
+
public SELiteralFactory getSELiteralFactory() {
return seLiteralFactory;
}
-
-
-
-
public ToAxiomConverter getToAxiomConverter() {
return toAxiomConverter;
}
-
-
-
-
public ToSELiteralConverter getToSELiteralConverter() {
return toSELiteralConverter;
}
-
-
public ManchesterOWLSyntaxOWLObjectRendererImpl getManchesterObjectRenderer() {
return manchesterObjectRenderer;
}
-
-
-
- public ManchesterOWLSyntaxDescriptionParser getManchesterDescriptionParser() {
- return manchesterDescriptionParser;
- }
-
- /**
- * Convenience method to (polymorphically) create an entity from resource URI (if known).
- * TODO: where should this sit?
- * @param uri URI of resource to create entity from
- * @return entity identified by URI
- * @throws UnknownReferenceException if OWLObject not known
- */
- public OWLEntity toEntity(URI uri) throws JasdlException{
- URI ontURI;
- try {
- ontURI = new URI(uri.getScheme(), uri.getSchemeSpecificPart(), null);
- } catch (URISyntaxException e) {
- throw new JasdlException("Invalid entity URI "+uri);
- }
- OWLOntology ontology = getLogicalURIManager().getLeft(ontURI);;
-
- // clumsy approach, but I can't find any way of achieving this polymorphically (i.e. retrieve an OWLObject from a URI) using OWL-API
- OWLEntity entity;
- if(ontology.containsClassReference(uri)){
- entity = getOntologyManager().getOWLDataFactory().getOWLClass(uri);
- }else if (ontology.containsObjectPropertyReference(uri)){
- entity = getOntologyManager().getOWLDataFactory().getOWLObjectProperty(uri);
- }else if (ontology.containsDataPropertyReference(uri)){
- entity = getOntologyManager().getOWLDataFactory().getOWLDataProperty(uri);
- }else if (ontology.containsIndividualReference(uri)){
- entity = getOntologyManager().getOWLDataFactory().getOWLIndividual(uri);
- }else{
- throw new UnknownMappingException("Unknown ontology resource URI: "+uri);
- }
- return entity;
+ public ManchesterOWLSyntaxDescriptionParser getManchesterNsPrefixDescriptionParser() {
+ return manchesterNsPrefixDescriptionParser;
}
-
-
-
- private class NSPrefixEntityChecker implements OWLEntityChecker{
-
- private JasdlAgent agent;
-
- public NSPrefixEntityChecker(JasdlAgent agent){
- this.agent = agent;
- }
-
- public OWLClass getOWLClass(String name) {
- OWLEntity entity = convert(name);
- if(entity == null){
- return null;
- }
- if(entity.isOWLClass()){
- return entity.asOWLClass();
- }else{
- return null;
- }
- }
-
- public OWLDataProperty getOWLDataProperty(String name) {
- OWLEntity entity = convert(name);
- if(entity == null){
- return null;
- }
- if(entity.isOWLDataProperty()){
- return entity.asOWLDataProperty();
- }else{
- return null;
- }
- }
-
- public OWLDataType getOWLDataType(String name) {
- OWLEntity entity = convert(name);
- if(entity == null){
- return null;
- }
- if(entity.isOWLDataType()){
- return entity.asOWLDataType();
- }else{
- return null;
- }
- }
-
- public OWLIndividual getOWLIndividual(String name) {
- OWLEntity entity = convert(name);
- if(entity == null){
- return null;
- }
- if(entity.isOWLIndividual()){
- return entity.asOWLIndividual();
- }else{
- return null;
- }
- }
-
- public OWLObjectProperty getOWLObjectProperty(String name) {
- OWLEntity entity = convert(name);
- if(entity == null){
- return null;
- }
- if(entity.isOWLObjectProperty()){
- return entity.asOWLObjectProperty();
- }else{
- return null;
- }
- }
-
- private OWLEntity convert(String name){
- String[] tokens = name.split(":");
- try {
- Atom functor = new Atom(tokens[1]);
- Atom label = new Atom(tokens[0]);
- Alias alias = AliasFactory.INSTANCE.create(functor, label);
- return (OWLEntity)agent.getAliasManager().getRight(alias); // guaranteed to be an entity? Not for anonymous classes!
- } catch (Exception e) {
- return null;
- }
- }
-
-
+ public ManchesterOWLSyntaxDescriptionParser getManchesterURIDescriptionParser() {
+ return manchesterURIDescriptionParser;
}
-
-
-
-
-
}
Modified: trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlConfigurator.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlConfigurator.java 2008-03-17 08:41:44 UTC (rev 1156)
+++ trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/JasdlConfigurator.java 2008-03-17 19:13:28 UTC (rev 1157)
@@ -6,32 +6,30 @@
import jasdl.bridge.alias.Alias;
import jasdl.bridge.alias.AliasFactory;
import jasdl.bridge.alias.MappingStrategy;
-import jasdl.util.DuplicateMappingException;
import jasdl.util.JasdlException;
-import jasdl.util.UnknownMappingException;
import jason.asSyntax.Atom;
import jason.runtime.Settings;
import java.lang.reflect.Constructor;
import java.net.URI;
-import java.net.URISyntaxException;
+import java.util.Arrays;
import java.util.List;
-import java.util.Set;
import java.util.Vector;
-import org.mindswap.pellet.owlapi.Reasoner;
import org.semanticweb.owl.model.OWLEntity;
import org.semanticweb.owl.model.OWLOntology;
-import org.semanticweb.owl.model.OWLOntologyCreationException;
public class JasdlConfigurator {
private static String MAS2J_PREFIX = "jasdl";
private static String MAS2J_ONTOLOGIES = "_ontologies";
private static String MAS2J_URI = "_uri";
private static String MAS2J_MAPPING_STRATEGIES = "_mapping_strategies";
- private static String MAS2J_MAPPING_MANUAL = "_mapping_manual";
+ private static String MAS2J_MAPPING_MANUAL = "_mapping_manual";
+ private static String MAS2J_AGENT_NAME = "_agent_name";
+ public static List<Atom> reservedOntologyLabels = Arrays.asList( new Atom[] {new Atom("default"), new Atom("self")});
+
private JasdlAgent agent;
public JasdlConfigurator(JasdlAgent agent){
@@ -40,11 +38,17 @@
public void configure(Settings stts) throws JasdlException{
try{
+ // load agent name
+ agent.setAgentName(prepareUserParameter( stts, MAS2J_PREFIX + MAS2J_AGENT_NAME ));
+
+ // load default mapping strategies
+ agent.setDefaultMappingStrategies(getMappingStrategies(stts, new Atom("default"))); //implication "default" is a reserved ontology label
+
loadOntologies(stts);
applyManualMappings(stts);
- applyMiscMappings();
- applyMappingStrategies(stts);
+ applyMiscMappings();
+
}catch(JasdlException e){
throw new JasdlException("JASDL agent encountered error during configuration. Reason: "+e);
}
@@ -58,16 +62,24 @@
private void loadOntologies(Settings stts) throws JasdlException{
String[] labels = splitUserParameter( stts, MAS2J_PREFIX + MAS2J_ONTOLOGIES );
for(String label : labels){
+ if(reservedOntologyLabels.contains(label)){
+ throw new JasdlException(label+" is a reserved ontology label");
+ }
URI physicalURI;
try {
physicalURI = new URI(prepareUserParameter( stts, MAS2J_PREFIX + "_" + label + MAS2J_URI ));
- agent.loadOntology(new Atom(label), physicalURI);
+ agent.loadOntology(new Atom(label), physicalURI, getMappingStrategies(stts, new Atom(label)));
} catch (Exception e) {
throw new JasdlException("Unable to instantiate ontology \""+label+"\". Reason: "+e);
}
}
}
+ /**
+ * Overrides auto mappings!
+ * @param stts
+ * @throws JasdlException
+ */
private void applyManualMappings(Settings stts) throws JasdlException{
for(Atom label : agent.getLabelManager().getLefts()){
String[] mappings = splitUserParameter(stts, MAS2J_PREFIX + "_" + label + MAS2J_MAPPING_MANUAL);
@@ -78,6 +90,11 @@
Alias alias = AliasFactory.INSTANCE.create(new Atom(split[0].trim()), label);
URI uri = URI.create(ontology.getURI() + "#" + split[1].trim());
OWLEntity entity = agent.toEntity(uri);
+
+ if(agent.getAliasManager().isKnownRight(entity)){ // manual mappings override automatic ones
+ agent.getAliasManager().removeByRight(entity);
+ }
+
agent.getAliasManager().put(alias, entity);
}
}
@@ -92,53 +109,29 @@
* Applies mappings to all resources in an ontology according to composition of supplied strategies.
* @param stts .mas2j settings
*/
- private void applyMappingStrategies(Settings stts) throws JasdlException{
- for(Atom label : agent.getLabelManager().getLefts()){
- List<MappingStrategy> strategies = new Vector<MappingStrategy>();
- String[] strategyNames = splitUserParameter(stts, MAS2J_PREFIX + "_" + label + MAS2J_MAPPING_STRATEGIES);
- for(String strategyName : strategyNames){
- if(strategyName.length() > 0){
- try {
- Class cls = Class.forName(strategyName);
- Constructor ct = cls.getConstructor(new Class[] {});
- MappingStrategy strategy = (MappingStrategy)ct.newInstance(new Object[] {});
- if(strategy == null){
- throw new JasdlException("Unknown mapping strategy class: "+strategy);
- }else{
- strategies.add(strategy);
- }
- }catch (Throwable e) {
- throw new JasdlException("Error instantiating mapping strategy "+strategyName+". Reason: "+e);
+ private List<MappingStrategy> getMappingStrategies(Settings stts, Atom label) throws JasdlException{
+ List<MappingStrategy> strategies = new Vector<MappingStrategy>();
+ String[] strategyNames = splitUserParameter(stts, MAS2J_PREFIX + "_" + label + MAS2J_MAPPING_STRATEGIES);
+ for(String strategyName : strategyNames){
+ if(strategyName.length() > 0){
+ try {
+ Class cls = Class.forName(strategyName);
+ Constructor ct = cls.getConstructor(new Class[] {});
+ MappingStrategy strategy = (MappingStrategy)ct.newInstance(new Object[] {});
+ if(strategy == null){
+ throw new JasdlException("Unknown mapping strategy class: "+strategy);
+ }else{
+ strategies.add(strategy);
}
+ }catch (Throwable e) {
+ throw new JasdlException("Error instantiating mapping strategy "+strategyName+". Reason: "+e);
}
}
-
- OWLOntology ontology = agent.getLabelManager().getRight(label);
-
- // we need to construct a reasoner specifically for this to isolate entities from just one ontology
- Reasoner reasoner = new Reasoner(agent.getOntologyManager());
- Set<OWLOntology> imports = agent.getOntologyManager().getImportsClosure(ontology);
- reasoner.loadOntologies(imports);
-
- List<OWLEntity> entities = new Vector<OWLEntity>();
- entities.addAll(reasoner.getClasses());
- entities.addAll(reasoner.getProperties());
- entities.addAll(reasoner.getIndividuals());
-
- for(OWLEntity entity : entities){
- try{
- String _functor = entity.getURI().getFragment();
- for(MappingStrategy strategy : strategies){
- _functor = strategy.apply(_functor);
- }
- Atom functor = new Atom(_functor);
- agent.getAliasManager().put(AliasFactory.INSTANCE.create(functor, label), entity);
- }catch(DuplicateMappingException e){
- // only apply mapping strategies to entities that have not been manually mapped already
- }
- }
-
- }
+ }
+ if(strategies.size() == 0){
+ strategies = agent.getDefaultMappingStrategies();
+ }
+ return strategies;
}
/**
Added: trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/parsing/NSPrefixEntityChecker.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/parsing/NSPrefixEntityChecker.java (rev 0)
+++ trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/parsing/NSPrefixEntityChecker.java 2008-03-17 19:13:28 UTC (rev 1157)
@@ -0,0 +1,103 @@
+package jasdl.asSemantics.parsing;
+import jasdl.asSemantics.JasdlAgent;
+import jasdl.bridge.alias.Alias;
+import jasdl.bridge.alias.AliasFactory;
+import jason.asSyntax.Atom;
+
+import org.semanticweb.owl.expression.OWLEntityChecker;
+import org.semanticweb.owl.model.OWLClass;
+import org.semanticweb.owl.model.OWLDataProperty;
+import org.semanticweb.owl.model.OWLDataType;
+import org.semanticweb.owl.model.OWLEntity;
+import org.semanticweb.owl.model.OWLIndividual;
+import org.semanticweb.owl.model.OWLObjectProperty;
+
+/**
+ * For parsing class-expressions defined with entities in the alias label:functor format.
+ * E.g. "(travel:hotel and travel:hasActivity some travel:museums) and owl:thing"
+ * @author Tom Klapiscak
+ *
+ */
+public class NSPrefixEntityChecker implements OWLEntityChecker{
+
+ private JasdlAgent agent;
+
+ public NSPrefixEntityChecker(JasdlAgent agent){
+ this.agent = agent;
+ }
+
+ public OWLClass getOWLClass(String name) {
+ OWLEntity entity = convert(name);
+ if(entity == null){
+ return null;
+ }
+ if(entity.isOWLClass()){
+ return entity.asOWLClass();
+ }else{
+ return null;
+ }
+ }
+
+ public OWLDataProperty getOWLDataProperty(String name) {
+ OWLEntity entity = convert(name);
+ if(entity == null){
+ return null;
+ }
+ if(entity.isOWLDataProperty()){
+ return entity.asOWLDataProperty();
+ }else{
+ return null;
+ }
+ }
+
+ public OWLDataType getOWLDataType(String name) {
+ OWLEntity entity = convert(name);
+ if(entity == null){
+ return null;
+ }
+ if(entity.isOWLDataType()){
+ return entity.asOWLDataType();
+ }else{
+ return null;
+ }
+ }
+
+ public OWLIndividual getOWLIndividual(String name) {
+ OWLEntity entity = convert(name);
+ if(entity == null){
+ // TODO: instantiate individuals?
+ return null;
+ }
+ if(entity.isOWLIndividual()){
+ return entity.asOWLIndividual();
+ }else{
+ return null;
+ }
+ }
+
+ public OWLObjectProperty getOWLObjectProperty(String name) {
+ OWLEntity entity = convert(name);
+ if(entity == null){
+ return null;
+ }
+ if(entity.isOWLObjectProperty()){
+ return entity.asOWLObjectProperty();
+ }else{
+ return null;
+ }
+ }
+
+ private OWLEntity convert(String name){
+ String[] tokens = name.split(":");
+ try {
+ Atom functor = new Atom(tokens[1]);
+ Atom label = new Atom(tokens[0]);
+ Alias alias = AliasFactory.INSTANCE.create(functor, label);
+ return (OWLEntity)agent.getAliasManager().getRight(alias); // guaranteed to be an entity? Not for anonymous classes!
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+
+ }
\ No newline at end of file
Added: trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/parsing/URIEntityChecker.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/parsing/URIEntityChecker.java (rev 0)
+++ trunk/applications/jasdl-owlapi/src/jasdl/asSemantics/parsing/URIEntityChecker.java 2008-03-17 19:13:28 UTC (rev 1157)
@@ -0,0 +1,99 @@
+package jasdl.asSemantics.parsing;
+
+import jasdl.asSemantics.JasdlAgent;
+
+import java.net.URI;
+
+import org.semanticweb.owl.expression.OWLEntityChecker;
+import org.semanticweb.owl.model.OWLClass;
+import org.semanticweb.owl.model.OWLDataProperty;
+import org.semanticweb.owl.model.OWLDataType;
+import org.semanticweb.owl.model.OWLEntity;
+import org.semanticweb.owl.model.OWLIndividual;
+import org.semanticweb.owl.model.OWLObjectProperty;
+
+/**
+ * For parsing class-expressions where entities are defined by their fully-qualified URIs.
+ * E.g. "http://www.dur.ac.uk.t.g.klapiscak/travel.owl#Hotel and http://www.dur.ac.uk.t.g.klapiscak/travel.owl#Accommodation".
+ * @author tom
+ *
+ */
+public class URIEntityChecker implements OWLEntityChecker{
+
+ private JasdlAgent agent;
+
+ public URIEntityChecker(JasdlAgent agent){
+ this.agent = agent;
+ }
+
+ public OWLClass getOWLClass(String uri) {
+ OWLEntity entity = convert(uri);
+ if(entity == null){
+ return null;
+ }
+ if(entity.isOWLClass()){
+ return entity.asOWLClass();
+ }else{
+ return null;
+ }
+ }
+
+ public OWLDataProperty getOWLDataProperty(String uri) {
+ OWLEntity entity = convert(uri);
+ if(entity == null){
+ return null;
+ }
+ if(entity.isOWLDataProperty()){
+ return entity.asOWLDataProperty();
+ }else{
+ return null;
+ }
+ }
+
+ public OWLDataType getOWLDataType(String uri) {
+ OWLEntity entity = convert(uri);
+ if(entity == null){
+ return null;
+ }
+ if(entity.isOWLDataType()){
+ return entity.asOWLDataType();
+ }else{
+ return null;
+ }
+ }
+
+ public OWLIndividual getOWLIndividual(String uri) {
+ OWLEntity entity = convert(uri);
+ if(entity == null){
+ return null;
+ }
+ if(entity.isOWLIndividual()){
+ return entity.asOWLIndividual();
+ }else{
+ return null;
+ }
+ }
+
+ public OWLObjectProperty getOWLObjectProperty(String uri) {
+ OWLEntity entity = convert(uri);
+ if(entity == null){
+ return null;
+ }
+ if(entity.isOWLObjectProperty()){
+ return entity.asOWLObjectProperty();
+ }else{
+ return null;
+ }
+ }
+
+ private OWLEntity convert(String _uri){
+ try {
+ URI uri = new URI(_uri);
+ return agent.toEntity(uri);
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+
+}
\ No newline at end of file
Modified: trunk/applications/jasdl-owlapi/src/jasdl/asSyntax/JasdlPlanLibrary.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/asSyntax/JasdlPlanLibrary.java 2008-03-17 08:41:44 UTC (rev 1156)
+++ trunk/applications/jasdl-owlapi/src/jasdl/asSyntax/JasdlPlanLibrary.java 2008-03-17 19:13:28 UTC (rev 1157)
@@ -21,7 +21,6 @@
import static jasdl.util.Common.getTEOp;
import jasdl.asSemantics.JasdlAgent;
-import jasdl.bridge.alias.Alias;
import jasdl.bridge.seliteral.SELiteral;
import jasdl.util.JasdlException;
import jasdl.util.NotEnrichedException;
@@ -58,6 +57,7 @@
}catch(NotEnrichedException e){
super.add(p);
}catch(Exception e){
+ e.printStackTrace();
throw new JasdlException("Exception caught while initialising JasdlPlanLibrary: "+e);
}
}
@@ -136,8 +136,8 @@
Collections.reverse(functors);
for(String functor : functors){
- Literal imaginaryLiteral = mutateLiteral(l, functor);
- Trigger imaginaryTrigger = new Trigger(getTEOp(te), te.getType(), imaginaryLiteral);
+ sl.mutateFunctor(functor);
+ Trigger imaginaryTrigger = new Trigger(getTEOp(te), te.getType(), sl.getLiteral());
moreGeneral.add(imaginaryTrigger);
}
return moreGeneral;
@@ -163,17 +163,6 @@
return os;
}
- /**
- * Creates a new literal identical except functor is replaced by new functor
- * @param original the original literal
- * @param newFunctor functor to replace the original functor with
- * @return
- */
- private static Literal mutateLiteral(Literal original, String newFunctor){
- Literal mutated = new Literal(newFunctor); // negation dealt with by ~ prefix
- mutated.addTerms(original.getTerms());
- mutated.addAnnots(original.getAnnots());
- return mutated;
- }
+
}
Modified: trunk/applications/jasdl-owlapi/src/jasdl/bb/JasdlBeliefBase.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/bb/JasdlBeliefBase.java 2008-03-17 08:41:44 UTC (rev 1156)
+++ trunk/applications/jasdl-owlapi/src/jasdl/bb/JasdlBeliefBase.java 2008-03-17 19:13:28 UTC (rev 1157)
@@ -24,13 +24,14 @@
private JasdlAgent agent;
@Override
- public boolean add(Literal l) {
+ public boolean add(Literal l) {
getLogger().fine("Adding "+l);
try{
SELiteral sl = agent.getSELiteralFactory().create(l);
+ getLogger().fine("... "+sl);
OWLOntology ontology = sl.getOntology();
OWLIndividualAxiom axiom = sl.createAxiom();
- getLogger().fine("... as axiom: "+axiom);
+ getLogger().fine("..... as axiom: "+axiom);
AddAxiom add = new AddAxiom(ontology, axiom);
agent.getOntologyManager().applyChange(add);
agent.getReasoner().refresh();
@@ -43,7 +44,8 @@
}
return true;
- }catch(NotEnrichedException e){
+ }catch(NotEnrichedException e){
+ getLogger().fine("... semantically-naive");
return super.add(l); // semantically-naive, use standard Jason mechanisms
}catch(Exception e){
getLogger().warning("Exception caught adding SELiteral "+l+" to belief base: ");
@@ -112,11 +114,11 @@
Set<OWLIndividual> is = diff.getOWLIndividuals();
Set<OWLIndividual> js = ((OWLDifferentIndividualsAxiom)axiom).getIndividuals();
if(is.containsAll(js)){
- found.setTerm(0, l.getTerm(0)); // Sets are equivalent, change to original ordering
+ found.getLiteral().setTerm(0, l.getTerm(0)); // Sets are equivalent, change to original ordering
}
}
- relevant.add(found);
+ relevant.add(found.getLiteral());
}
getLogger().fine("... found: "+relevant);
}catch(NotEnrichedException e){
Modified: trunk/applications/jasdl-owlapi/src/jasdl/bridge/MappingManager.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/bridge/MappingManager.java 2008-03-17 08:41:44 UTC (rev 1156)
+++ trunk/applications/jasdl-owlapi/src/jasdl/bridge/MappingManager.java 2008-03-17 19:13:28 UTC (rev 1157)
@@ -94,4 +94,14 @@
public Set<Y> getRights(){
return yToXMap.keySet();
}
+
+ public void removeByLeft(X x){
+ Y y = xToYMap.remove(x);
+ yToXMap.remove(y);
+ }
+
+ public void removeByRight(Y y){
+ X x = yToXMap.remove(y);
+ xToYMap.remove(x);
+ }
}
Modified: trunk/applications/jasdl-owlapi/src/jasdl/bridge/ToAxiomConverter.java
===================================================================
--- trunk/applications/jasdl-owlapi/src/jasdl/bridge/ToAxiomConverter.java 2008-03-17 08:41:44 UTC (rev 1156)
+++ trunk/applications/jasdl-owlapi/src/jasdl/bridge/ToAxiomConverter.java 2008-03-17 19:13:28 UTC (rev 1157)
@@ -91,7 +91,7 @@
* @throws JasdlException
*/
public OWLIndividualAxiom create(SELiteral sl) throws JasdlException{
- if(!sl.isGround()){
+ if(!sl.getLiteral().isGround()){
throw new JasdlException("Cannot create an axiom from unground SELiteral "+sl);
}
Set<OWLIndividualAxiom> axioms = convert(sl, false);
@@ -133,7 +133,7 @@
Set<OWLIndividual> is = new HashSet<OWLIndividual>();
OWLDescription desc = sl.getOWLDescription();
- if(sl.isGround()){
+ if(sl.getLiteral().isGround()){
OWLIndividual i = sl.getOWLIndividual();
if(!checkForExistence || agent.getReasoner().hasType(i, desc)){
is.add(i);
@@ -196,7 +196,7 @@
Set<OWLIndividual> os = new HashSet<OWLIndividual>();
OWLIndividual s = sl.getSu...
[truncated message content] |