001 package aima.test.logictest.foltest; 002 003 import java.util.ArrayList; 004 import java.util.List; 005 006 import junit.framework.TestCase; 007 import aima.logic.fol.StandardizeApartIndexicalFactory; 008 import aima.logic.fol.domain.DomainFactory; 009 import aima.logic.fol.kb.FOLKnowledgeBase; 010 import aima.logic.fol.kb.data.Clause; 011 import aima.logic.fol.kb.data.Literal; 012 import aima.logic.fol.parsing.ast.Predicate; 013 import aima.logic.fol.parsing.ast.Term; 014 import aima.logic.fol.parsing.ast.Variable; 015 016 /** 017 * @author Ravi Mohan 018 * @author Ciaran O'Reilly 019 * 020 */ 021 public class FOLKnowledgeBaseTest extends TestCase { 022 023 private FOLKnowledgeBase weaponsKB, kingsKB; 024 025 @Override 026 public void setUp() { 027 StandardizeApartIndexicalFactory.flush(); 028 029 weaponsKB = new FOLKnowledgeBase(DomainFactory.weaponsDomain()); 030 031 kingsKB = new FOLKnowledgeBase(DomainFactory.kingsDomain()); 032 } 033 034 public void testAddRuleAndFact() { 035 weaponsKB.tell("(Missile(x) => Weapon(x))"); 036 assertEquals(1, weaponsKB.getNumberRules()); 037 weaponsKB.tell("American(West)"); 038 assertEquals(1, weaponsKB.getNumberRules()); 039 assertEquals(1, weaponsKB.getNumberFacts()); 040 } 041 042 public void testAddComplexRule() { 043 weaponsKB 044 .tell("( (((American(x) AND Weapon(y)) AND Sells(x,y,z)) AND Hostile(z)) => Criminal(x))"); 045 assertEquals(1, weaponsKB.getNumberRules()); 046 weaponsKB.tell("American(West)"); 047 assertEquals(1, weaponsKB.getNumberRules()); 048 049 List<Term> terms = new ArrayList<Term>(); 050 terms.add(new Variable("v0")); 051 052 Clause dcRule = weaponsKB.getAllDefiniteClauseImplications().get(0); 053 assertNotNull(dcRule); 054 assertEquals(true, dcRule.isImplicationDefiniteClause()); 055 assertEquals(new Literal(new Predicate("Criminal", terms)), dcRule 056 .getPositiveLiterals().get(0)); 057 } 058 059 public void testFactNotAddedWhenAlreadyPresent() { 060 kingsKB.tell("((King(x) AND Greedy(x)) => Evil(x))"); 061 kingsKB.tell("King(John)"); 062 kingsKB.tell("King(Richard)"); 063 kingsKB.tell("Greedy(John)"); 064 065 assertEquals(1, kingsKB.getNumberRules()); 066 assertEquals(3, kingsKB.getNumberFacts()); 067 068 kingsKB.tell("King(John)"); 069 kingsKB.tell("King(Richard)"); 070 kingsKB.tell("Greedy(John)"); 071 072 assertEquals(1, kingsKB.getNumberRules()); 073 assertEquals(3, kingsKB.getNumberFacts()); 074 075 kingsKB.tell("(((King(John))))"); 076 kingsKB.tell("(((King(Richard))))"); 077 kingsKB.tell("(((Greedy(John))))"); 078 079 assertEquals(1, kingsKB.getNumberRules()); 080 assertEquals(3, kingsKB.getNumberFacts()); 081 } 082 }