RRQRDecomposition.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.  *      http://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. package org.apache.commons.math4.legacy.linear;

  18. import org.apache.commons.math4.core.jdkmath.JdkMath;


  19. /**
  20.  * Calculates the rank-revealing QR-decomposition of a matrix, with column pivoting.
  21.  * <p>The rank-revealing QR-decomposition of a matrix A consists of three matrices Q,
  22.  * R and P such that AP=QR.  Q is orthogonal (Q<sup>T</sup>Q = I), and R is upper triangular.
  23.  * If A is m&times;n, Q is m&times;m and R is m&times;n and P is n&times;n.</p>
  24.  * <p>QR decomposition with column pivoting produces a rank-revealing QR
  25.  * decomposition and the {@link #getRank(double)} method may be used to return the rank of the
  26.  * input matrix A.</p>
  27.  * <p>This class compute the decomposition using Householder reflectors.</p>
  28.  * <p>For efficiency purposes, the decomposition in packed form is transposed.
  29.  * This allows inner loop to iterate inside rows, which is much more cache-efficient
  30.  * in Java.</p>
  31.  * <p>This class is based on the class with similar name from the
  32.  * <a href="http://math.nist.gov/javanumerics/jama/">JAMA</a> library, with the
  33.  * following changes:</p>
  34.  * <ul>
  35.  *   <li>a {@link #getQT() getQT} method has been added,</li>
  36.  *   <li>the {@code solve} and {@code isFullRank} methods have been replaced
  37.  *   by a {@link #getSolver() getSolver} method and the equivalent methods
  38.  *   provided by the returned {@link DecompositionSolver}.</li>
  39.  * </ul>
  40.  *
  41.  * @see <a href="http://mathworld.wolfram.com/QRDecomposition.html">MathWorld</a>
  42.  * @see <a href="http://en.wikipedia.org/wiki/QR_decomposition">Wikipedia</a>
  43.  *
  44.  * @since 3.2
  45.  */
  46. public class RRQRDecomposition extends QRDecomposition {

  47.     /** An array to record the column pivoting for later creation of P. */
  48.     private int[] p;

  49.     /** Cached value of P. */
  50.     private RealMatrix cachedP;


  51.     /**
  52.      * Calculates the QR-decomposition of the given matrix.
  53.      * The singularity threshold defaults to zero.
  54.      *
  55.      * @param matrix The matrix to decompose.
  56.      *
  57.      * @see #RRQRDecomposition(RealMatrix, double)
  58.      */
  59.     public RRQRDecomposition(RealMatrix matrix) {
  60.         this(matrix, 0d);
  61.     }

  62.     /**
  63.      * Calculates the QR-decomposition of the given matrix.
  64.      *
  65.      * @param matrix The matrix to decompose.
  66.      * @param threshold Singularity threshold.
  67.      * @see #RRQRDecomposition(RealMatrix)
  68.      */
  69.     public RRQRDecomposition(RealMatrix matrix,  double threshold) {
  70.         super(matrix, threshold);
  71.     }

  72.     /** Decompose matrix.
  73.      * @param qrt transposed matrix
  74.      */
  75.     @Override
  76.     protected void decompose(double[][] qrt) {
  77.         p = new int[qrt.length];
  78.         for (int i = 0; i < p.length; i++) {
  79.             p[i] = i;
  80.         }
  81.         super.decompose(qrt);
  82.     }

  83.     /** Perform Householder reflection for a minor A(minor, minor) of A.
  84.      *
  85.      * @param minor minor index
  86.      * @param qrt transposed matrix
  87.      */
  88.     @Override
  89.     protected void performHouseholderReflection(int minor, double[][] qrt) {
  90.         double l2NormSquaredMax = 0;
  91.         // Find the unreduced column with the greatest L2-Norm
  92.         int l2NormSquaredMaxIndex = minor;
  93.         for (int i = minor; i < qrt.length; i++) {
  94.             double l2NormSquared = 0;
  95.             for (int j = minor; j < qrt[i].length; j++) {
  96.                 l2NormSquared += qrt[i][j] * qrt[i][j];
  97.             }
  98.             if (l2NormSquared > l2NormSquaredMax) {
  99.                 l2NormSquaredMax = l2NormSquared;
  100.                 l2NormSquaredMaxIndex = i;
  101.             }
  102.         }
  103.         // swap the current column with that with the greated L2-Norm and record in p
  104.         if (l2NormSquaredMaxIndex != minor) {
  105.             double[] tmp1 = qrt[minor];
  106.             qrt[minor] = qrt[l2NormSquaredMaxIndex];
  107.             qrt[l2NormSquaredMaxIndex] = tmp1;
  108.             int tmp2 = p[minor];
  109.             p[minor] = p[l2NormSquaredMaxIndex];
  110.             p[l2NormSquaredMaxIndex] = tmp2;
  111.         }

  112.         super.performHouseholderReflection(minor, qrt);
  113.     }


  114.     /**
  115.      * Returns the pivot matrix, P, used in the QR Decomposition of matrix A such that AP = QR.
  116.      *
  117.      * If no pivoting is used in this decomposition then P is equal to the identity matrix.
  118.      *
  119.      * @return a permutation matrix.
  120.      */
  121.     public RealMatrix getP() {
  122.         if (cachedP == null) {
  123.             int n = p.length;
  124.             cachedP = MatrixUtils.createRealMatrix(n,n);
  125.             for (int i = 0; i < n; i++) {
  126.                 cachedP.setEntry(p[i], i, 1);
  127.             }
  128.         }
  129.         return cachedP ;
  130.     }

  131.     /**
  132.      * Return the effective numerical matrix rank.
  133.      * <p>The effective numerical rank is the number of non-negligible
  134.      * singular values.</p>
  135.      * <p>This implementation looks at Frobenius norms of the sequence of
  136.      * bottom right submatrices.  When a large fall in norm is seen,
  137.      * the rank is returned. The drop is computed as:</p>
  138.      * <pre>
  139.      *   (thisNorm/lastNorm) * rNorm &lt; dropThreshold
  140.      * </pre>
  141.      * <p>
  142.      * where thisNorm is the Frobenius norm of the current submatrix,
  143.      * lastNorm is the Frobenius norm of the previous submatrix,
  144.      * rNorm is is the Frobenius norm of the complete matrix
  145.      * </p>
  146.      *
  147.      * @param dropThreshold threshold triggering rank computation
  148.      * @return effective numerical matrix rank
  149.      */
  150.     public int getRank(final double dropThreshold) {
  151.         RealMatrix r    = getR();
  152.         int rows        = r.getRowDimension();
  153.         int columns     = r.getColumnDimension();
  154.         int rank        = 1;
  155.         double lastNorm = r.getFrobeniusNorm();
  156.         double rNorm    = lastNorm;
  157.         while (rank < JdkMath.min(rows, columns)) {
  158.             double thisNorm = r.getSubMatrix(rank, rows - 1, rank, columns - 1).getFrobeniusNorm();
  159.             if (thisNorm == 0 || (thisNorm / lastNorm) * rNorm < dropThreshold) {
  160.                 break;
  161.             }
  162.             lastNorm = thisNorm;
  163.             rank++;
  164.         }
  165.         return rank;
  166.     }

  167.     /**
  168.      * Get a solver for finding the A &times; X = B solution in least square sense.
  169.      * <p>
  170.      * Least Square sense means a solver can be computed for an overdetermined system,
  171.      * (i.e. a system with more equations than unknowns, which corresponds to a tall A
  172.      * matrix with more rows than columns). In any case, if the matrix is singular
  173.      * within the tolerance set at {@link RRQRDecomposition#RRQRDecomposition(RealMatrix,
  174.      * double) construction}, an error will be triggered when
  175.      * the {@link DecompositionSolver#solve(RealVector) solve} method will be called.
  176.      * </p>
  177.      * @return a solver
  178.      */
  179.     @Override
  180.     public DecompositionSolver getSolver() {
  181.         return new Solver(super.getSolver(), this.getP());
  182.     }

  183.     /** Specialized solver. */
  184.     private static final class Solver implements DecompositionSolver {

  185.         /** Upper level solver. */
  186.         private final DecompositionSolver upper;

  187.         /** A permutation matrix for the pivots used in the QR decomposition. */
  188.         private RealMatrix p;

  189.         /**
  190.          * Build a solver from decomposed matrix.
  191.          *
  192.          * @param upper upper level solver.
  193.          * @param p permutation matrix
  194.          */
  195.         private Solver(final DecompositionSolver upper, final RealMatrix p) {
  196.             this.upper = upper;
  197.             this.p     = p;
  198.         }

  199.         /** {@inheritDoc} */
  200.         @Override
  201.         public boolean isNonSingular() {
  202.             return upper.isNonSingular();
  203.         }

  204.         /** {@inheritDoc} */
  205.         @Override
  206.         public RealVector solve(RealVector b) {
  207.             return p.operate(upper.solve(b));
  208.         }

  209.         /** {@inheritDoc} */
  210.         @Override
  211.         public RealMatrix solve(RealMatrix b) {
  212.             return p.multiply(upper.solve(b));
  213.         }

  214.         /**
  215.          * {@inheritDoc}
  216.          * @throws SingularMatrixException if the decomposed matrix is singular.
  217.          */
  218.         @Override
  219.         public RealMatrix getInverse() {
  220.             return solve(MatrixUtils.createRealIdentityMatrix(p.getRowDimension()));
  221.         }
  222.     }
  223. }