Exemplo n.º 1
0
        protected void testFullFOLKBLovesAnimalQueryNotKillsJackTunaSucceeds(
            InferenceProcedure infp, bool expectedToTimeOut)
        {
            FOLKnowledgeBase akb = FOLKnowledgeBaseFactory
                                   .createLovesAnimalKnowledgeBase(infp);
            List <Term> terms = new List <Term>();

            terms.Add(new Constant("Jack"));
            terms.Add(new Constant("Tuna"));
            NotSentence query = new NotSentence(new Predicate("Kills", terms));

            InferenceResult answer = akb.ask(query);

            Assert.IsTrue(null != answer);
            if (expectedToTimeOut)
            {
                Assert.IsFalse(answer.isPossiblyFalse());
                Assert.IsFalse(answer.isTrue());
                Assert.IsTrue(answer.isUnknownDueToTimeout());
                Assert.IsFalse(answer.isPartialResultDueToTimeout());
                Assert.IsTrue(0 == answer.getProofs().Count);
            }
            else
            {
                Assert.IsFalse(answer.isPossiblyFalse());
                Assert.IsTrue(answer.isTrue());
                Assert.IsFalse(answer.isUnknownDueToTimeout());
                Assert.IsFalse(answer.isPartialResultDueToTimeout());
                Assert.IsTrue(1 == answer.getProofs().Count);
                Assert.IsTrue(0 == answer.getProofs()[0]
                              .getAnswerBindings().Count);
            }
        }
Exemplo n.º 2
0
            public AnswerHandler(FOLKnowledgeBase kb, Sentence query, long maxQueryTime, FOLModelElimination fOLModelElimination)
            {
                finishTime = CommonFactory.Now().AddMilliseconds(maxQueryTime);

                Sentence refutationQuery = new NotSentence(query);

                // Want to use an answer literal to pull
                // query variables where necessary
                Literal answerLiteral = kb.createAnswerLiteral(refutationQuery);

                answerLiteralVariables = kb.collectAllVariables(answerLiteral.getAtomicSentence());

                // Create the Set of Support based on the Query.
                if (answerLiteralVariables.Size() > 0)
                {
                    Sentence refutationQueryWithAnswer = new ConnectedSentence(
                        Connectors.OR, refutationQuery, answerLiteral
                        .getAtomicSentence().copy());

                    sos = fOLModelElimination.createChainsFromClauses(kb.convertToClauses(refutationQueryWithAnswer));

                    answerChain.addLiteral(answerLiteral);
                }
                else
                {
                    sos = fOLModelElimination.createChainsFromClauses(kb.convertToClauses(refutationQuery));
                }

                foreach (Chain s in sos)
                {
                    s.setProofStep(new ProofStepGoal(s));
                }
            }
        protected void testHornClauseKBRingOfThievesQuerySkisXReturnsNancyRedBertDrew(InferenceProcedure infp)
        {
            FOLKnowledgeBase   rotkb = FOLKnowledgeBaseFactory.createRingOfThievesKnowledgeBase(infp);
            ICollection <Term> terms = CollectionFactory.CreateQueue <Term>();

            terms.Add(new Variable("x"));
            Predicate query = new Predicate("Skis", terms);

            InferenceResult answer = rotkb.ask(query);

            Assert.IsTrue(null != answer);
            Assert.IsFalse(answer.isPossiblyFalse());
            Assert.IsTrue(answer.isTrue());
            Assert.IsFalse(answer.isUnknownDueToTimeout());
            // DB can expand infinitely so is only partial.
            Assert.IsTrue(answer.isPartialResultDueToTimeout());
            Assert.AreEqual(4, answer.getProofs().Size());
            Assert.AreEqual(1, answer.getProofs().Get(0).getAnswerBindings().Size());
            Assert.AreEqual(1, answer.getProofs().Get(1).getAnswerBindings().Size());
            Assert.AreEqual(1, answer.getProofs().Get(2).getAnswerBindings().Size());
            Assert.AreEqual(1, answer.getProofs().Get(3).getAnswerBindings().Size());

            ICollection <Constant> expected = CollectionFactory.CreateQueue <Constant>();

            expected.Add(new Constant("Nancy"));
            expected.Add(new Constant("Red"));
            expected.Add(new Constant("Bert"));
            expected.Add(new Constant("Drew"));
            foreach (Proof p in answer.getProofs())
            {
                expected.Remove(p.getAnswerBindings().Get(new Variable("x")) as Constant);
            }
            Assert.AreEqual(0, expected.Size());
        }
        protected void testEqualityNoAxiomsKBabcAEqualsCSucceeds(InferenceProcedure infp, bool expectedToFail)
        {
            FOLKnowledgeBase akb = FOLKnowledgeBaseFactory.createABCEqualityKnowledgeBase(infp, false);

            TermEquality query = new TermEquality(new Constant("A"), new Constant("C"));

            InferenceResult answer = akb.ask(query);

            Assert.IsTrue(null != answer);
            if (expectedToFail)
            {
                Assert.IsTrue(answer.isPossiblyFalse());
                Assert.IsFalse(answer.isTrue());
                Assert.IsFalse(answer.isUnknownDueToTimeout());
                Assert.IsFalse(answer.isPartialResultDueToTimeout());
                Assert.IsTrue(0 == answer.getProofs().Size());
            }
            else
            {
                Assert.IsFalse(answer.isPossiblyFalse());
                Assert.IsTrue(answer.isTrue());
                Assert.IsFalse(answer.isUnknownDueToTimeout());
                Assert.IsFalse(answer.isPartialResultDueToTimeout());
                Assert.IsTrue(1 == answer.getProofs().Size());
                Assert.IsTrue(0 == answer.getProofs().Get(0)
                              .getAnswerBindings().Size());
            }
        }
Exemplo n.º 5
0
        protected static void lovesAnimalDemo(InferenceProcedure ip)
        {
            StandardizeApartIndexicalFactory.flush();

            FOLKnowledgeBase kb = FOLKnowledgeBaseFactory.createLovesAnimalKnowledgeBase(ip);

            string kbStr = kb.ToString();

            ICollection <Term> terms = CollectionFactory.CreateQueue <Term>();

            terms.Add(new Constant("Curiosity"));
            terms.Add(new Constant("Tuna"));
            Predicate query = new Predicate("Kills", terms);

            InferenceResult answer = kb.ask(query);

            System.Console.WriteLine("Loves Animal Knowledge Base:");
            System.Console.WriteLine(kbStr);
            System.Console.WriteLine("Query: " + query);
            foreach (Proof p in answer.getProofs())
            {
                System.Console.Write(ProofPrinter.printProof(p));
                System.Console.WriteLine("");
            }
        }
Exemplo n.º 6
0
        private static void kingsDemo1(InferenceProcedure ip)
        {
            StandardizeApartIndexicalFactory.flush();

            FOLKnowledgeBase kb = FOLKnowledgeBaseFactory
                                  .createKingsKnowledgeBase(ip);

            String kbStr = kb.ToString();

            List <Term> terms = new List <Term>();

            terms.Add(new Constant("John"));
            Predicate query = new Predicate("Evil", terms);

            InferenceResult answer = kb.ask(query);

            System.Console.WriteLine("Kings Knowledge Base:");
            System.Console.WriteLine(kbStr);
            System.Console.WriteLine("Query: " + query);
            foreach (Proof p in answer.getProofs())
            {
                System.Console.Write(ProofPrinter.printProof(p));
                System.Console.WriteLine("");
            }
        }
        protected void testFullFOLKBLovesAnimalQueryKillsJackTunaFalse(InferenceProcedure infp, bool expectedToTimeOut)
        {
            FOLKnowledgeBase   akb   = FOLKnowledgeBaseFactory.createLovesAnimalKnowledgeBase(infp);
            ICollection <Term> terms = CollectionFactory.CreateQueue <Term>();

            terms.Add(new Constant("Jack"));
            terms.Add(new Constant("Tuna"));
            Predicate query = new Predicate("Kills", terms);

            InferenceResult answer = akb.ask(query);

            Assert.IsTrue(null != answer);
            if (expectedToTimeOut)
            {
                Assert.IsFalse(answer.isPossiblyFalse());
                Assert.IsFalse(answer.isTrue());
                Assert.IsTrue(answer.isUnknownDueToTimeout());
                Assert.IsFalse(answer.isPartialResultDueToTimeout());
                Assert.IsTrue(0 == answer.getProofs().Size());
            }
            else
            {
                Assert.IsTrue(answer.isPossiblyFalse());
                Assert.IsFalse(answer.isTrue());
                Assert.IsFalse(answer.isUnknownDueToTimeout());
                Assert.IsFalse(answer.isPartialResultDueToTimeout());
                Assert.IsTrue(0 == answer.getProofs().Size());
            }
        }
Exemplo n.º 8
0
        protected void testEqualityAndSubstitutionAxiomsKBabcdFFASucceeds(
            InferenceProcedure infp)
        {
            FOLKnowledgeBase akb = FOLKnowledgeBaseFactory
                                   .createABCDEqualityAndSubstitutionKnowledgeBase(infp, true);

            List <Term> terms = new List <Term>();

            terms.Add(new Constant("A"));
            Function fa = new Function("F", terms);

            terms = new List <Term>();
            terms.Add(fa);
            TermEquality query = new TermEquality(new Function("F", terms),
                                                  new Constant("A"));

            InferenceResult answer = akb.ask(query);

            Assert.IsTrue(null != answer);
            Assert.IsFalse(answer.isPossiblyFalse());
            Assert.IsTrue(answer.isTrue());
            Assert.IsFalse(answer.isUnknownDueToTimeout());
            Assert.IsFalse(answer.isPartialResultDueToTimeout());
            Assert.IsTrue(1 == answer.getProofs().Count);
            Assert.IsTrue(0 == answer.getProofs()[0].getAnswerBindings()
                          .Count);
        }
Exemplo n.º 9
0
        // Artificial Intelligence A Modern Approach (2nd Edition): page 288.
        // COMPOSE(delta, tau) is the substitution whose effect is identical to
        // the effect of applying each substitution in turn. That is,
        // SUBST(COMPOSE(theta1, theta2), p) = SUBST(theta2, SUBST(theta1, p))
        private Dictionary <Variable, Term> compose(FOLKnowledgeBase KB,
                                                    Dictionary <Variable, Term> theta1, Dictionary <Variable, Term> theta2)
        {
            Dictionary <Variable, Term> composed = new Dictionary <Variable, Term>();

            // So that it behaves like:
            // SUBST(theta2, SUBST(theta1, p))
            // There are two steps involved here.
            // See: http://logic.stanford.edu/classes/cs157/2008/notes/chap09.pdf
            // for a detailed discussion:

            // 1. Apply theta2 to the range of theta1.
            foreach (Variable v in theta1.Keys)
            {
                composed.Add(v, KB.subst(theta2, theta1[v]));
            }

            // 2. Adjoin to delta all pairs from tau with different
            // domain variables.
            foreach (Variable v in theta2.Keys)
            {
                if (!theta1.ContainsKey(v))
                {
                    composed.Add(v, theta2[v]);
                }
            }

            return(cascadeSubstitutions(KB, composed));
        }
        protected void testEqualityAndSubstitutionNoAxiomsKBabcdPDSucceeds(InferenceProcedure infp, bool expectedToFail)
        {
            FOLKnowledgeBase akb = FOLKnowledgeBaseFactory.createABCDEqualityAndSubstitutionKnowledgeBase(infp, false);

            ICollection <Term> terms = CollectionFactory.CreateQueue <Term>();

            terms.Add(new Constant("D"));
            Predicate query = new Predicate("P", terms);

            InferenceResult answer = akb.ask(query);

            Assert.IsTrue(null != answer);
            if (expectedToFail)
            {
                Assert.IsTrue(answer.isPossiblyFalse());
                Assert.IsFalse(answer.isTrue());
                Assert.IsFalse(answer.isUnknownDueToTimeout());
                Assert.IsFalse(answer.isPartialResultDueToTimeout());
                Assert.IsTrue(0 == answer.getProofs().Size());
            }
            else
            {
                Assert.IsFalse(answer.isPossiblyFalse());
                Assert.IsTrue(answer.isTrue());
                Assert.IsFalse(answer.isUnknownDueToTimeout());
                Assert.IsFalse(answer.isPartialResultDueToTimeout());
                Assert.IsTrue(1 == answer.getProofs().Size());
                Assert.IsTrue(0 == answer.getProofs().Get(0)
                              .getAnswerBindings().Size());
            }
        }
Exemplo n.º 11
0
        // Artificial Intelligence A Modern Approach (2nd Edition): page 288.
        // COMPOSE(delta, tau) is the substitution whose effect is identical to
        // the effect of applying each substitution in turn. That is,
        // SUBST(COMPOSE(theta1, theta2), p) = SUBST(theta2, SUBST(theta1, p))
        private IMap <Variable, Term> compose(FOLKnowledgeBase KB, IMap <Variable, Term> theta1, IMap <Variable, Term> theta2)
        {
            IMap <Variable, Term> composed = CollectionFactory.CreateInsertionOrderedMap <Variable, Term>();

            // So that it behaves like:
            // SUBST(theta2, SUBST(theta1, p))
            // There are two steps involved here.
            // See: http://logic.stanford.edu/classes/cs157/2008/notes/chap09.pdf
            // for a detailed discussion:

            // 1. Apply theta2 to the range of theta1.
            foreach (Variable v in theta1.GetKeys())
            {
                composed.Put(v, KB.subst(theta2, theta1.Get(v)));
            }

            // 2. Adjoin to delta all pairs from tau with different
            // domain variables.
            foreach (Variable v in theta2.GetKeys())
            {
                if (!theta1.ContainsKey(v))
                {
                    composed.Put(v, theta2.Get(v));
                }
            }

            return(cascadeSubstitutions(KB, composed));
        }
Exemplo n.º 12
0
        public void setUp()
        {
            StandardizeApartIndexicalFactory.flush();

            weaponsKB = new FOLKnowledgeBase(DomainFactory.weaponsDomain());

            kingsKB = new FOLKnowledgeBase(DomainFactory.kingsDomain());
        }
Exemplo n.º 13
0
        // See:
        // http://logic.stanford.edu/classes/cs157/2008/miscellaneous/faq.html#jump165
        // for need for this.
        private IMap <Variable, Term> cascadeSubstitutions(FOLKnowledgeBase KB,
                                                           IMap <Variable, Term> theta)
        {
            foreach (Variable v in theta.GetKeys())
            {
                Term t = theta.Get(v);
                theta.Put(v, KB.subst(theta, t));
            }

            return(theta);
        }
Exemplo n.º 14
0
        // See:
        // http://logic.stanford.edu/classes/cs157/2008/miscellaneous/faq.html#jump165
        // for need for this.
        private Dictionary <Variable, Term> cascadeSubstitutions(FOLKnowledgeBase KB,
                                                                 Dictionary <Variable, Term> theta)
        {
            foreach (Variable v in theta.Keys)
            {
                Term t = theta[v];
                theta.Add(v, KB.subst(theta, t));
            }

            return(theta);
        }
Exemplo n.º 15
0
        // See:
        // http://logic.stanford.edu/classes/cs157/2008/miscellaneous/faq.html#jump165
        // for need for this.
        private IDictionary <Variable, ITerm> CascadeSubstitutions(FOLKnowledgeBase kb,
                                                                   IDictionary <Variable, ITerm> theta)
        {
            foreach (Variable v in theta.Keys)
            {
                ITerm t = theta[v];
                theta[v] = kb.Subst(theta, t);
            }

            return(theta);
        }
Exemplo n.º 16
0
        // See:
        // http://logic.stanford.edu/classes/cs157/2008/miscellaneous/faq.html#jump165
        // for need for this.
        private Dictionary <Variable, Term> cascadeSubstitutions(FOLKnowledgeBase KB,
                                                                 Dictionary <Variable, Term> theta)
        {
            var keys = theta.Keys.ToList();

            foreach (Variable v in keys)
            {
                theta[v] = KB.subst(theta, theta[v]);
            }

            return(theta);
        }
        public void testExhaustsSearchSpace()
        {
            // Taken from AIMA pg 679
            FOLDomain domain = new FOLDomain();

            domain.addPredicate("alternate");
            domain.addPredicate("bar");
            domain.addPredicate("fri_sat");
            domain.addPredicate("hungry");
            domain.addPredicate("patrons");
            domain.addPredicate("price");
            domain.addPredicate("raining");
            domain.addPredicate("reservation");
            domain.addPredicate("type");
            domain.addPredicate("wait_estimate");
            domain.addPredicate("will_wait");
            domain.addConstant("Some");
            domain.addConstant("Full");
            domain.addConstant("French");
            domain.addConstant("Thai");
            domain.addConstant("Burger");
            domain.addConstant("$");
            domain.addConstant("_30_60");
            domain.addConstant("X0");
            FOLParser parser = new FOLParser(domain);

            // The hypothesis
            String c1 = "patrons(v,Some)";
            String c2 = "patrons(v,Full) AND (hungry(v) AND type(v,French))";
            String c3 = "patrons(v,Full) AND (hungry(v) AND (type(v,Thai) AND fri_sat(v)))";
            String c4 = "patrons(v,Full) AND (hungry(v) AND type(v,Burger))";
            String sh = "FORALL v (will_wait(v) <=> (" + c1 + " OR (" + c2
                        + " OR (" + c3 + " OR (" + c4 + ")))))";

            Sentence hypothesis = parser.parse(sh);
            Sentence desc       = parser
                                  .parse("(((((((((alternate(X0) AND NOT(bar(X0))) AND NOT(fri_sat(X0))) AND hungry(X0)) AND patrons(X0,Full)) AND price(X0,$)) AND NOT(raining(X0))) AND NOT(reservation(X0))) AND type(X0,Thai)) AND wait_estimate(X0,_30_60))");
            Sentence classification = parser.parse("will_wait(X0)");

            FOLKnowledgeBase kb = new FOLKnowledgeBase(domain,
                                                       new FOLOTTERLikeTheoremProver(false));

            kb.tell(hypothesis);
            kb.tell(desc);

            InferenceResult ir = kb.ask(classification);

            Assert.IsFalse(ir.isTrue());
            Assert.IsTrue(ir.isPossiblyFalse());
            Assert.IsFalse(ir.isUnknownDueToTimeout());
            Assert.IsFalse(ir.isPartialResultDueToTimeout());
            Assert.AreEqual(0, ir.getProofs().Count);
        }
Exemplo n.º 18
0
        //
        // START-InferenceProcedure

        public InferenceResult ask(FOLKnowledgeBase kb, Sentence aQuery)
        {
            //
            // Get the background knowledge - are assuming this is satisfiable
            // as using Set of Support strategy.
            List <Clause> bgClauses  = new List <Clause>(kb.getAllClauses());
            List <Clause> removeList = SubsumptionElimination.findSubsumedClauses(bgClauses);

            foreach (Clause c in removeList)
            {
                bgClauses.Remove(c);
            }
            List <Chain> background = createChainsFromClauses(bgClauses);

            // Collect the information necessary for constructing
            // an answer (supports use of answer literals).
            AnswerHandler ansHandler = new AnswerHandler(kb, aQuery, maxQueryTime, this);

            IndexedFarParents ifps = new IndexedFarParents(ansHandler
                                                           .getSetOfSupport(), background);

            // Iterative deepening to be used
            for (int maxDepth = 1; maxDepth < int.MaxValue; maxDepth++)
            {
                // Track the depth actually reached
                ansHandler.resetMaxDepthReached();

                if (null != tracer)
                {
                    tracer.reset();
                }

                foreach (Chain nearParent in ansHandler.getSetOfSupport())
                {
                    recursiveDLS(maxDepth, 0, nearParent, ifps, ansHandler);
                    if (ansHandler.isComplete())
                    {
                        return(ansHandler);
                    }
                }
                // This means the search tree
                // has bottomed out (i.e. finite).
                // Return what I know based on exploring everything.
                if (ansHandler.getMaxDepthReached() < maxDepth)
                {
                    return(ansHandler);
                }
            }

            return(ansHandler);
        }
Exemplo n.º 19
0
        // END-InferenceProcedure
        //

        //
        // PRIVATE METHODS
        //

        /**
         * <code>
         * function FOL-BC-ASK(KB, goals, theta) returns a set of substitutions
         *   input: KB, a knowledge base
         *          goals, a list of conjuncts forming a query (theta already applied)
         *          theta, the current substitution, initially the empty substitution {}
         * </code>
         */
        private List <List <ProofStepBwChGoal> > folbcask(FOLKnowledgeBase KB,
                                                          BCAskAnswerHandler ansHandler, List <Literal> goals,
                                                          Dictionary <Variable, Term> theta)
        {
            List <List <ProofStepBwChGoal> > thisLevelProofSteps = new List <List <ProofStepBwChGoal> >();

            // local variables: answers, a set of substitutions, initially empty

            // if goals is empty then return {theta}
            if (goals.Count == 0)
            {
                thisLevelProofSteps.Add(new List <ProofStepBwChGoal>());
                return(thisLevelProofSteps);
            }

            // qDelta <- SUBST(theta, FIRST(goals))
            Literal qDelta = KB.subst(theta, goals[0]);

            // for each sentence r in KB where
            // STANDARDIZE-APART(r) = (p1 ^ ... ^ pn => q)
            foreach (Clause r in KB.getAllDefiniteClauses())
            {
                Clause r2 = KB.standardizeApart(r);
                // and thetaDelta <- UNIFY(q, qDelta) succeeds
                Dictionary <Variable, Term> thetaDelta = KB.unify(r2.getPositiveLiterals()
                                                                  [0].getAtomicSentence(), qDelta.getAtomicSentence());
                if (null != thetaDelta)
                {
                    // new_goals <- [p1,...,pn|REST(goals)]
                    List <Literal> newGoals = new List <Literal>(r2
                                                                 .getNegativeLiterals());
                    newGoals.AddRange(goals.Skip(1));
                    // answers <- FOL-BC-ASK(KB, new_goals, COMPOSE(thetaDelta,
                    // theta)) U answers
                    Dictionary <Variable, Term>      composed             = compose(KB, thetaDelta, theta);
                    List <List <ProofStepBwChGoal> > lowerLevelProofSteps = folbcask(
                        KB, ansHandler, newGoals, composed);

                    ansHandler.addProofStep(lowerLevelProofSteps, r2, qDelta,
                                            composed);

                    thisLevelProofSteps.AddRange(lowerLevelProofSteps);
                }
            }

            // return answers
            return(thisLevelProofSteps);
        }
        protected void testDefiniteClauseKBKingsQueryRichardEvilFalse(InferenceProcedure infp)
        {
            FOLKnowledgeBase   kkb   = FOLKnowledgeBaseFactory.createKingsKnowledgeBase(infp);
            ICollection <Term> terms = CollectionFactory.CreateQueue <Term>();

            terms.Add(new Constant("Richard"));
            Predicate       query  = new Predicate("Evil", terms);
            InferenceResult answer = kkb.ask(query);

            Assert.IsTrue(null != answer);
            Assert.IsTrue(answer.isPossiblyFalse());
            Assert.IsFalse(answer.isTrue());
            Assert.IsFalse(answer.isUnknownDueToTimeout());
            Assert.IsFalse(answer.isPartialResultDueToTimeout());
            Assert.IsTrue(0 == answer.getProofs().Size());
        }
Exemplo n.º 21
0
        /**
         * <code>
         * function FOL-BC-ASK(KB, goals, theta) returns a set of substitutions
         *   input: KB, a knowledge base
         *          goals, a list of conjuncts forming a query (theta already applied)
         *          theta, the current substitution, initially the empty substitution {}
         * </code>
         */
        private ICollection <ICollection <ProofStepBwChGoal> > folbcask(FOLKnowledgeBase KB,
                                                                        BCAskAnswerHandler ansHandler, ICollection <Literal> goals,
                                                                        IMap <Variable, Term> theta)
        {
            ICollection <ICollection <ProofStepBwChGoal> > thisLevelProofSteps = CollectionFactory.CreateQueue <ICollection <ProofStepBwChGoal> >();

            // local variables: answers, a set of substitutions, initially empty

            // if goals is empty then return {theta}
            if (goals.IsEmpty())
            {
                thisLevelProofSteps.Add(CollectionFactory.CreateQueue <ProofStepBwChGoal>());
                return(thisLevelProofSteps);
            }

            // qDelta <- SUBST(theta, FIRST(goals))
            Literal qDelta = KB.subst(theta, goals.Get(0));

            // for each sentence r in KB where
            // STANDARDIZE-APART(r) = (p1 ^ ... ^ pn => q)
            foreach (Clause rIter in KB.getAllDefiniteClauses())
            {
                Clause r = rIter;
                r = KB.standardizeApart(r);
                // and thetaDelta <- UNIFY(q, qDelta) succeeds
                IMap <Variable, Term> thetaDelta = KB.unify(r.getPositiveLiterals()
                                                            .Get(0).getAtomicSentence(), qDelta.getAtomicSentence());
                if (null != thetaDelta)
                {
                    // new_goals <- [p1,...,pn|REST(goals)]
                    ICollection <Literal> newGoals = CollectionFactory.CreateQueue <Literal>(r.getNegativeLiterals());
                    newGoals.AddAll(goals.subList(1, goals.Size()));
                    // answers <- FOL-BC-ASK(KB, new_goals, COMPOSE(thetaDelta,
                    // theta)) U answers
                    IMap <Variable, Term> composed = compose(KB, thetaDelta, theta);
                    ICollection <ICollection <ProofStepBwChGoal> > lowerLevelProofSteps = folbcask(
                        KB, ansHandler, newGoals, composed);

                    ansHandler.addProofStep(lowerLevelProofSteps, r, qDelta, composed);

                    thisLevelProofSteps.AddAll(lowerLevelProofSteps);
                }
            }

            // return answers
            return(thisLevelProofSteps);
        }
        protected void testDefiniteClauseKBKingsQueryEvilXReturnsJohnSucceeds(InferenceProcedure infp)
        {
            FOLKnowledgeBase   kkb   = FOLKnowledgeBaseFactory.createKingsKnowledgeBase(infp);
            ICollection <Term> terms = CollectionFactory.CreateQueue <Term>();

            terms.Add(new Variable("x"));
            Predicate       query  = new Predicate("Evil", terms);
            InferenceResult answer = kkb.ask(query);

            Assert.IsTrue(null != answer);
            Assert.IsFalse(answer.isPossiblyFalse());
            Assert.IsTrue(answer.isTrue());
            Assert.IsFalse(answer.isUnknownDueToTimeout());
            Assert.IsFalse(answer.isPartialResultDueToTimeout());
            Assert.IsTrue(1 == answer.getProofs().Size());
            Assert.IsTrue(1 == answer.getProofs().Get(0).getAnswerBindings().Size());
            Assert.AreEqual(new Constant("John"), answer.getProofs().Get(0).getAnswerBindings().Get(new Variable("x")));
        }
Exemplo n.º 23
0
        //
        // Protected Methods
        //
        protected void testDefiniteClauseKBKingsQueryCriminalXFalse(
            InferenceProcedure infp)
        {
            FOLKnowledgeBase kkb = FOLKnowledgeBaseFactory
                                   .createKingsKnowledgeBase(infp);
            List <Term> terms = new List <Term>();

            terms.Add(new Variable("x"));
            Predicate       query  = new Predicate("Criminal", terms);
            InferenceResult answer = kkb.ask(query);

            Assert.IsTrue(null != answer);
            Assert.IsTrue(answer.isPossiblyFalse());
            Assert.IsFalse(answer.isTrue());
            Assert.IsFalse(answer.isUnknownDueToTimeout());
            Assert.IsFalse(answer.isPartialResultDueToTimeout());
            Assert.IsTrue(0 == answer.getProofs().Count);
        }
Exemplo n.º 24
0
        protected void testDefiniteClauseKBKingsQueryKingXReturnsJohnAndRichardSucceeds(
            InferenceProcedure infp)
        {
            FOLKnowledgeBase kkb = FOLKnowledgeBaseFactory
                                   .createKingsKnowledgeBase(infp);
            List <Term> terms = new List <Term>();

            terms.Add(new Variable("x"));
            Predicate       query  = new Predicate("King", terms);
            InferenceResult answer = kkb.ask(query);

            Assert.IsTrue(null != answer);
            Assert.IsFalse(answer.isPossiblyFalse());
            Assert.IsTrue(answer.isTrue());
            Assert.IsFalse(answer.isUnknownDueToTimeout());
            Assert.IsFalse(answer.isPartialResultDueToTimeout());
            Assert.IsTrue(2 == answer.getProofs().Count);
            Assert.IsTrue(1 == answer.getProofs()[0].getAnswerBindings()
                          .Count);
            Assert.IsTrue(1 == answer.getProofs()[1].getAnswerBindings()
                          .Count);

            bool gotJohn, gotRichard;

            gotJohn = gotRichard = false;
            Constant cJohn    = new Constant("John");
            Constant cRichard = new Constant("Richard");

            foreach (Proof p in answer.getProofs())
            {
                Dictionary <Variable, Term> ans = p.getAnswerBindings();
                Assert.AreEqual(1, ans.Count);
                if (cJohn.Equals(ans[new Variable("x")]))
                {
                    gotJohn = true;
                }
                if (cRichard.Equals(ans[new Variable("x")]))
                {
                    gotRichard = true;
                }
            }
            Assert.IsTrue(gotJohn);
            Assert.IsTrue(gotRichard);
        }
Exemplo n.º 25
0
        public void Train(DataSet ds)
        {
            folDSDomain = new FOLDataSetDomain(ds.Specification, trueGoalValue);
            IList <FOLExample> folExamples = new List <FOLExample>();
            int egNo = 1;

            foreach (Example e in ds.examples)
            {
                folExamples.Add(new FOLExample(folDSDomain, e, egNo));
                egNo++;
            }

            // Setup a KB to be used for learning
            kb = new FOLKnowledgeBase(folDSDomain, new FOLOTTERLikeTheoremProver(1000, false));

            var cbl = new CurrentBestLearning(folDSDomain, kb);

            currentBestHypothesis = cbl.GetCurrentBestLearningHypothesis(folExamples);
        }
Exemplo n.º 26
0
        protected void testDefiniteClauseKBKingsQueryJohnEvilSucceeds(
            InferenceProcedure infp)
        {
            FOLKnowledgeBase kkb = FOLKnowledgeBaseFactory
                                   .createKingsKnowledgeBase(infp);
            List <Term> terms = new List <Term>();

            terms.Add(new Constant("John"));
            Predicate       query  = new Predicate("Evil", terms);
            InferenceResult answer = kkb.ask(query);

            Assert.IsTrue(null != answer);
            Assert.IsFalse(answer.isPossiblyFalse());
            Assert.IsTrue(answer.isTrue());
            Assert.IsFalse(answer.isUnknownDueToTimeout());
            Assert.IsFalse(answer.isPartialResultDueToTimeout());
            Assert.IsTrue(1 == answer.getProofs().Count);
            Assert.IsTrue(0 == answer.getProofs()[0].getAnswerBindings()
                          .Count);
        }
Exemplo n.º 27
0
        protected static void abcEqualityNoAxiomDemo(InferenceProcedure ip)
        {
            StandardizeApartIndexicalFactory.flush();

            FOLKnowledgeBase kb = FOLKnowledgeBaseFactory.createABCEqualityKnowledgeBase(ip, false);

            string kbStr = kb.ToString();

            TermEquality query = new TermEquality(new Constant("A"), new Constant("C"));

            InferenceResult answer = kb.ask(query);

            System.Console.WriteLine("ABC Equality No Axiom Knowledge Base:");
            System.Console.WriteLine(kbStr);
            System.Console.WriteLine("Query: " + query);
            foreach (Proof p in answer.getProofs())
            {
                System.Console.Write(ProofPrinter.printProof(p));
                System.Console.WriteLine("");
            }
        }
Exemplo n.º 28
0
        /**
         * Returns a set of substitutions
         *
         * @param KB
         *            a knowledge base
         * @param query
         *            goals, a list of conjuncts forming a query
         *
         * @return a set of substitutions
         */
        public InferenceResult ask(FOLKnowledgeBase KB, Sentence query)
        {
            // Assertions on the type queries this Inference procedure
            // supports
            if (!(query is AtomicSentence))
            {
                throw new IllegalArgumentException("Only Atomic Queries are supported.");
            }

            ICollection <Literal> goals = CollectionFactory.CreateQueue <Literal>();

            goals.Add(new Literal((AtomicSentence)query));

            BCAskAnswerHandler ansHandler = new BCAskAnswerHandler();

            ICollection <ICollection <ProofStepBwChGoal> > allProofSteps = folbcask(KB, ansHandler, goals, CollectionFactory.CreateInsertionOrderedMap <Variable, Term>());

            ansHandler.setAllProofSteps(allProofSteps);

            return(ansHandler);
        }
Exemplo n.º 29
0
        public IInferenceResult Ask(FOLKnowledgeBase kb, ISentence query)
        {
            // Assertions on the type queries this Inference procedure
            // supports
            if (!(query is IAtomicSentence))
            {
                throw new ArgumentOutOfRangeException("query", "Only Atomic Queries are supported.");
            }

            IList <Literal> goals = new List <Literal>();

            goals.Add(new Literal((IAtomicSentence)query));

            var ansHandler = new BCAskAnswerHandler();

            IList <IList <ProofStepBwChGoal> > allProofSteps = this.Folbcask(kb, ansHandler,
                                                                             goals, new Dictionary <Variable, ITerm>());

            ansHandler.SetAllProofSteps(allProofSteps);

            return(ansHandler);
        }
Exemplo n.º 30
0
            public AnswerHandler(FOLKnowledgeBase kb, ISentence aQuery,
                                 long maxQueryTime)
            {
                var ts = DateTime.Now - DateTime.MinValue;

                this.finishTime = (long)ts.TotalMilliseconds + maxQueryTime;

                ISentence refutationQuery = new NotSentence(aQuery);

                // Want to use an answer literal to pull
                // query variables where necessary
                Literal answerLiteral = kb.CreateAnswerLiteral(refutationQuery);

                answerLiteralVariables = kb.CollectAllVariables(answerLiteral
                                                                .AtomicSentence);

                // Create the Set of Support based on the Query.
                if (answerLiteralVariables.Count > 0)
                {
                    ISentence refutationQueryWithAnswer = new ConnectedSentence(
                        Connectors.Or, refutationQuery, (ISentence)answerLiteral.AtomicSentence.Copy());

                    sos = CreateChainsFromClauses(kb
                                                  .ConvertToClauses(refutationQueryWithAnswer));

                    answerChain.AddLiteral(answerLiteral);
                }
                else
                {
                    sos = CreateChainsFromClauses(kb
                                                  .ConvertToClauses(refutationQuery));
                }

                foreach (Chain s in sos)
                {
                    s.SetProofStep(new ProofStepGoal(s));
                }
            }