/// <summary>
        /// Fits the data to a linear combination of fit functions.
        /// </summary>
        /// <param name="functions">The component functions.</param>
        /// <returns>A fit result containing the best-fit coefficients of the component functions and a &#x3C7;<sup>2</sup> test
        /// of the quality of the fit.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="functions"/> is null.</exception>
        /// <exception cref="InsufficientDataException">There are fewer data points than fit parameters.</exception>
        public UncertainMeasurementFitResult FitToLinearFunction(Func <T, double>[] functions)
        {
            if (functions == null)
            {
                throw new ArgumentNullException(nameof(functions));
            }
            if (functions.Length > data.Count)
            {
                throw new InsufficientDataException();
            }

            // construct the design matrix
            RectangularMatrix A = new RectangularMatrix(data.Count, functions.Length);

            for (int r = 0; r < data.Count; r++)
            {
                for (int c = 0; c < functions.Length; c++)
                {
                    A[r, c] = functions[c](data[r].X) / data[r].Y.Uncertainty;
                }
            }

            // construct the right-hand-side
            ColumnVector b = new ColumnVector(data.Count);

            for (int r = 0; r < data.Count; r++)
            {
                b[r] = data[r].Y.Value / data[r].Y.Uncertainty;
            }

            // Solve the system via QR
            ColumnVector    a;
            SymmetricMatrix C;

            QRDecomposition.SolveLinearSystem(A, b, out a, out C);

            // do a chi^2 test
            double chi2 = 0.0;

            for (int i = 0; i < data.Count; i++)
            {
                double f = 0.0;
                for (int j = 0; j < functions.Length; j++)
                {
                    f += functions[j](data[i].X) * a[j];
                }
                chi2 += Math.Pow((data[i].Y.Value - f) / data[i].Y.Uncertainty, 2);
            }
            TestResult test = new TestResult("χ²", chi2, new ChiSquaredDistribution(data.Count - functions.Length), TestType.RightTailed);

            // return the results
            string[] names = new string[functions.Length];
            for (int j = 0; j < names.Length; j++)
            {
                names[j] = j.ToString();
            }
            ParameterCollection parameters = new ParameterCollection(names, a, C);

            return(new UncertainMeasurementFitResult(parameters, test));
        }
示例#2
0
        public void QRDecompositionComputeTest()
        {
            Matrix matrix = MatrixFactory.CreateSquare(12, -51, 4,
                                                       6, 167, -68,
                                                       -4, 24, -41);

            Matrix qExpected = MatrixFactory.CreateSquare(6.0 / 7, 69.0 / 175, -58.0 / 175,
                                                          3.0 / 7, -158.0 / 175, 6.0 / 175,
                                                          -2.0 / 7, -6.0 / 35, -33.0 / 35);

            Matrix rExpected = MatrixFactory.CreateSquare(14, 21, -14,
                                                          0, -175, 70,
                                                          0, 0, 35);

            QRDecomposition decomposition = new QRDecomposition(matrix);

            decomposition.Compute();

            for (Int32 j = 0; j < matrix.NumberOfRows; j++)
            {
                for (Int32 k = 0; k < matrix.NumberOfColumns; k++)
                {
                    Assert.AreEqual(qExpected[j, k], decomposition.Q[j, k], 0.001);
                    Assert.AreEqual(rExpected[j, k], decomposition.R[j, k], 0.001);
                }
            }
        }
示例#3
0
        public void Simple()
        {
            var a = new Matrix(2, 2);

            a[0, 0] = 0;
            a[0, 1] = 0;
            a[1, 0] = 1;
            a[1, 1] = 0;

            var b = new Matrix(2, 2);

            b[0, 0] = 0;
            b[0, 1] = 0;
            b[1, 0] = 0;
            b[1, 1] = 1;

            var qrDecomposition = new QRDecomposition(a);

            Assert.IsFalse(qrDecomposition.IsFullRank);

            qrDecomposition = new QRDecomposition(b);
            Assert.IsFalse(qrDecomposition.IsFullRank);

            qrDecomposition = new QRDecomposition(a * b);
            Assert.IsFalse(qrDecomposition.IsFullRank);
        }
示例#4
0
        public void Hilbert()
        {
            var matrix = GetHilbertMatrix4();

            var decomposition = new QRDecomposition(matrix);
            var matrixR       = decomposition.RightFactorMatrix;
            var matrixH       = decomposition.H;

            Assert.AreEqual(matrixR[0, 0], -1.19, 0.01);
            Assert.AreEqual(matrixR[0, 1], -0.67, 0.01);
            Assert.AreEqual(matrixR[0, 2], -0.47, 0.01);
            Assert.AreEqual(matrixR[0, 3], -0.37, 0.01);

            Assert.AreEqual(matrixR[1, 0], 0);
            Assert.AreEqual(matrixR[1, 1], -0.12, 0.01);
            Assert.AreEqual(matrixR[1, 2], -0.13, 0.01);
            Assert.AreEqual(matrixR[1, 3], -0.12, 0.01);

            Assert.AreEqual(matrixR[2, 0], 0);
            Assert.AreEqual(matrixR[2, 1], 0);
            Assert.AreEqual(matrixR[2, 2], -0.01, 0.01);
            Assert.AreEqual(matrixR[2, 3], -0.01, 0.01);

            Assert.AreEqual(matrixR[3, 0], 0);
            Assert.AreEqual(matrixR[3, 1], 0);
            Assert.AreEqual(matrixR[3, 2], 0);
            Assert.AreEqual(matrixR[3, 3], -0.0001, 0.0001);
        }
示例#5
0
文件: Q.cs 项目: vh-vahan/ngenerics
        public void Hilbert()
        {
            var matrix = GetHilbertMatrix4();

            var decomposition = new QRDecomposition(matrix);
            var matrixQ       = decomposition.LeftFactorMatrix;

            Assert.AreEqual(matrixQ[0, 0], -0.84, 0.01);
            Assert.AreEqual(matrixQ[0, 1], 0.52, 0.01);
            Assert.AreEqual(matrixQ[0, 2], -0.15, 0.01);
            Assert.AreEqual(matrixQ[0, 3], 0.03, 0.01);

            Assert.AreEqual(matrixQ[1, 0], -0.42, 0.01);
            Assert.AreEqual(matrixQ[1, 1], -0.44, 0.01);
            Assert.AreEqual(matrixQ[1, 2], 0.73, 0.01);
            Assert.AreEqual(matrixQ[1, 3], -0.32, 0.01);

            Assert.AreEqual(matrixQ[2, 0], -0.28, 0.01);
            Assert.AreEqual(matrixQ[2, 1], -0.53, 0.01);
            Assert.AreEqual(matrixQ[2, 2], -0.14, 0.01);
            Assert.AreEqual(matrixQ[2, 3], 0.79, 0.01);

            Assert.AreEqual(matrixQ[3, 0], -0.21, 0.01);
            Assert.AreEqual(matrixQ[3, 1], -0.50, 0.01);
            Assert.AreEqual(matrixQ[3, 2], -0.65, 0.01);
            Assert.AreEqual(matrixQ[3, 3], -0.53, 0.01);
        }
示例#6
0
        /// <summary>
        /// Computes the polynomial of given degree which best fits the data.
        /// </summary>
        /// <param name="m">The degree, which must be non-negative.</param>
        /// <returns>The fit result.</returns>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="m"/> is negative.</exception>
        /// <exception cref="InsufficientDataException">There are fewer data points than coefficients to be fit.</exception>
        public FitResult PolynomialRegression(int m)
        {
            if (m < 0)
            {
                throw new ArgumentOutOfRangeException("m");
            }

            int n = Count;

            if (n < m + 1)
            {
                throw new InsufficientDataException();
            }

            // Construct the n X m design matrix A_{ij} = x_{i}^{j}
            RectangularMatrix A = new RectangularMatrix(n, m + 1);
            ColumnVector      y = new ColumnVector(n);

            for (int i = 0; i < n; i++)
            {
                double x = xData[i];
                A[i, 0] = 1.0;
                for (int j = 1; j <= m; j++)
                {
                    A[i, j] = A[i, j - 1] * x;
                }
                y[i] = yData[i];
            }

            ColumnVector    a;
            SymmetricMatrix C;

            QRDecomposition.SolveLinearSystem(A, y, out a, out C);

            // Compute the residual vector r and s^2 = r^2 / dof
            ColumnVector r   = A * a - y;
            double       V   = r.Transpose() * r;
            double       ss2 = V / (n - (m + 1));

            // Scale up the covariance by s^2
            for (int i = 0; i <= m; i++)
            {
                for (int j = i; j <= m; j++)
                {
                    C[i, j] = C[i, j] * ss2;
                }
            }

            // compute F-statistic
            // total variance dof = n - 1, explained variance dof = m, unexplained variance dof = n - (m + 1)
            double     totalVarianceSum       = yData.Variance * n;
            double     unexplainedVarianceSum = V;
            double     explainedVarianceSum   = totalVarianceSum - unexplainedVarianceSum;
            double     unexplainedVarianceDof = n - (m + 1);
            double     explainedVarianceDof   = m;
            double     F    = (explainedVarianceSum / explainedVarianceDof) / (unexplainedVarianceSum / unexplainedVarianceDof);
            TestResult test = new TestResult("F", F, TestType.RightTailed, new FisherDistribution(explainedVarianceDof, unexplainedVarianceDof));

            return(new FitResult(a, C, test));
        }
        public MatrixValue Function(MatrixValue x, MatrixValue y, MatrixValue f)
        {
            if (x.Length != y.Length)
            {
                throw new YAMPDifferentLengthsException(x.Length, y.Length);
            }

            if (x.Length != f.DimensionY)
            {
                throw new YAMPDifferentLengthsException(x.Length, f.DimensionY);
            }

            var m = f.DimensionX;

            if (m < 2)
            {
                throw new YAMPArgumentInvalidException("Linfit", "f", 3);
            }

            var M = f;
            var b = new MatrixValue(x.Length, 1);

            for (var j = 1; j <= M.Rows; j++)
            {
                b[j, 1] = y[j];
            }

            var qr = QRDecomposition.Create(M);

            return(qr.Solve(b));
        }
示例#8
0
        public void QRDecomposition()
        {
            GeneralMatrix A = new GeneralMatrix(columnwise, 4);

            QRDecomposition QR = A.QRD();
            GeneralMatrix   R  = QR.R;

            Assert.IsTrue(GeneralTests.Check(A, QR.Q.Multiply(R)));
        }
示例#9
0
        public void MatrixQRDecomposition1()
        {
            double[] columnwise = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0 };

            Matrix          b  = new Matrix(columnwise, 4);
            QRDecomposition qr = b.QRDecomposition;
            Matrix          r  = qr.R;

            Assert.That(qr.Q * r, NumericIs.AlmostEqualTo(b), "QRDecomposition");
        }
        public static Object Qr(Double[,] matrix)
        {
            var qr = QRDecomposition.Create(matrix);

            return(ObjectHelpers.CreateObject(
                       "q", qr.Q,
                       "r", qr.R,
                       "full", qr.HasFullRank
                       ));
        }
示例#11
0
        private QFactorResult calculateLeastSquareLorenz()
        {
            int          i, j = 0;
            int          f0_index;
            PointPairInt range;
            int          n;

            // Preprocessing (removing data points which are far away from transmittance peak)
            f0_index = findCenterFrequencyIndex();
            if (f0_index < 0 || f0_index > pointList.Count)
            {
                return(new QFactorResult());   // return "no result" if center frequency not found.
            }
            range = findBandwidthIndexes(f0_index, 3.0F);
            if (range.I0 == int.MaxValue)
            {
                return(new QFactorResult());   // return "no result" if center frequency not found.
            }
            n = range.I1 - range.I0;
            if (n < 5)
            {       // When we have very small amount of points, turn off Q-calculations completely - we don't want to have useless results!
                    // We need to return the center frequency which is already found.
                return(new QFactorResult(pointList[f0_index].frequency, n));
            }

            GeneralMatrix X = new GeneralMatrix(n, 3);  // vandermonde matrix with measured frequency points
            GeneralMatrix Y = new GeneralMatrix(n, 3);  // vector with measured power levels

            for (i = 0; i < pointList.Count; i++)
            {
                if (i > range.I0 && i <= range.I1)
                {
                    X.SetElement(j, 0, Math.Pow(pointList[i].frequency, 2));
                    X.SetElement(j, 1, pointList[i].frequency);
                    X.SetElement(j, 2, 1);
                    Y.SetElement(j, 0, Math.Pow(10, -pointList[i].gain / 10));   // measured power is converted to linear form and inverted (1/x)
                    j++;
                }
            }
            QRDecomposition QR   = new QRDecomposition(X);
            GeneralMatrix   beta = QR.Solve(Y);             // Linear regression used to find beta coefficients

            double A = beta.GetElement(0, 0);
            double B = beta.GetElement(1, 0);
            double C = beta.GetElement(2, 0);

            double F0 = -B / (2 * A);
            double Q  = -B / (2 * Math.Sqrt(4 * A * C - B * B));
            double P0 = -1 / ((B * B) / (4 * A) - C);

            P0 = 10 * Math.Log10(P0);

            //return new QFactorResult(Q, F0, F0 - 0.5 * F0 / Q, F0 + 0.5 * F0 / Q, P0-3, P0-3);
            return(new QFactorResult(Q, F0, P0, F0 / Q, n));
        }
示例#12
0
        public double[] Solve(
            SparseMatrix A,
            double[] b)
        {
            QRDecomposition decomposition = Householder(A);

            var Qt = Transpose(decomposition.Q);
            var Qb = Multiply(Qt, b);

            return(BackwardSubstitution(decomposition.R, Qb));
        }
示例#13
0
        public static void run()
        {
            int    row1 = 4, col1 = 3;
            Matrix A1 = Matrix.Random(row1, col1);
            //QRDecomposition qrd1 = new QRDecomposition(A1);
            QRDecomposition qrd1 = A1.QRDecomposition;

            Console.WriteLine("Full-rank matrix = {0}", qrd1.IsFullRank);
            Console.WriteLine("Q matrix = {0}", qrd1.Q.ToString());
            Console.WriteLine("R matrix = {0}", qrd1.R.ToString());
        }
示例#14
0
        public void QRDecompositionComputeTest()
        {
            for (Int32 matrixIndex = 0; matrixIndex < this.matrices.Length; matrixIndex++)
            {
                QRDecomposition decomposition = new QRDecomposition(this.matrices[matrixIndex]);
                decomposition.Compute();

                decomposition.Q.ShouldBe(this.expectedQ[matrixIndex], 0.001);
                decomposition.R.ShouldBe(this.expectedR[matrixIndex], 0.001);

                Matrix product = decomposition.Q * decomposition.R;
                product.ShouldBe(this.matrices[matrixIndex], 0.001);
            }
        }
示例#15
0
        public void When_Decompose_With_QR()
        {
            Matrix matrix = new double[][]
            {
                new double[] { 1, 2, 2, 6, 4 },
                new double[] { 5, 4, 8, 9, 7 },
                new double[] { 5, 3, 9, 7, 8 },
                new double[] { 2, 1, 1, 5, 5 },
                new double[] { 2, 4, 7, 7, 9 }
            };
            var result = QRDecomposition.Decompose(matrix);

            Assert.Equal(2.5567, System.Math.Round(result.R.GetValue(4, 4).GetNumber(), 4));
            Assert.Equal(2.2847, System.Math.Round(result.R.GetValue(3, 4).GetNumber(), 4));
            Assert.Equal(-0.4053, System.Math.Round(result.R.GetValue(2, 4).GetNumber(), 4));
            Assert.Equal(5.3878, System.Math.Round(result.R.GetValue(1, 4).GetNumber(), 4));
            Assert.Equal(13.9302, System.Math.Round(result.R.GetValue(0, 4).GetNumber(), 4));
        }
示例#16
0
        public void Simple()
        {
            var decomposition = new QRDecomposition(GetMatrix());

            var matrixR = decomposition.RightFactorMatrix;

            Assert.AreEqual(matrixR[0, 0], -14d, 0.0000001);
            Assert.AreEqual(matrixR[0, 1], -21d, 0.0000001);
            Assert.AreEqual(matrixR[0, 2], 24.571428571428569d, 0.0000001);

            Assert.AreEqual(matrixR[1, 0], 0d, 0.0000001);
            Assert.AreEqual(matrixR[1, 1], -175d, 0.0000001);
            Assert.AreEqual(matrixR[1, 2], 63.657142857142844d, 0.0000001);

            Assert.AreEqual(matrixR[2, 0], 0d, 0.0000001);
            Assert.AreEqual(matrixR[2, 1], 0d, 0.0000001);
            Assert.AreEqual(matrixR[2, 2], 0.11428571428571477d, 0.0000001);
        }
示例#17
0
文件: Q.cs 项目: vh-vahan/ngenerics
        public void Simple()
        {
            var decomposition = new QRDecomposition(GetMatrix());

            var matrixQ = decomposition.LeftFactorMatrix;


            Assert.AreEqual(matrixQ[0, 0], -6d / 7d, 0.0000001);
            Assert.AreEqual(matrixQ[0, 1], 69d / 175d, 0.0000001);
            Assert.AreEqual(matrixQ[0, 2], -58d / 175d, 0.0000001);

            Assert.AreEqual(matrixQ[1, 0], -3d / 7d, 0.0000001);
            Assert.AreEqual(matrixQ[1, 1], -158d / 175d, 0.0000001);
            Assert.AreEqual(matrixQ[1, 2], 6d / 175d, 0.0000001);

            Assert.AreEqual(matrixQ[2, 0], 2d / 7d, 0.0000001);
            Assert.AreEqual(matrixQ[2, 1], -6d / 35d, 0.0000001);
            Assert.AreEqual(matrixQ[2, 2], -33d / 35d, 0.0000001);
        }
示例#18
0
        public static void Main2(string[] argv)
        {
            print("\n    Test of Matrix Class, using magic squares.\n");
            print("    See MagicSquareExample.main() for an explanation.\n");
            print("\n      n     trace       max_eig   rank        cond      lu_res      qr_res\n\n");
            DateTime now = DateTime.Now;
            double   num = Math.Pow(2.0, -52.0);

            for (int i = 3; i <= 32; i++)
            {
                print(fixedWidthIntegertoString(i, 7));
                JamaMatrix jamaMatrix = magic(i);
                int        n          = (int)jamaMatrix.trace();
                print(fixedWidthIntegertoString(n, 10));
                EigenvalueDecomposition eigenvalueDecomposition =
                    new EigenvalueDecomposition(jamaMatrix.plus(jamaMatrix.transpose()).times(0.5));
                double[] realEigenvalues = eigenvalueDecomposition.RealEigenvalues;
                print(fixedWidthDoubletoString(realEigenvalues[i - 1], 14, 3));
                int n2 = jamaMatrix.rank();
                print(fixedWidthIntegertoString(n2, 7));
                double num2 = jamaMatrix.cond();
                print(num2 < 1.0 / num ? fixedWidthDoubletoString(num2, 12, 3) : "         Inf");
                LUDecomposition lUDecomposition = new LUDecomposition(jamaMatrix);
                JamaMatrix      l           = lUDecomposition.L;
                JamaMatrix      u           = lUDecomposition.U;
                int[]           pivot       = lUDecomposition.Pivot;
                JamaMatrix      jamaMatrix2 = l.times(u).minus(jamaMatrix.getMatrix(pivot, 0, i - 1));
                double          x           = jamaMatrix2.norm1() / (i * num);
                print(fixedWidthDoubletoString(x, 12, 3));
                QRDecomposition qRDecomposition = new QRDecomposition(jamaMatrix);
                JamaMatrix      q = qRDecomposition.Q;
                jamaMatrix2 = qRDecomposition.R;
                jamaMatrix2 = q.times(jamaMatrix2).minus(jamaMatrix);
                x           = jamaMatrix2.norm1() / (i * num);
                print(fixedWidthDoubletoString(x, 12, 3));
                print("\n");
            }

            double x2 = (DateTime.Now.Ticks - now.Ticks) / 1000.0;

            print("\nElapsed Time = " + fixedWidthDoubletoString(x2, 12, 3) + " seconds\n");
            print("Adios\n");
        }
示例#19
0
        public void ExceptionDifferentRowCount()
        {
            var matrixA = new Matrix(2, 2);

            matrixA[0, 0] = 0;
            matrixA[0, 1] = 0;
            matrixA[1, 0] = 1;
            matrixA[1, 1] = 0;

            var matrixB = new Matrix(2, 2);

            matrixB[0, 0] = 0;
            matrixB[0, 1] = 0;
            matrixB[1, 0] = 0;
            matrixB[1, 1] = 1;

            var qrDecomposition = new QRDecomposition(matrixA);

            qrDecomposition.Solve(matrixB);
        }
示例#20
0
        public void ExceptionDifferentRowCount()
        {
            var matrixA = new Matrix(2, 2);

            matrixA[0, 0] = 0;
            matrixA[0, 1] = 0;
            matrixA[1, 0] = 1;
            matrixA[1, 1] = 0;

            var matrixB = new Matrix(2, 2);

            matrixB[0, 0] = 0;
            matrixB[0, 1] = 0;
            matrixB[1, 0] = 0;
            matrixB[1, 1] = 1;

            var qrDecomposition = new QRDecomposition(matrixA);

            Assert.Throws <ArgumentException>(() => qrDecomposition.Solve(matrixB));
        }
        public static Double[,] Inverse(Double[,] matrix)
        {
            var rows   = matrix.GetLength(0);
            var cols   = matrix.GetLength(1);
            var target = Helpers.One(cols);

            if (cols < 24)
            {
                var lu = new LUDecomposition(matrix);
                return(lu.Solve(target));
            }
            else if (Helpers.IsSymmetric(matrix))
            {
                var cho = new CholeskyDecomposition(matrix);
                return(cho.Solve(target));
            }
            else
            {
                var qr = QRDecomposition.Create(matrix);
                return(qr.Solve(target));
            }
        }
示例#22
0
        public void ExceptionRankDeficient()
        {
            var matrixA = new Matrix(3, 2);

            matrixA[0, 0] = 1;
            matrixA[0, 1] = 2;
            matrixA[1, 0] = 3;
            matrixA[1, 1] = 4;
            matrixA[2, 0] = 4;
            matrixA[2, 1] = 2;

            var matrixB = new Matrix(2, 2);

            matrixB[0, 0] = 0;
            matrixB[0, 1] = 0;
            matrixB[1, 0] = 0;
            matrixB[1, 1] = 1;

            var qrDecomposition = new QRDecomposition(matrixA);

            Assert.Throws <ArgumentException>(() => qrDecomposition.Solve(matrixB));
        }
示例#23
0
        public void ExceptionRankDeficient()
        {
            var matrixA = new Matrix(3, 2);

            matrixA[0, 0] = 1;
            matrixA[0, 1] = 2;
            matrixA[1, 0] = 3;
            matrixA[1, 1] = 4;
            matrixA[2, 0] = 4;
            matrixA[2, 1] = 2;

            var matrixB = new Matrix(2, 2);

            matrixB[0, 0] = 0;
            matrixB[0, 1] = 0;
            matrixB[1, 0] = 0;
            matrixB[1, 1] = 1;

            var qrDecomposition = new QRDecomposition(matrixA);

            qrDecomposition.Solve(matrixB);
        }
示例#24
0
        public void RectangularQRDecomposition()
        {
            RectangularMatrix M = GenerateRandomMatrix(30, 10);

            QRDecomposition QRD = M.QRDecomposition();

            Assert.IsTrue(QRD.RowCount == M.RowCount);
            Assert.IsTrue(QRD.ColumnCount == M.ColumnCount);

            SquareMatrix Q = QRD.QMatrix;

            Assert.IsTrue(Q.Dimension == M.RowCount);
            Assert.IsTrue(TestUtilities.IsNearlyEqual(Q * Q.Transpose, UnitMatrix.OfDimension(Q.Dimension)));

            RectangularMatrix R = QRD.RMatrix;

            Assert.IsTrue(R.RowCount == M.RowCount);
            Assert.IsTrue(R.ColumnCount == M.ColumnCount);

            RectangularMatrix QR = Q * R;

            Assert.IsTrue(TestUtilities.IsNearlyEqual(QR, M));
        }
示例#25
0
        public MatrixValue Function(MatrixValue x, MatrixValue y, ScalarValue n)
        {
            if (x.Length != y.Length)
            {
                throw new YAMPDifferentLengthsException(x.Length, y.Length);
            }

            var nn = n.GetIntegerOrThrowException("n", Name);
            var m  = nn + 1;

            if (m < 2)
            {
                throw new YAMPArgumentRangeException("n", 0.0);
            }

            var M = new MatrixValue(x.Length, m);
            var b = new MatrixValue(x.Length, 1);

            for (var j = 1; j <= M.Rows; j++)
            {
                var el = ScalarValue.One;
                var z  = x[j];

                for (var i = 1; i <= M.Columns; i++)
                {
                    M[j, i] = el;
                    el     *= z;
                }

                b[j, 1] = y[j];
            }

            var qr = QRDecomposition.Create(M);

            return(qr.Solve(b));
        }
示例#26
0
        public void Simple()
        {
            var matrixA = new Matrix(3, 2);

            matrixA[0, 0] = 1;
            matrixA[0, 1] = 2;

            matrixA[1, 0] = 3;
            matrixA[1, 1] = 4;

            matrixA[2, 0] = 4;
            matrixA[2, 1] = 2;

            var matrixB = new Matrix(3, 2);

            matrixB[0, 0] = 3;
            matrixB[0, 1] = 4;

            matrixB[1, 0] = 4;
            matrixB[1, 1] = 2;

            matrixB[2, 0] = 1;
            matrixB[2, 1] = 2;

            var decomposition = new QRDecomposition(matrixA);
            var solveMatrix   = decomposition.Solve(matrixB);

            Assert.AreEqual(solveMatrix.Rows, 2);
            Assert.AreEqual(solveMatrix.Columns, 2);

            Assert.AreEqual(solveMatrix[0, 0], -0.514285714, 0.00000001);
            Assert.AreEqual(solveMatrix[0, 1], -0.057142857, 0.00000001);

            Assert.AreEqual(solveMatrix[1, 0], 1.4714285714, 0.00000001);
            Assert.AreEqual(solveMatrix[1, 1], 0.8857142857, 0.00000001);
        }
示例#27
0
		public static void Main(string[] argv)
		{
			MagicSquareExample.print("\n    Test of Matrix Class, using magic squares.\n");
			MagicSquareExample.print("    See MagicSquareExample.main() for an explanation.\n");
			MagicSquareExample.print("\n      n     trace       max_eig   rank        cond      lu_res      qr_res\n\n");
			DateTime now = DateTime.Now;
			double num = Math.Pow(2.0, -52.0);
			for (int i = 3; i <= 32; i++)
			{
				MagicSquareExample.print(MagicSquareExample.fixedWidthIntegertoString(i, 7));
				JamaMatrix jamaMatrix = MagicSquareExample.magic(i);
				int n = (int)jamaMatrix.trace();
				MagicSquareExample.print(MagicSquareExample.fixedWidthIntegertoString(n, 10));
				EigenvalueDecomposition eigenvalueDecomposition = new EigenvalueDecomposition(jamaMatrix.plus(jamaMatrix.transpose()).times(0.5));
				double[] realEigenvalues = eigenvalueDecomposition.RealEigenvalues;
				MagicSquareExample.print(MagicSquareExample.fixedWidthDoubletoString(realEigenvalues[i - 1], 14, 3));
				int n2 = jamaMatrix.rank();
				MagicSquareExample.print(MagicSquareExample.fixedWidthIntegertoString(n2, 7));
				double num2 = jamaMatrix.cond();
				MagicSquareExample.print((num2 < 1.0 / num) ? MagicSquareExample.fixedWidthDoubletoString(num2, 12, 3) : "         Inf");
				LUDecomposition lUDecomposition = new LUDecomposition(jamaMatrix);
				JamaMatrix l = lUDecomposition.L;
				JamaMatrix u = lUDecomposition.U;
				int[] pivot = lUDecomposition.Pivot;
				JamaMatrix jamaMatrix2 = l.times(u).minus(jamaMatrix.getMatrix(pivot, 0, i - 1));
				double x = jamaMatrix2.norm1() / ((double)i * num);
				MagicSquareExample.print(MagicSquareExample.fixedWidthDoubletoString(x, 12, 3));
				QRDecomposition qRDecomposition = new QRDecomposition(jamaMatrix);
				JamaMatrix q = qRDecomposition.Q;
				jamaMatrix2 = qRDecomposition.R;
				jamaMatrix2 = q.times(jamaMatrix2).minus(jamaMatrix);
				x = jamaMatrix2.norm1() / ((double)i * num);
				MagicSquareExample.print(MagicSquareExample.fixedWidthDoubletoString(x, 12, 3));
				MagicSquareExample.print("\n");
			}
			double x2 = (double)(DateTime.Now.Ticks - now.Ticks) / 1000.0;
			MagicSquareExample.print("\nElapsed Time = " + MagicSquareExample.fixedWidthDoubletoString(x2, 12, 3) + " seconds\n");
			MagicSquareExample.print("Adios\n");
		}
示例#28
0
文件: Matrix.cs 项目: cvereker/Demo
 /// <summary>
 /// Indexer For a Vector Matrix. i is the row number.
 /// </summary>
 public virtual double this[int iRow]
 {
     get
     {
         return this._MatrixData[iRow, 0];
     }
     set
     {
         this._MatrixData[iRow, 0] = value;
         this.LUDecomp = null;
         this.QRDecomp = null;
         this.EigenDecomp = null;
     }
 }
示例#29
0
文件: Matrix.cs 项目: cvereker/Demo
 /// <summary>
 /// Solve A Linear System
 /// </summary>
 /// <param name="rhs"></param>
 /// <returns></returns>
 public Matrix Solve(Matrix rhs)
 {
     if (this.Width != this.Height)
     {
         if (QRDecomp == null) QRDecomp = new QRDecomposition(this);
         return QRDecomp.Solve(rhs);
     }
     else
     {
         if (LUDecomp == null) LUDecomp = new LUDecomposition(this);
         return LUDecomp.Solve(rhs);
     }
 }
示例#30
0
        public static void  Main(System.String[] argv)
        {
            /*
             | Tests LU, QR, SVD and symmetric Eig decompositions.
             |
             |   n       = order of magic square.
             |   trace   = diagonal sum, should be the magic sum, (n^3 + n)/2.
             |   max_eig = maximum eigenvalue of (A + A')/2, should equal trace.
             |   rank    = linear algebraic rank,
             |             should equal n if n is odd, be less than n if n is even.
             |   cond    = L_2 condition number, ratio of singular values.
             |   lu_res  = test of LU factorization, norm1(L*U-A(p,:))/(n*eps).
             |   qr_res  = test of QR factorization, norm1(Q*R-A)/(n*eps).
             */

            print("\n    Test of GeneralMatrix Class, using magic squares.\n");
            print("    See MagicSquareExample.main() for an explanation.\n");
            print("\n      n     trace       max_eig   rank        cond      lu_res      qr_res\n\n");

            System.DateTime start_time = System.DateTime.Now;
            double          eps        = System.Math.Pow(2.0, -52.0);

            for (int n = 3; n <= 32; n++)
            {
                print(fixedWidthIntegertoString(n, 7));

                GeneralMatrix M = magic(n);

                //UPGRADE_WARNING: Narrowing conversions may produce unexpected results in C#. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1042"'
                int t = (int)M.Trace();
                print(fixedWidthIntegertoString(t, 10));

                EigenvalueDecomposition E = new EigenvalueDecomposition(M.Add(M.Transpose()).Multiply(0.5));
                double[] d = E.RealEigenvalues;
                print(fixedWidthDoubletoString(d[n - 1], 14, 3));

                int r = M.Rank();
                print(fixedWidthIntegertoString(r, 7));

                double c = M.Condition();
                print(c < 1 / eps ? fixedWidthDoubletoString(c, 12, 3):"         Inf");

                LUDecomposition LU  = new LUDecomposition(M);
                GeneralMatrix   L   = LU.L;
                GeneralMatrix   U   = LU.U;
                int[]           p   = LU.Pivot;
                GeneralMatrix   R   = L.Multiply(U).Subtract(M.GetMatrix(p, 0, n - 1));
                double          res = R.Norm1() / (n * eps);
                print(fixedWidthDoubletoString(res, 12, 3));

                QRDecomposition QR = new QRDecomposition(M);
                GeneralMatrix   Q  = QR.Q;
                R   = QR.R;
                R   = Q.Multiply(R).Subtract(M);
                res = R.Norm1() / (n * eps);
                print(fixedWidthDoubletoString(res, 12, 3));

                print("\n");
            }

            System.DateTime stop_time = System.DateTime.Now;
            double          etime     = (stop_time.Ticks - start_time.Ticks) / 1000.0;

            print("\nElapsed Time = " + fixedWidthDoubletoString(etime, 12, 3) + " seconds\n");
            print("Adios\n");
        }
        internal MultiLinearRegressionResult(IReadOnlyList <double> yColumn, IReadOnlyList <IReadOnlyList <double> > xColumns, IReadOnlyList <string> xNames) : base()
        {
            Debug.Assert(yColumn != null);
            Debug.Assert(xColumns != null);
            Debug.Assert(xColumns.Count > 0);
            Debug.Assert(xNames.Count == xColumns.Count);

            n = yColumn.Count;
            m = xColumns.Count;
            if (n <= m)
            {
                throw new InsufficientDataException();
            }

            // Compute the design matrix X.
            interceptIndex = -1;
            RectangularMatrix X = new RectangularMatrix(n, m);

            for (int c = 0; c < m; c++)
            {
                IReadOnlyList <double> xColumn = xColumns[c];
                if (xColumn == null)
                {
                    Debug.Assert(xNames[c] == "Intercept");
                    Debug.Assert(interceptIndex < 0);
                    for (int r = 0; r < n; r++)
                    {
                        X[r, c] = 1.0;
                    }
                    interceptIndex = c;
                }
                else
                {
                    Debug.Assert(xNames[c] != null);
                    if (xColumn.Count != n)
                    {
                        throw new DimensionMismatchException();
                    }
                    for (int r = 0; r < n; r++)
                    {
                        X[r, c] = xColumn[r];
                    }
                }
            }
            Debug.Assert(interceptIndex >= 0);
            ColumnVector v = new ColumnVector(yColumn);

            // Use X = QR to solve X b = y and compute C.
            QRDecomposition.SolveLinearSystem(X, v, out b, out C);

            // For ANOVA, we will need mean and variance of y
            int    yn;
            double ym;

            Univariate.ComputeMomentsUpToSecond(yColumn, out yn, out ym, out SST);

            // Compute residuals
            SSR = 0.0;
            SSF = 0.0;
            ColumnVector yHat = X * b;

            residuals = new List <double>(n);
            for (int i = 0; i < n; i++)
            {
                double z = yColumn[i] - yHat[i];
                residuals.Add(z);
                SSR += z * z;
                SSF += MoreMath.Sqr(yHat[i] - ym);
            }
            sigma2 = SSR / (n - m);

            // Scale up C by \sigma^2
            // (It sure would be great to be able to overload *=.)
            for (int i = 0; i < m; i++)
            {
                for (int j = i; j < m; j++)
                {
                    C[i, j] = C[i, j] * sigma2;
                }
            }

            names = xNames;
        }
示例#32
0
 /**
  * Creates a linear solver that uses QR decomposition.
  *
  */
 public LinearSolverQr_ZDRM(QRDecomposition <ZMatrixRMaj> decomposer)
 {
     this.decomposer = decomposer;
 }
        /// <summary>
        /// Fits the data to a linear combination of fit functions.
        /// </summary>
        /// <param name="functions">The component functions.</param>
        /// <returns>A fit result containing the best-fit coefficients of the component functions and a &#x3C7;<sup>2</sup> test
        /// of the quality of the fit.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="functions"/> is null.</exception>
        /// <exception cref="InsufficientDataException">There are fewer data points than fit parameters.</exception>
        public FitResult FitToLinearFunction(Func <T, double>[] functions)
        {
            if (functions == null)
            {
                throw new ArgumentNullException(nameof(functions));
            }
            if (functions.Length > data.Count)
            {
                throw new InsufficientDataException();
            }

            // construct the design matrix
            RectangularMatrix A = new RectangularMatrix(data.Count, functions.Length);

            for (int r = 0; r < data.Count; r++)
            {
                for (int c = 0; c < functions.Length; c++)
                {
                    A[r, c] = functions[c](data[r].X) / data[r].Y.Uncertainty;
                }
            }

            // construct the right-hand-side
            ColumnVector b = new ColumnVector(data.Count);

            for (int r = 0; r < data.Count; r++)
            {
                b[r] = data[r].Y.Value / data[r].Y.Uncertainty;
            }

            // Solve the system via QR
            ColumnVector    a;
            SymmetricMatrix C;

            QRDecomposition.SolveLinearSystem(A, b, out a, out C);

            /*
             * // construct the data matrix
             * SymmetricMatrix A = new SymmetricMatrix(functions.Length);
             * for (int i = 0; i < A.Dimension; i++) {
             *  for (int j = 0; j <= i; j++) {
             *      double Aij = 0.0;
             *      for (int k = 0; k < data.Count; k++) {
             *          Aij += functions[i](data[k].X) * functions[j](data[k].X) / Math.Pow(data[k].Y.Uncertainty, 2);
             *      }
             *      A[i, j] = Aij;
             *  }
             * }
             *
             * // construct the rhs
             * double[] b = new double[functions.Length];
             * for (int i = 0; i < b.Length; i++) {
             *  b[i] = 0.0;
             *  for (int j = 0; j < data.Count; j++) {
             *      b[i] += data[j].Y.Value * functions[i](data[j].X) / Math.Pow(data[j].Y.Uncertainty, 2);
             *  }
             * }
             *
             * // solve the system
             * CholeskyDecomposition CD = A.CholeskyDecomposition();
             * if (CD == null) throw new InvalidOperationException();
             * Debug.Assert(CD != null);
             * SymmetricMatrix C = CD.Inverse();
             * ColumnVector a = CD.Solve(b);
             */

            // do a chi^2 test
            double chi2 = 0.0;

            for (int i = 0; i < data.Count; i++)
            {
                double f = 0.0;
                for (int j = 0; j < functions.Length; j++)
                {
                    f += functions[j](data[i].X) * a[j];
                }
                chi2 += Math.Pow((data[i].Y.Value - f) / data[i].Y.Uncertainty, 2);
            }
            TestResult test = new TestResult("ChiSquare", chi2, TestType.RightTailed, new ChiSquaredDistribution(data.Count - functions.Length));

            // return the results
            FitResult fit = new FitResult(a, C, test);

            return(fit);
        }