Exemple #1
0
        private DoubleVector Pivot(IReadOnlyList <double> B)
        {
            var ret      = new DoubleVector(B.Count);
            var retArray = ret.GetInternalData();

            for (int i = 0; i < pivots.Length; i++)
            {
                retArray[i] = B[pivots[i]];
            }
            return(ret);
        }
        public void SolveGETest()
        {
            const int N = 50;
            var       a = new SparseDoubleMatrix(N, N);

            for (int i = 0; i < N; i++)
            {
                a[i, i] = 1;
            }
            // Apply random rotations around each pair of axes. This will keep det(A) ~ 1
            var rand = new Random();

            for (int i = 0; i < N; i++)
            {
                for (int j = i + 1; j < N; j++)
                {
                    double angle = rand.NextDouble() * 2 * Math.PI;
                    var    r     = new SparseDoubleMatrix(N, N);
                    for (int k = 0; k < N; k++)
                    {
                        r[k, k] = 1;
                    }
                    r[i, i] = r[j, j] = Math.Cos(angle);
                    r[i, j] = Math.Sin(angle);
                    r[j, i] = -Math.Sin(angle);
                    a       = a * r;
                }
            }

            var ainit = a.Clone();
            // Generate random vector
            var b = new DoubleVector(N);

            for (int i = 0; i < N; i++)
            {
                b[i] = rand.NextDouble();
            }

            var binit = b.Clone();
            // Solve system
            var solver = new GaussianEliminationSolver();
            var sw     = new Stopwatch();

            sw.Start();
            var x = solver.SolveDestructive(a, b.GetInternalData());

            sw.Stop();
            Trace.WriteLine("Gaussian elimination took: " + sw.ElapsedTicks);
            // Put solution into system
            var b2 = ainit * x;

            // Verify result is the same
            Assert.IsTrue(VectorMath.LInfinityNorm(binit, b2) < 1e-6);
        }
        ///<summary>Solves a system on linear equations, AX=B, where A is the factored matrixed.</summary>
        ///<param name="B">RHS side of the system.</param>
        ///<returns>the solution vector, X.</returns>
        ///<exception cref="ArgumentNullException">B is null.</exception>
        ///<exception cref="NotPositiveDefiniteException">A is not positive definite.</exception>
        ///<exception cref="ArgumentException">The number of rows of A and the length of B must be the same.</exception>
        public DoubleVector Solve(IReadOnlyList <double> B)
        {
            if (B == null)
            {
                throw new System.ArgumentNullException("B cannot be null.");
            }
            Compute();
            if (!ispd)
            {
                throw new NotPositiveDefiniteException();
            }
            else
            {
                if (B.Count != order)
                {
                    throw new System.ArgumentException("The length of B must be the same as the order of the matrix.");
                }
#if MANAGED
                // Copy right hand side.
                var X      = new DoubleVector(B);
                var xarray = X.GetInternalData();

                // Solve L*Y = B;
                for (int i = 0; i < order; i++)
                {
                    double sum = B[i];
                    for (int k = i - 1; k >= 0; k--)
                    {
                        sum -= l.data[i][k] * xarray[k];
                    }
                    xarray[i] = sum / l.data[i][i];
                }
                // Solve L'*X = Y;
                for (int i = order - 1; i >= 0; i--)
                {
                    double sum = xarray[i];
                    for (int k = i + 1; k < order; k++)
                    {
                        sum -= l.data[k][i] * xarray[k];
                    }
                    xarray[i] = sum / l.data[i][i];
                }

                return(X);
#else
                double[] rhs = DoubleMatrix.ToLinearArray(B);
                Lapack.Potrs.Compute(Lapack.UpLo.Lower, order, 1, l.data, order, rhs, B.Length);
                DoubleVector ret = new DoubleVector(order, B.Length);
                ret.data = rhs;
                return(ret);
#endif
            }
        }
 public void GetInternalData()
 {
   double[] testvector = new double[2]{0,1};
   DoubleVector test = new DoubleVector(testvector);
   double[] internaldata = test.GetInternalData();
   
   Assert.AreEqual(internaldata.Length,testvector.Length);
   Assert.AreEqual(internaldata[0],testvector[0]);
   Assert.AreEqual(internaldata[1],testvector[1]);
 }
Exemple #5
0
		/// <summary>
		///
		/// </summary>
		/// <param name="x"></param>
		/// <param name="bw"></param>
		/// <param name="bwSel"></param>
		/// <param name="adjust"></param>
		/// <param name="kernel"></param>
		/// <param name="weights"></param>
		/// <param name="width"></param>
		/// <param name="widthSel"></param>
		/// <param name="n"></param>
		/// <param name="from"></param>
		/// <param name="to"></param>
		/// <param name="cut"></param>
		/// <remarks>Adapted from the R-project (www.r-project.org), Version 2.72, file density.R</remarks>
		public static ProbabilityDensityResult ProbabilityDensity(
			this IROVector x,
			double bw,
			string bwSel,
			double adjust,
			ConvolutionKernel kernel,
			IROVector weights,
			double width,
			string widthSel,
			int n,
			double from,
			double to,
			double cut // default: 3
			)
		{
			double wsum;
			if (null == weights)
			{
				weights = VectorMath.GetConstantVector(1.0 / x.Length, x.Length);
				wsum = 1;
			}
			else
			{
				wsum = weights.Sum();
			}

			double totMass = 1;

			int n_user = n;
			n = Math.Max(n, 512);
			if (n > 512)
				n = BinaryMath.NextPowerOfTwoGreaterOrEqualThan(n);

			if (bw.IsNaN() && !(width.IsNaN() && null == widthSel))
			{
				if (!width.IsNaN())
				{
					// S has width equal to the length of the support of the kernel
					// except for the gaussian where it is 4 * sd.
					// R has bw a multiple of the sd.
					double fac = 1;
					switch (kernel)
					{
						case ConvolutionKernel.Gaussian:
							fac = 4;
							break;

						case ConvolutionKernel.Rectangular:
							fac = 2 * Math.Sqrt(3);
							break;

						case ConvolutionKernel.Triangular:
							fac = 2 * Math.Sqrt(6);
							break;

						case ConvolutionKernel.Epanechnikov:
							fac = 2 * Math.Sqrt(5);
							break;

						case ConvolutionKernel.Biweight:
							fac = 2 * Math.Sqrt(7);
							break;

						case ConvolutionKernel.Cosine:
							fac = 2 / Math.Sqrt(1 / 3 - 2 / (Math.PI * Math.PI));
							break;

						case ConvolutionKernel.Optcosine:
							fac = 2 / Math.Sqrt(1 - 8 / (Math.PI * Math.PI));
							break;

						default:
							throw new ArgumentException("Unknown convolution kernel");
					}
					bw = width / fac;
				}
				else
				{
					bwSel = widthSel;
				}
			}

			if (null != bwSel)
			{
				if (x.Length < 2)
					throw new ArgumentException("need at least 2 points to select a bandwidth automatically");
				switch (bwSel.ToLowerInvariant())
				{
					case "nrd0":
						//nrd0 = bw.nrd0(x),
						break;

					case "nrd":
						//nrd = bw.nrd(x),
						break;

					case "ucv":
						//ucv = bw.ucv(x),
						break;

					case "bcv":
						//bcv = bw.bcv(x),
						break;

					case "sj":
						//sj = , "sj-ste" = bw.SJ(x, method="ste"),
						break;

					case "sj-dpi":
						//"sj-dpi" = bw.SJ(x, method="dpi"),
						break;

					default:
						throw new ArgumentException("Unknown bandwith selection rule: " + bwSel.ToString());
				}
			}

			if (!RMath.IsFinite(bw))
				throw new ArithmeticException("Bandwidth is not finite");

			bw = adjust * bw;

			if (!(bw > 0))
				throw new ArithmeticException("Bandwith is not positive");

			if (from.IsNaN())
				from = x.GetMinimum() - cut * bw;
			if (to.IsNaN())
				to = x.GetMaximum() + cut * bw;

			if (!RMath.IsFinite(from))
				throw new ArithmeticException("non-finite 'from'");
			if (!to.IsFinite())
				throw new ArithmeticException("non-finite 'to'");
			double lo = from - 4 * bw;
			double up = to + 4 * bw;

			var y = new DoubleVector(2 * n);
			MassDistribution(x, weights, lo, up, y, n);
			y.Multiply(totMass);

			var kords = new DoubleVector(2 * n);
			kords.FillWithLinearSequenceGivenByStartEnd(0, 2 * (up - lo));

			for (int i = n + 1, j = n - 1; j >= 0; i++, j--)
				kords[i] = -kords[j];

			switch (kernel)
			{
				case ConvolutionKernel.Gaussian:
					kords.Apply(new Probability.NormalDistribution(0, bw).PDF);
					break;

				case ConvolutionKernel.Rectangular:
					double a = bw * Math.Sqrt(3);
					kords.Apply(delegate(double xx) { return Math.Abs(xx) < a ? 0.5 / a : 0; });
					break;

				case ConvolutionKernel.Triangular:
					a = bw * Math.Sqrt(6);
					kords.Apply(delegate(double xx) { return Math.Abs(xx) < a ? (1 - Math.Abs(xx) / a) / a : 0; });
					break;

				case ConvolutionKernel.Epanechnikov:
					a = bw * Math.Sqrt(5);
					kords.Apply(delegate(double xx) { return Math.Abs(xx) < a ? 0.75 * (1 - RMath.Pow2(Math.Abs(xx) / a)) / a : 0; });
					break;

				case ConvolutionKernel.Biweight:
					a = bw * Math.Sqrt(7);
					kords.Apply(delegate(double xx) { return Math.Abs(xx) < a ? 15.0 / 16.0 * RMath.Pow2(1 - RMath.Pow2(Math.Abs(xx) / a)) / a : 0; });
					break;

				case ConvolutionKernel.Cosine:
					a = bw / Math.Sqrt(1.0 / 3 - 2 / RMath.Pow2(Math.PI));
					kords.Apply(delegate(double xx) { return Math.Abs(xx) < a ? (1 + Math.Cos(Math.PI * xx / a)) / (2 * a) : 0; });
					break;

				case ConvolutionKernel.Optcosine:
					a = bw / Math.Sqrt(1 - 8 / RMath.Pow2(Math.PI));
					kords.Apply(delegate(double xx) { return Math.Abs(xx) < a ? Math.PI / 4 * Math.Cos(Math.PI * xx / (2 * a)) / a : 0; });
					break;

				default:
					throw new ArgumentException("Unknown convolution kernel");
			}

			var result = new DoubleVector(2 * n);
			Fourier.FastHartleyTransform.CyclicRealConvolution(y.GetInternalData(), kords.GetInternalData(), result.GetInternalData(), 2 * n, null);
			y.Multiply(1.0 / (2 * n));
			VectorMath.Max(y, 0, y);
			var xords = VectorMath.CreateEquidistantSequenceByStartEndLength(lo, up, n);
			var xu = VectorMath.CreateEquidistantSequenceByStartEndLength(from, to, n_user);

			double[] res2 = new double[xu.Length];
			Interpolation.LinearInterpolation.Interpolate(xords, result, n, xu, xu.Length, 0, out res2);

			return new ProbabilityDensityResult() { X = xu, Y = VectorMath.ToROVector(res2), Bandwidth = bw };
		}