001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.math4.legacy.distribution; 018 019import org.apache.commons.math4.legacy.exception.NotStrictlyPositiveException; 020import org.apache.commons.math4.legacy.exception.util.LocalizedFormats; 021import org.apache.commons.rng.UniformRandomProvider; 022 023/** 024 * Base class for multivariate probability distributions. 025 * 026 * @since 3.1 027 */ 028public abstract class AbstractMultivariateRealDistribution 029 implements MultivariateRealDistribution { 030 /** The number of dimensions or columns in the multivariate distribution. */ 031 private final int dimension; 032 033 /** 034 * @param n Number of dimensions. 035 */ 036 protected AbstractMultivariateRealDistribution(int n) { 037 dimension = n; 038 } 039 040 /** {@inheritDoc} */ 041 @Override 042 public int getDimension() { 043 return dimension; 044 } 045 046 /** {@inheritDoc} */ 047 @Override 048 public abstract Sampler createSampler(UniformRandomProvider rng); 049 050 /** 051 * Utility function for creating {@code n} vectors generated by the 052 * given {@code sampler}. 053 * 054 * @param n Number of samples. 055 * @param sampler Sampler. 056 * @return an array of size {@code n} whose elements are random vectors 057 * sampled from this distribution. 058 */ 059 public static double[][] sample(int n, 060 MultivariateRealDistribution.Sampler sampler) { 061 if (n <= 0) { 062 throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES, 063 n); 064 } 065 066 final double[][] samples = new double[n][]; 067 for (int i = 0; i < n; i++) { 068 samples[i] = sampler.sample(); 069 } 070 return samples; 071 } 072}