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.  *      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 org.hipparchus.exception.LocalizedCoreFormats;
  23. import org.hipparchus.exception.MathIllegalArgumentException;
  24. import org.hipparchus.util.FastMath;

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

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

  49.     /** Rank of the symmetric positive semidefinite matrix. */
  50.     private int rank;

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

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

  80.         final int order = matrix.getRowDimension();
  81.         final double[][] c = matrix.getData();
  82.         final double[][] b = new double[order][order];

  83.         int[] index = new int[order];
  84.         for (int i = 0; i < order; ++i) {
  85.             index[i] = i;
  86.         }

  87.         int r = 0;
  88.         for (boolean loop = true; loop;) {

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


  98.             // swap elements
  99.             if (swapR != r) {
  100.                 final int tmpIndex    = index[r];
  101.                 index[r]              = index[swapR];
  102.                 index[swapR]          = tmpIndex;
  103.                 final double[] tmpRow = b[r];
  104.                 b[r]                  = b[swapR];
  105.                 b[swapR]              = tmpRow;
  106.             }

  107.             // check diagonal element
  108.             int ir = index[r];
  109.             if (c[ir][ir] <= small) {

  110.                 if (r == 0) {
  111.                     throw new MathIllegalArgumentException(LocalizedCoreFormats.NOT_POSITIVE_DEFINITE_MATRIX);
  112.                 }

  113.                 // check remaining diagonal elements
  114.                 for (int i = r; i < order; ++i) {
  115.                     if (c[index[i]][index[i]] < -small) {
  116.                         // there is at least one sufficiently negative diagonal element,
  117.                         // the symmetric positive semidefinite matrix is wrong
  118.                         throw new MathIllegalArgumentException(LocalizedCoreFormats.NOT_POSITIVE_DEFINITE_MATRIX);
  119.                     }
  120.                 }

  121.                 // all remaining diagonal elements are close to zero, we consider we have
  122.                 // found the rank of the symmetric positive semidefinite matrix
  123.                 loop = false;

  124.             } else {

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

  142.                 // prepare next iteration
  143.                 loop = ++r < order;
  144.             }
  145.         }

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

  154.     }

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

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

  174. }