From 3ac9b0fcb29c6f76dbe034275a893b6330e9323d Mon Sep 17 00:00:00 2001 From: Donato Meoli Date: Wed, 2 Dec 2026 02:45:52 +0100 Subject: [PATCH 1/4] Parse the whole input of the FOL parser, or raise on what is left after the sentence The connectives at the top level read as if the input were parenthesized, so King(John) AND Evil(Richard) is no longer read as King(John); the tests whose inputs had a stray closing parenthesis are corrected. --- .../core/logic/fol/parsing/FOLParser.java | 32 ++++++++++++++++--- .../core/unit/logic/fol/SubstVisitorTest.java | 22 ++++++------- .../unit/logic/fol/parsing/FOLParserTest.java | 24 +++++++++++++- 3 files changed, 61 insertions(+), 17 deletions(-) diff --git a/aima-core/src/main/java/aima/core/logic/fol/parsing/FOLParser.java b/aima-core/src/main/java/aima/core/logic/fol/parsing/FOLParser.java index 0abf363ed..1da442f05 100644 --- a/aima-core/src/main/java/aima/core/logic/fol/parsing/FOLParser.java +++ b/aima-core/src/main/java/aima/core/logic/fol/parsing/FOLParser.java @@ -42,9 +42,26 @@ public FOLDomain getFOLDomain() { return lexer.getFOLDomain(); } + /** + * Parses the whole input as one sentence. The binary connectives at the + * top level are read as if the input were enclosed in parentheses, i.e., + * from left to right without precedence, so that + * King(John) AND Evil(Richard) reads as + * (King(John) AND Evil(Richard)); any other token left after + * the sentence is a syntax error, instead of being silently dropped. + * + * @param s + * the input to parse. + * @return the sentence of the input. + */ public Sentence parse(String s) { setUpToParse(s); - return parseSentence(); + Sentence sentence = parseConnectives(parseSentence()); + if (!isEndOfInput(lookAhead(1))) { + throw new RuntimeException("Syntax error: unexpected " + lookAhead(1).getText() + + " after the sentence " + sentence); + } + return sentence; } public void setUpToParse(String s) { @@ -222,16 +239,21 @@ private Sentence parseQuantifiedSentence() { private Sentence parseParanthizedSentence() { match("("); - Sentence sen = parseSentence(); + Sentence sen = parseConnectives(parseSentence()); + match(")"); + return sen; /* new ParanthizedSentence */ + + } + + // the binary connectives that follow a sentence, from left to right + private Sentence parseConnectives(Sentence sen) { while (binaryConnector(lookAhead(1))) { String connector = lookAhead(1).getText(); consume(); Sentence other = parseSentence(); sen = new ConnectedSentence(connector, sen, other); } - match(")"); - return sen; /* new ParanthizedSentence */ - + return sen; } private boolean binaryConnector(Token t) { diff --git a/aima-core/src/test/java/aima/test/core/unit/logic/fol/SubstVisitorTest.java b/aima-core/src/test/java/aima/test/core/unit/logic/fol/SubstVisitorTest.java index 7a0fd3bd5..04f22693a 100644 --- a/aima-core/src/test/java/aima/test/core/unit/logic/fol/SubstVisitorTest.java +++ b/aima-core/src/test/java/aima/test/core/unit/logic/fol/SubstVisitorTest.java @@ -105,7 +105,7 @@ public void testSubstSingleVariableSucceedsWithTermEquality() { @Test public void testSubstSingleVariableSucceedsWithTermEquality2() { - Sentence beforeSubst = parser.parse("BrotherOf(John) = x)"); + Sentence beforeSubst = parser.parse("BrotherOf(John) = x"); Sentence expectedAfterSubst = parser.parse("BrotherOf(John) = Richard"); Map p = new LinkedHashMap(); @@ -114,12 +114,12 @@ public void testSubstSingleVariableSucceedsWithTermEquality2() { Sentence afterSubst = sv.subst(p, beforeSubst); Assert.assertEquals(expectedAfterSubst, afterSubst); - Assert.assertEquals(parser.parse("BrotherOf(John) = x)"), beforeSubst); + Assert.assertEquals(parser.parse("BrotherOf(John) = x"), beforeSubst); } @Test public void testSubstWithUniversalQuantifierAndSngleVariable() { - Sentence beforeSubst = parser.parse("FORALL x King(x))"); + Sentence beforeSubst = parser.parse("FORALL x King(x)"); Sentence expectedAfterSubst = parser.parse("King(John)"); Map p = new LinkedHashMap(); @@ -127,12 +127,12 @@ public void testSubstWithUniversalQuantifierAndSngleVariable() { Sentence afterSubst = sv.subst(p, beforeSubst); Assert.assertEquals(expectedAfterSubst, afterSubst); - Assert.assertEquals(parser.parse("FORALL x King(x))"), beforeSubst); + Assert.assertEquals(parser.parse("FORALL x King(x)"), beforeSubst); } @Test public void testSubstWithUniversalQuantifierAndZeroVariablesMatched() { - Sentence beforeSubst = parser.parse("FORALL x King(x))"); + Sentence beforeSubst = parser.parse("FORALL x King(x)"); Sentence expectedAfterSubst = parser.parse("FORALL x King(x)"); Map p = new LinkedHashMap(); @@ -140,12 +140,12 @@ public void testSubstWithUniversalQuantifierAndZeroVariablesMatched() { Sentence afterSubst = sv.subst(p, beforeSubst); Assert.assertEquals(expectedAfterSubst, afterSubst); - Assert.assertEquals(parser.parse("FORALL x King(x))"), beforeSubst); + Assert.assertEquals(parser.parse("FORALL x King(x)"), beforeSubst); } @Test public void testSubstWithUniversalQuantifierAndOneOfTwoVariablesMatched() { - Sentence beforeSubst = parser.parse("FORALL x,y King(x,y))"); + Sentence beforeSubst = parser.parse("FORALL x,y King(x,y)"); Sentence expectedAfterSubst = parser.parse("FORALL x King(x,John)"); Map p = new LinkedHashMap(); @@ -153,12 +153,12 @@ public void testSubstWithUniversalQuantifierAndOneOfTwoVariablesMatched() { Sentence afterSubst = sv.subst(p, beforeSubst); Assert.assertEquals(expectedAfterSubst, afterSubst); - Assert.assertEquals(parser.parse("FORALL x,y King(x,y))"), beforeSubst); + Assert.assertEquals(parser.parse("FORALL x,y King(x,y)"), beforeSubst); } @Test public void testSubstWithExistentialQuantifierAndSngleVariable() { - Sentence beforeSubst = parser.parse("EXISTS x King(x))"); + Sentence beforeSubst = parser.parse("EXISTS x King(x)"); Sentence expectedAfterSubst = parser.parse("King(John)"); Map p = new LinkedHashMap(); @@ -172,7 +172,7 @@ public void testSubstWithExistentialQuantifierAndSngleVariable() { @Test public void testSubstWithNOTSentenceAndSngleVariable() { - Sentence beforeSubst = parser.parse("NOT King(x))"); + Sentence beforeSubst = parser.parse("NOT King(x)"); Sentence expectedAfterSubst = parser.parse("NOT King(John)"); Map p = new LinkedHashMap(); @@ -180,7 +180,7 @@ public void testSubstWithNOTSentenceAndSngleVariable() { Sentence afterSubst = sv.subst(p, beforeSubst); Assert.assertEquals(expectedAfterSubst, afterSubst); - Assert.assertEquals(parser.parse("NOT King(x))"), beforeSubst); + Assert.assertEquals(parser.parse("NOT King(x)"), beforeSubst); } @Test diff --git a/aima-core/src/test/java/aima/test/core/unit/logic/fol/parsing/FOLParserTest.java b/aima-core/src/test/java/aima/test/core/unit/logic/fol/parsing/FOLParserTest.java index ab556747b..30ae11764 100644 --- a/aima-core/src/test/java/aima/test/core/unit/logic/fol/parsing/FOLParserTest.java +++ b/aima-core/src/test/java/aima/test/core/unit/logic/fol/parsing/FOLParserTest.java @@ -106,7 +106,7 @@ public void testTermEquality() { public void testTermEquality2() { try { TermEquality te = (TermEquality) parser - .parse("BrotherOf(John) = x)"); + .parse("BrotherOf(John) = x"); Assert.assertEquals(te, new TermEquality( getBrotherOfFunction(new Constant("John")), new Variable( "x"))); @@ -226,6 +226,28 @@ public void testConnectedImplication() { parser.parse("((Missile(m) AND Owns(Nono,m)) => Sells(West , m ,Nono))"); } + @Test + public void testParseReadsTheWholeInput() { + // the connectives at the top level read as if the input were + // enclosed in parentheses + Sentence s = parser.parse("King(John) AND King(Richard)"); + Assert.assertEquals(parser.parse("(King(John) AND King(Richard))"), s); + Assert.assertEquals(parser.parse("((King(John) AND King(Richard)) OR King(Saladin))"), + parser.parse("King(John) AND King(Richard) OR King(Saladin)")); + Assert.assertEquals(parser.parse("(NOT King(John) => King(Richard))"), + parser.parse("NOT King(John) => King(Richard)")); + } + + @Test(expected = RuntimeException.class) + public void testParseRejectsATokenAfterTheSentence() { + parser.parse("King(John) King(Richard)"); + } + + @Test(expected = RuntimeException.class) + public void testParseRejectsAClosingParenthesisAfterTheSentence() { + parser.parse("King(John))"); + } + // // PRIVATE METHODS // From 006409ceefbedccb941e2ca0938d986ad5b8a720 Mon Sep 17 00:00:00 2001 From: Donato Meoli Date: Wed, 2 Dec 2026 02:45:52 +0100 Subject: [PATCH 2/4] Tell a failed PLAN-ROUTE from an empty route in the hybrid wumpus agents planRoute, planRouteToRooms and planShot return an Optional, empty when no goal can be reached; PLAN-SHOT no longer appends a shot to a missing route. --- .../EfficientHybridWumpusAgent.java | 21 +++++----- .../wumpusworld/HybridWumpusAgent.java | 40 +++++++++++-------- .../wumpusworld/HybridWumpusAgentTest.java | 33 ++++++++++----- 3 files changed, 58 insertions(+), 36 deletions(-) diff --git a/aima-core/src/main/java/aima/core/environment/wumpusworld/EfficientHybridWumpusAgent.java b/aima-core/src/main/java/aima/core/environment/wumpusworld/EfficientHybridWumpusAgent.java index 6f3da8351..345d98148 100644 --- a/aima-core/src/main/java/aima/core/environment/wumpusworld/EfficientHybridWumpusAgent.java +++ b/aima-core/src/main/java/aima/core/environment/wumpusworld/EfficientHybridWumpusAgent.java @@ -126,7 +126,7 @@ public Optional act(WumpusPercept percept) { Set goals = new LinkedHashSet<>(); goals.add(modelCave.getStart().getRoom()); plan.add(WumpusAction.GRAB); - plan.addAll(planRouteToRooms(goals, safe)); + plan.addAll(planRouteToRooms(goals, safe).orElse(Collections.emptyList())); plan.add(WumpusAction.CLIMB); } @@ -136,7 +136,7 @@ public Optional act(WumpusPercept percept) { // Optimization: Agent remembers visited locations, no need to ask. unvisited = SetOps.difference(modelCave.getAllRooms(), visitedRooms); // plan <- PLAN-ROUTE(current, unvisited ∩ safe, safe) - plan.addAll(planRouteToRooms(unvisited, safe)); + plan.addAll(planRouteToRooms(unvisited, safe).orElse(Collections.emptyList())); } // if plan is empty and ASK(KB, HaveArrowt) = true then @@ -145,7 +145,7 @@ public Optional act(WumpusPercept percept) { Set possibleWumpus = getKB().askPossibleWumpusRooms(t); notifyViews("Ask possible Wumpus positions -> " + possibleWumpus); // plan <- PLAN-SHOT(current, possible_wumpus, safe) - plan.addAll(planShot(possibleWumpus, safe)); + planShot(possibleWumpus, safe).ifPresent(plan::addAll); } // if plan is empty then //no choice but to take a risk @@ -156,7 +156,7 @@ public Optional act(WumpusPercept percept) { notifyViews("Ask not unsafe -> " + notUnsafe); // plan <- PLAN-ROUTE(current, unvisited ∩ not_unsafe, safe) // Correction: Last argument must be not_unsafe! - plan.addAll(planRouteToRooms(unvisited, notUnsafe)); + plan.addAll(planRouteToRooms(unvisited, notUnsafe).orElse(Collections.emptyList())); } // if plan is empty then @@ -165,7 +165,7 @@ public Optional act(WumpusPercept percept) { // plan PLAN-ROUTE(current, {[1,1]}, safe) + [Climb] Set goal = new LinkedHashSet<>(); goal.add(modelCave.getStart().getRoom()); - plan.addAll(planRouteToRooms(goal, safe)); + plan.addAll(planRouteToRooms(goal, safe).orElse(Collections.emptyList())); plan.add(WumpusAction.CLIMB); } // action <- POP(plan) @@ -189,18 +189,19 @@ public Optional act(WumpusPercept percept) { * a set of squares that can form part of the route * * @return the best sequence of actions that the agent have to do to reach a - * goal from the current position. + * goal from the current position, empty if the agent is already in + * a goal position, or no value if no goal can be reached through + * the allowed squares (the failure of PLAN-ROUTE). */ - public List planRoute(Set goals, Set allowed) { + @Override + public Optional> planRoute(Set goals, Set allowed) { modelCave.setAllowed(allowed); Problem problem = new GeneralProblem<>(currentPosition, WumpusFunctions.createActionsFunction(modelCave), WumpusFunctions.createResultFunction(modelCave), goals::contains); SearchForActions search = new AStarSearch<>(new GraphSearch<>(), WumpusFunctions.createManhattanDistanceFunction(goals)); - Optional> actions = search.findActions(problem); - - return actions.orElse(Collections.emptyList()); + return search.findActions(problem); } /** diff --git a/aima-core/src/main/java/aima/core/environment/wumpusworld/HybridWumpusAgent.java b/aima-core/src/main/java/aima/core/environment/wumpusworld/HybridWumpusAgent.java index 8453a3890..057b4f19f 100644 --- a/aima-core/src/main/java/aima/core/environment/wumpusworld/HybridWumpusAgent.java +++ b/aima-core/src/main/java/aima/core/environment/wumpusworld/HybridWumpusAgent.java @@ -143,7 +143,7 @@ public Optional act(WumpusPercept percept) { Set goals = new LinkedHashSet<>(); goals.add(start.getRoom()); plan.add(WumpusAction.GRAB); - plan.addAll(planRouteToRooms(goals, safe)); + plan.addAll(planRouteToRooms(goals, safe).orElse(Collections.emptyList())); plan.add(WumpusAction.CLIMB); } @@ -153,7 +153,7 @@ public Optional act(WumpusPercept percept) { unvisited = kb.askUnvisitedRooms(t); notifyViews("Ask unvisited -> " + unvisited); /// plan <- PLAN-ROUTE(current, unvisited ∩ safe, safe) - plan.addAll(planRouteToRooms(SetOps.intersection(unvisited, safe), safe)); + plan.addAll(planRouteToRooms(SetOps.intersection(unvisited, safe), safe).orElse(Collections.emptyList())); } /// if plan is empty and ASK(KB, HaveArrowt) = true then @@ -162,7 +162,7 @@ public Optional act(WumpusPercept percept) { Set possibleWumpus = kb.askPossibleWumpusRooms(t); notifyViews("Ask possible Wumpus positions -> " + possibleWumpus); /// plan <- PLAN-SHOT(current, possible_wumpus, safe) - plan.addAll(planShot(possibleWumpus, safe)); + planShot(possibleWumpus, safe).ifPresent(plan::addAll); } /// if plan is empty then (no choice but to take a risk) @@ -172,7 +172,7 @@ public Optional act(WumpusPercept percept) { notifyViews("Ask not unsafe -> " + notUnsafe); /// plan <- PLAN-ROUTE(current, unvisited ∩ not_unsafe, safe) // Correction: Last argument must be not_unsafe! - plan.addAll(planRouteToRooms(unvisited, notUnsafe)); + plan.addAll(planRouteToRooms(unvisited, notUnsafe).orElse(Collections.emptyList())); } /// if plan is empty then @@ -181,7 +181,7 @@ public Optional act(WumpusPercept percept) { /// plan PLAN-ROUTE(current, {[1,1]}, safe) + [Climb] Set goal = new LinkedHashSet<>(); goal.add(start.getRoom()); - plan.addAll(planRouteToRooms(goal, safe)); + plan.addAll(planRouteToRooms(goal, safe).orElse(Collections.emptyList())); plan.add(WumpusAction.CLIMB); } /// action <- POP(plan) @@ -203,9 +203,11 @@ public Optional act(WumpusPercept percept) { * a set of squares that can form part of the route * * @return the best sequence of actions that the agent have to do to reach a - * goal from the current position. + * goal from the current position, empty if the agent is already in + * a goal square, or no value if no goal can be reached through the + * allowed squares (the failure of PLAN-ROUTE). */ - public List planRouteToRooms(Set goals, Set allowed) { + public Optional> planRouteToRooms(Set goals, Set allowed) { final Set goalPositions = new LinkedHashSet<>(); for (Room goalRoom : goals) { int x = goalRoom.getX(); @@ -225,9 +227,11 @@ public List planRouteToRooms(Set goals, Set allowed) { * a set of squares that can form part of the route * * @return the best sequence of actions that the agent have to do to reach a - * goal from the current position. + * goal from the current position, empty if the agent is already in + * a goal position, or no value if no goal can be reached through + * the allowed squares (the failure of PLAN-ROUTE). */ - public List planRoute(Set goals, Set allowed) { + public Optional> planRoute(Set goals, Set allowed) { WumpusCave cave = new WumpusCave(kb.getCaveXDimension(), kb.getCaveYDimension()).setAllowed(allowed); Problem problem = new GeneralProblem<>(currentPosition, @@ -235,9 +239,7 @@ public List planRoute(Set goals, Set allowed) WumpusFunctions.createResultFunction(cave), goals::contains); SearchForActions search = new AStarSearch<>(new GraphSearch<>(), WumpusFunctions.createManhattanDistanceFunction(goals)); - Optional> actions = search.findActions(problem); - - return actions.orElse(Collections.emptyList()); + return search.findActions(problem); } /** @@ -248,9 +250,11 @@ public List planRoute(Set goals, Set allowed) * a set of squares that can form part of the route * * @return the sequence of actions to reach the nearest square that is in - * line with a possible wumpus position. The last action is a shot. + * line with a possible wumpus position, whose last action is a + * shot, or no value if no such square can be reached (and then + * the arrow is not wasted on a shot from the wrong square). */ - public List planShot(Set possibleWumpus, Set allowed) { + public Optional> planShot(Set possibleWumpus, Set allowed) { Set shootingPositions = new LinkedHashSet<>(); @@ -277,9 +281,11 @@ public List planShot(Set possibleWumpus, Set allowed) for (AgentPosition.Orientation orientation : AgentPosition.Orientation.values()) shootingPositions.remove(new AgentPosition(room.getX(), room.getY(), orientation)); - List actions = new ArrayList<>(planRoute(shootingPositions, allowed)); - actions.add(WumpusAction.SHOOT); - return actions; + return planRoute(shootingPositions, allowed).map(route -> { + List actions = new ArrayList<>(route); + actions.add(WumpusAction.SHOOT); + return actions; + }); } public Metrics getMetrics() { diff --git a/aima-core/src/test/java/aima/test/core/unit/environment/wumpusworld/HybridWumpusAgentTest.java b/aima-core/src/test/java/aima/test/core/unit/environment/wumpusworld/HybridWumpusAgentTest.java index 0b2ca4cd9..0d027fda3 100644 --- a/aima-core/src/test/java/aima/test/core/unit/environment/wumpusworld/HybridWumpusAgentTest.java +++ b/aima-core/src/test/java/aima/test/core/unit/environment/wumpusworld/HybridWumpusAgentTest.java @@ -22,7 +22,7 @@ public void testPlanRoute() { hwa = new HybridWumpusAgent(4, 4, new AgentPosition(1, 1, AgentPosition.Orientation.FACING_EAST)); // Should be a NoOp plan as we are already at the goal. - Assert.assertEquals(Collections.emptyList(), + Assert.assertEquals(Optional.of(Collections.emptyList()), hwa.planRouteToRooms( new LinkedHashSet() {{ add(new Room(1,1)); @@ -31,7 +31,7 @@ public void testPlanRoute() { )); hwa = new HybridWumpusAgent(4, 4, new AgentPosition(2, 1, AgentPosition.Orientation.FACING_EAST)); - Assert.assertEquals(Arrays.asList(WumpusAction.TURN_LEFT, WumpusAction.TURN_LEFT, WumpusAction.FORWARD), + Assert.assertEquals(Optional.of(Arrays.asList(WumpusAction.TURN_LEFT, WumpusAction.TURN_LEFT, WumpusAction.FORWARD)), hwa.planRouteToRooms( new LinkedHashSet() {{ add(new Room(1,1)); @@ -40,9 +40,9 @@ public void testPlanRoute() { )); hwa = new HybridWumpusAgent(4, 4, new AgentPosition(3, 1, AgentPosition.Orientation.FACING_EAST)); - Assert.assertEquals(Arrays.asList(WumpusAction.TURN_LEFT, WumpusAction.FORWARD, WumpusAction.FORWARD, + Assert.assertEquals(Optional.of(Arrays.asList(WumpusAction.TURN_LEFT, WumpusAction.FORWARD, WumpusAction.FORWARD, WumpusAction.TURN_LEFT, WumpusAction.FORWARD, WumpusAction.FORWARD, WumpusAction.TURN_LEFT, - WumpusAction.FORWARD, WumpusAction.FORWARD), + WumpusAction.FORWARD, WumpusAction.FORWARD)), hwa.planRouteToRooms( new LinkedHashSet() {{ add(new Room(1,1)); @@ -61,7 +61,7 @@ public void testPlanShot() { HybridWumpusAgent hwa; hwa = new HybridWumpusAgent(4, 4, new AgentPosition(1, 1, AgentPosition.Orientation.FACING_EAST)); // Should be just shoot as are facing the Wumpus - Assert.assertEquals(Collections.singletonList(WumpusAction.SHOOT), + Assert.assertEquals(Optional.of(Collections.singletonList(WumpusAction.SHOOT)), hwa.planShot( new LinkedHashSet() {{ add(new Room(3,1)); @@ -70,7 +70,7 @@ public void testPlanShot() { )); hwa = new HybridWumpusAgent(4, 4, new AgentPosition(1, 1, AgentPosition.Orientation.FACING_EAST)); - Assert.assertEquals(Arrays.asList(WumpusAction.TURN_LEFT, WumpusAction.SHOOT), + Assert.assertEquals(Optional.of(Arrays.asList(WumpusAction.TURN_LEFT, WumpusAction.SHOOT)), hwa.planShot( new LinkedHashSet() {{ add(new Room(1,2)); @@ -79,7 +79,7 @@ public void testPlanShot() { )); hwa = new HybridWumpusAgent(4, 4, new AgentPosition(1, 1, AgentPosition.Orientation.FACING_EAST)); - Assert.assertEquals(Arrays.asList(WumpusAction.FORWARD, WumpusAction.TURN_LEFT, WumpusAction.SHOOT), + Assert.assertEquals(Optional.of(Arrays.asList(WumpusAction.FORWARD, WumpusAction.TURN_LEFT, WumpusAction.SHOOT)), hwa.planShot( new LinkedHashSet() {{ add(new Room(2,2)); @@ -127,10 +127,25 @@ private static Set allRooms(int caveDimensions) { @Test public void testPlanRouteWithoutAPath() { // only the room of the agent is allowed: (1,1) cannot be reached, and - // the plan is empty, as PLAN-ROUTE gives no action to take + // PLAN-ROUTE fails, which is told apart from the empty plan of an + // agent already in a goal square HybridWumpusAgent hwa = new HybridWumpusAgent(4, 4, new AgentPosition(3, 1, AgentPosition.Orientation.FACING_EAST)); - Assert.assertEquals(Collections.emptyList(), hwa.planRouteToRooms( + Assert.assertEquals(Optional.empty(), hwa.planRouteToRooms( new LinkedHashSet<>(Collections.singletonList(new Room(1, 1))), new LinkedHashSet<>(Collections.singletonList(new Room(3, 1))))); + Assert.assertEquals(Optional.of(Collections.emptyList()), hwa.planRouteToRooms( + new LinkedHashSet<>(Collections.singletonList(new Room(3, 1))), + new LinkedHashSet<>(Collections.singletonList(new Room(3, 1))))); + } + + @Test + public void testPlanShotWithoutAShootingSquare() { + // the wumpus may be in (2,2), which is in line only with squares out + // of reach: no shot is planned, instead of a shot from (1,1) facing + // east that cannot hit it + HybridWumpusAgent hwa = new HybridWumpusAgent(4, 4, new AgentPosition(1, 1, AgentPosition.Orientation.FACING_EAST)); + Assert.assertEquals(Optional.empty(), hwa.planShot( + new LinkedHashSet<>(Collections.singletonList(new Room(2, 2))), + new LinkedHashSet<>(Collections.singletonList(new Room(1, 1))))); } } From 9626bc6dbfe712106c870553300ffc57ff22b634 Mon Sep 17 00:00:00 2001 From: Donato Meoli Date: Wed, 2 Dec 2026 02:45:52 +0100 Subject: [PATCH 3/4] Let a clause subsume a clause of the same length, so P(x) eliminates P(A) --- .../logic/fol/SubsumptionElimination.java | 13 ++++---- .../aima/core/logic/fol/kb/data/Clause.java | 18 +++++++++-- .../logic/fol/SubsumptionEliminationTest.java | 30 +++++++++++++++++++ 3 files changed, 53 insertions(+), 8 deletions(-) diff --git a/aima-core/src/main/java/aima/core/logic/fol/SubsumptionElimination.java b/aima-core/src/main/java/aima/core/logic/fol/SubsumptionElimination.java index b2fb3db27..ba1aba156 100644 --- a/aima-core/src/main/java/aima/core/logic/fol/SubsumptionElimination.java +++ b/aima-core/src/main/java/aima/core/logic/fol/SubsumptionElimination.java @@ -38,7 +38,10 @@ public class SubsumptionElimination { * a set of clauses in first order logic * * @return the clauses that are subsumed by (that is, more specific than) an - * existing clause in the specified set of clauses. + * existing clause in the specified set of clauses, which may have + * as many literals as the clause that subsumes them. Of two + * clauses that subsume each other only one is returned, so that + * the other stays. */ public static Set findSubsumedClauses(Set clauses) { Set subsumed = new HashSet(); @@ -63,13 +66,13 @@ public static Set findSubsumedClauses(Set clauses) { } cforsize.add(c); } - // Check if each smaller clause - // subsumes any of the larger clauses. - for (int i = min; i < max; i++) { + // Check if each clause subsumes any of the clauses + // of its size or larger (e.g., P(x) subsumes P(A)). + for (int i = min; i <= max; i++) { Set scs = clausesGroupedBySize.get(i); // Ensure there are clauses with this # of literals if (null != scs) { - for (int j = i + 1; j <= max; j++) { + for (int j = i; j <= max; j++) { Set lcs = clausesGroupedBySize.get(j); // Ensure there are clauses with this # of literals if (null != lcs) { diff --git a/aima-core/src/main/java/aima/core/logic/fol/kb/data/Clause.java b/aima-core/src/main/java/aima/core/logic/fol/kb/data/Clause.java index b6d5cb179..81d34eea2 100644 --- a/aima-core/src/main/java/aima/core/logic/fol/kb/data/Clause.java +++ b/aima-core/src/main/java/aima/core/logic/fol/kb/data/Clause.java @@ -228,14 +228,26 @@ public Set getNonTrivialFactors() { return Collections.unmodifiableSet(nonTrivialFactors); } + /** + * A clause Φ subsumes Ψ if a substitution of the variables of + * Φ turns it into a subset of Ψ; e.g., P(x) subsumes P(A) and P(A) + * V Q(B). The two clauses may have the same number of literals, but a + * clause does not subsume itself nor a variant of itself (a clause equal + * up to the names of its variables), so that of two variants neither is + * eliminated in favour of the other. + * + * @param othC + * the other clause. + * @return true if this clause subsumes the other one. + */ public boolean subsumes(Clause othC) { boolean subsumes = false; // Equality is not subsumption - if (!(this == othC)) { - // Ensure this has less literals total and that + if (!this.equals(othC)) { + // Ensure this has no more literals and that // it is a subset of the other clauses positive and negative counts - if (this.getNumberLiterals() < othC.getNumberLiterals() + if (this.getNumberLiterals() <= othC.getNumberLiterals() && this.getNumberPositiveLiterals() <= othC .getNumberPositiveLiterals() && this.getNumberNegativeLiterals() <= othC diff --git a/aima-core/src/test/java/aima/test/core/unit/logic/fol/SubsumptionEliminationTest.java b/aima-core/src/test/java/aima/test/core/unit/logic/fol/SubsumptionEliminationTest.java index a14f173f4..d4c685800 100644 --- a/aima-core/src/test/java/aima/test/core/unit/logic/fol/SubsumptionEliminationTest.java +++ b/aima-core/src/test/java/aima/test/core/unit/logic/fol/SubsumptionEliminationTest.java @@ -1,5 +1,7 @@ package aima.test.core.unit.logic.fol; +import java.util.Arrays; +import java.util.Collections; import java.util.HashSet; import java.util.Set; @@ -132,4 +134,32 @@ public void testClausesOfTheSameLengthWithoutSubsumption() { clauses.addAll(cnfConv.convertToCNF(parser.parse("(King(John) OR Greedy(John))")).getConjunctionOfClauses()); Assert.assertEquals(1, SubsumptionElimination.findSubsumedClauses(clauses).size()); } + + @Test + public void testAClauseSubsumesAClauseOfTheSameLength() { + // P(x) subsumes P(A), which has as many literals (section 9.5.6 of the + // 4th edition: there is no sense in adding P(A) when P(x) is known) + FOLDomain domain = new FOLDomain(); + domain.addPredicate("P"); + domain.addPredicate("Q"); + domain.addConstant("A"); + domain.addConstant("B"); + FOLParser parser = new FOLParser(domain); + CNFConverter cnfConv = new CNFConverter(parser); + Clause px = cnfConv.convertToCNF(parser.parse("P(x)")).getConjunctionOfClauses().get(0); + Clause pa = cnfConv.convertToCNF(parser.parse("P(A)")).getConjunctionOfClauses().get(0); + Clause pxqb = cnfConv.convertToCNF(parser.parse("(P(x) OR Q(B))")).getConjunctionOfClauses().get(0); + Clause paqy = cnfConv.convertToCNF(parser.parse("(P(A) OR Q(y))")).getConjunctionOfClauses().get(0); + Assert.assertTrue(px.subsumes(pa)); + Assert.assertFalse(pa.subsumes(px)); + Set clauses = new HashSet(Arrays.asList(px, pa)); + Assert.assertEquals(Collections.singleton(pa), SubsumptionElimination.findSubsumedClauses(clauses)); + // P(A) OR Q(y) and P(x) OR Q(B) do not subsume each other + clauses = new HashSet(Arrays.asList(pxqb, paqy)); + Assert.assertTrue(SubsumptionElimination.findSubsumedClauses(clauses).isEmpty()); + // a clause does not subsume itself nor a variant of itself + Clause py = cnfConv.convertToCNF(parser.parse("P(y)")).getConjunctionOfClauses().get(0); + Assert.assertFalse(px.subsumes(px)); + Assert.assertFalse(px.subsumes(py)); + } } From 5864138a945f9c4e0423f4d945705e1e2e5dfa14 Mon Sep 17 00:00:00 2001 From: Donato Meoli Date: Wed, 2 Dec 2026 02:45:52 +0100 Subject: [PATCH 4/4] Keep the model in Baum-Welch without observations, and the transitions with one As aima-python, a parameter without expected counts keeps its value instead of raising. --- .../probability/hmm/learning/BaumWelch.java | 20 +++++++---- .../hmm/learning/BaumWelchTest.java | 33 +++++++++++++++---- 2 files changed, 39 insertions(+), 14 deletions(-) diff --git a/aima-core/src/main/java/aima/core/probability/hmm/learning/BaumWelch.java b/aima-core/src/main/java/aima/core/probability/hmm/learning/BaumWelch.java index 485a9537e..313a7e241 100644 --- a/aima-core/src/main/java/aima/core/probability/hmm/learning/BaumWelch.java +++ b/aima-core/src/main/java/aima/core/probability/hmm/learning/BaumWelch.java @@ -43,18 +43,21 @@ private BaumWelch() { * the initial guess, whose sensor model gives the possible * observations. * @param ev - * the observations e1, ..., eT, at least - * two. + * the observations e1, ..., eT. * @param iterations * the number of iterations of EM. - * @return the hidden Markov model with the learned parameters. + * @return the hidden Markov model with the learned parameters. As in + * aima-python, a parameter without expected counts keeps its + * value: without observations the model is returned unchanged, + * and with a single observation there is no transition to count, + * so that only the prior and the sensor model are learned. */ public static HiddenMarkovModel learn(HiddenMarkovModel hmm, List> ev, int iterations) { int n = hmm.getTransitionModel().getRowDimension(); int T = ev.size(); - if (T < 2) { - throw new IllegalArgumentException("Baum-Welch needs at least two observations."); + if (T == 0) { + iterations = 0; } List keys = new ArrayList<>(hmm.getSensorModel().keySet()); Object[] obs = new Object[T]; @@ -148,8 +151,11 @@ public static HiddenMarkovModel learn(HiddenMarkovModel hmm, List 1) { + for (int j = 0; j < n; j++) { + A[i][j] = xiSum[i][j] / fromI; + } } for (Object key : keys) { double s = 0; diff --git a/aima-core/src/test/java/aima/test/core/unit/probability/hmm/learning/BaumWelchTest.java b/aima-core/src/test/java/aima/test/core/unit/probability/hmm/learning/BaumWelchTest.java index 2e1077b14..687505bf9 100644 --- a/aima-core/src/test/java/aima/test/core/unit/probability/hmm/learning/BaumWelchTest.java +++ b/aima-core/src/test/java/aima/test/core/unit/probability/hmm/learning/BaumWelchTest.java @@ -50,14 +50,33 @@ public void testBaumWelchNeverDecreasesTheLikelihood() { Assert.assertEquals(umbrella.getStateVariable(), learned.getStateVariable()); } - @Test(expected = IllegalArgumentException.class) - public void testBaumWelchNeedsTwoObservations() { - BaumWelch.learn(HMMExampleFactory.getUmbrellaWorldModel(), Collections.singletonList( - Collections.singletonList(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV, true))), 1); + @Test + public void testBaumWelchWithASingleObservationKeepsTheTransitionModel() { + // as test_baum_welch_without_observations_with_one_and_without_iterations + // of aima-python: there is no transition to count, while the prior is + // the filtered P(R_1 | u_1) = <9/11, 2/11> and the umbrella is always + // seen + HiddenMarkovModel umbrella = HMMExampleFactory.getUmbrellaWorldModel(); + HiddenMarkovModel learned = BaumWelch.learn(umbrella, Collections.singletonList( + Collections.singletonList(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV, true))), 5); + Assert.assertArrayEquals(umbrella.getTransitionModel().getRowPackedCopy(), + learned.getTransitionModel().getRowPackedCopy(), 0); + Assert.assertArrayEquals(new double[] { 9.0 / 11, 2.0 / 11 }, learned.getPrior().getRowPackedCopy(), 1e-12); + Assert.assertEquals(1.0, learned.getSensorModel().get(true).get(0, 0), 1e-12); + Assert.assertEquals(1.0, learned.getSensorModel().get(true).get(1, 1), 1e-12); + Assert.assertEquals(0.0, learned.getSensorModel().get(false).get(0, 0), 1e-12); } - @Test(expected = IllegalArgumentException.class) - public void testBaumWelchWithoutObservations() { - BaumWelch.learn(HMMExampleFactory.getUmbrellaWorldModel(), new ArrayList<>(), 1); + + @Test + public void testBaumWelchWithoutObservationsReturnsTheModel() { + HiddenMarkovModel umbrella = HMMExampleFactory.getUmbrellaWorldModel(); + HiddenMarkovModel same = BaumWelch.learn(umbrella, new ArrayList<>(), 5); + Assert.assertArrayEquals(umbrella.getTransitionModel().getRowPackedCopy(), + same.getTransitionModel().getRowPackedCopy(), 0); + Assert.assertArrayEquals(umbrella.getPrior().getRowPackedCopy(), same.getPrior().getRowPackedCopy(), 0); + for (Object e : umbrella.getSensorModel().keySet()) + Assert.assertArrayEquals(umbrella.getSensorModel().get(e).getRowPackedCopy(), + same.getSensorModel().get(e).getRowPackedCopy(), 0); } @Test