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
19 import org.apache.commons.math4.legacy.exception.NotStrictlyPositiveException;
20 import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
21 import org.apache.commons.rng.UniformRandomProvider;
22
23 /**
24 * Base class for multivariate probability distributions.
25 *
26 * @since 3.1
27 */
28 public abstract class AbstractMultivariateRealDistribution
29 implements MultivariateRealDistribution {
30 /** The number of dimensions or columns in the multivariate distribution. */
31 private final int dimension;
32
33 /**
34 * @param n Number of dimensions.
35 */
36 protected AbstractMultivariateRealDistribution(int n) {
37 dimension = n;
38 }
39
40 /** {@inheritDoc} */
41 @Override
42 public int getDimension() {
43 return dimension;
44 }
45
46 /** {@inheritDoc} */
47 @Override
48 public abstract Sampler createSampler(UniformRandomProvider rng);
49
50 /**
51 * Utility function for creating {@code n} vectors generated by the
52 * given {@code sampler}.
53 *
54 * @param n Number of samples.
55 * @param sampler Sampler.
56 * @return an array of size {@code n} whose elements are random vectors
57 * sampled from this distribution.
58 */
59 public static double[][] sample(int n,
60 MultivariateRealDistribution.Sampler sampler) {
61 if (n <= 0) {
62 throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES,
63 n);
64 }
65
66 final double[][] samples = new double[n][];
67 for (int i = 0; i < n; i++) {
68 samples[i] = sampler.sample();
69 }
70 return samples;
71 }
72 }