Example #1
0
        public Factor getFactorFor(params AssignmentProposition[] evidence)
        {
            Set <RandomVariable> fofVars = new Set <RandomVariable>(
                table.getFor());

            foreach (AssignmentProposition ap in evidence)
            {
                fofVars.Remove(ap.getTermVariable());
            }
            ProbabilityTable fof = new ProbabilityTable(new List <RandomVariable>(fofVars));

            // Otherwise need to iterate through the table for the
            // non evidence variables.
            Object[] termValues = new Object[fofVars.Count];
            //ProbabilityTable.Iterator di = new ProbabilityTable.Iterator() {
            //    public void iterate(Map<RandomVariable, Object> possibleWorld,
            //            double probability) {
            //        if (0 == termValues.length) {
            //            fof.getValues()[0] += probability;
            //        } else {
            //            int i = 0;
            //            for (RandomVariable rv : fof.getFor()) {
            //                termValues[i] = possibleWorld.get(rv);
            //                i++;
            //            }
            //            fof.getValues()[fof.getIndex(termValues)] += probability;
            //        }
            //    }
            //};
            //table.iterateOverTable(di, evidence);
            // TODO: another screwed up iterator
            return(fof);
        }
Example #2
0
        public CategoricalDistribution getConditioningCase(
            params AssignmentProposition[] parentValues)
        {
            if (parentValues.Length != parents.Count)
            {
                throw new ArgumentException(
                          "The number of parent value arguments ["
                          + parentValues.Length
                          + "] is not equal to the number of parents ["
                          + parents.Count + "] for this CPT.");
            }
            ProbabilityTable cc = new ProbabilityTable(getOn());

            //ProbabilityTable.Iterator  pti = new ProbabilityTable.Iterator() {
            //    private int idx = 0;


            //    public void iterate(Map<RandomVariable, Object> possibleAssignment,
            //            double probability) {
            //        cc.getValues()[idx] = probability;
            //        idx++;
            //    }
            //};
            //table.iterateOverTable(pti, parentValues);
            // TODO: this is screwed up
            return(cc);
        }
 public ProbabilityTableIterator(IProposition conjProp, ProbabilityTable ud, object[] values, ISet <IRandomVariable> vars)
 {
     this.conjProp = conjProp;
     this.ud       = ud;
     this.values   = values;
     this.vars     = vars;
 }
        internal CharacterProbabilisticSuggestionCollection(string text, int selection)
            : this()
        {
            Debug.Assert(text != null);
            Debug.Assert(0 <= selection);
            Debug.Assert(selection <= text.Length);

            var wordLength = text.ReverseWordLength(selection);

            if (0 < wordLength && wordLength < ProbabilityTable.MAX_WORD_LEN)
            {
                for (var ch = 'a'; ch <= 'z'; ch++)
                {
                    var probability = ProbabilityTable.GetProbability(wordLength,
                                                                      char.ToLower(text[selection - 1]), ch);
                    suggestions[ch - 'a'] = new CharacterSuggestion(ch, probability);
                }
            }
            else
            {
                for (var ch = 'a'; ch <= 'z'; ch++)
                {
                    var probability = ProbabilityTable.GetProbability(0, ProbabilityTable.WordBeginChar, ch);
                    suggestions[ch - 'a'] = new CharacterSuggestion(ch, probability);
                }
            }
        }
        public ICategoricalDistribution jointDistribution(params IProposition[] propositions)
        {
            ProbabilityTable       d        = null;
            IProposition           conjProp = ProbUtil.constructConjunction(propositions);
            ISet <IRandomVariable> vars     = CollectionFactory.CreateSet <IRandomVariable>(conjProp.getUnboundScope());

            if (vars.Size() > 0)
            {
                IRandomVariable[] distVars = vars.ToArray();

                ProbabilityTable ud     = new ProbabilityTable(distVars);
                object[]         values = new object[vars.Size()];

                ProbabilityTable.ProbabilityTableIterator di = new ProbabilityTableIterator(conjProp, ud, values, vars);

                distribution.iterateOverTable(di);

                d = ud;
            }
            else
            {
                // No Unbound Variables, therefore just return
                // the singular probability related to the proposition.
                d = new ProbabilityTable();
                d.setValue(0, prior(propositions));
            }
            return(d);
        }
        public void test_pointwiseProduct()
        {
            IRandomVariable xRV = new RandVar("X", new BooleanDomain());
            IRandomVariable yRV = new RandVar("Y", new BooleanDomain());
            IRandomVariable zRV = new RandVar("Z", new BooleanDomain());

            ProbabilityTable xyD = new ProbabilityTable(new double[] {
                // X = true, Y = true
                1.0,
                // X = true, Y = false
                2.0,
                // X = false, Y = true
                3.0,
                // X = false, Y = false
                4.0
            }, xRV, yRV);
            ProbabilityTable zD = new ProbabilityTable(new double[] { 3.0, 7.0 },
                                                       zRV);

            // Not commutative
            assertArrayEquals(new double[] { 3.0, 7.0, 6.0, 14.0, 9.0, 21.0,
                                             12.0, 28.0 }, xyD.pointwiseProduct(zD).getValues(),
                              DELTA_THRESHOLD);
            assertArrayEquals(new double[] { 3.0, 6.0, 9.0, 12.0, 7.0, 14.0,
                                             21.0, 28.0 }, zD.pointwiseProduct(xyD).getValues(),
                              DELTA_THRESHOLD);
        }
Example #7
0
 public CategoricalDistributionIteratorJointDistribution(IProposition conjProp, ISet <IRandomVariable> vars, ProbabilityTable ud, object[] values)
 {
     this.conjProp = conjProp;
     this.vars     = vars;
     this.ud       = ud;
     this.values   = values;
 }
Example #8
0
        protected void testForwardStep_UmbrellaWorld(IForwardStepInference uw)
        {
            // AIMA3e pg. 572
            // Day 0, no observations only the security guards prior beliefs
            // P(R<sub>0</sub>) = <0.5, 0.5>
            ICategoricalDistribution prior = new ProbabilityTable(new double[] { 0.5, 0.5 }, ExampleRV.RAIN_t_RV);

            // Day 1, the umbrella appears, so U<sub>1</sub> = true.
            // &asymp; <0.818, 0.182>
            ICollection <AssignmentProposition> e1 = CollectionFactory.CreateQueue <AssignmentProposition>();

            e1.Add(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV, true));
            ICategoricalDistribution f1 = uw.forward(prior, e1);

            assertArrayEquals(new double[] { 0.818, 0.182 }, f1.getValues(), DELTA_THRESHOLD);

            // Day 2, the umbrella appears, so U<sub>2</sub> = true.
            // &asymp; <0.883, 0.117>
            ICollection <AssignmentProposition> e2 = CollectionFactory.CreateQueue <AssignmentProposition>();

            e2.Add(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV, true));
            ICategoricalDistribution f2 = uw.forward(f1, e2);

            assertArrayEquals(new double[] { 0.883, 0.117 }, f2.getValues(),
                              DELTA_THRESHOLD);
        }
Example #9
0
        public virtual ICategoricalDistribution jointDistribution(params IProposition[] propositions)
        {
            ProbabilityTable       d        = null;
            IProposition           conjProp = ProbUtil.constructConjunction(propositions);
            ISet <IRandomVariable> vars     = CollectionFactory.CreateSet <IRandomVariable>(conjProp.getUnboundScope());

            if (vars.Size() > 0)
            {
                IRandomVariable[] distVars = new IRandomVariable[vars.Size()];
                int i = 0;
                foreach (IRandomVariable rv in vars)
                {
                    distVars[i] = rv;
                    ++i;
                }

                ProbabilityTable ud     = new ProbabilityTable(distVars);
                object[]         values = new object[vars.Size()];

                CategoricalDistributionIterator di = new CategoricalDistributionIteratorJointDistribution(conjProp, vars, ud, values);

                IRandomVariable[] X = conjProp.getScope().ToArray();
                bayesInference.Ask(X, new AssignmentProposition[0], bayesNet).iterateOver(di);

                d = ud;
            }
            else
            {
                // No Unbound Variables, therefore just return
                // the singular probability related to the proposition.
                d = new ProbabilityTable();
                d.setValue(0, prior(propositions));
            }
            return(d);
        }
Example #10
0
 public ProbabilityTableIteratorImpl(IBayesianNetwork bn, ProbabilityTable q, ObservedEvidence e, IRandomVariable[] x, EnumerationAsk enumerationAsk)
 {
     this.bn             = bn;
     this.q              = q;
     this.e              = e;
     this.x              = x;
     this.enumerationAsk = enumerationAsk;
 }
        public void test_iterateOverTable_fixedValues()
        {
            RandVar          aRV   = new RandVar("A", new BooleanDomain());
            RandVar          bRV   = new RandVar("B", new BooleanDomain());
            RandVar          cRV   = new RandVar("C", new BooleanDomain());
            ProbabilityTable ptABC = new ProbabilityTable(new double[] {
                // A = true, B = true, C = true
                1.0,
                // A = true, B = true, C = false
                10.0,
                // A = true, B = false, C = true
                100.0,
                // A = true, B = false, C = false
                1000.0,
                // A = false, B = true, C = true
                10000.0,
                // A = false, B = true, C = false
                100000.0,
                // A = false, B = false, C = true
                1000000.0,
                // A = false, B = false, C = false
                10000000.0
            }, aRV, bRV, cRV);

            ICollection <double> answer = CollectionFactory.CreateQueue <double>();

            ProbabilityTable.ProbabilityTableIterator pti = new iter(answer);

            answer.Clear();
            ptABC.iterateOverTable(pti, new AssignmentProposition(aRV, true));
            Assert.AreEqual(1111.0, sumOf(answer), DELTA_THRESHOLD);

            answer.Clear();
            ptABC.iterateOverTable(pti, new AssignmentProposition(aRV, false));
            Assert.AreEqual(11110000.0, sumOf(answer), DELTA_THRESHOLD);

            answer.Clear();
            ptABC.iterateOverTable(pti, new aima.net.probability.proposition.AssignmentProposition(bRV, true));
            Assert.AreEqual(110011.0, sumOf(answer), DELTA_THRESHOLD);

            answer.Clear();
            ptABC.iterateOverTable(pti, new AssignmentProposition(bRV, false));
            Assert.AreEqual(11001100.0, sumOf(answer), DELTA_THRESHOLD);

            answer.Clear();
            ptABC.iterateOverTable(pti, new AssignmentProposition(cRV, true));
            Assert.AreEqual(1010101.0, sumOf(answer), DELTA_THRESHOLD);

            answer.Clear();
            ptABC.iterateOverTable(pti, new AssignmentProposition(cRV, false));
            Assert.AreEqual(10101010.0, sumOf(answer), DELTA_THRESHOLD);

            answer.Clear();
            ptABC.iterateOverTable(pti, new AssignmentProposition(bRV, true),
                                   new AssignmentProposition(cRV, true));
            Assert.AreEqual(10001.0, sumOf(answer), DELTA_THRESHOLD);
        }
Example #12
0
        private ICategoricalDistribution initBackwardMessage()
        {
            ProbabilityTable b = new ProbabilityTable(tToTm1StateVarMap.GetKeys());

            for (int i = 0; i < b.size(); ++i)
            {
                b.setValue(i, 1.0);
            }

            return(b);
        }
Example #13
0
        protected void testBackwardStep_UmbrellaWorld(IBackwardStepInference uw)
        {
            // AIMA3e pg. 575
            ICategoricalDistribution            b_kp2t = new ProbabilityTable(new double[] { 1.0, 1.0 }, ExampleRV.RAIN_t_RV);
            ICollection <AssignmentProposition> e2     = CollectionFactory.CreateQueue <AssignmentProposition>();

            e2.Add(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV, true));
            ICategoricalDistribution b1 = uw.backward(b_kp2t, e2);

            assertArrayEquals(new double[] { 0.69, 0.41 }, b1.getValues(), DELTA_THRESHOLD);
        }
Example #14
0
        static void forwardBackWardDemo()
        {
            System.Console.WriteLine("DEMO: Forward-BackWard");
            System.Console.WriteLine("======================");

            System.Console.WriteLine("Umbrella World");
            System.Console.WriteLine("--------------");
            ForwardBackward uw = new ForwardBackward(
                GenericTemporalModelFactory.getUmbrellaWorldTransitionModel(),
                GenericTemporalModelFactory.getUmbrellaWorld_Xt_to_Xtm1_Map(),
                GenericTemporalModelFactory.getUmbrellaWorldSensorModel());

            ICategoricalDistribution prior = new ProbabilityTable(new double[] {
                0.5, 0.5
            }, ExampleRV.RAIN_t_RV);

            // Day 1
            ICollection <ICollection <AssignmentProposition> > evidence = CollectionFactory.CreateQueue <ICollection <AssignmentProposition> >();
            ICollection <AssignmentProposition> e1 = CollectionFactory.CreateQueue <AssignmentProposition>();

            e1.Add(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV, true));
            evidence.Add(e1);

            ICollection <ICategoricalDistribution> smoothed = uw.forwardBackward(evidence, prior);

            System.Console.WriteLine("Day 1 (Umbrealla_t=true) smoothed:\nday 1 = " + smoothed.Get(0));

            // Day 2
            ICollection <AssignmentProposition> e2 = CollectionFactory.CreateQueue <AssignmentProposition>();

            e2.Add(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV, true));
            evidence.Add(e2);

            smoothed = uw.forwardBackward(evidence, prior);

            System.Console.WriteLine("Day 2 (Umbrealla_t=true) smoothed:\nday 1 = "
                                     + smoothed.Get(0) + "\nday 2 = " + smoothed.Get(1));

            // Day 3
            ICollection <AssignmentProposition> e3 = CollectionFactory.CreateQueue <AssignmentProposition>();

            e3.Add(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV, false));
            evidence.Add(e3);

            smoothed = uw.forwardBackward(evidence, prior);

            System.Console.WriteLine("Day 3 (Umbrealla_t=false) smoothed:\nday 1 = "
                                     + smoothed.Get(0) + "\nday 2 = " + smoothed.Get(1)
                                     + "\nday 3 = " + smoothed.Get(2));

            System.Console.WriteLine("======================");
        }
        public void CoverCharacterPrediction()
        {
            var validChar = ProbabilityTable.GetProbability(1, 'a', 'b');

            Assert.AreNotEqual(0, validChar);

            var invalidChar = ProbabilityTable.GetProbability(0, '+', '¬');

            Assert.AreEqual(0, invalidChar);

            var tooLongWord = ProbabilityTable.GetProbability(128, 'a', 'b');

            Assert.AreEqual(0, tooLongWord);
        }
Example #16
0
        // function ENUMERATION-ASK(X, e, bn) returns a distribution over X

        /**
         * The ENUMERATION-ASK algorithm in Figure 14.9 evaluates expression trees
         * (Figure 14.8) using depth-first recursion.
         *
         * @param X
         *            the query variables.
         * @param observedEvidence
         *            observed values for variables E.
         * @param bn
         *            a Bayes net with variables {X} &cup; E &cup; Y /* Y = hidden
         *            variables //
         * @return a distribution over the query variables.
         */
        public ICategoricalDistribution enumerationAsk(IRandomVariable[] X,
                                                       AssignmentProposition[] observedEvidence,
                                                       IBayesianNetwork bn)
        {
            // Q(X) <- a distribution over X, initially empty
            ProbabilityTable Q = new ProbabilityTable(X);
            ObservedEvidence e = new ObservedEvidence(X, observedEvidence, bn);

            // for each value x<sub>i</sub> of X do
            ProbabilityTable.ProbabilityTableIterator di = new ProbabilityTableIteratorImpl(bn, Q, e, X, this);
            Q.iterateOverTable(di);

            // return NORMALIZE(Q(X))
            return(Q.normalize());
        }
        public FullJointDistributionModel(double[] values, params IRandomVariable[] vars)
        {
            if (null == vars)
            {
                throw new IllegalArgumentException("Random Variables describing the model's representation of the World need to be specified.");
            }

            distribution = new ProbabilityTable(values, vars);

            representation = CollectionFactory.CreateSet <IRandomVariable>();
            for (int i = 0; i < vars.Length; ++i)
            {
                representation.Add(vars[i]);
            }
            representation = CollectionFactory.CreateReadOnlySet <IRandomVariable>(representation);
        }
Example #18
0
        public FullJointDistributionModel(double[] values, params RandomVariable[] vars)
        {
            if (null == vars)
            {
                throw new ArgumentException(
                          "Random Variables describing the model's representation of the World need to be specified.");
            }

            distribution = new ProbabilityTable(values, vars);

            representation = new Set <RandomVariable>();
            for (int i = 0; i < vars.Length; i++)
            {
                representation.add(vars[i]);
            }
            //representation = Collections.unmodifiableSet(representation);
        }
Example #19
0
        public virtual ICategoricalDistribution GetConditioningCase(params AssignmentProposition[] parentValues)
        {
            if (parentValues.Length != parents.Size())
            {
                throw new IllegalArgumentException(
                          "The number of parent value arguments ["
                          + parentValues.Length
                          + "] is not equal to the number of parents ["
                          + parents.Size() + "] for this CPT.");
            }
            ProbabilityTable cc = new ProbabilityTable(GetOn());

            ProbabilityTable.ProbabilityTableIterator pti = new GetConditionCaseIterator(cc);
            table.iterateOverTable(pti, parentValues);

            return(cc);
        }
Example #20
0
        public CategoricalDistribution jointDistribution(
            params IProposition[] propositions)
        {
            ProbabilityTable d        = null;
            IProposition     conjProp = ProbUtil
                                        .constructConjunction(propositions);
            LinkedHashSet <RandomVariable> vars = new LinkedHashSet <RandomVariable>(
                conjProp.getUnboundScope());

            if (vars.Count > 0)
            {
                RandomVariable[] distVars = new RandomVariable[vars.Count];
                vars.CopyTo(distVars);

                ProbabilityTable ud     = new ProbabilityTable(distVars);
                Object[]         values = new Object[vars.Count];

                //ProbabilityTable.Iterator di = new ProbabilityTable.Iterator() {

                //    public void iterate(Map<RandomVariable, Object> possibleWorld,
                //            double probability) {
                //        if (conjProp.holds(possibleWorld)) {
                //            int i = 0;
                //            for (RandomVariable rv : vars) {
                //                values[i] = possibleWorld.get(rv);
                //                i++;
                //            }
                //            int dIdx = ud.getIndex(values);
                //            ud.setValue(dIdx, ud.getValues()[dIdx] + probability);
                //        }
                //    }
                //};

                //distribution.iterateOverTable(di);
                // TODO:
                d = ud;
            }
            else
            {
                // No Unbound Variables, therefore just return
                // the singular probability related to the proposition.
                d = new ProbabilityTable();
                d.setValue(0, prior(propositions));
            }
            return(d);
        }
Example #21
0
        /// <summary>
        /// Gets the random value within a specified range, except max value;
        /// </summary>
        /// <param name="table">The table.</param>
        /// <param name="min">The minimum.</param>
        /// <param name="max">The maximum.</param>
        /// <param name="isReversed">if set to <c>true</c> [isReversed].</param>
        /// <returns></returns>
        public static int GetRandomValue(this ProbabilityTable <int> table, int min, int max, bool isReversed)
        {
            var potentialValues = Enumerable.Range(min, max - min).ToList();

            var batchSize = (int)Math.Ceiling(potentialValues.Count / _batchCount);

            var potentialValuesTable = potentialValues.GroupBy(v => v / batchSize + 1)
                                       .SelectMany(g => g.Select(v => new { Value = v, Probability = table.GetProbability(GetBatchNumber((int)g.Key, isReversed)) })).ToList();

            var randomTable = potentialValuesTable
                              .SelectMany(v => Enumerable.Range(1, (int)Math.Ceiling(v.Probability * _probabilityMultiplier))
                                          .Select(i => v.Value))
                              .ToList();

            var random = LinearUniformRandom.GetInstance.Next(randomTable.Count);

            return(randomTable[random]);
        }
Example #22
0
        public virtual IFactor GetFactorFor(params AssignmentProposition[] evidence)
        {
            ISet <IRandomVariable> fofVars = CollectionFactory.CreateSet <IRandomVariable>(table.getFor());

            foreach (AssignmentProposition ap in evidence)
            {
                fofVars.Remove(ap.getTermVariable());
            }
            ProbabilityTable fof = new ProbabilityTable(fofVars);

            // Otherwise need to iterate through the table for the
            // non evidence variables.
            object[] termValues = new object[fofVars.Size()];
            ProbabilityTable.ProbabilityTableIterator di = new getFactorForIterator(termValues, fof);
            table.iterateOverTable(di, evidence);

            return(fof);
        }
Example #23
0
        protected void testForwardBackward_UmbrellaWorld(IForwardBackwardInference uw)
        {
            // AIMA3e pg. 572
            // Day 0, no observations only the security guards prior beliefs
            // P(R<sub>0</sub>) = <0.5, 0.5>
            ICategoricalDistribution prior = new ProbabilityTable(new double[] { 0.5, 0.5 }, ExampleRV.RAIN_t_RV);

            // Day 1
            ICollection <ICollection <AssignmentProposition> > evidence = CollectionFactory.CreateQueue <ICollection <AssignmentProposition> >();
            ICollection <AssignmentProposition> e1 = CollectionFactory.CreateQueue <AssignmentProposition>();

            e1.Add(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV, true));
            evidence.Add(e1);

            ICollection <ICategoricalDistribution> smoothed = uw.forwardBackward(evidence, prior);

            Assert.AreEqual(1, smoothed.Size());
            assertArrayEquals(new double[] { 0.818, 0.182 }, smoothed.Get(0).getValues(), DELTA_THRESHOLD);

            // Day 2
            ICollection <AssignmentProposition> e2 = CollectionFactory.CreateQueue <AssignmentProposition>();

            e2.Add(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV, true));
            evidence.Add(e2);

            smoothed = uw.forwardBackward(evidence, prior);

            Assert.AreEqual(2, smoothed.Size());
            assertArrayEquals(new double[] { 0.883, 0.117 }, smoothed.Get(0).getValues(), DELTA_THRESHOLD);
            assertArrayEquals(new double[] { 0.883, 0.117 }, smoothed.Get(1).getValues(), DELTA_THRESHOLD);

            // Day 3
            ICollection <AssignmentProposition> e3 = CollectionFactory.CreateQueue <AssignmentProposition>();

            e3.Add(new AssignmentProposition(ExampleRV.UMBREALLA_t_RV, false));
            evidence.Add(e3);

            smoothed = uw.forwardBackward(evidence, prior);

            Assert.AreEqual(3, smoothed.Size());
            assertArrayEquals(new double[] { 0.861, 0.138 }, smoothed.Get(0).getValues(), DELTA_THRESHOLD);
            assertArrayEquals(new double[] { 0.799, 0.201 }, smoothed.Get(1).getValues(), DELTA_THRESHOLD);
            assertArrayEquals(new double[] { 0.190, 0.810 }, smoothed.Get(2).getValues(), DELTA_THRESHOLD);
        }
Example #24
0
        public CPT(IRandomVariable on, double[] values, params IRandomVariable[] conditionedOn)
        {
            this.on = on;
            if (null == conditionedOn)
            {
                conditionedOn = new IRandomVariable[0];
            }
            IRandomVariable[] tableVars = new IRandomVariable[conditionedOn.Length + 1];
            for (int i = 0; i < conditionedOn.Length; ++i)
            {
                tableVars[i] = conditionedOn[i];
                parents.Add(conditionedOn[i]);
            }
            tableVars[conditionedOn.Length] = on;
            table = new ProbabilityTable(values, tableVars);
            onDomain.AddAll(((IFiniteDomain)on.getDomain()).GetPossibleValues());

            checkEachRowTotalsOne();
        }
Example #25
0
        public ICategoricalDistribution forward(ICategoricalDistribution f1_t, ICollection <AssignmentProposition> e_tp1)
        {
            ICategoricalDistribution s1 = new ProbabilityTable(f1_t.getFor());

            // Set up required working variables
            IProposition[] props = new IProposition[s1.getFor().Size()];
            int            i     = 0;

            foreach (IRandomVariable rv in s1.getFor())
            {
                props[i] = new RandVar(rv.getName(), rv.getDomain());
                ++i;
            }
            IProposition Xtp1 = ProbUtil.constructConjunction(props);

            AssignmentProposition[] xt = new AssignmentProposition[tToTm1StateVarMap.Size()];
            IMap <IRandomVariable, AssignmentProposition> xtVarAssignMap = CollectionFactory.CreateInsertionOrderedMap <IRandomVariable, AssignmentProposition>();

            i = 0;
            foreach (IRandomVariable rv in tToTm1StateVarMap.GetKeys())
            {
                xt[i] = new AssignmentProposition(tToTm1StateVarMap.Get(rv), "<Dummy Value>");
                xtVarAssignMap.Put(rv, xt[i]);
                ++i;
            }

            // Step 1: Calculate the 1 time step prediction
            // &sum;<sub>x<sub>t</sub></sub>
            CategoricalDistributionIterator if1_t = new CategoricalDistributionIteratorImpl(transitionModel,
                                                                                            xtVarAssignMap, s1, Xtp1, xt);

            f1_t.iterateOver(if1_t);

            // Step 2: multiply by the probability of the evidence
            // and normalize
            // <b>P</b>(e<sub>t+1</sub> | X<sub>t+1</sub>)
            ICategoricalDistribution s2 = sensorModel.posteriorDistribution(ProbUtil
                                                                            .constructConjunction(e_tp1.ToArray()), Xtp1);

            return(s2.multiplyBy(s1).normalize());
        }
Example #26
0
        public CategoricalDistribution enumerationAsk(RandomVariable[] X,
                                                      AssignmentProposition[] observedEvidence,
                                                      BayesianNetwork bn)
        {
            // Q(X) <- a distribution over X, initially empty
            ProbabilityTable Q = new ProbabilityTable(X);
            ObservedEvidence e = new ObservedEvidence(X, observedEvidence, bn);

            // for each value x<sub>i</sub> of X do
            //    ProbabilityTable.Iterator di = new ProbabilityTable.Iterator()
            //                                       {
            //                                           int cnt = 0;

            //                                                   /**
            //     * <pre>
            //     * Q(x<sub>i</sub>) <- ENUMERATE-ALL(bn.VARS, e<sub>x<sub>i</sub></sub>)
            //     *   where e<sub>x<sub>i</sub></sub> is e extended with X = x<sub>i</sub>
            //     * </pre>
            //     */
            //                                                   public void iterate(Map<RandomVariable,
            //                                           Object > possibleWorld,
            //                                           double probability) {
            //                                                      for (int i = 0; i < X.length; i++) {
            //                                                      e.setExtendedValue(X[i],
            //                                           possibleWorld.get(X[i]));
            //                                       }
            //    Q.setValue(cnt,
            //               enumerateAll(bn.getVariablesInTopologicalOrder(), e));
            //    cnt++;
            //}
            //}
            //    ;
            //    Q.iterateOverTable(di);

            //    // return NORMALIZE(Q(X))
            //    return Q.normalize();
            // TODO: need to clean this up, fail for now
            return(null);
        }
Example #27
0
        public ICategoricalDistribution backward(ICategoricalDistribution b_kp2t, ICollection <AssignmentProposition> e_kp1)
        {
            ICategoricalDistribution b_kp1t = new ProbabilityTable(b_kp2t.getFor());

            // Set up required working variables
            IProposition[] props = new IProposition[b_kp1t.getFor().Size()];
            int            i     = 0;

            foreach (IRandomVariable rv in b_kp1t.getFor())
            {
                IRandomVariable prv = tToTm1StateVarMap.Get(rv);
                props[i] = new RandVar(prv.getName(), prv.getDomain());
                ++i;
            }
            IProposition Xk = ProbUtil.constructConjunction(props);

            AssignmentProposition[] ax_kp1 = new AssignmentProposition[tToTm1StateVarMap.Size()];
            IMap <IRandomVariable, AssignmentProposition> x_kp1VarAssignMap = CollectionFactory.CreateInsertionOrderedMap <IRandomVariable, AssignmentProposition>();

            i = 0;
            foreach (IRandomVariable rv in b_kp1t.getFor())
            {
                ax_kp1[i] = new AssignmentProposition(rv, "<Dummy Value>");
                x_kp1VarAssignMap.Put(rv, ax_kp1[i]);
                ++i;
            }
            IProposition x_kp1 = ProbUtil.constructConjunction(ax_kp1);

            props = e_kp1.ToArray();
            IProposition pe_kp1 = ProbUtil.constructConjunction(props);

            // &sum;<sub>x<sub>k+1</sub></sub>
            CategoricalDistributionIterator ib_kp2t = new CategoricalDistributionIteratorImpl2(x_kp1VarAssignMap,
                                                                                               sensorModel, transitionModel, b_kp1t, pe_kp1, Xk, x_kp1);

            b_kp2t.iterateOver(ib_kp2t);

            return(b_kp1t);
        }
Example #28
0
    public override void OnInspectorGUI()
    {
        ProbabilityTable wpt = (ProbabilityTable)target;

        EditorGUILayout.BeginVertical();
        EditorGUILayout.LabelField("Items");
        float tmpProb = 0;

        for (int i = 0; i < wpt.Size; i++)
        {
            tmpProb = wpt.probabilities[i];
            EditorGUILayout.BeginHorizontal();
            wpt.items[i] = EditorGUILayout.ObjectField(wpt.items[i], typeof(Object), true, GUILayout.Width(200));
            tmpProb      = EditorGUILayout.Slider(tmpProb, 0, 1);     //EditorGUILayout.FloatField(tmpProb,GUILayout.Width(100));
            if (GUI.changed)
            {
                wpt.SetProbability(i, tmpProb);
            }
            if (GUILayout.Button("Remove"))
            {
                wpt.RemoveEntry(i);
            }
            EditorGUILayout.EndHorizontal();
        }

        if (GUILayout.Button("Add Entry"))
        {
            wpt.AddItem(null);
        }

        if (GUILayout.Button("Reset Probabilities"))
        {
            wpt.ResetProbabilities();
        }
        EditorGUILayout.EndVertical();
        EditorGUIUtility.LookLikeControls();
    }
        public void test_pointwiseProductPOS()
        {
            IRandomVariable xRV = new RandVar("X", new BooleanDomain());
            IRandomVariable yRV = new RandVar("Y", new BooleanDomain());
            IRandomVariable zRV = new RandVar("Z", new BooleanDomain());

            ProbabilityTable xyD = new ProbabilityTable(new double[] {
                // X = true, Y = true
                1.0,
                // X = true, Y = false
                2.0,
                // X = false, Y = true
                3.0,
                // X = false, Y = false
                4.0
            }, xRV, yRV);
            ProbabilityTable zD = new ProbabilityTable(new double[] { 3.0, 7.0 },
                                                       zRV);

            // Make commutative by specifying an order for the product
            assertArrayEquals(xyD.pointwiseProduct(zD).getValues(), zD
                              .pointwiseProductPOS(xyD, xRV, yRV, zRV).getValues(),
                              DELTA_THRESHOLD);
        }
 public Demographic(DemographicProcessesConfiguration configuration, ProbabilityTable <int> birthProbability, ProbabilityTable <int> deathProbability)
 {
     _configuration    = configuration;
     _birthProbability = birthProbability;
     _deathProbability = deathProbability;
 }