Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public Optional<WumpusAction> act(WumpusPercept percept) {
Set<Room> 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);
}

Expand All @@ -136,7 +136,7 @@ public Optional<WumpusAction> act(WumpusPercept percept) {
// Optimization: Agent remembers visited locations, no need to ask.
unvisited = SetOps.difference(modelCave.getAllRooms(), visitedRooms);
// plan <- PLAN-ROUTE(current, unvisited &cap; safe, safe)
plan.addAll(planRouteToRooms(unvisited, safe));
plan.addAll(planRouteToRooms(unvisited, safe).orElse(Collections.emptyList()));
}

// if plan is empty and ASK(KB, HaveArrow<sup>t</sup>) = true then
Expand All @@ -145,7 +145,7 @@ public Optional<WumpusAction> act(WumpusPercept percept) {
Set<Room> 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
Expand All @@ -156,7 +156,7 @@ public Optional<WumpusAction> act(WumpusPercept percept) {
notifyViews("Ask not unsafe -> " + notUnsafe);
// plan <- PLAN-ROUTE(current, unvisited &cap; 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
Expand All @@ -165,7 +165,7 @@ public Optional<WumpusAction> act(WumpusPercept percept) {
// plan PLAN-ROUTE(current, {[1,1]}, safe) + [Climb]
Set<Room> 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)
Expand All @@ -189,18 +189,19 @@ public Optional<WumpusAction> 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<WumpusAction> planRoute(Set<AgentPosition> goals, Set<Room> allowed) {
@Override
public Optional<List<WumpusAction>> planRoute(Set<AgentPosition> goals, Set<Room> allowed) {
modelCave.setAllowed(allowed);
Problem<AgentPosition, WumpusAction> problem = new GeneralProblem<>(currentPosition,
WumpusFunctions.createActionsFunction(modelCave),
WumpusFunctions.createResultFunction(modelCave), goals::contains);
SearchForActions<AgentPosition, WumpusAction> search =
new AStarSearch<>(new GraphSearch<>(), WumpusFunctions.createManhattanDistanceFunction(goals));
Optional<List<WumpusAction>> actions = search.findActions(problem);

return actions.orElse(Collections.emptyList());
return search.findActions(problem);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ public Optional<WumpusAction> act(WumpusPercept percept) {
Set<Room> 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);
}

Expand All @@ -153,7 +153,7 @@ public Optional<WumpusAction> act(WumpusPercept percept) {
unvisited = kb.askUnvisitedRooms(t);
notifyViews("Ask unvisited -> " + unvisited);
/// plan <- PLAN-ROUTE(current, unvisited &cap; 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, HaveArrow<sup>t</sup>) = true then
Expand All @@ -162,7 +162,7 @@ public Optional<WumpusAction> act(WumpusPercept percept) {
Set<Room> 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)
Expand All @@ -172,7 +172,7 @@ public Optional<WumpusAction> act(WumpusPercept percept) {
notifyViews("Ask not unsafe -> " + notUnsafe);
/// plan <- PLAN-ROUTE(current, unvisited &cap; 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
Expand All @@ -181,7 +181,7 @@ public Optional<WumpusAction> act(WumpusPercept percept) {
/// plan PLAN-ROUTE(current, {[1,1]}, safe) + [Climb]
Set<Room> 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)
Expand All @@ -203,9 +203,11 @@ public Optional<WumpusAction> 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<WumpusAction> planRouteToRooms(Set<Room> goals, Set<Room> allowed) {
public Optional<List<WumpusAction>> planRouteToRooms(Set<Room> goals, Set<Room> allowed) {
final Set<AgentPosition> goalPositions = new LinkedHashSet<>();
for (Room goalRoom : goals) {
int x = goalRoom.getX();
Expand All @@ -225,19 +227,19 @@ public List<WumpusAction> planRouteToRooms(Set<Room> goals, Set<Room> 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<WumpusAction> planRoute(Set<AgentPosition> goals, Set<Room> allowed) {
public Optional<List<WumpusAction>> planRoute(Set<AgentPosition> goals, Set<Room> allowed) {

WumpusCave cave = new WumpusCave(kb.getCaveXDimension(), kb.getCaveYDimension()).setAllowed(allowed);
Problem<AgentPosition, WumpusAction> problem = new GeneralProblem<>(currentPosition,
WumpusFunctions.createActionsFunction(cave),
WumpusFunctions.createResultFunction(cave), goals::contains);
SearchForActions<AgentPosition, WumpusAction> search =
new AStarSearch<>(new GraphSearch<>(), WumpusFunctions.createManhattanDistanceFunction(goals));
Optional<List<WumpusAction>> actions = search.findActions(problem);

return actions.orElse(Collections.emptyList());
return search.findActions(problem);
}

/**
Expand All @@ -248,9 +250,11 @@ public List<WumpusAction> planRoute(Set<AgentPosition> goals, Set<Room> 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<WumpusAction> planShot(Set<Room> possibleWumpus, Set<Room> allowed) {
public Optional<List<WumpusAction>> planShot(Set<Room> possibleWumpus, Set<Room> allowed) {

Set<AgentPosition> shootingPositions = new LinkedHashSet<>();

Expand All @@ -277,9 +281,11 @@ public List<WumpusAction> planShot(Set<Room> possibleWumpus, Set<Room> allowed)
for (AgentPosition.Orientation orientation : AgentPosition.Orientation.values())
shootingPositions.remove(new AgentPosition(room.getX(), room.getY(), orientation));

List<WumpusAction> actions = new ArrayList<>(planRoute(shootingPositions, allowed));
actions.add(WumpusAction.SHOOT);
return actions;
return planRoute(shootingPositions, allowed).map(route -> {
List<WumpusAction> actions = new ArrayList<>(route);
actions.add(WumpusAction.SHOOT);
return actions;
});
}

public Metrics getMetrics() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Clause> findSubsumedClauses(Set<Clause> clauses) {
Set<Clause> subsumed = new HashSet<Clause>();
Expand All @@ -63,13 +66,13 @@ public static Set<Clause> findSubsumedClauses(Set<Clause> 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<Clause> 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<Clause> lcs = clausesGroupedBySize.get(j);
// Ensure there are clauses with this # of literals
if (null != lcs) {
Expand Down
18 changes: 15 additions & 3 deletions aima-core/src/main/java/aima/core/logic/fol/kb/data/Clause.java
Original file line number Diff line number Diff line change
Expand Up @@ -228,14 +228,26 @@ public Set<Clause> getNonTrivialFactors() {
return Collections.unmodifiableSet(nonTrivialFactors);
}

/**
* A clause &Phi; subsumes &Psi; if a substitution of the variables of
* &Phi; turns it into a subset of &Psi;; 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
Expand Down
32 changes: 27 additions & 5 deletions aima-core/src/main/java/aima/core/logic/fol/parsing/FOLParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
* <code>King(John) AND Evil(Richard)</code> reads as
* <code>(King(John) AND Evil(Richard))</code>; 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) {
Expand Down Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,18 +43,21 @@ private BaumWelch() {
* the initial guess, whose sensor model gives the possible
* observations.
* @param ev
* the observations e<sub>1</sub>, ..., e<sub>T</sub>, at least
* two.
* the observations e<sub>1</sub>, ..., e<sub>T</sub>.
* @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<List<AssignmentProposition>> 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<Object> keys = new ArrayList<>(hmm.getSensorModel().keySet());
Object[] obs = new Object[T];
Expand Down Expand Up @@ -148,8 +151,11 @@ public static HiddenMarkovModel learn(HiddenMarkovModel hmm, List<List<Assignmen
}
inI += gamma[t][i];
}
for (int j = 0; j < n; j++) {
A[i][j] = xiSum[i][j] / fromI;
// with a single observation there is no transition to count
if (T > 1) {
for (int j = 0; j < n; j++) {
A[i][j] = xiSum[i][j] / fromI;
}
}
for (Object key : keys) {
double s = 0;
Expand Down
Loading