Ejemplo n.º 1
0
        public void readWorkCenters()
        {
            using (var reader = new StreamReader(Path.Combine(DirectoryInputCSVs, "WorkCenters.csv")))
            {
                int row = 1;

                while (!reader.EndOfStream)
                {
                    string[] values = reader.ReadLine().Split(',');

                    if (row != 1)
                    {
                        WaferFabSettings.WorkCenters.Add(values[0]);
                        WaferFabSettings.WCServiceTimeDistributions.Add(values[0], new ExponentialDistribution(Convert.ToDouble(values[1])));
                        Distribution servDist = new ExponentialDistribution(Convert.ToDouble(values[1]));

                        if (values.Length > 3) // temporary adding x identical machines
                        {
                            WaferFabSettings.WCMachines.Add(values[0], Convert.ToInt32(values[3]));
                        }

                        WaferFabSettings.WCDispatcherTypes.Add(values[0], DispatcherBase.Type.RANDOM);
                    }
                    row++;
                }
            }
        }
Ejemplo n.º 2
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);
        }
        public void FitTest1()
        {
            double[] values =
            {
                0, 1, 2, 4, 2, 3, 5, 7, 4, 3, 2, 1, 4,
            };

            var exp = new ExponentialDistribution();

            exp.Fit(values);

            string actual;

            var cultureInfo = CultureInfo.GetCultureInfo("fr-FR");

#if NETCORE
            System.Globalization.CultureInfo.DefaultThreadCurrentCulture   = cultureInfo;
            System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
#else
            Thread.CurrentThread.CurrentCulture = cultureInfo;
#endif
            actual = exp.ToString("G3", CultureInfo.InvariantCulture);
            Assert.AreEqual("Exp(x; λ = 0.342)", actual);

            actual = exp.ToString("G3");
            Assert.AreEqual("Exp(x; λ = 0,342)", actual);

            actual = exp.ToString(CultureInfo.InvariantCulture);
            Assert.AreEqual("Exp(x; λ = 0.342105263157895)", actual);

            actual = exp.ToString();
            Assert.AreEqual("Exp(x; λ = 0,342105263157895)", actual);
        }
Ejemplo n.º 4
0
        protected override void EndProcessing()
        {
            var dist = new ExponentialDistribution(Rate);
            var obj  = DistributionHelper.AddConvinienceMethods(dist);

            WriteObject(obj);
        }
Ejemplo n.º 5
0
        private EstPoint[] EstBruteforce(double gammaFrom, double gammaTo, int steps, bool minus = false)
        {
            EstPoint[] estPoints = new EstPoint[steps];
            GammaBounds(ref gammaFrom, ref gammaTo);
            double step = (gammaTo - gammaFrom) / (steps - 1);
            var    opts = new ParallelOptions {
                MaxDegreeOfParallelism = Environment.ProcessorCount * 4
            };

            Parallel.For(0, steps, opts, g => {
                double gamma = gammaFrom + g * step;
                var distr    = MakeDistr(gamma);
                var rnd2     = new ExponentialDistribution(distr.Alpha);
                int w        = 0;
                for (int batch = 0; batch < BatchCount; batch++)
                {
                    double[] array = rnd2.Generate(BatchSize);
                    double delta   = Hill(distr, array) - distr.AlphaRev;
                    if (!minus && delta > distr.Bn || minus && delta < -distr.Bn)
                    {
                        w++;
                    }
                }
                double w0    = (double)w / BatchCount;
                double p0    = 1;             //NormalDistribution.Standard.InverseDistributionFunction(gamma);
                double d     = p0 * Math.Sqrt(w0 * (1 - w0) / BatchCount);
                estPoints[g] = new EstPoint(w0, d, gamma);
            });
            return(estPoints);
        }
 public void ConstructorTest()
 {
     ExponentialDistribution n = new ExponentialDistribution(3.42521);
     Assert.AreEqual(3.42521, n.Rate);
     Assert.AreEqual(0.29195290215782393, n.Mean);
     Assert.AreEqual(0.085236497078375897, n.Variance);
 }
Ejemplo n.º 7
0
        public void ExponentialFitUncertainty()
        {
            // check that the uncertainty in reported fit parameters is actually meaningful
            // it should be the standard deviation of fit parameter values in a sample of many fits

            // define a population distribution
            ExponentialDistribution distribution = new ExponentialDistribution(4.0);

            // draw a lot of samples from it; fit each sample and
            // record the reported parameter value and error of each
            Sample values        = new Sample();
            Sample uncertainties = new Sample();

            for (int i = 0; i < 128; i++)
            {
                Sample sample               = SampleTest.CreateSample(distribution, 8, i);
                ExponentialFitResult fit    = ExponentialDistribution.FitToSample(sample);
                UncertainValue       lambda = fit.Parameters[0].Estimate;
                values.Add(lambda.Value);
                uncertainties.Add(lambda.Uncertainty);
            }

            // the reported values should agree with the source distribution
            Assert.IsTrue(values.PopulationMean.ConfidenceInterval(0.95).ClosedContains(distribution.Mean));

            // the reported errors should agree with the standard deviation of the reported parameters
            Assert.IsTrue(values.PopulationStandardDeviation.ConfidenceInterval(0.95).ClosedContains(uncertainties.Mean));
        }
Ejemplo n.º 8
0
        public void Next()
        {
            var mean  = 2.0;
            var count = 100000;

            var values = Enumerable.Range(0, count)
                         .Select(i => ExponentialDistribution.Next(mean))
                         .OrderBy(x => x)
                         .ToArray();

            Console.WriteLine($"Mean of Values: {values.Average()}");

            var largeValues = values.SkipWhile(x => x < mean).ToArray();

            // 1/e
            Console.WriteLine($"Large Count Ratio: {(double)largeValues.Length / count}");
            // 2/e
            Console.WriteLine($"Large Sum Ratio: {largeValues.Sum() / (mean * count)}");

            Console.WriteLine();
            foreach (var g in values.GroupBy(x => (int)x))
            {
                Console.WriteLine($"{g.Key}: {g.Count()}");
            }
            Console.WriteLine();
            foreach (var g in values.GroupBy(x => Math.Floor(x * 10) / 10))
            {
                Console.WriteLine($"{g.Key:F1}: {g.Count()}");
            }
        }
Ejemplo n.º 9
0
        public void FitTest1()
        {
            double[] values =
            {
                0, 1, 2, 4, 2, 3, 5, 7, 4, 3, 2, 1, 4,
            };

            var exp = new ExponentialDistribution();

            exp.Fit(values);

            string actual;

            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR");

            actual = exp.ToString("G3", CultureInfo.InvariantCulture);
            Assert.AreEqual("Exp(x; λ = 0.342)", actual);

            actual = exp.ToString("G3");
            Assert.AreEqual("Exp(x; λ = 0,342)", actual);

            actual = exp.ToString(CultureInfo.InvariantCulture);
            Assert.AreEqual("Exp(x; λ = 0.342105263157895)", actual);

            actual = exp.ToString();
            Assert.AreEqual("Exp(x; λ = 0,342105263157895)", actual);
        }
        public void ConstructorTest2()
        {
            var exp = new ExponentialDistribution(rate: 0.42);

            double mean = exp.Mean;     // 2.3809523809523809
            double median = exp.Median; // 1.6503504299046317
            double var = exp.Variance;  // 5.6689342403628125

            double cdf = exp.DistributionFunction(x: 0.27); // 0.10720652870550407
            double pdf = exp.ProbabilityDensityFunction(x: 0.27); // 0.3749732579436883
            double lpdf = exp.LogProbabilityDensityFunction(x: 0.27); // -0.98090056770472311

            double ccdf = exp.ComplementaryDistributionFunction(x: 0.27); // 0.89279347129449593
            double icdf = exp.InverseDistributionFunction(p: cdf); // 0.27

            double hf = exp.HazardFunction(x: 0.27); // 0.42
            double chf = exp.CumulativeHazardFunction(x: 0.27); // 0.1134

            string str = exp.ToString(CultureInfo.InvariantCulture); // Exp(x; λ = 0.42)

            Assert.AreEqual(2.3809523809523809, mean);
            Assert.AreEqual(1.6503504299046317, median);
            Assert.AreEqual(5.6689342403628125, var);
            Assert.AreEqual(0.1134, chf);
            Assert.AreEqual(0.10720652870550407, cdf);
            Assert.AreEqual(0.3749732579436883, pdf);
            Assert.AreEqual(-0.98090056770472311, lpdf);
            Assert.AreEqual(0.42, hf);
            Assert.AreEqual(0.89279347129449593, ccdf);
            Assert.AreEqual(0.27, icdf);
            Assert.AreEqual("Exp(x; λ = 0.42)", str);
        }
        public void MultivariateMoments()
        {
            // create a random sample
            MultivariateSample     M  = new MultivariateSample(3);
            ContinuousDistribution d0 = new NormalDistribution();
            ContinuousDistribution d1 = new ExponentialDistribution();
            ContinuousDistribution d2 = new UniformDistribution();
            Random rng = new Random(1);
            int    n   = 10;

            for (int i = 0; i < n; i++)
            {
                M.Add(d0.GetRandomValue(rng), d1.GetRandomValue(rng), d2.GetRandomValue(rng));
            }

            // test that moments agree
            for (int i = 0; i < 3; i++)
            {
                int[] p = new int[3];
                p[i] = 1;
                Assert.IsTrue(TestUtilities.IsNearlyEqual(M.Column(i).Mean, M.RawMoment(p)));
                p[i] = 2;
                Assert.IsTrue(TestUtilities.IsNearlyEqual(M.Column(i).Variance, M.CentralMoment(p)));
                for (int j = 0; j < i; j++)
                {
                    int[] q = new int[3];
                    q[i] = 1;
                    q[j] = 1;
                    Assert.IsTrue(TestUtilities.IsNearlyEqual(M.TwoColumns(i, j).Covariance, M.CentralMoment(q)));
                }
            }
        }
        public void ConstructorTest2()
        {
            var exp = new ExponentialDistribution(rate: 0.42);

            double mean   = exp.Mean;                                     // 2.3809523809523809
            double median = exp.Median;                                   // 1.6503504299046317
            double var    = exp.Variance;                                 // 5.6689342403628125

            double cdf  = exp.DistributionFunction(x: 0.27);              // 0.10720652870550407
            double pdf  = exp.ProbabilityDensityFunction(x: 0.27);        // 0.3749732579436883
            double lpdf = exp.LogProbabilityDensityFunction(x: 0.27);     // -0.98090056770472311

            double ccdf = exp.ComplementaryDistributionFunction(x: 0.27); // 0.89279347129449593
            double icdf = exp.InverseDistributionFunction(p: cdf);        // 0.27

            double hf  = exp.HazardFunction(x: 0.27);                     // 0.42
            double chf = exp.CumulativeHazardFunction(x: 0.27);           // 0.1134

            string str = exp.ToString(CultureInfo.InvariantCulture);      // Exp(x; λ = 0.42)

            Assert.AreEqual(2.3809523809523809, mean);
            Assert.AreEqual(1.6503504299046317, median);
            Assert.AreEqual(5.6689342403628125, var);
            Assert.AreEqual(0.1134, chf);
            Assert.AreEqual(0.10720652870550407, cdf);
            Assert.AreEqual(0.3749732579436883, pdf);
            Assert.AreEqual(-0.98090056770472311, lpdf);
            Assert.AreEqual(0.42, hf);
            Assert.AreEqual(0.89279347129449593, ccdf);
            Assert.AreEqual(0.27, icdf);
            Assert.AreEqual("Exp(x; λ = 0.42)", str);
        }
Ejemplo n.º 13
0
        public void WilcoxonNullDistribution()
        {
            // Pick a very non-normal distribution
            ContinuousDistribution d = new ExponentialDistribution();

            Random rng = new Random(271828);

            foreach (int n in TestUtilities.GenerateIntegerValues(4, 64, 4))
            {
                Sample wSample = new Sample();
                ContinuousDistribution wDistribution = null;
                for (int i = 0; i < 128; i++)
                {
                    BivariateSample sample = new BivariateSample();
                    for (int j = 0; j < n; j++)
                    {
                        double x = d.GetRandomValue(rng);
                        double y = d.GetRandomValue(rng);
                        sample.Add(x, y);
                    }
                    TestResult wilcoxon = sample.WilcoxonSignedRankTest();
                    wSample.Add(wilcoxon.Statistic);
                    wDistribution = wilcoxon.Distribution;
                }

                TestResult ks = wSample.KolmogorovSmirnovTest(wDistribution);
                Assert.IsTrue(ks.Probability > 0.05);

                Assert.IsTrue(wSample.PopulationMean.ConfidenceInterval(0.99).ClosedContains(wDistribution.Mean));
                Assert.IsTrue(wSample.PopulationStandardDeviation.ConfidenceInterval(0.99).ClosedContains(wDistribution.StandardDeviation));
            }
        }
Ejemplo n.º 14
0
        public void KendallNullDistributionTest()
        {
            // Pick independent distributions for x and y, which needn't be normal and needn't be related.
            ContinuousDistribution xDistrubtion  = new LogisticDistribution();
            ContinuousDistribution yDistribution = new ExponentialDistribution();
            Random rng = new Random(314159265);

            // generate bivariate samples of various sizes
            foreach (int n in TestUtilities.GenerateIntegerValues(8, 64, 4))
            {
                Sample testStatistics = new Sample();
                ContinuousDistribution testDistribution = null;

                for (int i = 0; i < 128; i++)
                {
                    BivariateSample sample = new BivariateSample();
                    for (int j = 0; j < n; j++)
                    {
                        sample.Add(xDistrubtion.GetRandomValue(rng), yDistribution.GetRandomValue(rng));
                    }

                    TestResult result = sample.KendallTauTest();
                    testStatistics.Add(result.Statistic);
                    testDistribution = result.Distribution;
                }

                TestResult r2 = testStatistics.KolmogorovSmirnovTest(testDistribution);
                Assert.IsTrue(r2.RightProbability > 0.05);

                Assert.IsTrue(testStatistics.PopulationMean.ConfidenceInterval(0.99).ClosedContains(testDistribution.Mean));
                Assert.IsTrue(testStatistics.PopulationVariance.ConfidenceInterval(0.99).ClosedContains(testDistribution.Variance));
            }
        }
Ejemplo n.º 15
0
        public void GammaFromExponential()
        {
            // test that x_1 + x_2 + ... + x_n ~ Gamma(n) when z ~ Exponential()

            Random rng = new Random(1);
            ExponentialDistribution eDistribution = new ExponentialDistribution();

            // pick some low values of n so distribution is not simply normal
            foreach (int n in new int[] { 2, 3, 4, 5 })
            {
                Sample gSample = new Sample();
                for (int i = 0; i < 100; i++)
                {
                    double sum = 0.0;
                    for (int j = 0; j < n; j++)
                    {
                        sum += eDistribution.GetRandomValue(rng);
                    }
                    gSample.Add(sum);
                }

                GammaDistribution gDistribution = new GammaDistribution(n);
                TestResult        result        = gSample.KolmogorovSmirnovTest(gDistribution);
                Assert.IsTrue(result.Probability > 0.05);
            }
        }
        public void ExponentialDistributionChiSquareTest(double lambda)
        {
            var expDistribution = new ExponentialDistribution(lambda);

            var test = ChiSquareTest.Test(expDistribution);

            Assert.IsTrue(test);
        }
        public void ConstructorTest()
        {
            ExponentialDistribution n = new ExponentialDistribution(3.42521);

            Assert.AreEqual(3.42521, n.Rate);
            Assert.AreEqual(0.29195290215782393, n.Mean);
            Assert.AreEqual(0.085236497078375897, n.Variance);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Metodo que calcula la frecuencia esperada en un intervalo
        /// </summary>
        /// <param name="intervalo"></param>
        /// <param name="tamanioMuestra"></param>
        /// <param name="cantidadIntervalos"></param>
        /// <returns></returns>
        public override double CalcularFrecuenciaEsperadaEnIntervalo(Intervalo intervalo, int tamanioMuestra, int cantidadIntervalos)
        {
            var distribucion = new ExponentialDistribution(1 / Lambda);

            var probabilidadEsperada = distribucion.LeftProbability(intervalo.LimiteSuperior) -
                                       distribucion.LeftProbability(intervalo.LimiteInferior);

            return(probabilidadEsperada * tamanioMuestra);
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            const int maxItemsInQueue = 6;

            int ia = 30, ib = 10;

            var s = new Schema(maxItemsInQueue, 2);

            const int totalWorkingTime = 10000;

            var fr  = new ExponentialDistribution(7, 5, 3, uint.MaxValue, totalWorkingTime, ia);
            var frl = fr.Generate();

            var dr  = new ExponentialDistribution(7, 5, 3, uint.MaxValue, totalWorkingTime, ib);
            var drl = dr.Generate();

            int sumOch       = 0;
            int wokingWorker = 0;

            for (int i = 0; i < totalWorkingTime; i++)
            {
                if (!s.HasGeneratedItem(i))
                {
                    s.GenerateItem(i + (int)(frl.Skip(r.Next(totalWorkingTime)).First() * ia));
                }

                if (s.IsGenerated(i))
                {
                    s.AddToQueue();
                }

                for (int j = 0; j < s.CountInQueue; j++)
                {
                    if (!s.AllChanelsInWorkingState(i))
                    {
                        var endTime = i + (int)(drl.Skip(r.Next(totalWorkingTime)).First() * ib);

                        if (endTime < totalWorkingTime)
                        {
                            s.AddToWork(i, endTime);
                            s.RemoveFromQueue();
                        }
                    }
                }

                wokingWorker += s.CountWorkingWorkers(i);

                sumOch += s.CountInQueue;
            }

            Console.WriteLine("Абсолютная пропускная способность = " + 1 / (double)ia * (1 - s.CountDroped / (double)totalWorkingTime));
            Console.WriteLine("Среднее число занятых рабочих = " + wokingWorker / (double)totalWorkingTime);
            Console.WriteLine("Среднее число неисправных станков = " + sumOch / (double)totalWorkingTime);
            Console.ReadKey();
        }
        public void DifferenceOfTwoExponentialDistributionsChiSquareTest(double lambda)
        {
            var distr1 = new ExponentialDistribution(lambda);
            var distr2 = new ExponentialDistribution(lambda);

            var diff = distr1 - distr2;

            var test = ChiSquareTest.Test(diff);

            Assert.IsTrue(test);
        }
        public void QuotientOfTwoExponentialDistributionsChiSquareTest(double lambda)
        {
            var distr1 = new ExponentialDistribution(lambda);
            var distr2 = new ExponentialDistribution(lambda);

            var quotient = distr1 / distr2;

            var test = ChiSquareTest.Test(quotient);

            Assert.IsTrue(test);
        }
 public ExponentialEstimate(List <double> data) : base(data)
 {
     if (data.Min() <= 0)
     {
         this.score = -1;        //negative data implies it can't be Exponential
         return;
     }
     this.DistributionType = Distribution.Exponential;
     testDistribution      = new ExponentialDistribution(data.Average());
     this.RunTestOfFit();
 }
        public void SumOfTwoExponentialDistributionsChiSquareTest(double lambda)
        {
            var distr1 = new ExponentialDistribution(lambda);
            var distr2 = new ExponentialDistribution(lambda);

            var sum = distr1 + distr2;

            var test = ChiSquareTest.Test(sum);

            Assert.IsTrue(test);
        }
        public void ProductOfTwoExponentialDistributionsChiSquareTest(double lambda)
        {
            var distr1 = new ExponentialDistribution(lambda);
            var distr2 = new ExponentialDistribution(lambda);

            var product = distr1 * distr2;

            var test = ChiSquareTest.Test(product);

            Assert.IsTrue(test);
        }
Ejemplo n.º 25
0
        public void ExponentialDistributionGeneratorTest(double lambda,
                                                         double distributionEpsilon, double statEpsilon, int totalValues, int totalIntervals)
        {
            var dist      = new ExponentialDistribution(lambda);
            var generator = new ExponentialDistributionGenerator(dist);

            CheckAssert(
                generator, dist,
                distributionEpsilon, statEpsilon,
                totalValues, totalIntervals);
        }
        public void GenerateTest()
        {
            ExponentialDistribution target = new ExponentialDistribution(2.5);

            double[] samples = target.Generate(1000000);

            var actual = ExponentialDistribution.Estimate(samples);

            actual.Fit(samples);

            Assert.AreEqual(2.5, actual.Rate, 0.01);
        }
        public List <double> getFrecuenciasEsperadas(List <Intervalo> intervalos)
        {
            var _frecuencias         = new List <double>(intervalos.Count);
            ContinuousDistribution d = new ExponentialDistribution(1 / _lambda);

            foreach (var _intervalo in intervalos)
            {
                var _frecuencia = d.LeftProbability(_intervalo._fin) - d.LeftProbability(_intervalo._inicio);
                _frecuencias.Add(_frecuencia);
            }
            return(_frecuencias);
        }
Ejemplo n.º 28
0
 private UnivariateContinuousDistribution FitDistribution(double [] samples)
 {
     if (samples.Length < 10)
     {
         return(new EmpiricalDistribution(samples));
     }
     else
     {
         var exp = new ExponentialDistribution(); // new LognormalDistribution(); //
         exp.Fit(samples);
         return(exp);
     }
 }
Ejemplo n.º 29
0
        public void WilcoxonNullDistribution()
        {
            // Pick a very non-normal distribution
            ContinuousDistribution d = new ExponentialDistribution();

            Random rng = new Random(271828);

            foreach (int n in TestUtilities.GenerateIntegerValues(4, 64, 4))
            {
                Sample wContinuousSample = new Sample();
                ContinuousDistribution wContinuousDistribution = null;

                List <int>           wDiscreteSample       = new List <int>();
                DiscreteDistribution wDiscreteDistribution = null;

                for (int i = 0; i < 256; i++)
                {
                    BivariateSample sample = new BivariateSample();
                    for (int j = 0; j < n; j++)
                    {
                        double x = d.GetRandomValue(rng);
                        double y = d.GetRandomValue(rng);
                        sample.Add(x, y);
                    }
                    TestResult wilcoxon = sample.WilcoxonSignedRankTest();
                    if (wilcoxon.UnderlyingStatistic != null)
                    {
                        wDiscreteSample.Add(wilcoxon.UnderlyingStatistic.Value);
                        wDiscreteDistribution = wilcoxon.UnderlyingStatistic.Distribution;
                    }
                    else
                    {
                        wContinuousSample.Add(wilcoxon.Statistic.Value);
                        wContinuousDistribution = wilcoxon.Statistic.Distribution;
                    }
                }

                if (wDiscreteDistribution != null)
                {
                    TestResult chi2 = wDiscreteSample.ChiSquaredTest(wDiscreteDistribution);
                    Assert.IsTrue(chi2.Probability > 0.01);
                }
                else
                {
                    TestResult ks = wContinuousSample.KolmogorovSmirnovTest(wContinuousDistribution);
                    Assert.IsTrue(ks.Probability > 0.01);
                    Assert.IsTrue(wContinuousSample.PopulationMean.ConfidenceInterval(0.99).ClosedContains(wContinuousDistribution.Mean));
                    Assert.IsTrue(wContinuousSample.PopulationStandardDeviation.ConfidenceInterval(0.99).ClosedContains(wContinuousDistribution.StandardDeviation));
                }
            }
        }
        public void Issue_632()
        {
            // https://github.com/accord-net/framework/issues/632

            var n = new ExponentialDistribution(4.2);

            Assert.AreEqual(0, n.DistributionFunction(-10));
            Assert.AreEqual(0, n.ProbabilityDensityFunction(-10));
            Assert.AreEqual(System.Math.Log(0), n.LogProbabilityDensityFunction(-10));

            Assert.AreEqual(0, n.DistributionFunction(0));
            Assert.AreEqual(4.2, n.ProbabilityDensityFunction(0));
            Assert.AreEqual(System.Math.Log(4.2), n.LogProbabilityDensityFunction(0));
        }
 public FuncionExponencial(double[] eventos) : base(eventos)
 {
     try
     {
         DistribucionContinua = new ExponentialDistribution();
         DistribucionContinua.Fit(eventos);
         this.L    = ((ExponentialDistribution)DistribucionContinua).Rate.ToString("0.0000");
         Resultado = new ResultadoAjuste(StringFDP, StringInversa, DistribucionContinua.StandardDeviation, DistribucionContinua.Mean, DistribucionContinua.Variance, this);
     }
     catch (Exception)
     {
         Resultado = null;
     }
 }
Ejemplo n.º 32
0
        public void MixtureExponentialTest1()
        {
            var exp     = new ExponentialDistribution();
            var mixture = new MixtureDistribution(exp, new ShiftedDistribution(exp, 10));

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

            for (double p = 0; p < 1.0; p += 0.01)
            {
                double q = mixture.Quantile(p);
                output.WriteLine($"{p.ToStringInvariant("N2")}: {q.ToStringInvariant()}");
                Assert.Equal(p, mixture.Cdf(q), comparer);
            }
        }
        public void ConstructorTest2()
        {
            var exp = new ExponentialDistribution(rate: 0.42);

            double mean = exp.Mean;     // 2.3809523809523809
            double median = exp.Median; // 1.6503504299046317
            double var = exp.Variance;  // 5.6689342403628125
            double mode = exp.Mode;     // 0.0

            double cdf = exp.DistributionFunction(x: 0.27); // 0.10720652870550407
            double pdf = exp.ProbabilityDensityFunction(x: 0.27); // 0.3749732579436883
            double lpdf = exp.LogProbabilityDensityFunction(x: 0.27); // -0.98090056770472311

            double ccdf = exp.ComplementaryDistributionFunction(x: 0.27); // 0.89279347129449593
            double icdf = exp.InverseDistributionFunction(p: cdf); // 0.27

            double hf = exp.HazardFunction(x: 0.27); // 0.42
            double chf = exp.CumulativeHazardFunction(x: 0.27); // 0.1134

            string str = exp.ToString(CultureInfo.InvariantCulture); // Exp(x; λ = 0.42)

            Assert.AreEqual(2.3809523809523809, mean);
            Assert.AreEqual(1.6503504299046317, median);
            Assert.AreEqual(0.0, mode);
            Assert.AreEqual(5.6689342403628125, var);
            Assert.AreEqual(0.1134, chf);
            Assert.AreEqual(0.10720652870550407, cdf);
            Assert.AreEqual(0.3749732579436883, pdf);
            Assert.AreEqual(-0.98090056770472311, lpdf);
            Assert.AreEqual(0.42, hf);
            Assert.AreEqual(0.89279347129449593, ccdf);
            Assert.AreEqual(0.27, icdf);
            Assert.AreEqual("Exp(x; λ = 0.42)", str);

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

            Assert.AreEqual(0.12212689139892995, range1.Min);
            Assert.AreEqual(7.1326958894142622, range1.Max);
            Assert.AreEqual(0.023929371079765359, range2.Min);
            Assert.AreEqual(10.964690919019265, range2.Max);
            Assert.AreEqual(0.023929371079765359, range3.Min);
            Assert.AreEqual(10.964690919019265, range3.Max);
        }
 /// <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, ExponentialDistribution dist, DistributionFunction function = DistributionFunction.PDF, int numInterpolatedValues = 100 )
 {
     List<string> titles = new List<string>()
       {
     "ExponentialDistribution",
     String.Format("\u03BB={0}", dist.Lambda)
       };
       UpdateContinuousDistribution( ref chart, dist, titles, function, numInterpolatedValues );
 }
        public void GenerateTest()
        {
            ExponentialDistribution target = new ExponentialDistribution(2.5);

            double[] samples = target.Generate(1000000);

            var actual = ExponentialDistribution.Estimate(samples);
            actual.Fit(samples);

            Assert.AreEqual(2.5, actual.Rate, 0.01);
        }
        public void MedianTest()
        {
            ExponentialDistribution target = new ExponentialDistribution(2.5);

            Assert.AreEqual(target.Median, target.InverseDistributionFunction(0.5));
        }
        public void FitTest1()
        {
            double[] values = 
            {
                0, 1, 2, 4, 2, 3, 5, 7, 4, 3, 2, 1, 4,
            };

            var exp = new ExponentialDistribution();

            exp.Fit(values);

            string actual;

            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR");

            actual = exp.ToString("G3", CultureInfo.InvariantCulture);
            Assert.AreEqual("Exp(x; λ = 0.342)", actual);

            actual = exp.ToString("G3");
            Assert.AreEqual("Exp(x; λ = 0,342)", actual);

            actual = exp.ToString(CultureInfo.InvariantCulture);
            Assert.AreEqual("Exp(x; λ = 0.342105263157895)", actual);

            actual = exp.ToString();
            Assert.AreEqual("Exp(x; λ = 0,342105263157895)", actual);
        }
        public void GenerateTest2()
        {
            ExponentialDistribution target = new ExponentialDistribution(2.5);

            double[] samples = new double[1000000];
            for (int i = 0; i < samples.Length; i++)
                samples[i] = target.Generate();

            var actual = ExponentialDistribution.Estimate(samples);
            actual.Fit(samples);

            Assert.AreEqual(2.5, actual.Rate, 0.01);
        }
 /// <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( ExponentialDistribution dist, DistributionFunction function = DistributionFunction.PDF, int numInterpolatedValues = 100 )
 {
     Show( ToChart( dist, function, numInterpolatedValues ) );
 }
Ejemplo n.º 40
0
 public PoissonInterarrivalTimer(double offeredLoad)
 {
     this.exponentialDistribution = new ExponentialDistribution(new Random(), offeredLoad);
     this.lastEventTime = DateTime.UtcNow;
 }
        public void CumulativeDistributionTest()
        {
            ExponentialDistribution n = new ExponentialDistribution(3);

            double[] expected = { 0, 0.950213, 0.997521, 0.999877, 0.999994, 1.0 };
            double[] actual = new double[expected.Length];

            for (int i = 0; i < actual.Length; i++)
                actual[i] = n.DistributionFunction(i);

            for (int i = 0; i < actual.Length; i++)
            {
                Assert.AreEqual(expected[i], actual[i], 1e-6);
                Assert.IsFalse(double.IsNaN(actual[i]));
            }
        }
        //---------------------------------------------------------------------
        ///<summary>
        /// Run the Biomass Insects extension at a particular timestep.
        ///</summary>
        public override void Run()
        {

            running = true;
            UI.WriteLine("   Processing landscape for Biomass Insect events ...");

            foreach(IInsect insect in manyInsect)
            {

                if(insect.MortalityYear == Model.Core.CurrentTime)
                    Outbreak.Mortality(insect);

                // Copy the data from current to last
                foreach (ActiveSite site in Model.Core.Landscape)
                    insect.LastYearDefoliation[site] = insect.ThisYearDefoliation[site];

                insect.ThisYearDefoliation.ActiveSiteValues = 0.0;
                //SiteVars.BiomassRemoved.ActiveSiteValues = 0;

                insect.ActiveOutbreak = false;
                insect.SingleOutbreakYear = false;

                NormalDistribution randVar = new NormalDistribution(RandomNumberGenerator.Singleton);
                randVar.Mu = 0;      // mean
                randVar.Sigma = 1;   // std dev
                double randomNum = randVar.NextDouble();

                ExponentialDistribution randVarE = new ExponentialDistribution(RandomNumberGenerator.Singleton);
                randVarE.Lambda = insect.MeanDuration;      // rate
                double randomNumE = randVarE.NextDouble();

                // First, has enough time passed since the last outbreak?
                double timeBetweenOutbreaks = insect.MeanTimeBetweenOutbreaks + (insect.StdDevTimeBetweenOutbreaks * randomNum);
                //double duration = insect.MeanDuration + (insect.StdDevDuration * randomNum);
                double duration = Math.Round(randomNumE + 1);
                
                if (duration > 5) // Limit maximum outbreak duration to 5 years for now.
                    duration = duration - 3;

                double timeAfterDuration = timeBetweenOutbreaks - duration;

                //UI.WriteLine("Calculated time between = {0}.  inputMeanTime={1}, inputStdTime={2}.", timeBetweenOutbreaks, insect.MeanTimeBetweenOutbreaks, insect.StdDevTimeBetweenOutbreaks);
                //UI.WriteLine("Calculated duration     = {0}.  inputMeanDura={1}, inputStdDura={2}.", duration, insect.MeanDuration, insect.StdDevDuration);
                //UI.WriteLine("Insect Start Time = {0}, Stop Time = {1}.", insect.OutbreakStartYear, insect.OutbreakStopYear);


                if(Model.Core.CurrentTime == 1)
                {
                    //UI.WriteLine("   Year 1:  Setting initial start and stop times.");
                    insect.OutbreakStartYear = (int) (timeBetweenOutbreaks / 2.0) + 1;
                    insect.OutbreakStopYear  = insect.OutbreakStartYear + (int) duration - 1;
                    UI.WriteLine("   {0} is not active.  StartYear={1}, StopYear={2}, CurrentYear={3}.", insect.Name, insect.OutbreakStartYear, insect.OutbreakStopYear, Model.Core.CurrentTime);
                }
                else if(insect.OutbreakStartYear <= Model.Core.CurrentTime
                    && insect.OutbreakStopYear > Model.Core.CurrentTime)
                {
                    //UI.WriteLine("   An outbreak starts or continues.  Start and stop time do not change.");
                    insect.ActiveOutbreak = true;
                    UI.WriteLine("   {0} is active.  StartYear={1}, StopYear={2}, CurrentYear={3}.", insect.Name, insect.OutbreakStartYear, insect.OutbreakStopYear, Model.Core.CurrentTime);

                    insect.MortalityYear = Model.Core.CurrentTime + 1;

                }
                //Special case for single year outbreak.
                else if(insect.OutbreakStartYear <= Model.Core.CurrentTime
                    && insect.OutbreakStopYear <= Model.Core.CurrentTime)
                {
                    insect.ActiveOutbreak = true;
                    UI.WriteLine("   {0} is active.  StartYear={1}, StopYear={2}, CurrentYear={3}.", insect.Name, insect.OutbreakStartYear, insect.OutbreakStopYear, Model.Core.CurrentTime);

                    if (insect.OutbreakStartYear == insect.OutbreakStopYear)
                        insect.SingleOutbreakYear = true;
                    insect.MortalityYear = Model.Core.CurrentTime + 1;
                    insect.OutbreakStartYear = Model.Core.CurrentTime + (int)timeBetweenOutbreaks;
                    insect.OutbreakStopYear = insect.OutbreakStartYear + (int)duration - 1;
                }

                else if(insect.OutbreakStopYear <= Model.Core.CurrentTime
                    && timeAfterDuration > Model.Core.CurrentTime - insect.OutbreakStopYear)
                {
                    //UI.WriteLine("   In between outbreaks, reset start and stop times.");
                    insect.ActiveOutbreak = true;
                    UI.WriteLine("   {0} is active.  StartYear={1}, StopYear={2}, CurrentYear={3}.", insect.Name, insect.OutbreakStartYear, insect.OutbreakStopYear, Model.Core.CurrentTime);

                    insect.MortalityYear = Model.Core.CurrentTime + 1;
                    insect.OutbreakStartYear = Model.Core.CurrentTime + (int) timeBetweenOutbreaks;
                    insect.OutbreakStopYear = insect.OutbreakStartYear + (int) duration - 1;
                }
                //UI.WriteLine("  Insect Start Time = {0}, Stop Time = {1}.", insect.OutbreakStartYear, insect.OutbreakStopYear);

                if(insect.ActiveOutbreak)
                {
                    //UI.WriteLine("   OutbreakStartYear={0}.", insect.OutbreakStartYear);

                    if(insect.OutbreakStartYear == Model.Core.CurrentTime || insect.SingleOutbreakYear)
                        // Initialize neighborhoodGrowthReduction with patches
                        Outbreak.InitializeDefoliationPatches(insect);
                    else
                        insect.NeighborhoodDefoliation.ActiveSiteValues = 0;

                    double sumDefoliation = 0.0;
                    int numSites = 0;
                    //foreach(ActiveSite site in Model.Core.Landscape)
                    //{
                    //    sumDefoliation += insect.ThisYearDefoliation[site];
                    //    if(insect.ThisYearDefoliation[site] > 0.0)
                    //        numSites++;

                    //}
                    double meanDefoliation = sumDefoliation / (double) numSites;


                    log.Write("{0},{1},{2},{3},{4},{5}",
                        Model.Core.CurrentTime,
                        insect.Name,
                        insect.OutbreakStartYear,
                        insect.OutbreakStopYear,
                        sumDefoliation,
                        numSites
                        );

                    //foreach (IEcoregion ecoregion in Ecoregions.Dataset)
                    //    log.Write(",{0}", 1);

                    log.WriteLine("");

                }


                //Only write maps if an outbreak is active.
                //if (!insect.ActiveOutbreak)
                //if (insect.OutbreakStartYear <= Model.Core.CurrentTime
                //    && insect.OutbreakStopYear + 1 >= Model.Core.CurrentTime)
                //if (insect.OutbreakStartYear <= Model.Core.CurrentTime)
                //    | insect.MortalityYear = Model.Core.CurrentTime)
                //    continue;

                //----- Write Insect GrowthReduction maps --------
                IOutputRaster<UShortPixel> map = CreateMap((Model.Core.CurrentTime - 1), insect.Name);

                using (map) {
                    UShortPixel pixel = new UShortPixel();
                    foreach (Site site in Model.Core.Landscape.AllSites) {
                        if (site.IsActive)
                                pixel.Band0 = (ushort) (insect.LastYearDefoliation[site] * 100.0);
                        else
                            //  Inactive site
                            pixel.Band0 = 0;

                        map.WritePixel(pixel);
                    }
                }

                //----- Write Initial Patch maps --------
                //IOutputRaster<UShortPixel> map2 = CreateMap(Model.Core.CurrentTime, ("InitialPatchMap" + insect.Name));
                //using (map2) {
                //    UShortPixel pixel = new UShortPixel();
                //    foreach (Site site in Model.Core.Landscape.AllSites) {
                //        if (site.IsActive)
                //        {
                //            if (insect.Disturbed[site])
                //                pixel.Band0 = (ushort) (SiteVars.InitialOutbreakProb[site] * 100);
                //            else
                //                pixel.Band0 = 0;
                //        }
                //        else
                //        {
                //            //  Inactive site
               //             pixel.Band0 = 0;
                //        }
                //        map2.WritePixel(pixel);
                //    }
                //}

                //----- Write Biomass Reduction maps --------
                IOutputRaster<UShortPixel> map3 = CreateMap(Model.Core.CurrentTime, ("BiomassRemoved" + insect.Name));
                using (map3) {
                    UShortPixel pixel = new UShortPixel();
                    foreach (Site site in Model.Core.Landscape.AllSites) {
                        if (site.IsActive)
                        {
                            // TESTING added by RMS
                            if(SiteVars.BiomassRemoved[site] > 0)
                               // UI.WriteLine("  Biomass revoved at {0}/{1}: {2}.", site.Location.Row, site.Location.Column, SiteVars.BiomassRemoved[site]);
                               pixel.Band0 = (ushort) (SiteVars.BiomassRemoved[site] / 100);
                            else
                               pixel.Band0 = 0;

                        }
                        else
                        {
                            //  Inactive site
                            pixel.Band0 = 0;
                        }
                        map3.WritePixel(pixel);
                        //Zero out the BiomassRemoved after the last insect mortality event in a given year.
                        //if (SiteVars.BiomassRemoved[site] > 0 && SiteVars.TimeOfLastEvent[site] < Model.Core.CurrentTime)
                            SiteVars.BiomassRemoved[site] = 0;
                    }
                }
            }

        }
        public void ProbabilityDistributionTest()
        {
            ExponentialDistribution n = new ExponentialDistribution(3);

            double[] expected = { 3, 0.149361, 0.00743626, 0.000370229, 0.0000184326 };
            double[] actual = new double[expected.Length];

            for (int i = 0; i < actual.Length; i++)
                actual[i] = n.ProbabilityDensityFunction(i);

            for (int i = 0; i < actual.Length; i++)
            {
                Assert.AreEqual(expected[i], actual[i], 1e-5);
                Assert.IsFalse(double.IsNaN(actual[i]));
            }
        }
 /// <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( ExponentialDistribution dist, DistributionFunction function = DistributionFunction.PDF, int numInterpolatedValues = 100 )
 {
     ChartControl chart = GetDefaultChart();
       Update( ref chart, dist, function, numInterpolatedValues );
       return chart;
 }
        public void ProbabilityDistributionTest2()
        {
            ExponentialDistribution n = new ExponentialDistribution(0.42);

            double[] expected = { 0.42, 0.27596, 0.181318, 0.119135, 0.0782771, 0.0514317 };
            double[] actual = new double[expected.Length];

            for (int i = 0; i < actual.Length; i++)
                actual[i] = n.ProbabilityDensityFunction(i);

            for (int i = 0; i < actual.Length; i++)
            {
                Assert.AreEqual(expected[i], actual[i], 1e-5);
                Assert.IsFalse(double.IsNaN(actual[i]));
            }
        }