Пример #1
0
        public List <Symbol> getImpureSymbolsIn(Sentence sentence)
        {
            List <Symbol> allNegatives = getNegativeSymbolsIn(sentence);
            List <Symbol> allPositives = getPositiveSymbolsIn(sentence);

            return(SetOps.intersection(allPositives, allNegatives));
        }
Пример #2
0
        /**
         * Determine if the clause represents a tautology, of which the following
         * are examples:<br>
         *
         * <pre>
         * {..., True, ...}
         * {..., ~False, ...}
         * {..., P, ..., ~P, ...}
         * </pre>
         *
         * @return true if the clause represents a tautology, false otherwise.
         */
        public bool?isTautology()
        {
            if (cachedIsTautologyResult == null)
            {
                foreach (Literal l in literals)
                {
                    if (l.isAlwaysTrue())
                    {
                        // {..., True, ...} is a tautology.
                        // {..., ~False, ...} is a tautology
                        cachedIsTautologyResult = true;
                    }
                }
                // If we still don't know
                if (cachedIsTautologyResult == null)
                {
                    if (SetOps.intersection(cachedPositiveSymbols, cachedNegativeSymbols).Size() > 0)
                    {
                        // We have:
                        // P | ~P
                        // which is always true.
                        cachedIsTautologyResult = true;
                    }
                    else
                    {
                        cachedIsTautologyResult = false;
                    }
                }
            }

            return(cachedIsTautologyResult);
        }
Пример #3
0
        public ProbabilityTable pointwiseProductPOS(ProbabilityTable multiplier, params IRandomVariable[] prodVarOrder)
        {
            ProbabilityTable product = new ProbabilityTable(prodVarOrder);

            if (!product.randomVarInfo.GetKeys()
                .SequenceEqual(
                    SetOps.union(CollectionFactory.CreateSet <IRandomVariable>(randomVarInfo.GetKeys()), CollectionFactory.CreateSet <IRandomVariable>(multiplier.randomVarInfo.GetKeys()))))
            {
                throw new IllegalArgumentException("Specified list deatailing order of mulitplier is inconsistent.");
            }

            // If no variables in the product
            if (1 == product.getValues().Length)
            {
                product.getValues()[0] = getValues()[0] * multiplier.getValues()[0];
            }
            else
            {
                // Otherwise need to iterate through the product
                // to calculate its values based on the terms.
                object[] term1Values        = new object[randomVarInfo.Size()];
                object[] term2Values        = new object[multiplier.randomVarInfo.Size()];
                ProbabilityTableIterator di = new ProbabilityTablecIteratorImpl3(term1Values,
                                                                                 term2Values, product, multiplier, this);
                product.iterateOverTable(di);
            }

            return(product);
        }
Пример #4
0
        public DynamicBayesNet(IBayesianNetwork priorNetwork,
                               IMap <IRandomVariable, IRandomVariable> X_0_to_X_1,
                               ISet <IRandomVariable> E_1, params INode[] rootNodes)
            : base(rootNodes)
        {
            foreach (var x0_x1 in X_0_to_X_1)
            {
                IRandomVariable x0 = x0_x1.GetKey();
                IRandomVariable x1 = x0_x1.GetValue();
                this.X_0.Add(x0);
                this.X_1.Add(x1);
                this.X_0_to_X_1.Put(x0, x1);
                this.X_1_to_X_0.Put(x1, x0);
            }
            this.E_1.AddAll(E_1);

            // Assert the X_0, X_1, and E_1 sets are of expected sizes
            ISet <IRandomVariable> combined = CollectionFactory.CreateSet <IRandomVariable>();

            combined.AddAll(X_0);
            combined.AddAll(X_1);
            combined.AddAll(E_1);
            if (SetOps.difference(CollectionFactory.CreateSet <IRandomVariable>(varToNodeMap.GetKeys()), combined).Size() != 0)
            {
                throw new IllegalArgumentException("X_0, X_1, and E_1 do not map correctly to the Nodes describing this Dynamic Bayesian Network.");
            }
            this.priorNetwork = priorNetwork;

            X_1_VariablesInTopologicalOrder.AddAll(GetVariablesInTopologicalOrder());
            X_1_VariablesInTopologicalOrder.RemoveAll(X_0);
            X_1_VariablesInTopologicalOrder.RemoveAll(E_1);
        }
Пример #5
0
        public virtual Object visitBinarySentence(BinarySentence bs, Object arg)
        {
            Hashtable s         = (Hashtable)arg;
            Hashtable termunion = new SetOps().union((Hashtable)bs.getFirst().accept(this, arg), (Hashtable)bs.getSecond().accept(this, arg));

            return(new SetOps().union(s, termunion));
        }
Пример #6
0
        public List <Symbol> getPurePositiveSymbolsIn(Sentence sentence)
        {
            List <Symbol> allNegatives = getNegativeSymbolsIn(sentence);
            List <Symbol> allPositives = getPositiveSymbolsIn(sentence);

            return(SetOps.difference(allPositives, allNegatives));
        }
Пример #7
0
        /**
         * Determina si la cláusula representa una tautología, si por ejemplo contiene True, ~False o (P o ~P).
         *
         * @return cierto si la cláusula representa una tautología, falso en caso contrario.
         */
        public bool IsTautology()
        {
            if (cachedIsTautologyResult == null)
            {
                foreach (Literal l in literals)
                {
                    if (l.IsAlwaysTrue())
                    {
                        // Si contiene True o contiene ~False es una tautología
                        cachedIsTautologyResult = true;
                    }
                }
                // Si seguimos sin saberlo
                if (cachedIsTautologyResult == null)
                {
                    if (SetOps.Intersection(cachedPositiveSymbols, cachedNegativeSymbols).Count > 0)   // Esto de SetOps.intersection me recuerda al Sets.intersection de Java... tendré que ver cómo sustituirlo en C#
                    // Tenemos P | ~P que siempre es cierto.
                    {
                        cachedIsTautologyResult = true;
                    }
                    else
                    {
                        cachedIsTautologyResult = false;
                    }
                }
            }

            return((bool)cachedIsTautologyResult); // No puede ser null por la forma en que se ha programado arriba
        }
Пример #8
0
        public List <Symbol> getPureSymbolsIn(Sentence sentence)
        {
            List <Symbol> allPureNegatives = getPureNegativeSymbolsIn(sentence);
            List <Symbol> allPurePositives = getPurePositiveSymbolsIn(sentence);

            return(SetOps.union(allPurePositives, allPureNegatives));
        }
Пример #9
0
        public ProbabilityTable pointwiseProduct(ProbabilityTable multiplier)
        {
            ISet <IRandomVariable> prodVars = SetOps.union(CollectionFactory.CreateSet <IRandomVariable>(randomVarInfo.GetKeys()),
                                                           CollectionFactory.CreateSet <IRandomVariable>(multiplier.randomVarInfo.GetKeys()));

            return(pointwiseProductPOS(multiplier, prodVars.ToArray()));
        }
Пример #10
0
        public ProbabilityTable pointwiseProductPOS(
            ProbabilityTable multiplier, params RandomVariable[] prodVarOrder)
        {
            ProbabilityTable product = new ProbabilityTable(prodVarOrder);

            if (!product.randomVarInfo.keySet().Equals(
                    SetOps.union(new List <RandomVariable>(randomVarInfo.keySet()),
                                 new List <RandomVariable>(multiplier.randomVarInfo
                                                           .keySet()))))
            {
                if (1 == product.getValues().Length)
                {
                    product.getValues()[0] = getValues()[0] * multiplier.getValues()[0];
                }
                else
                {
                    // Otherwise need to iterate through the product
                    // to calculate its values based on the terms.
                    Object[] term1Values = new Object[randomVarInfo.size()];
                    Object[] term2Values = new Object[multiplier.randomVarInfo
                                                      .size()];
                    //ProbabilityTable.Iterator di = new ProbabilityTable.Iterator() {
                    //    private int idx = 0;

                    //    public void iterate(Map<RandomVariable, Object> possibleWorld,
                    //            double probability) {
                    //        int term1Idx = termIdx(term1Values, ProbabilityTable.this,
                    //                possibleWorld);
                    //        int term2Idx = termIdx(term2Values, multiplier,
                    //                possibleWorld);

                    //        product.getValues()[idx] = getValues()[term1Idx]
                    //                * multiplier.getValues()[term2Idx];

                    //        idx++;
                    //    }

                    //    private int termIdx(Object[] termValues, ProbabilityTable d,
                    //            Map<RandomVariable, Object> possibleWorld) {
                    //        if (0 == termValues.Length) {
                    //            // The term has no variables so always position 0.
                    //            return 0;
                    //        }

                    //        int i = 0;
                    //        for (RandomVariable rv : d.randomVarInfo.keySet()) {
                    //            termValues[i] = possibleWorld.get(rv);
                    //            i++;
                    //        }

                    //        return d.getIndex(termValues);
                    //    }
                    //};
                    //product.iterateOverTable(di);
                    // TODO
                }
            }
            return(product);
        }
Пример #11
0
        public ProbabilityTable pointwiseProduct(ProbabilityTable multiplier)
        {
            List <RandomVariable> prodVars = SetOps.union(new List <RandomVariable>(randomVarInfo.Keys),
                                                          new List <RandomVariable>(multiplier.randomVarInfo.Keys));

            return(pointwiseProductPOS(multiplier, prodVars
                                       .ToArray()));
        }
Пример #12
0
        public virtual ISet <T> visitBinarySentence(ComplexSentence s, ISet <T> arg)
        {
            ISet <T> termunion = SetOps.union(
                s.getSimplerSentence(0).accept(this, arg), s
                .getSimplerSentence(1).accept(this, arg));

            return(SetOps.union(arg, termunion));
        }
Пример #13
0
        public void testDifference()
        {
            ISet <int> difference = SetOps.difference(s1, s2);

            Assert.AreEqual(3, difference.Size());
            Assert.IsTrue(difference.Contains(1));
            Assert.IsTrue(difference.Contains(2));
            Assert.IsTrue(difference.Contains(3));
        }
Пример #14
0
        public void testDifference2()
        {
            ISet <int> one = CollectionFactory.CreateSet <int>();
            ISet <int> two = CollectionFactory.CreateSet <int>();

            one.Add(1);
            two.Add(1);
            ISet <int> difference = SetOps.difference(one, two);

            Assert.IsTrue(difference.IsEmpty());
        }
Пример #15
0
        public void testDifference2()
        {
            List <int> one = new List <int>();
            List <int> two = new List <int>();

            one.Add(1);
            two.Add(1);
            List <int> difference = SetOps.difference(one, two);

            Assert.AreEqual(0, difference.Count);
        }
Пример #16
0
        public bool ttEntails(KnowledgeBase kb, string alpha)
        {
            Sentence        kbSentence    = kb.asSentence();
            Sentence        querySentence = (Sentence) new PEParser().parse(alpha);
            SymbolCollector collector     = new SymbolCollector();
            Hashtable       kbSymbols     = collector.getSymbolsIn(kbSentence);
            Hashtable       querySymbols  = collector.getSymbolsIn(querySentence);
            Hashtable       symbols       = new SetOps().union(kbSymbols, querySymbols);
            ArrayList       symbolList    = new Converter().setToList(symbols);

            return(ttCheckAll(kbSentence, querySentence, symbolList, new Model()));
        }
Пример #17
0
        public bool ttEntails(KnowledgeBase kb, String alpha)
        {
            Sentence        kbSentence    = kb.asSentence();
            Sentence        querySentence = (Sentence) new PEParser().parse(alpha);
            SymbolCollector collector     = new SymbolCollector();
            List <Symbol>   kbSymbols     = collector.getSymbolsIn(kbSentence);
            List <Symbol>   querySymbols  = collector.getSymbolsIn(querySentence);
            List <Symbol>   symbols       = SetOps.union(kbSymbols, querySymbols);
            List <Symbol>   symbolList    = symbols;

            return(ttCheckAll(kbSentence, querySentence, symbolList, new Model()));
        }
Пример #18
0
        public ProbabilityTable divideBy(ProbabilityTable divisor)
        {
            if (!randomVarInfo.GetKeys().ContainsAll(divisor.randomVarInfo.GetKeys()))
            {
                throw new IllegalArgumentException("Divisor must be a subset of the dividend.");
            }

            ProbabilityTable quotient = new ProbabilityTable(randomVarInfo.GetKeys());

            if (1 == divisor.getValues().Length)
            {
                double d = divisor.getValues()[0];
                for (int i = 0; i < quotient.getValues().Length; ++i)
                {
                    if (0 == d)
                    {
                        quotient.getValues()[i] = 0;
                    }
                    else
                    {
                        quotient.getValues()[i] = getValues()[i] / d;
                    }
                }
            }
            else
            {
                ISet <IRandomVariable> dividendDivisorDiff = SetOps
                                                             .difference(
                    CollectionFactory.CreateSet <IRandomVariable>(this.randomVarInfo.GetKeys()),
                    CollectionFactory.CreateSet <IRandomVariable>(divisor.randomVarInfo.GetKeys()));
                IMap <IRandomVariable, RVInfo> tdiff = null;
                MixedRadixNumber tdMRN = null;
                if (dividendDivisorDiff.Size() > 0)
                {
                    tdiff = CollectionFactory.CreateInsertionOrderedMap <IRandomVariable, RVInfo>();
                    foreach (IRandomVariable rv in dividendDivisorDiff)
                    {
                        tdiff.Put(rv, new RVInfo(rv));
                    }
                    tdMRN = new MixedRadixNumber(0, createRadixs(tdiff));
                }
                IMap <IRandomVariable, RVInfo> diff      = tdiff;
                MixedRadixNumber         dMRN            = tdMRN;
                int[]                    qRVs            = new int[quotient.radices.Length];
                MixedRadixNumber         qMRN            = new MixedRadixNumber(0, quotient.radices);
                ProbabilityTableIterator divisorIterator = new ProbabilityTableIteratorImp2(quotient, qRVs, qMRN, dMRN, diff, this);

                divisor.iterateOverTable(divisorIterator);
            }

            return(quotient);
        }
Пример #19
0
        public void testIntersection()
        {
            ISet <int> intersection = SetOps.intersection(s1, s2);

            Assert.AreEqual(1, intersection.Size());
            Assert.AreEqual(4, s1.Size());
            Assert.AreEqual(3, s2.Size());

            s1.Remove(1);
            Assert.AreEqual(1, intersection.Size());
            Assert.AreEqual(3, s1.Size());
            Assert.AreEqual(3, s2.Size());
        }
Пример #20
0
        public void testIntersection()
        {
            List <int> intersection = SetOps.intersection(s1, s2);

            Assert.AreEqual(1, intersection.Count);
            Assert.AreEqual(4, s1.Count);
            Assert.AreEqual(3, s2.Count);

            s1.Remove(1);
            Assert.AreEqual(1, intersection.Count);
            Assert.AreEqual(3, s1.Count);
            Assert.AreEqual(3, s2.Count);
        }
Пример #21
0
        public void testUnion()
        {
            List <int> union = SetOps.union(s1, s2);

            Assert.AreEqual(6, union.Count);
            Assert.AreEqual(4, s1.Count);
            Assert.AreEqual(3, s2.Count);

            s1.Remove(1);
            Assert.AreEqual(6, union.Count);
            Assert.AreEqual(3, s1.Count);
            Assert.AreEqual(3, s2.Count);
        }
Пример #22
0
        public void testUnion()
        {
            ISet <int> union = SetOps.union(s1, s2);

            Assert.AreEqual(6, union.Size());
            Assert.AreEqual(4, s1.Size());
            Assert.AreEqual(3, s2.Size());

            s1.Remove(1);
            Assert.AreEqual(6, union.Size());
            Assert.AreEqual(3, s1.Size());
            Assert.AreEqual(3, s2.Size());
        }
Пример #23
0
        public override Object visitNotSentence(UnarySentence ns, Object arg)
        {
            List <Symbol> s = (List <Symbol>)arg;

            if (ns.getNegated() is Symbol)
            {
                // do nothing .do NOT add a negated Symbol
            }
            else
            {
                s = SetOps
                    .union(s, (List <Symbol>)ns.getNegated().accept(this, arg));
            }
            return(s);
        }
Пример #24
0
        public override Object visitNotSentence(UnarySentence ns, Object arg)
        {
            List <Symbol> s = (List <Symbol>)arg;

            if (ns.getNegated() is Symbol)
            {
                s.Add((Symbol)ns.getNegated());
            }
            else
            {
                s = SetOps
                    .union(s, (List <Symbol>)ns.getNegated().accept(this, arg));
            }
            return(s);
        }
Пример #25
0
        public void testPLResolveWithTwoLiteralsMatching()
        {
            Clause        one      = Util.first(ConvertToConjunctionOfClauses.convert(parser.parse("~P21 | B11")).getClauses());
            Clause        two      = Util.first(ConvertToConjunctionOfClauses.convert(parser.parse("~B11 | P21 | P12")).getClauses());
            ISet <Clause> expected = ConvertToConjunctionOfClauses.convert(parser.parse("(P12 | P21 | ~P21) & (B11 | P12 | ~B11)")).getClauses();

            ISet <Clause> resolvents = resolution.plResolve(one, two);

            int numberExpectedResolvents = 2;

            if (resolution.isDiscardTautologies())
            {
                numberExpectedResolvents = 0; // due to being tautologies
            }
            Assert.AreEqual(numberExpectedResolvents, resolvents.Size());
            Assert.AreEqual(numberExpectedResolvents, SetOps.intersection(expected, resolvents).Size());
        }
Пример #26
0
            public ClauseSymbols(Sentence clause1, Sentence clause2)
            {
                SymbolClassifier classifier = new SymbolClassifier();

                clause1Symbols         = classifier.getSymbolsIn(clause1);
                clause1PositiveSymbols = classifier.getPositiveSymbolsIn(clause1);
                clause1NegativeSymbols = classifier.getNegativeSymbolsIn(clause1);

                clause2Symbols         = classifier.getSymbolsIn(clause2);
                clause2PositiveSymbols = classifier.getPositiveSymbolsIn(clause2);
                clause2NegativeSymbols = classifier.getNegativeSymbolsIn(clause2);

                positiveInClause1NegativeInClause2 = SetOps.intersection(
                    clause1PositiveSymbols, clause2NegativeSymbols);
                negativeInClause1PositiveInClause2 = SetOps.intersection(
                    clause1NegativeSymbols, clause2PositiveSymbols);
            }
Пример #27
0
        //
        // PRIVATE METHODS
        //

        private List <Sentence> filterOutClausesWithTwoComplementaryLiterals(
            List <Sentence> clauses)
        {
            List <Sentence>  filtered   = new List <Sentence>();
            SymbolClassifier classifier = new SymbolClassifier();

            foreach (Sentence clause in clauses)
            {
                List <Symbol> positiveSymbols = classifier
                                                .getPositiveSymbolsIn(clause);
                List <Symbol> negativeSymbols = classifier
                                                .getNegativeSymbolsIn(clause);
                if ((SetOps.intersection(positiveSymbols, negativeSymbols).Count == 0))
                {
                    filtered.Add(clause);
                }
            }
            return(filtered);
        }
Пример #28
0
        public virtual Object visitBinarySentence(BinarySentence bs, Object arg)
        {
            List <Sentence> s = new List <Sentence>();

            if (arg is List <Symbol> )
            {
                List <Symbol> symbols = ((List <Symbol>)arg);
                foreach (Symbol symbol in symbols)
                {
                    s.Add((Sentence)symbol);
                }
            }
            else
            {
                throw new ArgumentException("Could not cast arg to List<Sentence>");
            }
            List <Sentence> termunion = SetOps.union((List <Sentence>)bs.getFirst().accept(this, arg),
                                                     (List <Sentence>)bs.getSecond().accept(this, arg));

            return(SetOps.union(s, termunion));
        }
Пример #29
0
        private Sentence createResolventClause(ClauseSymbols cs, Symbol toRemove)
        {
            List <Symbol> positiveSymbols = SetOps
                                            .union(cs.clause1PositiveSymbols, cs.clause2PositiveSymbols);
            List <Symbol> negativeSymbols = SetOps
                                            .union(cs.clause1NegativeSymbols, cs.clause2NegativeSymbols);

            if (positiveSymbols.Contains(toRemove))
            {
                positiveSymbols.Remove(toRemove);
            }
            if (negativeSymbols.Contains(toRemove))
            {
                negativeSymbols.Remove(toRemove);
            }

            positiveSymbols.Sort(new SymbolComparator());
            negativeSymbols.Sort(new SymbolComparator());

            List <Sentence> sentences = new List <Sentence>();

            for (int i = 0; i < positiveSymbols.Count; i++)
            {
                sentences.Add(positiveSymbols[i]);
            }
            for (int i = 0; i < negativeSymbols.Count; i++)
            {
                sentences.Add(new UnarySentence(negativeSymbols[i]));
            }
            if (sentences.Count == 0)
            {
                return(new Symbol("EMPTY_CLAUSE")); // == empty clause
            }
            else
            {
                return(LogicUtils.chainWith("OR", sentences));
            }
        }
Пример #30
0
        public bool plResolution(KnowledgeBase kb, Sentence alpha)
        {
            Sentence kBAndNotAlpha = new BinarySentence("AND", kb.asSentence(),
                                                        new UnarySentence(alpha));
            List <Sentence> clauses = new CNFClauseGatherer()
                                      .getClausesFrom(new CNFTransformer().transform(kBAndNotAlpha));

            clauses = filterOutClausesWithTwoComplementaryLiterals(clauses);
            List <Sentence> newClauses = new List <Sentence>();

            while (true)
            {
                List <List <Sentence> > pairs = getCombinationPairs(clauses);

                for (int i = 0; i < pairs.Count; i++)
                {
                    List <Sentence> pair = pairs[i];
                    // System.Console.WriteLine("pair number" + i+" of "+pairs.Count);
                    List <Sentence> resolvents = plResolve(pair[0], pair[1]);
                    resolvents = filterOutClausesWithTwoComplementaryLiterals(resolvents);

                    if (resolvents.Contains(new Symbol("EMPTY_CLAUSE")))
                    {
                        return(true);
                    }
                    newClauses = SetOps.union(newClauses, resolvents);
                    // System.Console.WriteLine("clauseslist size = " +clauses.Count);
                }
                if (SetOps.intersection(newClauses, clauses).Count == newClauses
                    .Count)
                {// subset test
                    return(false);
                }
                clauses = SetOps.union(newClauses, clauses);
                clauses = filterOutClausesWithTwoComplementaryLiterals(clauses);
            }
        }