Inheritance: TestBase
Exemple #1
0
        private void _CalcCorr90()
        {
            _corr90 = new List <CorrRes>(_cntPoint90 - _cntItem90);

            for (int i = 0; i < (_cntPoint90 - _cntItem90); i++)
            {
                CorrRes  tmp = new CorrRes();
                double[] res = new double[(_cntPoint90 - _cntItem90)];

                tmp.i = i;

                for (int j = 0; j < (_cntPoint90 - _cntItem90); j++)
                {
                    res[j] = Covariance.Correlation(_A90, _resDict90[j]);
                }

                tmp.max   = res.Max();
                tmp.j_max = Array.IndexOf(res, tmp.max);
                tmp.min   = res.Min();
                tmp.j_min = Array.IndexOf(res, tmp.min);
                _corr90.Add(tmp);
            }

            int[] arr_i     = (from el in _corr90 orderby el.max select el.i).ToArray <int>();
            int[] arr_j_max = (from el in _corr90 orderby el.max select el.j_max).ToArray <int>();
            int   j_max     = arr_j_max.Last();

            Print("(90) j_max = " + j_max);
            _DrawGraphArray90(_resDict90[j_max], _xTime90, _resDict90[j_max + _cntItem90 - 1]);
        }
Exemple #2
0
        private void EvaluateCovariance(IObjectiveModel objective)
        {
            objective.EvaluateAt(objective.Point); // Hessian may be not yet updated.

            var Hessian = objective.Hessian;

            if (Hessian == null || objective.DegreeOfFreedom < 1)
            {
                Covariance     = null;
                Correlation    = null;
                StandardErrors = null;
                return;
            }

            Covariance = Hessian.PseudoInverse() * objective.Value / objective.DegreeOfFreedom;

            if (Covariance != null)
            {
                StandardErrors = Covariance.Diagonal().PointwiseSqrt();

                var correlation = Covariance.Clone();
                var d           = correlation.Diagonal().PointwiseSqrt();
                var dd          = d.OuterProduct(d);
                Correlation = correlation.PointwiseDivide(dd);
            }
            else
            {
                StandardErrors = null;
                Correlation    = null;
            }
        }
Exemple #3
0
    private static void covariance_initialize(int par_num)

    //****************************************************************************80
    //
    //  Discussion:
    //
    //    Note that VALUE.FACTOR is the upper triangular Cholesky factor of the
    //    covariance matrix VALUE_ARRAY, so that
    //
    //      VALUE.ARRAY = VALUE.FACTOR' * VALUE.FACTOR
    //
    //  Licensing:
    //
    //    This code is distributed under the GNU LGPL license.
    //
    //  Modified:
    //
    //    26 June 2013
    //
    //  Author:
    //
    //    John Burkardt
    //
    {
        int i;

        c = new Covariance
        {
            //
            //  Set ORDER
            //
            order = par_num
        };
        //
        //  Set ARRAY.
        //
        covariance_set(c.order);
        //
        //  Set FACTOR.
        //
        c.factor = typeMethods.r8mat_pofac(c.order, c.array);
        //
        //  Set INV
        //
        c.inv = typeMethods.r8mat_poinv(c.order, c.factor);
        //
        //  Set DET.
        //
        c.det = typeMethods.r8mat_podet(c.order, c.factor);
        //
        //  Set MEAN.
        //
        c.mean = new double[c.order];
        for (i = 0; i < c.order; i++)
        {
            c.mean[i] = 0.0;
        }
    }
        public PearsonsCorrelation(Covariance covariance)
        {
            RealMatrix covarianceMatrix = covariance.GetCovarianceMatrix();

            if (covarianceMatrix == null)
            {
                //throw new NullArgumentException(LocalizedFormats.COVARIANCE_MATRIX, new Object[0]);
            }
            this.nObs = covariance.getN();
            this.correlationMatrix = CovarianceToCorrelation(covarianceMatrix);
        }
Exemple #5
0
        public void Maximize(LLNASufficientStatistics sufficientStatistics)
        {
            for (int i = 0; i < K - 1; i++)
            {
                Mu[i] = sufficientStatistics.MuSufficientStatistic[i] / sufficientStatistics.NData;
            }

            for (int i = 0; i < K - 1; i++)
            {
                for (int j = 0; j < K - 1; j++)
                {
                    Covariance[i, j] =
                        (1 / sufficientStatistics.NData) *
                        (sufficientStatistics.CovarianceSufficientStatistic[i, j] +
                         sufficientStatistics.NData * Mu[i] * Mu[j] -
                         sufficientStatistics.MuSufficientStatistic[i] * Mu[j] -
                         sufficientStatistics.MuSufficientStatistic[j] * Mu[i]);
                }
            }

            if (_parameters.CovEstimate == SHRINK)
            {
                ShrinkCov(Covariance, sufficientStatistics.NData);
            }

            InvCovariance = Covariance.Inverse();
            LogDeterminantInvCovariance = InvCovariance.ComputeLNDeterminant();
            for (int i = 0; i < K; i++)
            {
                double sum = 0;
                for (int j = 0; j < LogBeta.ColumnCount; j++)
                {
                    sum += sufficientStatistics.BetaSufficientStatistic[i, j];
                }

                if (sum == 0)
                {
                    sum = MathHelper.SafeLog(sum) * LogBeta.ColumnCount;
                }
                else
                {
                    sum = MathHelper.SafeLog(sum);
                }

                for (int j = 0; j < LogBeta.ColumnCount; j++)
                {
                    LogBeta[i, j] = MathHelper.SafeLog(sufficientStatistics.BetaSufficientStatistic[i, j]) - sum;
                }
            }
        }
        public void Test()
        {
            //Covariance<Base> coB = new CoContraVarianceCollection();
            //Covariance<Derived> coD = coB;
            Covariance <Derived> coD = new CoContraVariance();
            Covariance <Base>    coB = coD;



            //Contravariance<Derived> contraD = new CoContraVarianceCollection();
            //Contravariance<Base> contraB = contraD;
            Contravariance <Base>    contraB = new CoContraVariance();
            Contravariance <Derived> contraD = contraB;
        }
        public bool Equals(IDistribution other)
        {
            var d = other as MultivariateDiscreteDistribution;

            if (d == null)
            {
                //throw new ApplicationException("Incompatable types, other is not UnivariateDiscreteDistribution");
                return(false);
            }

            return(VectorExtentions.EqualsTo(Variance, d.Variance) &&
                   VectorExtentions.EqualsTo(Mean, d.Mean) &&
                   Covariance.EqualsTo(d.Covariance) &&
                   Dimension == d.Dimension);
        }
Exemple #8
0
        static void varianceInDelegates()
        {
            //with variance, the method does not need to match with the delegate
            //Covariance      | return type    | Delegate return Parent                | Method return a Child
            //ContraVariance  | parameter type | Delegate recive as parameter a Child  | Method recive as parameter Parent

            Covariance conv = new Covariance(covarianceMethod);

            conv();

            Contravariance cont = new Contravariance(contraVarianceMethod);
            Child          c    = new Child();

            contraVarianceMethod(c);
        }
        public void TestMethod001()
        {
            // Arrange
            IEnumerable <Cat> cats = new List <Cat>
            {
                new Cat("Troublemaker"),
                new Cat("Alpithar")
            };
            Covariance covariance = new Covariance();

            // Act
            IEnumerable <string> result = covariance.GetAnimalNames(cats);

            // Assert
            Assert.IsTrue(result.Any(a => a.Equals("TroubleMaker", StringComparison.OrdinalIgnoreCase)));
        }
Exemple #10
0
    public void Merge(Covariance Group)
    {
        // Put your code here
        List <double> firstListToCopy  = Group.FirstList;
        List <double> secondListToCopy = Group.SecondList;

        this.sumOfFirst  += Group.SumOfFirst;
        this.sumOfSecond += Group.SumOfSecond;

        foreach (double d in firstListToCopy)
        {
            this.firstList.Add(d);
        }

        foreach (double d in secondListToCopy)
        {
            this.secondList.Add(d);
        }
    }
    public void Merge(Covariance Group)
    {
        // Put your code here
        List<double> firstListToCopy = Group.FirstList;
        List<double> secondListToCopy = Group.SecondList;

        this.sumOfFirst += Group.SumOfFirst;
        this.sumOfSecond += Group.SumOfSecond;

        foreach (double d in firstListToCopy)
        {
            this.firstList.Add(d);
        }

        foreach (double d in secondListToCopy)
        {
            this.secondList.Add(d);
        }
    }
        /// <summary>
        /// 显示波段统计量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Comparetwobands_Load(object sender, EventArgs e)
        {
            this.textBox1.Text += "波段" + (i + 1);
            this.textBox1.Text += "\t均值:";
            this.textBox1.Text += average1.ToString();
            this.textBox1.Text += "\t标准差:";
            this.textBox1.Text += standard1.ToString();
            this.textBox1.Text += "\r\n\r\n\r\n";

            this.textBox1.Text += "波段" + (j + 1);
            this.textBox1.Text += "\t均值:";
            this.textBox1.Text += average2.ToString();
            this.textBox1.Text += "\t标准差:";
            this.textBox1.Text += standard2.ToString();
            this.textBox1.Text += "\r\n\r\n\r\n";
            this.textBox1.Text += "协方差:";
            this.textBox1.Text += Covariance.ToString();
            this.textBox1.Text += "\r\n相关系数:";
            this.textBox1.Text += Correlation.ToString();
        }
Exemple #13
0
    public static void test()
    {
        ProblemSize ps = new()
        {
            chain_num = 10,
            cr_num    = 3,
            gen_num   = 10,
            pair_num  = 3,
            //par_num = 100,
            par_num = 5
        };

        c = new Covariance(ps.par_num);

        ProblemValue pv = new()
        {
            chain_filename         = "problem1_chain00.txt",
            gr_filename            = "problem1_gr.txt",
            gr_threshold           = 1.2,
            jumpstep               = 5,
            printstep              = 10,
            restart_read_filename  = "",
            restart_write_filename = "problem1_restart.txt",
            limits = new double[ps.par_num * 2]
        };

        for (int j = 0; j < ps.par_num; j++)
        {
            pv.limits[0 + j * 2] = 9.9;
            pv.limits[1 + j * 2] = +10.0;
        }

        Dream.dream(ref ps, ref pv, prior_sample, prior_density, sample_likelihood);
    }

    private static Dream.DensityResult prior_density(int par_num, double[] zp, int zpIndex = 0)
 public override string ToString()
 {
     return("LeastSquareResults [chiSq=" + ChiSq + ", fit parameters=" + FitParameters.ToString() +
            ", model parameters= " + ModelParameters.ToString() + ", covariance="
            + Covariance.ToString() + "]");
 }
Exemple #15
0
 Covariance(Covariance cc1, double v1, Covariance cc2, double v2)
 {
     vi    = cc1.vi + cc2.vi;
     vj    = cc1.vj + cc2.vj;
     value = v1 + v2;
 }
Exemple #16
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            // TODO: Implement Functionality Here

            Animal a = new Animal();
            SubCat c = new SubCat();
            Dog d = new Dog();
            Covariance cov = new Covariance();

            Console.WriteLine("---------------- Test generic animal");
            a.Out();
            cov.feed(a);
            Console.WriteLine("---------------- Func now");
            cov.funcfeed(() => a);
            Console.WriteLine("---------------- and Lazy!");
            var l_a = new Lazy<Animal>();
            cov.lazyfeed(l_a);
            Console.WriteLine("created {0}",l_a.IsValueCreated);
            Console.WriteLine("---------------- Func+Lazy");
            cov.funcfeed(() => l_a.Value);
            Console.WriteLine("created {0}",l_a.IsValueCreated);
            l_a.Value.Out();
            Console.WriteLine("---------------- CovLazy!!");
            var cl_a = new CovLazy<Animal>();
            cov.covlazyfeed(cl_a);
            Console.WriteLine("fired {0}",cl_a.IsFired);
            cl_a.MyVal.Out();
            Console.WriteLine("---------------- Test cat");
            c.Out();
            cov.feed(c);
            Console.WriteLine("---------------- Func now");
            cov.funcfeed(() => c);
            Console.WriteLine("---------------- and Lazy!");
            var l_c = new Lazy<SubCat>();
            cov.lazyfeed(l_c);
            Console.WriteLine("created {0}",l_c.IsValueCreated);
            Console.WriteLine("---------------- Func+Lazy");
            cov.funcfeed(() => l_c.Value);
            Console.WriteLine("created {0}",l_c.IsValueCreated);
            l_c.Value.Out();
            Console.WriteLine("---------------- CovLazy!!");
            var cl_c = new CovLazy<SubCat>();
            cov.covlazyfeed(cl_c);
            Console.WriteLine("fired {0}",cl_c.IsFired);
            cl_c.MyVal.Out();
            Console.WriteLine("---------------- Test dog");
            d.Out();
            cov.feed(new Dog());
            Console.WriteLine("---------------- Func now");
            cov.funcfeed(() => d);
            Console.WriteLine("---------------- and Lazy!");
            var l_d = new Lazy<Dog>();
            cov.lazyfeed(l_d);
            Console.WriteLine("created {0}",l_d.IsValueCreated);
            Console.WriteLine("---------------- Func+Lazy");
            cov.funcfeed(() => l_d.Value);
            Console.WriteLine("created {0}",l_d.IsValueCreated);
            l_d.Value.Out();
            Console.WriteLine("---------------- CovLazy!!");
            var cl_d = new CovLazy<Dog>();
            cov.covlazyfeed(cl_d);
            Console.WriteLine("fired {0}",cl_d.IsFired);
            cl_d.MyVal.Out();

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
Exemple #17
0
 private static void BaseCovarianceRunner()
 {
     NewSubject.WriteLine("Base Covariance");
     Covariance.Run();
 }
        public void Update <TMeasurements>(Vector <double> motion, TMeasurements measurements) where TMeasurements : IEnumerable <LandmarkMeasurement>
        {
            // expand kalman filter to accomodate new landmarks, if necessary
            var prevMeanCount = Mean.Count;
            var maxIndex      = measurements.Max(m => (int?)m.Index);

            if (maxIndex != null)
            {
                var m = LandmarkDim * maxIndex.Value + StateDim;
                if (m >= prevMeanCount)
                {
                    var mean       = new DenseVector(m + LandmarkDim);
                    var covariance = new DenseMatrix(m + LandmarkDim);
                    covariance.SetDiagonal(DenseVector.Create(m + LandmarkDim, 10000000));
                    Mean.CopySubVectorTo(mean, 0, 0, Mean.Count);
                    covariance.SetSubMatrix(0, Covariance.RowCount, 0, Covariance.ColumnCount, Covariance);
                    Mean       = mean;
                    Covariance = covariance;
                }
            }

            var N  = (Mean.Count - StateDim) / LandmarkDim;
            var Fx = new DenseMatrix(StateDim, StateDim + LandmarkDim * N);

            for (int i = 0; i < StateDim; i++)
            {
                Fx[i, i] = 1;
            }

            var motionModel    = new DenseVector(new[] { motion[0] * Math.Cos(Mean[2]), motion[0] * Math.Sin(Mean[2]), motion[1] });
            var motionJacobian = DenseMatrix.OfArray(new[, ]
            {
                { 0, 0, -motion[0] * Math.Sin(Mean[2]) },
                { 0, 0, motion[0] * Math.Cos(Mean[2]) },
                { 0, 0, 0 }
            });

            // Integrate motion
            var identity = DenseMatrix.CreateIdentity(Mean.Count);

            Mean += Fx.TransposeThisAndMultiply(motionModel.ToColumnMatrix()).Column(0);
            var jacobian = identity + Fx.TransposeThisAndMultiply(motionJacobian) * Fx;

            Covariance = jacobian * Covariance.TransposeAndMultiply(jacobian) + Fx.TransposeThisAndMultiply(MotionNoise) * Fx;

            // Auxiliary variables
            var positionEstimate = new DenseVector(new[] { Mean[0], Mean[1] });
            var Fxj = new DenseMatrix(StateDim + LandmarkDim, LandmarkDim * N + StateDim);

            for (int i = 0; i < StateDim; i++)
            {
                Fxj[i, i] = 1;
            }

            // Integrate measurements
            foreach (var measurement in measurements)
            {
                // m is the corrected index of the landmark
                var m = LandmarkDim * measurement.Index + StateDim;

                if (m >= prevMeanCount)
                {
                    // landmark never seen before
                    Mean[m]     = Mean[0] + measurement.Measurement[0] * Math.Cos(measurement.Measurement[1] + Mean[2]);
                    Mean[m + 1] = Mean[1] + measurement.Measurement[0] * Math.Sin(measurement.Measurement[1] + Mean[2]);
                }

                var landmarkEstimate = new DenseVector(new[] { Mean[m], Mean[m + 1] });
                var landmarkDelta    = landmarkEstimate - positionEstimate;
                var q                = landmarkDelta.DotProduct(landmarkDelta);
                var sqrtQ            = Math.Sqrt(q);
                var measurementModel = new DenseVector(new[] { sqrtQ, Math.Atan2(landmarkDelta[1], landmarkDelta[0]) - Mean[2] });
                for (int i = 0; i < LandmarkDim; i++)
                {
                    Fxj[StateDim + i, m + i] = 1;
                }

                var measurementJacobian = (1 / q) * DenseMatrix.OfArray(new[, ]
                {
                    { -sqrtQ * landmarkDelta[0], -sqrtQ * landmarkDelta[1], 0, sqrtQ * landmarkDelta[0], sqrtQ * landmarkDelta[1] },
                    { landmarkDelta[1], -landmarkDelta[0], -q, -landmarkDelta[1], landmarkDelta[0] }
                }) * Fxj;

                var kalmanGain = Covariance * measurementJacobian.TransposeThisAndMultiply((measurementJacobian * Covariance.TransposeAndMultiply(measurementJacobian) + MeasurementNoise).Inverse());
                Mean      += kalmanGain * (measurement.Measurement - measurementModel);
                Covariance = (identity - kalmanGain * measurementJacobian) * Covariance;

                for (int i = 0; i < LandmarkDim; i++)
                {
                    Fxj[StateDim + i, m + i] = 0;
                }
            }
        }
Exemple #19
0
 public Controller()
 {
     FF = new FormingFilter(3, 5000, 0.01, 11.427, 3.464, 0.286, 4.414);
     CM = new Covariance(3, 5000, 1.621, 0.542, 1.732, 2.903, 1.973, 0.01, 11.427, 3.464, 0.286, 4.414);
     KF = new KalmanFilter(3, 5000, FF.OutputSignal, CM);
 }