MultivariateNormalDistribution.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.distribution.multivariate;

  22. import org.hipparchus.exception.LocalizedCoreFormats;
  23. import org.hipparchus.exception.MathIllegalArgumentException;
  24. import org.hipparchus.linear.Array2DRowRealMatrix;
  25. import org.hipparchus.linear.EigenDecompositionSymmetric;
  26. import org.hipparchus.linear.RealMatrix;
  27. import org.hipparchus.random.RandomGenerator;
  28. import org.hipparchus.random.Well19937c;
  29. import org.hipparchus.util.FastMath;
  30. import org.hipparchus.util.Precision;

  31. /**
  32.  * Implementation of the multivariate normal (Gaussian) distribution.
  33.  *
  34.  * @see <a href="http://en.wikipedia.org/wiki/Multivariate_normal_distribution">
  35.  * Multivariate normal distribution (Wikipedia)</a>
  36.  * @see <a href="http://mathworld.wolfram.com/MultivariateNormalDistribution.html">
  37.  * Multivariate normal distribution (MathWorld)</a>
  38.  */
  39. public class MultivariateNormalDistribution
  40.     extends AbstractMultivariateRealDistribution {
  41.     /** Default singular matrix tolerance check value **/
  42.     private static final double DEFAULT_TOLERANCE = Precision.EPSILON;

  43.     /** Vector of means. */
  44.     private final double[] means;
  45.     /** Covariance matrix. */
  46.     private final RealMatrix covarianceMatrix;
  47.     /** The matrix inverse of the covariance matrix. */
  48.     private final RealMatrix covarianceMatrixInverse;
  49.     /** The determinant of the covariance matrix. */
  50.     private final double covarianceMatrixDeterminant;
  51.     /** Matrix used in computation of samples. */
  52.     private final RealMatrix samplingMatrix;
  53.     /** Inverse singular check tolerance when testing if invertable **/
  54.     private final double singularMatrixCheckTolerance;

  55.     /**
  56.      * Creates a multivariate normal distribution with the given mean vector and
  57.      * covariance matrix.<br>
  58.      * The number of dimensions is equal to the length of the mean vector
  59.      * and to the number of rows and columns of the covariance matrix.
  60.      * It is frequently written as "p" in formulae.
  61.      * <p>
  62.      * <b>Note:</b> this constructor will implicitly create an instance of
  63.      * {@link Well19937c} as random generator to be used for sampling only (see
  64.      * {@link #sample()} and {@link #sample(int)}). In case no sampling is
  65.      * needed for the created distribution, it is advised to pass {@code null}
  66.      * as random generator via the appropriate constructors to avoid the
  67.      * additional initialisation overhead.
  68.      *
  69.      * @param means Vector of means.
  70.      * @param covariances Covariance matrix.
  71.      * @throws MathIllegalArgumentException if the arrays length are
  72.      * inconsistent.
  73.      * @throws MathIllegalArgumentException if the eigenvalue decomposition cannot
  74.      * be performed on the provided covariance matrix.
  75.      * @throws MathIllegalArgumentException if any of the eigenvalues is
  76.      * negative.
  77.      */
  78.     public MultivariateNormalDistribution(final double[] means,
  79.                                           final double[][] covariances)
  80.         throws MathIllegalArgumentException {
  81.         this(means, covariances, DEFAULT_TOLERANCE);
  82.     }

  83.     /**
  84.      * Creates a multivariate normal distribution with the given mean vector and
  85.      * covariance matrix.<br>
  86.      * The number of dimensions is equal to the length of the mean vector
  87.      * and to the number of rows and columns of the covariance matrix.
  88.      * It is frequently written as "p" in formulae.
  89.      * <p>
  90.      * <b>Note:</b> this constructor will implicitly create an instance of
  91.      * {@link Well19937c} as random generator to be used for sampling only (see
  92.      * {@link #sample()} and {@link #sample(int)}). In case no sampling is
  93.      * needed for the created distribution, it is advised to pass {@code null}
  94.      * as random generator via the appropriate constructors to avoid the
  95.      * additional initialisation overhead.
  96.      *
  97.      * @param means Vector of means.
  98.      * @param covariances Covariance matrix.
  99.      * @param singularMatrixCheckTolerance Tolerance used during the singular matrix check before inversion
  100.      * @throws MathIllegalArgumentException if the arrays length are
  101.      * inconsistent.
  102.      * @throws MathIllegalArgumentException if the eigenvalue decomposition cannot
  103.      * be performed on the provided covariance matrix.
  104.      * @throws MathIllegalArgumentException if any of the eigenvalues is
  105.      * negative.
  106.      */
  107.     public MultivariateNormalDistribution(final double[] means,
  108.                                           final double[][] covariances,
  109.                                           final double singularMatrixCheckTolerance)
  110.         throws MathIllegalArgumentException {
  111.         this(new Well19937c(), means, covariances, singularMatrixCheckTolerance);
  112.     }


  113.     /**
  114.      * Creates a multivariate normal distribution with the given mean vector and
  115.      * covariance matrix.
  116.      * <br>
  117.      * The number of dimensions is equal to the length of the mean vector
  118.      * and to the number of rows and columns of the covariance matrix.
  119.      * It is frequently written as "p" in formulae.
  120.      *
  121.      * @param rng Random Number Generator.
  122.      * @param means Vector of means.
  123.      * @param covariances Covariance matrix.
  124.      * @throws MathIllegalArgumentException if the arrays length are
  125.      * inconsistent.
  126.      * @throws MathIllegalArgumentException if the eigenvalue decomposition cannot
  127.      * be performed on the provided covariance matrix.
  128.      * @throws MathIllegalArgumentException if any of the eigenvalues is
  129.      * negative.
  130.      */
  131.     public MultivariateNormalDistribution(RandomGenerator rng,
  132.                                           final double[] means,
  133.                                           final double[][] covariances) {
  134.         this(rng, means, covariances, DEFAULT_TOLERANCE);
  135.     }

  136.     /**
  137.      * Creates a multivariate normal distribution with the given mean vector and
  138.      * covariance matrix.
  139.      * <br>
  140.      * The number of dimensions is equal to the length of the mean vector
  141.      * and to the number of rows and columns of the covariance matrix.
  142.      * It is frequently written as "p" in formulae.
  143.      *
  144.      * @param rng Random Number Generator.
  145.      * @param means Vector of means.
  146.      * @param covariances Covariance matrix.
  147.      * @param singularMatrixCheckTolerance Tolerance used during the singular matrix check before inversion
  148.      * @throws MathIllegalArgumentException if the arrays length are
  149.      * inconsistent.
  150.      * @throws MathIllegalArgumentException if the eigenvalue decomposition cannot
  151.      * be performed on the provided covariance matrix.
  152.      * @throws MathIllegalArgumentException if any of the eigenvalues is
  153.      * negative.
  154.      */
  155.     public MultivariateNormalDistribution(RandomGenerator rng,
  156.                                           final double[] means,
  157.                                           final double[][] covariances,
  158.                                           final double singularMatrixCheckTolerance)
  159.             throws MathIllegalArgumentException {
  160.         super(rng, means.length);

  161.         final int dim = means.length;

  162.         if (covariances.length != dim) {
  163.             throw new MathIllegalArgumentException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
  164.                                                    covariances.length, dim);
  165.         }

  166.         for (int i = 0; i < dim; i++) {
  167.             if (dim != covariances[i].length) {
  168.                 throw new MathIllegalArgumentException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
  169.                                                        covariances[i].length, dim);
  170.             }
  171.         }

  172.         this.means = means.clone();
  173.         this.singularMatrixCheckTolerance = singularMatrixCheckTolerance;

  174.         covarianceMatrix = new Array2DRowRealMatrix(covariances);

  175.         // Covariance matrix eigen decomposition.
  176.         final EigenDecompositionSymmetric covMatDec =
  177.                         new EigenDecompositionSymmetric(covarianceMatrix, singularMatrixCheckTolerance, true);

  178.         // Compute and store the inverse.
  179.         covarianceMatrixInverse = covMatDec.getSolver().getInverse();
  180.         // Compute and store the determinant.
  181.         covarianceMatrixDeterminant = covMatDec.getDeterminant();

  182.         // Eigenvalues of the covariance matrix.
  183.         final double[] covMatEigenvalues = covMatDec.getEigenvalues();

  184.         for (double covMatEigenvalue : covMatEigenvalues) {
  185.             if (covMatEigenvalue < 0) {
  186.                 throw new MathIllegalArgumentException(LocalizedCoreFormats.NOT_POSITIVE_DEFINITE_MATRIX);
  187.             }
  188.         }

  189.         // Matrix where each column is an eigenvector of the covariance matrix.
  190.         final Array2DRowRealMatrix covMatEigenvectors = new Array2DRowRealMatrix(dim, dim);
  191.         for (int v = 0; v < dim; v++) {
  192.             final double[] evec = covMatDec.getEigenvector(v).toArray();
  193.             covMatEigenvectors.setColumn(v, evec);
  194.         }

  195.         final RealMatrix tmpMatrix = covMatEigenvectors.transpose();

  196.         // Scale each eigenvector by the square root of its eigenvalue.
  197.         for (int row = 0; row < dim; row++) {
  198.             final double factor = FastMath.sqrt(covMatEigenvalues[row]);
  199.             for (int col = 0; col < dim; col++) {
  200.                 tmpMatrix.multiplyEntry(row, col, factor);
  201.             }
  202.         }

  203.         samplingMatrix = covMatEigenvectors.multiply(tmpMatrix);
  204.     }

  205.     /**
  206.      * Gets the mean vector.
  207.      *
  208.      * @return the mean vector.
  209.      */
  210.     public double[] getMeans() {
  211.         return means.clone();
  212.     }

  213.     /**
  214.      * Gets the covariance matrix.
  215.      *
  216.      * @return the covariance matrix.
  217.      */
  218.     public RealMatrix getCovariances() {
  219.         return covarianceMatrix.copy();
  220.     }

  221.     /**
  222.      * Gets the current setting for the tolerance check used during singular checks before inversion
  223.      * @return tolerance
  224.      */
  225.     public double getSingularMatrixCheckTolerance() { return singularMatrixCheckTolerance; }

  226.     /** {@inheritDoc} */
  227.     @Override
  228.     public double density(final double[] vals) throws MathIllegalArgumentException {
  229.         final int dim = getDimension();
  230.         if (vals.length != dim) {
  231.             throw new MathIllegalArgumentException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
  232.                                                    vals.length, dim);
  233.         }

  234.         return FastMath.pow(2 * FastMath.PI, -0.5 * dim) *
  235.             FastMath.pow(covarianceMatrixDeterminant, -0.5) *
  236.             getExponentTerm(vals);
  237.     }

  238.     /**
  239.      * Gets the square root of each element on the diagonal of the covariance
  240.      * matrix.
  241.      *
  242.      * @return the standard deviations.
  243.      */
  244.     public double[] getStandardDeviations() {
  245.         final int dim = getDimension();
  246.         final double[] std = new double[dim];
  247.         final double[][] s = covarianceMatrix.getData();
  248.         for (int i = 0; i < dim; i++) {
  249.             std[i] = FastMath.sqrt(s[i][i]);
  250.         }
  251.         return std;
  252.     }

  253.     /** {@inheritDoc} */
  254.     @Override
  255.     public double[] sample() {
  256.         final int dim = getDimension();
  257.         final double[] normalVals = new double[dim];

  258.         for (int i = 0; i < dim; i++) {
  259.             normalVals[i] = random.nextGaussian();
  260.         }

  261.         final double[] vals = samplingMatrix.operate(normalVals);

  262.         for (int i = 0; i < dim; i++) {
  263.             vals[i] += means[i];
  264.         }

  265.         return vals;
  266.     }

  267.     /**
  268.      * Computes the term used in the exponent (see definition of the distribution).
  269.      *
  270.      * @param values Values at which to compute density.
  271.      * @return the multiplication factor of density calculations.
  272.      */
  273.     private double getExponentTerm(final double[] values) {
  274.         final double[] centered = new double[values.length];
  275.         for (int i = 0; i < centered.length; i++) {
  276.             centered[i] = values[i] - getMeans()[i];
  277.         }
  278.         final double[] preMultiplied = covarianceMatrixInverse.preMultiply(centered);
  279.         double sum = 0;
  280.         for (int i = 0; i < preMultiplied.length; i++) {
  281.             sum += preMultiplied[i] * centered[i];
  282.         }
  283.         return FastMath.exp(-0.5 * sum);
  284.     }
  285. }