Exemplo n.º 1
0
        public void MaritzJarrettConfidenceIntervalWeighedTest1()
        {
            var random       = new Random(42);
            var distribution = new BetaDistribution(2, 10);

            double[] data    = distribution.Random(random).Next(10);
            var      sample1 = new Sample(data);
            var      sample2 = new Sample(data, new ConstantSequence(1).GenerateArray(data.Length));
            var      sample3 = new Sample(
                data.Concat(new[] { 10.0, 10.0, 10.0 }).ToArray(),
                new ConstantSequence(1).GenerateArray(data.Length).Concat(new[] { 0.0, 0.0, 0.0 }).ToArray()
                );

            var estimator   = HarrellDavisQuantileEstimator.Instance;
            var probability = Probability.Half;
            var level       = ConfidenceLevel.L90;

            var ci1 = estimator.GetQuantileConfidenceIntervalEstimator(sample1, probability).GetConfidenceInterval(level);
            var ci2 = estimator.GetQuantileConfidenceIntervalEstimator(sample2, probability).GetConfidenceInterval(level);
            var ci3 = estimator.GetQuantileConfidenceIntervalEstimator(sample3, probability).GetConfidenceInterval(level);

            Output.WriteLine("CI1: " + ci1.ToString("N9"));
            Output.WriteLine("CI2: " + ci2.ToString("N9"));
            Output.WriteLine("CI3: " + ci3.ToString("N9"));

            var comparer = new AbsoluteEqualityComparer(1e-9);

            Assert.True(ci1.Equals(ci2, comparer));
            Assert.True(ci1.Equals(ci3, comparer));
        }
Exemplo n.º 2
0
        public void BetaMeanTest()
        {
            double alpha = 0.42;
            double beta  = 1.57;

            BetaDistribution betaDistribution = new BetaDistribution(alpha, beta);

            double mean   = betaDistribution.Mean;                                                     // 0.21105527638190955
            double median = betaDistribution.Median;                                                   // 0.11577706212908731
            double var    = betaDistribution.Variance;                                                 // 0.055689279830523512
            double chf    = betaDistribution.CumulativeHazardFunction(x: 0.27);                        // 1.1828193992944409
            double cdf    = betaDistribution.DistributionFunction(x: 0.27);                            // 0.69358638272337991
            double pdf    = betaDistribution.ProbabilityDensityFunction(x: 0.27);                      // 0.94644031936694828
            double lpdf   = betaDistribution.LogProbabilityDensityFunction(x: 0.27);                   // -0.055047364344046057
            double hf     = betaDistribution.HazardFunction(x: 0.27);                                  // 3.0887671630877072
            double ccdf   = betaDistribution.ComplementaryDistributionFunction(x: 0.27);               // 0.30641361727662009
            double icdf   = betaDistribution.InverseDistributionFunction(p: cdf);                      // 0.26999999068687469

            string str = betaDistribution.ToString(System.Globalization.CultureInfo.InvariantCulture); // "B(x; α = 0.42, β = 1.57)

            Assert.AreEqual(0.21105527638190955, mean);
            Assert.AreEqual(0.11577706212908731, median);
            Assert.AreEqual(0.055689279830523512, var);
            Assert.AreEqual(1.1828193992944409, chf);
            Assert.AreEqual(0.69358638272337991, cdf);
            Assert.AreEqual(0.94644031936694828, pdf);
            Assert.AreEqual(-0.055047364344046057, lpdf);
            Assert.AreEqual(3.0887671630877072, hf);
            Assert.AreEqual(0.30641361727662009, ccdf);
            Assert.AreEqual(0.27, icdf, 1e-10);
            Assert.AreEqual("B(x; α = 0.42, β = 1.57)", str);

            Assert.IsFalse(Double.IsNaN(median));
        }
Exemplo n.º 3
0
        public void HarrellDavisQuantileEstimatorWeightedTest1()
        {
            var random       = new Random(42);
            var distribution = new BetaDistribution(2, 10);

            double[] data1   = distribution.Random(random).Next(10);
            double[] data2   = data1.Select(x => x + 100).ToArray();
            double[] data    = data1.Concat(data2).ToArray();
            var      samples = new List <Sample> {
                new Sample(data1)
            };

            for (int i = 1; i <= 40; i++)
            {
                samples.Add(new Sample(data, ExponentialDecaySequence.CreateFromHalfLife(i).GenerateArray(data.Length)));
            }
            samples.Add(new Sample(data));
            var medians = samples.Select(s => HarrellDavisQuantileEstimator.Instance.GetMedian(s)).ToList();

            for (int i = 0; i < medians.Count; i++)
            {
                Output.WriteLine($"Median[{i}] =  {medians[i]:N9}");
            }
            for (int i = 0; i < medians.Count - 1; i++)
            {
                Assert.True(medians[i] < medians[i + 1]);
            }
        }
Exemplo n.º 4
0
        public async Task YeetItem([Remainder] string item)
        {
            var avatar  = EntityConverter.ConvertUser(Context.User);
            var factory = new PlayerFighterFactory();
            var p       = factory.CreatePlayerFighter(avatar);
            var inv     = avatar.Inv;

            var embed = new EmbedBuilder();
            var it    = inv.GetItem(item);

            if (inv.Remove(item))
            {
                UserAccountProvider.StoreUser(avatar);
                var maxdist = p.Stats.Atk * Math.Sqrt(p.Stats.Spd) / Math.Log(Math.Max(it.Price / 2, 2)) / 6;
                var level   = Math.Min(avatar.LevelNumber, 100);
                var a       = 5 + (double)level / 2;
                var b       = 55 - (double)level / 2;
                var beta    = new BetaDistribution(a, b);
                embed.WithDescription(
                    $"{Context.User.Username} yeets {it.Icon}{it.Name} {Math.Round(beta.Generate(1).FirstOrDefault() * maxdist, 2)} meters away.");
                embed.WithColor(it.Color);

                _ = Context.Channel.SendMessageAsync("", false, embed.Build());
            }
            else
            {
                embed.WithDescription(":x: You can only get rid of unequipped items in your possession.");
                embed.WithColor(Colors.Get("Error"));
                _ = Context.Channel.SendMessageAsync("", false, embed.Build());
            }

            await Task.CompletedTask;
        }
        public void BetaMLEFitTest1()
        {
            double[] x = samples;

            {
                BetaDistribution target = new BetaDistribution(0, 1);
                var options             = new BetaOptions()
                {
                    Method = BetaEstimationMethod.Moments
                };
                target.Fit(x, options);

                Assert.AreEqual(1, target.Alpha, 0.04);
                Assert.AreEqual(3, target.Beta, 0.5);
            }

            {
                BetaDistribution target = new BetaDistribution(0, 1);
                var options             = new BetaOptions()
                {
                    Method = BetaEstimationMethod.MaximumLikelihood
                };
                target.Fit(x, options);

                Assert.AreEqual(1, target.Alpha, 0.04);
                Assert.AreEqual(3, target.Beta, 0.55);
            }
        }
Exemplo n.º 6
0
        public void MaritzJarrettConfidenceIntervalTest(double confidenceLevel, double minSuccessRate, double maxSuccessRate)
        {
            var       random       = new Random(42);
            var       distribution = new BetaDistribution(2, 10);
            var       generator    = new LimitedRandomGenerator(distribution.Random(random).Next(1000), random);
            var       estimator    = HarrellDavisQuantileEstimator.Instance;
            double    median       = distribution.Median;
            const int iterations   = 1000;

            for (int n = 5; n <= 10; n++)
            {
                int successCount = 0;
                for (int i = 0; i < iterations; i++)
                {
                    var sample             = generator.Next(n).ToSample();
                    var confidenceInterval = estimator
                                             .GetQuantileConfidenceIntervalEstimator(sample, 0.5)
                                             .GetConfidenceInterval(confidenceLevel);
                    if (confidenceInterval.Contains(median))
                    {
                        successCount++;
                    }
                }

                double successRate = successCount * 1.0 / iterations;
                Output.WriteLine($"n = {n}, successRate = {successRate:N4}");
                Assert.True(minSuccessRate <= successRate && successRate <= maxSuccessRate);
            }
        }
Exemplo n.º 7
0
        //End of ui.cs file Contents

        //-------------------------------------------------------------------------

        //Begin of Random.cs file contents
        /// <summary>
        /// Initializes the random-number generator with a specific seed.
        /// </summary>
        public void Initialize(uint seed)
        {
            RandomNumberGenerator = new MT19937Generator(seed);
            betaDist              = new BetaDistribution(RandomNumberGenerator);
            betaPrimeDist         = new BetaPrimeDistribution(RandomNumberGenerator);
            cauchyDist            = new CauchyDistribution(RandomNumberGenerator);
            chiDist               = new ChiDistribution(RandomNumberGenerator);
            chiSquareDist         = new ChiSquareDistribution(RandomNumberGenerator);
            continuousUniformDist = new ContinuousUniformDistribution(RandomNumberGenerator);
            erlangDist            = new ErlangDistribution(RandomNumberGenerator);
            exponentialDist       = new ExponentialDistribution(RandomNumberGenerator);
            fisherSnedecorDist    = new FisherSnedecorDistribution(RandomNumberGenerator);
            fisherTippettDist     = new FisherTippettDistribution(RandomNumberGenerator);
            gammaDist             = new GammaDistribution(RandomNumberGenerator);
            laplaceDist           = new LaplaceDistribution(RandomNumberGenerator);
            lognormalDist         = new LognormalDistribution(RandomNumberGenerator);
            normalDist            = new NormalDistribution(RandomNumberGenerator);
            paretoDist            = new ParetoDistribution(RandomNumberGenerator);
            powerDist             = new PowerDistribution(RandomNumberGenerator);
            rayleighDist          = new RayleighDistribution(RandomNumberGenerator);
            studentsTDist         = new StudentsTDistribution(RandomNumberGenerator);
            triangularDist        = new TriangularDistribution(RandomNumberGenerator);
            weibullDist           = new WeibullDistribution(RandomNumberGenerator);
            poissonDist           = new PoissonDistribution(RandomNumberGenerator);

            // generator.randomGenerator = new MT19937Generator(seed);
        }
Exemplo n.º 8
0
        private void GenerateIndividual_Click(object sender, RoutedEventArgs e)
        {
            var xCount                = int.Parse(XCountRandom.Text);
            var alternativesCount     = int.Parse(AltCountRandom.Text);
            var constraintsCount      = int.Parse(ConstraintCountRandom.Text);
            var optDirection          = OptDirectionComboBoxRandom.SelectedIndex == 0 ? "max" : "min";
            var distributionTypeIndex = DistributionType.SelectedIndex;
            CustomDistribution distribution;

            switch (distributionTypeIndex)
            {
            case 0: distribution = new BetaDistribution(double.Parse(BetaA.Text), double.Parse(BetaB.Text)); break;

            case 1: distribution = new ChiDistribution(int.Parse(ChiK.Text)); break;

            case 2: distribution = new GammaDistribution(double.Parse(GammaShape.Text), double.Parse(GammaRate.Text)); break;

            case 3: distribution = new NormalDistribution(double.Parse(NormalMean.Text), double.Parse(NormalStdDev.Text)); break;

            case 4: distribution = new UniformDistribution(double.Parse(UniformMin.Text), double.Parse(UniformMax.Text)); break;

            default: distribution = new NormalDistribution(double.Parse(NormalMean.Text), double.Parse(NormalStdDev.Text)); break;
            }
            _viewModel.GenerateIndividualProblem(xCount, alternativesCount, constraintsCount, optDirection, distribution);
            ResultsSaveStackPanel.Visibility = Visibility.Visible;
        }
Exemplo n.º 9
0
        public void BetaInversion()
        {
            // test that beta distribution is accurately inverted over a wide range of a, b, P

            foreach (double a in TestUtilities.GenerateRealValues(0.01, 100.0, 8))
            {
                foreach (double b in cs)
                {
                    BetaDistribution B = new BetaDistribution(a, b);

                    foreach (double P in probabilities)
                    {
                        Console.WriteLine("a={0} b={1} P={2}", a, b, P);
                        double x = B.InverseLeftProbability(P);
                        Console.WriteLine("  x={0} P(x)={1}", x, B.LeftProbability(x));
                        // we would like to test that P(x) = P, but floating point limitations prevent us from meeting this standard
                        // P(x) changes so fast at extremes that sometimes even the minimal change in x causes a change
                        // in P(x) larger than our target precision; so instead we test that our routine gets us
                        // as close as it can, by checking that P(x-e) < P < P(x+e)
                        double Px  = B.LeftProbability(x);
                        double Pxm = B.LeftProbability(Math.Min(0.0, x * (1.0 - TestUtilities.TargetPrecision)));
                        double Pxp = B.LeftProbability(Math.Max(x * (1.0 + TestUtilities.TargetPrecision), 1.0));
                        Assert.IsTrue((Pxm <= P) && (P <= Pxp));
                    }
                }
            }
        }
Exemplo n.º 10
0
        public void BetaDistributionConstructorTest()
        {
            double expected, actual;

            {
                BetaDistribution target = new BetaDistribution(1.73, 4.2);
                actual   = target.ProbabilityDensityFunction(-1);
                expected = 0;
                Assert.AreEqual(expected, actual, 1e-7);
                Assert.IsFalse(Double.IsNaN(actual));

                actual   = target.ProbabilityDensityFunction(0);
                expected = 0;
                Assert.AreEqual(expected, actual, 1e-7);
                Assert.IsFalse(Double.IsNaN(actual));

                actual   = target.ProbabilityDensityFunction(1);
                expected = 0;
                Assert.AreEqual(expected, actual, 1e-7);
                Assert.IsFalse(Double.IsNaN(actual));

                actual   = target.ProbabilityDensityFunction(0.2);
                expected = 2.27095841;
                Assert.AreEqual(expected, actual, 1e-7);
                Assert.IsFalse(Double.IsNaN(actual));

                actual   = target.ProbabilityDensityFunction(0.4);
                expected = 1.50022749;
                Assert.AreEqual(expected, actual, 1e-7);
                Assert.IsFalse(Double.IsNaN(actual));
            }
        }
Exemplo n.º 11
0
        public void TestBivariateRegression()
        {
            // Do a bunch of linear regressions. r^2 should be distributed as expected.

            double a0 = 1.0;
            double b0 = 0.0;

            Random rng = new Random(1001110000);
            ContinuousDistribution xDistribution = new UniformDistribution(Interval.FromEndpoints(-2.0, 4.0));
            ContinuousDistribution eDistribution = new NormalDistribution();

            List <double> r2Sample = new List <double>();

            for (int i = 0; i < 500; i++)
            {
                BivariateSample xySample = new BivariateSample();
                for (int k = 0; k < 10; k++)
                {
                    double x = xDistribution.GetRandomValue(rng);
                    double y = a0 + b0 * x + eDistribution.GetRandomValue(rng);
                    xySample.Add(x, y);
                }
                LinearRegressionResult fit = xySample.LinearRegression();
                double a = fit.Intercept.Value;
                double b = fit.Slope.Value;

                r2Sample.Add(fit.RSquared);
            }

            ContinuousDistribution r2Distribution = new BetaDistribution((2 - 1) / 2.0, (10 - 2) / 2.0);
            TestResult             ks             = r2Sample.KolmogorovSmirnovTest(r2Distribution);

            Assert.IsTrue(ks.Probability > 0.05);
        }
Exemplo n.º 12
0
        public void MedianTest()
        {
            double alpha = 0.42;
            double beta  = 1.57;

            BetaDistribution target = new BetaDistribution(alpha, beta);

            Assert.AreEqual(target.Median, target.InverseDistributionFunction(0.5));
        }
Exemplo n.º 13
0
        public void TestBetaRoundTrip()
        {
            // arrange
            var expected = new BetaDistribution(0.5, 0.5, 0.3, 0.7);

            // act
            var serialized   = expected.ToString();
            var deserialized = Distribution.DeserializeDistribution(serialized);
            var distribution = deserialized.IfNone(() => { Assert.Fail(); return(default !); });
        public void BetaMeanTest()
        {
            double alpha = 0.42;
            double beta  = 1.57;

            BetaDistribution betaDistribution = new BetaDistribution(alpha, beta);

            double mean   = betaDistribution.Mean;                                                     // 0.21105527638190955
            double median = betaDistribution.Median;                                                   // 0.11577706212908731
            double var    = betaDistribution.Variance;                                                 // 0.055689279830523512
            double mode   = betaDistribution.Mode;                                                     // 57.999999999999957

            double chf  = betaDistribution.CumulativeHazardFunction(x: 0.27);                          // 1.1828193992944409
            double cdf  = betaDistribution.DistributionFunction(x: 0.27);                              // 0.69358638272337991
            double pdf  = betaDistribution.ProbabilityDensityFunction(x: 0.27);                        // 0.94644031936694828
            double lpdf = betaDistribution.LogProbabilityDensityFunction(x: 0.27);                     // -0.055047364344046057
            double hf   = betaDistribution.HazardFunction(x: 0.27);                                    // 3.0887671630877072
            double ccdf = betaDistribution.ComplementaryDistributionFunction(x: 0.27);                 // 0.30641361727662009
            double icdf = betaDistribution.InverseDistributionFunction(p: cdf);                        // 0.26999999068687469

            string str = betaDistribution.ToString(System.Globalization.CultureInfo.InvariantCulture); // "B(x; α = 0.42, β = 1.57)

            Assert.AreEqual(0.21105527638190955, mean);
            Assert.AreEqual(0.11577706212908731, median);
            Assert.AreEqual(57.999999999999957, mode);
            Assert.AreEqual(0.055689279830523512, var);
            Assert.AreEqual(1.1828193992944409, chf);
            Assert.AreEqual(0.69358638272337991, cdf);
            Assert.AreEqual(0.94644031936694828, pdf);
            Assert.AreEqual(-0.055047364344046057, lpdf);
            Assert.AreEqual(3.0887671630877072, hf);
            Assert.AreEqual(0.30641361727662009, ccdf);
            Assert.AreEqual(0.27, icdf, 1e-10);
            Assert.AreEqual("B(x; α = 0.42, β = 1.57)", str);

            Assert.IsFalse(Double.IsNaN(median));

            var range1 = betaDistribution.GetRange(0.95);
            var range2 = betaDistribution.GetRange(0.99);
            var range3 = betaDistribution.GetRange(0.01);

            Assert.AreEqual(0.00045925525776717733, range1.Min);
            Assert.AreEqual(0.72381020663218609, range1.Max);
            Assert.AreEqual(0.0000099485893745082635, range2.Min);
            Assert.AreEqual(0.89625688707910811, range2.Max);
            Assert.AreEqual(0.0000099485893745082432, range3.Min);
            Assert.AreEqual(0.89625688707910811, range3.Max);

            Assert.AreEqual(0, betaDistribution.Support.Min);
            Assert.AreEqual(1, betaDistribution.Support.Max);

            Assert.AreEqual(betaDistribution.InverseDistributionFunction(0), betaDistribution.Support.Min);
            Assert.AreEqual(betaDistribution.InverseDistributionFunction(1), betaDistribution.Support.Max);
        }
Exemplo n.º 15
0
        public void BetaFitTest1()
        {
            double[] x = { 0.1, 0.5, 0.3, 0.8, 0.6, 0.7, 0.9, 0.9, 0.9, 0.9 };

            BetaDistribution target = new BetaDistribution(0, 1);

            target.Fit(x);

            Assert.AreEqual(1.1810718232044195, target.Alpha);
            Assert.AreEqual(0.60843093922651903, target.Beta);
        }
Exemplo n.º 16
0
        public void TestBetaWithBoundsGetSample()
        {
            // arrange
            var subject = new BetaDistribution(0.5, 0.5, 0.3, 0.7);

            // act
            var sample = subject.GetSample();

            // assert
            Assert.IsTrue(sample > 0.3 && sample < 0.7);
        }
Exemplo n.º 17
0
    // Start is called before the first frame update
    void Start()
    {
        rnd = new System.Random();
        betaDistribution = new BetaDistribution();

        bandits = new Bandit[numberOfBandits];

        for (int i = 0; i < numberOfBandits; i++)
        {
            bandits[i] = new Bandit(rnd.NextDouble());
        }
    }
        public void BetaFit_IntWeights()
        {
            double[] x = { 1.0, 0.1, 0.5, 0.3, 0.5, 0.8, 0.6, 0.7, 0.9, 0.9, 0.9 };
            int[]    w = { 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 2 };

            BetaDistribution target = new BetaDistribution(0, 1);

            target.Fit(x, w);

            Assert.AreEqual(1.1810718232044195, target.Alpha);
            Assert.AreEqual(0.60843093922651903, target.Beta, 1e-8);
        }
Exemplo n.º 19
0
        public void TestBetaWithBoundsFillSamples()
        {
            // arrange
            var subject = new BetaDistribution(0.5, 0.5, 0.3, 0.7);
            var samples = Range(0, 42).Map(_ => NaN).ToArray();

            // act
            subject.FillSamples(samples);

            // assert
            Assert.IsTrue(samples.All(d => d > 0.3 && d < 0.7));
        }
        public void BetaFit_RealWeights()
        {
            double[] x = { 1.0, 0.1, 0.5, 0.3, 0.5, 0.8, 0.6, 0.7, 0.9, 0.9, 0.9 };
            int[]    w = { 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 2 };

            BetaDistribution target = new BetaDistribution(0, 1);

            target.Fit(x, w.ToDouble());

            Assert.AreEqual(1.1401591160220996, target.Alpha);
            Assert.AreEqual(0.58735469613259694, target.Beta);
        }
Exemplo n.º 21
0
        public void TestMultivariateRegression()
        {
            double cz = 1.0;
            double cx = 0.0;
            double cy = 0.0;

            Random       rng           = new Random(1001110000);
            Distribution xDistribution = new UniformDistribution(Interval.FromEndpoints(-4.0, 8.0));
            Distribution yDistribution = new UniformDistribution(Interval.FromEndpoints(-8.0, 4.0));
            Distribution eDistribution = new NormalDistribution();

            Sample r2Sample = new Sample();

            for (int i = 0; i < 500; i++)
            {
                MultivariateSample xyzSample = new MultivariateSample(3);
                for (int k = 0; k < 12; k++)
                {
                    double x = xDistribution.GetRandomValue(rng);
                    double y = yDistribution.GetRandomValue(rng);
                    double z = cx * x + cy * y + cz + eDistribution.GetRandomValue(rng);
                    xyzSample.Add(x, y, z);
                }
                FitResult fit = xyzSample.LinearRegression(2);
                double    fcx = fit.Parameters[0];
                double    fcy = fit.Parameters[1];
                double    fcz = fit.Parameters[2];

                double ss2 = 0.0;
                double ss1 = 0.0;
                foreach (double[] xyz in xyzSample)
                {
                    ss2 += MoreMath.Sqr(xyz[2] - (fcx * xyz[0] + fcy * xyz[1] + fcz));
                    ss1 += MoreMath.Sqr(xyz[2] - xyzSample.Column(2).Mean);
                }
                double r2 = 1.0 - ss2 / ss1;
                r2Sample.Add(r2);
            }

            Console.WriteLine("{0} {1} {2} {3} {4}", r2Sample.Count, r2Sample.PopulationMean, r2Sample.StandardDeviation, r2Sample.Minimum, r2Sample.Maximum);

            Distribution r2Distribution = new BetaDistribution((3 - 1) / 2.0, (12 - 3) / 2.0);

            //Distribution r2Distribution = new BetaDistribution((10 - 2) / 2.0, (2 - 1) / 2.0);
            Console.WriteLine("{0} {1}", r2Distribution.Mean, r2Distribution.StandardDeviation);

            TestResult ks = r2Sample.KolmogorovSmirnovTest(r2Distribution);

            Console.WriteLine(ks.RightProbability);
            Console.WriteLine(ks.Probability);
        }
Exemplo n.º 22
0
        public async Task TestBetaCumulativeDistributionAtBounds()
        {
            // arrange
            var subject        = new BetaDistribution(0.5, 0.5, 0.3, 0.7);
            var expectedLowerP = (await GetNumDataAsync("pbeta(0.3, 0.5, 0.5)"))[0].Data[0];
            var expectedUpperP = (await GetNumDataAsync("pbeta(0.7, 0.5, 0.5)"))[0].Data[0];

            // act
            var(actualLowerP, actualUpperP) = subject.CumulativeDistributionAtBounds;

            // assert
            Assert.AreEqual(expectedLowerP, actualLowerP, Base.Constant.TOLERANCE);
            Assert.AreEqual(expectedUpperP, actualUpperP, Base.Constant.TOLERANCE);
        }
Exemplo n.º 23
0
        public static (double faintSuspicion, double strongSuspicion) GetSuspicionLevels(double mean, double sigma, double faintSuspicionCoefficient, double strongSuspicionCoefficient)
        {
            if (Math.Abs(sigma) < 1e-7)
            {
                return(1, 1);
            }
            var(alpha, beta) = GetBetaParameters(mean, sigma);
            var betaDistribution         = new BetaDistribution(alpha, beta);
            var faintSigmaToProbability  = new NormalDistribution(0, 1).DistributionFunction(faintSuspicionCoefficient);
            var strongSigmaToProbability = new NormalDistribution(0, 1).DistributionFunction(strongSuspicionCoefficient);
            var faintSuspicion           = betaDistribution.InverseDistributionFunction(faintSigmaToProbability);
            var strongSuspicion          = betaDistribution.InverseDistributionFunction(strongSigmaToProbability);

            return(faintSuspicion, strongSuspicion);
        }
Exemplo n.º 24
0
        public async Task TestBetaGetDensities()
        {
            // arrange
            var subject  = new BetaDistribution(0.5, 0.5);
            var expected = (await GetNumDataAsync(
                                "sapply(seq(qbeta(0.3, 0.5, 0.5), qbeta(0.7, 0.5, 0.5), length.out = 5), function(cd){dbeta(cd, 0.5, 0.5)})"
                                ))[0].Data.ToArr();

            // act
            var(_, actual) = subject.GetDensities(0.3, 0.7, 5);

            // assert
            Assert.IsTrue(actual.Count == 5);
            expected.Iter((i, d) => Assert.AreEqual(d, actual[i], Base.Constant.TOLERANCE));
        }
Exemplo n.º 25
0
        protected override void EndProcessing()
        {
            BetaDistribution dist;

            if (ParameterSetName == "Alpha")
            {
                dist = new BetaDistribution(Alpha, Beta);
            }
            else
            {
                dist = new BetaDistribution(Successes, Trials);
            }
            var obj = DistributionHelper.AddConvinienceMethods(dist);

            WriteObject(obj);
        }
        public void BetaGenerateTest()
        {
            Accord.Math.Tools.SetupGenerator(0);

            int n = 100000;

            double[] samples = BetaDistribution
                               .Random(alpha: 2, beta: 3, samples: n);

            Assert.AreEqual(n, samples.Length);

            var actual = BetaDistribution.Estimate(samples);

            Assert.AreEqual(2, actual.Alpha, 1e-2);
            Assert.AreEqual(3, actual.Beta, 1e-2);
        }
        public void LogLikelihoodTest()
        {
            var target = new BetaDistribution(3.0, 2.0);

            double sum = 0;

            for (int i = 0; i < samples.Length; i++)
            {
                sum -= target.LogProbabilityDensityFunction(samples[i]);
            }

            double expected = sum;
            double actual   = BetaDistribution.LogLikelihood(samples, target.Alpha, target.Beta);

            Assert.AreEqual(expected, actual, 1e-10);
        }
Exemplo n.º 28
0
        public void TestBivariateRegression()
        {
            double a0 = 1.0;
            double b0 = 0.0;

            Random       rng           = new Random(1001110000);
            Distribution xDistribution = new UniformDistribution(Interval.FromEndpoints(-2.0, 4.0));
            Distribution eDistribution = new NormalDistribution();

            Sample r2Sample = new Sample();

            for (int i = 0; i < 500; i++)
            {
                BivariateSample xySample = new BivariateSample();
                for (int k = 0; k < 10; k++)
                {
                    double x = xDistribution.GetRandomValue(rng);
                    double y = a0 + b0 * x + eDistribution.GetRandomValue(rng);
                    xySample.Add(x, y);
                }
                FitResult fit = xySample.LinearRegression();
                double    a   = fit.Parameters[0];
                double    b   = fit.Parameters[1];

                double ss2 = 0.0;
                double ss1 = 0.0;
                foreach (XY xy in xySample)
                {
                    ss2 += MoreMath.Sqr(xy.Y - (a + b * xy.X));
                    ss1 += MoreMath.Sqr(xy.Y - xySample.Y.Mean);
                }
                double r2 = 1.0 - ss2 / ss1;
                r2Sample.Add(r2);
            }

            Console.WriteLine("{0} {1} {2} {3} {4}", r2Sample.Count, r2Sample.PopulationMean, r2Sample.StandardDeviation, r2Sample.Minimum, r2Sample.Maximum);

            Distribution r2Distribution = new BetaDistribution((2 - 1) / 2.0, (10 - 2) / 2.0);

            //Distribution r2Distribution = new BetaDistribution((10 - 2) / 2.0, (2 - 1) / 2.0);
            Console.WriteLine("{0} {1}", r2Distribution.Mean, r2Distribution.StandardDeviation);

            TestResult ks = r2Sample.KolmogorovSmirnovTest(r2Distribution);

            Console.WriteLine(ks.RightProbability);
            Console.WriteLine(ks.Probability);
        }
Exemplo n.º 29
0
 public void TestBetaDistribution()
 {
     double[][] para =
     {
         new double[] { 2.5, 3.5, 0.2739037303169420423172000, 1.749247541974141744140178, 0.7393662913208028693203748, 0.5988730468534031966438193 }
     };
     for (int i = 0; i < para.Length; i++)
     {
         var tester = new ContDistTester(para[i], delegate(double a, double b)
         {
             var ret = new BetaDistribution(a, b);
             return(ret);
         }
                                         );
         tester.Test(1E-14);
     }
 }
        public void BetaMLEFit_IntWeights()
        {
            double[] x = { 1.0, 0.1, 0.5, 0.3, 0.5, 0.8, 0.6, 0.7, 0.9, 0.9, 0.9 };
            int[]    w = { 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 2 };

            BetaDistribution target = new BetaDistribution(0, 1);


            var options = new BetaOptions()
            {
                Method = BetaEstimationMethod.MaximumLikelihood
            };

            target.Fit(x, w, options);

            Assert.AreEqual(1.1810718232044195, target.Alpha);
            Assert.AreEqual(0.60843093922651903, target.Beta, 1e-10);
        }
/*        public Distribution(
                        DistributionType name,
                        double value1,
                        double value2
                        )
        {
            this.name = name;
            this.value1 = value1;
            this.value2 = value2;
        }*/
        //---------------------------------------------------------------------

        public static double GenerateRandomNum(DistributionType dist, double parameter1, double parameter2)
        {
            double randomNum = 0.0;
            /*if(dist == DistributionType.Normal)
            {
                NormalDistribution randVar = new NormalDistribution(RandomNumberGenerator.Singleton);
                randVar.Mu = parameter1;      // mean
                randVar.Sigma = parameter2;   // std dev
                randomNum = randVar.NextDouble();
            }
            if(dist == DistributionType.Lognormal)
            {
                LognormalDistribution randVar = new LognormalDistribution(RandomNumberGenerator.Singleton);
                randVar.Mu = parameter1;      // mean
                randVar.Sigma = parameter2;   // std dev
                randomNum = randVar.NextDouble();
            }*/
            if(dist == DistributionType.Weibull)
            {
                WeibullDistribution randVar = new WeibullDistribution(RandomNumberGenerator.Singleton);
                randVar.Alpha = parameter1;      // mean
                randVar.Lambda = parameter2;   // std dev
                randomNum = randVar.NextDouble();
            }

            if(dist == DistributionType.Gamma)
            {
                GammaDistribution randVar = new GammaDistribution(RandomNumberGenerator.Singleton);
                randVar.Alpha = parameter1;      // mean
                randVar.Theta = parameter2;   // std dev
                randomNum = randVar.NextDouble();
            }
            if(dist == DistributionType.Beta)
            {
                BetaDistribution randVar = new BetaDistribution(RandomNumberGenerator.Singleton);
                randVar.Alpha = parameter1;      // mean
                randVar.Beta = parameter2;   // std dev
                randomNum = randVar.NextDouble();
            }
            return randomNum;
        }
 /// <summary>
 /// Returns a new line chart plotting the specified function of the given distribution for 0.0001 &lt;= p &lt;= 0.9999.
 /// </summary>
 /// <param name="dist">The distribution.</param>
 /// <param name="function">The distribution function to plot.</param>
 /// <param name="numInterpolatedValues">The number of interpolated values.</param>
 /// <returns>A new chart.</returns>
 public static ChartControl ToChart( BetaDistribution dist, DistributionFunction function = DistributionFunction.PDF, int numInterpolatedValues = 100 )
 {
     ChartControl chart = GetDefaultChart();
       Update( ref chart, dist, function, numInterpolatedValues );
       return chart;
 }
 /// <summary>
 /// Updates the given chart with the specified distribution.
 /// </summary>
 /// <param name="chart">A chart.</param>
 /// <param name="dist">The distribution.</param>
 /// <param name="function">The distribution function to plot.</param>
 /// <param name="numInterpolatedValues">The number of interpolated values.</param>
 /// <returns>A new chart.</returns>
 /// <remarks>
 /// Plots the specified function of the given distribution for 0.0001 &lt;= p &lt;= 0.9999.
 /// <br/>
 /// Titles are added only if chart does not currently contain any titles.
 /// <br/>
 /// chart.Series[0] is replaced, or added if necessary.
 /// </remarks>
 public static void Update( ref ChartControl chart, BetaDistribution dist, DistributionFunction function = DistributionFunction.PDF, int numInterpolatedValues = 100 )
 {
     List<string> titles = new List<string>()
       {
     "BetaDistribution",
     String.Format("\u03B1={0}, \u03B2={1}", dist.Alpha, dist.Beta)
       };
       UpdateContinuousDistribution( ref chart, dist, titles, function, numInterpolatedValues );
 }
 /// <summary>
 /// Shows a new chart in a default form.
 /// </summary>
 /// <param name="dist">The distribution.</param>
 /// <param name="function">The distribution function to plot.</param>
 /// <param name="numInterpolatedValues">The number of interpolated values.</param>
 /// <remarks>
 /// Equivalent to:
 /// <code>
 /// NMathStatsChart.Show( ToChart( dist, function, numInterpolatedValues ) );
 /// </code>
 /// </remarks>
 public static void Show( BetaDistribution dist, DistributionFunction function = DistributionFunction.PDF, int numInterpolatedValues = 100 )
 {
     Show( ToChart( dist, function, numInterpolatedValues ) );
 }