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.  *      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.math3.distribution;

  18. import org.apache.commons.math3.exception.DimensionMismatchException;
  19. import org.apache.commons.math3.linear.Array2DRowRealMatrix;
  20. import org.apache.commons.math3.linear.EigenDecomposition;
  21. import org.apache.commons.math3.linear.NonPositiveDefiniteMatrixException;
  22. import org.apache.commons.math3.linear.RealMatrix;
  23. import org.apache.commons.math3.linear.SingularMatrixException;
  24. import org.apache.commons.math3.random.RandomGenerator;
  25. import org.apache.commons.math3.random.Well19937c;
  26. import org.apache.commons.math3.util.FastMath;
  27. import org.apache.commons.math3.util.MathArrays;

  28. /**
  29.  * Implementation of the multivariate normal (Gaussian) distribution.
  30.  *
  31.  * @see <a href="http://en.wikipedia.org/wiki/Multivariate_normal_distribution">
  32.  * Multivariate normal distribution (Wikipedia)</a>
  33.  * @see <a href="http://mathworld.wolfram.com/MultivariateNormalDistribution.html">
  34.  * Multivariate normal distribution (MathWorld)</a>
  35.  *
  36.  * @since 3.1
  37.  */
  38. public class MultivariateNormalDistribution
  39.     extends AbstractMultivariateRealDistribution {
  40.     /** Vector of means. */
  41.     private final double[] means;
  42.     /** Covariance matrix. */
  43.     private final RealMatrix covarianceMatrix;
  44.     /** The matrix inverse of the covariance matrix. */
  45.     private final RealMatrix covarianceMatrixInverse;
  46.     /** The determinant of the covariance matrix. */
  47.     private final double covarianceMatrixDeterminant;
  48.     /** Matrix used in computation of samples. */
  49.     private final RealMatrix samplingMatrix;

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

  81.     /**
  82.      * Creates a multivariate normal distribution with the given mean vector and
  83.      * covariance matrix.
  84.      * <br/>
  85.      * The number of dimensions is equal to the length of the mean vector
  86.      * and to the number of rows and columns of the covariance matrix.
  87.      * It is frequently written as "p" in formulae.
  88.      *
  89.      * @param rng Random Number Generator.
  90.      * @param means Vector of means.
  91.      * @param covariances Covariance matrix.
  92.      * @throws DimensionMismatchException if the arrays length are
  93.      * inconsistent.
  94.      * @throws SingularMatrixException if the eigenvalue decomposition cannot
  95.      * be performed on the provided covariance matrix.
  96.      * @throws NonPositiveDefiniteMatrixException if any of the eigenvalues is
  97.      * negative.
  98.      */
  99.     public MultivariateNormalDistribution(RandomGenerator rng,
  100.                                           final double[] means,
  101.                                           final double[][] covariances)
  102.             throws SingularMatrixException,
  103.                    DimensionMismatchException,
  104.                    NonPositiveDefiniteMatrixException {
  105.         super(rng, means.length);

  106.         final int dim = means.length;

  107.         if (covariances.length != dim) {
  108.             throw new DimensionMismatchException(covariances.length, dim);
  109.         }

  110.         for (int i = 0; i < dim; i++) {
  111.             if (dim != covariances[i].length) {
  112.                 throw new DimensionMismatchException(covariances[i].length, dim);
  113.             }
  114.         }

  115.         this.means = MathArrays.copyOf(means);

  116.         covarianceMatrix = new Array2DRowRealMatrix(covariances);

  117.         // Covariance matrix eigen decomposition.
  118.         final EigenDecomposition covMatDec = new EigenDecomposition(covarianceMatrix);

  119.         // Compute and store the inverse.
  120.         covarianceMatrixInverse = covMatDec.getSolver().getInverse();
  121.         // Compute and store the determinant.
  122.         covarianceMatrixDeterminant = covMatDec.getDeterminant();

  123.         // Eigenvalues of the covariance matrix.
  124.         final double[] covMatEigenvalues = covMatDec.getRealEigenvalues();

  125.         for (int i = 0; i < covMatEigenvalues.length; i++) {
  126.             if (covMatEigenvalues[i] < 0) {
  127.                 throw new NonPositiveDefiniteMatrixException(covMatEigenvalues[i], i, 0);
  128.             }
  129.         }

  130.         // Matrix where each column is an eigenvector of the covariance matrix.
  131.         final Array2DRowRealMatrix covMatEigenvectors = new Array2DRowRealMatrix(dim, dim);
  132.         for (int v = 0; v < dim; v++) {
  133.             final double[] evec = covMatDec.getEigenvector(v).toArray();
  134.             covMatEigenvectors.setColumn(v, evec);
  135.         }

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

  137.         // Scale each eigenvector by the square root of its eigenvalue.
  138.         for (int row = 0; row < dim; row++) {
  139.             final double factor = FastMath.sqrt(covMatEigenvalues[row]);
  140.             for (int col = 0; col < dim; col++) {
  141.                 tmpMatrix.multiplyEntry(row, col, factor);
  142.             }
  143.         }

  144.         samplingMatrix = covMatEigenvectors.multiply(tmpMatrix);
  145.     }

  146.     /**
  147.      * Gets the mean vector.
  148.      *
  149.      * @return the mean vector.
  150.      */
  151.     public double[] getMeans() {
  152.         return MathArrays.copyOf(means);
  153.     }

  154.     /**
  155.      * Gets the covariance matrix.
  156.      *
  157.      * @return the covariance matrix.
  158.      */
  159.     public RealMatrix getCovariances() {
  160.         return covarianceMatrix.copy();
  161.     }

  162.     /** {@inheritDoc} */
  163.     public double density(final double[] vals) throws DimensionMismatchException {
  164.         final int dim = getDimension();
  165.         if (vals.length != dim) {
  166.             throw new DimensionMismatchException(vals.length, dim);
  167.         }

  168.         return FastMath.pow(2 * FastMath.PI, -0.5 * dim) *
  169.             FastMath.pow(covarianceMatrixDeterminant, -0.5) *
  170.             getExponentTerm(vals);
  171.     }

  172.     /**
  173.      * Gets the square root of each element on the diagonal of the covariance
  174.      * matrix.
  175.      *
  176.      * @return the standard deviations.
  177.      */
  178.     public double[] getStandardDeviations() {
  179.         final int dim = getDimension();
  180.         final double[] std = new double[dim];
  181.         final double[][] s = covarianceMatrix.getData();
  182.         for (int i = 0; i < dim; i++) {
  183.             std[i] = FastMath.sqrt(s[i][i]);
  184.         }
  185.         return std;
  186.     }

  187.     /** {@inheritDoc} */
  188.     @Override
  189.     public double[] sample() {
  190.         final int dim = getDimension();
  191.         final double[] normalVals = new double[dim];

  192.         for (int i = 0; i < dim; i++) {
  193.             normalVals[i] = random.nextGaussian();
  194.         }

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

  196.         for (int i = 0; i < dim; i++) {
  197.             vals[i] += means[i];
  198.         }

  199.         return vals;
  200.     }

  201.     /**
  202.      * Computes the term used in the exponent (see definition of the distribution).
  203.      *
  204.      * @param values Values at which to compute density.
  205.      * @return the multiplication factor of density calculations.
  206.      */
  207.     private double getExponentTerm(final double[] values) {
  208.         final double[] centered = new double[values.length];
  209.         for (int i = 0; i < centered.length; i++) {
  210.             centered[i] = values[i] - getMeans()[i];
  211.         }
  212.         final double[] preMultiplied = covarianceMatrixInverse.preMultiply(centered);
  213.         double sum = 0;
  214.         for (int i = 0; i < preMultiplied.length; i++) {
  215.             sum += preMultiplied[i] * centered[i];
  216.         }
  217.         return FastMath.exp(-0.5 * sum);
  218.     }
  219. }