SingularValueDecomposition.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.legacy.exception.NumberIsTooLargeException;
  19. import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
  20. import org.apache.commons.math4.core.jdkmath.JdkMath;
  21. import org.apache.commons.numbers.core.Precision;

  22. /**
  23.  * Calculates the compact Singular Value Decomposition of a matrix.
  24.  * <p>
  25.  * The Singular Value Decomposition of matrix A is a set of three matrices: U,
  26.  * &Sigma; and V such that A = U &times; &Sigma; &times; V<sup>T</sup>. Let A be
  27.  * a m &times; n matrix, then U is a m &times; p orthogonal matrix, &Sigma; is a
  28.  * p &times; p diagonal matrix with positive or null elements, V is a p &times;
  29.  * n orthogonal matrix (hence V<sup>T</sup> is also orthogonal) where
  30.  * p=min(m,n).
  31.  * </p>
  32.  * <p>This class is similar to the class with similar name from the
  33.  * <a href="http://math.nist.gov/javanumerics/jama/">JAMA</a> library, with the
  34.  * following changes:</p>
  35.  * <ul>
  36.  *   <li>the {@code norm2} method which has been renamed as {@link #getNorm()
  37.  *   getNorm},</li>
  38.  *   <li>the {@code cond} method which has been renamed as {@link
  39.  *   #getConditionNumber() getConditionNumber},</li>
  40.  *   <li>the {@code rank} method which has been renamed as {@link #getRank()
  41.  *   getRank},</li>
  42.  *   <li>a {@link #getUT() getUT} method has been added,</li>
  43.  *   <li>a {@link #getVT() getVT} method has been added,</li>
  44.  *   <li>a {@link #getSolver() getSolver} method has been added,</li>
  45.  *   <li>a {@link #getCovariance(double) getCovariance} method has been added.</li>
  46.  * </ul>
  47.  * @see <a href="http://mathworld.wolfram.com/SingularValueDecomposition.html">MathWorld</a>
  48.  * @see <a href="http://en.wikipedia.org/wiki/Singular_value_decomposition">Wikipedia</a>
  49.  * @since 2.0 (changed to concrete class in 3.0)
  50.  */
  51. public class SingularValueDecomposition {
  52.     /** Relative threshold for small singular values. */
  53.     private static final double EPS = 0x1.0p-52;
  54.     /** Absolute threshold for small singular values. */
  55.     private static final double TINY = 0x1.0p-966;
  56.     /** Computed singular values. */
  57.     private final double[] singularValues;
  58.     /** max(row dimension, column dimension). */
  59.     private final int m;
  60.     /** min(row dimension, column dimension). */
  61.     private final int n;
  62.     /** Indicator for transposed matrix. */
  63.     private final boolean transposed;
  64.     /** Cached value of U matrix. */
  65.     private final RealMatrix cachedU;
  66.     /** Cached value of transposed U matrix. */
  67.     private RealMatrix cachedUt;
  68.     /** Cached value of S (diagonal) matrix. */
  69.     private RealMatrix cachedS;
  70.     /** Cached value of V matrix. */
  71.     private final RealMatrix cachedV;
  72.     /** Cached value of transposed V matrix. */
  73.     private RealMatrix cachedVt;
  74.     /**
  75.      * Tolerance value for small singular values, calculated once we have
  76.      * populated "singularValues".
  77.      **/
  78.     private final double tol;

  79.     /**
  80.      * Calculates the compact Singular Value Decomposition of the given matrix.
  81.      *
  82.      * @param matrix Matrix to decompose.
  83.      */
  84.     public SingularValueDecomposition(final RealMatrix matrix) {
  85.         final double[][] A;

  86.          // "m" is always the largest dimension.
  87.         if (matrix.getRowDimension() < matrix.getColumnDimension()) {
  88.             transposed = true;
  89.             A = matrix.transpose().getData();
  90.             m = matrix.getColumnDimension();
  91.             n = matrix.getRowDimension();
  92.         } else {
  93.             transposed = false;
  94.             A = matrix.getData();
  95.             m = matrix.getRowDimension();
  96.             n = matrix.getColumnDimension();
  97.         }

  98.         singularValues = new double[n];
  99.         final double[][] U = new double[m][n];
  100.         final double[][] V = new double[n][n];
  101.         final double[] e = new double[n];
  102.         final double[] work = new double[m];
  103.         // Reduce A to bidiagonal form, storing the diagonal elements
  104.         // in s and the super-diagonal elements in e.
  105.         final int nct = JdkMath.min(m - 1, n);
  106.         final int nrt = JdkMath.max(0, n - 2);
  107.         for (int k = 0; k < JdkMath.max(nct, nrt); k++) {
  108.             if (k < nct) {
  109.                 // Compute the transformation for the k-th column and
  110.                 // place the k-th diagonal in s[k].
  111.                 // Compute 2-norm of k-th column without under/overflow.
  112.                 singularValues[k] = 0;
  113.                 for (int i = k; i < m; i++) {
  114.                     singularValues[k] = JdkMath.hypot(singularValues[k], A[i][k]);
  115.                 }
  116.                 if (singularValues[k] != 0) {
  117.                     if (A[k][k] < 0) {
  118.                         singularValues[k] = -singularValues[k];
  119.                     }
  120.                     for (int i = k; i < m; i++) {
  121.                         A[i][k] /= singularValues[k];
  122.                     }
  123.                     A[k][k] += 1;
  124.                 }
  125.                 singularValues[k] = -singularValues[k];
  126.             }
  127.             for (int j = k + 1; j < n; j++) {
  128.                 if (k < nct &&
  129.                     singularValues[k] != 0) {
  130.                     // Apply the transformation.
  131.                     double t = 0;
  132.                     for (int i = k; i < m; i++) {
  133.                         t += A[i][k] * A[i][j];
  134.                     }
  135.                     t = -t / A[k][k];
  136.                     for (int i = k; i < m; i++) {
  137.                         A[i][j] += t * A[i][k];
  138.                     }
  139.                 }
  140.                 // Place the k-th row of A into e for the
  141.                 // subsequent calculation of the row transformation.
  142.                 e[j] = A[k][j];
  143.             }
  144.             if (k < nct) {
  145.                 // Place the transformation in U for subsequent back
  146.                 // multiplication.
  147.                 for (int i = k; i < m; i++) {
  148.                     U[i][k] = A[i][k];
  149.                 }
  150.             }
  151.             if (k < nrt) {
  152.                 // Compute the k-th row transformation and place the
  153.                 // k-th super-diagonal in e[k].
  154.                 // Compute 2-norm without under/overflow.
  155.                 e[k] = 0;
  156.                 for (int i = k + 1; i < n; i++) {
  157.                     e[k] = JdkMath.hypot(e[k], e[i]);
  158.                 }
  159.                 if (e[k] != 0) {
  160.                     if (e[k + 1] < 0) {
  161.                         e[k] = -e[k];
  162.                     }
  163.                     for (int i = k + 1; i < n; i++) {
  164.                         e[i] /= e[k];
  165.                     }
  166.                     e[k + 1] += 1;
  167.                 }
  168.                 e[k] = -e[k];
  169.                 if (k + 1 < m &&
  170.                     e[k] != 0) {
  171.                     // Apply the transformation.
  172.                     for (int i = k + 1; i < m; i++) {
  173.                         work[i] = 0;
  174.                     }
  175.                     for (int j = k + 1; j < n; j++) {
  176.                         for (int i = k + 1; i < m; i++) {
  177.                             work[i] += e[j] * A[i][j];
  178.                         }
  179.                     }
  180.                     for (int j = k + 1; j < n; j++) {
  181.                         final double t = -e[j] / e[k + 1];
  182.                         for (int i = k + 1; i < m; i++) {
  183.                             A[i][j] += t * work[i];
  184.                         }
  185.                     }
  186.                 }

  187.                 // Place the transformation in V for subsequent
  188.                 // back multiplication.
  189.                 for (int i = k + 1; i < n; i++) {
  190.                     V[i][k] = e[i];
  191.                 }
  192.             }
  193.         }
  194.         // Set up the final bidiagonal matrix or order p.
  195.         int p = n;
  196.         if (nct < n) {
  197.             singularValues[nct] = A[nct][nct];
  198.         }
  199.         if (m < p) {
  200.             singularValues[p - 1] = 0;
  201.         }
  202.         if (nrt + 1 < p) {
  203.             e[nrt] = A[nrt][p - 1];
  204.         }
  205.         e[p - 1] = 0;

  206.         // Generate U.
  207.         for (int j = nct; j < n; j++) {
  208.             for (int i = 0; i < m; i++) {
  209.                 U[i][j] = 0;
  210.             }
  211.             U[j][j] = 1;
  212.         }
  213.         for (int k = nct - 1; k >= 0; k--) {
  214.             if (singularValues[k] != 0) {
  215.                 for (int j = k + 1; j < n; j++) {
  216.                     double t = 0;
  217.                     for (int i = k; i < m; i++) {
  218.                         t += U[i][k] * U[i][j];
  219.                     }
  220.                     t = -t / U[k][k];
  221.                     for (int i = k; i < m; i++) {
  222.                         U[i][j] += t * U[i][k];
  223.                     }
  224.                 }
  225.                 for (int i = k; i < m; i++) {
  226.                     U[i][k] = -U[i][k];
  227.                 }
  228.                 U[k][k] = 1 + U[k][k];
  229.                 for (int i = 0; i < k - 1; i++) {
  230.                     U[i][k] = 0;
  231.                 }
  232.             } else {
  233.                 for (int i = 0; i < m; i++) {
  234.                     U[i][k] = 0;
  235.                 }
  236.                 U[k][k] = 1;
  237.             }
  238.         }

  239.         // Generate V.
  240.         for (int k = n - 1; k >= 0; k--) {
  241.             if (k < nrt &&
  242.                 e[k] != 0) {
  243.                 for (int j = k + 1; j < n; j++) {
  244.                     double t = 0;
  245.                     for (int i = k + 1; i < n; i++) {
  246.                         t += V[i][k] * V[i][j];
  247.                     }
  248.                     t = -t / V[k + 1][k];
  249.                     for (int i = k + 1; i < n; i++) {
  250.                         V[i][j] += t * V[i][k];
  251.                     }
  252.                 }
  253.             }
  254.             for (int i = 0; i < n; i++) {
  255.                 V[i][k] = 0;
  256.             }
  257.             V[k][k] = 1;
  258.         }

  259.         // Main iteration loop for the singular values.
  260.         final int pp = p - 1;
  261.         while (p > 0) {
  262.             int k;
  263.             int kase;
  264.             // Here is where a test for too many iterations would go.
  265.             // This section of the program inspects for
  266.             // negligible elements in the s and e arrays.  On
  267.             // completion the variables kase and k are set as follows.
  268.             // kase = 1     if s(p) and e[k-1] are negligible and k<p
  269.             // kase = 2     if s(k) is negligible and k<p
  270.             // kase = 3     if e[k-1] is negligible, k<p, and
  271.             //              s(k), ..., s(p) are not negligible (qr step).
  272.             // kase = 4     if e(p-1) is negligible (convergence).
  273.             for (k = p - 2; k >= 0; k--) {
  274.                 final double threshold
  275.                     = TINY + EPS * (JdkMath.abs(singularValues[k]) +
  276.                                     JdkMath.abs(singularValues[k + 1]));

  277.                 // the following condition is written this way in order
  278.                 // to break out of the loop when NaN occurs, writing it
  279.                 // as "if (JdkMath.abs(e[k]) <= threshold)" would loop
  280.                 // indefinitely in case of NaNs because comparison on NaNs
  281.                 // always return false, regardless of what is checked
  282.                 // see issue MATH-947
  283.                 if (!(JdkMath.abs(e[k]) > threshold)) {
  284.                     e[k] = 0;
  285.                     break;
  286.                 }
  287.             }

  288.             if (k == p - 2) {
  289.                 kase = 4;
  290.             } else {
  291.                 int ks;
  292.                 for (ks = p - 1; ks >= k; ks--) {
  293.                     if (ks == k) {
  294.                         break;
  295.                     }
  296.                     final double t = (ks != p ? JdkMath.abs(e[ks]) : 0) +
  297.                         (ks != k + 1 ? JdkMath.abs(e[ks - 1]) : 0);
  298.                     if (JdkMath.abs(singularValues[ks]) <= TINY + EPS * t) {
  299.                         singularValues[ks] = 0;
  300.                         break;
  301.                     }
  302.                 }
  303.                 if (ks == k) {
  304.                     kase = 3;
  305.                 } else if (ks == p - 1) {
  306.                     kase = 1;
  307.                 } else {
  308.                     kase = 2;
  309.                     k = ks;
  310.                 }
  311.             }
  312.             k++;
  313.             // Perform the task indicated by kase.
  314.             double f;
  315.             switch (kase) {
  316.                 // Deflate negligible s(p).
  317.                 case 1:
  318.                     f = e[p - 2];
  319.                     e[p - 2] = 0;
  320.                     for (int j = p - 2; j >= k; j--) {
  321.                         double t = JdkMath.hypot(singularValues[j], f);
  322.                         final double cs = singularValues[j] / t;
  323.                         final double sn = f / t;
  324.                         singularValues[j] = t;
  325.                         if (j != k) {
  326.                             f = -sn * e[j - 1];
  327.                             e[j - 1] = cs * e[j - 1];
  328.                         }

  329.                         for (int i = 0; i < n; i++) {
  330.                             t = cs * V[i][j] + sn * V[i][p - 1];
  331.                             V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1];
  332.                             V[i][j] = t;
  333.                         }
  334.                     }
  335.                     break;
  336.                 // Split at negligible s(k).
  337.                 case 2:
  338.                     f = e[k - 1];
  339.                     e[k - 1] = 0;
  340.                     for (int j = k; j < p; j++) {
  341.                         double t = JdkMath.hypot(singularValues[j], f);
  342.                         final double cs = singularValues[j] / t;
  343.                         final double sn = f / t;
  344.                         singularValues[j] = t;
  345.                         f = -sn * e[j];
  346.                         e[j] = cs * e[j];

  347.                         for (int i = 0; i < m; i++) {
  348.                             t = cs * U[i][j] + sn * U[i][k - 1];
  349.                             U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1];
  350.                             U[i][j] = t;
  351.                         }
  352.                     }
  353.                     break;
  354.                 // Perform one qr step.
  355.                 case 3:
  356.                     // Calculate the shift.
  357.                     final double maxPm1Pm2 = JdkMath.max(JdkMath.abs(singularValues[p - 1]),
  358.                                                           JdkMath.abs(singularValues[p - 2]));
  359.                     final double scale = JdkMath.max(JdkMath.max(JdkMath.max(maxPm1Pm2,
  360.                                                                                 JdkMath.abs(e[p - 2])),
  361.                                                                    JdkMath.abs(singularValues[k])),
  362.                                                       JdkMath.abs(e[k]));
  363.                     final double sp = singularValues[p - 1] / scale;
  364.                     final double spm1 = singularValues[p - 2] / scale;
  365.                     final double epm1 = e[p - 2] / scale;
  366.                     final double sk = singularValues[k] / scale;
  367.                     final double ek = e[k] / scale;
  368.                     final double b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2.0;
  369.                     final double c = (sp * epm1) * (sp * epm1);
  370.                     double shift = 0;
  371.                     if (b != 0 ||
  372.                         c != 0) {
  373.                         shift = JdkMath.sqrt(b * b + c);
  374.                         if (b < 0) {
  375.                             shift = -shift;
  376.                         }
  377.                         shift = c / (b + shift);
  378.                     }
  379.                     f = (sk + sp) * (sk - sp) + shift;
  380.                     double g = sk * ek;
  381.                     // Chase zeros.
  382.                     for (int j = k; j < p - 1; j++) {
  383.                         double t = JdkMath.hypot(f, g);
  384.                         double cs = f / t;
  385.                         double sn = g / t;
  386.                         if (j != k) {
  387.                             e[j - 1] = t;
  388.                         }
  389.                         f = cs * singularValues[j] + sn * e[j];
  390.                         e[j] = cs * e[j] - sn * singularValues[j];
  391.                         g = sn * singularValues[j + 1];
  392.                         singularValues[j + 1] = cs * singularValues[j + 1];

  393.                         for (int i = 0; i < n; i++) {
  394.                             t = cs * V[i][j] + sn * V[i][j + 1];
  395.                             V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1];
  396.                             V[i][j] = t;
  397.                         }
  398.                         t = JdkMath.hypot(f, g);
  399.                         cs = f / t;
  400.                         sn = g / t;
  401.                         singularValues[j] = t;
  402.                         f = cs * e[j] + sn * singularValues[j + 1];
  403.                         singularValues[j + 1] = -sn * e[j] + cs * singularValues[j + 1];
  404.                         g = sn * e[j + 1];
  405.                         e[j + 1] = cs * e[j + 1];
  406.                         if (j < m - 1) {
  407.                             for (int i = 0; i < m; i++) {
  408.                                 t = cs * U[i][j] + sn * U[i][j + 1];
  409.                                 U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1];
  410.                                 U[i][j] = t;
  411.                             }
  412.                         }
  413.                     }
  414.                     e[p - 2] = f;
  415.                     break;
  416.                 // Convergence.
  417.                 default:
  418.                     // Make the singular values positive.
  419.                     if (singularValues[k] <= 0) {
  420.                         singularValues[k] = singularValues[k] < 0 ? -singularValues[k] : 0;

  421.                         for (int i = 0; i <= pp; i++) {
  422.                             V[i][k] = -V[i][k];
  423.                         }
  424.                     }
  425.                     // Order the singular values.
  426.                     while (k < pp) {
  427.                         if (singularValues[k] >= singularValues[k + 1]) {
  428.                             break;
  429.                         }
  430.                         double t = singularValues[k];
  431.                         singularValues[k] = singularValues[k + 1];
  432.                         singularValues[k + 1] = t;
  433.                         if (k < n - 1) {
  434.                             for (int i = 0; i < n; i++) {
  435.                                 t = V[i][k + 1];
  436.                                 V[i][k + 1] = V[i][k];
  437.                                 V[i][k] = t;
  438.                             }
  439.                         }
  440.                         if (k < m - 1) {
  441.                             for (int i = 0; i < m; i++) {
  442.                                 t = U[i][k + 1];
  443.                                 U[i][k + 1] = U[i][k];
  444.                                 U[i][k] = t;
  445.                             }
  446.                         }
  447.                         k++;
  448.                     }
  449.                     p--;
  450.                     break;
  451.             }
  452.         }

  453.         // Set the small value tolerance used to calculate rank and pseudo-inverse
  454.         tol = JdkMath.max(m * singularValues[0] * EPS,
  455.                            JdkMath.sqrt(Precision.SAFE_MIN));

  456.         if (!transposed) {
  457.             cachedU = MatrixUtils.createRealMatrix(U);
  458.             cachedV = MatrixUtils.createRealMatrix(V);
  459.         } else {
  460.             cachedU = MatrixUtils.createRealMatrix(V);
  461.             cachedV = MatrixUtils.createRealMatrix(U);
  462.         }
  463.     }

  464.     /**
  465.      * Returns the matrix U of the decomposition.
  466.      * <p>U is an orthogonal matrix, i.e. its transpose is also its inverse.</p>
  467.      * @return the U matrix
  468.      * @see #getUT()
  469.      */
  470.     public RealMatrix getU() {
  471.         // return the cached matrix
  472.         return cachedU;
  473.     }

  474.     /**
  475.      * Returns the transpose of the matrix U of the decomposition.
  476.      * <p>U is an orthogonal matrix, i.e. its transpose is also its inverse.</p>
  477.      * @return the U matrix (or null if decomposed matrix is singular)
  478.      * @see #getU()
  479.      */
  480.     public RealMatrix getUT() {
  481.         if (cachedUt == null) {
  482.             cachedUt = getU().transpose();
  483.         }
  484.         // return the cached matrix
  485.         return cachedUt;
  486.     }

  487.     /**
  488.      * Returns the diagonal matrix &Sigma; of the decomposition.
  489.      * <p>&Sigma; is a diagonal matrix. The singular values are provided in
  490.      * non-increasing order, for compatibility with Jama.</p>
  491.      * @return the &Sigma; matrix
  492.      */
  493.     public RealMatrix getS() {
  494.         if (cachedS == null) {
  495.             // cache the matrix for subsequent calls
  496.             cachedS = MatrixUtils.createRealDiagonalMatrix(singularValues);
  497.         }
  498.         return cachedS;
  499.     }

  500.     /**
  501.      * Returns the diagonal elements of the matrix &Sigma; of the decomposition.
  502.      * <p>The singular values are provided in non-increasing order, for
  503.      * compatibility with Jama.</p>
  504.      * @return the diagonal elements of the &Sigma; matrix
  505.      */
  506.     public double[] getSingularValues() {
  507.         return singularValues.clone();
  508.     }

  509.     /**
  510.      * Returns the matrix V of the decomposition.
  511.      * <p>V is an orthogonal matrix, i.e. its transpose is also its inverse.</p>
  512.      * @return the V matrix (or null if decomposed matrix is singular)
  513.      * @see #getVT()
  514.      */
  515.     public RealMatrix getV() {
  516.         // return the cached matrix
  517.         return cachedV;
  518.     }

  519.     /**
  520.      * Returns the transpose of the matrix V of the decomposition.
  521.      * <p>V is an orthogonal matrix, i.e. its transpose is also its inverse.</p>
  522.      * @return the V matrix (or null if decomposed matrix is singular)
  523.      * @see #getV()
  524.      */
  525.     public RealMatrix getVT() {
  526.         if (cachedVt == null) {
  527.             cachedVt = getV().transpose();
  528.         }
  529.         // return the cached matrix
  530.         return cachedVt;
  531.     }

  532.     /**
  533.      * Returns the n &times; n covariance matrix.
  534.      * <p>The covariance matrix is V &times; J &times; V<sup>T</sup>
  535.      * where J is the diagonal matrix of the inverse of the squares of
  536.      * the singular values.</p>
  537.      * @param minSingularValue value below which singular values are ignored
  538.      * (a 0 or negative value implies all singular value will be used)
  539.      * @return covariance matrix
  540.      * @exception IllegalArgumentException if minSingularValue is larger than
  541.      * the largest singular value, meaning all singular values are ignored
  542.      */
  543.     public RealMatrix getCovariance(final double minSingularValue) {
  544.         // get the number of singular values to consider
  545.         final int p = singularValues.length;
  546.         int dimension = 0;
  547.         while (dimension < p &&
  548.                singularValues[dimension] >= minSingularValue) {
  549.             ++dimension;
  550.         }

  551.         if (dimension == 0) {
  552.             throw new NumberIsTooLargeException(LocalizedFormats.TOO_LARGE_CUTOFF_SINGULAR_VALUE,
  553.                                                 minSingularValue, singularValues[0], true);
  554.         }

  555.         final double[][] data = new double[dimension][p];
  556.         getVT().walkInOptimizedOrder(new DefaultRealMatrixPreservingVisitor() {
  557.             /** {@inheritDoc} */
  558.             @Override
  559.             public void visit(final int row, final int column,
  560.                     final double value) {
  561.                 data[row][column] = value / singularValues[row];
  562.             }
  563.         }, 0, dimension - 1, 0, p - 1);

  564.         RealMatrix jv = new Array2DRowRealMatrix(data, false);
  565.         return jv.transpose().multiply(jv);
  566.     }

  567.     /**
  568.      * Returns the L<sub>2</sub> norm of the matrix.
  569.      * <p>The L<sub>2</sub> norm is max(|A &times; u|<sub>2</sub> /
  570.      * |u|<sub>2</sub>), where |.|<sub>2</sub> denotes the vectorial 2-norm
  571.      * (i.e. the traditional euclidean norm).</p>
  572.      * @return norm
  573.      */
  574.     public double getNorm() {
  575.         return singularValues[0];
  576.     }

  577.     /**
  578.      * Return the condition number of the matrix.
  579.      * @return condition number of the matrix
  580.      */
  581.     public double getConditionNumber() {
  582.         return singularValues[0] / singularValues[n - 1];
  583.     }

  584.     /**
  585.      * Computes the inverse of the condition number.
  586.      * In cases of rank deficiency, the {@link #getConditionNumber() condition
  587.      * number} will become undefined.
  588.      *
  589.      * @return the inverse of the condition number.
  590.      */
  591.     public double getInverseConditionNumber() {
  592.         return singularValues[n - 1] / singularValues[0];
  593.     }

  594.     /**
  595.      * Return the effective numerical matrix rank.
  596.      * <p>The effective numerical rank is the number of non-negligible
  597.      * singular values. The threshold used to identify non-negligible
  598.      * terms is max(m,n) &times; ulp(s<sub>1</sub>) where ulp(s<sub>1</sub>)
  599.      * is the least significant bit of the largest singular value.</p>
  600.      * @return effective numerical matrix rank
  601.      */
  602.     public int getRank() {
  603.         int r = 0;
  604.         for (int i = 0; i < singularValues.length; i++) {
  605.             if (singularValues[i] > tol) {
  606.                 r++;
  607.             }
  608.         }
  609.         return r;
  610.     }

  611.     /**
  612.      * Get a solver for finding the A &times; X = B solution in least square sense.
  613.      * @return a solver
  614.      */
  615.     public DecompositionSolver getSolver() {
  616.         return new Solver(singularValues, getUT(), getV(), getRank() == m, tol);
  617.     }

  618.     /** Specialized solver. */
  619.     private static final class Solver implements DecompositionSolver {
  620.         /** Pseudo-inverse of the initial matrix. */
  621.         private final RealMatrix pseudoInverse;
  622.         /** Singularity indicator. */
  623.         private final boolean nonSingular;

  624.         /**
  625.          * Build a solver from decomposed matrix.
  626.          *
  627.          * @param singularValues Singular values.
  628.          * @param uT U<sup>T</sup> matrix of the decomposition.
  629.          * @param v V matrix of the decomposition.
  630.          * @param nonSingular Singularity indicator.
  631.          * @param tol tolerance for singular values
  632.          */
  633.         private Solver(final double[] singularValues, final RealMatrix uT,
  634.                        final RealMatrix v, final boolean nonSingular, final double tol) {
  635.             final double[][] suT = uT.getData();
  636.             for (int i = 0; i < singularValues.length; ++i) {
  637.                 final double a;
  638.                 if (singularValues[i] > tol) {
  639.                     a = 1 / singularValues[i];
  640.                 } else {
  641.                     a = 0;
  642.                 }
  643.                 final double[] suTi = suT[i];
  644.                 for (int j = 0; j < suTi.length; ++j) {
  645.                     suTi[j] *= a;
  646.                 }
  647.             }
  648.             pseudoInverse = v.multiply(new Array2DRowRealMatrix(suT, false));
  649.             this.nonSingular = nonSingular;
  650.         }

  651.         /**
  652.          * Solve the linear equation A &times; X = B in least square sense.
  653.          * <p>
  654.          * The m&times;n matrix A may not be square, the solution X is such that
  655.          * ||A &times; X - B|| is minimal.
  656.          * </p>
  657.          * @param b Right-hand side of the equation A &times; X = B
  658.          * @return a vector X that minimizes the two norm of A &times; X - B
  659.          * @throws org.apache.commons.math4.legacy.exception.DimensionMismatchException
  660.          * if the matrices dimensions do not match.
  661.          */
  662.         @Override
  663.         public RealVector solve(final RealVector b) {
  664.             return pseudoInverse.operate(b);
  665.         }

  666.         /**
  667.          * Solve the linear equation A &times; X = B in least square sense.
  668.          * <p>
  669.          * The m&times;n matrix A may not be square, the solution X is such that
  670.          * ||A &times; X - B|| is minimal.
  671.          * </p>
  672.          *
  673.          * @param b Right-hand side of the equation A &times; X = B
  674.          * @return a matrix X that minimizes the two norm of A &times; X - B
  675.          * @throws org.apache.commons.math4.legacy.exception.DimensionMismatchException
  676.          * if the matrices dimensions do not match.
  677.          */
  678.         @Override
  679.         public RealMatrix solve(final RealMatrix b) {
  680.             return pseudoInverse.multiply(b);
  681.         }

  682.         /**
  683.          * Check if the decomposed matrix is non-singular.
  684.          *
  685.          * @return {@code true} if the decomposed matrix is non-singular.
  686.          */
  687.         @Override
  688.         public boolean isNonSingular() {
  689.             return nonSingular;
  690.         }

  691.         /**
  692.          * Get the pseudo-inverse of the decomposed matrix.
  693.          *
  694.          * @return the inverse matrix.
  695.          */
  696.         @Override
  697.         public RealMatrix getInverse() {
  698.             return pseudoInverse;
  699.         }
  700.     }
  701. }