Inheritance: Sentence
Example #1
0
        // END-Sentence
        //

        public override bool Equals(Object o)
        {
            if (this == o)
            {
                return(true);
            }
            if ((o == null) || !(o is NotSentence))
            {
                return(false);
            }
            NotSentence ns = (NotSentence)o;

            return(ns.negated.Equals(negated));
        }
        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);
            }
        }
Example #3
0
	//
	// PRIVATE METHODS
	//
	private void constructFOLEg() {
		ithExampleConstant = new Constant(folDSDomain.getExampleConstant(egNo));

		List<Term> terms = new List<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
		List<Sentence> descParts = new List<Sentence>();
		foreach (String dname in folDSDomain.getDescriptionDataSetNames()) {
			String foldDName = folDSDomain.getFOLName(dname);
			terms = new List<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.Count == 1) {
			description = descParts[0];
		} else if (descParts.Count > 1) {
			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]);
			}
		}
	}
 public Object visitNotSentence(NotSentence sentence, Object arg)
 {
     sentence.getNegated().accept(this, arg);
     return arg;
 }
Example #5
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;
        }
Example #6
0
 public Object visitNotSentence(NotSentence sentence, Object arg)
 {
     return new NotSentence((Sentence)sentence.getNegated().accept(this,
             arg));
 }
Example #7
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));
        }
Example #8
0
        public Object visitNotSentence(NotSentence notSentence, Object arg)
        {
            Sentence negated = notSentence.getNegated();

            return new NotSentence((Sentence)negated.accept(this, arg));
        }
            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));
                }
            }
        //
        // 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);
	}
Example #11
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;
        }
Example #12
0
 public Object visitNotSentence(NotSentence sentence, Object arg)
 {
     throw new NotImplementedException(
             "visitNotSentence() should not be called.");
 }
Example #13
0
        //
        // START-InferenceProcedure
        public InferenceResult ask(FOLKnowledgeBase KB, Sentence alpha)
        {

            // clauses <- the set of clauses in CNF representation of KB ^ ~alpha
            List<Clause> clauses = new List<Clause>();
            foreach (Clause c in KB.getAllClauses())
            {
                Clause c2 = KB.standardizeApart(c);
                c2.setStandardizedApartCheckNotRequired();
                clauses.AddRange(c2.getFactors());
            }
            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();
                    clauses.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();
                    clauses.AddRange(c2.getFactors());
                }
            }

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

            // new <- {}
            List<Clause> newClauses = new List<Clause>();
            List<Clause> toAdd = new List<Clause>();
            // loop do
            int noOfPrevClauses = clauses.Count;
            do
            {
                if (null != tracer)
                {
                    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)
                        List<Clause> resolvents = cI.binaryResolvents(cJ);

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

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

                            ansHandler.checkForPossibleAnswers(toAdd);

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

                            newClauses.AddRange(toAdd);
                        }

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

                noOfPrevClauses = clauses.Count;

                // clauses <- clauses <UNION> new
                clauses.AddRange(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;
        }