예제 #1
0
        public void build_prob_map()
        {
            Normal N_x = new Normal(X / 2, STD_X);
            Normal N_y = new Normal(Y / 2, STD_Y);

            DenseMatrix M_x = new DenseMatrix(Y, X, 0.0);
            DenseMatrix M_y = new DenseMatrix(Y, X, 0.0);

            DenseVector V_x = new DenseVector(X);
            for (int i = 0; i < X; i++)
            {
                V_x[i] = N_x.Density(i);
            }

            for (int j = 0; j < Y; j++)
            {
                M_x.SetRow(j, V_x);
            }

            DenseVector V_y = new DenseVector(Y);
            for (int i = 0; i < Y; i++)
            {
                V_y[i] = N_y.Density(i);
            }

            for (int j = 0; j < X; j++)
            {
                M_y.SetColumn(j, V_y);
            }

            DenseMatrix MULT = (DenseMatrix)M_x.PointwiseMultiply(M_y);
            double s = MULT.Data.Sum();
            MULT = (DenseMatrix)MULT.PointwiseDivide(new DenseMatrix(Y, X, s));
            //this.dataGridView1.DataSource = MULT;
            //Console.WriteLine(MULT.Data.Sum());
            PROB_MAP_ORIG = MULT;

            s = MULT[Y / 2, X / 2];
            MULT = (DenseMatrix)MULT.PointwiseDivide(new DenseMatrix(Y, X, s));

            /*
            for (int i = 0; i < Y; i++)
            {
                Console.Write(i + " - ");
                for (int j = 0; j < X; j++)
                {
                    Console.Write(MULT[i, j] + " ");
                }
                Console.WriteLine();
                Console.WriteLine();
            }
            */
            PROB_MAP = MULT;
        }
예제 #2
0
        /// <summary>
        /// Computes the density of the Student t-distribution.
        /// </summary>
        /// <param name="x">The location at which to compute the density.</param>
        /// <returns>the density at <paramref name="x"/>.</returns>
        public double Density(double x)
        {
            // TODO JVG we can probably do a better job for Cauchy special case
            if (_dof >= 1e+8d)
            {
                return(Normal.Density(_location, _scale, x));
            }

            var d = (x - _location) / _scale;

            return(Math.Exp(SpecialFunctions.GammaLn((_dof + 1.0) / 2.0) - SpecialFunctions.GammaLn(_dof / 2.0))
                   * Math.Pow(1.0 + (d * d / _dof), -0.5 * (_dof + 1.0))
                   / Math.Sqrt(_dof * Math.PI)
                   / _scale);
        }
예제 #3
0
        /// <summary>
        /// Computes the density of the Student t-distribution.
        /// </summary>
        /// <param name="x">The location at which to compute the density.</param>
        /// <returns>the density at <paramref name="x"/>.</returns>
        public double Density(double x)
        {
            // TODO JVG we can probably do a better job for Cauchy special case
            if (Double.IsPositiveInfinity(_dof))
            {
                return(Normal.Density(_location, _scale, x));
            }

            var d = (x - _location) / _scale;

            return(SpecialFunctions.Gamma((_dof + 1.0) / 2.0)
                   * Math.Pow(1.0 + (d * d / _dof), -0.5 * (_dof + 1.0))
                   / SpecialFunctions.Gamma(_dof / 2.0)
                   / Math.Sqrt(_dof * Math.PI)
                   / _scale);
        }
예제 #4
0
        private void disp_button_Click(object sender, EventArgs e)
        {
            /*
            Normal N = new Normal(0.0, 1.0);
            DenseVector VALS = new DenseVector(20, 0);
            for (int i = -10; i < 10; i++)
            {
                VALS[i + 10] = N.Density(i);
                Console.WriteLine(VALS[i + 10]);
            }
            */

            /*
            //double[] d = new double[]{0,0};
            DenseMatrix mu = new DenseMatrix(2, 1, new[] { 0.0, 0.0 });
            DenseMatrix K = new DenseMatrix(1, 1, new[] { 1.0 });
            DenseMatrix V = new DenseMatrix(2,2, new[] {4.0, 0.0, 0.0, 1.0 });
            MatrixNormal mN = new MatrixNormal(mu, V, K);

            Console.WriteLine(mu.RowCount);
            Console.WriteLine(mu.ColumnCount);
            Console.WriteLine(mN.Sample());
            Console.WriteLine(mN.Sample());
            DenseMatrix sample_pt = new DenseMatrix(2, 1, new[] { 0.0, 0.1 });
            double pt = mN.Density(sample_pt);
            */

            int M = 150;
            int N = 200;

            Normal N_x = new Normal(N/2, 50);
            Normal N_y = new Normal(M/2, 30);

            DenseMatrix M_x = new DenseMatrix(M, N, 0.0);
            DenseMatrix M_y = new DenseMatrix(M, N, 0.0);

            DenseVector V_x = new DenseVector(N);
            for (int i = 0; i < N; i++)
            {
                V_x[i] = N_x.Density(i);
            }

            for (int j = 0; j < M; j++)
            {
                M_x.SetRow(j, V_x);
            }

            DenseVector V_y = new DenseVector(M);
            for (int i = 0; i < M; i++)
            {
                V_y[i] = N_y.Density(i);
            }

            for (int j = 0; j < N; j++)
            {
                M_y.SetColumn(j, V_y);
            }

            DenseMatrix MULT = (DenseMatrix)M_x.PointwiseMultiply(M_y);
            double s = MULT.Data.Sum();
            MULT = (DenseMatrix)MULT.PointwiseDivide(new DenseMatrix(M,N,s));
            //this.dataGridView1.DataSource = MULT;
            //Console.WriteLine(MULT.Data.Sum());

            s = MULT[M / 2, N / 2];
            MULT = (DenseMatrix)MULT.PointwiseDivide(new DenseMatrix(M, N, s));

            /*
            for (int i = 0; i < M; i++)
            {
                Console.Write(i + " - ");
                for (int j = 0; j < N; j++)
                {
                    Console.Write(MULT[i, j] + " ");
                }
                Console.WriteLine();
                Console.WriteLine();
            }
            */
            Console.WriteLine(Environment.ProcessorCount);
        }
예제 #5
0
 /// <summary>
 /// Truncated N(0, 1) to (x1, x2), where P(X <= x1) = trim and P(X <= x2) = 1 - trim
 /// </summary>
 /// <param name="trim">tail probability</param>
 /// <returns>approximately (E[X^2] = 1) / Et[X^2]</returns>
 private static double InflationFactor(double trim)
 {
     var norm = new Normal(); // N(0, 1)
     double a = norm.InverseCumulativeDistribution(1 - trim);
     double step = 2 * a / 10000;
     double[] x1s = Helper.Seq(-a + step / 2, a - step / 2, 10000);
     // Truncated N(0, 1) to P(X <= x) = trim and P(X <= x) = 1 - trim
     double eX2 = 0.0;
     foreach (double x1 in x1s) { eX2 += (x1 * x1) * norm.Density(x1); }
     eX2 = eX2 * step / (1 - 2 * trim);
     // eX2 now approximates Et[X^2]: E[X^2] of the truncated N(0, 1)
     return 1 / eX2; // approx (E[X^2] = 1) / Et[X^2]
     // == 1 / (1 + (-a * dnorm(-a) - a * dnorm(a)) / (1 - 2*trim) - ((dnorm(-1) - dnorm(a)) / (1 - 2* trim))^2)
     // According to http://en.wikipedia.org/wiki/Truncated_normal_distribution
 }
        /// <summary>
        /// Run example
        /// </summary>
        /// <a href="http://en.wikipedia.org/wiki/Normal_distribution">Normal distribution</a>
        public void Run()
        {
            // 1. Initialize the new instance of the Normal distribution class with parameters Mean = 0, StdDev = 1
            var normal = new Normal(0, 1);
            Console.WriteLine(@"1. Initialize the new instance of the Normal distribution class with parameters Mean = {0}, StdDev = {1}", normal.Mean, normal.StdDev);
            Console.WriteLine();

            // 2. Distributuion properties:
            Console.WriteLine(@"2. {0} distributuion properties:", normal);

            // Cumulative distribution function
            Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", normal.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));

            // Probability density
            Console.WriteLine(@"{0} - Probability density at location '0.3'", normal.Density(0.3).ToString(" #0.00000;-#0.00000"));

            // Log probability density
            Console.WriteLine(@"{0} - Log probability density at location '0.3'", normal.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));

            // Entropy
            Console.WriteLine(@"{0} - Entropy", normal.Entropy.ToString(" #0.00000;-#0.00000"));

            // Largest element in the domain
            Console.WriteLine(@"{0} - Largest element in the domain", normal.Maximum.ToString(" #0.00000;-#0.00000"));

            // Smallest element in the domain
            Console.WriteLine(@"{0} - Smallest element in the domain", normal.Minimum.ToString(" #0.00000;-#0.00000"));

            // Mean
            Console.WriteLine(@"{0} - Mean", normal.Mean.ToString(" #0.00000;-#0.00000"));

            // Median
            Console.WriteLine(@"{0} - Median", normal.Median.ToString(" #0.00000;-#0.00000"));

            // Mode
            Console.WriteLine(@"{0} - Mode", normal.Mode.ToString(" #0.00000;-#0.00000"));

            // Variance
            Console.WriteLine(@"{0} - Variance", normal.Variance.ToString(" #0.00000;-#0.00000"));

            // Standard deviation
            Console.WriteLine(@"{0} - Standard deviation", normal.StdDev.ToString(" #0.00000;-#0.00000"));

            // Skewness
            Console.WriteLine(@"{0} - Skewness", normal.Skewness.ToString(" #0.00000;-#0.00000"));
            Console.WriteLine();

            // 3. Generate 10 samples
            Console.WriteLine(@"3. Generate 10 samples");
            for (var i = 0; i < 10; i++)
            {
                Console.Write(normal.Sample().ToString("N05") + @" ");
            }

            Console.WriteLine();
            Console.WriteLine();

            // 4. Generate 100000 samples of the Normal(0, 1) distribution and display histogram
            Console.WriteLine(@"4. Generate 100000 samples of the Normal(0, 1) distribution and display histogram");
            var data = new double[100000];
            for (var i = 0; i < data.Length; i++)
            {
                data[i] = normal.Sample();
            }

            ConsoleHelper.DisplayHistogram(data);
            Console.WriteLine();

            // 5. Generate 100000 samples of the Normal(-10, 0.2) distribution and display histogram
            Console.WriteLine(@"5. Generate 100000 samples of the Normal(-10, 0.01) distribution and display histogram");
            normal.Mean = -10;
            normal.StdDev = 0.01;
            for (var i = 0; i < data.Length; i++)
            {
                data[i] = normal.Sample();
            }

            ConsoleHelper.DisplayHistogram(data);
        }
예제 #7
0
 /// <summary>
 /// Sets up A similarity function to indicate correlation
 /// </summary>
 /// <param name="distance">The distance between two nodes</param>
 /// <returns>The data similarity "PDF"</returns>
 private double SimilarityPDF(double distance)
 {
     var Gaussian = new Normal(0, Simulation.Default.Sigma);
     double normalizer = Gaussian.Density(0);
     return Gaussian.Density(distance) / normalizer;
 }
예제 #8
0
 /// <summary>
 /// Initializes the Data of the field
 /// </summary>
 private void Init()
 {
     //Generate random data to the network. These are partially correlated.
     //Console.WriteLine("Initiating Data network..");
     var Gaussian = new Normal(Simulation.Default.Data_Initial_Mean, Simulation.Default.Data_Initial_Sigma);
     for (int i = 0; i < Data.Length; i++)
     {
         for (int j = 0; j < Data[i].Length; j++)
         {
             Data[i][j] = Gaussian.Density(new Random(i * Data[i].Length + j).NextDouble()) / Gaussian.Density(0) * Simulation.Default.Data_Initial_Mean;
         }
     }
     //Setup data correlation changes
     //Console.WriteLine("Setting up " + Simulation.Default.Data_Changes + " data changes..");
     for (int i = 0; i < Simulation.Default.Data_Changes; i++)
     {
         GenerateChange();
     }
 }
 public PlotModel createHistogPlotModel(IEnumerable<double> data, String varname)
 {
     if (data == null)
     {
         return null;
     }
     double[] oAr = data.ToArray();
     int n = oAr.Length;
     if (n < 2)
     {
         return null;
     }
     ColumnSeries s2 = new ColumnSeries();
     DescriptiveStatistics st = new DescriptiveStatistics(oAr);
     double mean = st.Mean;
     double dev = st.StandardDeviation;
     if (dev <= 0.0)
     {
         return null;
     }
     var histog = new Histogram(oAr, 11);
     int nc = histog.BucketCount;
     Normal dist = new Normal();
     Collection<HistogItem> items = new Collection<HistogItem>();
     for (int i = 0; i < nc; ++i)
     {
         HistogItem item = new HistogItem();
         var b = histog[i];
         double x = (b.LowerBound + b.UpperBound) / 2.0;
         String label = String.Format("{0}", myconvert(x));
         int nx = (int)(dist.Density((x - mean) / dev) * n);
         item.Label = label;
         item.Value1 = b.Count;
         item.Value2 = nx;
         items.Add(item);
     }// i
     var model = new PlotModel(varname)
     {
         LegendPlacement = LegendPlacement.Outside,
         LegendPosition = LegendPosition.RightTop,
         LegendOrientation = LegendOrientation.Vertical
     };
     // Add the axes, note that MinimumPadding and AbsoluteMinimum should be set on the value axis.
     model.Axes.Add(new CategoryAxis { ItemsSource = items, LabelField = "Label" });
     model.Axes.Add(new LinearAxis(AxisPosition.Left) { MinimumPadding = 0, AbsoluteMinimum = 0 });
     model.Series.Add(new ColumnSeries { Title = varname, ItemsSource = items, ValueField = "Value1" });
     model.Series.Add(new ColumnSeries { Title = "DistributionNormale", ItemsSource = items, ValueField = "Value2" });
     return model;
 }
        public PointPairList getDensityCurve (IList<double> data, double bandwidth)
        {
            int intervals = 1000;
            var result = new PointPairList { Capacity = intervals };

            //generate a base line
            var statistics = new DescriptiveStatistics(data);
            double minValue = data.Min() - (2 * statistics.StandardDeviation);
            double maxValue = data.Max() + (2 * statistics.StandardDeviation);
            double interval = (maxValue - minValue) / intervals * 1.0;

            for (int i = 0; i < intervals; i++)
                result.Add(minValue + i * interval, 0);

            if (bandwidth == 0)
                bandwidth = 1.06 * statistics.StandardDeviation * Math.Pow(data.Count, -1.0 / 5);

            var orderedData = data.OrderBy(o => o);
            foreach (var value in orderedData)
            {
                Normal nD = new Normal(0, 1);
                for (int q = 0; q < intervals; q++)
                    result[q].Y += (1 / (data.Count * bandwidth)) * nD.Density((value - result[q].X) / bandwidth);
            }
            return result;
        }