示例#1
0
        /**
         * Utility method for outputting InferenceResults in a formatted textual
         * representation.
         *
         * @param ir
         *            an InferenceResult
         * @return a String representation of the InferenceResult.
         */
        public static String printInferenceResult(InferenceResult ir)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("InferenceResult.isTrue=" + ir.isTrue());
            sb.Append("\n");
            sb.Append("InferenceResult.isPossiblyFalse=" + ir.isPossiblyFalse());
            sb.Append("\n");
            sb.Append("InferenceResult.isUnknownDueToTimeout="
                      + ir.isUnknownDueToTimeout());
            sb.Append("\n");
            sb.Append("InferenceResult.isPartialResultDueToTimeout="
                      + ir.isPartialResultDueToTimeout());
            sb.Append("\n");
            sb.Append("InferenceResult.#Proofs=" + ir.getProofs().Count);
            sb.Append("\n");
            int          proofNo = 0;
            List <Proof> proofs  = ir.getProofs();

            foreach (Proof p in proofs)
            {
                proofNo++;
                sb.Append("InferenceResult.Proof#" + proofNo + "=\n"
                          + ProofPrinter.printProof(p));
            }
            return(sb.ToString());
        }
 public InferenceResultItem(InferenceResult<Cluster[]> result)
 {
     LogOdds = result.Evidence.LogOdds;
     ClusterCount = result.Result.Length;
     Summary = "Means: " + string.Join(", ", result.Result.Select(c => "[" + ToString(c.Means) + "]"));
     this.Clusters = result.Result;
 }
示例#3
0
 public void EnqueueLightData(InferenceResult data)
 {
     if (data != null)
     {
         workQueue.Enqueue(data);
     }
 }
示例#4
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("");
            }
        }
示例#5
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);
        }
示例#6
0
        public String predict(Example e)
        {
            String prediction = "~" + e.targetValue();

            if (null != currentBestHypothesis)
            {
                FOLExample etp = new FOLExample(folDSDomain, e, 0);
                kb.clear();
                kb.tell(etp.getDescription());
                kb.tell(currentBestHypothesis.getHypothesis());
                InferenceResult ir = kb.ask(etp.getClassification());
                if (ir.isTrue())
                {
                    if (trueGoalValue.Equals(e.targetValue()))
                    {
                        prediction = e.targetValue();
                    }
                }
                else if (ir.isPossiblyFalse() || ir.isUnknownDueToTimeout())
                {
                    if (!trueGoalValue.Equals(e.targetValue()))
                    {
                        prediction = e.targetValue();
                    }
                }
            }

            return(prediction);
        }
        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 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());
            }
        }
示例#9
0
        public InferenceResult ask(Sentence query)
        {
            // Want to standardize apart the query to ensure
            // it does not clash with any of the sentences
            // in the database
            StandardizeApartResult saResult = _standardizeApart.standardizeApart(query, queryIndexical);

            // Need to map the result variables (as they are standardized apart)
            // to the original queries variables so that the caller can easily
            // understand and use the returned set of substitutions
            InferenceResult infResult = getInferenceProcedure().ask(this, saResult.getStandardized());

            foreach (Proof p in infResult.getProofs())
            {
                IMap <Variable, Term> im = p.getAnswerBindings();
                IMap <Variable, Term> em = CollectionFactory.CreateInsertionOrderedMap <Variable, Term>();
                foreach (Variable rev in saResult.getReverseSubstitution().GetKeys())
                {
                    em.Put((Variable)saResult.getReverseSubstitution().Get(rev), im.Get(rev));
                }
                p.replaceAnswerBindings(em);
            }

            return(infResult);
        }
        /// <summary>
        /// Auto-detect purpose for the data view columns.
        /// </summary>
        /// <param name="env">The host environment to use.</param>
        /// <param name="data">The data to use for inference.</param>
        /// <param name="columnIndices">Indices of columns that we're interested in.</param>
        /// <param name="args">Additional arguments to inference.</param>
        /// <returns>The result includes the array of auto-detected column purposes.</returns>
        public static InferenceResult InferPurposes(IHostEnvironment env, IDataView data, IEnumerable <int> columnIndices, Arguments args)
        {
            Contracts.CheckValue(env, nameof(env));
            var host = env.Register("InferPurposes");

            host.CheckValue(data, nameof(data));
            host.CheckValue(columnIndices, nameof(columnIndices));

            InferenceResult result;

            using (var ch = host.Start("InferPurposes"))
            {
                var takenData = data.Take(args.MaxRowsToRead);
                var cols      = columnIndices.Select(x => new IntermediateColumn(takenData, x)).ToArray();
                data = takenData;

                foreach (var expert in GetExperts())
                {
                    using (var expertChannel = host.Start(expert.GetType().ToString()))
                    {
                        expert.Apply(expertChannel, cols);
                        expertChannel.Done();
                    }
                }

                ch.Check(cols.All(x => x.IsPurposeSuggested), "Purpose inference must be conclusive");

                result = new InferenceResult(cols.Select(x => x.GetColumn()).ToArray());

                ch.Info("Automatic purpose inference complete");
                ch.Done();
            }
            return(result);
        }
        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());
            }
        }
示例#12
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("");
            }
        }
        /**
         * Utility method for outputting InferenceResults in a formatted textual
         * representation.
         * 
         * @param ir
         *            an InferenceResult
         * @return a String representation of the InferenceResult.
         */
        public static String printInferenceResult(InferenceResult ir) {
		StringBuilder sb = new StringBuilder();

		sb.Append("InferenceResult.isTrue=" + ir.isTrue());
		sb.Append("\n");
		sb.Append("InferenceResult.isPossiblyFalse=" + ir.isPossiblyFalse());
		sb.Append("\n");
		sb.Append("InferenceResult.isUnknownDueToTimeout="
				+ ir.isUnknownDueToTimeout());
		sb.Append("\n");
		sb.Append("InferenceResult.isPartialResultDueToTimeout="
				+ ir.isPartialResultDueToTimeout());
		sb.Append("\n");
		sb.Append("InferenceResult.#Proofs=" + ir.getProofs().Count);
		sb.Append("\n");
		int proofNo = 0;
        List<Proof.Proof> proofs = ir.getProofs();
		foreach (Proof.Proof p in proofs) {
			proofNo++;
			sb.Append("InferenceResult.Proof#" + proofNo + "=\n"
					+ ProofPrinter.printProof(p));
		}

		return sb.ToString();
	}
        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());
            }
        }
示例#15
0
        public InferenceResult ask(Sentence aQuery)
        {
            // Want to standardize apart the query to ensure
            // it does not clash with any of the sentences
            // in the database
            StandardizeApartResult saResult = _standardizeApart.standardizeApart(
                aQuery, queryIndexical);

            // Need to map the result variables (as they are standardized apart)
            // to the original queries variables so that the caller can easily
            // understand and use the returned set of substitutions
            InferenceResult infResult = getInferenceProcedure().ask(this,
                                                                    saResult.getStandardized());
            List <Proof> proofs = infResult.getProofs();

            foreach (Proof p in proofs)
            {
                Dictionary <Variable, Term> im = p.getAnswerBindings();
                Dictionary <Variable, Term> em = new Dictionary <Variable, Term>();
                foreach (Variable rev in saResult.getReverseSubstitution().Keys)
                {
                    Term toInsert = im.ContainsKey(rev) ? im[rev] : null;
                    em.Add((Variable)saResult.getReverseSubstitution()[rev], toInsert);
                }
                p.replaceAnswerBindings(em);
            }
            return(infResult);
        }
示例#16
0
            public InferenceResult <TVar, TInterval> Join(InferenceResult <TVar, TInterval> that)
            {
                if (IsBottom)
                {
                    return(that);
                }
                if (that.IsBottom)
                {
                    return(this);
                }

                var result = Empty;

                foreach (var var in Constraints.Keys)
                {
                    var leftContraints = Constraints[var];
                    if (leftContraints == null)
                    {
                        continue;
                    }

                    // tops are not included
                    Sequence <TInterval> rightConstraints;
                    if (that.Constraints.TryGetValue(var, out rightConstraints) && rightConstraints != null)
                    {
                        var intv = leftContraints.Head.Join(rightConstraints.Head);
                        if (!intv.IsTop)
                        {
                            result.AddConstraintFor(var, intv);
                        }
                    }
                }

                return(result);
            }
示例#17
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);
            }
        }
示例#18
0
 public void stepFinished(ISet <Clause> clauses, InferenceResult result)
 {
     System.Console.WriteLine("Total # Pairs of Clauses Considered:" + noPairsConsidered);
     System.Console.WriteLine("Total # Pairs of Clauses Resolved  :" + noPairsResolved);
     noPairsConsidered = 0;
     noPairsResolved   = 0;
     maxClauseSizeSeen = 0;
 }
示例#19
0
 void FixedUpdate()
 {
     if (workQueue.Count > 0)
     {
         InferenceResult data = workQueue.Dequeue();
         CoordinateMapping(data);
     }
 }
		public void stepFinished(Set<Clause> clauses, InferenceResult result) {
			System.Console.WriteLine("Total # Pairs of Clauses Considered:"
					+ noPairsConsidered);
			System.Console.WriteLine("Total # Pairs of Clauses Resolved  :"
					+ noPairsResolved);
			noPairsConsidered = 0;
			noPairsResolved = 0;
			maxClauseSizeSeen = 0;
		}
示例#21
0
        public List <string> GetProof(InferenceResult result)
        {
            var      toReturn = new List <string>();
            Iterator terator  = result.getProofs().iterator();

            while (terator.hasNext())
            {
                toReturn.AddRange(ProofPrinter.printProof((Proof)terator.next()).Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries));
            }
            return(toReturn);
        }
        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);
        }
        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());
        }
        /// <summary>
        /// Auto-detect purpose for the data view columns.
        /// </summary>
        /// <param name="env">The host environment to use.</param>
        /// <param name="data">The data to use for inference.</param>
        /// <param name="columnIndices">Indices of columns that we're interested in.</param>
        /// <param name="args">Additional arguments to inference.</param>
        /// <param name="dataRoles">(Optional) User defined Role mappings for data.</param>
        /// <returns>The result includes the array of auto-detected column purposes.</returns>
        public static InferenceResult InferPurposes(IHostEnvironment env, IDataView data, IEnumerable <int> columnIndices, Arguments args,
                                                    RoleMappedData dataRoles = null)
        {
            Contracts.CheckValue(env, nameof(env));
            var host = env.Register("InferPurposes");

            host.CheckValue(data, nameof(data));
            host.CheckValue(columnIndices, nameof(columnIndices));

            InferenceResult result;

            using (var ch = host.Start("InferPurposes"))
            {
                var takenData = data.Take(args.MaxRowsToRead);
                var cols      = columnIndices.Select(x => new IntermediateColumn(takenData, x)).ToList();
                data = takenData;

                if (dataRoles != null)
                {
                    var items = dataRoles.Schema.GetColumnRoles();
                    foreach (var item in items)
                    {
                        Enum.TryParse(item.Key.Value, out ColumnPurpose purpose);
                        var col = cols.Find(x => x.ColumnName == item.Value.Name);
                        col.SuggestedPurpose = purpose;
                    }
                }

                foreach (var expert in GetExperts())
                {
                    using (var expertChannel = host.Start(expert.GetType().ToString()))
                    {
                        expert.Apply(expertChannel, cols.ToArray());
                        expertChannel.Done();
                    }
                }

                ch.Check(cols.All(x => x.IsPurposeSuggested), "Purpose inference must be conclusive");

                result = new InferenceResult(cols.Select(x => x.GetColumn()).ToArray());

                ch.Info("Automatic purpose inference complete");
                ch.Done();
            }
            return(result);
        }
        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")));
        }
示例#26
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);
        }
示例#27
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);
        }
示例#28
0
    void CoordinateMapping(InferenceResult data)
    {
        if (RayCameraPrefab == null)
        {
            Debug.Log("Where is the ray camera prefab?");
            return;
        }

        GameObject rayCameraObject = Instantiate(RayCameraPrefab, data.HMDPosition, Quaternion.Euler(data.HMDRotation), this.transform);
        Camera     rayCamera       = rayCameraObject.GetComponent <Camera>() as Camera;

        rayCamera.aspect        = Camera.main.aspect;
        rayCamera.nearClipPlane = Camera.main.nearClipPlane;
        rayCamera.farClipPlane  = Camera.main.farClipPlane;

        if (rayCamera == null)
        {
            Debug.Log("ray camera hasn't camera component.");
            return;
        }


        foreach (DetectionBox box in data.DetectionBoxes)
        {
            // draw ray
            Vector3    boxCenter = GetBoxCenter(box.min, box.max);
            RaycastHit hit;
            Ray        ray = rayCamera.ScreenPointToRay(boxCenter);

            // create light
            if (Physics.Raycast(ray, out hit))
            {
                // in case of a collision with already mapped light's collider
                if (hit.collider.CompareTag(TAG_LIGHT))
                {
                    continue;
                }

                GameObject lightObject = LightManager.Instance.CreateLight(box, hit.point, debug: true);
            }
        }
        Destroy(rayCameraObject);
    }
示例#29
0
            static void LessThanRefinement <TEnv, TVar, TExpr, TInterval>
                (Rational successor, TEnv env,
                TInterval leftIntv, TInterval rightIntv,
                TVar leftVar, TVar rightVar,
                ref InferenceResult <TVar, TInterval> result)
                where TEnv : IIntervalEnvironment <TVar, TExpr, TInterval, Rational>
                where TInterval : IntervalBase <TInterval, Rational>
                where TVar : IEquatable <TVar>
            {
                TInterval refined;

                if (TryRefineKLessThanRight <TEnv, TVar, TExpr, TInterval> (leftIntv, rightVar, successor, env, out refined))
                {
                    result = result.AddConstraintFor(rightVar, refined);
                }
                if (TryRefineLessThan <TEnv, TVar, TExpr, TInterval> (leftVar, rightIntv, env, out refined))
                {
                    result = result.AddConstraintFor(leftVar, refined);
                }
            }
示例#30
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);
        }
示例#31
0
            public static void NotEqual <TEnv, TVar, TExpr, TInterval>
                (TExpr left, TExpr right, IExpressionDecoder <TVar, TExpr> decoder, TEnv env, out InferenceResult <TVar, TInterval> resultLeft,
                out InferenceResult <TVar, TInterval> resultRight) where TInterval : IntervalBase <TInterval, Rational>
                where TEnv : IIntervalEnvironment <TVar, TExpr, TInterval, Rational>
                where TVar : IEquatable <TVar>
            {
                resultLeft  = InferenceResult <TVar, TInterval> .Empty;
                resultRight = InferenceResult <TVar, TInterval> .Empty;

                var leftIntv  = env.Eval(left);
                var rightIntv = env.Eval(right);

                var leftVar  = decoder.UnderlyingVariable(left);
                var rightVar = decoder.UnderlyingVariable(right);

                var successor = IsFloat(left, decoder) || IsFloat(right, decoder) ? Rational.Zero : Rational.One;

                // l != r <==> l < r && r < l
                LessThanRefinement <TEnv, TVar, TExpr, TInterval> (successor, env, leftIntv, rightIntv, leftVar, rightVar, ref resultLeft);
                LessThanRefinement <TEnv, TVar, TExpr, TInterval> (successor, env, rightIntv, leftIntv, rightVar, leftVar, ref resultRight);
            }
示例#32
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("");
            }
        }
示例#33
0
    InferenceResult ParseData(string data)
    {
        string[] parts;
        string[] hmdPositionRaw;
        string[] hmdRotationRaw;
        string[] boxes;

        Vector3 hmdPosition, hmdRotation;

        DetectionBox[]  detectionBoxes;
        InferenceResult result = null;

        try
        {
            parts = data.Split(':');

            hmdPositionRaw = parts[0].Split('|');
            hmdPosition    = RawToVector3(hmdPositionRaw);

            hmdRotationRaw = parts[1].Split('|');
            hmdRotation    = RawToVector3(hmdRotationRaw);

            boxes = parts[2].Split('\\');

            detectionBoxes = new DetectionBox[boxes.Length];
            for (int i = 0; i < boxes.Length; i++)
            {
                string[] boxData = boxes[i].Split('|');
                detectionBoxes[i] = new DetectionBox(boxData);
            }

            result = new InferenceResult(hmdPosition, hmdRotation, detectionBoxes);
        }
        catch
        {
            result = null;
        }

        return(result);
    }