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 @@ -58,7 +58,14 @@ public class WalkSAT {
*/
public Model walkSAT(Set<Clause> clauses, double p, int maxFlips) {
assertLegalProbability(p);

// the empty clause (e.g., from False) is false in every model: no
// flip can satisfy it
for (Clause c : clauses) {
if (c.isFalse()) {
return null;
}
}

// model <- a random assignment of true/false to the symbols in clauses
Model model = randomAssignmentToSymbolsInClauses(clauses);
// for i = 1 to max_flips do (Note: maxFlips < 0 means infinity)
Expand Down Expand Up @@ -122,7 +129,12 @@ protected Model randomAssignmentToSymbolsInClauses(Set<Clause> clauses) {
// Collect the symbols in clauses
Set<PropositionSymbol> symbols = new LinkedHashSet<PropositionSymbol>();
for (Clause c : clauses) {
symbols.addAll(c.getSymbols());
for (PropositionSymbol symbol : c.getSymbols()) {
// True and False are constants, not symbols to assign
if (!symbol.isAlwaysTrue() && !symbol.isAlwaysFalse()) {
symbols.add(symbol);
}
}
}

// Make initial set of assignments
Expand Down
16 changes: 14 additions & 2 deletions aima-core/src/main/java/aima/core/perception/ImageProcessing.java
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,18 @@ public static double[] hog(double[][] image, int cellSize, int bins, int blockSi
* differences.
*/
public static FlowEstimate sumSquaredDifference(double[][] pic1, double[][] pic2) {
return sumSquaredDifference(pic1, pic2, 30);
}

/**
* As {@link #sumSquaredDifference(double[][], double[][])}, with the shifts
* between -maxShift and maxShift in each direction; with maxShift = 0 the
* only shift is no motion.
*/
public static FlowEstimate sumSquaredDifference(double[][] pic1, double[][] pic2, int maxShift) {
if (maxShift < 0) {
throw new IllegalArgumentException("The largest shift cannot be negative.");
}
int rows = pic1.length;
int cols = pic1[0].length;
if (rows != pic2.length || cols != pic2[0].length) {
Expand All @@ -290,8 +302,8 @@ public static FlowEstimate sumSquaredDifference(double[][] pic1, double[][] pic2
double ssd = Double.POSITIVE_INFINITY;
int bestDx = 0;
int bestDy = 0;
for (int dx = -30; dx <= 30; dx++) {
for (int dy = -30; dy <= 30; dy++) {
for (int dx = -maxShift; dx <= maxShift; dx++) {
for (int dy = -maxShift; dy <= maxShift; dy++) {
double diff = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,14 +257,16 @@ public void unsolvableProblemHasNoForwardPlan() {
{ "air cargo", "At(C1,SFO)^Plane(P1)", "Plane(C1)" },
{ "spare tire", "At(Flat,Axle)", "Tire(Axle)" },
{ "three-block tower", "On(C,A)^Clear(B)", "Block(Table)" },
{ "blocks world", "On(A,Table)^Clear(C)", "Block(Table)" } };
{ "blocks world", "On(A,Table)^Clear(C)", "Block(Table)" },
{ "doubles tennis", "At(A,LeftBaseline)^Partner(A,B)", "Actor(Ball)" } };

private static PlanningProblem standardProblem(int i, String goal) {
PlanningProblem p = i == 0 ? PlanningProblemFactory.airCargoTransportProblem()
: i == 1 ? PlanningProblemFactory.spareTireProblem()
: i == 2 ? PlanningProblemFactory.threeBlockTowerProblem()
: PlanningProblemFactory.blocksWorldProblem("On(A,Table)^On(B,A)^On(C,Table)^Clear(B)^Clear(C)",
"On(A,B)", "A", "B", "C");
: i == 3 ? PlanningProblemFactory.blocksWorldProblem(
"On(A,Table)^On(B,A)^On(C,Table)^Clear(B)^Clear(C)", "On(A,B)", "A", "B", "C")
: PlanningProblemFactory.doublesTennisProblem();
return new PlanningProblem(p.getInitialState(), Utils.parse(goal), p.getActionSchemas());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.junit.Assert;
Expand All @@ -18,16 +19,21 @@
import aima.core.logic.propositional.inference.DimacsParser;
import aima.core.logic.propositional.inference.MapColoringSAT;
import aima.core.logic.propositional.inference.OptimizedDPLL;
import aima.core.logic.propositional.inference.OptimizedPLResolution;
import aima.core.logic.propositional.inference.PLResolution;
import aima.core.logic.propositional.inference.RestartStrategies;
import aima.core.logic.propositional.inference.RestartStrategy;
import aima.core.logic.propositional.inference.SATPlan;
import aima.core.logic.propositional.inference.SATSolver;
import aima.core.logic.propositional.inference.TwoWLClauseDatabase;
import aima.core.logic.propositional.inference.WalkSAT;
import aima.core.logic.propositional.kb.KnowledgeBase;
import aima.core.logic.propositional.kb.data.Clause;
import aima.core.logic.propositional.kb.data.Literal;
import aima.core.logic.propositional.kb.data.Model;
import aima.core.logic.propositional.parsing.PLParser;
import aima.core.logic.propositional.parsing.ast.PropositionSymbol;
import aima.core.logic.propositional.parsing.ast.Sentence;
import aima.core.logic.propositional.transformations.ConvertToConjunctionOfClauses;
import aima.core.util.datastructure.Pair;
import java.util.function.IntUnaryOperator;
Expand Down Expand Up @@ -403,4 +409,44 @@ public void testMapColoringOfASingleRegionAndOfNoRegions() {
// and without colors a region cannot be colored
Assert.assertNull(new DPLL().solve(MapColoringSAT.create(new ArrayList<>(), "T: ")));
}

@Test
public void testTheConstantsTrueAndFalseInsideASentence() {
// False and A & False are unsatisfiable, the others satisfiable; the
// constants are no symbols, so a model never assigns them
PLParser parser = new PLParser();
String[] unsatisfiable = { "False", "A & False", "~True" };
String[] satisfiable = { "True", "A | False", "A | True", "~False", "~A | ~False", "A <=> False" };
for (String text : unsatisfiable) {
Sentence s = parser.parse(text);
Set<Clause> clauses = ConvertToConjunctionOfClauses.apply(s).getClauses();
Assert.assertTrue(text, clauses.stream().anyMatch(Clause::isFalse));
Assert.assertFalse(text, new DPLL().isSatisfiable(s));
Assert.assertFalse(text, new OptimizedDPLL().isSatisfiable(s));
Assert.assertFalse(text, new CDCL().isSatisfiable(s));
Assert.assertNull(text, new WalkSAT(new Random(0)).walkSAT(clauses, 0.5, 100));
KnowledgeBase kb = new KnowledgeBase();
kb.tell(s);
Assert.assertTrue(text, new PLResolution().isEntailed(kb, PropositionSymbol.FALSE));
Assert.assertTrue(text, new OptimizedPLResolution().isEntailed(kb, PropositionSymbol.FALSE));
}
for (String text : satisfiable) {
Sentence s = parser.parse(text);
Set<Clause> clauses = ConvertToConjunctionOfClauses.apply(s).getClauses();
Assert.assertFalse(text, clauses.stream().anyMatch(Clause::isFalse));
Assert.assertTrue(text, new DPLL().isSatisfiable(s));
Assert.assertTrue(text, new OptimizedDPLL().isSatisfiable(s));
Assert.assertTrue(text, new CDCL().isSatisfiable(s));
for (Model model : Arrays.asList(new DPLL().solve(clauses), new CDCL().solve(clauses),
new WalkSAT(new Random(0)).walkSAT(clauses, 0.5, 100))) {
Assert.assertTrue(text, model.satisfies(clauses));
Assert.assertNull(text, model.getValue(PropositionSymbol.TRUE));
Assert.assertNull(text, model.getValue(PropositionSymbol.FALSE));
}
KnowledgeBase kb = new KnowledgeBase();
kb.tell(s);
Assert.assertFalse(text, new PLResolution().isEntailed(kb, PropositionSymbol.FALSE));
Assert.assertFalse(text, new OptimizedPLResolution().isEntailed(kb, PropositionSymbol.FALSE));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,24 @@ public void testFlowOfASinglePixel() {
Assert.assertEquals(4, flow.getSsd(), DELTA);
}

@Test
public void testFlowWithNoShiftAllowed() {
// the second frame is the first moved down by one row; with no shift
// allowed the flow is (0, 0), with the sum of squared differences of
// the frames as they are, while a shift of 1 finds the motion
double[][] pic1 = { { 0, 0, 0 }, { 0, 9, 0 }, { 0, 0, 0 }, { 0, 0, 0 } };
double[][] pic2 = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 9, 0 }, { 0, 0, 0 } };
ImageProcessing.FlowEstimate still = ImageProcessing.sumSquaredDifference(pic1, pic2, 0);
Assert.assertEquals(0, still.getDx());
Assert.assertEquals(0, still.getDy());
Assert.assertEquals(162, still.getSsd(), DELTA);
ImageProcessing.FlowEstimate moved = ImageProcessing.sumSquaredDifference(pic1, pic2, 1);
Assert.assertEquals(0, moved.getSsd(), DELTA);
Assert.assertEquals(moved.getDx(), ImageProcessing.sumSquaredDifference(pic1, pic2).getDx());
Assert.assertEquals(1, Math.abs(moved.getDx()));
Assert.assertEquals(0, moved.getDy());
}

@Test
public void testSegmentationEdgeCases() {
// a single pixel, and a single level, give a black picture
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,16 @@
import org.junit.Assert;
import org.junit.Test;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import aima.core.probability.RandomVariable;
import aima.core.probability.bayes.FiniteNode;
import aima.core.probability.bayes.approx.ParticleFiltering;
import aima.core.probability.bayes.impl.BayesNet;
import aima.core.probability.bayes.impl.DynamicBayesNet;
import aima.core.probability.bayes.impl.FullCPTNode;
import aima.core.probability.example.DynamicBayesNetExampleFactory;
import aima.core.probability.example.ExampleRV;
import aima.core.probability.proposition.AssignmentProposition;
Expand Down Expand Up @@ -97,4 +106,29 @@ public void testASingleParticle() {
Assert.assertEquals(ExampleRV.RAIN_t_RV, S[0][0].getTermVariable());
Assert.assertEquals(true, S[0][0].getValue());
}

@Test
public void testAPerfectSensorRulesOutTheParticlesThatContradictIt() {
// the umbrella world with P(umbrella | rain) = 1 and P(umbrella | not
// rain) = 0: the particles without rain get weight 0 and are never
// resampled
FiniteNode prior = new FullCPTNode(ExampleRV.RAIN_tm1_RV, new double[] { 0.5, 0.5 });
FiniteNode rainTm1 = new FullCPTNode(ExampleRV.RAIN_tm1_RV, new double[] { 0.5, 0.5 });
FiniteNode rainT = new FullCPTNode(ExampleRV.RAIN_t_RV, new double[] { 0.7, 0.3, 0.3, 0.7 }, rainTm1);
new FullCPTNode(ExampleRV.UMBREALLA_t_RV, new double[] { 1, 0, 0, 1 }, rainT);
Map<RandomVariable, RandomVariable> x0ToX1 = new HashMap<>();
x0ToX1.put(ExampleRV.RAIN_tm1_RV, ExampleRV.RAIN_t_RV);
DynamicBayesNet dbn = new DynamicBayesNet(new BayesNet(prior), x0ToX1,
Collections.singleton(ExampleRV.UMBREALLA_t_RV), rainTm1);
// the prior gives rain to the first two particles; the transitions
// give rain at t to the first and the third; resampling draws from
// the weights (1/2, 0, 1/2, 0)
ParticleFiltering pf = new ParticleFiltering(4, dbn, new MockRandomizer(
new double[] { 0.4, 0.4, 0.6, 0.6, 0.7, 0.71, 0.29, 0.31, 0.1, 0.45, 0.55, 0.99 }));
AssignmentProposition[][] S = pf.particleFiltering(new AssignmentProposition[] {
new AssignmentProposition(ExampleRV.UMBREALLA_t_RV, true) });
Assert.assertEquals(4, S.length);
for (AssignmentProposition[] particle : S)
Assert.assertEquals(true, particle[0].getValue());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.function.ToDoubleFunction;
Expand Down Expand Up @@ -238,4 +239,34 @@ public void testEdgeCaseTieBetweenEqualCostPaths() {
Assert.assertTrue(actions.isPresent());
Assert.assertEquals(2.0, edgeCaseCost(p, actions.get()), 0.0);
}

// BEST-FIRST-SEARCH as GraphSearch4e (figure 3.7): the start is a goal, the
// goal cannot be reached, and two paths to the goal tie on f = g

@Test
public void testBestFirstSearchOfFigure3_7FromTheGoalAndWithoutASolution() {
Assert.assertEquals(Optional.of(Collections.emptyList()), new AStarSearch<String, MoveToAction>(
new GraphSearch4e<>(), n -> 0.0).findActions(edgeCaseProblem("A", "A")));
Assert.assertEquals(Optional.empty(), new AStarSearch<String, MoveToAction>(new GraphSearch4e<>(), n -> 0.0)
.findActions(edgeCaseProblem("A", "Z")));
}

@Test
public void testBestFirstSearchOfFigure3_7OnATie() {
// S - A - G and S - B - G both cost 2: either is returned, at cost 2
ExtendableMap map = new ExtendableMap();
map.addUnidirectionalLink("S", "A", 1.0);
map.addUnidirectionalLink("S", "B", 1.0);
map.addUnidirectionalLink("A", "G", 1.0);
map.addUnidirectionalLink("B", "G", 1.0);
Problem<String, MoveToAction> p = new GeneralProblem<>("S", MapFunctions.createActionsFunction(map),
MapFunctions.createResultFunction(), Predicate.isEqual("G"),
MapFunctions.createDistanceStepCostFunction(map));
Optional<List<MoveToAction>> actions = new AStarSearch<String, MoveToAction>(new GraphSearch4e<>(), n -> 0.0)
.findActions(p);
Assert.assertTrue(actions.isPresent());
Assert.assertEquals(2, actions.get().size());
Assert.assertTrue(Arrays.asList("A", "B").contains(actions.get().get(0).getToLocation()));
Assert.assertEquals(2.0, edgeCaseCost(p, actions.get()), 0.0);
}
}