RectangularCholeskyDecomposition.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 rectangular Cholesky decomposition of a matrix.
  21.  * <p>The rectangular Cholesky decomposition of a real symmetric positive
  22.  * semidefinite matrix A consists of a rectangular matrix B with the same
  23.  * number of rows such that: A is almost equal to BB<sup>T</sup>, depending
  24.  * on a user-defined tolerance. In a sense, this is the square root of A.</p>
  25.  * <p>The difference with respect to the regular {@link CholeskyDecomposition}
  26.  * is that rows/columns may be permuted (hence the rectangular shape instead
  27.  * of the traditional triangular shape) and there is a threshold to ignore
  28.  * small diagonal elements. This is used for example to generate {@link
  29.  * org.apache.commons.math4.legacy.random.CorrelatedVectorFactory correlated
  30.  * random n-dimensions vectors} in a p-dimension subspace (p &lt; n).
  31.  * In other words, it allows generating random vectors from a covariance
  32.  * matrix that is only positive semidefinite, and not positive definite.</p>
  33.  * <p>Rectangular Cholesky decomposition is <em>not</em> suited for solving
  34.  * linear systems, so it does not provide any {@link DecompositionSolver
  35.  * decomposition solver}.</p>
  36.  *
  37.  * @see <a href="http://mathworld.wolfram.com/CholeskyDecomposition.html">MathWorld</a>
  38.  * @see <a href="http://en.wikipedia.org/wiki/Cholesky_decomposition">Wikipedia</a>
  39.  * @since 2.0 (changed to concrete class in 3.0)
  40.  */
  41. public class RectangularCholeskyDecomposition {

  42.     /** Permutated Cholesky root of the symmetric positive semidefinite matrix. */
  43.     private final RealMatrix root;

  44.     /** Rank of the symmetric positive semidefinite matrix. */
  45.     private int rank;

  46.     /**
  47.      * Decompose a symmetric positive semidefinite matrix.
  48.      * <p>
  49.      * <b>Note:</b> this constructor follows the linpack method to detect dependent
  50.      * columns by proceeding with the Cholesky algorithm until a nonpositive diagonal
  51.      * element is encountered.
  52.      *
  53.      * @see <a href="http://eprints.ma.man.ac.uk/1193/01/covered/MIMS_ep2008_56.pdf">
  54.      * Analysis of the Cholesky Decomposition of a Semi-definite Matrix</a>
  55.      *
  56.      * @param matrix Symmetric positive semidefinite matrix.
  57.      * @exception NonPositiveDefiniteMatrixException if the matrix is not
  58.      * positive semidefinite.
  59.      * @since 3.1
  60.      */
  61.     public RectangularCholeskyDecomposition(RealMatrix matrix)
  62.         throws NonPositiveDefiniteMatrixException {
  63.         this(matrix, 0);
  64.     }

  65.     /**
  66.      * Decompose a symmetric positive semidefinite matrix.
  67.      *
  68.      * @param matrix Symmetric positive semidefinite matrix.
  69.      * @param small Diagonal elements threshold under which columns are
  70.      * considered to be dependent on previous ones and are discarded.
  71.      * @exception NonPositiveDefiniteMatrixException if the matrix is not
  72.      * positive semidefinite.
  73.      */
  74.     public RectangularCholeskyDecomposition(RealMatrix matrix, double small)
  75.         throws NonPositiveDefiniteMatrixException {

  76.         final int order = matrix.getRowDimension();
  77.         final double[][] c = matrix.getData();
  78.         final double[][] b = new double[order][order];

  79.         int[] index = new int[order];
  80.         for (int i = 0; i < order; ++i) {
  81.             index[i] = i;
  82.         }

  83.         int r = 0;
  84.         for (boolean loop = true; loop;) {

  85.             // find maximal diagonal element
  86.             int swapR = r;
  87.             for (int i = r + 1; i < order; ++i) {
  88.                 int ii  = index[i];
  89.                 int isr = index[swapR];
  90.                 if (c[ii][ii] > c[isr][isr]) {
  91.                     swapR = i;
  92.                 }
  93.             }


  94.             // swap elements
  95.             if (swapR != r) {
  96.                 final int tmpIndex    = index[r];
  97.                 index[r]              = index[swapR];
  98.                 index[swapR]          = tmpIndex;
  99.                 final double[] tmpRow = b[r];
  100.                 b[r]                  = b[swapR];
  101.                 b[swapR]              = tmpRow;
  102.             }

  103.             // check diagonal element
  104.             int ir = index[r];
  105.             if (c[ir][ir] <= small) {

  106.                 if (r == 0) {
  107.                     throw new NonPositiveDefiniteMatrixException(c[ir][ir], ir, small);
  108.                 }

  109.                 // check remaining diagonal elements
  110.                 for (int i = r; i < order; ++i) {
  111.                     if (c[index[i]][index[i]] < -small) {
  112.                         // there is at least one sufficiently negative diagonal element,
  113.                         // the symmetric positive semidefinite matrix is wrong
  114.                         throw new NonPositiveDefiniteMatrixException(c[index[i]][index[i]], i, small);
  115.                     }
  116.                 }

  117.                 // all remaining diagonal elements are close to zero, we consider we have
  118.                 // found the rank of the symmetric positive semidefinite matrix
  119.                 loop = false;
  120.             } else {

  121.                 // transform the matrix
  122.                 final double sqrt = JdkMath.sqrt(c[ir][ir]);
  123.                 b[r][r] = sqrt;
  124.                 final double inverse  = 1 / sqrt;
  125.                 final double inverse2 = 1 / c[ir][ir];
  126.                 for (int i = r + 1; i < order; ++i) {
  127.                     final int ii = index[i];
  128.                     final double e = inverse * c[ii][ir];
  129.                     b[i][r] = e;
  130.                     c[ii][ii] -= c[ii][ir] * c[ii][ir] * inverse2;
  131.                     for (int j = r + 1; j < i; ++j) {
  132.                         final int ij = index[j];
  133.                         final double f = c[ii][ij] - e * b[j][r];
  134.                         c[ii][ij] = f;
  135.                         c[ij][ii] = f;
  136.                     }
  137.                 }

  138.                 // prepare next iteration
  139.                 loop = ++r < order;
  140.             }
  141.         }

  142.         // build the root matrix
  143.         rank = r;
  144.         root = MatrixUtils.createRealMatrix(order, r);
  145.         for (int i = 0; i < order; ++i) {
  146.             for (int j = 0; j < r; ++j) {
  147.                 root.setEntry(index[i], j, b[i][j]);
  148.             }
  149.         }
  150.     }

  151.     /** Get the root of the covariance matrix.
  152.      * The root is the rectangular matrix <code>B</code> such that
  153.      * the covariance matrix is equal to <code>B.B<sup>T</sup></code>
  154.      * @return root of the square matrix
  155.      * @see #getRank()
  156.      */
  157.     public RealMatrix getRootMatrix() {
  158.         return root;
  159.     }

  160.     /** Get the rank of the symmetric positive semidefinite matrix.
  161.      * The r is the number of independent rows in the symmetric positive semidefinite
  162.      * matrix, it is also the number of columns of the rectangular
  163.      * matrix of the decomposition.
  164.      * @return r of the square matrix.
  165.      * @see #getRootMatrix()
  166.      */
  167.     public int getRank() {
  168.         return rank;
  169.     }
  170. }