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.math4.legacy.distribution;

  18. import java.util.Arrays;
  19. import org.apache.commons.statistics.distribution.ContinuousDistribution;
  20. import org.apache.commons.statistics.distribution.NormalDistribution;
  21. import org.apache.commons.math4.legacy.exception.DimensionMismatchException;
  22. import org.apache.commons.math4.legacy.linear.Array2DRowRealMatrix;
  23. import org.apache.commons.math4.legacy.linear.EigenDecomposition;
  24. import org.apache.commons.math4.legacy.linear.NonPositiveDefiniteMatrixException;
  25. import org.apache.commons.math4.legacy.linear.RealMatrix;
  26. import org.apache.commons.math4.legacy.linear.SingularMatrixException;
  27. import org.apache.commons.rng.UniformRandomProvider;
  28. import org.apache.commons.math4.core.jdkmath.JdkMath;

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

  51.     /**
  52.      * Creates a multivariate normal distribution with the given mean vector and
  53.      * covariance matrix.
  54.      * <p>
  55.      * The number of dimensions is equal to the length of the mean vector
  56.      * and to the number of rows and columns of the covariance matrix.
  57.      * It is frequently written as "p" in formulae.
  58.      * </p>
  59.      *
  60.      * @param means Vector of means.
  61.      * @param covariances Covariance matrix.
  62.      * @throws DimensionMismatchException if the arrays length are
  63.      * inconsistent.
  64.      * @throws SingularMatrixException if the eigenvalue decomposition cannot
  65.      * be performed on the provided covariance matrix.
  66.      * @throws NonPositiveDefiniteMatrixException if any of the eigenvalues is
  67.      * negative.
  68.      */
  69.     public MultivariateNormalDistribution(final double[] means,
  70.                                           final double[][] covariances)
  71.             throws SingularMatrixException,
  72.                    DimensionMismatchException,
  73.                    NonPositiveDefiniteMatrixException {
  74.         super(means.length);

  75.         final int dim = means.length;

  76.         if (covariances.length != dim) {
  77.             throw new DimensionMismatchException(covariances.length, dim);
  78.         }

  79.         for (int i = 0; i < dim; i++) {
  80.             if (dim != covariances[i].length) {
  81.                 throw new DimensionMismatchException(covariances[i].length, dim);
  82.             }
  83.         }

  84.         this.means = Arrays.copyOf(means, means.length);

  85.         covarianceMatrix = new Array2DRowRealMatrix(covariances);

  86.         // Covariance matrix eigen decomposition.
  87.         final EigenDecomposition covMatDec = new EigenDecomposition(covarianceMatrix);

  88.         // Compute and store the inverse.
  89.         covarianceMatrixInverse = covMatDec.getSolver().getInverse();
  90.         // Compute and store the determinant.
  91.         covarianceMatrixDeterminant = covMatDec.getDeterminant();

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

  94.         for (int i = 0; i < covMatEigenvalues.length; i++) {
  95.             if (covMatEigenvalues[i] < 0) {
  96.                 throw new NonPositiveDefiniteMatrixException(covMatEigenvalues[i], i, 0);
  97.             }
  98.         }

  99.         // Matrix where each column is an eigenvector of the covariance matrix.
  100.         final Array2DRowRealMatrix covMatEigenvectors = new Array2DRowRealMatrix(dim, dim);
  101.         for (int v = 0; v < dim; v++) {
  102.             final double[] evec = covMatDec.getEigenvector(v).toArray();
  103.             covMatEigenvectors.setColumn(v, evec);
  104.         }

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

  106.         // Scale each eigenvector by the square root of its eigenvalue.
  107.         for (int row = 0; row < dim; row++) {
  108.             final double factor = JdkMath.sqrt(covMatEigenvalues[row]);
  109.             for (int col = 0; col < dim; col++) {
  110.                 tmpMatrix.multiplyEntry(row, col, factor);
  111.             }
  112.         }

  113.         samplingMatrix = covMatEigenvectors.multiply(tmpMatrix);
  114.     }

  115.     /**
  116.      * Gets the mean vector.
  117.      *
  118.      * @return the mean vector.
  119.      */
  120.     public double[] getMeans() {
  121.         return Arrays.copyOf(means, means.length);
  122.     }

  123.     /**
  124.      * Gets the covariance matrix.
  125.      *
  126.      * @return the covariance matrix.
  127.      */
  128.     public RealMatrix getCovariances() {
  129.         return covarianceMatrix.copy();
  130.     }

  131.     /** {@inheritDoc} */
  132.     @Override
  133.     public double density(final double[] vals) throws DimensionMismatchException {
  134.         final int dim = getDimension();
  135.         if (vals.length != dim) {
  136.             throw new DimensionMismatchException(vals.length, dim);
  137.         }

  138.         return JdkMath.pow(2 * JdkMath.PI, -0.5 * dim) *
  139.             JdkMath.pow(covarianceMatrixDeterminant, -0.5) *
  140.             getExponentTerm(vals);
  141.     }

  142.     /**
  143.      * Gets the square root of each element on the diagonal of the covariance
  144.      * matrix.
  145.      *
  146.      * @return the standard deviations.
  147.      */
  148.     public double[] getStandardDeviations() {
  149.         final int dim = getDimension();
  150.         final double[] std = new double[dim];
  151.         final double[][] s = covarianceMatrix.getData();
  152.         for (int i = 0; i < dim; i++) {
  153.             std[i] = JdkMath.sqrt(s[i][i]);
  154.         }
  155.         return std;
  156.     }

  157.     /** {@inheritDoc} */
  158.     @Override
  159.     public MultivariateRealDistribution.Sampler createSampler(final UniformRandomProvider rng) {
  160.         return new MultivariateRealDistribution.Sampler() {
  161.             /** Normal distribution. */
  162.             private final ContinuousDistribution.Sampler gauss = NormalDistribution.of(0, 1).createSampler(rng);

  163.             /** {@inheritDoc} */
  164.             @Override
  165.             public double[] sample() {
  166.                 final int dim = getDimension();
  167.                 final double[] normalVals = new double[dim];

  168.                 for (int i = 0; i < dim; i++) {
  169.                     normalVals[i] = gauss.sample();
  170.                 }

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

  172.                 for (int i = 0; i < dim; i++) {
  173.                     vals[i] += means[i];
  174.                 }

  175.                 return vals;
  176.             }
  177.         };
  178.     }

  179.     /**
  180.      * Computes the term used in the exponent (see definition of the distribution).
  181.      *
  182.      * @param values Values at which to compute density.
  183.      * @return the multiplication factor of density calculations.
  184.      */
  185.     private double getExponentTerm(final double[] values) {
  186.         final double[] centered = new double[values.length];
  187.         for (int i = 0; i < centered.length; i++) {
  188.             centered[i] = values[i] - means[i];
  189.         }
  190.         final double[] preMultiplied = covarianceMatrixInverse.preMultiply(centered);
  191.         double sum = 0;
  192.         for (int i = 0; i < preMultiplied.length; i++) {
  193.             sum += preMultiplied[i] * centered[i];
  194.         }
  195.         return JdkMath.exp(-0.5 * sum);
  196.     }
  197. }