Esempio n. 1
0
        public void DataContractAndDataContractJsonSerializersVectorTest()
        {
            for (var vectorType = 0; vectorType < 4; vectorType++)
            {
                Vector v;
                if (vectorType == 0)
                {
                    v = Vector.FromArray(3.5, 4.3);
                }
                else
                {
                    var sparsity = Sparsity.Sparse;
                    if (vectorType == 1)
                    {
                        sparsity = Sparsity.Sparse;
                    }
                    else if (vectorType == 2)
                    {
                        sparsity = Sparsity.ApproximateWithTolerance(0.1);
                    }
                    else if (vectorType == 3)
                    {
                        sparsity = Sparsity.Piecewise;
                    }
                    v    = Vector.Constant(3, 1.4, sparsity);
                    v[1] = 2.5;
                }

                var v2 = CloneDataContract(v);
                Assert.Equal(0, v.MaxDiff(v2), 1e-10);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Tests EP and BP gate exit ops for Bernoulli random variable for correctness given message parameters and a shift.
        /// </summary>
        /// <param name="gate1ProbTrue">Probability of being true for the variable when the selector is true.</param>
        /// <param name="gate2ProbTrue">Probability of being true for the variable when the selector is false.</param>
        /// <param name="selectorProbTrue">Probability of being true for the selector variable.</param>
        /// <param name="shift">The value of the shift.</param>
        private void DoBernoulliExitTest(double gate1ProbTrue, double gate2ProbTrue, double selectorProbTrue, double shift)
        {
            const double ExitTwoProbTrue = 0.3; // ExitTwo op depends on the incoming message from outside the gate
            var          cases = new[] { Bernoulli.FromLogOdds(Math.Log(selectorProbTrue) - shift), Bernoulli.FromLogOdds(Math.Log(1 - selectorProbTrue) - shift) };
            var          values = new[] { new Bernoulli(gate1ProbTrue), new Bernoulli(gate2ProbTrue) };
            var          exitTwo = new Bernoulli(ExitTwoProbTrue);
            Bernoulli    value1, value2;

            double expectedProbTrueFromExit = (selectorProbTrue * gate1ProbTrue) + ((1 - selectorProbTrue) * gate2ProbTrue);

            value1 = GateExitOp <bool> .ExitAverageConditional(new Bernoulli(), cases, values, new Bernoulli());

            value2 = BeliefPropagationGateExitOp.ExitAverageConditional(cases, values, new Bernoulli());
            Assert.Equal(expectedProbTrueFromExit, value1.GetProbTrue(), 1e-4);
            Assert.Equal(expectedProbTrueFromExit, value2.GetProbTrue(), 1e-4);

            double gate1Scale = (ExitTwoProbTrue * gate1ProbTrue) + ((1 - ExitTwoProbTrue) * (1 - gate1ProbTrue));
            double gate2Scale = (ExitTwoProbTrue * gate2ProbTrue) + ((1 - ExitTwoProbTrue) * (1 - gate2ProbTrue));
            double expectedProbTrueFromExitTwo =
                (selectorProbTrue * gate1ProbTrue / gate1Scale) + ((1 - selectorProbTrue) * gate2ProbTrue / gate2Scale);
            double expectedProbFalseFromExitTwo =
                (selectorProbTrue * (1 - gate1ProbTrue) / gate1Scale) + ((1 - selectorProbTrue) * (1 - gate2ProbTrue) / gate2Scale);

            expectedProbTrueFromExitTwo /= expectedProbTrueFromExitTwo + expectedProbFalseFromExitTwo;
            value1 = GateExitTwoOp.ExitTwoAverageConditional <Bernoulli>(exitTwo, cases[0], cases[1], values, new Bernoulli());
            value2 = BeliefPropagationGateExitTwoOp.ExitTwoAverageConditional(exitTwo, cases[0], cases[1], values, new Bernoulli());
            Assert.Equal(expectedProbTrueFromExitTwo, value1.GetProbTrue(), 1e-4);
            Assert.Equal(expectedProbTrueFromExitTwo, value2.GetProbTrue(), 1e-4);
        }
Esempio n. 3
0
        public void SparseDirichletProduct()
        {
            double    commonPseudoCount     = 1.0;
            double    nonCommonPseudoCount1 = 10.0;
            double    nonCommonPseudoCount2 = 30.0;
            Dirichlet d1 = new Dirichlet(
                SparseVector.FromSparseValues(100, commonPseudoCount, new List <SparseElement>
            {
                new SparseElement(20, nonCommonPseudoCount1),
                new SparseElement(55, nonCommonPseudoCount1)
            }));

            Dirichlet d2 = new Dirichlet(
                SparseVector.FromSparseValues(100, commonPseudoCount, new List <SparseElement>
            {
                new SparseElement(25, nonCommonPseudoCount2),
                new SparseElement(55, nonCommonPseudoCount2)
            }));

            Dirichlet d = d1 * d2;

            Assert.Equal(Sparsity.Sparse, d.Sparsity);
            SparseVector sv = (SparseVector)(d.PseudoCount);

            Assert.Equal(3, sv.SparseValues.Count);
        }
Esempio n. 4
0
 /// <summary>
 /// A helper function for evidence messages when the output of the factor is not observed.
 /// </summary>
 /// <param name="str">The message to <c>str</c>.</param>.
 private static void TestEvidence(StringDistribution str)
 {
     Assert.Equal(0, StringFormatOp_RequireEveryPlaceholder_NoArgumentNames.LogEvidenceRatio(str));
     Assert.Equal(0, StringFormatOp_RequireEveryPlaceholder.LogEvidenceRatio(str));
     Assert.Equal(0, StringFormatOp_AllowMissingPlaceholders_NoArgumentNames.LogEvidenceRatio(str));
     Assert.Equal(0, StringFormatOp_AllowMissingPlaceholders.LogEvidenceRatio(str));
 }
Esempio n. 5
0
        public void RandRestartThreadsTest()
        {
            double sum1 = RandRestartThreadsTest_Helper();
            double sum2 = RandRestartThreadsTest_Helper();

            Assert.Equal(sum1, sum2, 1e-10);
        }
Esempio n. 6
0
        public void SparseDiscreteRatio()
        {
            double   commonValue     = 1.0;
            double   nonCommonValue1 = 10.0;
            double   nonCommonValue2 = 30.0;
            Discrete d1 = new Discrete(
                SparseVector.FromSparseValues(100, commonValue, new List <SparseElement>
            {
                new SparseElement(20, nonCommonValue1),
                new SparseElement(55, nonCommonValue1)
            }));

            Discrete d2 = new Discrete(
                SparseVector.FromSparseValues(100, commonValue, new List <SparseElement>
            {
                new SparseElement(25, nonCommonValue2),
                new SparseElement(55, nonCommonValue2)
            }));

            Discrete d = d1 / d2;

            Assert.Equal(Sparsity.Sparse, d.Sparsity);
            SparseVector sv = (SparseVector)(d.GetProbs());

            Assert.Equal(3, sv.SparseValues.Count);
        }
        public void ImpossibleBranchTest3()
        {
            Variable <string> str1 = Variable.StringLower().Named("str1");
            Variable <string> str2 = Variable.StringLower().Named("str2");
            Variable <string> text = Variable.New <string>().Named("text");

            Variable <int> selector = Variable.DiscreteUniform(2).Named("selector");

            using (Variable.Case(selector, 0))
            {
                text.SetTo(str1 + Variable.Constant(" ") + str2);
            }

            using (Variable.Case(selector, 1))
            {
                text.SetTo(str1);
            }

            text.ObservedValue = "abc";

            var engine            = new InferenceEngine();
            var selectorPosterior = engine.Infer <Discrete>(selector);
            var str1Posterior     = engine.Infer <StringDistribution>(str1);
            var str2Posterior     = engine.Infer <StringDistribution>(str2);

            Assert.True(selectorPosterior.IsPointMass && selectorPosterior.Point == 1);
            Assert.True(str1Posterior.IsPointMass && str1Posterior.Point == "abc");
            Assert.Equal(StringDistribution.Lower(), str2Posterior);
        }
Esempio n. 8
0
        public void Copy()
        {
            StringTransducer copy = StringTransducer.Copy();

            StringInferenceTestUtilities.TestTransducerValue(copy, "important", "important", 1.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "important", "i", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "important", "imp", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "important", "t", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "important", "mpo", 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, string.Empty, string.Empty, 1.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, "important", string.Empty, 0.0);
            StringInferenceTestUtilities.TestTransducerValue(copy, string.Empty, "important", 0.0);

            //// Test that projection on Copy() doesn't change the automaton

            StringAutomaton automaton = StringAutomaton.ConstantOn(2.0, "a", "ab", "ac");

            automaton = automaton.Sum(StringAutomaton.ConstantOn(1.0, "a"));
            automaton = automaton.Sum(StringAutomaton.Constant(2.0));
            automaton = automaton.Product(StringAutomaton.Constant(3.0));

            StringAutomaton automatonClone = copy.ProjectSource(automaton);

            Assert.Equal(automaton, automatonClone);
        }
Esempio n. 9
0
        public void GatedModelUncertainOutputTest()
        {
            Variable <bool>   selector = Variable.Bernoulli(0.5);
            Variable <string> concat   = Variable.New <string>();

            using (Variable.If(selector))
            {
                Variable <string> arg1 = Variable.Random(StringDistribution.OneOf("ab", "abc"));
                Variable <string> arg2 = Variable.Random(StringDistribution.OneOf("cd", "d"));
                concat.SetTo(arg1 + arg2);
            }

            using (Variable.IfNot(selector))
            {
                Variable <string> arg1 = "ab";
                Variable <string> arg2 = Variable.Random(StringDistribution.OneOf("cd", "d", "e"));
                concat.SetTo(arg1 + arg2);
            }

            Variable.ConstrainEqualRandom(concat, StringDistribution.OneOf("abcd", "abd"));

            var engine            = new InferenceEngine();
            var selectorPosterior = engine.Infer <Bernoulli>(selector);

            Assert.Equal(9.0 / 17.0, selectorPosterior.GetProbTrue());
        }
Esempio n. 10
0
        public void GatedModelObservedOutputTest2()
        {
            Variable <bool>   selector = Variable.Bernoulli(0.5);
            Variable <string> concat   = Variable.New <string>();

            using (Variable.If(selector))
            {
                Variable <string> arg1 = Variable.StringLower();
                Variable <string> arg2 = Variable.Random(StringDistribution.OneOf("cd", "d"));
                concat.SetTo(arg1 + arg2);
            }

            using (Variable.IfNot(selector))
            {
                Variable <string> arg1 = "ab";
                Variable <string> arg2 = Variable.Random(StringDistribution.OneOf("cd", "d", "e"));
                concat.SetTo(arg1 + arg2);
            }

            concat.ObservedValue = "abcd";

            var engine            = new InferenceEngine();
            var selectorPosterior = engine.Infer <Bernoulli>(selector);

            Assert.Equal(0.0, selectorPosterior.GetProbTrue());
        }
Esempio n. 11
0
        public void InferArgumentsFromConcatenationTest2()
        {
            var str1 = Variable.StringUpper(minLength: 0);
            var str2 = Variable.StringLower(minLength: 0);
            var str3 = Variable.StringUpper(minLength: 0);
            var s    = str1 + str2 + str3;

            s.ObservedValue = "ABC";
            var engine = new InferenceEngine();

            var posteriorOverStr1 = engine.Infer <StringDistribution>(str1);

            StringInferenceTestUtilities.TestIfIncludes(posteriorOverStr1, string.Empty, "A", "AB", "ABC");
            StringInferenceTestUtilities.TestIfExcludes(posteriorOverStr1, "B", "BC", "C");

            var posteriorOverStr2 = engine.Infer <StringDistribution>(str2);

            Assert.True(posteriorOverStr2.IsPointMass);
            Assert.Equal(string.Empty, posteriorOverStr2.Point);

            var posteriorOverStr3 = engine.Infer <StringDistribution>(str3);

            StringInferenceTestUtilities.TestIfIncludes(posteriorOverStr3, "ABC", "BC", "C", string.Empty);
            StringInferenceTestUtilities.TestIfExcludes(posteriorOverStr3, "A", "AB", "B");
        }
Esempio n. 12
0
        public void Transpose()
        {
            StringTransducer transducer = StringTransducer.Consume(StringAutomaton.Constant(3.0));
            StringTransducer transpose1 = StringTransducer.Transpose(transducer);
            StringTransducer transpose2 = transducer.Clone();

            transpose2.TransposeInPlace();

            var pairs = new[]
            {
                new[] { "a", string.Empty },
                new[] { string.Empty, string.Empty },
                new[] { "a", "bc" },
                new[] { "a", "a" }
            };

            foreach (string[] valuePair in pairs)
            {
                double referenceValue1 = transducer.GetValue(valuePair[0], valuePair[1]);
                Assert.Equal(referenceValue1, transpose1.GetValue(valuePair[1], valuePair[0]));
                Assert.Equal(referenceValue1, transpose2.GetValue(valuePair[1], valuePair[0]));

                double referenceValue2 = transducer.GetValue(valuePair[1], valuePair[0]);
                Assert.Equal(referenceValue2, transpose1.GetValue(valuePair[0], valuePair[1]));
                Assert.Equal(referenceValue2, transpose2.GetValue(valuePair[0], valuePair[1]));
            }
        }
Esempio n. 13
0
        public void WordMiddleLimitedLength()
        {
            const double Eps = 1e-6;

            var wordMiddleLimitedLength1 = WordStrings.WordMiddle(3, 5);

            StringInferenceTestUtilities.TestIfIncludes(wordMiddleLimitedLength1, " h w ", ". ab.", "...");
            StringInferenceTestUtilities.TestIfExcludes(
                wordMiddleLimitedLength1,
                "hello",
                " w",
                "hi ",
                "1 2",
                ".",
                "..",
                " hello world ",
                string.Empty);
            Assert.Equal(wordMiddleLimitedLength1.GetLogProb(" h w "), wordMiddleLimitedLength1.GetLogProb(" h "), Eps);

            var wordMiddleLimitedLength2 = WordStrings.WordMiddle(1, 5);

            StringInferenceTestUtilities.TestIfIncludes(wordMiddleLimitedLength2, " ", " h w ", ". ab.", "...");
            StringInferenceTestUtilities.TestIfExcludes(wordMiddleLimitedLength2, "hello", " w", "hi ", "1 2", " hello world ", string.Empty);
            Assert.Equal(wordMiddleLimitedLength2.GetLogProb("."), wordMiddleLimitedLength2.GetLogProb(" h "), Eps);

            var wordMiddleLimitedLength3 = WordStrings.WordMiddle(1, 2);

            StringInferenceTestUtilities.TestIfIncludes(wordMiddleLimitedLength3, " ", " .");
            StringInferenceTestUtilities.TestIfExcludes(wordMiddleLimitedLength3, "hw", " w", "h ", "12", " hello world ", string.Empty);
            Assert.Equal(wordMiddleLimitedLength3.GetLogProb("."), wordMiddleLimitedLength3.GetLogProb(".."), Eps);
        }
Esempio n. 14
0
        /// <summary>
        /// A helper function for evidence messages when the output of the factor is observed.
        /// </summary>
        /// <param name="str">The observed value of <c>str</c>.</param>
        /// <param name="format">The message from <c>format</c>.</param>
        /// <param name="args">The message from <c>args</c>.</param>
        /// <param name="expectedLogEvidence">
        /// The expected log-evidence if the format string is required to contain placeholders for all arguments.
        /// </param>
        /// <param name="expectedLogEvidenceWithMissingPlaceholders">
        /// The expected log-evidence if the format string may not contain placeholders for some arguments.
        /// </param>
        private static void TestEvidence(
            string str,
            StringDistribution format,
            StringDistribution[] args,
            double expectedLogEvidence,
            double expectedLogEvidenceWithMissingPlaceholders)
        {
            const double LogEvidenceEps = 1e-6;

            string[] argNames = GetDefaultArgumentNames(args.Length);

            Assert.Equal(
                expectedLogEvidence,
                StringFormatOp_RequireEveryPlaceholder_NoArgumentNames.LogEvidenceRatio(str, format, args),
                LogEvidenceEps);
            Assert.Equal(
                expectedLogEvidence,
                StringFormatOp_RequireEveryPlaceholder.LogEvidenceRatio(str, format, args, argNames),
                LogEvidenceEps);
            Assert.Equal(
                expectedLogEvidenceWithMissingPlaceholders,
                StringFormatOp_AllowMissingPlaceholders_NoArgumentNames.LogEvidenceRatio(str, format, args),
                LogEvidenceEps);
            Assert.Equal(
                expectedLogEvidenceWithMissingPlaceholders,
                StringFormatOp_AllowMissingPlaceholders.LogEvidenceRatio(str, format, args, argNames),
                LogEvidenceEps);
        }
        public void SimpleGatedModelTest4()
        {
            const double SelectorProbabilityTrue = 0.3;
            const string PreferredOption         = "a";

            Variable <string> str      = Variable.StringUniform().Named("str");
            Variable <bool>   selector = Variable.Bernoulli(SelectorProbabilityTrue).Named("selector");

            using (Variable.If(selector))
            {
                Variable.ConstrainEqual(str, PreferredOption);
            }

            using (Variable.IfNot(selector))
            {
                Variable.ConstrainEqualRandom(str, StringDistribution.Any());
            }

            str.ObservedValue = PreferredOption;

            var engine            = new InferenceEngine();
            var selectorPosterior = engine.Infer <Bernoulli>(selector);

            Assert.Equal(1.0, selectorPosterior.GetProbTrue(), 1e-6);
        }
        public void ImpossibleBranchTest1()
        {
            Variable <string> str      = Variable.New <string>().Named("str");
            Variable <bool>   selector = Variable.Bernoulli(0.5).Named("selector");

            using (Variable.If(selector))
            {
                var str1 = Variable.StringUniform();
                var str2 = Variable.StringUniform();
                str.SetTo(str1 + " " + str2);
            }

            using (Variable.IfNot(selector))
            {
                var str1 = Variable.StringUniform();
                var str2 = Variable.StringUniform();
                str.SetTo(str1 + "-" + str2);
            }

            str.ObservedValue = "ab-c";

            var engine            = new InferenceEngine();
            var selectorPosterior = engine.Infer <Bernoulli>(selector);

            Assert.Equal(1.0, selectorPosterior.GetProbFalse());
        }
        public void ComputeNormalizerWithManyNonTrivialLoops2()
        {
            StringAutomaton automaton = StringAutomaton.Zero();

            automaton.AddStates(6);

            automaton.States[0].AddEpsilonTransition(Weight.FromValue(0.2), automaton.States[1]);
            automaton.States[0].AddEpsilonTransition(Weight.FromValue(0.5), automaton.States[3]);
            automaton.States[0].EndWeight = Weight.FromValue(0.3);
            automaton.States[1].AddEpsilonTransition(Weight.FromValue(0.8), automaton.States[0]);
            automaton.States[1].AddEpsilonTransition(Weight.FromValue(0.1), automaton.States[2]);
            automaton.States[1].EndWeight = Weight.FromValue(0.1);
            automaton.States[2].EndWeight = Weight.FromValue(1.0);
            automaton.States[3].AddEpsilonTransition(Weight.FromValue(0.2), automaton.States[4]);
            automaton.States[3].AddEpsilonTransition(Weight.FromValue(0.1), automaton.States[5]);
            automaton.States[3].EndWeight = Weight.FromValue(0.7);
            automaton.States[4].AddEpsilonTransition(Weight.FromValue(0.5), automaton.States[2]);
            automaton.States[4].AddEpsilonTransition(Weight.FromValue(0.5), automaton.States[6]);
            automaton.States[4].EndWeight = Weight.FromValue(0.0);
            automaton.States[5].AddEpsilonTransition(Weight.FromValue(0.1), automaton.States[3]);
            automaton.States[5].AddEpsilonTransition(Weight.FromValue(0.9), automaton.States[6]);
            automaton.States[5].EndWeight = Weight.Zero;
            automaton.States[6].EndWeight = Weight.One;

            AssertStochastic(automaton);
            Assert.Equal(0.0, automaton.GetLogNormalizer(), 1e-6);
            Assert.Equal(0.0, GetLogNormalizerByGetValue(automaton), 1e-6);
            Assert.Equal(0.0, GetLogNormalizerByGetValueWithTransducers(automaton), 1e-6);
        }
        public void StringFormatTest2()
        {
            var templates = Variable.Observed(new string[] { "My name is {0}.", "I'm {0}." });

            templates.Name = nameof(templates);
            var a = Variable.Random(StringDistribution.OneOf("John", "Tom"));

            a.Name = nameof(a);
            var templateNumber = Variable.DiscreteUniform(templates.Range);

            templateNumber.Name = nameof(templateNumber);
            var b = Variable.New <string>().Named("b");

            using (Variable.Switch(templateNumber))
            {
                b.SetTo(Variable.StringFormat(templates[templateNumber], a));
            }

            var engine = new InferenceEngine();

            engine.Compiler.GivePriorityTo(typeof(ReplicateOp_NoDivide));
            engine.Compiler.RecommendedQuality = QualityBand.Experimental;
            Test("a", engine.Infer <IDistribution <string> >(a), "John", "Tom");
            Test("b", engine.Infer <IDistribution <string> >(b), "My name is John.", "My name is Tom.", "I'm John.", "I'm Tom.");
            b.ObservedValue = "My name is John.";
            var tempNum = engine.Infer <Discrete>(templateNumber);

            Assert.Equal(new Discrete(1.0, 0.0), tempNum);
            Test("a", engine.Infer <IDistribution <string> >(a), "John");
        }
Esempio n. 19
0
        public void SampleGeometric()
        {
            Rand.Restart(96);

            const double StoppingProbability = 0.7;

            // The length of sequences sampled from this distribution must follow a geometric distribution
            StringAutomaton automaton = StringAutomaton.Zero();

            automaton.Start = automaton.AddState();
            automaton.Start.SetEndWeight(Weight.FromValue(StoppingProbability));
            automaton.Start.AddTransition('a', Weight.FromValue(1 - StoppingProbability), automaton.Start);
            StringDistribution dist = StringDistribution.FromWeightFunction(automaton);

            var       acc         = new MeanVarianceAccumulator();
            const int SampleCount = 30000;

            for (int i = 0; i < SampleCount; ++i)
            {
                string sample = dist.Sample();
                acc.Add(sample.Length);
            }

            const double ExpectedMean     = (1.0 - StoppingProbability) / StoppingProbability;
            const double ExpectedVariance = (1.0 - StoppingProbability) / (StoppingProbability * StoppingProbability);

            Assert.Equal(ExpectedMean, acc.Mean, 1e-2);
            Assert.Equal(ExpectedVariance, acc.Variance, 1e-2);
        }
Esempio n. 20
0
        public void MessageOpsTest()
        {
            const double Eps = 1e-6;

            StringDistribution str1 = StringOfLengthOp.StrAverageConditional(DiscreteChar.Letter(), 10);

            Assert.Equal(StringDistribution.Repeat(DiscreteChar.Letter(), 10, 10), str1);

            StringDistribution str2 = StringOfLengthOp.StrAverageConditional(
                DiscreteChar.PointMass('a'), Discrete.UniformInRange(5, 2, 4));

            Assert.Equal(StringDistribution.OneOf("aa", "aaa", "aaaa"), str2);

            StringDistribution str3 = StringOfLengthOp.StrAverageConditional(
                DiscreteChar.OneOf('a', 'b'), new Discrete(0.1, 0.0, 0.6, 0.3));

            StringInferenceTestUtilities.TestProbability(str3, 0.1, string.Empty);
            StringInferenceTestUtilities.TestProbability(str3, 0.6 / 4, "aa", "ab", "ba", "bb");
            StringInferenceTestUtilities.TestProbability(str3, 0.3 / 8, "aaa", "bbb", "abb", "bab");

            Discrete length1 = StringOfLengthOp.LengthAverageConditional(
                StringDistribution.OneOf("aa", "bbb"), DiscreteChar.PointMass('a'), Discrete.Uniform(10));

            Assert.Equal(Discrete.PointMass(2, 10), length1);

            Discrete length2 = StringOfLengthOp.LengthAverageConditional(
                StringDistribution.OneOf("aab", "ab", "b", "bc"), DiscreteChar.OneOf('a', 'b'), Discrete.Uniform(10));

            Assert.Equal(4.0 / 7.0, length2[1], Eps);
            Assert.Equal(2.0 / 7.0, length2[2], Eps);
            Assert.Equal(1.0 / 7.0, length2[3], Eps);
        }
        public void RepeatCorrectness()
        {
            var sourceDict = new Dictionary <string, double>()
            {
                ["a"]  = 0.5,
                ["aa"] = 0.5
            };
            var wf                 = StringDictionaryWeightFunction.FromDistinctValues(sourceDict);
            var repeatedWf         = wf.Repeat(0, 3);
            var expectedResultDict = new Dictionary <string, double>()
            {
                [string.Empty] = 1.0,
                ["a"]          = 0.5,
                ["aa"]         = 0.75,  // aa, a+a
                ["aaa"]        = 0.625, // aa+a, a+aa, a+a+a
                ["aaaa"]       = 0.625, // aa+aa, aa+a+a, a+aa+a, a+a+aa
                ["aaaaa"]      = 0.375, // aa+aa+a, aa+a+aa, a+aa+aa
                ["aaaaaa"]     = 0.125  // aa+aa+aa
            };

            Assert.Equal(expectedResultDict.Count, repeatedWf.Dictionary.Count);
            foreach (var kvp in expectedResultDict)
            {
                Assert.True(repeatedWf.Dictionary.TryGetValue(kvp.Key, out Weight weight));
                Assert.Equal(kvp.Value, weight.Value, MMath.Ulp1);
            }
        }
Esempio n. 22
0
 public void AssertEqualTo(MyClass that)
 {
     Assert.Equal(0, this.bernoulli.MaxDiff(that.bernoulli));
     Assert.Equal(0, this.beta.MaxDiff(that.beta));
     Assert.Equal(0, this.binomial.MaxDiff(that.binomial));
     Assert.Equal(0, this.conjugateDirichlet.MaxDiff(that.conjugateDirichlet));
     Assert.Equal(0, this.dirichlet.MaxDiff(that.dirichlet));
     Assert.Equal(0, this.discrete.MaxDiff(that.discrete));
     Assert.Equal(0, this.gamma.MaxDiff(that.gamma));
     Assert.Equal(0, this.gammaPower.MaxDiff(that.gammaPower));
     Assert.Equal(0, this.gaussian.MaxDiff(that.gaussian));
     Assert.Equal(0, this.nonconjugateGaussian.MaxDiff(that.nonconjugateGaussian));
     Assert.Equal(0, this.pointMass.MaxDiff(that.pointMass));
     Assert.Equal(0, this.sparseBernoulliList.MaxDiff(that.sparseBernoulliList));
     Assert.Equal(0, this.sparseBetaList.MaxDiff(that.sparseBetaList));
     Assert.Equal(0, this.sparseGammaList.MaxDiff(that.sparseGammaList));
     Assert.Equal(0, this.truncatedGamma.MaxDiff(that.truncatedGamma));
     Assert.Equal(0, this.truncatedGaussian.MaxDiff(that.truncatedGaussian));
     Assert.Equal(0, this.wrappedGaussian.MaxDiff(that.wrappedGaussian));
     Assert.Equal(0, this.sparseGaussianList.MaxDiff(that.sparseGaussianList));
     Assert.Equal(0, this.unnormalizedDiscrete.MaxDiff(that.unnormalizedDiscrete));
     Assert.Equal(0, this.vectorGaussian.MaxDiff(that.vectorGaussian));
     Assert.Equal(0, this.wishart.MaxDiff(that.wishart));
     Assert.Equal(0, this.pareto.MaxDiff(that.pareto));
     Assert.Equal(0, this.poisson.MaxDiff(that.poisson));
     Assert.Equal(0, ga.MaxDiff(that.ga));
     Assert.Equal(0, vga.MaxDiff(that.vga));
     Assert.Equal(0, ga2D.MaxDiff(that.ga2D));
     Assert.Equal(0, vga2D.MaxDiff(that.vga2D));
     Assert.Equal(0, gaJ.MaxDiff(that.gaJ));
     Assert.Equal(0, vgaJ.MaxDiff(that.vgaJ));
     Assert.Equal(0, this.sparseGp.MaxDiff(that.sparseGp));
     Assert.True(this.quantileEstimator.ValueEquals(that.quantileEstimator));
 }
Esempio n. 23
0
        public void OneOfTest()
        {
            var abc = StringDistribution.OneOf("a", "b", "c");
            var s   = abc.ToString();

            Console.WriteLine("a or b or c:" + s);
            Assert.Equal("[a|b|c]", s);
        }
        public void PointMassDetectionLoopInDeadEnd()
        {
            StringAutomaton f = StringAutomaton.Zero();

            f.Start.AddTransition('a', Weight.FromValue(0.5)).AddSelfTransition('a', Weight.FromValue(0.5)).AddTransition('b', Weight.One);
            f.Start.AddTransition('b', Weight.FromValue(0.5)).EndWeight = Weight.One;
            Assert.Equal("b", f.TryComputePoint());
        }
        public void PointMassDetectionWithDeadLoop()
        {
            StringAutomaton f = StringAutomaton.Zero();

            f.Start.AddTransition('a', Weight.FromValue(0.5)).AddTransition('b', Weight.Zero, f.Start);
            f.Start.AddTransitionsForSequence("abc").EndWeight = Weight.One;
            Assert.Equal("abc", f.TryComputePoint());
        }
        public void PointMassDetectionWithEpsilonLoop()
        {
            StringAutomaton f = StringAutomaton.Zero();

            AddEpsilonLoop(f.Start, 5, 0.5);
            f.Start.AddTransitionsForSequence("abc").EndWeight = Weight.One;
            Assert.Equal("abc", f.TryComputePoint());
        }
Esempio n. 27
0
        public void Repeat2()
        {
            var baseDist = StringDistribution.OneOf("a", "b");
            var dist1    = StringDistribution.Repeat(baseDist, minTimes: 1, maxTimes: 3);
            var dist2    = StringDistribution.Repeat(DiscreteChar.OneOf('a', 'b'), minTimes: 1, maxTimes: 3);

            Assert.Equal(dist2, dist1);
        }
 /// <summary>
 /// Tests whether the logarithm of the value of a given automaton on given strings equals to a specified value.
 /// </summary>
 /// <param name="automaton">The automaton.</param>
 /// <param name="trueLogValue">The expected logarithm of the function value.</param>
 /// <param name="strings">The strings to test.</param>
 public static void TestValue(ListAutomaton <string, StringDistribution> automaton, double trueValue, params List <string>[] strings)
 {
     foreach (var str in strings)
     {
         double logValue = automaton.GetLogValue(str);
         Assert.Equal(Math.Log(trueValue), logValue, LogValueEps);
     }
 }
Esempio n. 29
0
        public void NormalCdfRatioTest()
        {
            double r0 = MMath.Sqrt2PI / 2;

            Assert.Equal(r0, MMath.NormalCdfRatio(0));
            Assert.Equal(r0, MMath.NormalCdfRatio(6.6243372842224754E-170));
            Assert.Equal(r0, MMath.NormalCdfRatio(-6.6243372842224754E-170));
        }
Esempio n. 30
0
        public void WordMiddle()
        {
            var wordMiddle = WordStrings.WordMiddle();

            StringInferenceTestUtilities.TestIfIncludes(wordMiddle, " hello world ", ". abc.", ". abc. def gh. ", " ", "..");
            StringInferenceTestUtilities.TestIfExcludes(wordMiddle, "hello", " world", "hi ", "1 2", string.Empty);
            Assert.Equal(wordMiddle.GetLogProb(" "), wordMiddle.GetLogProb(" world "));
        }