protected void testFullFOLKBLovesAnimalQueryNotKillsJackTunaSucceeds(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"));
            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().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());
            }
        }
Beispiel #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));
                }
            }
Beispiel #3
0
        private void constructFOLEg()
        {
            ithExampleConstant = new Constant(folDSDomain.getExampleConstant(egNo));

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

            terms.Add(ithExampleConstant);
            // Create the classification sentence
            classification = new Predicate(folDSDomain.getGoalPredicateName(), terms);
            if (!example.getAttributeValueAsString(
                    folDSDomain.getDataSetTargetName()).Equals(folDSDomain.getTrueGoalValue()))
            {
                // if not true then needs to be a Not sentence
                classification = new NotSentence(classification);
            }

            // Create the description sentence
            ICollection <Sentence> descParts = CollectionFactory.CreateQueue <Sentence>();

            foreach (string dname in folDSDomain.getDescriptionDataSetNames())
            {
                string foldDName = folDSDomain.getFOLName(dname);
                terms = CollectionFactory.CreateQueue <Term>();
                terms.Add(ithExampleConstant);
                // If multivalued becomes a two place predicate
                // e.g: Patrons(X1, Some)
                // otherwise: Hungry(X1) or ~ Hungry(X1)
                // see pg 769 of AIMA
                Sentence part = null;
                if (folDSDomain.isMultivalued(dname))
                {
                    terms.Add(new Constant(folDSDomain.getFOLName(example.getAttributeValueAsString(dname))));
                    part = new Predicate(foldDName, terms);
                }
                else
                {
                    part = new Predicate(foldDName, terms);
                    // Need to determine if false
                    if (!folDSDomain.getTrueGoalValue().Equals(
                            example.getAttributeValueAsString(dname)))
                    {
                        part = new NotSentence(part);
                    }
                }
                descParts.Add(part);
            }
            if (descParts.Size() == 1)
            {
                description = descParts.Get(0);
            }
            else if (descParts.Size() > 1)
            {
                description = new ConnectedSentence(Connectors.AND, descParts.Get(0), descParts.Get(1));
                for (int i = 2; i < descParts.Size(); ++i)
                {
                    description = new ConnectedSentence(Connectors.AND, description, descParts.Get(i));
                }
            }
        }
Beispiel #4
0
        public object visitNotSentence(NotSentence notSentence, object arg)
        {
            // CNF requires NOT (~) to appear only in literals, so we 'move ~
            // inwards' by repeated application of the following equivalences:
            Sentence negated = notSentence.getNegated();

            // ~(~alpha) equivalent to alpha (double negation elimination)
            if (negated is NotSentence)
            {
                return(((NotSentence)negated).getNegated().accept(this, arg));
            }

            if (negated is ConnectedSentence)
            {
                ConnectedSentence negConnected = (ConnectedSentence)negated;
                Sentence          alpha        = negConnected.getFirst();
                Sentence          beta         = negConnected.getSecond();
                // ~(alpha ^ beta) equivalent to (~alpha V ~beta) (De Morgan)
                if (Connectors.isAND(negConnected.getConnector()))
                {
                    // I need to ensure the ~s are moved in deeper
                    Sentence notAlpha = (Sentence)(new NotSentence(alpha)).accept(this, arg);
                    Sentence notBeta  = (Sentence)(new NotSentence(beta)).accept(this, arg);
                    return(new ConnectedSentence(Connectors.OR, notAlpha, notBeta));
                }

                // ~(alpha V beta) equivalent to (~alpha ^ ~beta) (De Morgan)
                if (Connectors.isOR(negConnected.getConnector()))
                {
                    // I need to ensure the ~s are moved in deeper
                    Sentence notAlpha = (Sentence)(new NotSentence(alpha)).accept(this, arg);
                    Sentence notBeta  = (Sentence)(new NotSentence(beta)).accept(this, arg);
                    return(new ConnectedSentence(Connectors.AND, notAlpha, notBeta));
                }
            }

            // in addition, rules for negated quantifiers:
            if (negated is QuantifiedSentence)
            {
                QuantifiedSentence negQuantified = (QuantifiedSentence)negated;
                // I need to ensure the ~ is moved in deeper
                Sentence notP = (Sentence)(new NotSentence(negQuantified.getQuantified())).accept(this, arg);

                // ~FORALL x p becomes EXISTS x ~p
                if (Quantifiers.isFORALL(negQuantified.getQuantifier()))
                {
                    return(new QuantifiedSentence(Quantifiers.EXISTS, negQuantified.getVariables(), notP));
                }

                // ~EXISTS x p becomes FORALL x ~p
                if (Quantifiers.isEXISTS(negQuantified.getQuantifier()))
                {
                    return(new QuantifiedSentence(Quantifiers.FORALL, negQuantified.getVariables(), notP));
                }
            }

            return(new NotSentence((Sentence)negated.accept(this, arg)));
        }
Beispiel #5
0
        private void ConstructFOLEg()
        {
            ithExampleConstant = new Constant(folDSDomain.GetExampleConstant(egNo));

            var terms = new List <ITerm>();

            terms.Add(ithExampleConstant);
            // Create the classification sentence
            classification = new Predicate(folDSDomain.GetGoalPredicateName(), terms);
            if (!example.GetAttributeValueAsString(folDSDomain.GetDataSetTargetName()).Equals(folDSDomain.TrueGoalValue))
            {
                // if not true then needs to be a Not sentence
                classification = new NotSentence(classification);
            }

            // Create the description sentence
            var descParts = new List <ISentence>();

            foreach (String dname in folDSDomain.DescriptionDataSetNames)
            {
                String foldDName = folDSDomain.GetFOLName(dname);
                terms = new List <ITerm>();
                terms.Add(ithExampleConstant);
                // If multivalued becomes a two place predicate
                // e.g: Patrons(X1, Some)
                // otherwise: Hungry(X1) or ~ Hungry(X1)
                // see pg 769 of AIMA
                ISentence part = null;
                if (this.folDSDomain.IsMultivalued(dname))
                {
                    terms.Add(new Constant(this.folDSDomain.GetFOLName(this.example.GetAttributeValueAsString(dname))));
                    part = new Predicate(foldDName, terms);
                }
                else
                {
                    part = new Predicate(foldDName, terms);

                    // Need to determine if false
                    if (!this.folDSDomain.TrueGoalValue.Equals(this.example.GetAttributeValueAsString(dname)))
                    {
                        part = new NotSentence(part);
                    }
                }
                descParts.Add(part);
            }
            if (descParts.Count == 1)
            {
                this.description = descParts[0];
            }
            else if (descParts.Count > 1)
            {
                this.description = new ConnectedSentence(Connectors.And, descParts[0], descParts[1]);
                for (int i = 2; i < descParts.Count; i++)
                {
                    description = new ConnectedSentence(Connectors.And, description, descParts[i]);
                }
            }
        }
Beispiel #6
0
        public void testNotSentence()
        {
            NotSentence ns = (NotSentence)parser
                             .parse("NOT BrotherOf(John) = EnemyOf(Saladin)");

            Assert.AreEqual(ns.getNegated().ToString(), (new TermEquality(
                                                             getBrotherOfFunction(new Constant("John")),
                                                             getEnemyOfFunction())).ToString());
        }
Beispiel #7
0
        public Object visitNotSentence(NotSentence sentence, Object arg)
        {
            ArgData ad = (ArgData)arg;

            // Indicate that the enclosed predicate is negated
            ad.negated = true;
            sentence.getNegated().accept(this, arg);
            ad.negated = false;

            return(sentence);
        }
Beispiel #8
0
        public object VisitNotSentence(NotSentence sentence, object arg)
        {
            ArgData ad = (ArgData)arg;

            // Indicate that the enclosed predicate is negated
            ad.Negated = true;
            sentence.Negated.Accept(this, arg);
            ad.Negated = false;

            return(sentence);
        }
            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));
                }
            }
            public AnswerHandler(FOLKnowledgeBase kb, Sentence aQuery,
                                 long maxQueryTime, FOLModelElimination folModelElimination)
            {
                finishTime = System.DateTime.UtcNow.Ticks + maxQueryTime;

                Sentence 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
                                                                .getAtomicSentence());

                // Create the Set of Support based on the Query.
                if (answerLiteralVariables.Count > 0)
                {
                    Sentence refutationQueryWithAnswer = new ConnectedSentence(
                        Connectors.OR, refutationQuery, (Sentence)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));
                }
            }
Beispiel #11
0
        public object VisitNotSentence(NotSentence notSentence, object arg)
        {
            // CNF requires NOT (~) to appear only in literals, so we 'move ~
            // inwards' by repeated application of the following equivalences:
            ISentence negated = notSentence.Negated;

            // ~(~alpha) equivalent to alpha (double negation elimination)
            if (negated is NotSentence)
            {
                return(((NotSentence)negated).Negated.Accept(this, arg));
            }

            if (negated is ConnectedSentence)
            {
                ConnectedSentence negConnected = (ConnectedSentence)negated;
                ISentence         alpha        = negConnected.First;
                ISentence         beta         = negConnected.Second;
                // ~(alpha ^ beta) equivalent to (~alpha V ~beta) (De Morgan)
                if (Connectors.IsAnd(negConnected.Connector))
                {
                    // I need to ensure the ~s are moved in deeper
                    ISentence notAlpha = (ISentence)(new NotSentence(alpha)).Accept(
                        this, arg);
                    ISentence notBeta = (ISentence)(new NotSentence(beta)).Accept(
                        this, arg);
                    return(new ConnectedSentence(Connectors.Or, notAlpha, notBeta));
                }

                // ~(alpha V beta) equivalent to (~alpha ^ ~beta) (De Morgan)
                if (Connectors.IsOr(negConnected.Connector))
                {
                    // I need to ensure the ~s are moved in deeper
                    ISentence notAlpha = (ISentence)(new NotSentence(alpha)).Accept(
                        this, arg);
                    ISentence notBeta = (ISentence)(new NotSentence(beta)).Accept(
                        this, arg);
                    return(new ConnectedSentence(Connectors.And, notAlpha, notBeta));
                }
            }

            // in addition, rules for negated quantifiers:
            if (negated is QuantifiedSentence)
            {
                QuantifiedSentence negQuantified = (QuantifiedSentence)negated;
                // I need to ensure the ~ is moved in deeper
                ISentence notP = (ISentence)(new NotSentence(negQuantified
                                                             .Quantified)).Accept(this, arg);

                // ~ForAll x p becomes Exists x ~p
                if (Quantifiers.IsForall(negQuantified.Quantifier))
                {
                    return(new QuantifiedSentence(Quantifiers.Exists, negQuantified
                                                  .Variables, notP));
                }

                // ~Exists x p becomes ForAll x ~p
                if (Quantifiers.IsExists(negQuantified.Quantifier))
                {
                    return(new QuantifiedSentence(Quantifiers.ForAll, negQuantified
                                                  .Variables, notP));
                }
            }

            return(new NotSentence((ISentence)negated.Accept(this, arg)));
        }
Beispiel #12
0
        //
        // START-InferenceProcedure
        public InferenceResult ask(FOLKnowledgeBase KB, Sentence alpha)
        {
            // clauses <- the set of clauses in CNF representation of KB ^ ~alpha
            ISet <Clause> clauses = CollectionFactory.CreateSet <Clause>();

            foreach (Clause cIter in KB.getAllClauses())
            {
                Clause c = cIter;
                c = KB.standardizeApart(c);
                c.setStandardizedApartCheckNotRequired();
                clauses.AddAll(c.getFactors());
            }
            Sentence notAlpha = new NotSentence(alpha);
            // Want to use an answer literal to pull
            // query variables where necessary
            Literal         answerLiteral          = KB.createAnswerLiteral(notAlpha);
            ISet <Variable> answerLiteralVariables = KB.collectAllVariables(answerLiteral.getAtomicSentence());
            Clause          answerClause           = new Clause();

            if (answerLiteralVariables.Size() > 0)
            {
                Sentence notAlphaWithAnswer = new ConnectedSentence(Connectors.OR,
                                                                    notAlpha, answerLiteral.getAtomicSentence());
                foreach (Clause cIter in KB.convertToClauses(notAlphaWithAnswer))
                {
                    Clause c = cIter;
                    c = KB.standardizeApart(c);
                    c.setProofStep(new ProofStepGoal(c));
                    c.setStandardizedApartCheckNotRequired();
                    clauses.AddAll(c.getFactors());
                }

                answerClause.addLiteral(answerLiteral);
            }
            else
            {
                foreach (Clause cIter in KB.convertToClauses(notAlpha))
                {
                    Clause c = cIter;
                    c = KB.standardizeApart(c);
                    c.setProofStep(new ProofStepGoal(c));
                    c.setStandardizedApartCheckNotRequired();
                    clauses.AddAll(c.getFactors());
                }
            }

            TFMAnswerHandler ansHandler = new TFMAnswerHandler(answerLiteral,
                                                               answerLiteralVariables, answerClause, maxQueryTime);

            // new <- {}
            ISet <Clause> newClauses = CollectionFactory.CreateSet <Clause>();
            ISet <Clause> toAdd      = CollectionFactory.CreateSet <Clause>();
            // loop do
            int noOfPrevClauses = clauses.Size();

            do
            {
                if (null != tracer)
                {
                    tracer.stepStartWhile(clauses, clauses.Size(), newClauses.Size());
                }

                newClauses.Clear();

                // for each Ci, Cj in clauses do
                Clause[] clausesA = clauses.ToArray();

                // Basically, using the simple T)wo F)inger M)ethod here.
                for (int i = 0; i < clausesA.Length; i++)
                {
                    Clause cI = clausesA[i];
                    if (null != tracer)
                    {
                        tracer.stepOuterFor(cI);
                    }
                    for (int j = i; j < clausesA.Length; j++)
                    {
                        Clause cJ = clausesA[j];

                        if (null != tracer)
                        {
                            tracer.stepInnerFor(cI, cJ);
                        }

                        // resolvent <- FOL-RESOLVE(Ci, Cj)
                        ISet <Clause> resolvents = cI.binaryResolvents(cJ);

                        if (resolvents.Size() > 0)
                        {
                            toAdd.Clear();
                            // new <- new <UNION> resolvent
                            foreach (Clause rc in resolvents)
                            {
                                toAdd.AddAll(rc.getFactors());
                            }

                            if (null != tracer)
                            {
                                tracer.stepResolved(cI, cJ, toAdd);
                            }

                            ansHandler.checkForPossibleAnswers(toAdd);

                            if (ansHandler.isComplete())
                            {
                                break;
                            }

                            newClauses.AddAll(toAdd);
                        }

                        if (ansHandler.isComplete())
                        {
                            break;
                        }
                    }
                    if (ansHandler.isComplete())
                    {
                        break;
                    }
                }

                noOfPrevClauses = clauses.Size();

                // clauses <- clauses <UNION> new
                clauses.AddAll(newClauses);

                if (ansHandler.isComplete())
                {
                    break;
                }

                // if new is a <SUBSET> of clauses then finished
                // searching for an answer
                // (i.e. when they were added the # clauses
                // did not increase).
            } while (noOfPrevClauses < clauses.Size());

            if (null != tracer)
            {
                tracer.stepFinished(clauses, ansHandler);
            }

            return(ansHandler);
        }
Beispiel #13
0
 public object visitNotSentence(NotSentence sentence, object arg)
 {
     throw new IllegalStateException("visitNotSentence() should not be called.");
 }
Beispiel #14
0
 public Object visitNotSentence(NotSentence sentence, Object arg)
 {
     throw new InvalidOperationException("Should not be called");
 }
 public object VisitNotSentence(NotSentence sentence, object arg)
 {
     sentence.Negated.Accept(this, arg);
     return(sentence);
 }
Beispiel #16
0
 public Object visitNotSentence(NotSentence sentence, Object arg)
 {
     return(new NotSentence((Sentence)sentence.getNegated().accept(this,
                                                                   arg)));
 }
Beispiel #17
0
        // START-InferenceProcedure

        /**
         * <code>
         * function FOL-FC-ASK(KB, alpha) returns a substitution or false
         *   inputs: KB, the knowledge base, a set of first order definite clauses
         *           alpha, the query, an atomic sentence
         * </code>
         */
        public InferenceResult ask(FOLKnowledgeBase KB, Sentence query)
        {
            // Assertions on the type of queries this Inference procedure
            // supports
            if (!(query is AtomicSentence))
            {
                throw new ArgumentException(
                          "Only Atomic Queries are supported.");
            }

            FCAskAnswerHandler ansHandler = new FCAskAnswerHandler();

            Literal alpha = new Literal((AtomicSentence)query);

            // local variables: new, the new sentences inferred on each iteration
            List <Literal> newSentences = new List <Literal>();

            // Ensure query is not already a know fact before
            // attempting forward chaining.
            List <Dictionary <Variable, Term> > answers = KB.fetch(alpha);

            if (answers.Count > 0)
            {
                ansHandler.addProofStep(new ProofStepFoChAlreadyAFact(alpha));
                ansHandler.setAnswers(answers);
                return(ansHandler);
            }

            // repeat until new is empty
            do
            {
                // new <- {}
                newSentences.Clear();
                // for each rule in KB do
                // (p1 ^ ... ^ pn => q) <-STANDARDIZE-VARIABLES(rule)
                foreach (Clause impl in KB.getAllDefiniteClauseImplications())
                {
                    Clause impl2 = KB.standardizeApart(impl);
                    // for each theta such that SUBST(theta, p1 ^ ... ^ pn) =
                    // SUBST(theta, p'1 ^ ... ^ p'n)
                    // --- for some p'1,...,p'n in KB
                    foreach (Dictionary <Variable, Term> theta in KB.fetch(invert(new List <Literal>(impl2
                                                                                                     .getNegativeLiterals()))))
                    {
                        // q' <- SUBST(theta, q)
                        Literal qPrime = KB.subst(theta, impl.getPositiveLiterals()
                                                  [0]);
                        // if q' does not unify with some sentence already in KB or
                        // new then do
                        if (!KB.isRenaming(qPrime) &&
                            !KB.isRenaming(qPrime, newSentences))
                        {
                            // add q' to new
                            newSentences.Add(qPrime);
                            ansHandler.addProofStep(impl, qPrime, theta);
                            // theta <- UNIFY(q', alpha)
                            Dictionary <Variable, Term> theta2 = KB.unify(qPrime.getAtomicSentence(), alpha
                                                                          .getAtomicSentence());
                            // if theta is not fail then return theta
                            if (null != theta2)
                            {
                                foreach (Literal l in newSentences)
                                {
                                    Sentence s = null;
                                    if (l.isPositiveLiteral())
                                    {
                                        s = l.getAtomicSentence();
                                    }
                                    else
                                    {
                                        s = new NotSentence(l.getAtomicSentence());
                                    }
                                    KB.tell(s);
                                }
                                ansHandler.setAnswers(KB.fetch(alpha));
                                return(ansHandler);
                            }
                        }
                    }
                }
                // add new to KB
                foreach (Literal l in newSentences)
                {
                    Sentence s = null;
                    if (l.isPositiveLiteral())
                    {
                        s = l.getAtomicSentence();
                    }
                    else
                    {
                        s = new NotSentence(l.getAtomicSentence());
                    }
                    KB.tell(s);
                }
            } while (newSentences.Count > 0);
            // return false
            return(ansHandler);
        }
        public IInferenceResult Ask(FOLKnowledgeBase kb, ISentence alpha)
        {
            // clauses <- the set of clauses in CNF representation of KB ^ ~alpha
            ISet <Clause> clauses = new HashedSet <Clause>();

            foreach (Clause c in kb.GetAllClauses())
            {
                var standardizedC = kb.StandardizeApart(c);
                standardizedC.SetStandardizedApartCheckNotRequired();
                clauses.UnionWith(standardizedC.GetFactors());
            }
            ISentence notAlpha = new NotSentence(alpha);
            // Want to use an answer literal to pull
            // query variables where necessary
            Literal         answerLiteral          = kb.CreateAnswerLiteral(notAlpha);
            ISet <Variable> answerLiteralVariables = kb
                                                     .CollectAllVariables(answerLiteral.AtomicSentence);
            Clause answerClause = new Clause();

            if (answerLiteralVariables.Count > 0)
            {
                ISentence notAlphaWithAnswer = new ConnectedSentence(Connectors.Or,
                                                                     notAlpha, answerLiteral.AtomicSentence);
                foreach (Clause c in kb.ConvertToClauses(notAlphaWithAnswer))
                {
                    var standardizedC = kb.StandardizeApart(c);
                    standardizedC.SetProofStep(new ProofStepGoal(standardizedC));
                    standardizedC.SetStandardizedApartCheckNotRequired();
                    clauses.UnionWith(standardizedC.GetFactors());
                }

                answerClause.AddLiteral(answerLiteral);
            }
            else
            {
                foreach (Clause c in kb.ConvertToClauses(notAlpha))
                {
                    var standardizedC = kb.StandardizeApart(c);
                    standardizedC.SetProofStep(new ProofStepGoal(standardizedC));
                    standardizedC.SetStandardizedApartCheckNotRequired();
                    clauses.UnionWith(standardizedC.GetFactors());
                }
            }

            var ansHandler = new TFMAnswerHandler(answerLiteral,
                                                  answerLiteralVariables, answerClause, this.MaxQueryTime);

            // new <- {}
            ISet <Clause> newClauses = new HashedSet <Clause>();
            ISet <Clause> toAdd      = new HashedSet <Clause>();
            // loop do
            int noOfPrevClauses = clauses.Count;

            do
            {
                if (Tracer != null)
                {
                    Tracer.StepStartWhile(clauses, clauses.Count, newClauses
                                          .Count);
                }

                newClauses.Clear();

                // for each Ci, Cj in clauses do
                Clause[] clausesA = new Clause[clauses.Count];
                clausesA = clauses.ToArray();
                // Basically, using the simple T)wo F)inger M)ethod here.
                for (int i = 0; i < clausesA.Length; i++)
                {
                    Clause cI = clausesA[i];
                    if (null != Tracer)
                    {
                        Tracer.StepOuterFor(cI);
                    }
                    for (int j = i; j < clausesA.Length; j++)
                    {
                        Clause cJ = clausesA[j];

                        if (null != Tracer)
                        {
                            Tracer.StepInnerFor(cI, cJ);
                        }

                        // resolvent <- FOL-RESOLVE(Ci, Cj)
                        ISet <Clause> resolvents = cI.BinaryResolvents(cJ);

                        if (resolvents.Count > 0)
                        {
                            toAdd.Clear();
                            // new <- new <UNION> resolvent
                            foreach (Clause rc in resolvents)
                            {
                                toAdd.UnionWith(rc.GetFactors());
                            }

                            if (null != Tracer)
                            {
                                Tracer.StepResolved(cI, cJ, toAdd);
                            }

                            ansHandler.CheckForPossibleAnswers(toAdd);

                            if (ansHandler.IsComplete())
                            {
                                break;
                            }

                            newClauses.UnionWith(toAdd);
                        }

                        if (ansHandler.IsComplete())
                        {
                            break;
                        }
                    }
                    if (ansHandler.IsComplete())
                    {
                        break;
                    }
                }

                noOfPrevClauses = clauses.Count;

                // clauses <- clauses <UNION> new
                clauses.UnionWith(newClauses);

                if (ansHandler.IsComplete())
                {
                    break;
                }

                // if new is a <SUBSET> of clauses then finished
                // searching for an answer
                // (i.e. when they were added the # clauses
                // did not increase).
            } while (noOfPrevClauses < clauses.Count);

            if (null != Tracer)
            {
                Tracer.StepFinished(clauses, ansHandler);
            }

            return(ansHandler);
        }
Beispiel #19
0
        public object VisitNotSentence(NotSentence notSentence, object arg)
        {
            ISentence negated = notSentence.Negated;

            return(new NotSentence((ISentence)negated.Accept(this, arg)));
        }
 public object VisitNotSentence(NotSentence sentence, object arg)
 {
     throw new InvalidOperationException(
               "visitNotSentence() should not be called.");
 }
Beispiel #21
0
 public object visitNotSentence(NotSentence sentence, object arg)
 {
     sentence.getNegated().accept(this, arg);
     return(sentence);
 }
Beispiel #22
0
        public IInferenceResult Ask(FOLKnowledgeBase KB, ISentence alpha) 
        {
            ISet<Clause> sos = new HashedSet<Clause>();
            ISet<Clause> usable = new HashedSet<Clause>();

            // Usable set will be the set of clauses in the KB,
            // are assuming this is satisfiable as using the
            // ISet of Support strategy.
            //foreach (var standardizedC in KB.GetAllClauses().Select(c => KB.StandardizeApart(c)))
            foreach (var standardizedC in KB.GetAllClauses())
            {
                standardizedC.SetStandardizedApartCheckNotRequired();
                usable.UnionWith(standardizedC.GetFactors());
            }

            // Ensure reflexivity axiom is added to usable if using paramodulation.
            if (this.UseParamodulation) 
            {
                // Reflexivity Axiom: x = x
                var reflexivityAxiom = new TermEquality(new Variable("x"), new Variable("x"));
                var reflexivityClause = new Clause();
                reflexivityClause.AddLiteral(new Literal(reflexivityAxiom));
                reflexivityClause = KB.StandardizeApart(reflexivityClause);
                reflexivityClause.SetStandardizedApartCheckNotRequired();
                usable.Add(reflexivityClause);
            }

            ISentence notAlpha = new NotSentence(alpha);
            // Want to use an answer literal to pull
            // query variables where necessary
            var answerLiteral = KB.CreateAnswerLiteral(notAlpha);
            var answerLiteralVariables = KB
                    .CollectAllVariables(answerLiteral.AtomicSentence);
            var answerClause = new Clause();

            if (answerLiteralVariables.Count > 0) {
                ISentence notAlphaWithAnswer = new ConnectedSentence(Connectors.Or,
                        notAlpha, answerLiteral.AtomicSentence);
               // foreach (var standardizedC in
              //      KB.ConvertToClauses(notAlphaWithAnswer).Select(KB.StandardizeApart))
                  foreach (var standardizedC in
                      KB.ConvertToClauses(notAlphaWithAnswer))
                   {
                       Clause c = KB.StandardizeApart(standardizedC);
                       c.SetProofStep(new ProofStepGoal(c));
                       c.SetStandardizedApartCheckNotRequired();
                       sos.UnionWith(c.GetFactors());
                   }

                answerClause.AddLiteral(answerLiteral);
            } 
            else 
            {
                //foreach (var standardizedC in
                //    KB.ConvertToClauses(notAlpha).Select(KB.StandardizeApart)) 
                foreach (var standardizedC in
                    KB.ConvertToClauses(notAlpha))
                {
                    Clause c = KB.StandardizeApart(standardizedC);
                    c.SetProofStep(new ProofStepGoal(c));
                    c.SetStandardizedApartCheckNotRequired();
                    sos.UnionWith(standardizedC.GetFactors());
                }
            }

            // Ensure all subsumed clauses are removed
            usable.ExceptWith(SubsumptionElimination.FindSubsumedClauses(usable));
            sos.ExceptWith(SubsumptionElimination.FindSubsumedClauses(sos));

            var ansHandler = new OTTERAnswerHandler(answerLiteral,
                    answerLiteralVariables, answerClause, this.MaxQueryTime);

            var idxdClauses = new IndexedClauses(LightestClauseHeuristic, sos, usable);

            return this.Otter(ansHandler, idxdClauses, sos, usable);
        }
Beispiel #23
0
 public Object visitNotSentence(NotSentence sentence, Object arg)
 {
     throw new NotImplementedException(
               "visitNotSentence() should not be called.");
 }
Beispiel #24
0
        public Object visitNotSentence(NotSentence notSentence, Object arg)
        {
            Sentence negated = notSentence.getNegated();

            return(new NotSentence((Sentence)negated.accept(this, arg)));
        }
        // START-InferenceProcedure
        public InferenceResult ask(FOLKnowledgeBase KB, Sentence alpha)
        {
            List <Clause> sos    = new List <Clause>();
            List <Clause> usable = new List <Clause>();

            // Usable set will be the set of clauses in the KB,
            // are assuming this is satisfiable as using the
            // Set of Support strategy.
            foreach (Clause c in KB.getAllClauses())
            {
                Clause c2 = KB.standardizeApart(c);
                c2.setStandardizedApartCheckNotRequired();
                usable.AddRange(c2.getFactors());
            }

            // Ensure reflexivity axiom is added to usable if using paramodulation.
            if (isUseParamodulation())
            {
                // Reflexivity Axiom: x = x
                TermEquality reflexivityAxiom = new TermEquality(new Variable("x"),
                                                                 new Variable("x"));
                Clause reflexivityClause = new Clause();
                reflexivityClause.addLiteral(new Literal(reflexivityAxiom));
                reflexivityClause = KB.standardizeApart(reflexivityClause);
                reflexivityClause.setStandardizedApartCheckNotRequired();
                usable.Add(reflexivityClause);
            }

            Sentence notAlpha = new NotSentence(alpha);
            // Want to use an answer literal to pull
            // query variables where necessary
            Literal         answerLiteral          = KB.createAnswerLiteral(notAlpha);
            List <Variable> answerLiteralVariables = KB
                                                     .collectAllVariables(answerLiteral.getAtomicSentence());
            Clause answerClause = new Clause();

            if (answerLiteralVariables.Count > 0)
            {
                Sentence notAlphaWithAnswer = new ConnectedSentence(Connectors.OR,
                                                                    notAlpha, answerLiteral.getAtomicSentence());
                foreach (Clause c in KB.convertToClauses(notAlphaWithAnswer))
                {
                    Clause c2 = KB.standardizeApart(c);
                    c2.setProofStep(new ProofStepGoal(c2));
                    c2.setStandardizedApartCheckNotRequired();
                    sos.AddRange(c2.getFactors());
                }

                answerClause.addLiteral(answerLiteral);
            }
            else
            {
                foreach (Clause c in KB.convertToClauses(notAlpha))
                {
                    Clause c2 = KB.standardizeApart(c);
                    c2.setProofStep(new ProofStepGoal(c2));
                    c2.setStandardizedApartCheckNotRequired();
                    sos.AddRange(c2.getFactors());
                }
            }

            // Ensure all subsumed clauses are removed
            foreach (Clause c in SubsumptionElimination.findSubsumedClauses(usable))
            {
                usable.Remove(c);
            }
            foreach (Clause c in SubsumptionElimination.findSubsumedClauses(sos))
            {
                sos.Remove(c);
            }

            OTTERAnswerHandler ansHandler = new OTTERAnswerHandler(answerLiteral,
                                                                   answerLiteralVariables, answerClause, maxQueryTime);

            IndexedClauses idxdClauses = new IndexedClauses(
                getLightestClauseHeuristic(), sos, usable);

            return(otter(ansHandler, idxdClauses, sos, usable));
        }
Beispiel #26
0
 public object VisitNotSentence(NotSentence sentence, object arg)
 {
     return(new NotSentence((ISentence)sentence.Negated.Accept(this, arg)));
 }