示例#1
0
        // Artificial Intelligence A Modern Approach (2nd Edition): page 288.
        // COMPOSE(delta, tau) is the substitution whose effect is identical to
        // the effect of applying each substitution in turn. That is,
        // SUBST(COMPOSE(theta1, theta2), p) = SUBST(theta2, SUBST(theta1, p))
        private IMap <Variable, Term> compose(FOLKnowledgeBase KB, IMap <Variable, Term> theta1, IMap <Variable, Term> theta2)
        {
            IMap <Variable, Term> composed = CollectionFactory.CreateInsertionOrderedMap <Variable, Term>();

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

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

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

            return(cascadeSubstitutions(KB, composed));
        }
示例#2
0
 public BidirectionalSearch(NodeExpander <S, A> nodeExpander)
     : base(nodeExpander)
 {
     explored = CollectionFactory.CreateQueue <IMap <S, ExtendedNode> >();
     explored.Add(CollectionFactory.CreateInsertionOrderedMap <S, ExtendedNode>());
     explored.Add(CollectionFactory.CreateInsertionOrderedMap <S, ExtendedNode>());
 }
示例#3
0
        private void sampleFromTransitionModel(int i)
        {
            // x <- an event initialized with S[i]
            IMap <IRandomVariable, object> x = CollectionFactory.CreateInsertionOrderedMap <IRandomVariable, object>();

            for (int n = 0; n < S[i].Length; n++)
            {
                AssignmentProposition x1 = S[i][n];
                x.Put(this.dbn.GetX_1_to_X_0().Get(x1.getTermVariable()), x1.getValue());
            }

            // foreach variable X<sub>1<sub>i</sub></sub> in
            // X<sub>1<sub>1</sub></sub>,...,X<sub>1<sub>n<</sub>/sub> do
            foreach (IRandomVariable X1_i in dbn.GetX_1_VariablesInTopologicalOrder())
            {
                // x1[i] <- a random sample from
                // <b>P</b>(X<sub>1<sub>i</sub></sub> |
                // parents(X<sub>1<sub>i</sub></sub>))
                x.Put(X1_i, ProbUtil.randomSample(dbn.GetNode(X1_i), x, randomizer));
            }

            // S[i] <- sample from <b>P</b>(<b>X</b><sub>1</sub> |
            // <b>X</b><sub>0</sub> = S[i])
            for (int n = 0; n < S_tp1[i].Length; n++)
            {
                AssignmentProposition x1 = S_tp1[i][n];
                x1.setValue(x.Get(x1.getTermVariable()));
            }
        }
示例#4
0
        private static int standardizeApart(ICollection <Variable> variables, object expr, int saIdx)
        {
            IMap <string, int> indexicals = CollectionFactory.CreateInsertionOrderedMap <string, int>();

            foreach (Variable v in variables)
            {
                if (!indexicals.ContainsKey(v.getIndexedValue()))
                {
                    indexicals.Put(v.getIndexedValue(), saIdx++);
                }
            }
            foreach (Variable v in variables)
            {
                if (!indexicals.ContainsKey(v.getIndexedValue()))
                {
                    throw new RuntimeException("ERROR: duplicate var=" + v + ", expr=" + expr);
                }
                else
                {
                    v.setIndexical(indexicals.Get(v.getIndexedValue()));
                }
            }

            return(saIdx);
        }
示例#5
0
 public DecisionList(string positive, string negative)
 {
     this.positive = positive;
     this.negative = negative;
     this.tests    = CollectionFactory.CreateQueue <DecisionListTest>();
     testOutcomes  = CollectionFactory.CreateInsertionOrderedMap <DecisionListTest, string>();
 }
示例#6
0
        public static T mode <T>(ICollection <T> l)
        {
            IMap <T, int> hash = CollectionFactory.CreateInsertionOrderedMap <T, int>();

            foreach (T obj in l)
            {
                if (hash.ContainsKey(obj))
                {
                    hash.Put(obj, hash.Get(obj) + 1);
                }
                else
                {
                    hash.Put(obj, 1);
                }
            }

            T maxkey = hash.GetKeys().Get(0);

            foreach (T key in hash.GetKeys())
            {
                if (hash.Get(key) > hash.Get(maxkey))
                {
                    maxkey = key;
                }
            }
            return(maxkey);
        }
        // function WEIGHTED-SAMPLE(bn, e) returns an event and a weight

        /**
         * The WEIGHTED-SAMPLE function in Figure 14.15.
         *
         * @param e
         *            observed values for variables E
         * @param bn
         *            a Bayesian network specifying joint distribution
         *            <b>P</b>(X<sub>1</sub>,...,X<sub>n</sub>)
         * @return return <b>x</b>, w - an event with its associated weight.
         */
        public Pair <IMap <IRandomVariable, object>, double> weightedSample(IBayesianNetwork bn, AssignmentProposition[] e)
        {
            // w <- 1;
            double w = 1.0;
            // <b>x</b> <- an event with n elements initialized from e
            IMap <IRandomVariable, object> x = CollectionFactory.CreateInsertionOrderedMap <IRandomVariable, object>();

            foreach (AssignmentProposition ap in e)
            {
                x.Put(ap.getTermVariable(), ap.getValue());
            }

            // foreach variable X<sub>i</sub> in X<sub>1</sub>,...,X<sub>n</sub> do
            foreach (IRandomVariable Xi in bn.GetVariablesInTopologicalOrder())
            {
                // if X<sub>i</sub> is an evidence variable with value x<sub>i</sub>
                // in e
                if (x.ContainsKey(Xi))
                {
                    // then w <- w * P(X<sub>i</sub> = x<sub>i</sub> |
                    // parents(X<sub>i</sub>))
                    w *= bn.GetNode(Xi)
                         .GetCPD()
                         .GetValue(ProbUtil.getEventValuesForXiGivenParents(bn.GetNode(Xi), x));
                }
                else
                {
                    // else <b>x</b>[i] <- a random sample from
                    // <b>P</b>(X<sub>i</sub> | parents(X<sub>i</sub>))
                    x.Put(Xi, ProbUtil.randomSample(bn.GetNode(Xi), x, randomizer));
                }
            }
            // return <b>x</b>, w
            return(new Pair <IMap <IRandomVariable, object>, double>(x, w));
        }
示例#8
0
        /**
         * Access a folder of .txt files containing wikipedia html source, and give
         * back a hashtable of pages, which each page having it's correct inlink
         * list and outlink list.
         *
         * @param folderPath
         * @return a hashtable of Page objects, accessed by article name (which is a
         *         location for wikipedia: \wiki\*article name*)
         */
        public static IMap <string, Page> loadPages(string folderPath)
        {
            IMap <string, Page> pageTable = CollectionFactory.CreateInsertionOrderedMap <string, Page>();
            Page currPage;

            string[] listOfFiles;
            wlf = new WikiLinkFinder();

            if (Directory.Exists(folderPath))
            {
                listOfFiles = Directory.GetFiles(folderPath);
            }
            else
            {
                return(null);
            } // maybe should throw exception instead?

            // Access each .txt file to create a new Page object for that file's
            // article
            for (int i = 0; i < listOfFiles.Length; ++i)
            {
                currPage = wikiPageFromFile(folderPath, new FileInfo(listOfFiles[i]));
                pageTable.Put(currPage.getLocation(), currPage);
            }
            // now that all pages are loaded and their outlinks have been determined,
            // we can determine a page's inlinks and then return the loaded table
            return(pageTable = determineAllInlinks(pageTable));
        } // end loadPages()
示例#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);
        }
示例#10
0
        public Clause standardizeApart(Clause clause, StandardizeApartIndexical standardizeApartIndexical)
        {
            ISet <Variable>       toRename           = variableCollector.collectAllVariables(clause);
            IMap <Variable, Term> renameSubstitution = CollectionFactory.CreateInsertionOrderedMap <Variable, Term>();

            foreach (Variable var in toRename)
            {
                Variable v = null;
                do
                {
                    v = new Variable(standardizeApartIndexical.getPrefix() + standardizeApartIndexical.getNextIndex());
                    // Ensure the new variable name is not already
                    // accidentally used in the sentence
                } while (toRename.Contains(v));

                renameSubstitution.Put(var, v);
            }

            if (renameSubstitution.Size() > 0)
            {
                ICollection <Literal> literals = CollectionFactory.CreateQueue <Literal>();

                foreach (Literal l in clause.getLiterals())
                {
                    literals.Add(substVisitor.subst(renameSubstitution, l));
                }
                Clause renamed = new Clause(literals);
                renamed.setProofStep(new ProofStepRenaming(renamed, clause.getProofStep()));
                return(renamed);
            }

            return(clause);
        }
示例#11
0
        public static Example exampleFromString(string data, DataSetSpecification dataSetSpec, string separator)
        {
            IRegularExpression        splitter        = TextFactory.CreateRegularExpression(separator);
            IMap <string, IAttribute> attributes      = CollectionFactory.CreateInsertionOrderedMap <string, IAttribute>();
            ICollection <string>      attributeValues = CollectionFactory.CreateQueue <string>(splitter.Split(data));

            if (dataSetSpec.isValid(attributeValues))
            {
                ICollection <string> names = dataSetSpec.getAttributeNames();
                int min = names.Size() > attributes.Size() ? names.Size() : attributes.Size();

                for (int i = 0; i < min; ++i)
                {
                    string name = names.Get(i);
                    IAttributeSpecification attributeSpec = dataSetSpec.getAttributeSpecFor(name);
                    IAttribute attribute = attributeSpec.CreateAttribute(attributeValues.Get(i));
                    attributes.Put(name, attribute);
                }
                string targetAttributeName = dataSetSpec.getTarget();
                return(new Example(attributes, attributes.Get(targetAttributeName)));
            }
            else
            {
                throw new RuntimeException("Unable to construct Example from " + data);
            }
        }
示例#12
0
        public double getInformationFor()
        {
            string             attributeName = specification.getTarget();
            IMap <string, int> counts        = CollectionFactory.CreateInsertionOrderedMap <string, int>();

            foreach (Example e in examples)
            {
                string val = e.getAttributeValueAsString(attributeName);
                if (counts.ContainsKey(val))
                {
                    counts.Put(val, counts.Get(val) + 1);
                }
                else
                {
                    counts.Put(val, 1);
                }
            }

            double[] data = new double[counts.GetKeys().Size()];
            int      i    = 0;

            foreach (int value in counts.GetValues())
            {
                data[i] = value;
                ++i;
            }
            data = Util.normalize(data);

            return(Util.information(data));
        }
示例#13
0
        public object visitQuantifiedSentence(QuantifiedSentence sentence, object arg)
        {
            Sentence        quantified     = sentence.getQuantified();
            ISet <Variable> universalScope = (Set <Variable>)arg;

            // Skolemize: Skolemization is the process of removing existential
            // quantifiers by elimination. This is done by introducing Skolem
            // functions. The general rule is that the arguments of the Skolem
            // function are all the universally quantified variables in whose
            // scope the existential quantifier appears.
            if (Quantifiers.isEXISTS(sentence.getQuantifier()))
            {
                IMap <Variable, Term> skolemSubst = CollectionFactory.CreateInsertionOrderedMap <Variable, Term>();
                foreach (Variable eVar in sentence.getVariables())
                {
                    if (universalScope.Size() > 0)
                    {
                        // Replace with a Skolem Function
                        string skolemFunctionName = parser.getFOLDomain().addSkolemFunction();

                        ICollection <Term> terms = CollectionFactory.CreateQueue <Term>();
                        foreach (Variable v in universalScope)
                        {
                            terms.Add(v);
                        }
                        skolemSubst.Put(eVar, new Function(skolemFunctionName, terms));
                    }
                    else
                    {
                        // Replace with a Skolem Constant
                        string skolemConstantName = parser.getFOLDomain().addSkolemConstant();
                        skolemSubst.Put(eVar, new Constant(skolemConstantName));
                    }
                }

                Sentence skolemized = substVisitor.subst(skolemSubst, quantified);
                return(skolemized.accept(this, arg));
            }

            // Drop universal quantifiers.
            if (Quantifiers.isFORALL(sentence.getQuantifier()))
            {
                // Add to the universal scope so that
                // existential skolemization may be done correctly
                universalScope.AddAll(sentence.getVariables());

                Sentence droppedUniversal = (Sentence)quantified.accept(this, arg);

                // Enusre my scope is removed before moving back up
                // the call stack when returning
                universalScope.RemoveAll(sentence.getVariables());

                return(droppedUniversal);
            }

            // Should not reach here as have already
            // handled the two quantifiers.
            throw new IllegalStateException("Unhandled Quantifier:" + sentence.getQuantifier());
        }
        public static IMap <IRandomVariable, IRandomVariable> getUmbrellaWorld_Xt_to_Xtm1_Map()
        {
            IMap <IRandomVariable, IRandomVariable> tToTm1StateVarMap = CollectionFactory.CreateInsertionOrderedMap <IRandomVariable, IRandomVariable>();

            tToTm1StateVarMap.Put(ExampleRV.RAIN_t_RV, ExampleRV.RAIN_tm1_RV);

            return(tToTm1StateVarMap);
        }
示例#15
0
 public override void reset()
 {
     U = CollectionFactory.CreateInsertionOrderedMap <S, double>();
     Ns.clear();
     s = default(S);
     a = default(A);
     r = null;
 }
示例#16
0
 /**
  * Creates a new CSP.
  */
 public CSP()
 {
     variables    = CollectionFactory.CreateQueue <VAR>();
     domains      = CollectionFactory.CreateQueue <Domain <VAL> >();
     constraints  = CollectionFactory.CreateQueue <IConstraint <VAR, VAL> >();
     varIndexHash = CollectionFactory.CreateInsertionOrderedMap <Variable, int>();
     cnet         = CollectionFactory.CreateInsertionOrderedMap <Variable, ICollection <IConstraint <VAR, VAL> > >();
 }
示例#17
0
 public override void reset()
 {
     P.Clear();
     R.Clear();
     U = CollectionFactory.CreateInsertionOrderedMap <S, double>();
     Nsa.clear();
     NsDelta_sa.clear();
     s = default(S);
     a = default(A);
 }
示例#18
0
 /// <summary>
 /// Constructs a Table with the specified row and column headers.
 /// </summary>
 /// <param name="rowHeaders">a list of row headers</param>
 /// <param name="columnHeaders">a list of column headers</param>
 public Table(ICollection <RowHeaderType> rowHeaders, ICollection <ColumnHeaderType> columnHeaders)
 {
     this.rowHeaders    = rowHeaders;
     this.columnHeaders = columnHeaders;
     this.rows          = CollectionFactory.CreateInsertionOrderedMap <RowHeaderType, IMap <ColumnHeaderType, ValueType> >();
     foreach (RowHeaderType rowHeader in rowHeaders)
     {
         rows.Put(rowHeader, CollectionFactory.CreateInsertionOrderedMap <ColumnHeaderType, ValueType>());
     }
 }
示例#19
0
        // function GIBBS-ASK(X, e, bn, N) returns an estimate of <b>P</b>(X|e)

        /**
         * The GIBBS-ASK algorithm in Figure 14.16. For answering queries given
         * evidence in a Bayesian Network.
         *
         * @param X
         *            the query variables
         * @param e
         *            observed values for variables E
         * @param bn
         *            a Bayesian network specifying joint distribution
         *            <b>P</b>(X<sub>1</sub>,...,X<sub>n</sub>)
         * @param Nsamples
         *            the total number of samples to be generated
         * @return an estimate of <b>P</b>(X|e)
         */
        public ICategoricalDistribution gibbsAsk(IRandomVariable[] X,
                                                 AssignmentProposition[] e, IBayesianNetwork bn, int Nsamples)
        {
            // local variables: <b>N</b>, a vector of counts for each value of X,
            // initially zero
            double[] N = new double[ProbUtil.expectedSizeOfCategoricalDistribution(X)];
            // Z, the nonevidence variables in bn
            ISet <IRandomVariable> Z = CollectionFactory.CreateSet <IRandomVariable>(bn.GetVariablesInTopologicalOrder());

            foreach (AssignmentProposition ap in e)
            {
                Z.Remove(ap.getTermVariable());
            }
            // <b>x</b>, the current state of the network, initially copied from e
            IMap <IRandomVariable, object> x = CollectionFactory.CreateInsertionOrderedMap <IRandomVariable, object>();

            foreach (AssignmentProposition ap in e)
            {
                x.Put(ap.getTermVariable(), ap.getValue());
            }

            // initialize <b>x</b> with random values for the variables in Z
            foreach (IRandomVariable Zi in Z)
            {
                x.Put(Zi, ProbUtil.randomSample(bn.GetNode(Zi), x, randomizer));
            }

            // for j = 1 to N do
            for (int j = 0; j < Nsamples; j++)
            {
                // for each Z<sub>i</sub> in Z do
                foreach (IRandomVariable Zi in Z)
                {
                    // set the value of Z<sub>i</sub> in <b>x</b> by sampling from
                    // <b>P</b>(Z<sub>i</sub>|mb(Z<sub>i</sub>))
                    x.Put(Zi, ProbUtil.mbRandomSample(bn.GetNode(Zi), x, randomizer));
                }
                // Note: moving this outside the previous for loop,
                // as described in fig 14.6, as will only work
                // correctly in the case of a single query variable X.
                // However, when multiple query variables, rare events
                // will get weighted incorrectly if done above. In case
                // of single variable this does not happen as each possible
                // value gets * |Z| above, ending up with the same ratios
                // when normalized (i.e. its still more efficient to place
                // outside the loop).
                //
                // <b>N</b>[x] <- <b>N</b>[x] + 1
                // where x is the value of X in <b>x</b>
                N[ProbUtil.indexOf(X, x)] += 1.0;
            }
            // return NORMALIZE(<b>N</b>)
            return(new ProbabilityTable(N, X).normalize());
        }
示例#20
0
        /**
         * Create a IMap<K, V> with the passed in keys having their values
         * initialized to the passed in value.
         *
         * @param keys
         *            the keys for the newly constructed map.
         * @param value
         *            the value to be associated with each of the maps keys.
         * @return a map with the passed in keys initialized to value.
         */
        public static IMap <K, V> create <K, V>(ICollection <K> keys, V value)
        {
            IMap <K, V> map = CollectionFactory.CreateInsertionOrderedMap <K, V>();

            foreach (K k in keys)
            {
                map.Put(k, value);
            }

            return(map);
        }
示例#21
0
        protected IMap <PropositionSymbol, bool?> initializeInferred(KnowledgeBase kb)
        {
            // inferred <- a table, where inferred[s] is initially false for all
            // symbols
            IMap <PropositionSymbol, bool?> inferred = CollectionFactory.CreateInsertionOrderedMap <PropositionSymbol, bool?>();

            foreach (PropositionSymbol p in SymbolCollector.getSymbolsFrom(kb.asSentence()))
            {
                inferred.Put(p, false);
            }
            return(inferred);
        }
示例#22
0
        /// <summary>
        /// Handles new vertices.
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        private IMap <VertexLabelType, EdgeLabelType> checkForNewVertex(VertexLabelType v)
        {
            IMap <VertexLabelType, EdgeLabelType> result = globalEdgeLookup.Get(v);

            if (result == null)
            {
                result = CollectionFactory.CreateInsertionOrderedMap <VertexLabelType, EdgeLabelType>();
                globalEdgeLookup.Put(v, result);
                vertexLabels.Add(v);
            }
            return(result);
        }
示例#23
0
        public void test_indexesOfValue()
        {
            RandVar X = new RandVar("X", new BooleanDomain());
            RandVar Y = new RandVar("Y", new ArbitraryTokenDomain("A", "B", "C"));
            RandVar Z = new RandVar("Z", new BooleanDomain());

            // An ordered X,Y,Z enumeration of values should look like:
            // 00: true, A, true
            // 01: true, A, false
            // 02: true, B, true
            // 03: true, B, false
            // 04: true, C, true
            // 05: true, C, false
            // 06: false, A, true
            // 07: false, A, false
            // 08: false, B, true
            // 09: false, B, false
            // 10: false, C, true
            // 11: false, C, false
            IRandomVariable[] vars = new IRandomVariable[] { X, Y, Z };
            IMap <IRandomVariable, object> even = CollectionFactory.CreateInsertionOrderedMap <IRandomVariable, object>();


            even.Put(X, true);
            CollectionAssert.AreEqual(new int[] { 0, 1, 2, 3, 4, 5 },
                                      ProbUtil.indexesOfValue(vars, 0, even));

            even.Put(X, false);
            CollectionAssert.AreEqual(new int[] { 6, 7, 8, 9, 10, 11 },
                                      ProbUtil.indexesOfValue(vars, 0, even));


            even.Put(Y, "A");
            CollectionAssert.AreEqual(new int[] { 0, 1, 6, 7 },
                                      ProbUtil.indexesOfValue(vars, 1, even));

            even.Put(Y, "B");
            CollectionAssert.AreEqual(new int[] { 2, 3, 8, 9 },
                                      ProbUtil.indexesOfValue(vars, 1, even));

            even.Put(Y, "C");
            CollectionAssert.AreEqual(new int[] { 4, 5, 10, 11 },
                                      ProbUtil.indexesOfValue(vars, 1, even));


            even.Put(Z, true);
            CollectionAssert.AreEqual(new int[] { 0, 2, 4, 6, 8, 10 },
                                      ProbUtil.indexesOfValue(vars, 2, even));

            even.Put(Z, false);
            CollectionAssert.AreEqual(new int[] { 1, 3, 5, 7, 9, 11 },
                                      ProbUtil.indexesOfValue(vars, 2, even));
        }
示例#24
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);
        }
示例#25
0
        private void initializeHypothesisWeights(int size)
        {
            if (size == 0)
            {
                throw new RuntimeException("cannot initialize Ensemble learning with Zero Learners");
            }

            learnerWeights = CollectionFactory.CreateInsertionOrderedMap <ILearner, double>();
            foreach (ILearner le in learners)
            {
                learnerWeights.Put(le, 1.0);
            }
        }
示例#26
0
        public IMap <Variable, Term> standardizeApart(ICollection <Literal> l1Literals,
                                                      ICollection <Literal> l2Literals,
                                                      StandardizeApartIndexical standardizeApartIndexical)
        {
            ISet <Variable> toRename = CollectionFactory.CreateSet <Variable>();

            foreach (Literal pl in l1Literals)
            {
                toRename.AddAll(variableCollector.collectAllVariables(pl
                                                                      .getAtomicSentence()));
            }
            foreach (Literal nl in l2Literals)
            {
                toRename.AddAll(variableCollector.collectAllVariables(nl.getAtomicSentence()));
            }

            IMap <Variable, Term> renameSubstitution = CollectionFactory.CreateInsertionOrderedMap <Variable, Term>();

            foreach (Variable var in toRename)
            {
                Variable v = null;
                do
                {
                    v = new Variable(standardizeApartIndexical.getPrefix()
                                     + standardizeApartIndexical.getNextIndex());
                    // Ensure the new variable name is not already
                    // accidentally used in the sentence
                } while (toRename.Contains(v));

                renameSubstitution.Put(var, v);
            }

            ICollection <Literal> posLits = CollectionFactory.CreateQueue <Literal>();
            ICollection <Literal> negLits = CollectionFactory.CreateQueue <Literal>();

            foreach (Literal pl in l1Literals)
            {
                posLits.Add(substVisitor.subst(renameSubstitution, pl));
            }
            foreach (Literal nl in l2Literals)
            {
                negLits.Add(substVisitor.subst(renameSubstitution, nl));
            }

            l1Literals.Clear();
            l1Literals.AddAll(posLits);
            l2Literals.Clear();
            l2Literals.AddAll(negLits);

            return(renameSubstitution);
        }
示例#27
0
        /**
         *
         * @return a map for each element and the corresponding disjoint set that it
         *         belongs to.
         */
        public IMap <E, ISet <E> > getElementToDisjointSet()
        {
            // Note: Instantiate normal sets to ensure IdentityHashSet
            // is not exposed outside of this class.
            // This also ensures the internal logic cannot
            // be corrupted externally due to changing sets.
            IMap <E, ISet <E> > result = CollectionFactory.CreateInsertionOrderedMap <E, ISet <E> >();

            foreach (KeyValuePair <E, ISet <E> > entry in elementToSet)
            {
                result.Put(entry.GetKey(), CollectionFactory.CreateSet <E>(entry.GetValue()));
            }
            return(result);
        }
示例#28
0
        public void testParanthisedSingleVariable()
        {
            Sentence beforeSubst        = parser.parse("((( King(x))))");
            Sentence expectedAfterSubst = parser.parse("King(John) ");

            IMap <Variable, Term> p = CollectionFactory.CreateInsertionOrderedMap <Variable, Term>();

            p.Put(new Variable("x"), new Constant("John"));

            Sentence afterSubst = sv.subst(p, beforeSubst);

            Assert.AreEqual(expectedAfterSubst, afterSubst);
            Assert.AreEqual(parser.parse("((( King(x))))"), beforeSubst);
        }
示例#29
0
        public void testSubstSingleVariableFailsWithPredicate()
        {
            Sentence beforeSubst        = parser.parse("King(x)");
            Sentence expectedAfterSubst = parser.parse(" King(x) ");

            IMap <Variable, Term> p = CollectionFactory.CreateInsertionOrderedMap <Variable, Term>();

            p.Put(new Variable("y"), new Constant("John"));

            Sentence afterSubst = sv.subst(p, beforeSubst);

            Assert.AreEqual(expectedAfterSubst, afterSubst);
            Assert.AreEqual(beforeSubst, parser.parse("King(x)"));
        }
示例#30
0
 /// <summary>
 /// Construct a Cell World with size xDimension * y Dimension cells, all with
 /// their values set to a default content value.
 /// </summary>
 /// <param name="xDimension">the size of the x dimension.</param>
 /// <param name="yDimension">the size of the y dimension.</param>
 /// <param name="defaultCellContent">the default content to assign to each cell created.</param>
 public CellWorld(int xDimension, int yDimension, C defaultCellContent)
 {
     for (int x = 1; x <= xDimension; x++)
     {
         IMap <int, Cell <C> > xCol = CollectionFactory.CreateInsertionOrderedMap <int, Cell <C> >();
         for (int y = 1; y <= yDimension; y++)
         {
             Cell <C> c = new Cell <C>(x, y, defaultCellContent);
             cells.Add(c);
             xCol.Put(y, c);
         }
         cellLookup.Put(x, xCol);
     }
 }