StorelessCovariance.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.stat.correlation;

  22. import org.hipparchus.exception.LocalizedCoreFormats;
  23. import org.hipparchus.exception.MathIllegalArgumentException;
  24. import org.hipparchus.exception.MathRuntimeException;
  25. import org.hipparchus.linear.MatrixUtils;
  26. import org.hipparchus.linear.RealMatrix;
  27. import org.hipparchus.util.MathUtils;

  28. /**
  29.  * Covariance implementation that does not require input data to be
  30.  * stored in memory. The size of the covariance matrix is specified in the
  31.  * constructor. Specific elements of the matrix are incrementally updated with
  32.  * calls to incrementRow() or increment Covariance().
  33.  * <p>
  34.  * This class is based on a paper written by Philippe P&eacute;bay:
  35.  * <a href="http://prod.sandia.gov/techlib/access-control.cgi/2008/086212.pdf">
  36.  * Formulas for Robust, One-Pass Parallel Computation of Covariances and
  37.  * Arbitrary-Order Statistical Moments</a>, 2008, Technical Report SAND2008-6212,
  38.  * Sandia National Laboratories.
  39.  * <p>
  40.  * Note: the underlying covariance matrix is symmetric, thus only the
  41.  * upper triangular part of the matrix is stored and updated each increment.
  42.  */
  43. public class StorelessCovariance extends Covariance {

  44.     /** the square covariance matrix (upper triangular part) */
  45.     private final StorelessBivariateCovariance[] covMatrix;

  46.     /** dimension of the square covariance matrix */
  47.     private final int dimension;

  48.     /**
  49.      * Create a bias corrected covariance matrix with a given dimension.
  50.      *
  51.      * @param dim the dimension of the square covariance matrix
  52.      */
  53.     public StorelessCovariance(final int dim) {
  54.         this(dim, true);
  55.     }

  56.     /**
  57.      * Create a covariance matrix with a given number of rows and columns and the
  58.      * indicated bias correction.
  59.      *
  60.      * @param dim the dimension of the covariance matrix
  61.      * @param biasCorrected if <code>true</code> the covariance estimate is corrected
  62.      * for bias, i.e. n-1 in the denominator, otherwise there is no bias correction,
  63.      * i.e. n in the denominator.
  64.      */
  65.     public StorelessCovariance(final int dim, final boolean biasCorrected) {
  66.         dimension = dim;
  67.         covMatrix = new StorelessBivariateCovariance[dimension * (dimension + 1) / 2];
  68.         initializeMatrix(biasCorrected);
  69.     }

  70.     /**
  71.      * Initialize the internal two-dimensional array of
  72.      * {@link StorelessBivariateCovariance} instances.
  73.      *
  74.      * @param biasCorrected if the covariance estimate shall be corrected for bias
  75.      */
  76.     private void initializeMatrix(final boolean biasCorrected) {
  77.         for(int i = 0; i < dimension; i++){
  78.             for(int j = 0; j < dimension; j++){
  79.                 setElement(i, j, new StorelessBivariateCovariance(biasCorrected));
  80.             }
  81.         }
  82.     }

  83.     /**
  84.      * Returns the index (i, j) translated into the one-dimensional
  85.      * array used to store the upper triangular part of the symmetric
  86.      * covariance matrix.
  87.      *
  88.      * @param i the row index
  89.      * @param j the column index
  90.      * @return the corresponding index in the matrix array
  91.      */
  92.     private int indexOf(final int i, final int j) {
  93.         return j < i ? i * (i + 1) / 2 + j : j * (j + 1) / 2 + i;
  94.     }

  95.     /**
  96.      * Gets the element at index (i, j) from the covariance matrix
  97.      * @param i the row index
  98.      * @param j the column index
  99.      * @return the {@link StorelessBivariateCovariance} element at the given index
  100.      */
  101.     private StorelessBivariateCovariance getElement(final int i, final int j) {
  102.         return covMatrix[indexOf(i, j)];
  103.     }

  104.     /**
  105.      * Sets the covariance element at index (i, j) in the covariance matrix
  106.      * @param i the row index
  107.      * @param j the column index
  108.      * @param cov the {@link StorelessBivariateCovariance} element to be set
  109.      */
  110.     private void setElement(final int i, final int j,
  111.                             final StorelessBivariateCovariance cov) {
  112.         covMatrix[indexOf(i, j)] = cov;
  113.     }

  114.     /**
  115.      * Get the covariance for an individual element of the covariance matrix.
  116.      *
  117.      * @param xIndex row index in the covariance matrix
  118.      * @param yIndex column index in the covariance matrix
  119.      * @return the covariance of the given element
  120.      * @throws MathIllegalArgumentException if the number of observations
  121.      * in the cell is &lt; 2
  122.      */
  123.     public double getCovariance(final int xIndex, final int yIndex)
  124.         throws MathIllegalArgumentException {

  125.         return getElement(xIndex, yIndex).getResult();
  126.     }

  127.     /**
  128.      * Increment the covariance matrix with one row of data.
  129.      *
  130.      * @param data array representing one row of data.
  131.      * @throws MathIllegalArgumentException if the length of <code>rowData</code>
  132.      * does not match with the covariance matrix
  133.      */
  134.     public void increment(final double[] data)
  135.         throws MathIllegalArgumentException {

  136.         int length = data.length;
  137.         MathUtils.checkDimension(length, dimension);

  138.         // only update the upper triangular part of the covariance matrix
  139.         // as only these parts are actually stored
  140.         for (int i = 0; i < length; i++){
  141.             for (int j = i; j < length; j++){
  142.                 getElement(i, j).increment(data[i], data[j]);
  143.             }
  144.         }

  145.     }

  146.     /**
  147.      * Appends {@code sc} to this, effectively aggregating the computations in {@code sc}
  148.      * with this.  After invoking this method, covariances returned should be close
  149.      * to what would have been obtained by performing all of the {@link #increment(double[])}
  150.      * operations in {@code sc} directly on this.
  151.      *
  152.      * @param sc externally computed StorelessCovariance to add to this
  153.      * @throws MathIllegalArgumentException if the dimension of sc does not match this
  154.      */
  155.     public void append(StorelessCovariance sc) throws MathIllegalArgumentException {
  156.         MathUtils.checkDimension(sc.dimension, dimension);

  157.         // only update the upper triangular part of the covariance matrix
  158.         // as only these parts are actually stored
  159.         for (int i = 0; i < dimension; i++) {
  160.             for (int j = i; j < dimension; j++) {
  161.                 getElement(i, j).append(sc.getElement(i, j));
  162.             }
  163.         }
  164.     }

  165.     /**
  166.      * {@inheritDoc}
  167.      * @throws MathIllegalArgumentException if the number of observations
  168.      * in a cell is &lt; 2
  169.      */
  170.     @Override
  171.     public RealMatrix getCovarianceMatrix() throws MathIllegalArgumentException {
  172.         return MatrixUtils.createRealMatrix(getData());
  173.     }

  174.     /**
  175.      * Return the covariance matrix as two-dimensional array.
  176.      *
  177.      * @return a two-dimensional double array of covariance values
  178.      * @throws MathIllegalArgumentException if the number of observations
  179.      * for a cell is &lt; 2
  180.      */
  181.     public double[][] getData() throws MathIllegalArgumentException {
  182.         final double[][] data = new double[dimension][dimension];
  183.         for (int i = 0; i < dimension; i++) {
  184.             for (int j = 0; j < dimension; j++) {
  185.                 data[i][j] = getElement(i, j).getResult();
  186.             }
  187.         }
  188.         return data;
  189.     }

  190.     /**
  191.      * This {@link Covariance} method is not supported by a {@link StorelessCovariance},
  192.      * since the number of bivariate observations does not have to be the same for different
  193.      * pairs of covariates - i.e., N as defined in {@link Covariance#getN()} is undefined.
  194.      *
  195.      * @return nothing as this implementation always throws a
  196.      * {@link MathRuntimeException}
  197.      * @throws MathRuntimeException in all cases
  198.      */
  199.     @Override
  200.     public int getN() throws MathRuntimeException {
  201.         throw new MathRuntimeException(LocalizedCoreFormats.UNSUPPORTED_OPERATION);
  202.     }
  203. }