AbstractMultivariateRealDistribution.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 org.apache.commons.math4.legacy.exception.NotStrictlyPositiveException;
  19. import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
  20. import org.apache.commons.rng.UniformRandomProvider;

  21. /**
  22.  * Base class for multivariate probability distributions.
  23.  *
  24.  * @since 3.1
  25.  */
  26. public abstract class AbstractMultivariateRealDistribution
  27.     implements MultivariateRealDistribution {
  28.     /** The number of dimensions or columns in the multivariate distribution. */
  29.     private final int dimension;

  30.     /**
  31.      * @param n Number of dimensions.
  32.      */
  33.     protected AbstractMultivariateRealDistribution(int n) {
  34.         dimension = n;
  35.     }

  36.     /** {@inheritDoc} */
  37.     @Override
  38.     public int getDimension() {
  39.         return dimension;
  40.     }

  41.     /** {@inheritDoc} */
  42.     @Override
  43.     public abstract Sampler createSampler(UniformRandomProvider rng);

  44.     /**
  45.      * Utility function for creating {@code n} vectors generated by the
  46.      * given {@code sampler}.
  47.      *
  48.      * @param n Number of samples.
  49.      * @param sampler Sampler.
  50.      * @return an array of size {@code n} whose elements are random vectors
  51.      * sampled from this distribution.
  52.      */
  53.     public static double[][] sample(int n,
  54.                                     MultivariateRealDistribution.Sampler sampler) {
  55.         if (n <= 0) {
  56.             throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES,
  57.                                                    n);
  58.         }

  59.         final double[][] samples = new double[n][];
  60.         for (int i = 0; i < n; i++) {
  61.             samples[i] = sampler.sample();
  62.         }
  63.         return samples;
  64.     }
  65. }