TriDiagonalTransformer.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 java.util.Arrays;

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


  20. /**
  21.  * Class transforming a symmetrical matrix to tridiagonal shape.
  22.  * <p>A symmetrical m &times; m matrix A can be written as the product of three matrices:
  23.  * A = Q &times; T &times; Q<sup>T</sup> with Q an orthogonal matrix and T a symmetrical
  24.  * tridiagonal matrix. Both Q and T are m &times; m matrices.</p>
  25.  * <p>This implementation only uses the upper part of the matrix, the part below the
  26.  * diagonal is not accessed at all.</p>
  27.  * <p>Transformation to tridiagonal shape is often not a goal by itself, but it is
  28.  * an intermediate step in more general decomposition algorithms like {@link
  29.  * EigenDecomposition eigen decomposition}. This class is therefore intended for internal
  30.  * use by the library and is not public. As a consequence of this explicitly limited scope,
  31.  * many methods directly returns references to internal arrays, not copies.</p>
  32.  * @since 2.0
  33.  */
  34. class TriDiagonalTransformer {
  35.     /** Householder vectors. */
  36.     private final double[][] householderVectors;
  37.     /** Main diagonal. */
  38.     private final double[] main;
  39.     /** Secondary diagonal. */
  40.     private final double[] secondary;
  41.     /** Cached value of Q. */
  42.     private RealMatrix cachedQ;
  43.     /** Cached value of Qt. */
  44.     private RealMatrix cachedQt;
  45.     /** Cached value of T. */
  46.     private RealMatrix cachedT;

  47.     /**
  48.      * Build the transformation to tridiagonal shape of a symmetrical matrix.
  49.      * <p>The specified matrix is assumed to be symmetrical without any check.
  50.      * Only the upper triangular part of the matrix is used.</p>
  51.      *
  52.      * @param matrix Symmetrical matrix to transform.
  53.      * @throws NonSquareMatrixException if the matrix is not square.
  54.      */
  55.     TriDiagonalTransformer(RealMatrix matrix) {
  56.         if (!matrix.isSquare()) {
  57.             throw new NonSquareMatrixException(matrix.getRowDimension(),
  58.                                                matrix.getColumnDimension());
  59.         }

  60.         final int m = matrix.getRowDimension();
  61.         householderVectors = matrix.getData();
  62.         main      = new double[m];
  63.         secondary = new double[m - 1];
  64.         cachedQ   = null;
  65.         cachedQt  = null;
  66.         cachedT   = null;

  67.         // transform matrix
  68.         transform();
  69.     }

  70.     /**
  71.      * Returns the matrix Q of the transform.
  72.      * <p>Q is an orthogonal matrix, i.e. its transpose is also its inverse.</p>
  73.      * @return the Q matrix
  74.      */
  75.     public RealMatrix getQ() {
  76.         if (cachedQ == null) {
  77.             cachedQ = getQT().transpose();
  78.         }
  79.         return cachedQ;
  80.     }

  81.     /**
  82.      * Returns the transpose of the matrix Q of the transform.
  83.      * <p>Q is an orthogonal matrix, i.e. its transpose is also its inverse.</p>
  84.      * @return the Q matrix
  85.      */
  86.     public RealMatrix getQT() {
  87.         if (cachedQt == null) {
  88.             final int m = householderVectors.length;
  89.             double[][] qta = new double[m][m];

  90.             // build up first part of the matrix by applying Householder transforms
  91.             for (int k = m - 1; k >= 1; --k) {
  92.                 final double[] hK = householderVectors[k - 1];
  93.                 qta[k][k] = 1;
  94.                 if (hK[k] != 0.0) {
  95.                     final double inv = 1.0 / (secondary[k - 1] * hK[k]);
  96.                     double beta = 1.0 / secondary[k - 1];
  97.                     qta[k][k] = 1 + beta * hK[k];
  98.                     for (int i = k + 1; i < m; ++i) {
  99.                         qta[k][i] = beta * hK[i];
  100.                     }
  101.                     for (int j = k + 1; j < m; ++j) {
  102.                         beta = 0;
  103.                         for (int i = k + 1; i < m; ++i) {
  104.                             beta += qta[j][i] * hK[i];
  105.                         }
  106.                         beta *= inv;
  107.                         qta[j][k] = beta * hK[k];
  108.                         for (int i = k + 1; i < m; ++i) {
  109.                             qta[j][i] += beta * hK[i];
  110.                         }
  111.                     }
  112.                 }
  113.             }
  114.             qta[0][0] = 1;
  115.             cachedQt = MatrixUtils.createRealMatrix(qta);
  116.         }

  117.         // return the cached matrix
  118.         return cachedQt;
  119.     }

  120.     /**
  121.      * Returns the tridiagonal matrix T of the transform.
  122.      * @return the T matrix
  123.      */
  124.     public RealMatrix getT() {
  125.         if (cachedT == null) {
  126.             final int m = main.length;
  127.             double[][] ta = new double[m][m];
  128.             for (int i = 0; i < m; ++i) {
  129.                 ta[i][i] = main[i];
  130.                 if (i > 0) {
  131.                     ta[i][i - 1] = secondary[i - 1];
  132.                 }
  133.                 if (i < main.length - 1) {
  134.                     ta[i][i + 1] = secondary[i];
  135.                 }
  136.             }
  137.             cachedT = MatrixUtils.createRealMatrix(ta);
  138.         }

  139.         // return the cached matrix
  140.         return cachedT;
  141.     }

  142.     /**
  143.      * Get the Householder vectors of the transform.
  144.      * <p>Note that since this class is only intended for internal use,
  145.      * it returns directly a reference to its internal arrays, not a copy.</p>
  146.      * @return the main diagonal elements of the B matrix
  147.      */
  148.     double[][] getHouseholderVectorsRef() {
  149.         return householderVectors;
  150.     }

  151.     /**
  152.      * Get the main diagonal elements of the matrix T of the transform.
  153.      * <p>Note that since this class is only intended for internal use,
  154.      * it returns directly a reference to its internal arrays, not a copy.</p>
  155.      * @return the main diagonal elements of the T matrix
  156.      */
  157.     double[] getMainDiagonalRef() {
  158.         return main;
  159.     }

  160.     /**
  161.      * Get the secondary diagonal elements of the matrix T of the transform.
  162.      * <p>Note that since this class is only intended for internal use,
  163.      * it returns directly a reference to its internal arrays, not a copy.</p>
  164.      * @return the secondary diagonal elements of the T matrix
  165.      */
  166.     double[] getSecondaryDiagonalRef() {
  167.         return secondary;
  168.     }

  169.     /**
  170.      * Transform original matrix to tridiagonal form.
  171.      * <p>Transformation is done using Householder transforms.</p>
  172.      */
  173.     private void transform() {
  174.         final int m = householderVectors.length;
  175.         final double[] z = new double[m];
  176.         for (int k = 0; k < m - 1; k++) {

  177.             //zero-out a row and a column simultaneously
  178.             final double[] hK = householderVectors[k];
  179.             main[k] = hK[k];
  180.             double xNormSqr = 0;
  181.             for (int j = k + 1; j < m; ++j) {
  182.                 final double c = hK[j];
  183.                 xNormSqr += c * c;
  184.             }
  185.             final double a = (hK[k + 1] > 0) ? -JdkMath.sqrt(xNormSqr) : JdkMath.sqrt(xNormSqr);
  186.             secondary[k] = a;
  187.             if (a != 0.0) {
  188.                 // apply Householder transform from left and right simultaneously

  189.                 hK[k + 1] -= a;
  190.                 final double beta = -1 / (a * hK[k + 1]);

  191.                 // compute a = beta A v, where v is the Householder vector
  192.                 // this loop is written in such a way
  193.                 //   1) only the upper triangular part of the matrix is accessed
  194.                 //   2) access is cache-friendly for a matrix stored in rows
  195.                 Arrays.fill(z, k + 1, m, 0);
  196.                 for (int i = k + 1; i < m; ++i) {
  197.                     final double[] hI = householderVectors[i];
  198.                     final double hKI = hK[i];
  199.                     double zI = hI[i] * hKI;
  200.                     for (int j = i + 1; j < m; ++j) {
  201.                         final double hIJ = hI[j];
  202.                         zI   += hIJ * hK[j];
  203.                         z[j] += hIJ * hKI;
  204.                     }
  205.                     z[i] = beta * (z[i] + zI);
  206.                 }

  207.                 // compute gamma = beta vT z / 2
  208.                 double gamma = 0;
  209.                 for (int i = k + 1; i < m; ++i) {
  210.                     gamma += z[i] * hK[i];
  211.                 }
  212.                 gamma *= beta / 2;

  213.                 // compute z = z - gamma v
  214.                 for (int i = k + 1; i < m; ++i) {
  215.                     z[i] -= gamma * hK[i];
  216.                 }

  217.                 // update matrix: A = A - v zT - z vT
  218.                 // only the upper triangular part of the matrix is updated
  219.                 for (int i = k + 1; i < m; ++i) {
  220.                     final double[] hI = householderVectors[i];
  221.                     for (int j = i; j < m; ++j) {
  222.                         hI[j] -= hK[i] * z[j] + z[i] * hK[j];
  223.                     }
  224.                 }
  225.             }
  226.         }
  227.         main[m - 1] = householderVectors[m - 1][m - 1];
  228.     }
  229. }