Example #1
0
        protected override void EndProcessing()
        {
            var dist = new LogisticDistribution(Location, Scale);
            var obj  = DistributionHelper.AddConvinienceMethods(dist);

            WriteObject(obj);
        }
Example #2
0
        public void LogisticTest()
        {
            var target   = new TukeyLambdaDistribution(lambda: 0);
            var logistic = new LogisticDistribution();

            compare(target, logistic, 1e-5);
        }
Example #3
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));
            }
        }
        public void ConstructorTest1()
        {
            var log = new LogisticDistribution(location: 0.42, scale: 1.2);

            double mean   = log.Mean;                                    // 0.42
            double median = log.Median;                                  // 0.42
            double mode   = log.Mode;                                    // 0.42
            double var    = log.Variance;                                // 4.737410112522892

            double cdf  = log.DistributionFunction(x: 1.4);              // 0.693528308197921
            double pdf  = log.ProbabilityDensityFunction(x: 1.4);        // 0.17712232827170876
            double lpdf = log.LogProbabilityDensityFunction(x: 1.4);     // -1.7309146649427332

            double ccdf = log.ComplementaryDistributionFunction(x: 1.4); // 0.306471691802079
            double icdf = log.InverseDistributionFunction(p: cdf);       // 1.3999999999999997

            double hf  = log.HazardFunction(x: 1.4);                     // 0.57794025683160088
            double chf = log.CumulativeHazardFunction(x: 1.4);           // 1.1826298874077226

            string str = log.ToString(CultureInfo.InvariantCulture);     // Logistic(x; μ = 0.42, scale = 1.2)

            Assert.AreEqual(0.41999999999999998, mean);
            Assert.AreEqual(0.41999999999999998, median);
            Assert.AreEqual(4.737410112522892, var);
            Assert.AreEqual(1.1826298874077226, chf);
            Assert.AreEqual(0.693528308197921, cdf);
            Assert.AreEqual(0.17712232827170876, pdf);
            Assert.AreEqual(-1.7309146649427332, lpdf);
            Assert.AreEqual(0.57794025683160088, hf);
            Assert.AreEqual(0.306471691802079, ccdf);
            Assert.AreEqual(1.3999999999999997, icdf);
            Assert.AreEqual("Logistic(x; μ = 0.42, scale = 1.2)", str);
        }
Example #5
0
        // Идеальное количество людей для остановки без округления
        public static double GetAvg(int PassengerCount, double PeakTime, double PeakWidth, int Minute, int StationCount)
        {
            LogisticDistribution logis = new LogisticDistribution(PeakTime, PeakWidth);

            double res = PassengerCount * logis.ProbabilityDensity(Minute) / StationCount;

            logis = null;
            return(res);
        }
        public void LinearRegressionVariances()
        {
            // do a set of logistic regression fits
            // make sure not only that the fit parameters are what they should be, but that their variances/covariances are as returned

            Random rng = new Random(314159);

            // define line parameters
            double a0 = 2.0; double b0 = -1.0;

            // do a lot of fits, recording results of each
            FrameTable data = new FrameTable();

            data.AddColumns <double>("a", "va", "b", "vb", "abCov", "p", "dp");

            for (int k = 0; k < 128; k++)
            {
                // we should be able to draw x's from any distribution; noise should be drawn from a normal distribution
                ContinuousDistribution xd = new LogisticDistribution();
                ContinuousDistribution nd = new NormalDistribution(0.0, 2.0);

                // generate a synthetic data set
                BivariateSample sample = new BivariateSample();
                for (int i = 0; i < 12; i++)
                {
                    double x = xd.GetRandomValue(rng);
                    double y = a0 + b0 * x + nd.GetRandomValue(rng);
                    sample.Add(x, y);
                }

                // do the regression
                LinearRegressionResult result = sample.LinearRegression();

                // record result
                UncertainValue p = result.Predict(12.0);
                data.AddRow(new Dictionary <string, object>()
                {
                    { "a", result.Intercept.Value },
                    { "va", result.Parameters.VarianceOf("Intercept") },
                    { "b", result.Slope.Value },
                    { "vb", result.Parameters.VarianceOf("Slope") },
                    { "abCov", result.Parameters.CovarianceOf("Slope", "Intercept") },
                    { "p", p.Value },
                    { "dp", p.Uncertainty }
                });
            }

            // variances of parameters should agree with predictions
            Assert.IsTrue(data["a"].As <double>().PopulationVariance().ConfidenceInterval(0.99).ClosedContains(data["va"].As <double>().Median()));
            Assert.IsTrue(data["b"].As <double>().PopulationVariance().ConfidenceInterval(0.99).ClosedContains(data["vb"].As <double>().Median()));
            Assert.IsTrue(data["a"].As <double>().PopulationCovariance(data["b"].As <double>()).ConfidenceInterval(0.99).ClosedContains(data["abCov"].As <double>().Median()));

            // variance of prediction should agree with claim
            Assert.IsTrue(data["p"].As <double>().PopulationStandardDeviation().ConfidenceInterval(0.99).ClosedContains(data["dp"].As <double>().Median()));
        }
Example #7
0
        public void TestLogistic()
        {
            ProbabilityDistribution normal = new LogisticDistribution(location: 0, scale: 1);

            double[] tester = new double[100];
            for (var i = 0; i < 100; i++)
            {
                tester[i] = normal.NextDouble();
            }

            string jsonResult = JsonConvert.SerializeObject(tester);
        }
Example #8
0
        public void ConstructorTest1()
        {
            var log = new LogisticDistribution(location: 0.42, scale: 1.2);

            double mean   = log.Mean;                                    // 0.42
            double median = log.Median;                                  // 0.42
            double mode   = log.Mode;                                    // 0.42
            double var    = log.Variance;                                // 4.737410112522892

            double cdf  = log.DistributionFunction(x: 1.4);              // 0.693528308197921
            double pdf  = log.ProbabilityDensityFunction(x: 1.4);        // 0.17712232827170876
            double lpdf = log.LogProbabilityDensityFunction(x: 1.4);     // -1.7309146649427332

            double ccdf = log.ComplementaryDistributionFunction(x: 1.4); // 0.306471691802079
            double icdf = log.InverseDistributionFunction(p: cdf);       // 1.3999999999999997

            double hf  = log.HazardFunction(x: 1.4);                     // 0.57794025683160088
            double chf = log.CumulativeHazardFunction(x: 1.4);           // 1.1826298874077226

            string str = log.ToString(CultureInfo.InvariantCulture);     // Logistic(x; μ = 0.42, s = 1.2)

            Assert.AreEqual(0.41999999999999998, mean);
            Assert.AreEqual(0.41999999999999998, median);
            Assert.AreEqual(0.41999999999999998, mode);
            Assert.AreEqual(4.737410112522892, var);
            Assert.AreEqual(1.1826298874077226, chf);
            Assert.AreEqual(0.693528308197921, cdf);
            Assert.AreEqual(0.17712232827170876, pdf);
            Assert.AreEqual(-1.7309146649427332, lpdf);
            Assert.AreEqual(0.57794025683160088, hf);
            Assert.AreEqual(0.306471691802079, ccdf);
            Assert.AreEqual(1.3999999999999997, icdf);
            Assert.AreEqual("Logistic(x; μ = 0.42, s = 1.2)", str);

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

            Assert.AreEqual(-3.1133267749997273, range1.Min);
            Assert.AreEqual(3.9533267749997272, range1.Max);
            Assert.AreEqual(-5.0941438201615066, range2.Min);
            Assert.AreEqual(5.9341438201615064, range2.Max);
            Assert.AreEqual(-5.0941438201615075, range3.Min);
            Assert.AreEqual(5.9341438201615064, range3.Max);

            Assert.AreEqual(double.NegativeInfinity, log.Support.Min);
            Assert.AreEqual(double.PositiveInfinity, log.Support.Max);

            Assert.AreEqual(log.InverseDistributionFunction(0), log.Support.Min);
            Assert.AreEqual(log.InverseDistributionFunction(1), log.Support.Max);
        }
Example #9
0
        public void EquivalencyTest3()
        {
            // when ksi -> 0, the shifted log-logistic reduces to the logistic distribution.

            double sigma = 0.42; // scale
            double ksi   = 0;    // shape
            double mu    = 2.4;  // location

            var target = new ShiftedLogLogisticDistribution(location: mu, scale: sigma, shape: ksi);
            var log    = new LogisticDistribution(mu, sigma);

            Assert.AreEqual(log.Mean, target.Mean);
            Assert.AreEqual(log.Median, target.Median);
            Assert.AreEqual(log.Mode, target.Mode);
            Assert.AreEqual(log.Variance, target.Variance);

            double actual, expected;

            for (double i = -10; i < 10; i += 0.1)
            {
                expected = log.DistributionFunction(i);
                actual   = target.DistributionFunction(i);
                Assert.IsTrue(expected.IsRelativelyEqual(actual, 1e-15));

                expected = log.ProbabilityDensityFunction(i);
                actual   = target.ProbabilityDensityFunction(i);
                Assert.IsTrue(expected.IsRelativelyEqual(actual, 1e-15));

                expected = log.LogProbabilityDensityFunction(i);
                actual   = target.LogProbabilityDensityFunction(i);
                Assert.IsTrue(expected.IsRelativelyEqual(actual, 1e-10));

                expected = log.ComplementaryDistributionFunction(i);
                actual   = target.ComplementaryDistributionFunction(i);
                Assert.IsTrue(expected.IsRelativelyEqual(actual, 1e-15));

                double p = log.DistributionFunction(i);
                expected = log.InverseDistributionFunction(p);
                actual   = target.InverseDistributionFunction(p);
                Assert.AreEqual(expected, actual, 1e-5);

                expected = log.HazardFunction(i);
                actual   = target.HazardFunction(i);
                Assert.IsTrue(expected.IsRelativelyEqual(actual, 1e-15));

                expected = log.CumulativeHazardFunction(i);
                actual   = target.CumulativeHazardFunction(i);
                Assert.IsTrue(expected.IsRelativelyEqual(actual, 1e-15));
            }
        }
Example #10
0
 public FuncionLogistica(double[] eventos) : base(eventos)
 {
     try
     {
         double media = eventos.Average();
         int    n     = eventos.Count();
         double sigma = eventos.Sum(x => Math.Pow(x - media, 2)) / n;
         DistribucionContinua = new LogisticDistribution(media, sigma);
         this.MU   = ((LogisticDistribution)DistribucionContinua).Location.ToString("0.0000");
         this.S    = ((LogisticDistribution)DistribucionContinua).Scale.ToString("0.0000");
         Resultado = new ResultadoAjuste(StringFDP, StringInversa, DistribucionContinua.StandardDeviation, DistribucionContinua.Mean, DistribucionContinua.Variance, this);
     }
     catch (Exception)
     {
         Resultado = null;
     }
 }
Example #11
0
        // Округленное количество людей для одной остановки с рандомом
        public static int Get(int PassengerCount, double PeakTime, double PeakWidth, int Minute, int StationCount)
        {
            LogisticDistribution logis = new LogisticDistribution(PeakTime, PeakWidth);

            double value = PassengerCount * logis.ProbabilityDensity(Minute) * 2.02 * RNG.NextDouble() / StationCount;

            int res = (int)Math.Round(value);

            IdealSum += value;
            RealSum  += res;

            if (Math.Abs(RealSum - IdealSum) >= 1)
            {
                int corr = (int)(Math.Floor(Math.Abs(RealSum - IdealSum)) * Math.Sign(RealSum - IdealSum));
                IdealSum -= RealSum - corr;
                RealSum   = 0;
                res      -= corr;
            }

            logis = null;
            return(res);
        }
 /// <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( LogisticDistribution dist, DistributionFunction function = DistributionFunction.PDF, int numInterpolatedValues = 100 )
 {
     Show( ToChart( dist, function, numInterpolatedValues ) );
 }
 /// <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, LogisticDistribution dist, DistributionFunction function = DistributionFunction.PDF, int numInterpolatedValues = 100 )
 {
     List<string> titles = new List<string>()
       {
     "LogisticDistribution",
     String.Format("location={0}, scale={1}", dist.Location, dist.Scale)
       };
       UpdateContinuousDistribution( ref chart, dist, titles, function, numInterpolatedValues );
 }
 /// <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( LogisticDistribution dist, DistributionFunction function = DistributionFunction.PDF, int numInterpolatedValues = 100 )
 {
     ChartControl chart = GetDefaultChart();
       Update( ref chart, dist, function, numInterpolatedValues );
       return chart;
 }
        public void BivariateLinearRegression()
        {
            // do a set of logistic regression fits
            // make sure not only that the fit parameters are what they should be, but that their variances/covariances are as returned

            Random rng = new Random(314159);

            // define logistic parameters
            double a0 = 2.0; double b0 = -1.0;

            // keep track of sample of returned a and b fit parameters
            BivariateSample ps = new BivariateSample();

            // also keep track of returned covariance estimates
            // since these vary slightly from fit to fit, we will average them
            double caa = 0.0;
            double cbb = 0.0;
            double cab = 0.0;

            // also keep track of test statistics
            Sample fs = new Sample();

            // do 100 fits
            for (int k = 0; k < 100; k++)
            {
                // we should be able to draw x's from any distribution; noise should be drawn from a normal distribution
                Distribution xd = new LogisticDistribution();
                Distribution nd = new NormalDistribution(0.0, 2.0);

                // generate a synthetic data set
                BivariateSample s = new BivariateSample();
                for (int i = 0; i < 25; i++)
                {
                    double x = xd.GetRandomValue(rng);
                    double y = a0 + b0 * x + nd.GetRandomValue(rng);
                    s.Add(x, y);
                }

                // do the regression
                FitResult r = s.LinearRegression();

                // record best fit parameters
                double a = r.Parameter(0).Value;
                double b = r.Parameter(1).Value;
                ps.Add(a, b);

                // record estimated covariances
                caa += r.Covariance(0, 0);
                cbb += r.Covariance(1, 1);
                cab += r.Covariance(0, 1);

                // record the fit statistic
                fs.Add(r.GoodnessOfFit.Statistic);
                Console.WriteLine("F={0}", r.GoodnessOfFit.Statistic);
            }

            caa /= ps.Count;
            cbb /= ps.Count;
            cab /= ps.Count;

            // check that mean parameter estimates are what they should be: the underlying population parameters
            Assert.IsTrue(ps.X.PopulationMean.ConfidenceInterval(0.95).ClosedContains(a0));
            Assert.IsTrue(ps.Y.PopulationMean.ConfidenceInterval(0.95).ClosedContains(b0));

            Console.WriteLine("{0} {1}", caa, ps.X.PopulationVariance);
            Console.WriteLine("{0} {1}", cbb, ps.Y.PopulationVariance);

            // check that parameter covarainces are what they should be: the reported covariance estimates
            Assert.IsTrue(ps.X.PopulationVariance.ConfidenceInterval(0.95).ClosedContains(caa));
            Assert.IsTrue(ps.Y.PopulationVariance.ConfidenceInterval(0.95).ClosedContains(cbb));
            Assert.IsTrue(ps.PopulationCovariance.ConfidenceInterval(0.95).ClosedContains(cab));

            // check that F is distributed as it should be
            Console.WriteLine(fs.KolmogorovSmirnovTest(new FisherDistribution(2, 48)).LeftProbability);
        }
Example #16
0
        public void BivariateLinearRegression()
        {
            // do a set of logistic regression fits
            // make sure not only that the fit parameters are what they should be, but that their variances/covariances are as returned

            Random rng = new Random(314159);

            // define line parameters
            double a0 = 2.0; double b0 = -1.0;

            // keep track of sample of returned a and b fit parameters
            BivariateSample pSample = new BivariateSample();

            // also keep track of returned covariance estimates
            // since these vary slightly from fit to fit, we will average them
            double caa = 0.0;
            double cbb = 0.0;
            double cab = 0.0;

            // Record predictions for a new point
            double x0      = 12.0;
            Sample ySample = new Sample();
            double ySigma  = 0.0;

            // do 100 fits
            for (int k = 0; k < 128; k++)
            {
                // we should be able to draw x's from any distribution; noise should be drawn from a normal distribution
                ContinuousDistribution xd = new LogisticDistribution();
                ContinuousDistribution nd = new NormalDistribution(0.0, 2.0);

                // generate a synthetic data set
                BivariateSample sample = new BivariateSample();
                for (int i = 0; i < 16; i++)
                {
                    double x = xd.GetRandomValue(rng);
                    double y = a0 + b0 * x + nd.GetRandomValue(rng);
                    sample.Add(x, y);
                }

                // do the regression
                LinearRegressionResult result = sample.LinearRegression();

                // test consistancy
                Assert.IsTrue(result.Intercept == result.Parameters[0].Estimate);
                Assert.IsTrue(result.Intercept.Value == result.Parameters.Best[0]);
                Assert.IsTrue(TestUtilities.IsNearlyEqual(result.Intercept.Uncertainty, Math.Sqrt(result.Parameters.Covariance[0, 0])));
                Assert.IsTrue(result.Slope == result.Parameters[1].Estimate);
                Assert.IsTrue(result.Slope.Value == result.Parameters.Best[1]);
                Assert.IsTrue(TestUtilities.IsNearlyEqual(result.Slope.Uncertainty, Math.Sqrt(result.Parameters.Covariance[1, 1])));
                Assert.IsTrue(TestUtilities.IsNearlyEqual(result.R.Statistic, sample.CorrelationCoefficient));

                // record best fit parameters
                double a = result.Parameters.Best[0];
                double b = result.Parameters.Best[1];
                pSample.Add(a, b);

                // record estimated covariances
                caa += result.Parameters.Covariance[0, 0];
                cbb += result.Parameters.Covariance[1, 1];
                cab += result.Parameters.Covariance[0, 1];

                UncertainValue yPredict = result.Predict(x0);
                ySample.Add(yPredict.Value);
                ySigma += yPredict.Uncertainty;

                double SST = 0.0;
                foreach (double y in sample.Y)
                {
                    SST += MoreMath.Sqr(y - sample.Y.Mean);
                }
                Assert.IsTrue(TestUtilities.IsNearlyEqual(SST, result.Anova.Total.SumOfSquares));

                double SSR = 0.0;
                foreach (double z in result.Residuals)
                {
                    SSR += z * z;
                }
                Assert.IsTrue(TestUtilities.IsNearlyEqual(SSR, result.Anova.Residual.SumOfSquares));
            }

            caa    /= pSample.Count;
            cbb    /= pSample.Count;
            cab    /= pSample.Count;
            ySigma /= pSample.Count;

            // check that mean parameter estimates are what they should be: the underlying population parameters
            Assert.IsTrue(pSample.X.PopulationMean.ConfidenceInterval(0.95).ClosedContains(a0));
            Assert.IsTrue(pSample.Y.PopulationMean.ConfidenceInterval(0.95).ClosedContains(b0));

            Console.WriteLine("{0} {1}", caa, pSample.X.PopulationVariance);
            Console.WriteLine("{0} {1}", cbb, pSample.Y.PopulationVariance);

            // check that parameter covarainces are what they should be: the reported covariance estimates
            Assert.IsTrue(pSample.X.PopulationVariance.ConfidenceInterval(0.95).ClosedContains(caa));
            Assert.IsTrue(pSample.Y.PopulationVariance.ConfidenceInterval(0.95).ClosedContains(cbb));
            Assert.IsTrue(pSample.PopulationCovariance.ConfidenceInterval(0.95).ClosedContains(cab));

            // Check that the predicted ys conform to the model and the asserted uncertainty.
            Assert.IsTrue(ySample.PopulationMean.ConfidenceInterval(0.95).ClosedContains(a0 + x0 * b0));
            //Assert.IsTrue(ySample.PopulationStandardDeviation.ConfidenceInterval(0.95).ClosedContains(ySigma));
        }