QRDecomposition.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      https://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. /*
  18.  * This is not the original file distributed by the Apache Software Foundation
  19.  * It has been modified by the Hipparchus project
  20.  */

  21. package org.hipparchus.linear;

  22. import java.util.Arrays;

  23. import org.hipparchus.exception.LocalizedCoreFormats;
  24. import org.hipparchus.exception.MathIllegalArgumentException;
  25. import org.hipparchus.util.FastMath;


  26. /**
  27.  * Calculates the QR-decomposition of a matrix.
  28.  * <p>The QR-decomposition of a matrix A consists of two matrices Q and R
  29.  * that satisfy: A = QR, Q is orthogonal (Q<sup>T</sup>Q = I), and R is
  30.  * upper triangular. If A is m&times;n, Q is m&times;m and R m&times;n.</p>
  31.  * <p>This class compute the decomposition using Householder reflectors.</p>
  32.  * <p>For efficiency purposes, the decomposition in packed form is transposed.
  33.  * This allows inner loop to iterate inside rows, which is much more cache-efficient
  34.  * in Java.</p>
  35.  * <p>This class is based on the class with similar name from the
  36.  * <a href="http://math.nist.gov/javanumerics/jama/">JAMA</a> library, with the
  37.  * following changes:</p>
  38.  * <ul>
  39.  *   <li>a {@link #getQT() getQT} method has been added,</li>
  40.  *   <li>the {@code solve} and {@code isFullRank} methods have been replaced
  41.  *   by a {@link #getSolver() getSolver} method and the equivalent methods
  42.  *   provided by the returned {@link DecompositionSolver}.</li>
  43.  * </ul>
  44.  *
  45.  * @see <a href="http://mathworld.wolfram.com/QRDecomposition.html">MathWorld</a>
  46.  * @see <a href="http://en.wikipedia.org/wiki/QR_decomposition">Wikipedia</a>
  47.  *
  48.  */
  49. public class QRDecomposition {
  50.     /**
  51.      * A packed TRANSPOSED representation of the QR decomposition.
  52.      * <p>The elements BELOW the diagonal are the elements of the UPPER triangular
  53.      * matrix R, and the rows ABOVE the diagonal are the Householder reflector vectors
  54.      * from which an explicit form of Q can be recomputed if desired.</p>
  55.      */
  56.     private double[][] qrt;
  57.     /** The diagonal elements of R. */
  58.     private double[] rDiag;
  59.     /** Cached value of Q. */
  60.     private RealMatrix cachedQ;
  61.     /** Cached value of QT. */
  62.     private RealMatrix cachedQT;
  63.     /** Cached value of R. */
  64.     private RealMatrix cachedR;
  65.     /** Cached value of H. */
  66.     private RealMatrix cachedH;
  67.     /** Singularity threshold. */
  68.     private final double threshold;

  69.     /**
  70.      * Calculates the QR-decomposition of the given matrix.
  71.      * The singularity threshold defaults to zero.
  72.      *
  73.      * @param matrix The matrix to decompose.
  74.      *
  75.      * @see #QRDecomposition(RealMatrix,double)
  76.      */
  77.     public QRDecomposition(RealMatrix matrix) {
  78.         this(matrix, 0d);
  79.     }

  80.     /**
  81.      * Calculates the QR-decomposition of the given matrix.
  82.      *
  83.      * @param matrix The matrix to decompose.
  84.      * @param threshold Singularity threshold.
  85.      */
  86.     public QRDecomposition(RealMatrix matrix,
  87.                            double threshold) {
  88.         this.threshold = threshold;

  89.         final int m = matrix.getRowDimension();
  90.         final int n = matrix.getColumnDimension();
  91.         qrt = matrix.transpose().getData();
  92.         rDiag = new double[FastMath.min(m, n)];
  93.         cachedQ  = null;
  94.         cachedQT = null;
  95.         cachedR  = null;
  96.         cachedH  = null;

  97.         decompose(qrt);

  98.     }

  99.     /** Decompose matrix.
  100.      * @param matrix transposed matrix
  101.      */
  102.     protected void decompose(double[][] matrix) {
  103.         for (int minor = 0; minor < FastMath.min(matrix.length, matrix[0].length); minor++) {
  104.             performHouseholderReflection(minor, matrix);
  105.         }
  106.     }

  107.     /** Perform Householder reflection for a minor A(minor, minor) of A.
  108.      * @param minor minor index
  109.      * @param matrix transposed matrix
  110.      */
  111.     protected void performHouseholderReflection(int minor, double[][] matrix) {

  112.         final double[] qrtMinor = matrix[minor];

  113.         /*
  114.          * Let x be the first column of the minor, and a^2 = |x|^2.
  115.          * x will be in the positions qr[minor][minor] through qr[m][minor].
  116.          * The first column of the transformed minor will be (a,0,0,..)'
  117.          * The sign of a is chosen to be opposite to the sign of the first
  118.          * component of x. Let's find a:
  119.          */
  120.         double xNormSqr = 0;
  121.         for (int row = minor; row < qrtMinor.length; row++) {
  122.             final double c = qrtMinor[row];
  123.             xNormSqr += c * c;
  124.         }
  125.         final double a = (qrtMinor[minor] > 0) ? -FastMath.sqrt(xNormSqr) : FastMath.sqrt(xNormSqr);
  126.         rDiag[minor] = a;

  127.         if (a != 0.0) {

  128.             /*
  129.              * Calculate the normalized reflection vector v and transform
  130.              * the first column. We know the norm of v beforehand: v = x-ae
  131.              * so |v|^2 = <x-ae,x-ae> = <x,x>-2a<x,e>+a^2<e,e> =
  132.              * a^2+a^2-2a<x,e> = 2a*(a - <x,e>).
  133.              * Here <x, e> is now qr[minor][minor].
  134.              * v = x-ae is stored in the column at qr:
  135.              */
  136.             qrtMinor[minor] -= a; // now |v|^2 = -2a*(qr[minor][minor])

  137.             /*
  138.              * Transform the rest of the columns of the minor:
  139.              * They will be transformed by the matrix H = I-2vv'/|v|^2.
  140.              * If x is a column vector of the minor, then
  141.              * Hx = (I-2vv'/|v|^2)x = x-2vv'x/|v|^2 = x - 2<x,v>/|v|^2 v.
  142.              * Therefore the transformation is easily calculated by
  143.              * subtracting the column vector (2<x,v>/|v|^2)v from x.
  144.              *
  145.              * Let 2<x,v>/|v|^2 = alpha. From above we have
  146.              * |v|^2 = -2a*(qr[minor][minor]), so
  147.              * alpha = -<x,v>/(a*qr[minor][minor])
  148.              */
  149.             for (int col = minor+1; col < matrix.length; col++) {
  150.                 final double[] qrtCol = matrix[col];
  151.                 double alpha = 0;
  152.                 for (int row = minor; row < qrtCol.length; row++) {
  153.                     alpha -= qrtCol[row] * qrtMinor[row];
  154.                 }
  155.                 alpha /= a * qrtMinor[minor];

  156.                 // Subtract the column vector alpha*v from x.
  157.                 for (int row = minor; row < qrtCol.length; row++) {
  158.                     qrtCol[row] -= alpha * qrtMinor[row];
  159.                 }
  160.             }
  161.         }
  162.     }


  163.     /**
  164.      * Returns the matrix R of the decomposition.
  165.      * <p>R is an upper-triangular matrix</p>
  166.      * @return the R matrix
  167.      */
  168.     public RealMatrix getR() {

  169.         if (cachedR == null) {

  170.             // R is supposed to be m x n
  171.             final int n = qrt.length;
  172.             final int m = qrt[0].length;
  173.             double[][] ra = new double[m][n];
  174.             // copy the diagonal from rDiag and the upper triangle of qr
  175.             for (int row = FastMath.min(m, n) - 1; row >= 0; row--) {
  176.                 ra[row][row] = rDiag[row];
  177.                 for (int col = row + 1; col < n; col++) {
  178.                     ra[row][col] = qrt[col][row];
  179.                 }
  180.             }
  181.             cachedR = MatrixUtils.createRealMatrix(ra);
  182.         }

  183.         // return the cached matrix
  184.         return cachedR;
  185.     }

  186.     /**
  187.      * Returns the matrix Q of the decomposition.
  188.      * <p>Q is an orthogonal matrix</p>
  189.      * @return the Q matrix
  190.      */
  191.     public RealMatrix getQ() {
  192.         if (cachedQ == null) {
  193.             cachedQ = getQT().transpose();
  194.         }
  195.         return cachedQ;
  196.     }

  197.     /**
  198.      * Returns the transpose of the matrix Q of the decomposition.
  199.      * <p>Q is an orthogonal matrix</p>
  200.      * @return the transpose of the Q matrix, Q<sup>T</sup>
  201.      */
  202.     public RealMatrix getQT() {
  203.         if (cachedQT == null) {

  204.             // QT is supposed to be m x m
  205.             final int n = qrt.length;
  206.             final int m = qrt[0].length;
  207.             double[][] qta = new double[m][m];

  208.             /*
  209.              * Q = Q1 Q2 ... Q_m, so Q is formed by first constructing Q_m and then
  210.              * applying the Householder transformations Q_(m-1),Q_(m-2),...,Q1 in
  211.              * succession to the result
  212.              */
  213.             for (int minor = m - 1; minor >= FastMath.min(m, n); minor--) {
  214.                 qta[minor][minor] = 1.0d;
  215.             }

  216.             for (int minor = FastMath.min(m, n)-1; minor >= 0; minor--){
  217.                 final double[] qrtMinor = qrt[minor];
  218.                 qta[minor][minor] = 1.0d;
  219.                 if (qrtMinor[minor] != 0.0) {
  220.                     for (int col = minor; col < m; col++) {
  221.                         double alpha = 0;
  222.                         for (int row = minor; row < m; row++) {
  223.                             alpha -= qta[col][row] * qrtMinor[row];
  224.                         }
  225.                         alpha /= rDiag[minor] * qrtMinor[minor];

  226.                         for (int row = minor; row < m; row++) {
  227.                             qta[col][row] += -alpha * qrtMinor[row];
  228.                         }
  229.                     }
  230.                 }
  231.             }
  232.             cachedQT = MatrixUtils.createRealMatrix(qta);
  233.         }

  234.         // return the cached matrix
  235.         return cachedQT;
  236.     }

  237.     /**
  238.      * Returns the Householder reflector vectors.
  239.      * <p>H is a lower trapezoidal matrix whose columns represent
  240.      * each successive Householder reflector vector. This matrix is used
  241.      * to compute Q.</p>
  242.      * @return a matrix containing the Householder reflector vectors
  243.      */
  244.     public RealMatrix getH() {
  245.         if (cachedH == null) {

  246.             final int n = qrt.length;
  247.             final int m = qrt[0].length;
  248.             double[][] ha = new double[m][n];
  249.             for (int i = 0; i < m; ++i) {
  250.                 for (int j = 0; j < FastMath.min(i + 1, n); ++j) {
  251.                     ha[i][j] = qrt[j][i] / -rDiag[j];
  252.                 }
  253.             }
  254.             cachedH = MatrixUtils.createRealMatrix(ha);
  255.         }

  256.         // return the cached matrix
  257.         return cachedH;
  258.     }

  259.     /**
  260.      * Get a solver for finding the A &times; X = B solution in least square sense.
  261.      * <p>
  262.      * Least Square sense means a solver can be computed for an overdetermined system,
  263.      * (i.e. a system with more equations than unknowns, which corresponds to a tall A
  264.      * matrix with more rows than columns). In any case, if the matrix is singular
  265.      * within the tolerance set at {@link QRDecomposition#QRDecomposition(RealMatrix,
  266.      * double) construction}, an error will be triggered when
  267.      * the {@link DecompositionSolver#solve(RealVector) solve} method will be called.
  268.      * </p>
  269.      * @return a solver
  270.      */
  271.     public DecompositionSolver getSolver() {
  272.         return new Solver();
  273.     }

  274.     /** Specialized solver. */
  275.     private class Solver implements DecompositionSolver {

  276.         /** {@inheritDoc} */
  277.         @Override
  278.         public boolean isNonSingular() {
  279.             return !checkSingular(rDiag, threshold, false);
  280.         }

  281.         /** {@inheritDoc} */
  282.         @Override
  283.         public RealVector solve(RealVector b) {
  284.             final int n = qrt.length;
  285.             final int m = qrt[0].length;
  286.             if (b.getDimension() != m) {
  287.                 throw new MathIllegalArgumentException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
  288.                                                        b.getDimension(), m);
  289.             }
  290.             checkSingular(rDiag, threshold, true);

  291.             final double[] x = new double[n];
  292.             final double[] y = b.toArray();

  293.             // apply Householder transforms to solve Q.y = b
  294.             for (int minor = 0; minor < FastMath.min(m, n); minor++) {

  295.                 final double[] qrtMinor = qrt[minor];
  296.                 double dotProduct = 0;
  297.                 for (int row = minor; row < m; row++) {
  298.                     dotProduct += y[row] * qrtMinor[row];
  299.                 }
  300.                 dotProduct /= rDiag[minor] * qrtMinor[minor];

  301.                 for (int row = minor; row < m; row++) {
  302.                     y[row] += dotProduct * qrtMinor[row];
  303.                 }
  304.             }

  305.             // solve triangular system R.x = y
  306.             for (int row = rDiag.length - 1; row >= 0; --row) {
  307.                 y[row] /= rDiag[row];
  308.                 final double yRow = y[row];
  309.                 final double[] qrtRow = qrt[row];
  310.                 x[row] = yRow;
  311.                 for (int i = 0; i < row; i++) {
  312.                     y[i] -= yRow * qrtRow[i];
  313.                 }
  314.             }

  315.             return new ArrayRealVector(x, false);
  316.         }

  317.         /** {@inheritDoc} */
  318.         @Override
  319.         public RealMatrix solve(RealMatrix b) {
  320.             final int n = qrt.length;
  321.             final int m = qrt[0].length;
  322.             if (b.getRowDimension() != m) {
  323.                 throw new MathIllegalArgumentException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
  324.                                                        b.getRowDimension(), m);
  325.             }
  326.             checkSingular(rDiag, threshold, true);

  327.             final int columns        = b.getColumnDimension();
  328.             final int blockSize      = BlockRealMatrix.BLOCK_SIZE;
  329.             final int cBlocks        = (columns + blockSize - 1) / blockSize;
  330.             final double[][] xBlocks = BlockRealMatrix.createBlocksLayout(n, columns);
  331.             final double[][] y       = new double[b.getRowDimension()][blockSize];
  332.             final double[]   alpha   = new double[blockSize];

  333.             for (int kBlock = 0; kBlock < cBlocks; ++kBlock) {
  334.                 final int kStart = kBlock * blockSize;
  335.                 final int kEnd   = FastMath.min(kStart + blockSize, columns);
  336.                 final int kWidth = kEnd - kStart;

  337.                 // get the right hand side vector
  338.                 b.copySubMatrix(0, m - 1, kStart, kEnd - 1, y);

  339.                 // apply Householder transforms to solve Q.y = b
  340.                 for (int minor = 0; minor < FastMath.min(m, n); minor++) {
  341.                     final double[] qrtMinor = qrt[minor];
  342.                     final double factor     = 1.0 / (rDiag[minor] * qrtMinor[minor]);

  343.                     Arrays.fill(alpha, 0, kWidth, 0.0);
  344.                     for (int row = minor; row < m; ++row) {
  345.                         final double   d    = qrtMinor[row];
  346.                         final double[] yRow = y[row];
  347.                         for (int k = 0; k < kWidth; ++k) {
  348.                             alpha[k] += d * yRow[k];
  349.                         }
  350.                     }
  351.                     for (int k = 0; k < kWidth; ++k) {
  352.                         alpha[k] *= factor;
  353.                     }

  354.                     for (int row = minor; row < m; ++row) {
  355.                         final double   d    = qrtMinor[row];
  356.                         final double[] yRow = y[row];
  357.                         for (int k = 0; k < kWidth; ++k) {
  358.                             yRow[k] += alpha[k] * d;
  359.                         }
  360.                     }
  361.                 }

  362.                 // solve triangular system R.x = y
  363.                 for (int j = rDiag.length - 1; j >= 0; --j) {
  364.                     final int      jBlock = j / blockSize;
  365.                     final int      jStart = jBlock * blockSize;
  366.                     final double   factor = 1.0 / rDiag[j];
  367.                     final double[] yJ     = y[j];
  368.                     final double[] xBlock = xBlocks[jBlock * cBlocks + kBlock];
  369.                     int index = (j - jStart) * kWidth;
  370.                     for (int k = 0; k < kWidth; ++k) {
  371.                         yJ[k]          *= factor;
  372.                         xBlock[index++] = yJ[k];
  373.                     }

  374.                     final double[] qrtJ = qrt[j];
  375.                     for (int i = 0; i < j; ++i) {
  376.                         final double rIJ  = qrtJ[i];
  377.                         final double[] yI = y[i];
  378.                         for (int k = 0; k < kWidth; ++k) {
  379.                             yI[k] -= yJ[k] * rIJ;
  380.                         }
  381.                     }
  382.                 }
  383.             }

  384.             return new BlockRealMatrix(n, columns, xBlocks, false);
  385.         }

  386.         /**
  387.          * {@inheritDoc}
  388.          * @throws MathIllegalArgumentException if the decomposed matrix is singular.
  389.          */
  390.         @Override
  391.         public RealMatrix getInverse() {
  392.             return solve(MatrixUtils.createRealIdentityMatrix(qrt[0].length));
  393.         }

  394.         /**
  395.          * Check singularity.
  396.          *
  397.          * @param diag Diagonal elements of the R matrix.
  398.          * @param min Singularity threshold.
  399.          * @param raise Whether to raise a {@link MathIllegalArgumentException}
  400.          * if any element of the diagonal fails the check.
  401.          * @return {@code true} if any element of the diagonal is smaller
  402.          * or equal to {@code min}.
  403.          * @throws MathIllegalArgumentException if the matrix is singular and
  404.          * {@code raise} is {@code true}.
  405.          */
  406.         private boolean checkSingular(double[] diag, double min, boolean raise) {
  407.             for (final double d : diag) {
  408.                 if (FastMath.abs(d) <= min) {
  409.                     if (raise) {
  410.                         throw new MathIllegalArgumentException(LocalizedCoreFormats.SINGULAR_MATRIX);
  411.                     } else {
  412.                         return true;
  413.                     }
  414.                 }
  415.             }
  416.             return false;
  417.         }

  418.         /** {@inheritDoc} */
  419.         @Override
  420.         public int getRowDimension() {
  421.             return qrt[0].length;
  422.         }

  423.         /** {@inheritDoc} */
  424.         @Override
  425.         public int getColumnDimension() {
  426.             return qrt.length;
  427.         }

  428.     }
  429. }